Contents tagged with C#
Accessing C# Variables in JavaScript
Introduction
So often I come across this question on various forums that 'How to access the variables/properties from C# in Javascript?'. And this is one of the scenarios which you are (most) likely to come across if you are writing an ASP.Net application.
For most beginners, it might get confusing as they start wondering how to pass on information from a server side variable to client side.
Solution
The one shortcut we used to used during the (good old) ASP days, and which still works in ASP.NET is to declare a public property in codebehind. Let us say we declare a string variable firstName in codebehind.
public string firstName = "Manas"; public string lastName = "Bhardwaj";
Now, we can access this in aspx page/javascript like this:
<script> var myName; function GetMyName() { myName = <%=this.firstName%> + ' ' + <%=this.lastName%>; alert(myName); } </script>To do it nicely, you can use RegisterClientScriptBlock. RegisterClientScriptBlock accepts the following parameters:
Type: The type of the client script to register.
key: The key of the client script to register.
script: The client script literal to register.
addScriptTags: A Boolean value indicating whether to add script tags.string script = string.Format("var myName = '{0} {1}';", firstName, lastName); if (!ClientScript.IsClientScriptBlockRegistered("myScript")) { ClientScript.RegisterClientScriptBlock(typeof(_Default), "myScript", script, true); }Once done, the variable 'myName' is available at the client side (javascript in aspx page) and can be accessed like:
<script> function GetMyName() { alert(myName); } </script>How to Toggle String Case in .NET
Well, this one comes from after a discussion from one of threads on CodeProject. The following snippet shows how to toggle string casing in .NET:
public string ToggleCase(string input) { string result = string.Empty; char[] inputArray = input.ToCharArray(); foreach (char c in inputArray) { if (char.IsLower(c)) result += Char.ToUpper(c); else result += Char.ToLower(c); } return result; }Dynamically adding Style Sheet Reference in ASP.Net
In ASP.Net, many times there are scenarios when you want to add a style sheet (CSS) reference to your page from the code behind. Usually, we can do a line (example below) in the page and we are done.
<LINK REL='StyleSheet' HREF='manas.css' TYPE='text/css'>
To do something like this from codebehind, you can use the snippet below.
public void AddHeaderStyleSheetReference(Page PageObject, string StyleSheetURL) { if (PobjPage.Header != null) { HtmlGenericControl StyleSheet = new HtmlGenericControl("Link"); LobjStyleSheet.Attributes.Add("Rel", "StyleSheet"); LobjStyleSheet.Attributes.Add("Type", "text/css"); LobjStyleSheet.Attributes.Add("HRef", PageObject.ResolveClientUrl(StyleSheetURL)); PageObject.Header.Controls.Add(StyleSheet); } }A similar approach can be made to add the javascript file references to you page.
public void AddHeaderScriptReference(Page PageObject, string ScriptURL) { if (PageObject.Header != null) { HtmlGenericControl IncludeScript = new HtmlGenericControl("Script"); LobjIncludeScript.Attributes.Add("Type", "JavaScript"); LobjIncludeScript.Attributes.Add("CharSet", "UTF8"); LobjIncludeScript.Attributes.Add("Src", PageObject.ResolveClientUrl(ScriptURL)); PageObject.Header.Controls.Add(IncludeScript); } }Access Active Directory - The .NET Way
Introduction
Accessing Active Director (AD) is one of the most basic scenarios for an intranet application. For a new developer though, sometimes it becomes clumsy to get this. But believe me, it is just as simple as hitting a full toss (shows how much I love cricket).
Using the Code
The following code shows how to do it with C#. Remember to include System.DirectoryServices. Here you go:
public static Hashtable SearchLDAP(string userID) { DirectoryEntry entry = new DirectoryEntry("LDAP://DC=Domain,DC=com"); DirectorySearcher mySearcher = new DirectorySearcher(entry); mySearcher.Filter = "(&(objectClass=user)(anr="+ userID +"))"; mySearcher.PropertiesToLoad.Add("givenname"); mySearcher.PropertiesToLoad.Add("sn"); mySearcher.PropertiesToLoad.Add("mail"); mySearcher.PropertiesToLoad.Add("description"); mySearcher.PropertiesToLoad.Add("l"); Hashtable associateDetailsTable = new Hashtable(); ResultPropertyValueCollection resultCollection; SearchResult searchResult = mySearcher.FindOne(); associateDetailsTable.Add("AssociateID", userID); if(searchResult != null) { resultCollection = searchResult.Properties["givenname"]; foreach(object result in resultCollection) { associateDetailsTable.Add("FirstName", result.ToString()); } resultCollection = searchResult.Properties["sn"]; foreach(object result in resultCollection) { associateDetailsTable.Add("LastName", result.ToString()); } resultCollection = searchResult.Properties["mail"]; foreach(object result in resultCollection) { associateDetailsTable.Add("Mail", result.ToString()); } resultCollection = searchResult.Properties["description"]; foreach(object result in resultCollection) { associateDetailsTable.Add("Designation", result.ToString()); } resultCollection = searchResult.Properties["l"]; foreach(object result in resultCollection) { associateDetailsTable.Add("Location", result.ToString()); } } return associateDetailsTable; }Create Multiple Sink Files with Log4net
Introduction
MyLogger library enables you to log the level of errors/events in distinct files. To use MyLogger in your project, add the reference into your project. You will also need to add a reference to Log4net, as MyLogger is nothing but a simple wrapper round Log4net. To start the Logger, place the following code in the start of your application:
Logger.loggerFileName = "LogFile"; Logger.StartLoggingThread();
Once the method StartLoggingThread is called, it starts the logger thread. Here in MyLogger, I have included two levels of logging, i.e. Error and Trace, although it can be increased to the same number as provided by Log4net. To log an error, write:
try { int i = 10; int j = 0; int k = i / j; } catch (Exception ex) { Logger.LogMessage("An Error Occurred : " + ex.Message, Logger.LOG_ERROR); }
The Logger.LOG_ERROR property lets the MyLogger class know that it is an error and needs to be logged in the error file. Similarly, if you want to trace something, use Logger.LOG_TRACE. For example:
Logger.LogMessage("Reading from File", Logger.LOG_TRACE);
Remember to ShutDown the logger when you are closing the application. You can write this code in the Application Exit event for your application:
Logger.ShutDownLogger();
Details
The above section explains how to use MyLogger in your application. Now I'll explain how MyLogger has been designed and how you can enhance it for further use.
MyLogger runs on a separate thread, thus enabling the application to respond in a comparatively faster fashion and not wait while Log4net logs in the event. This thread becomes active when an event occurs which is notified by the ManualResetEvent.
Currently, there are only two appenders created while MyLogger starts up, but you can modify and add more appenders as per your need. The Logger.LOG_ERROR property lets the MyLogger class know that it is an error and needs to be logged in the error file. The public property loggerFileName is used to set the output filename. Download source