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.


/* Jscript - event logger */
// Creates a Eventlog object
function EvntLog(){
this.about = "This will log all the messages to system event log on a IE browser";
}
// adds functions to it
EvntLog.prototype = {
Error:function(ErrorMsg){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(1,Error);
},
Success:function(SuccessMessage){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(0,Message);
},
Warn:function(WarningMessage){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(2,Message);
},
Info:function(InformationMessage){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(4,Information);
},
AuditSuccess:function(AuditSuccessMessage){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(8,Message);
},
AuditFailure:function(AuditFailureMessage){
var WshShell = new ActiveXObject("WScript.shell");
WshShell.LogEvent(16,Message);
}
}

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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace killercodes_in.ProcKiller
{
//Process Killer
class IProcKiller
{
public void I_KillByName(string ProcName)
{
try
{
Process[] processByName = Process.GetProcessesByName(ProcName);
//Process pogo = Process.GetProcesses();
foreach (Process pr in processByName)
{
pr.Kill();
}
}
catch
{
Console.WriteLine("Cannot terminate " + ProcName + "\n");
}
}
public void I_KillByWinName(string WindowName)
{
//bool res;
try
{
Process[] pro = Process.GetProcesses();
foreach (Process p in pro)
{
if (p.MainWindowTitle.Equals(WindowName))
{
p.Kill();;
}
else
{
}
}
}
catch
{
System.Windows.Forms.MessageBox.Show("Cannot terminate " + WindowName + "\n Process Not found", "Erraor:");
}
//return true;
}
}
}

HttpWebRequest example with error handling using C#

This is an example of simple HttpWebRequest with error handling module
using System;
using System.IO;
using System.Net;
using System.Text;
public class HttpWebRequestTool
{
public static void Main(String[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Missing argument. Need a URL and a filename");
}
else
{
StreamWriter sWriter = new StreamWriter(args[1]);
sWriter.Write(WRequest(args[0], "GET", ""));
sWriter.Close();
}
}
public static string WRequest(string URL, string method, string postData)
{
string responseData = "";
try
{
System.Net.HttpWebRequest hwrequest =
(System.Net.HttpWebRequest)System.Net.WebRequest.Create(URL);
hwrequest.Accept = "*/*";
hwrequest.AllowAutoRedirect = true;
hwrequest.UserAgent = "http_requester/0.1";
hwrequest.Timeout= 60000;
hwrequest.Method = method;
if (hwrequest.Method == "POST")
{
hwrequest.ContentType = "application/x-www-form-urlencoded";
// Use UTF8Encoding instead of ASCIIEncoding for XML requests:
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] postByteArray = encoding.GetBytes(postData);
hwrequest.ContentLength = postByteArray.Length;
System.IO.Stream postStream = hwrequest.GetRequestStream();
postStream.Write(postByteArray, 0, postByteArray.Length);
postStream.Close();
}
System.Net.HttpWebResponse hwresponse =
(System.Net.HttpWebResponse) hwrequest.GetResponse();
if (hwresponse.StatusCode == System.Net.HttpStatusCode.OK)
{
System.IO.Stream responseStream = hwresponse.GetResponseStream();
System.IO.StreamReader myStreamReader =
new System.IO.StreamReader(responseStream);
responseData = myStreamReader.ReadToEnd();
}
hwresponse.Close();
}
catch (Exception e)
{
responseData = "An error occurred: " + e.Message;
}
return responseData;
}
}

Matrix falling number - animation

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

using System;
namespace Killercodes.matrix
{
class Program
{
static int Counter;
static Random rand = new Random();
static int Interval = 100; // Normal Flowing of Matrix Rain
static int FullFlow = Interval + 30; // Fast Flowing of Matrix Rain
static int Blacking = FullFlow + 50; // Displaying the Test Alone
static ConsoleColor NormalColor = ConsoleColor.DarkGreen;
static ConsoleColor GlowColor = ConsoleColor.Green;
static ConsoleColor FancyColor = ConsoleColor.White;
//static String TextInput = "Matrix";
static char AsciiCharacter//Randomised Inputs
{
get
{
int t = rand.Next(10);
if (t <= 2)
return (char)('0' + rand.Next(10));
else if (t <= 4)
return (char)('a' + rand.Next(27));
else if (t <= 6)
return (char)('A' + rand.Next(27));
else
return (char)(rand.Next(32, 255));
}
}
static void Main()
{
Console.ForegroundColor = NormalColor;
Console.WindowLeft = Console.WindowTop = 0;
Console.WindowHeight = Console.BufferHeight = Console.LargestWindowHeight;
Console.WindowWidth = Console.BufferWidth = Console.LargestWindowWidth;
Console.SetWindowPosition(0, 0);
Console.CursorVisible = false;
int width, height;
int[] y;
Initialize(out width, out height, out y);//Setting the Starting Point
while (true)
{
Counter = Counter + 1;
UpdateAllColumns(width, height, y);
if (Counter > (3 * Interval))
Counter = 0;
}
}
private static void UpdateAllColumns(int width, int height, int[] y)
{
int x;
if (Counter < Interval)
{
for (x = 0; x < width; ++x)
{
if (x % 10 == 1)//Randomly setting up the White Position
Console.ForegroundColor = FancyColor;
else
Console.ForegroundColor = GlowColor;
Console.SetCursorPosition(x, y[x]);
Console.Write(AsciiCharacter);
if (x % 10 == 9)
Console.ForegroundColor = FancyColor;
else
Console.ForegroundColor = NormalColor;
int temp = y[x] - 2;
Console.SetCursorPosition(x, inScreenYPosition(temp, height));
Console.Write(AsciiCharacter);
int temp1 = y[x] - 20;
Console.SetCursorPosition(x, inScreenYPosition(temp1, height));
Console.Write(' ');
y[x] = inScreenYPosition(y[x] + 1, height);
}
}
else if (Counter > Interval && Counter < FullFlow)
{
for (x = 0; x < width; ++x)
{
Console.SetCursorPosition(x, y[x]);
if (x % 10 == 9)
Console.ForegroundColor = FancyColor;
else
Console.ForegroundColor = NormalColor;
Console.Write(AsciiCharacter);//Printing the Character Always at Fixed position
y[x] = inScreenYPosition(y[x] + 1, height);
}
}
else if (Counter > FullFlow)
{
for (x = 0; x < width; ++x)
{
Console.SetCursorPosition(x, y[x]);
Console.Write(' ');//Slowly blacking out the Screen
int temp1 = y[x] - 20;
Console.SetCursorPosition(x, inScreenYPosition(temp1, height));
Console.Write(' ');
if (Counter > FullFlow && Counter < Blacking)// Clearing the Entire screen to get the Darkness
{
if (x % 10 == 9)
Console.ForegroundColor = FancyColor;
else
Console.ForegroundColor = NormalColor;
int temp = y[x] - 2;
Console.SetCursorPosition(x, inScreenYPosition(temp, height));
Console.Write(AsciiCharacter);//The Text is printed Always
}
Console.SetCursorPosition(width / 2, height / 2);
//Console.Write(TextInput);
y[x] = inScreenYPosition(y[x] + 1, height);
}
}
}
public static int inScreenYPosition(int yPosition, int height)
{
if (yPosition < 0)//When there is negative value
return yPosition + height;
else if (yPosition < height)//Normal
return yPosition;
else// When y goes out of screen when autoincremented by 1
return 0;
}
private static void Initialize(out int width, out int height, out int[] y)
{
height = Console.WindowHeight;
width = Console.WindowWidth - 1;
y = new int[width];
Console.Clear();
for (int x = 0; x < width; ++x)//Setting the cursor at random at program startup
{
y[x] = rand.Next(height);
}
}
}
}

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

FeedForwardProgram Neural Network Demo

public class NeuralNetwork
{
public delegate void PrintEventHandler(object message);
public event PrintEventHandler Cout;
private int numInput;
private int numHidden;
private int numOutput;
private double[] inputs;
private double[][] ihWeights; // input-to-hidden
private double[] ihBiases;
private double[][] hoWeights; // hidden-to-output
private double[] hoBiases;
private double[] outputs;
public void SelfDemo()
{
try
{
Console.WriteLine("\nBegin neural network feed-forward demo\n");
Console.WriteLine("Creating a 3-input, 4-hidden, 2-output neural network");
Console.WriteLine("Using log-sigmoid function for input-to-hidden and hidden-to-output activation");
const int numInput = 3;
const int numHidden = 4;
const int numOutput = 2;
NeuralNetwork nn = new NeuralNetwork(numInput, numHidden, numOutput);
nn.Cout += message => Console.Write("{0}", message);
const int numWeights = (numInput * numHidden) + (numHidden * numOutput) + numHidden + numOutput; // (3*4)+(4*2)+4+2 = 26
double[] weights = new double[numWeights] {
0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2,
-2.0, -6.0, -1.0, -7.0,
1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0,
-2.5, -5.0 };
Console.WriteLine("\nWeights and biases are:");
nn.ShowVector(weights, 2);
Console.WriteLine("Loading neural network weights and biases");
nn.SetWeights(weights);
Console.WriteLine("\nSetting neural network inputs:");
double[] xValues = new double[] { 2.0, 3.0, 4.0 };
nn.ShowVector(xValues, 2);
Console.WriteLine("Loading inputs and computing outputs\n");
double[] yValues = nn.ComputeOutputs(xValues);
Console.WriteLine("\nNeural network outputs are:");
nn.ShowVector(yValues, 4);
Console.WriteLine("\nEnd neural network demo\n");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
Console.ReadLine();
}
public void Write(string format, object[] args)
{
string message = string.Format(format, args);
if (this.Cout != null)
{
this.Cout(message);
}
}
public void Write(string message)
{
if (this.Cout != null)
{
this.Cout(message);
}
}
public NeuralNetwork(int numInput, int numHidden, int numOutput)
{
this.numInput = numInput;
this.numHidden = numHidden;
this.numOutput = numOutput;
inputs = new double[numInput];
ihWeights = MakeMatrix(numInput, numHidden);
ihBiases = new double[numHidden];
hoWeights = MakeMatrix(numHidden, numOutput);
hoBiases = new double[numOutput];
outputs = new double[numOutput]; // aka hoOutputs
}
/*public int numWeights()
{
int numWeights = (numInput * numHidden) + (numHidden * numOutput) + numHidden + numOutput; // (3*4)+(4*2)+4+2 = 26
return numWeights;
}*/
private static double[][] MakeMatrix(int rows, int cols)
{
double[][] result = new double[rows][];
for (int i = 0; i < rows; ++i)
result[i] = new double[cols];
return result;
}
public void SetWeights(double[] weights)
{
// order: ihWeights (row-col order), ihBiases, hoWeights, hoBiases
int numWeights = (numInput * numHidden) + (numHidden * numOutput) + numHidden + numOutput;
if (weights.Length != numWeights)
throw new Exception("The weights array length: " + weights.Length + " does not match the total number of weights and biases: " + numWeights);
int k = 0; // points into weights param
for (int i = 0; i < numInput; ++i)
for (int j = 0; j < numHidden; ++j)
ihWeights[i][j] = weights[k++];
for (int i = 0; i < numHidden; ++i)
ihBiases[i] = weights[k++];
for (int i = 0; i < numHidden; ++i)
for (int j = 0; j < numOutput; ++j)
hoWeights[i][j] = weights[k++];
for (int i = 0; i < numOutput; ++i)
hoBiases[i] = weights[k++];
}
public void ShowMatrix(double[][] matrix, int numRows)
{
Write("\n");
int ct = 0;
if (numRows == -1) numRows = int.MaxValue; // if numRows == -1, show all rows
for (int i = 0; i < matrix.Length && ct < numRows; ++i)
{
for (int j = 0; j < matrix[0].Length; ++j)
{
if (matrix[i][j] >= 0.0) Write(" "); // blank space instead of '+' sign
Write(matrix[i][j].ToString("F2") + " ");
}
Write("\n");
++ct;
}
Write("\n");
}
public void ShowVector(double[] vector, int decimals)
{
Write("\n");
for (int i = 0; i < vector.Length; ++i)
{
if (i > 0 && i % 12 == 0) // max of 12 values per row
Write("\n");
if (vector[i] >= 0.0) Console.Write(" ");
Write(vector[i].ToString("F" + decimals) + " "); // 2 decimals
}
Console.WriteLine("\n");
}
public double[] ComputeOutputs(double[] xValues)
{
if (xValues.Length != numInput)
throw new Exception("Inputs array length " + inputs.Length + " does not match NN numInput value " + numInput);
double[] ihSums = new double[this.numHidden]; // these scratch arrays could be class members
double[] ihOutputs = new double[this.numHidden];
double[] hoSums = new double[this.numOutput];
for (int i = 0; i < xValues.Length; ++i) // copy x-values to inputs
this.inputs[i] = xValues[i];
//Console.WriteLine("Inputs:");
//FeedForwardProgram.ShowVector(this.inputs, 2);
Write("input-to-hidden weights:");
ShowMatrix(this.ihWeights, -1);
for (int j = 0; j < numHidden; ++j) // compute input-to-hidden weighted sums
for (int i = 0; i < numInput; ++i)
ihSums[j] += this.inputs[i] * ihWeights[i][j];
Write("input-to-hidden sums before adding i-h biases:");
ShowVector(ihSums, 2);
Write("input-to-hidden biases:");
ShowVector(this.ihBiases, 2);
for (int i = 0; i < numHidden; ++i) // add biases to input-to-hidden sums
ihSums[i] += ihBiases[i];
Write("input-to-hidden sums after adding i-h biases:");
ShowVector(ihSums, 2);
for (int i = 0; i < numHidden; ++i) // determine input-to-hidden output
ihOutputs[i] = LogSigmoid(ihSums[i]);
Write("input-to-hidden outputs after log-sigmoid activation:");
ShowVector(ihOutputs, 2);
Console.WriteLine("hidden-to-output weights:");
ShowMatrix(hoWeights, -1);
for (int j = 0; j < numOutput; ++j) // compute hidden-to-output weighted sums
for (int i = 0; i < numHidden; ++i)
hoSums[j] += ihOutputs[i] * hoWeights[i][j];
Write("hidden-to-output sums before adding h-o biases:");
ShowVector(hoSums, 2);
Write("hidden-to-output biases:");
ShowVector(this.hoBiases, 2);
for (int i = 0; i < numOutput; ++i) // add biases to input-to-hidden sums
hoSums[i] += hoBiases[i];
Write("hidden-to-output sums after adding h-o biases:");
ShowVector(hoSums, 2);
for (int i = 0; i < numOutput; ++i) // determine hidden-to-output result
this.outputs[i] = LogSigmoid(hoSums[i]);
double[] result = new double[numOutput]; // copy hidden-to-output to this.outputs
this.outputs.CopyTo(result, 0);
return result;
} // ComputeOutputs
private static double LogSigmoid(double z)
{
if (z < -20.0) return 0.0;
else if (z > 20.0) return 1.0;
else return 1.0 / (1.0 + Math.Exp(-z));
}
//extend
private static int CalculateWeight(int inputNodeCount, int hiddenNodeCount, int outputNodeCount)
{
int numWeights = (inputNodeCount * hiddenNodeCount) + (hiddenNodeCount * outputNodeCount) + hiddenNodeCount + outputNodeCount; //count the total weights
return numWeights;
}
} // class