Posts

Showing posts with the label ASP.NET

How to hide generated javascript file in visual studio code

In this post I am going to show you a cool trick in visual studio code. Let's suppose you are writing typescript code in visual studio code and you want to hide generated javascript code.

Create .vscode folder in your folder and then create settings.json file and paste following code

{ "files.exclude": { "node_modules":true, "**/.git": true, "**/.DS_Store": true, "**/*.js.map": true, "**/*.js": {"when": "$(basename).ts"}     } }

How to enable CORS in web API2

In this post I am going to show you a very simple and useful tips that how to enable CORS in web API2.
What is CORS
Cross-origin resource sharing (CORS) is a mechanism that allows many resources (e.g. fonts, JavaScript, etc.) on a web page to be requested from anotherdomain outside the domain from which the resource originated
How to enable in CORS in web API2
In Visual Studio, from the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:Install-Package Microsoft.AspNet.WebApi.Cors Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.
public static void Register(HttpConfiguration config) { // New code config.EnableCors(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RoutePa…

How To Change your ASP.Net controls at runtime

Lets say you are working in a fairly large asp.net application. Now because of situation (or clients request) you want to change all the textbox or button control to some server control or user control. This can be very very tedious JOB if you are using Asp.net 1.X. But if you are using Asp.net 2.0 , there is a very easy way to get this done using tagMapping
it’s a way to turn all instances of a type into another type at compile time. In human language it means that it can turn all e.g. System.Web.UI.WebControls.Textbox (in our example ) instances in the entire website into another control.That is so cool that I had to do a little example. I’ve created a very simple control that inherits from a TextBox and overrides the Text property so that it HTML encodes the text. I placed it in the App_Code folder and called it SafeTextBox.

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; …

How to change some text before it is sent to the client.

In this post,I will show you how to modify the response before it is sent to the client.The trick here is to override the Render method of the Page class and modify the response.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InterceptHtml.aspx.cs" Inherits="InterceptHtml" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> Hello World! <br /> Hi </div> </form> </body> </html>
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using Syst…

How to create custom config section in asp.net

You can extend ASP.NET configuration settings with XML configuration elements of
your own. To do this, you create a custom configuration section handler.
The handler must be a .NET Framework class that inherits from 
the System.Configuration.ConfigurationSection class. The section handler 
interprets and processes the settings that are defined in XML configuration 
elements in a specific section of a Web.config file. You can read and write 
these settings through the handler's properties.
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; namespace CustomConfigSection { publicclass LoginRedirectByRoleSection : ConfigurationSection { [ConfigurationProperty("roleRedirects")] public RoleRedirectCollection RoleRedirects { get { return (RoleRedirectCollection)this["roleRedirects"]; } set { this["roleRedirects"] = valu…

How to read namespace based xml using Linq

In this post,I will show you how to read xml with namespace.For this demo,I will use following xmlstructure<?xml version="1.0" encoding="utf-8" ?> <accounts xmlns="urn:account"> <account>1001</account> <account>1002</account> </accounts> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; namespace XLinq { class Program { static void Main(string[] args) { var doc = XDocument.Load("accounts.xml"); var query = from x in doc.Descendants("{urn:account}account") select x; foreach (var item in query) { Console.WriteLine(item); } } } }

Natural Sorting in asp.net

Image
In this post,I will show you how to implement natural sorting in asp.net.There are several ways to implement this,but in this post,I am going to use windows api.
Check out following link for more detailsStrCmpLogicalW (shlwapi)
Let's start the implementation

Create a new class named FileList and add following code


Create a new class in App_Code folder and add following code


Here is complete source codeFileList.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; publicclass FileList { public FileList() { } publicstring Name { get; set; } public DateTime DateModified { get; set; } publicstring FileType { get; set; } publicstatic List<FileList> List { get { returnnew List<FileList> { new FileList{Name="file11.txt",DateModified=DateTime.Now,FileType="Text"}, new FileList{Name="file1.txt",DateModified=DateTime.Now,FileType="Text"}…

Calling cross domain wcf service using Jquery

In this post,I will show you how to call cross domain service using jquery.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.ServiceModel; using System.IO; using System.ServiceModel.Web; using System.Runtime.Serialization.Json; namespace CorssDomainService { [DataContract] publicclass Order { [DataMember] publicint ID { get; set; } [DataMember] public DateTime OrderDate { get; set; } [DataMember] publicstring Name { get; set; } } [ServiceContract] publicinterface IOrderService { [OperationContract] [WebInvoke(Method = "GET", UriTemplate = "/", ResponseFormat = WebMessageFormat.Json )] string ProcessOrder(); } [ServiceBehavior] publicclass OrderService : IOrderService { [OperationBehavior] publicstring ProcessOrder() { …

How to validate asp.net form using Jquery

In this post I will show you how to validate asp.net form using jqery. Create a new website,add a new js file ,and add following code inside it function validateForm(e) { var formIsValid = true; // check that a valid email address has been entered var emailRegExp = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/; if (!emailRegExp.test(String($("#txtEmail").val()).toUpperCase())) { addError("txtEmail", "Please enter a valid email address."); formIsValid = false; } else { removeError("txtEmail"); } // check that first name has one or more characters if ($("#txtFirstName").val() == '') { addError("txtFirstName", "This field is required."); formIsValid = false; } else { removeError("txtFirstName"); } // check that last name has one or more characters if ($("#txtLastName").val() == '') { …

How to remove duplicates elements from List using IEqualityComparer

In this post,I will show you how to remove duplicate record from List using IEqualityComparer.It has two methods to support the comparison of objects for equality.Let us suppose that you have a Employee class that has four properties EmployeeID,FirstName,LastName and Age.publicclass Employee { public Employee() { } publicstring EmployeeID { get; set; } publicstring FirstName { get; set; } publicstring LastName { get; set; } publicint Age { get; set; } public List&lt;Employee&gt; Employees { get { returnnew List&lt;Employee&gt;() { new Employee(){EmployeeID="E001",FirstName="F001",LastName="L001",Age=21}, new Employee(){EmployeeID="E002",FirstName="F002",LastName="L002",Age=25}, new Employee(){EmployeeID="E003",FirstName="F003",LastName="L003",Age=26}, new Employee(){EmployeeID="E001",Firs…

How to sum the value of gridview column using jquery

In this post I will show how to sum the value of gridview column on selection of checkbox .Let us suppose that you have a gridview which has three column named Name,Quantity and Price.Now your requirement is to sum the value of price filed on selection of checkbox.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><scriptsrc="Scripts/jquery-1.4.1.js"type="text/javascript"></script> <title></title> <script type="text/javascript"> $(document).ready(function () { var total; //Column index value of price field (Column index start from 1)var columnIndexValue = 4; varchecked…

How to read pdf document properties in asp.net

Image
In this post, I will show you how to read the pdf document properties in asp.net.As we know that there is no- such  in-built class in .net framework that read the pdf document.So,for this demo,I will used third-party library iTextSharp.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PdfPropertiesReader.aspx.cs" Inherits="PdfPropertiesReader" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title></title></head><body><formid="form1"runat="server"><div><divid="pdfProperties"runat="server"></div></div><asp:ButtonID="Button1"runat="server"OnClick="Button1_Click"Text="Read Pdf Properties"/></form>&…

How to convert IEnumerable to Html table in asp.net

In this post I will show how to convert IEnumerable to string (Html table).Assume you have a customer class which has three properties named FirstName,LastName and Age.Now,you want to display customer collection on UI.
For this I have created following method which retrives propertyname and value dynamically (using reflection) and return result as string
public static string ToHtmlTable(IEnumerable list, string tableSyle, string headerStyle, string rowStyle, string alternateRowStyle)<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title></title><styletype="text/css"> .headerStyle { background-color: #abc;…

How to fetch header info from given url

Image
In this post I will show how to fetch header info from given url using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; namespace SNIPPET_CS { publicclass HeaderInfo { publicstring Key { get; set; } publicstring Value { get; set; } publicstatic List<HeaderInfo> GetHttpResponseHeaders(string url) { List<HeaderInfo> headerList = new List<HeaderInfo>(); WebRequest webRequestObject = WebRequest.Create(url); WebResponse responseObject = webRequestObject.GetResponse(); if (responseObject != null) { headerList.AddRange(from string headerKey in responseObject.Headers select new HeaderInfo() { Key = headerKey, Value = responseObj…

How to encrypt/decrypt data in asp.net using Symmetric algorithm

Image
In this post I am going to show you how to encrypt and decrypt data in asp.net using Symmetric algorithm.Before going to implementation details let discuss some security related terms before.What is Hashing


Hashing is one-way algorithm, means once the data is hashed you can’t recovered it latter.
Hashing is a cryptographic function that is used to provide a secure fingerprint of data. A common usage you may have encountered is to check a file you have downloaded.
What is Encryption
If you want to secure your data, and latter you want to retrieve the original data. We used encryption because encryption is two-way processes. For encryption we requires following things
Key:Key is a piece of information that is used as an input parameter in encryption. The output of encryption is determined by the key.
Types of Encryption
are two main types of encryption and decryption algorithms, symmetric and asymmetric.Symmetric: In symmetric encryption we used same key for encryption and dec…

How to compress response in asp.net

Image
In this post I will show you how to compress http response in asp.net for improving performance. Before going into details let's create a simple website with single page Default.aspx and add following code into it Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><title></title></head><body><formid="form1"runat="server"><div><asp:GridViewID="grdPerson"runat="server"></asp:GridView></div></form></body></html> Default.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI…