Skip to content

My Super Generic Webservice DataTable to serialisable XML string method call

OK I couldn’t hold back as to how super this C# method I wrote yesterday and would like you guys to know about.

Essentially what it does is that it reads in an SQL database tables, converts ii into a DataTable using SQL Data Adapter then the very clever bit is that it convert it to a MemorySteam that is XML serialisable over the HTTP to WCF Data Services for it to be received on the other end as a Stream and serialised back to DataTable again! Its fantastic, and its so generic, you can use this time and time again. Hope its useful for you!

public string Add(string webServiceCall, string sourceTable, string destinationTable)
 {
 // Restful service URL
 string url = readServiceUri().ToString() + webServiceCall;
// declare ascii encoding
 ASCIIEncoding encoding = new ASCIIEncoding();
 string strResult = string.Empty;
 string xmlResult = "";
DataSet dataSet = new DataSet();
 DataTable dataTable = new DataTable();
 dataTable.TableName = destinationTable;
 using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString))
 {
 SqlCommand cmd = new SqlCommand("SELECT * FROM " + sourceTable, conn);
cmd.CommandType = CommandType.Text;
 SqlDataAdapter adapter = new SqlDataAdapter();
 try
 {
 adapter.SelectCommand = cmd;
 adapter.Fill(dataTable);
 }
 catch (Exception ex)
 {
 throw new Exception("ERROR " + ex);
 }
 }
// Important logical conversion to XML string
 dataSet.Tables.Add(dataTable);
 using (MemoryStream memoryStream = new MemoryStream())
 {
 using (TextWriter streamWriter = new StreamWriter(memoryStream))
 {
 XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataSet));
 xmlSerializer.Serialize(streamWriter, dataSet);
 xmlResult = Encoding.UTF8.GetString(memoryStream.ToArray());
 }
 }
try
 {
string postData = xmlResult.ToString();
 // Convert xmlstring to byte using ascii encoding
 byte[] data = encoding.GetBytes(postData);
 // Declare httpwebrequet wrt url defined above
 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
 // Set method as post
 webRequest.Method = "POST";
 // Set content type
 webRequest.ContentType = "application/x-www-form-urlencoded";
 // Set content length
 webRequest.ContentLength = data.Length;
 // Set timeout
 webRequest.Timeout = 60000;
 // Get stream data out of webrequest object
 Stream newStream = webRequest.GetRequestStream();
 newStream.Write(data, 0, data.Length);
 newStream.Close();
 // Declare & read response from service
 HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
 if (webResponse.StatusCode == HttpStatusCode.OK)
 {
 // set utf8 encoding
 Encoding enc = System.Text.Encoding.GetEncoding("utf-8");
 // read response stream from response object
 StreamReader loResponseStream =
 new StreamReader(webResponse.GetResponseStream(), enc);
 // read string from stream data
 strResult = loResponseStream.ReadToEnd();
 // close the stream object
 loResponseStream.Close();
 // close the response object
 webResponse.Close();
 // below steps remove unwanted data from response string
 strResult = strResult.Replace("</string>", "");
if (strResult.Contains("OK"))
 {
 return "OK";
 }
 else
 {
 return "FAIL";
 }
}
 else
 {
 return "FAIL";
 }
 }
 catch (Exception ex)
 {
 throw new Exception("ERROR " + ex);
 }
 }

JSON to HTML JQuery Converter

After fumbling to find a JSON convert to HTML using JQuery, I have finally found useful piece of code for reading a list of JSON objects and sets it to a HTML table for output. It is useful for calling AJAX in JQuery for MVC C# controllers which returns a JSON object and in return the AJAX can translate the JSON object to HTML. Here's the code.

var myList = [{"name" : "abc", "age" : 50}, {"age" : "25", "hobby" : "swimming"}, {"name" : "xyz", "hobby" : "programming"}]; // Builds the HTML Table out of myList. function buildHtmlTable(selector) { var columns = addAllColumnHeaders(myList, selector); for (var i = 0 ; i < myList.length ; i++) { var row$ = $('<tr/>'); for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) { var cellValue = myList[i][columns[colIndex]]; if (cellValue == null) { cellValue = ""; } row$.append($('<td/>').html(cellValue)); } $(selector).append(row$); } } // Adds a header row to the table and returns the set of columns. // Need to do union of keys from all records as some records may not contain // all records function addAllColumnHeaders(myList) { var columnSet = []; var headerTr$ = $('<tr/>'); for (var i = 0 ; i < myList.length ; i++) { var rowHash = myList[i]; for (var key in rowHash) { if ($.inArray(key, columnSet) == -1){ columnSet.push(key); headerTr$.append($('<th/>').html(key)); } } } $(selector).append(headerTr$); return columnSet; }​

HTML:

<body onLoad="buildHtmlTable('#excelDataTable')">
<table id="excelDataTable" border="1">
  </table>
</body>

Use AppSettingsReader!

This is something that is useful and is a very general tip,m you can use the AppSettingsReader from System.Configuration to read a key value set in the web.config.

 System.Configuration.AppSettingsReader settingsReader =
 new AppSettingsReader();

 //Get your key from config file!

 string key = (string)settingsReader.GetValue("AValue",
 typeof(String));

//This is saved here in the web.config

 <appSettings>
 <add key="AValue" value="hereismyvalue" />
 </appSettings>

This is very useful for using the same string on many Controller classes for example!

Ambiguous Error in ViewModel

If you ever receive the common MVC error when converting a returning object to the correct type which occurs during runtime say for a page called OrderSummary.

The current request for action ‘OrderSummary’ on controller type ‘HomeController’ is ambiguous between the following action methods:
System.Web.Mvc.ActionResult OrderSummary() on type WebApplication.Controllers.HomeController
System.Web.Mvc.ActionResult OrderSummary(System.Collections.Generic.List`1[WebApplication.Models.OrderViewModel]) on type WebApplication.Controllers.HomeController

The problem here is that the object OrderViewModel is not being passed correctly as a list of enumerable type that the View Model can read in, you can set this like so: –

var convertedList = (from db in onlineOrders.AsEnumerable()
 select new Order()
 {
 Id = Convert.ToInt32(db["Id"]),
 ItemID = Convert.ToInt32(db["ItemID"]),
 CustomerID = Convert.ToInt32(db["CustomerID"]),
 DateOrdered = (emp["DateOrdered"] == DBNull.Value ? (DateTime?)null : Convert.ToDateTime(db["DateOrdered"])),
 Quantity = Convert.ToInt32(db["Quantity"])
 }).ToList();
List<OrderList> convertedList = new List<OrderList>();
var emptyList = convertedList;
return View(convertedList);

You notice here that the convertlist is using the enumerable type of ToList () which convert the the database read items from the table onlineOrders as enumerable, rather than casting it manually which doesn’t work, and then I add this converted enumerable list to be placed in var that is read to the ViewMoel called OrderSummary.

Hope that helps!!!!!!

 

How to have the navbar in Twitter Bootstrap stay fixed for screen width less than 768px Update

Here is an update on the previous post I have made in that you may need to automatically allow the top bar navigation to become fixed and also run the code on load.

So here is the revised code.

$(document).ready(function () {

var screenxs =768;

if (window.innerWidth <= screenxs) {
$(“#topbar”).removeClass(“hide”);
$(“#topbar”).addClass(“navbar-fixed-top”);
} else {
$(“#topbar”).removeClass(“navbar-fixed-top”);
$(“#topbar”).addClass(“hide”);
}

$(window).resize(function () {
if (window.innerWidth <= screenxs) {
$(“#topbar”).removeClass(“hide”);
$(“#topbar”).addClass(“navbar-fixed-top”);
} else {
$(“#topbar”).removeClass(“navbar-fixed-top”);
$(“#topbar”).addClass(“hide”);
}
});
});

How to have the navbar in Twitter Bootstrap stay fixed for screen width less than 768px

Here is some useful code for how to have the navbar in Twitter Bootstrap stay fixed for screen width less than 768px: - 

class="navbar-static-top visible-xs-block">
class="navbar-default hidden-xs">

Otherwise, use media queries to control what is visible/hidden. I don’t have any experience with Foundation, but I imagine the solution will be similar.

or, toggle between those classes using jQuery

var screen-xs = 767;

// an assumption is made here that the targeted div will have a static identifier, like class="navbar"
// this initializes the navbar on screen load with an appropriate class
if (window.innerWidth <= screen-xs) {
  $(".navbar").addClass("navbar-static-top");
} else {
  $(".navbar").addClass("navbar-default");
}

// if you want these classes to toggle when a desktop user shrinks the browser width to an xs width - or from xs to larger
$(window).resize(function() {
  if (window.innerWidth <= screen-xs) {
    $(".navbar").removeClass("navbar-default");
    $(".navbar").addClass("navbar-static-top");
  } else {
    $(".navbar").removeClass("navbar-static-top");
    $(".navbar").addClass("navbar-default");
  }
});

Async and Wait

Was a little stuck on using the async and wait methods from a Task object, here are some examples I got to get it eventually compiling

static void Main()
{
Model db = new Model();

foreach (Client account in db.Clients.Where(x => x.Lic_Type_Id == 0).ToList())
{
// Create task and start it.
// … Wait for it to complete.
Task<string> t1 = Task.Factory.StartNew<string>(() => GreetUser(“Hi”));
t1.Start();
t1.Wait();

//Task task = new Task(ProcessClientAccountAsync(“”));
Task t2 = Task.Factory.StartNew(() => ProcessClientAccountAsync(“Hi”));
t2.Start();
t2.Wait();
}

}

static string GreetUser(string message)
{
return message;
}

static async void ProcessClientAccountAsync(string a)
{
WebApplication.Controllers.AccountController.CreateClientAccount newClientAccount = new Controllers.AccountController.CreateClientAccount(“a”, “b”, “c”);
ActionResult result = await newClientAccount.Execute();
}

Follow

Get every new post delivered to your Inbox.

Join 797 other followers