Passing XMLDocument to Stored Procedure - javascript

My current setup is as follows:
Client Javascript JSON stringified object is passed to a server function as so
Client:
var requestObject = JSON.stringify(clientObject);
$.ajax({
url: 'ServerClass.aspx/ServerFunction',
data: requestObject,
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
context: document.body,
type: 'POST',
success: saveSuccessfulFunction
});
Server:
[WebMethod(EnableSession = true)]
public static int SaveAllReportOptions(string requestObject)
{
XmlDocument xdoc = JsonConvert.DeserializeXmlNode("{\"root\":" + clientObject + "}", "roots");
DBClass.Save(xdoc);
}
public int Save(XmlDocument clientObject)
{
SqlCommand dCmd = new SqlCommand("MyStoredProcedure", conn);
dCmd.CommandType = CommandType.StoredProcedure;
dCmd.Parameters.AddWithValue("#objectXML", SqlDbType.Xml).Value = clientObject.InnerXml;
SqlParameter returnValue = dCmd.Parameters.Add("#ret", SqlDbType.Int);
returnValue.Direction = ParameterDirection.ReturnValue;
conn.Open();
dCmd.ExecuteNonQuery();
conn.Close();
int i = Convert.ToInt32(dCmd.Parameters["#ret"].Value);
return i;
}
The stored procedure successfully extracts the different nodes/attributes from the XMLDocument passed in and goes on to perform the relevant update/insert commands.
SELECT tab.col.value('att1[1]','NCHAR(10)') as attribute1,
tab.col.value('att2[1]','INT') as attribute2...
FROM #objectXML.nodes('/roots/root') AS tab(col)
My issue isn't with the above code but with certain do's and don'ts observed from various online/in house software coding standards.
Source 1
X DO NOT use XmlNode or XmlDocument to represent XML data. Favor using instances of IXPathNavigable, XmlReader,XmlWriter, or subtypes of XNode instead. XmlNode and XmlDocument are not designed for exposing in public APIs.
Source 2
✓ DO use XmlReader, IXPathNavigable, or subtypes of XNode as input or output of members that accept or return XML.
Use these abstractions instead of XmlDocument, XmlNode, or XPathDocument, because this decouples the methods from specific implementations of an in-memory XML document and allows them to work with virtual XML data sources that expose XNode, XmlReader, or XPathNavigator.
Source 3
X DO NOT subclass XmlDocument if you want to create a type representing an XML view of an underlying object model or data source.
Basically, I would like to know if it is safe and reliable enough to use XMLDocument for the purpose detailed above. And if not, if there are any alternatives which would be better suited for my scenario.

I used this approach -
For e.g. You have customer object with multiple orders ( child classes)
1. At client side - after assigning values in both the classes
customerObject = JSON.stringify(cls_m_Customer, function(k, v){ return v === "" ? "" : v });
2. At server side -
JavaScriptSerializer jss = new JavaScriptSerializer();
cls_m_Customer objCustomer = new cls_m_Customer();
objCustomer = jss.Deserialize<cls_m_Customer>(customerData);
3. At Business Class - create two dictionaries for customer and orders classes and add these tables to dataset and then convert ds into xml like -
Dictionary<string, cls_m_Customer> dic_Customer = new Dictionary<string, cls_m_Customer>();
dic_Customer.Add("1", this);
DataSet ds = new DataSet();
DataTable dtCustomer = DictionaryToDataTable.ConvertTo<cls_m_Customer>(dic_Customer, "Customer");
DataTable dtOrders = DictionaryToDataTable.ConvertTo<cls_m_Order>(this._Order, "Orders");
ds.Tables.Add(dtCustomer);
ds.Tables.Add(dtOrders);
DataRelation drQ = new DataRelation("Customer Related Orders", dtCustomer.Columns["_CustomerID"], dtOrders.Columns["_CustomerID"]);
drQ.Nested = true;
ds.Relations.Add(drQ);
customerXml = ds.GetXml();

Related

Return JavaScript object literal, not JSON string, from ASP.NET MVC endpoint

For various reasons, I have switched from ASP.NET MVC's built in JSON serializer (the one that returns a System.Web.Mvc.JsonResult object (see edit below)) to Newtonsoft. I didn't realize until after I began testing that the former returns a JavaScript object literal, while Newtonsoft returns a JSON formatted string.
I like not having to parse JSON strings on the client side — having it already as an object literal is very convenient — but I want to stick with Newtonsoft for other technical reasons.
For example, instead of seeing this result on my client...
"{"Errors":["Please enter a valid email address."],"HasErrors":true}"
...I'd like to see this result:
{"Errors":["Please enter a valid email address."],"HasErrors":true} // no quotes
Is there a way to make Newtonsoft return JS object literals instead of strings?
EDIT
The way my question was framed wasn't the best. There's nothing wrong with the JsonResult type. In fact, the solution still uses it. The only problem was the default Controller.Json methods, which can be overridden to use Newtonsoft (Json.NET) instead of the built-in serializer.
Just write a custom JsonResult that uses Newtonsoft serializer:
Something along the lines:
public abstract class BaseController : Controller
{
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding)
{
return new JsonNetResult
{
ContentType = contentType,
ContentEncoding = contentEncoding,
Data = data
};
}
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonNetResult
{
ContentType = contentType,
ContentEncoding = contentEncoding,
Data = data,
JsonRequestBehavior = behavior
};
}
}
JsonNetResult.cs:
using System;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
public class JsonNetResult : JsonResult
{
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult()
{
Formatting = Formatting.None;
SerializerSettings = new JsonSerializerSettings();
JsonRequestBehavior = JsonRequestBehavior.DenyGet;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet
&& String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.");
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data != null)
{
var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
var serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(writer, Data);
writer.Flush();
}
}
}
Credit: https://gist.github.com/jpoehls/1424538
Answer is here: How to force ASP.NET Web API to always return JSON?
Excerpt:
Clear all formatters and add Json formatter back.
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
EDIT
I added it to Global.asax inside Application_Start().

How to implement a grid like structure instead of tabular structure using jquery DataTables in ASP.NET using Ajax

I have to use datatable and make things like given in the image
I want my ui to look like this using data tables instead that they are normally shown in table format
the data must be picked from the database and then retrieved by ajax the retrieve function will be looking like
public static List<string[]> AllItems()
{
List<string[]> ItemList = new List<string[]>();
using (MySqlConnection exmp = new MySqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
{
using (MySqlCommand getAllItems = new MySqlCommand())
{
getAllItems.Connection = exmp;
getAllItems.CommandType = CommandType.Text;
getAllItems.CommandText = "SELECT * FROM table1";
exmp.Open();
MySqlDataReader reader = getAllItems.ExecuteReader();
while (reader.Read())
{
string[] temp = new string[8];
//Item Name
temp[0] = reader[0].ToString();
// Item Nick Name
temp[1] = reader[1].ToString();
//Item property
temp[2] = reader[2].ToString();
//Item Image URl
temp[3] = reader[3].toString();
//Item Price
temp[4] = reader[4].toString();
//Item Special Property that makes a link
temp[5] = reader[5].toString();
ItemList.Add(temp);
}
}
}
return ItemList;
}
My ajax function to retrieve json
$.ajax({
type: "POST",
url: "default.aspx/AllItems",
data: {},
contentType: "application/json",
dataType: "json",
success: OnSuccess
});
Now using the code given above for retrieving data from database, I have to make a structure as given in the pic mentioned above using datatables How can I do it?
Please provide some sample code; I'll be grateful to you.

Ajax call to Asp.net Web Method using Jquery

I am using a jquery method, to send information (namely only member identification #) from client side to the server side.
The server side has the traditional Web Method implemented so as to capture data sent and execute SQL queries based on it.
Web-service-method-using-jQuery
However until now I have been returning a single string from the server side back to the client side after the SQL query.
Wondering what would be the best way to return a complicated series of strings... member Identification number, start date, end date, type of member... depending on the type of the member, there can be multiple start dates and end dates.
Should I be looking into XML ?
What about returning even a datatable
$.ajax({
type: "POST",
url: "YourPage.aspx/doSomething",
data: "{'id':'1'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var returnedstring = data.d;
var jsondata = $.parseJSON(data.d);//if you want your data in json
}
});
aspx:
[WebMethod]
public static string doSomething(int id)
{
....
DataTable dt = new DataTable();
dt = anothermethodReturningdt(id)
return JsonConvert.SerializeObject(dt);
}
You can use json.net for serializing .Net objects
Edit
you can also do this
[WebMethod]
public static string doSomething(int id)
{
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
return JsonConvert.SerializeObject(product);
}
The point is you can serialize any type of object, arrays, collections etc and then pass it back to the calling script.

How tp parse Json result which is returned with an arraylist in a webmethod?

This is a simplified code. I have a webservice (.asmx) as following:
I store some values in Test class and then store the class in an arraylist.
I do this two times in two different arraylists.
and then store these two array lists in a third arraylist.
and then pass this arraylist as output of webmethod.
private class Test
{
public string Id;
public string Name;
}
[webmethod]
public ArrayList RuleReport(long RuleId)
{
Test t = new Test();
t.Id = "1";
t.Name = "a";
ArrayList ar = new ArrayList();
ArrayList ar2 = new ArrayList();
ArrayList ar3 = new ArrayList();
ar.Add(t);
t = new Test();
t.Id = "2";
t.Name = "b";
ar2.Add(t);
ar3.Add(ar);
ar3.Add(ar2);
return ar3;
}
and in js file I want to parse he json result to read each Id and Name values of two arraylists.
id=1,name=a
id=2,name=b
this is my jquery code:
$.ajax(
{ url: " Ajaxes/Rules.asmx/RuleReport",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
data: "{'RuleId':'79'}",
async: false,
success: function(data) {
$.each(data.d, function(index, obj) {
alert(obj.d[0].Id);// something like this. How to do it???
})
}, error: function() { }
});
this is the json response in fire bug:
{"d":[[{"Id":"1","Name":"a"}],[{"Id":"2","Name":"b"}]]}
how to get every Id and Name values???
With your current setup inside $.each loop you are getting
[{"Id":"1","Name":"a"}]
as obj. As you can see it's a array of object with only one object as it's content. You can access that object with obj[0] and then their properties can be accessed with obj[0].Id and obj[0].Name
You can do this with the following code
$.each(data.d,function(index,obj){
var id = obj[0].Id;
var name = obj[0].Name;
// do what ever you want with them
})​
Working fiddle

How can I output javascript to a view in asp.net mvc3?

Good morning All,
I have a javascript variable in my view. I keep doing this...
var skinData = null;
and then on document.ready....
$.ajax({
type: 'POST',
url: 'theme/getskins',
data: {},
contentType: 'application/json; charset=utf-8',
success: function(data){
skinData = data;
}
});
my question is why am I doing this on after the view has loaded. I'm trying to do this in _ViewStart.cshtml
viewPage.ViewBag.SkinInfo = new JsonResult { Data = SkinManager.GetSkins() };
How can I take this value and output its value to my javascript variable. I don't think I need to do another request when I really want to push this to the client on the first trip. Any tips or advice is of course appreciated. How can I do this correctly? I tried a few variations of this but it obvious isn't working. Stuff like...
var skinData = #ViewBag.SkinInfo.Data;
This just outputs the namespace. Any ideas how to do this correctly?
Cheers,
~ck in San Diego
You will want to use some a serializer to convert your .GetSkins() method result into a json object. Either the built in JavaScriptSerializer or json.net
JavaScriptSerializer serializer = new JavaScriptSerializer();
viewPage.ViewBag.SkinInfo = serializer.Serialize(SkinManager.GetSkins());
And then in your view
var skinData = #Html.Raw(ViewBag.SkinInfo);
Here's a way of doing it using a Html helper. It will convert your object into json and put it into a javascript variable.
HtmlHelper extension method
public static MvcHtmlString Jsonize(this HtmlHelper helper, string variableName, object obj)
{
StringBuilder str = new StringBuilder();
str.Append("<script type='text/javascript'>");
str.Append("var ");
str.Append(variableName);
str.Append("=");
if (obj == null)
str.Append("null");
else
str.Append(JsonHelper.Serialize(obj));
str.Append(";");
str.Append("</script>");
return MvcHtmlString.Create(str.ToString());
}
The json serializer. I'm using the DataContractJsonSerializer in this case.
public class JsonHelper
{
public static string Serialize(object obj)
{
string json = null;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
json = Encoding.Default.GetString(ms.ToArray());
}
return json;
}
}
Once you have that done, you can just use it in your views to create a javascript variable that contains your object
#Html.Jsonize("data", ViewBag.SkinInfo.Data);
which will create something like this:
<script type='text/javascript'>
var data = { your serialized object };
</script>

Categories

Resources