Search

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;
    }