Posts

Showing posts with the label Asp.Net

Log exception to file in c# .net core application explained

In production environment when any bug gets reported at that time as developer wants to get the exception details of bug to resolve the issue on high priority.
In some case there might be situation where exception is not logged in table but developer wants to check the bug immediately. for that purpose we need to write the
exception details including stack trace of bug in file. To implement this easily i am going to demonstrate the implementation of custom logging in file as below.

First we need to construct the exception and logger method in custom logger class as shown below.


public class CustomLogger { public static List<string> ConstructExceptionDetails(Exception ex,string FunctionName) { return new List<string>() { $"{DateTime.Now} - {FunctionName}", $"Exception: {ex.Message}", $"StackTrace: {ex.StackTrace}", $"InnerException: {ex.InnerException?.…

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, Permissio…

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 promptThen type >CD C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -iAfter 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 ControllersCreate new base custom controller class which inherits the base controller classInherit created base custom controller class to your controllersFollowing 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 use this created custom…

Internet explorer Loads pages from cache issue resolution in asp.net

Internet explorer have tendency to load pages from cache for same requested URL. Which makes thing worse where the content of the web page updated frequently. In this situation Internet Explorer not send request to the server for page rendering. To resolve the issue in asp.net there are two option available. Write the HTML code in head tag or write server side code to tell Internet explorer to not to load pages from cache.

If you are trying to add code in design or HTML page then add following code

<HTML><HEAD> <META HTTP-EQUIV="Pragma" CONTENT="no-cache"> <META HTTP-EQUIV="Expires" CONTENT="-1"> </HEAD><BODY> </BODY> </HTML> 
In Asp.NET, you can do it on a page-by-page granularity by using this set of methods prior to calling the web page by following way.


HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1)); HttpContext.Response.Cache.SetValidUntilExpires(false); HttpContext.Response.C…

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

ICallbackICallbackEventHandler
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.Serialization.JavaScriptSe…

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 fileupload 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 item in values.FirstO…

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, tar…

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%>'; var gr…

HTTP Error 500.19 - Internal Server Error -Complete solution

Image
HTTP Error 500.19 - Internal Server Error The requested page cannot be accessed because the related configuration data for the page is invalid.