Posts

Showing posts with the label asp.net

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

Javascript show clock in webpage example

Image
This example show how to insert clock on the website which is not static clock, but like a digital clock. Script for Creating Clock 1: <script type="text/javascript"> 2: function updateClock() { 3: var currentTime = new Date(); 4: var currentHours = currentTime.getHours(); 5: var currentMinutes = currentTime.getMinutes(); 6: var currentSeconds = currentTime.getSeconds(); 7: // Pad the minutes and seconds with leading zeros, if required 8: currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes; 9: currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds; 10: // Choose either "AM" or "PM" as appropriate 11: var timeOfDay = (currentHours < 12) ? "AM" : "PM"; 12: // Convert the hours component to 12-hour format if needed 13: currentHours = (currentHours &

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> /// &l

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"

Handle Error Modes in ASP.NET redirect to proper page - Web.config

Most of the websites and web applications must have an error handler. Some programmers might question what are the error handler should have on one website. Below is the basic error handler that you need to set in the website : Page Not Found - 404 Internal Server Error - 500 Access Denied - 403 The above error page must-have in one website. This is because when the application catch error, the end-users will see asp.net designed page without detailed error information that might not user friendly for the end-users. To handle these errors, all you need to do are two things which are Create the above error page and set in the web.config file in asp.net. Below is an example of a setting in the web.config file. Web.Config <configuration> <system.web> <customErrors defaultRedirect="~/500.html?" mode="RemoteOnly"> <error statusCode="404" redirect="~/404.html" /> <error statusCode="500" redirect=&quo

Optimize compilation for a complex projects

Image
Most of the web applications nowadays are complex applications that maybe have more than 50MB source code to deploy on the server and it will lead to a long compilation time around 3-10 minutes depends on the server resources. Some will say, it still ok to wait for the compilation since it only happens for the first time. What about require to change the source code with a very minimal code of line.? Like one line only.? Do you still love to wait 3-10 minutes? The answer is no. But how to avoid this situation. It is simple, just one line of configuration on the web.config will help to fasten compilation code (Just in time compilation). The answer is put : optimizeCompilations="true" as an attribute on the compilation element in the web.config file.

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.

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&q

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&q

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/     page.aspx By Mohd Zulkamal NOTE : – If You have Found this post Helpful, I will appreciat