Search

Get UnCached version form Ajax file request

While loading external javascript there is problem of caching the general solutionfor this is appending a url parameter like "?rnd=Date.Now()" at the end of the url, so that the url is always unique while making the call. The other way around is to set the IIS ouput caching with FIle change notifications. But the same could be achieve without much effort by setting the response header. We can set the response header to get the modified version from the server instead of the cached one using the following script:

How to define a class in JScript ?

This a common example for JScript(ECMA262) to create a class with defined constructor. The constructor can be parameteries to accent a/multiple parameter.

Wiindows Search with batch script

Till last year i was using Windows XP which was quite faster then windows 7 on searching files in the local system. But again windows 7 started giving me hard-time with it’s indexing services. So i started using the old batch script i wrote in the late 90’s. Its’s called windows search.


All you have to do, is to copy and save this file as "search.bat" in the user folder(c:\users\).

calling it is even easier cause it supports wildcard(*) characters.

Example:
search *.txt

will search the whole directory for the files with text extension, the query can be modified if you know a part of the file name as
search read*.txt

After pressing enter.. it takes a while and pops up a message window(with instructions), clicking ok in the message window will open notepad with a file search.txt with all the results.

Recycling IIS Application Pools

Recycling IIS app pool are always considered a better option then IISReset to refresh & purge resources. As it Before recycling itself , it invokes a new worker process first and then shutdown the old worker process which makes the IIS still available to take request. Here is the appcmd to recycle appool

%windir%\system32\inetsrv\appcmd recycle apppool /apppool.name:<app pool name>

for Example:

To reset the CRMAppPool( Crm developers know why ;)

%windir%\system32\inetsrv\appcmd recycle apppool /apppool.name:CRMAppPool

will recycle the apppool named "CRMAppPool”.

Web.Config Guide

Important Configuration Tags

There are a lot of configuration tags that are provided by the web.config file, like authentication, authorization, browserCaps, clientTarget etc., but all of these don't have that much importance (and also can't be covered in a single article ), so here, I have only concentrated on the main tags of the config file.

<authentication>

This element is used to verify the client's identity when the client requests a page from the server. This is set at the application level. We have four types of authentication modes: “None”, “Windows”, “Forms”, and “Passport”.
If we don't need any authentication, this is the setting we use:
<authentication mode="None"/>
Normally, Windows authentication is used, for which, we need to check the checkbox: Integrated Windows Authentication.
<authentication mode="Windows"/>
This authentication is handled by IIS. When the user sends a request to the server, IIS authenticates it and sends the authentication identity to the code.
IIS gives us four choices for the authentication modes: Anonymous, Basic, Digest, and Windows Integrated. If the user selects Anonymous, then IIS doesn't perform any authentication. For Basic authentication, the user has to provide a username and password. This authentication is very unsecure, because the user credentials are sent in clear text format over the network. Digest authentication is same as Basic, except it hashes the user's password and transmits the hashed version over the wire. So, it is more secure than Basic. For Windows Integrated authentication, passwords never cross the network. The user must still have a username and password, but the application uses either the Kerberos or a challenge/response protocol to authenticate the user.
Forms authentication uses web application forms to collect user credentials, and on the basis of the credential, it takes action on a web application.
<authentication mode="Forms">
<forms name="Form" loginUrl="index.asp" />
</authentication>
Passport authentication is provided by Microsoft. A redirect URL should be specified, and is used when the requested page is not authenticated, and then it redirects to this URL.
<authentication mode="Passport">
<passport redirectUrl="internal" />
</authentication>
Here, users are authenticated using the information in Microsoft's Passport database. The advantage is, we can use existing user credentials (such as an email address and password) without forcing users to go through a separate registration process. The disadvantage is we need to go through the licensing agreement with Microsoft and pay a yearly fee based on the use.
For using Passport authentication, you first install the Passport Software Development Kit (SDK) on your server. The SDK can be downloaded from here. It includes full details of implementing passport authentication in your own applications.
 

<authorization>

The <authorization> tag controls client access to web page resources. This element can be declared at any level (machine, site, application, subdirectory, or page).
<authorization>
<allow users="comma-separated list of users"
roles="comma-separated list of roles"
verbs="comma-separated list of verbs"/>
<deny users="comma-separated list of users"
roles="comma-separated list of roles"
verbs="comma-separated list of verbs"/>
</authorization>
<allow> : Using this tag, we can control access to resources on the basis of the following verbs. In these attributes, we use symbols: ? and *.? means for anonymous users/resources, and * means for all users.
  • users: This contains the list of user names (comma separated) that are allowed to access the resources.
  • roles: This contains the list of roles (comma separated) that are allowed to access the resources.
  • verbs: This contains the list of HTTP verbs to which the action applies (comma separated). It is used to create a rule that applies to a specific type of HTTP request (GET, POST, HEAD, OR DEBUG).
<deny> : Using this tag, we can control access to resources on the basis of the following verbs:
  • users: This contains the list of users names (comma separated) that are denied access to the resources.
  • roles: This contains the list of roles (comma separated) that are denied access to the resources.
  • verbs: This contains the list of HTTP verbs to which the action applies (comma separated). It is used to create a rule that applies to a specific type of HTTP request (GET, POST, HEAD, OR DEBUG).

<compilation>

In this section, we can configure the settings of the compiler. Here, we can have lots of attributes, but the most common ones are debug and defaultLanguage. Setting debug to true means we want the debugging information in the browser, but it has a performance tradeoff, so normally, it is set as false. And, defaultLanguage tells ASP.NET which language compiler to use: VB or C#.
 

<customErrors>

This tags includes the error settings for the application, and is used to give custom error pages (user-friendly error pages) to end users. In the case that an error occurs, the website is redirected to the default URL. For enabling and disabling custom errors, we need to specify the mode attribute.
<customErrors defaultRedirect="url" mode="Off">
<error statusCode="403" redirect="/accesdenied.html" />
<error statusCode="404" redirect="/pagenotfound.html" />
</customErrors>
  • "On" means this settings is on, and if there is any error, the website is redirected to the default URL.
  • "Off" means the custom errors are disabled.
  • "RemoteOnly" shows that custom errors will be shown to remote clients only.
<error statusCode="403" redirect="/accesdenied.html" />
<error statusCode="404" redirect="/pagenotfound.html" />
This means if there is an error of 403, then the website will redirected to the custom page accessdenied.html. Similarly for 404 as defined above.
Note: If an error occurs in the custom error page itself, ASP.NET won't able to handle it. It won't try to reforward the user to the same page. Instead, it'll show the normal default client error page with a generic message.
 

<globalization>

This section is used when we want to use encoding or specify a culture for the application. This is a very vast topic, and can take an article itself for explaining it. Here, we define the character set for the server to send the response to the client, which is by default is UTF-8, and the settings of which the server should use to interpret and display culturally specific strings, such as numbers and dates.
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
 

<httpRuntime>

This section can be used to configure the general runtime settings of the application. The main two are:
<httpRuntime appRequestQueueLimit="50" executionTimeout="300" />
As the name suggests, the attribute appRequestQueueLimit defines the number of requests that can be queued up on the server for processing. If there are 51 or more requests, then server would return the 503 error ("Server too busy").
The attribute executionTimeout defines the number of minutes ASP.NET will process a request before it gets timeout.
 

<trace>

As the name suggestz, it is used for tracing the execution of an application. We have here two levels of tracing: page level and application level. Application level enables the trace log of the execution of every page available in the application. IfpageOutput="true", trace information will be displayed at the bottom of each page. Else, we can view the trace log in the application root folder, under the name trace.axd.
<trace enabled="false" requestLimit="10" pageOutput="false"
traceMode="SortByTime" locaOnly="true" />
Set the attribute localOnly to false for not viewing the trace information from the client.
For enabling trace at page level, set Trace="True" in the Page tag (on the top of the page).
 

<identity>

Using this tag, we can control the identity of the application. By default, Impersonation is disabled. Using Impersonation, an ASP.NET application can execute optionally with the identity of a client on whose behalf they are operating.
<identity impersonate="false" userName="domain\username" password="password" />
 

<sessionState>

In this section, we tell ASP.NET where to store the session. By default, it's inproc which means storing the session values on the server. But we have four options:
  • "Off" means session is not enabled for the application.
  • "inproc" means storing the session values on the server.
  • "StateServer" means session states are stored in a remote server.
  • "SQLServer" means session states are stored in a SQL Server database. For this, we need to install the InstallSQLState.sql script in the SQL Server database. It is mainly used when the we use web farms (an application deployed on multiple servers), but it makes the performance slow as compared to "inproc".
Here are the other settings:
  • "cookieless": when it is true, it means the session used is without cookies.
  • “timeout” specifies after how much time the session would expire if the application is not accessed during that period.
  • "stateConnectionString" needs to be specified when the session mode is StateServer.
  • "sqlConnectionString" is the connection string of the SQL Server database if the session mode is sqlserver.
  • "stateNetworkTimeout" attribute, when using the StateServer mode to store session state, specifies the number of seconds the TCP/IP network connection between the web server and the state server can be idle before the session is abandoned. The default is 10.
<sessionState mode="Off"
cookieless="true"
timeout="100"
stateConnectionString="tcpip=server:port"
sqlConnectionString="sql connection string"
stateNetworkTimeout="number of seconds"/>
 

<appSettings>

This section is used to store custom application configuration like database connection strings, file paths etc. This also can be used for custom application-wide constants to store information over multiple pages. It is based on the requirements of the application.
<appSettings>
<add key="Emailto" value="me@microsoft.com" />
<add key="cssFile" value="CSS/text.css" />
</appSettings>
It can be accessed from code like:
ConfigurationSettings.AppSettings("Emailto");


Reflector - C# reflection over console

A custom C# reflection over console

Syntax highlight using RichTextBox

This example uses the RegEx to search the keywords and highlight them with different color

Referencing DLL from GAC in Visual Studio

Long back i wrote about it http://www.killercodes.in/2010/09/how-to-reference-assemblies-in-gac.html but this requires some registry editing and generally developers don't have privileges to do that in the production system. I too face the similar issue and i found that the GAC for .Net framework resides at

"C:\Windows\assembly\"
. So the first thing is to put your DLL there. Then

  • GoTo Projects --> Properties

  • Click Reference Path and browse the GAC folder(for 3.5 it's "C:\Windows\assembly\")


Now remove any of the local references that can conflict with the GAC version of DLL and Buld.

Why it works beacuse during the build Visaul studio will try to resolve the references and since we have specified a reference path to the Framework 3.5 GAC folder, it will resolve the reference by taking it from the GAC folder and since the folder structure remains same across windows system there will be no errors.



although i have tested it with framework 3.5 but it will work with any other framwork also.
..keep coding

Logging JScript Errors to windows event log

Writing Jscript is a tough task, there were no errors if the data is well structured, but somtimes i wish to log all those information & exception in some place to review/analyse. Yes we can log all them in browser event log, but that is temprorary and will be all gone when the window is closed. Still there is something that you can do with Windows Event Logger. Here is a small script that uses activeXObject to write the log to eventviewer. Later you can view the log by running "eventvwer" in the cmd prompt.



And this is how you can call it:
 
// Calling the log to write error
EvntLog.Err("error in script");

Note: Due to inconsistent ActiveX use, it works only with InternetExplorer browser family :(
..keep coding

Creating a System Restore point using VBScript

Create a VBScript file (*.vbs) and paste the below code, it will create a system Restore point.


' Create a System Restore Point
' supported on: Windows XP

dim spi
Set spi = Createobject("sapi.spvoice")
spi.speak "Well come napstr"
spi.speak "Initialising Automated Restore"
Const DEVICE_DRIVER_INSTALL = 10
Const BEGIN_SYSTEM_CHANGE = 100

strComputer = "."
Set objWMI = GetObject("winmgmts:" _
& "\\" & strComputer & "\root\default")

Set objItem = objWMI.Get("SystemRestore")
errResults = objItem.CreateRestorePoint _
("AUTOMATED NAPSTR RESTORE", DEVICE_DRIVER_INSTALL, BEGIN_SYSTEM_CHANGE)

spi.speak "Automated Restore point Created"

Kill a process using c#

The following class is a process manager, that helps to find and kill process with Id or name.

HttpWebRequest example with error handling using C#

This is an example of simple HttpWebRequest with error handling module

Matrix falling number - animation

This will create the green matrix falling numbers animation in a c# console with green text


Clock application with hourly beeping function



//this is a clock application with infinite-loop and hourly beeping function
while(start)
{
DateTime dtn = DateTime.Now;
if (dtn.Minute == 59 && dtn.Second == 59)
{
Console.Beep(5500, 250);
Console.Beep(3500, 250);
Console.Beep(5500, 250);
}
else if (dtn.Minute == 30 && dtn.Second == 59)
{
Console.Beep(5500, 250);
}
}




Transforming XML to HTML on the fly

Here is the simple source code needed transform the XML file to HTML on the client (try it yourself):

<html>
<body>
<script language="javascript">

xml.async = false
xml.load("cd_catalog.xml")

// Load the XSL
var xsl = new ActiveXObject("Microsoft.XMLDOM")
xsl.async = false
xsl.load("cd_catalog.xsl")

// Transform
document.write(xml.transformNode(xsl));

</script>

</body>
</html>

Using window.console in JScript

just to log messages in browser console, the console must be visible, the below function is a foolproof way to implement it, regardless of the browser.
 
/* Jscript */
//console
(function() {
if (!window.console) {
window.console = {};
}
// union of Chrome, FF, IE, and Safari console methods
var m = [
"log", "info", "warn", "error", "debug", "trace", "dir", "group",
"groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd",
"dirxml", "assert", "count", "markTimeline", "timeStamp", "clear"
];
// define undefined methods as noops to prevent errors
for (var i = 0; i < m.length; i++) {
if (!window.console[m[i]]) {
window.console[m[i]] = function() {};
}
}
})();


now in you can write anywhere
 window.console.warn(" this is warning");

to print in the console, this is quite useful with the old IE browsers.

Redirecting errors to Errors.aspx page

Although everyone wants to code bugfree, but exception are generated with the change of environment. Here is a sample as how to setup an error.aspx to

// This is the error page looking for message & stack over the http context
public partial class Errors : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!HttpContext.Current.Items.Contains("Title") && !HttpContext.Current.Items.Contains("Message"))
{
Response.Redirect("/");
}
else
{
//these can me a string literal or asp.net label
msgtitle.Text = "<br/><span class='mtitle'>" + (String)HttpContext.Current.Items["Title"] + "</span><br/>";
msgcontent.Text = "<span class='mcontent'>" + (String)HttpContext.Current.Items["Message"] + "<span/>";
msgStack.Text = "<b>Stack:</b><br/>" + (String) HttpContext.Current.Items["Stack"];
}
}
}



according to MSDN.. Server.Transfer acts as an efficient replacement for the Response.Redirect method. Response.Redirect specifies to the browser to request a different page. Because a redirect forces a new page request, the browser makes two requests to the Web server, so the Web server handles an extra request. IIS 5.0 introduced a new function, Server.Transfer, which transfers execution to a different ASP page on the server. This avoids the extra request, resulting in better overall system performance, as well as a better user experience.

so we aregoing to use it to throw the error, you can make use of this action delegate in every page to throw the exception


// setup for error message for other page -pass the title/message to the error page
Action RedirectError = (title, message,stack) =>
{
//adds the title,message & stack from the passed parameter to the HttpContext
HttpContext.Current.Items.Add("Title", title);
HttpContext.Current.Items.Add("Message",message);
// adds the stacktrace to httpcontext if it's not null
if(stack != null)
HttpContext.Current.Items.Add("Stack", stack);

//transfers the execution to a different aspx page
Server.Transfer("Errors.aspx");
};




Serialize/ De-Serialize

Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called de-serialization.
It allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.
    /// 
    /// Serializes an Object
    /// 
    /// Object to SerializedObject
    /// serialized string(xml)
    public string SerializeObject(Object objectInstance)
    {
        System.IO.StringWriter stringwriter = new System.IO.StringWriter();
        System.Xml.Serialization.XmlSerializer serilizer = new System.Xml.Serialization.XmlSerializer(objectInstance.GetType());
        serilizer.Serialize(stringwriter, objectInstance);
        return stringwriter.ToString();
    }
To de-serialize it back to the object,
    /// 
    /// De-Serializes an Object
    /// 
    /// serialized string(xml)
    /// 
    public Object DeSerializeObject(string serializedObject)
    {
        var stringReader = new System.IO.StringReader(serializedObject);
        var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Object));
        return serializer.Deserialize(stringReader) as Object;
    }

Generating class through C# code




namespace killercodes_in.CodeGeneration
{
public class GenerateClass
{
public void Generate()
{
//output file name
string fileName = "HelloWorld.cs";

//text writer to write the code
TextWriter tw = new StreamWriter(new FileStream(fileName, FileMode.Create));

//code generator and code provider
ICodeGenerator codeGenerator = new CSharpCodeProvider().CreateGenerator();
CSharpCodeProvider cdp = new CSharpCodeProvider();
codeGenerator = cdp.CreateGenerator();

//namespace and includes
CodeNamespace Samples = new CodeNamespace("Samples");
Samples.Imports.Add(new CodeNamespaceImport("System"));

//declare a class
CodeTypeDeclaration Class1 = new CodeTypeDeclaration("HelloWorld");
Samples.Types.Add(Class1);
Class1.IsClass = true;

//reference to a method - writeHelloWorld
CodeMethodReferenceExpression Method1Ref = new CodeMethodReferenceExpression();
Method1Ref.MethodName = "writeHelloWorld";
CodeMethodInvokeExpression mi1 = new CodeMethodInvokeExpression();
mi1.Method = Method1Ref;

//constructor for the class
CodeConstructor cc = new CodeConstructor();
cc.Attributes = MemberAttributes.Public;
cc.Statements.Add(mi1);
Class1.Members.Add(cc);

//method - writeHelloWorld
CodeMemberMethod Method1 = new CodeMemberMethod();
Method1.Name = "writeHelloWorld";
Method1.ReturnType = new CodeTypeReference(typeof(void));
//Method1.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), "text"));
CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Hello World!!"));
Method1.Statements.Add(cs1);
Class1.Members.Add(Method1);

//method - Main
CodeEntryPointMethod Start = new CodeEntryPointMethod();
Start.Statements.Add(new CodeSnippetStatement("HelloWorld hw = new HelloWorld();"));
Class1.Members.Add(Start);

//generate the source code file
codeGenerator.GenerateCodeFromNamespace(Samples, tw, null);

//close the text writer
tw.Close();

RunClass sampleRun = new RunClass();
}
}
}



LINQ to Lambda

As we know the LINQ is a language integrated query introduced in visual studio 2008 which offered an compact, and intelligible syntax for manipulating data & objects. Also Lambda expressions are introduced which is like an anonymous function that can be used to write local functions, delegates and expression tree. The below are few examples as how to modify the LINQ expression to Lambda.

Filtering

//Linq
    var column = from o in Orders
                 where o.CustomersId = 45
                 select o;
/* can be converted to Lambda as */
//Lambda
    var column = Orders.Where(o => o.CustomersId == 45);


Compile On Fly

This class compiles and executes a dot.net snippets on the fly in memory. Although this is a basic example, but it can be extended with xml inside Completecode();