Posts

Showing posts with the label C#

JSON & DataTable in asp.net / c#

Before start you need to convert your json data to c# class. You can achieve this by using online tools like :  http://json2csharp.com/ Go to :  http://json2csharp.com/ Paste your Json data into box and click Generate Button. Copy the code generated and create Class file in your asp.net solution. After finish convert json data to c# class, Copy the code below. Example JSON Data 1: { 2: "name":"apicode", 3: "email": 4: [ 5: "apicode@gmail.com","apicode@gmail.com" 6: ], 7: "websites": 8: { 9: "home_page":"http:\/\/apicode.blogspot.com", 10: "blog":"http:\/\/apicode.blogspot.com" 11: } 12: } JSON Class after converted 1: public class Websites 2: { 3: public string home_page { get; set; } 4: public string blog { get; set; } 5: } 6: public class RootO...

How to make request to web service with soap message - asp.net /C#

If you have web services and want to call the web service from your c# code, you can try to use this code example. The code example uses HttpWebRequest to create a request for the web service.  Code Behind HttpWebRequest request = (HttpWebRequest)WebRequest.Create(<web service address>); request.Headers.Add("SOAPAction", "http://tempuri.org/" + <web service method>); request.ContentType = "text/xml;charset=\"utf-8\""; request.KeepAlive = false; request.Timeout = 300000; // - in millisecond. (5 minit) request.Method = "POST"; request.Credentials = CredentialCache.DefaultCredentials; byte[] byteArray = Encoding.ASCII.GetBytes(<data you want to send to webservice>); request.ContentLength = byteArray.Length; Stream s = request.GetRequestStream(); s.Write(byteArray, 0, byteArray.Length); s.Dispose(); ...

Decrypt web.config file - asp.net

Image
This is an example of how to decrypt a web.config file in asp.net. You can refer to this post on how to encrypt web config file. The example will decrypt web config file for 3 section which is ConnectionString, AppSetting, and system.web/authentication. Front End .aspx code <br /> This is button to decrypt web config.<br /> <asp:Button ID="Button2" runat="server" Text="Decrypt Web Config" OnClick="Button2_Click" /> Code behind private static string[] sectionName = { "connectionStrings", "appSettings", "system.web/authentication" }; public static string[] SectionName { get { return sectionName; } set { sectionName = value; } } protected void Button2_Click(object sender, EventArgs e) { //decrypt UnProtectSection(); } /// <summary> /// Decrypted web conf...

Check if web.config file encrypted or not.

This is an example of how to check if the web.config file is encrypted or not. Refer to this article to encrypt and decrypt the web.config file. The example will check the web.config file for 3 section which is ConnectionString, AppSetting, and system.web/authentication. Code Behind private static string[] sectionName = { "connectionStrings", "appSettings", "system.web/authentication" }; public static string[] SectionName { get { return sectionName; } set { sectionName = value; } } /// <summary> /// method to check if web config file is encrypted or not /// </summary> /// <returns></returns> private bool CheckWebConfigIfEncrypt() { bool isEncrypt = false; foreach (string a in SectionName) { Configuration config = WebConfigurationManager. OpenWebConfigu...

Encrypt Web.config file - asp.net

Image
This is an example of how to encrypt a web.config file in asp.net. The example will encrypt web config file for 3 section which is ConnectionString, AppSetting, and system.web/authentication. Front End .aspx Code  <br /> This is button to encrypt web config.<br /> <asp:Button ID="Button1" runat="server" Text="Encrypt Web config" OnClick="Button1_Click" /> Code Behind private static string[] sectionName = { "connectionStrings", "appSettings", "system.web/authentication" }; public static string[] SectionName { get { return sectionName; } set { sectionName = value; } } protected void Button1_Click(object sender, EventArgs e) { //encrypt ProtectSection(); } /// <summary> /// Encrypte WebConfig file for certain section /// </summary> /// ...

How to read JSON Data and convert to DataTable - asp.net / C#

This is an example of how to read JSON Data using C# code. First, before you start coding, please read this post on how to convert JSON data to c# class. How to convert JSON data to Class - C# After finish convert JSON data to C# class, write this code to read your JSON data. Example JSON Data { "name":"swengineercode", "email": [ "swengineercode@gmail.com","swengineercode@gmail.com" ], "websites": { "home_page":"http:\/\/swengineercode.blogspot.com", "blog":"http:\/\/swengineercode.blogspot.com" } } JSON Class after converted public class Websites { public string home_page { get; set; } public string blog { get; set; } } public class RootObject { public string name { get; set; } public List<string> email { get; set; } public Websites websites { get; set; } } ...

How to convert JSON to C# Class

Today I found one very good tool to convert JSON data to C# class. Please go to this link:  http://json2csharp.com/ You just paste the JSON data, and it will give you the class for each element in the JSON data. Example JSON Data : Note: This example JSON data from TripAdvisor API. { "address_obj": { "street1": "Lot PTB22819 ", "street2": "Jalan Skudai", "city": "Johor Bahru", "state": "Johor", "country": "Malaysia", "postalcode": "80200", "address_string": "Lot PTB22819 Jalan Skudai, Johor Bahru 80200 Malaysia" }, "latitude": "1.485111", "rating": "4.0", "description": "Staying true to our unique no frills concept, we provide you a good night's sleep at outstanding value. Our hotels come with high quality beds, power showers, 24-hour s...

Compress and decompress stream object in asp.net - GZip

This is a snippet code to provides methods and properties for compressing and decompressing streams using the GZip algorithm. abstract class Stream using System; using System.IO; namespace CompressionMethod { /// <summary> /// Provides a generic view of a sequence of bytes. /// </summary> public abstract class Stream : IDisposable { #region "Properties" /// <summary> /// Gets or sets system stream. /// </summary> public abstract System.IO.Stream SystemStream { get; } /// <summary> /// Gets the length in bytes of the stream. /// </summary> public abstract long Length { get; } /// <summary> /// Gets or sets the position within the current stream. /// </summary> public abstract long Position { get; set; } #endregion #region "Methods" ...

Compress and decompress stream object in asp.net - Deflate

This is a snippet code to provides methods and properties for compressing and decompressing streams using the Deflate algorithm. abstract class Stream using System; using System.IO; namespace CompressionMethod { /// <summary> /// Provides a generic view of a sequence of bytes. /// </summary> public abstract class Stream : IDisposable { #region "Properties" /// <summary> /// Gets or sets system stream. /// </summary> public abstract System.IO.Stream SystemStream { get; } /// <summary> /// Gets the length in bytes of the stream. /// </summary> public abstract long Length { get; } /// <summary> /// Gets or sets the position within the current stream. /// </summary> public abstract long Position { get; set; } #endregion #region "Methods" ...

Force to download file in ASP.NET

This is an example of how to force the current HTTP Context Response to download files. Before that, you need to set a path/folder in your web application to store files that you just created or pre-set the file to download. In ASP.NET this is the way to set a path. Since we can use the tiddler("~") symbol to referring to the root with a virtual path set from IIS. string pathFile = Server.MapPath(Request.ApplicationPath); Force download method : string pathFile = Server.MapPath(Request.ApplicationPath); Response.AddHeader("Content-Type", "application/octet-stream"); Response.AddHeader("Content-Transfer-Encoding", "Binary"); Response.AddHeader("Content-disposition", "attachment; filename=\"" + yourfilename + ".csv\""); Response.WriteFile(pathFile + yourfilename + ".csv"); Response.End();

Fix issue file not upload to server with Multiview + File Upload + UpdatePanel - asp.net

Recently I have developed some modules to upload the file to the server. In my code, I have an update panel and also the multiview. Somehow the upload not working. So I thought I was not set the full postback for the upload process in the trigger section under the update panel. But actually, the full postback was set correctly. So I wonder, why the upload not working.  So I start to investigate my code, and luckily I found the solution. The solution  I just need to set enctype attribute at the form and value  multipart/form-data. This is the code I use. protected override void OnInit(EventArgs e) { base.OnInit(e); Page.Form.Attributes.Add("enctype", "multipart/form-data"); } Hopefully, this simple solution helps someone.

Example Lock Dataset in C#

This is an example of how to lock your database or prevent data in the dataset to changed (read-only dataset). In a large web application, you may have a reference table in the database, and the application no need to read on the reference table every time the application needs to get a reference. You can store the reference table in cache memory. But you afraid that the data might accidentally  changed by your code. This is the way to make your dataset lock / read-only. Lock Dataset method /// <summary> /// Makes the given DataSet read-only /// </summary> /// <param name="ds">DataSet</param> public static void LockDataSet(DataSet ds) { // Do not lock null if (ds == null) { return; } EventHandler locked = (sender, e) => { string msg = String.Format("DataSet '{0}' cannot be modified, it is read-only.", ds.DataSetName); ...

Splits the camel cased input text into separate words.

Image
This is an example method to split "Camel Cased" into separated words. Example Camel Cased ThisIsOneExample TomorrowIsWhatDay ThisIsAnotherExample ASPX Page <asp:Label ID="Label1" runat="server" Text="Camel Words"></asp:Label>: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /> <br /> <asp:Button ID="Button1" runat="server" Text="Convert" onclick="Button1_Click" /> <br /> Preview : <asp:Literal ID="Literal1" runat="server"></asp:Literal> <br /> <p>&nbsp;</p> <p>&nbsp;</p> Code Behind protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string camelWords = TextBox1.Text; IEnumerable<string> _words = Sp...

Combine / Union two dataset - C#

This method is example to combine two dataset into single dataset. This method also called Union two dataset meaning that if both dataset contains same data, the combined dataset will not included. Method Union Dataset : /// <summary> /// Creates the union of two Datasets, the values are compared for uniqueness by the given ID column name. /// </summary> /// <param name="ds1">First DataSet</param> /// <param name="ds2">Second DataSet</param> /// <param name="idColumn">ID column name</param> public static DataSet Union(DataSet ds1, DataSet ds2, string idColumn) { if (ds1 == null) { return ds2; } if (ds2 == null) { return ds1; } ArrayList addTables = new ArrayList(); // Add the new rows foreach (DataTable dt in ds2.Tables) { DataTable destTable = ds1.Tables[d...

Detect browser name & version from code behind - asp.net

Image
This is example in asp.net how to detect client browser and version. The method used in this example can work after copy paste in the Visual Studio. Aspx Code <br /> <h5> <asp:Literal ID="Literal1" runat="server"></asp:Literal> </h5> <p> &nbsp;</p> <p> &nbsp;</p> Code Behind  private string SAFARI_CODE = "Safari"; private string CHROME_CODE = "Chrome"; private string IE_CODE = "IE"; private string IE_LONGCODE = "Internet Explorer"; private string GECKO_CODE = "Gecko"; private string OPERA_CODE = "Opera"; protected void Page_Load(object sender, EventArgs e) { Literal1.Text = GetBrowserClass(true); } /// <summary> /// Gets the browser specific CSS class name. /// </summary> /// <param name="includeVersion...

Detect request is a crawler/bot - asp.net

Sometimes you want to avoid bot from crawling the page with sensitive information like phone number and email address, so you need to have a method to detect either the request is a visitors or bot.  This code snippet shows how you can determine the request is a crawler or not. Code Behind  /// <summary> /// Returns whether browsing device is search engine crawler (spider, bot). /// </summary> public bool IsCrawler() { if (HttpContext.Current != null) { HttpRequest currentRequest = HttpContext.Current.Request; return (currentRequest.Browser != null) && currentRequest.Browser.Crawler; } return false; } You can put this method under a static class and call it from the Global.asax file.

Example to remove all script block using C# code - asp.net

Image
This is example how to remove script block in HTML. This method will be very useful if you want to validate the html passed from input string do not have any script block. Example HTML have script block : <div> this is the information </div> <script>alert('Your computer have security vulnerable');</script> Example ASPX Code : Note : This html using Editor Controller in AjaxToolkit library <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </ajaxToolkit:ToolkitScriptManager> Input Text : <cc1:Editor ID="Editor1" runat="server" /> <br /> <asp:Button ID="Button1" runat="server...

Get Url Reference - asp.net

This is just for reference to get the URL based on HttpRequest Class. You can call the method below : Request.ApplicationPath :   /virtual_dir Request.CurrentExecutionFilePath :  /virtual_dir/webapp/page.aspx Request.FilePath :  /virtual_dir/webapp/page.aspx Request.Path :  /virtual_dir/webapp/page.aspx Request.PhysicalApplicationPath :   d:\Inetpub\wwwroot\virtual_dir\ Request.QueryString :   /virtual_dir/webapp/page.aspx?q=qvalue Request.Url.AbsolutePath :  /virtual_dir/webapp/page.aspx Request.Url.AbsoluteUri :   http://localhost:2000/virtual_dir/webapp/page.aspx?q=qvalue Request.Url.Host :  localhost Request.Url.Authority : localhost:80 Request.Url.LocalPath : /virtual_dir/webapp/page.aspx Request.Url.PathAndQuery :  /virtual_dir/webapp/page.aspx?q=qvalue Request.Url.Port :  80 Request.Url.Query : ?q=qvalue Request.Url.Scheme :    http Request.Url.Segments :  /     virtual_dir/     webapp/ ...

Await in Catch and Finally

This is just a brief note to publicize a coming improvement to the async language support. With the new compilers, changes to the C# language (e.g., async/await) are easier than they used to be. One improvement that is coming is the use of await in catch and finally blocks. This enables your error-handling/cleanup code to be asynchronous without awkward code mangling. For example, let’s say that you want to (asynchronously) log an exception in one of your async methods. The natural way to write this is: try {   await OperationThatMayThrowAsync(); } catch (Exception ex) {   await MyLogger.LogAsync(ex); } And this natural code works fine in Visual Studio “14”. However, the currently-released Visual Studio 2013 does not support await in a catch, so you would have to keep some kind of “error flag” and move the actual error handling logic outside the catch block: Exception exception = null; try {   await OperationThatMayThrowAsync(); } catch (Exception ex) {   exception...

HEX to ASCII and ASCII to HEX Class - C#

This article shows you how to convert string to hexadecimal and vice versa. HEX TO ASCII Class using System.Collections.Generic; using System.Text; using Microsoft.VisualBasic; // I'm using  this class for Hex Converion namespace Hex_Converter {     public class HexConverter     {         public string Data_Hex_Asc(ref string Data)         {             string Data1 = "";             string sData = "";             while (Data.Length > 0)             //first take two hex value using substring.             //then  convert Hex value into ascii.             //then convert ascii value into character.             {                 Data1 = System.Convert.ToChar(System.Convert...