Posts

Showing posts with the label Asp.Net

Security Exception in ASP.NET on shared hosting environment [solved]

When i was trying to host my newly developed website on shared server and i stuck with following exception Security Exception in ASP.NET [SecurityException: Request failed.] System.Security.CodeAccessSecurityEngine.ThrowSecurityException(RuntimeAssembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed) +165 System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Object assemblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed) +100 System.Security.CodeAccessSecurityEngine.CheckSetHelper(PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMethodHandleInternal rmh, Object assemblyOrString, SecurityAction action, Boolean throwException) +284 System.Security.CodeAccessSecurityEngine.CheckSetHelper(CompressedStack cs, PermissionSet grants, Per

Cannot create type 'webservice' error solution

We create a web-service in development environment it working fine. But when we deploy the developed web service in production server many people get the Cannot create type 'some web-service  error. After finding the solution on the net i got one resolution which i am going to share now. To get ride of this error we need to re-install the .net framework 2.0 in IIS. This is essential to run web service on server. Following is the step you need to follow to register the .net framework in IIS. Open command prompt Then type >CD  C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ aspnet_regiis.exe -i After above instruction the .net framework will be register in IIS. Now run the web service again. it should be run normally. Hurray you did it

Disable button after click in asp.net

To prevent double submit a form by user we need to restrict the user to click the button again. The idea is that we will use JavaScript to disable the button once user clicks first time. Add the following lines on .aspx page <asp:Button ID="btnProcess" runat="server" onclick="btnProcess_Click" Text="Process" /> Add the following line on .aspx.cs page (Page_Load). string strProcessScript = "this.value='Processing...';this.disabled=true;"; btnProcess.Attributes.Add("onclick", strProcessScript + ClientScript.GetPostBackEventReference(btnProcess, "").ToString()); This will disable Button, and then change the text of the button " Processing... ", and then continue on with the server side event btnProcess_OnClick event handler.

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

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

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

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

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

Highlight gridview row in update panel without posting back in asp net

When user selects particular row of gridview then that row should be highlighted. but in asp.net you do not have mechanism to to this task automatically. For this purpose you need to write some custom code, which includes some JavaScript code. to highlight the row selected by user follow the step below For this you have to write this code in your code behind file in OnRowCreated event or your can also write this code in OnRowDataBound event of grid... protected void ctlGridView_OnRowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Attributes.Add("onclick", "onGridViewRowSelected('" + e.Row.RowIndex.ToString() + "')"); } } then add following script to your aspx page in script tag <script language="javascript" type="text/javascript"> var gridViewCtlId = '<%=ctlGridView.ClientID%>

Restore the lost focus of Auto post back controls in asp.net update Panel control

Problem: We put  autopostback controls like textbox, DropDownList controls inside in update panel to reducing the flickering of the Page.but when user uses tab for entering the details  the focus of the control losts. Web site users who prefer to use keyboard need to use mouse to activate appropriate input box or press TAB multiple times. Solution: Step 1: Save following in js file give any name to it (like MyUpdatePanelFocus.js ) var lastFocusedControlId = ""; function focusHandler(e) { document.activeElement = e.originalTarget; } function appInit() { if (typeof (window.addEventListener) !== "undefined") { window.addEventListener("focus", focusHandler, true); } Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler); Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler); } function pageLoadingHandler(sender, args) { lastFocusedControlId = typeof (document.acti

Send bulk Email in asp.net using excel file

When you want to send the mail to multiple person email id and your data exists in the excel file like email address and his name. you can accomplish this task using asp.net and c#. In C# under System.Net.Mail and System.Net  namespace you can use classes which can help us to send mail effortlessly. I am giving some sample code to understand the concept Following is aspx design Page Sample < %@ Page Language =" C# " AutoEventWireup =" true " CodeFile =" LogDatails.aspx.cs " Inherits =" LogDatails " % > < !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 " >

404 error on report viewer contorol in asp .net while hosting on IIS 7 issue solved

If you are facing the problem rendering report viewer elements while loading the report viewer on browser  Why it happens? The answer is IIS7 Handler Mappings does not contain Reserved.ReportViewerWebControl.axd httpHandler, and therefore unable to render the ReportViewer elements needed by the JavaSript.  What is the Solution? Open  Internet Information Services (IIS) Manager  and select your Web application. Under  IIS  area, double-click on  Handler Mappings  icon. At the  Action  pane on your right, click on  Add Managed Handler . At the  Add Managed Handler  dialog, enter the following: Request path:  Reserved.ReportViewerWebControl.axd Type:  Microsoft.Reporting.WebForms.HttpHandler Name:  Reserved-ReportViewerWebControl-axd Click  OK . What happens to your web application after you do above setting in IIS ? Reserved-ReportViewerWebControl-axd handler is now added to your Handler Mappings list. Notice that the following line has also been added to your

Encrypt web.Config sections using c# in asp.net

To give secuity to to your web application you need to make your applications secured you can encrypt the certain sections of web.config . To accomplish this task microsoft has provided library in the namespace System.Web.Configuration . To Encrypt the web.config section you can use the following code using System.Configuration.Provider; using System.Configuration.Assemblies; using System.Web.Configuration; Configuration confi = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); ConfigurationSection section = confi.ConnectionStrings; section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); To Decrypt the web.config section you can use the following code using System.Configuration.Provider; using System.Configuration.Assemblies; using System.Web.Configuration; Configuration confi = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath); ConfigurationSection section = confi.ConnectionStrings; section.Sec

Regular Expression for numeric field in Asp.net 2.0 & 3.5

Any new developer needed to understand importance of the validation in their application to avoid future errors or bug in application. For this purpose developer must ensure the user input to their application is proper and well handled to avoid future bug or error in the application. In the list of validation the important validation is numeric validation. in numeric validation user must enter or application must prompt the user to enter only numeric field. In asp.net we/developer normally use the Regular Expression Validation but proper regulion expression is as follows ^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$ Use this to restrict the user to enter Only numeric field give me ur feedback if any Enjoy

Add MouseOver and Mouseout effect to asp.net Calendar Control

When I thought that give some interesting effect to calendar control, which will improve look and feel of the Calendar I started working on it and I created the following code which I want to share following is my design code.... <div> <asp:Calendar ID="Calendar1" runat="server" BackColor="White" BorderColor="Black" BorderStyle="Solid" CellSpacing="1" Font-Names="Verdana" Font-Size="9pt" ForeColor="Black" Height="250px" NextPrevFormat="ShortMonth" onselectionchanged="Calendar1_SelectionChanged" Width="779px" ondayrender="Calendar1_DayRender"> <SelectedDayStyle BackColor="#333399" ForeColor="White" /> <TodayDayStyle BackColor="#999999" ForeColor="White" /> <OtherMonthDayStyle ForeCo