Posts

Prevent ASP.NET Forms Authentication from Timing Out on a Shared Hosting

I’m hosting a website on a shared hosting server. This site uses Forms Authentication to generate the session cookie that authenticates my users. Everything worked fine with the site, including authentication, until I tried to make it so my authentication cookies didn’t expire every 20 minutes, which is the default expiration setting for Forms Authentication I have set following settings to my web.config <authentication mode="Forms" > <forms loginUrl="~/Account/LogOn" timeout="2880" /> </authentication> but even though the user log outs from the system in 2 mins its irritating to user. To solve the issue we need to set machine key into the web.config file. To generate the machine key use following code snippet. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; namespace keygenerator { class Program { static void Main(string[] argv

File extension validation using javascript in MVC

This is article which demonstrate the validation of allowed file extension for upload of files in MVC using javascript. In this article i have used validation for valid image format like Jpeg, Jpg,Gif and png image format. If users ties to upload any other file apart from above mentioned file then the javascript function will shows proper message to user to select appropriate files. I have used html input file control for uploading of files in MVC application. following is the html code for it. <body> <div style="height:50px; padding-bottom:20px;"> @using (@Html.BeginForm("Create","FileUpload",FormMethod.Post,new{ enctype = "multipart/form-data"})) { <input type="file" id="file1" name="sdf" style=" margin-top:0px;" onchange="if( CheckExtention(this.value) ) {parent.ShowHideImage(true);this.form.submit();}" /> } </div> </body> and followi

Asp.Net MVC best practices part 1

If you decided to develop the application using Asp.Net MVC application and. I am going to demonstrate you to follow the best practices in MVC to develop the robust web application . If you want to log the exceptions occurs in controllers you need to write try catch blocks in each action method. This approach is also not recommended because you need to write try catch block in each action method. To get ride of this you can handle exceptions and log each exception by using centralized approach. These approaches are as follows Do not inherit the Controller base class directly to your Controllers Create new base custom controller class which inherits the base controller class Inherit created base custom controller class to your controllers Following is the sample code which demonstrate the above best practices public class BaseController : Controller { } In above code I have inherited the controller class to custom base controller class and below is the code to us

Numeric validation on textbox/input on keydown event using JQuery

This is simple way to implement the numeric validation on textbox or input control using jquery. Firstly you need to use jquery selector for binding the keydown event to input control. Once you bind it it will only allow numeric keys and reject the alphabetical keys. Following is the code snippet of the numeric validation using Jquery. $(document).ready(function () { $("#MobileNo").keydown(function (e) { // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || // Allow: Ctrl+A (e.keyCode == 65 && e.ctrlKey === true) || // Allow: home, end, left, right, down, up (e.keyCode >= 35 && e.keyCode <= 40)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop the keypress if ((e.shiftKey || (e.keyCode < 48 || e.k

Call server side methods asynchronously without having a postback using callback in asp.net

Callback is another fabulous way to communicate with server for light weight tasks. While working in ASP.NET, sometimes we need to call server side methods asynchronously without having a postback. Sometimes it is either a full page postback or partial page postback. To Implement callback in asp.net following interfaces to me implement in the asp.net page ICallback ICallbackEventHandler Let us first implement ICallbackEventHandler to call the server side method asynchronously step-by-step. The following are the definition of two methods which we need to implement. RaiseCallbackEvent method invoke through JavaScript function. public void RaiseCallbackEvent(string eventArgument) { //populate Customer object to return Customer customer = new Customer(); customer.Name = "Muhammad Adnan"; customer.Age = 24; //javascript serialization of Customer object System.Web.Script.Serialization.JavaScriptSerializer jss; jss = new System.Web.Script.Serializa

Database backup from Sql script using cursor in sql server 2008/2010

This is simple example of taking database backup from the sql script. In my example I have illustrated the simplest way to take the back up from the database. I have used the cursor for the same.    Following is the code of the Backup script. DECLARE @name VARCHAR(50) -- database name DECLARE @path VARCHAR(256) -- path for backup files DECLARE @fileName VARCHAR(256) -- filename for backup DECLARE @fileDate VARCHAR(20) -- used for file name SET @path = 'C:\Backup\' SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112) DECLARE db_cursor CURSOR FOR SELECT name FROM master.dbo.sysdatabases WHERE name NOT IN ('master','model','msdb','tempdb') OPEN db_cursor FETCH NEXT FROM db_cursor INTO @name WHILE @@FETCH_STATUS = 0 BEGIN SET @fileName = @path + @name + '_' + @fileDate + '.BAK' BACKUP DATABASE @name TO DISK = @fileName FETCH NEXT FROM db_cursor INTO @name END CLOSE db_cursor DEAL

How to Import CSV File and bind csv file data to gridview in asp.net using c#

I am going to demonstrate in this article about importing CSV file data into datatable and then bind that data to Asp.net gridview control. I have tried to make code simpler and less line of code. I am assuming that you have saved the csv file to server by using file-upload control. After that create function which returns string[] private IEnumerable<string[]> GetAllDataFromCSVFile(string FileName) { string str; using (StreamReader rd=new StreamReader(FileName)) { while ((str = rd.ReadLine()) != null) { yield return str.Split(','); } } } Create another function which returns final data-table with CSV File data private DataTable GetCSVData(string FileName) { var values = GetAllDataFromCSVFile(FileName); DataTable dt = new DataTable(); int j=0; foreach (var

Populate Dropdown with jquery using JSON request in asp.net mvc3

In this Article, I am going to demonstrate to fill the dropdownlist with J query using JSON in asp.net mvc3 . To achieve this task we need to write the following JavaScript code in view ( .cshtml page). @{ ViewBag.Title = "Products"; } <script type="text/javascript"> jquery(document).ready(function () { jquery("ddlCategory").change(function () { var idModel = jquery("#ddlCategory").val(); jquery.getJSON("product/items/", { category: idModel }, function (carData) { var select =jquery("#ddlitems"); select.empty(); select.append($('<option/>', { value: 0, text: "" })); jquery.each(carData, function (index, itemData) {

ASP.NET Redirect to open a new browser window using javascript window.Open method

To  redirect the page in new window there is no readymade methode in asp.net. To overcome this lack of readymade function, we need to do some custom coding and it will only achieve by using javascript Window.Open Methode. I have created the methode in c#.nnet to redirect the desired page in new window. Following is my methode defination.. public static void Redirect(string url, string target, string windowFeatures) { HttpContext context = HttpContext.Current; Page page = (Page)context.Handler; string script; if (!String.IsNullOrEmpty(windowFeatures)) { script = @"window.open(""{0}"", ""{1}"", ""{2}"");"; } else { script = @"window.open(""{0}"", ""{1}"");"; } script = String.Format(script, url

How to convert rows into columns in Sql Server 2008

Image
Convert rows into columns in sql server database? We're going to see how to do that using different query, and there is the "Pivot" function in SQL Server 2005.     Example: We are using two tables: Subject which is a lookup table that holds the subject names, and the StudentSubject which contains the student grades for the different subject. We are going to build the query having fixed columns: We can use the "case"  statement in the query to convert rows into columns. SELECT StudentId, SUM(Physics) AS Physics, SUM(Chemistry) As Chemistry, SUM(Math) AS Math, SUM(English) As English FROM (SELECT StudentId, (CASE SubjectId WHEN 24 THEN ISNULL(Grade, 0) END) AS Physics, (CASE SubjectId WHEN 25 THEN ISNULL(Grade, 0) END) AS Chemistry, (CASE SubjectId WHEN 26 THEN ISNULL(Grade, 0) END) As Math, (CASE SubjectId WHEN 28 THEN ISNULL(Grade, 0) END) AS English FROM Student_Subject) s GROUP BY StudentId Now, we can convert rows into columns