How to increase timeout value for microsoft ajax scriptmanager?
There are two ways to increase timeout value for microsoft ajax scriptmanager.The default value of the AsyncPostBackTimeOut property is 90 seconds.
<asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeOut="600"> </asp:ScriptManager>
or in code:
ScriptManagerInstanceID.AsyncPostBackTimeout = 600;
How to catch scriptmanager exceptions in Javascript
<script type="text/javascript"> Sys.WebForms.PageRequestManager.getInstance().add_endRequest(requestEndHandler ); // This function will handle the end request event function requestEndHandler(sender, args) { if( args.get_error() ){ document.getElementById("errorMessageLabel").innerText = args.get_error().description; args.set_errorHandled(true); } } </script> ... <div id="errorMessageLabel"></div>
What is Just My Code Debugging in visual studio 2010
Visual Studio 2010 provides a debugging feature called Just My Code⢠that allows programmers to test and debug only the portion of the code they have written. When this option is enabled, the debugger always steps over method calls to methods of classes that you did not write. All the IDE-generated code can be ignored.
To enable this option, in the Options dialog, select the Debugging category to view the available debugging tools and options. Then click the checkbox that appears next to the Enable Just My Code (Managed only) option to enable or disable this feature.
Display text in different languages using unicode
namespace Unicodeinfo { public partial class Unicodefrm : Form { public Unicodefrm() { InitializeComponent(); } // assign Unicode strings to each Label private void Unicodefrm_Load( object sender, EventArgs e ) { // English char[] english = { '\u0057', '\u0065', '\u006C', '\u0063', '\u006F', '\u006D', '\u0065', '\u0020', '\u0074', '\u006F', '\u0020' }; englishLabel.Text = new string( english ) + "Unicode" + '\u0021'; // French char[] french = { '\u0042', '\u0069', '\u0065', '\u006E', '\u0076', '\u0065', '\u006E', '\u0075', '\u0065', '\u0020', '\u0061', '\u0075', '\u0020' }; frenchLabel.Text = new string ( french ) + "Unicode" + '\u0021' ; // German char[] german = { '\u0057', '\u0069', '\u006C', '\u006B', '\u006F', '\u006D', '\u006D', '\u0065', '\u006E', '\u0020', '\u007A', '\u0075', '\u0020' }; germanLabel.Text = new string ( german ) + "Unicode" + '\u0021'; // Japanese char[] japanese = { '\u3078', '\u3087', '\u3045', '\u3053', '\u305D', '\u0021'}; japaneseLabel.Text = "Unicode" + new string( japanese ); // Portuguese char[] portuguese = { '\u0053', '\u0065', '\u006A', '\u0061', '\u0020', '\u0062', '\u0065', '\u006D', '\u0020', '\u0076', '\u0069', '\u006E', '\u0064', '\u006F', '\u0020', '\u0061', '\u0020' }; portugueseLabel.Text = new string ( portuguese ) + "Unicode" + '\u0021'; // Russian char[] russian = { '\u0414', '\u043E', '\u0431', '\u0440', '\u043E', '\u0020', '\u043F', '\u043E', '\u0436', '\u0430', '\u043B', '\u043E', '\u0432', '\u0430', '\u0442', '\u044A', '\u0020', '\u0432', '\u0020' }; russianLabel.Text = new string ( russian ) + "Unicode" + '\u0021'; // Spanish char[] spanish = { '\u0042', '\u0069', '\u0065', '\u006E', '\u0076', '\u0065', '\u006E', '\u0069', '\u0064', '\u006F', '\u0020', '\u0061', '\u0020'}; spanishLabel.Text = new string ( spanish ) + "Unicode" + '\u0021'; // Simplified Chinese char[] chinese = { '\u6B22', '\u8FCE', '\u4F7F', '\u7528', '\u0020'}; chineseLabel.Text = new string ( chinese ) + "Unicode" + '\u0021'; } // end method Unicodefrm_Load } // end class Unicodefrm } // end namespace Unicodeinfo
Calculating the hash value of an XML in C# ASP.NET
static byte[] HashXml ( XmlElement xe, HashAlgorithm hash ) { XmlDocument xd = new XmlDocument(); xd.LoadXml (xe.OuterXml); return HashXml(xd, hash); }
static byte[] HashXml ( XmlDocument xd, HashAlgorithm hash ) { //Get the assembly Assembly a = Assembly.Load("System.Security, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); //Get the hashing class Type t = a.GetType("System.Security.Cryptography.Xml.CanonicalXml"); ConstructorInfo c = t.GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(XmlDocument), typeof(XmlResolver) }, null); //construct the object object cx = c.Invoke(new object[] { xd, null }); //calculate the Hash byte[] result = (byte[])t.InvokeMember( "GetDigestedBytes", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, cx, new object[] { hash }); return result; }
ASP.NET File Types
.aspx file
This ASP.NET web forms file contains the markup (or user interface code) of the file and optionally the underlying application code.
.cs or .vb files
These are the code-behind files. If the page has indicated so, the underlying application code will be created here. This is the default setting.
web.config
This is the applicationās general configuration file. It is an XML-based file that contains all settings for customizing the connection strings, application settings, security, external assemblies, memory, state management, and so on.
global.ascx
In this file, you can add code for event handlers at the application level. Events are those for when the application starts or ends or when an error is thrown.
.ascx files
These are user control files. In these files, you can create small pieces of functionality the same way as with a full ASPX page, but the difference is that they can not be accessed directly and must be hosted inside ASPX pages. You can reuse these user controls in any page of your application.
.asmx or .svc files
ASMX files are ASP.NET web services. These files provide services for pages in your application or any other program that can access them. ASMX web services are
being slowly replaced by Windows Communication Foundation (WCF) services, which have the extension .svc and offer improved security and scalability features.
.master files
Master pages are like ASPX pages with the difference that they are used as templates for other pages, sharing the look and feel and base functionality. Master pages inside other master pages are called nested master pages.
Generate country list using CultureInfo class in C#
/// <summary> /// method for generating a country list, say for populating /// a ComboBox, with country options. We return the /// values in a Generic List<T> /// </summary> /// <returns></returns> public static List<string> GetCountryList() { //create a new Generic list to hold the country names returned List<string> cultureList = new List<string>(); //create an array of CultureInfo to hold all the cultures found, these include the users local cluture, and all the //cultures installed with the .Net Framework CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures); //loop through all the cultures found foreach (CultureInfo culture in cultures) { //pass the current culture's Locale ID (http://msdn.microsoft.com/en-us/library/0h88fahh.aspx) //to the RegionInfo contructor to gain access to the information for that culture RegionInfo region = new RegionInfo(culture.LCID); //make sure out generic list doesnt already //contain this country if (!(cultureList.Contains(region.EnglishName))) //not there so add the EnglishName (http://msdn.microsoft.com/en-us/library/system.globalization.regioninfo.englishname.aspx) //value to our generic list cultureList.Add(region.EnglishName); } return cultureList; } }
Check if the value is of type decimal in C#
public static bool validateDecimal(string ParNumber) { try { decimal result; if (decimal.TryParse(ParNumber, out result)) { return true; } else { return false; } } catch { return false; } }
Check if field is mandatory field in C# ASP.NET
The function expects you pass a string value and the column of a table to validate.
private static bool IsMandatory(string text,string column) { try { String[] a = text.Replace("[", "").Replace("]", "").Split('~'); string xx = a.Where(p => p.Contains(column)).FirstOrDefault().ToString(); string value = xx.Substring(xx.IndexOf("=") + 1); bool status = bool.Parse(value); return status; } catch { return true; } }
Check if date is valid (future date) in C#
public static bool validateDateNotFuture(string ParDate) { try { DateTime d= Convert.ToDateTime(ParDate); if (d > DateTime.Now) { return false; } else { return true; } } catch { return false; } }
Regex to check for valid telephone number
public static bool validateTelePhone(string ParNumber) { if (!Regex.Match(ParNumber, @"^[1-9]\d{3}-[1-9]\d{3}-\d{4}$").Success) { return false; } return true; }
Check for valid percentage in C# .NET
public static bool validatePercentage(string ParNumber) { try { Convert.ToDecimal(ParNumber); if (Convert.ToDecimal(ParNumber) < 100 && Convert.ToDecimal(ParNumber) >= 0) { return true; } else { return false; } } catch { return false; } }
Check for number in C#
public static bool validateNumber(string ParNumber) { try { Convert.ToInt32(ParNumber); return true; } catch { return false; } }
Check if value is Money
public static bool validateMoney(string ParMoney) { try { Convert.ToDouble(ParMoney); return true; } catch { return false; } }
Check if the value is of type Datetime
public static bool validateDate(string ParDate) { try { Convert.ToDateTime(ParDate); return true; } catch { return false; } }
Computation of hashes
Generating hashing for files or keys is often used in programming to identify files, tables or other data collection types. There are different ways of doing this and some are efficient meaning the method of hashing is reliable unlike others which may generate similar keys for different types of bytes.
/// <summary> /// /// </summary> /// <param name="bytes">pass the sequence of bytes for which the hash is computed</param> /// <returns></returns> public uint ComputeChecksum(byte[] bytes) { uint[] table; uint poly = 0xedb88320; table = new uint[256]; uint temp = 0; for (int i = 0; i < table.Length; ++i) { temp = Convert.ToUInt32(i); for (int j = 8; j > 0; --j) { if ((temp & 1) == 1) { temp = (uint)((temp >> 1) ^ poly); } else { temp >>= 1; } } table[i] = temp; } uint crc = 0xffffffff; for (int i = 0; i < bytes.Length; ++i) { byte index = (byte)(((crc) & 0xff) ^ bytes[i]); crc = (uint)((crc >> 8) ^ table[index]); } return ~crc; }
Windows impersonation for moving files in C#
When you have a system and you may want to move files in a secure environment without the users having to know the password to the destination machine. The following functions do this by using maintained username, password and domain from the database which can be encrypted and decrypted. For my case I have used tripledes class to encrypt my parameter values.
/// </summary> /// <param name="Source">source location</param> /// <param name="Destination">destination location</param> /// <param name="Dorm">domain</param> /// <param name="Pass">password</param> /// <param name="Usr">username</param> public static void fnSecureCopy(string Source, string Destination, string Dorm, string Pass, string Usr) { IntPtr token = IntPtr.Zero; IntPtr tokenDuplicate = IntPtr.Zero; if (RevertToSelf()) { if (LogonUser(Usr, Dorm, clsEncDec.DecryptString(Pass), LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token)) { if (DuplicateToken(token, LOGON32_LOGON_INTERACTIVE, ref tokenDuplicate)) { WindowsIdentity identity = new WindowsIdentity(tokenDuplicate); WindowsImpersonationContext context = identity.Impersonate(); if ((context != null)) { CloseHandle(token); CloseHandle(tokenDuplicate); if (!Directory.Exists(Path.GetDirectoryName(Destination))) Directory.CreateDirectory(Path.GetDirectoryName(Destination)); File.Copy(Source, Destination); clsLogs.fnErrorLog("Impersonated user: " + WindowsIdentity.GetCurrent().Name, "RepoWeb"); context.Undo(); ClsAudit.Log_Audit("Generate", "Generated Format 31" + Destination); } } } if (token != IntPtr.Zero) CloseHandle(token); if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate); } else { //log error clsLogs.fnErrorLog("Failed to impersonate user: " + Dorm + @"\" + Usr, "Impersonation to copy file."); } }
Reset all controls of a web form in C#
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Text.RegularExpressions; using System.Globalization; using System.Collections.Generic; /// <summary> /// Summary description for Constants_Audit /// </summary> public class Constants_Audit { public Constants_Audit() { // // TODO: Add constructor logic here // } public static void ResetFields(ControlCollection pageControls) { foreach (Control contl in pageControls) { string strCntName = (contl.GetType()).Name; switch (strCntName) { case "TextBox": TextBox tbSource = (TextBox)contl; tbSource.Text = ""; break; case "RadioButtonList": RadioButtonList rblSource = (RadioButtonList)contl; rblSource.SelectedIndex = -1; break; case "DropDownList": DropDownList ddlSource = (DropDownList)contl; ddlSource.SelectedIndex = -1; break; } ResetFields(contl.Controls); } } }
Format a date passed as a string in C#
The following function formats a date passed as a string for you to be able to control the date type that you are familiar with. Dates sometimes can cause unnecessary errors that are quite hard to debug since different countries use different date types .
public static string SQLDate(string date) { int p1 = date.IndexOf("/"); int p2 = date.IndexOf("/", p1 + 1); if (p1 != -1 || p2 != -1) { string d = date.Substring(0, p1); string m = date.Substring((p1 + 1), (p2 - p1 - 1)); string y = date.Substring(p2 + 1); if (y.Length < 4 || y.Length > 4) return ""; date = m + "/" + d + "/" + y; return date; ; } return ""; }
Writing System Logs and System Errors in C#.Net
The following source code illustrates how you can accomplish writing System logs that will enable users to report more detailed errors encountered by the system.
Many Users are not familiar with errors that are thrown by the system and when reporting these bugs it becomes more hectic for the developer to intemperate what the user reported. Hence a logs which can register both errors and events will help a programmer understand the problem and solve it within a shorter period.
using System; using System.Data; using System.Configuration; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Text; using System.IO; /// <summary> /// System Logs /// </summary> public class Logs { public Logs() { // // TODO: Add constructor logic here // } #region "Writing Text File Logs" /// <summary> /// Write Error Log /// </summary> /// <param name="error">Exception</param> /// <param name="frm">Location</param> public static void fnErrorLog(string error, string frm) { try { //Input all the necessary parameters that you want the log to capture string username = HttpContext.Current.Session["FullName"].ToString(); int userID = int.Parse(HttpContext.Current.Session["UserId"].ToString()); //Give the path to which the textfile shall be written and a suitable filename string errorLog = File_Path() + @"Errors\" + string.Format("{0:yyyyMMdd}",DateTime.Now) + @".log"; //For my case i prefer to check for any existing similar files or directory existence and create if non existent if (!Directory.Exists(Path.GetDirectoryName(errorLog))) Directory.CreateDirectory(Path.GetDirectoryName(errorLog)); FileStream fStream = new FileStream(errorLog, FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter sWriter = new StreamWriter(fStream); sWriter.Close(); fStream.Close(); //Error Logging Starts FileStream fStreamDup = new FileStream(errorLog, FileMode.Append, FileAccess.Write); StreamWriter sWrite = new StreamWriter(fStreamDup); sWrite.WriteLine("Error: " + error + " occured on: " + frm + ", at: " + DateTime.Now.ToString() + " User: " + username); //sWriterDup.WriteLine(); sWrite.Close(); fStreamDup.Close(); } catch //(Exception ex) { //MessageBox.Show(ex.Message); } } /// <summary> /// Write Event Log /// </summary> /// <param name="evnt">Event Occurred</param> public static void fnEventLog(string evnt) { try { string username = HttpContext.Current.Session["auth101"].ToString(); int userID = int.Parse(HttpContext.Current.Session["UserId"].ToString()); string eventLog = File_Path() + string.Format("{0:yyyyMMdd}", DateTime.Now) + @".log"; if (!Directory.Exists(Path.GetDirectoryName(eventLog))) Directory.CreateDirectory(Path.GetDirectoryName(eventLog)); //Get the file for exclusive read/write access FileStream fStream = new FileStream(eventLog, FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter sWriter = new StreamWriter(fStream); sWriter.Close(); fStream.Close(); //Event Logging Starts FileStream fStreamDup = new FileStream(eventLog, FileMode.Append, FileAccess.Write); StreamWriter sWriterDup = new StreamWriter(fStreamDup); sWriterDup.WriteLine("User: " + username + " Action: " + evnt + ", at: " + DateTime.Now.ToString()); //sWriterDup.WriteLine(); sWriterDup.Close(); fStreamDup.Close(); } catch (Exception ex) { clsLogs.fnErrorLog(ex.Message, "fnEventLog"); } } #endregion }

