Friday, 26 March 2010

Enum.ToString() Method

Syntax : Enum.ToString(format)

Converts the value of this instance to its equivalent string representation using the specified format.

The format parameter can contain format characters "G" or "g", "D" or "d", "X" or "x", and "F" or "f". If format is a null reference (Nothing in Visual Basic) or an empty string (""), the general format specifier ("G") is used.

Notes to Callers:If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return. For example, the following enumeration defines two members, Shade.Gray and Shade.Grey, that have the same underlying value.

enum Shade
{
White = 0, Gray = 1, Grey = 1, Black = 2
}

The following method call attempts to retrieve the name of a member of the Shade enumeration whose underlying value is 1. The method can return either "Gray" or "Grey", and your code should not make any assumptions about which string will be returned.

string shadeName = ((Shade) 1).ToString("F");

Enumeration Format Strings

You can use the Enum.ToString() method to create a new string object that represents the numeric, hexadecimal, or string value of an enumeration member. This method takes one of the enumeration formatting strings to specify the value that you want returned.

G or g
Enum.ToString("G") : Displays the enumeration entry as a string value, if possible, and otherwise displays the integer value of the current instance.

F or f
Enum.ToString("F") : Displays the enumeration entry as a string value, if possible.

D or d : Displays the enumeration entry as an integer value in the shortest representation possible.

public enum Color {Red = 1, Blue = 2, Green = 3}

Color myColor = Color.Green;

Console.WriteLine("The value of myColor is {0}.", myColor.ToString("G"));
Console.WriteLine("The value of myColor is {0}.", myColor.ToString("F"));
Console.WriteLine("The value of myColor is {0}.", myColor.ToString("D"));
Console.WriteLine("The value of myColor is 0x{0}.", myColor.ToString("X"));
// The example displays the following output to the console:
// The value of myColor is Green.
// The value of myColor is Green.
// The value of myColor is 3.
// The value of myColor is 0x00000003.

Thursday, 25 March 2010

Random.Next() Method

Random.Next(int minValue, int maxValue), return value is a psuedo-random number greater than or equal to minValue and less than maxValue. If minValue and maxValue are equal, this value is returned.

Thread Safety

Random's instance methods are not thread-safe. That's why the class (and almost every class in the .Net framework) says, "Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe." Some people just don't know how to read documentation.

Warning: Random.Next() NOT thread safe; results in constant 0

Warning: Random.Next() NOT thread safe; results in constant value equal to the minimum specified value (Next(int)) or 0 if uing the parameterless overload (Next()). Calling Random.Next() from multiple threads will eventually result in a corrupted class and a constant random number of minvalue.

Instantiating random numbers with the default constructor can result in identical random number sequences, as the feed is based on the current datatime. This can lead to unexpected results.

A suggested procedure is:

static class RandomFactory
{

private static Random globalRandom = new Random();


public static Random Create() {

lock (globalRandom) {

Random newRandom = new Random(globalRandom.Next());

return newRandom;

}

}

Instantiate your random object through RandomFactory.Create(). This will always lead to unique randomizers within each procedure and minimizes the number of lockin required.

Tuesday, 23 March 2010

.NET Reflector

click here to downlaod free RedGate .NET Rfelector


.NET Reflector is a free software utility for Microsoft .NET combining class browsing, static analysis and decompilation, originally written by Lutz Roeder. MSDN Magazine named it as one of the Ten Must-Have utilities for developers, Scott Hanselman listed it as part of his "Big Ten Life and Work-Changing Utilities".

.NET Reflector was the first .NET assembly browser. It can be used to inspect, navigate, search, analyze, and browse the contents of a .NET component such as an assembly and translates the binary information to a human-readable form. By default Reflector allows decompilation of .NET assemblies into C#, Visual Basic .NET and Common Intermediate Language. Reflector also includes a "Call Tree", that can be used to drill down into IL methods to see what other methods they call. It will show the metadata, resources and XML documentation. .NET Reflector can be used by .NET developers to understand the inner workings of code libraries, to show the differences between two versions of the same assembly, and how the various parts of a .NET application interact with each other. There are a large number of addins for Reflector.

.NET Reflector can be used to track down performance problems and bugs, browse classes, and maintain or help become familiar with code bases. It can also be used to find assembly dependencies, and even windows DLL dependencies, by using the Analyzer option. There is a call tree and inheritance-browser. It will pick up the same documentation or comments that are stored in xml files alongside their associated assemblies that are used to drive IntelliSense inside Visual Studio. It is even possible to cross-navigate related documentation (xmldoc), searching for specific types, members and references. It can be used to effectively convert source code between C# and VB.

.NET Reflector has been designed to host add-ins to extend its functionality, many of which are open source. Some of these add-ins provide other languages that can be disassembled to, such as PowerShell, Delphi and MC++. Others analyze assemblies in different ways, providing quality metrics, sequence diagrams, class diagrams, dependency structure matrices or dependency graphs. It is possible to use add-ins to search text, save disassembled code to disk, export an assembly to XMI/UML, compare different versions, or to search code. Other add-ins allow debugging processes. Some add-ins are designed to facilitate testing by creating stubs and wrappers.

On 20 August 2008, Red Gate Software announced they were taking responsibility for future development of the software.A new version, V6, introduced in February 2010, comes with .NET 4 support and a free addin to Visual Studio, and is the result of a great deal of work with the community of .NET Reflector users in beta-test.

Conditional Comments

One of the most common operations performed in a Web page is to detect the browser type and version. Browser detection is performed to ensure that the content presented to the browser is compatible and renders correctly. The browser type can be detected using many different techniques. Most methods of browser detection make use of script on the server or client.

This article introduces conditional comments, which offer certain advantages over scripted browser detection techniques. Conditional comments make it easy for developers to take advantage of the enhanced features offered by Microsoft Internet Explorer 5 and later versions, while writing pages that downgrade gracefully in less-capable browsers or display correctly in browsers other than Windows Internet Explorer. Conditional comments are the preferred means of differentiating Cascading Style Sheets (CSS) rules intended for specific versions of Internet Explorer.

Conditional comments only work in Explorer on Windows, and are thus excellently suited to give special instructions meant only for Explorer on Windows. They are supported from Explorer 5 onwards, and it is even possible to distinguish between 5.0, 5.5 and 6.0.

Benefits of Using Conditional Comments

Conditional comments have certain advantages over scripting methods of browser detection.

* Low client-side impact.

When a downlevel browser encounters a downlevel-hidden conditional comment, the browser skips over the HTML inside the comment, and the content elements are not parsed, downloaded, or rendered. This saves client machine resources.

* No script required.

Conditional comments do not require scripting and DHTML, and when no scripting is used in a Web page, no scripting engine needs to be loaded. Conditional comments are processed during the downloading and parsing phase, so only the content that is targeted for the browser is actually downloaded. Conditional comments can be combined freely with other browser detection techniques.

* Separate code from detection logic.

Using conditional comments, script logic can be separated into smaller and simpler segments of code, which are easier to maintain and understand. Plus, code segments are loaded only by the browser version for which they were intended.

* Cross-browser.

Conditional comments have been around since Internet Explorer 5, but their use is not restricted to Internet Explorer alone. Conditional comments can be used to customize content delivered to browsers that support conditional comments and those that do not.

Syntax of Conditional Comments

The basic syntax of each type of comment is shown in the following table. The first comment shown is the basic HTML Comment, which is included for the purpose of comparison and to illustrate the different syntax used by each type of conditional comment.
Comment type Syntax or possible value

standard HTML comment
downlevel-hidden
downlevel-revealed HTML

The HTML shown inside the syntax block in each of the conditional comments denotes any block of HTML content, including script. Both types of conditional comment use a conditional expression to indicate whether the content inside the comment block should be parsed or ignored.

downlevel browser : Any browser except Internet Explorer 5 and later versions. For the purposes of this article, downlevel refers specifically to any browser or browser version that does not support conditional comments.

uplevel browser : Internet Explorer 5 and later versions, which support conditional comments.

downlevel-hidden : A conditional comment block that is ignored by downlevel browsers. Internet Explorer 5 and later versions render the HTML content if the expression evaluates to true.
downlevel-revealed : A conditional comment block that is parsed by downlevel browsers. Internet Explorer 5 and later versions also render the HTML content if the expression evaluates to true.

Downlevel-hidden Conditional Comments

The following sample shows a downlevel-hidden conditional comment, which contains a short paragraph of text.

<!--[if IE 8]>
<p>Welcome to Internet Explorer 8. </p>
<![endif]-->


The downlevel-hidden conditional comment contains hyphens ("--") in the opening and closing tag, similar to the basic HTML Comment. The condition appears in the opening portion of the tag, and [endif] is placed prior to the closing portion of the tag. The content is placed inside the comment tags.

Because the first four characters and the last three characters of the comment are identical to a basic HTML Comment element, downlevel browsers ignore the HTML content inside the comment block. Since content is effectively hidden from browsers that do not support conditional comments, this type of conditional comment is called downlevel-hidden.

If the result of the conditional expression is true, the content inside the comment block is parsed and rendered by Internet Explorer 5 and later versions. This behavior makes the downlevel-hidden conditional comment particularly useful for content that has been specifically designed for Internet Explorer.

The following sample illustrates how a client-side script block can be placed inside a conditional comment; in this case, a message is displayed in Internet Explorer 5 and later.

<!--[if gte IE 7]>
<SCRIPT LANGUAGE="Javascript">

alert("Congratulations! You are running Internet Explorer 7 or greater.");

</SCRIPT>

<P>Thank you for closing the message box.<P>

<![endif]-->

Click here for more.

Conditional CSS

<!--[if gte IE 5.5]>
<![if lt IE 7]>
<style type="text/css">

H1 {font-family:verdana}

</style>
<![endif]>
<![endif]-->

Target all versions of IE

<!--[if IE]>
<link rel="stylesheet" type="text/css" href="ie-only.css" />
<![endif]-->

Target ALL non-IE browsers

<! [if !IE]>
<link rel="stylesheet" type="text/css" href="non-ie.css" />
<![endif] >

Friday, 19 March 2010

Downloading Large Files: Issues and Tricks

The ASP.NET framework includes the WriteFile and TransmitFile methods for serving up large chunks of data. As Dino explains, they're an improvement over plain old OutputStream, but you'll still need to address to the problems of tracking and resuming large file downloads on your own.

To serve users a server file, you don't need rocket science. A relatively simple piece of code would do the job. You use the OutputStream property of the HttpResponse object to write the bytes you want to send to the client. The following code snippet shows how to save an in-memory graphic document.

Bitmap bmp = new Bitmap(...); context.Response.ContentType = "image/jpeg"; bmp.Save(context.Response.OutputStream, ImageFormat.Jpeg);

Using the OutputStream object directly may be annoying at times. For this reason, the HttpResponse object features a few helper methods. One of these methods is BinaryWrite. As you can see, its implementation is quite straightforward:

public void BinaryWrite(byte[] buffer) { this.OutputStream.Write(buffer, 0, buffer.Length); }

The method accepts an array of bytes and just writes it out to the stream. What if you want to download an entire file? In theory, you must open the file, read its contents in separate blocks of data and write each block out to the stream. The ASP.NET framework, though, provides us with two specific methods for writing potentially large chunks of data down to the output stream. They are WriteFile and TransmitFile.

The WriteFile method does exactly what you should do yourself to send a file down to the client. It uses an internal file stream to access the content, reads the content in a single shot, and then writes it out to the output stream. In addition, the WriteFile method exposes a simple programming interface where all that you have to do is indicating the name of the file to download. To be precise, WriteFile has a number of overloads and may accept additional parameters, but this doesn't change the basic fact: the method writes out a server file.

Both WriteFile and BinaryWrite methods seem perfect for streaming data down to the client. However, both can put the Web server memory under pressure if called to work on very large files. Why? It's because both methods load the entire data block (the contents of the file or the byte array) into the Web server's memory. For large files, this can cause severe problems that can culminate in the recycling of the ASP.NET process. The TransmitFile method is designed to elegantly work around the problem. It sends output directly from a file to the ASP.NET ISAPI extension and then down to the client, without passing a humongous string to the ISAPI extension.

The TransmitFile method was introduced years ago through a hot-fix package for ASP.NET 1.x as documented in Microsoft KnowledgeBase article KB823409 and later incorporated in the .NET Framework 1.x SP1 and newer versions of ASP.NET. In summary, TransmitFile is the most stable and reliable of the other methods, although you won't notice any significant difference for most files.

Although TransmitFile makes large file downloads more stable than ever and defeats the problem of recycling, it is far from being a full solution to the problem of tracking and resuming large file downloads. For example, if a download fails, for whatever reason, TransmitFile can only start it again from the beginning. In the end, the perfect solution is creating your own file downloader that transmits the file piecemeal, thus avoiding unwanted pressure on the memory and giving the developer the chance of recovering from errors and latency.

Source : http://www.drdobbs.com/windows/202804466

Thursday, 18 March 2010

Setting margin using jQuery

$("#samplediv").css("marginTop", 100) sets margin-tp of DIV samplediv to 100px

Different ways of binding data to a drop down list

Different ways to bind data to a drop down list

* Binding to a Simple Array
* Binding to an Enum
* Binding to an ArrayList
* Binding to a hashtable
* Binding to a data table
* Binding to a data set
* Binding to a data view
* Binding to a set of objects
* Binding manually

Binding to a Simple Array

Dim months() As String = {"January", "February", "March", "April", "May", "June", "July"}
Me.DropDownList1.DataSource = months
Me.DropDownList1.DataBind()

Here both the “text” and “value” of the selected item of the “dropdownlist” would be same.

Binding to an Enum

public enum Color
{
RED,
GREEN,
BLUE
}

To bind "Color" to dropdownlist ddlColor

ddlColor.DataSource = Enum.GetNames(typeof(Color));
ddlColor.DataBind();

and to get the selected value

Color selectedColor = (Color)Enum.Parse(ddlColor.SelectedValue);

Binding to an ArrayList

ArrayList has lot of flexibilities that a simple array does not have. For example, we can remove, clear or do any manipulations within the “ArrayList”.

Dim ar As New ArrayList
ar.Add("January")
ar.Add("February")
ar.Add("March")

Me.DropDownList1.DataSource = ar
Me.DropDownList1.DataBind()

The “text” and “value” of any selected item within the “dropdownlist” would still be the same.

Binding to a hashtable

Hashtable is very similar to an “ArrayList.” but it stores information as key-value pair.

Dim months As New Hashtable
ht.Add("1001", "Jan")
ht.Add("1002", "Feb")

Me.DropDownList1.DataSource = months
Me.DropDownList1.DataTextField = "value"
Me.DropDownList1.DataValueField = "key"
Me.DropDownList1.DataBind()

Binding to a DataTable or DataSet or DataView

Me.DropDownList1.DataSource = DataTable / DataSet.Tables(index) / DataView
Me.DropDownList1.DataTextField = "ProductName"
Me.DropDownList1.DataValueField = "ProductID"
Me.DropDownList1.DataBind()

Binding to a set of objects

If you have your own structure (defined in the form of “class” or “structure”), you can still use them to create several objects and together bind to the “dropdownlist.”

At this moment, I just created a simple class (CStudent) which can hold a “regdno” and “sname”. I also defined two read/write properties to “set-get” the property values. Let us go through the class first.

Public Class Student

Private _regdno As String
Private _sname As String

Public Sub New(ByVal r As String, ByVal n As String)
RegNo = r
SName = n
End Sub
Public Property RegNo() As String
Get
Return _regdno
End Get
Set(ByVal Value As String)
_regdno = Value
End Set
End Property

Public Property SName() As String
Get
Return _sname
End Get
Set(ByVal Value As String)
_sname = Value
End Set
End Property

End Class

Once you create the above class, we need to declare objects (along with values) to work with those classes. Make sure that a “class” is simply a specification (or user-defined data type). It does not allocate any memory to hold the values (unless you create the objects). The following code creates a few objects based on the class “CStudent” and binds it to the “dropdownlist.”


Me.DropDownList1.Items.Clear()

Dim items As New ArrayList

items.Add(New Student("1001", "test1"))
items.Add(New Student("1002", "test2"))
items.Add(New Student("1003", "test3"))

Me.DropDownList1.DataSource = items
Me.DropDownList1.DataTextField = "SName"
Me.DropDownList1.DataValueField = "RegNo"
Me.DropDownList1.DataBind()


“ArrayList” can hold any type of object.

Binding Manually

We can manually add different types of items to the “dropdownlist.”

Dim li As ListItem
li = New ListItem
li.Text = "first"
li.Value = 1
Me.DropDownList1.Items.Add(li)

li = New ListItem("second")
Me.DropDownList1.Items.Add(li)

li = New ListItem("third", "3")
Me.DropDownList1.Items.Add(li)

For i As Integer = 4 To 10
Me.DropDownList1.Items.Add(New ListItem("item" & i, i))
Next

Fiddler - Web Debugging Tool

Fiddler is a Web Debugging Proxy which logs all HTTP(S) traffic between your computer and the Internet. Fiddler allows you to inspect all HTTP(S) traffic, set breakpoints, and "fiddle" with incoming or outgoing data. Fiddler includes a powerful event-based scripting subsystem, and can be extended using any .NET language.

Fiddler is freeware and can debug traffic from virtually any application, including Internet Explorer, Mozilla Firefox, Opera, and thousands more.

Dowload Fiddler from here http://www.fiddler2.com/fiddler2/

Wednesday, 17 March 2010

What does the term sticky session mean in a web-farm scenario?

Sticky session refers to the feature of many commercial load balancing solutions for web-farms to route the requests for a particular session to the same physical machine that serviced the first request for that session. This is mainly used to ensure that a in-proc session is not lost as a result of requests for a session being routed to different servers. Since requests for a user are always routed to the same machine that first served the request for that session, sticky sessions can cause uneven load distribution across servers.

Source : http://dev.fyicenter.com/Interview-Questions/JavaScript/What_does_the_term_sticky_session_mean_in_a_web_.html

What is the downside to sticky sessions with load balancers?

There are two main downsides:

1. Your load isn't evenly distributed. Sticky sessions will stick, hence the name. While initial requests will be distributed evenly, you might end up with a significant number of users spending more time than others. If all of these are initially set to a single server, that server will have much more load. Typically, this isn't really going to have a huge impact, and can be mitigated by having more servers in your cluster.

2. Proxies conglomerate users into single IP's, all of which would get sent to a single server. While that typically does no harm, again other than increasing individual server loads, proxies can also operate in a cluster. A request into your F5 from such a system would not necessarily be sent back to the same server if the request comes out of a different proxy server in their proxy cluster.

Source : http://serverfault.com/questions/46307/what-is-the-downside-to-sticky-sessions-with-load-balancers

Load balancer persistence (sticky sessions)

The Question:
If I have a load balancer in front of three servers (call them A, B, and C) and a client connects to a web service on server B using a WCF http binding that has a session (e.g., wsHttpBinding with sessions enabled), am I guaranteed that I will always communicate with server B until I close the client's proxy?

The Answer:
The answer to my question was "yes" if sticky sessions are enabled (Thanks to Pablo Cibraro MVP).

I discovered that a sticky session is one of several kinds of load balancer persistence and that you will have to check your load balancer's manual to determine what it supports. For example, here is a list of persistent types supported by the F5 load balancer:

* Cookie persistence - uses an HTTP cookie stored on a client’s computer to allow the client to reconnect to the same server previously visited at a web site.
* Destination address affinity persistence - Also known as sticky persistence, destination address affinity persistence supports TCP and UDP protocols, and directs session requests to the same server based solely on the destination IP address of a packet.
* Hash persistence - Hash persistence allows you to create a persistence hash based on an existing iRule.
* Microsoft Remote Desktop Protocol persistence - persistence tracks sessions between clients and servers running the Microsoft Remote Desktop Protocol (RDP) service.
* SIP persistence - is a type of persistence used for servers that receive Session Initiation Protocol (SIP) messages sent through UDP. SIP is a protocol that enables real-time messaging, voice, data, and video.
* Source address affinity persistence - Also known as simple persistence, source address affinity persistence supports TCP and UDP protocols, and directs session requests to the same server based solely on the source IP address of a packet.
* SSL persistence - is a type of persistence that tracks non-terminated SSL sessions, using the SSL session ID. Even when the client’s IP address changes, the LTM system still recognizes the connection as being persistent based on the session ID. Note that the term non-terminated SSL sessions refers to sessions in which the LTM system does not perform the tasks of SSL certificate authentication and encryption/re-encryption.
* Universal persistence - allows you to write an expression that defines what to persist on in a packet. The expression, written using the same TM expression syntax that you use in iRules, defines some sequence of bytes to use as a session identifier.

Other issues to keep in mind:

* Load balancer session timeout value.

Source : http://daveonsoftware.blogspot.com/2007/08/load-balancer-persistence-sticky.html

Tuesday, 16 March 2010

Select / Dropdownlist jQuery

1. Get the value of the selected item

$("#dropdownlist").val()

2. Get the text of the selected item

You would think this would be easy as well, but it isn’t. You cannot just use the text() method on the combobox. That will give you the text values of all of the options in a single string. Not what you want. The trick is to use the :selected query modifier on the option.

$("#dropdownlist option:selected").text()

3. Find out when the select value changed

$("#dropdownlist").change(function() { /* do something here */ });

4. Programmatically set the selected item.

$("#dropdownlist").val(2);

5. Modify the list.

Modifying a select element is not fundamentally different than modifying any other element in the DOM, but there are a few basics here to keep in mind. Mainly: try to avoid using the DOM directly. Create html strings instead.

Clear the list: $(“#dropdownlist”).html(“”);

Add to the list: $(“”).appendTo(“#dropdownlist”);

Using Windows Hosts File

The hosts file is a computer file used in an operating system to map hostnames to IP addresses. This method is one of several system facilities to address network nodes on a computer network. On some operating systems, the host file content is used preferentially over other methods, such as the Domain Name System (DNS), but many systems implement name service switches to provide customization. Unlike DNS, the hosts file is under the control of the local computer's administrator.

Location
“hosts” file is stored in the \Windows\ folder for 9X/Me systems and in \Windows\system32\drivers\etc\ for Windows 2000/XP.

Format of Hosts File
The “hosts” file is a plain text file named just that, hosts.Note that there is no extension on the file name.

Make particular note of the so-called “loopback” entry:
127.0.0.1 localhost
This entry is a not an actual Internet IP address but defines a local address and can be used to direct the computer to send a packet to itself. This function is used in ad blocking and is discussed below.

If a hosts file exists, it is automatically searched during any process using the Windows TCP/IP stack.

Creating a Hosts File
Generally, the entries in the hosts file have to be created one way or the other. The IP address corresponding to an URL has to be looked up and entered. While those familiar with the PING function can do this themselves, the task would rapidly become too tedious for more than a few sites. Also, many sites regard PING as a nuisance and block it. Fortunately, others have created hosts files that can be downloaded. Several references are given in the sidebar.

Speeding Up Browsing
Many of the so-called Web accelerators that are available as freeware or as part of commercial packages make use of the hosts file. The idea is that if you can resolve IP addresses on your own computer instead of waiting for a DNS server to do it, you can cut the time required to find a Web site. If you have a slow connection or if the servers are very busy, you might shave a second or two off the connection time of your most used sites. Or on the rare occasion when DNS servers are down, you might even be able to continue to use the Web.

Blocking Adware
Perhaps the biggest use of the hosts file is to block sites that are regarded as undesirable or to block ads. This done by assigning the loopback IP 127.0.0.1 to an URL that you wish blocked. Thus an entry might be: “127.0.0.1 www.unwanted.com” (without quotes). Any request for such an IP address just gets sent right back to your own computer.

Useful Run and DOS commands

Run commad to view services
services.msc

To view system information
msinfo32

To view Remote Desktop Client
mstsc

For IIS
inetmgr - To view IIS Management Console
iisreset - To restart (stop and start) IIS
iisreset /start - to start IIS
iisreset /stop - to stop IIS

To view command prompt
cmd

To start Event Viewer
eventvwr

To view control panel
control.exe / control

Keyboard Properties
control keyboard

Mouse properties
control mouse

Internet Explorer
iexplore

More available here
http://mypchell.com/guides/34-guides/69-156-useful-run-commands

DOS command for viewing system information
systeminfo

Test / send information to another network computer or network device.
ping

More available here

http://www.computerhope.com/overview.htm
http://www.easydos.com/dosindex.html

focus on an input field using jQuery

To focus on a login input box with id 'login' on page startup, try:

$("#login").focus();

To following script can be used to trigger some action on focus of each input field in the form.

$("input").focus(function () {
$(this).next("span").css('display','inline').fadeOut(1000);
});

jQuery string length

How can I get the length of text entered in a textbox using jQuery?

$("#myTextbox").val().length; will give the length of text in myTextbox.

Monday, 15 March 2010

Creating an array of objects in C#

Creating an array of objects, rather than an array of simple data types such as integers, is a two-part process. First you declare the array, and then you must create the objects that are stored in the array. This example creates a class that defines an audio CD. It then creates an array that stores 20 audio CDs.

namespace CDCollection
{
// Define a CD type.
class CD
{
private string album;
private string artist;
private int rating;

public string Album
{
get {return album;}
set {album = value;}
}
public string Artist
{
get {return artist;}
set {artist = value;}
}
public int Rating
{
get {return rating;}
set {rating = value;}
}
}

class Program
{
static void Main(string[] args)
{
// Create the array to store the CDs.
CD[] cdLibrary = new CD[20];

// Populate the CD library with CD objects.
for (int i=0; i<20; i++)
{
cdLibrary[i] = new CD();
}

// Assign details to the first album.
cdLibrary[0].Album = "Must See";
cdLibrary[0].Artist = "Anonymous";
cdLibrary[0].Rating = 5;
}
}
}

Collections

An array is just one of many options for storing sets of data by using C#. The option that you select depends on several factors, such as how you intend to manipulate or access the items. For example, a list is generally faster than an array if you must insert items at the beginning or in the middle of the collection. Other types of collection classes include map, tree, and stack; each one has its own advantages. For more information, see System.Collections, and System.Collections.Generic.

The following example shows how to use the List<(Of <(T>)>) class. Notice that unlike the Array class, items can be inserted into the middle of the list. This example restricts the items in the list so that they must be strings.


public class TestCollections
{
public static void TestList()
{
System.Collections.Generic.List sandwich = new System.Collections.Generic.List();

sandwich.Add("A");
sandwich.Add("B");

sandwich.Insert(1, "C");

foreach (string ingredient in sandwich)
{
System.Console.WriteLine(ingredient);
}
}
}
// Output:
// A
// B
// C


How to Bind Enum Types to a dropdown list or any other bindable Control in ASP.NET?

public enum Color
{
RED,
GREEN,
BLUE
}

Every Enum type derives from System.Enum. There are two static methods that help bind data to a drop-down list control (and retrieve the value). These are Enum.GetNames and Enum.Parse. Using GetNames, you are able to bind to your drop-down list control as follows:

protected System.Web.UI.WebControls.DropDownList ddColor;

private void Page_Load(object sender, System.EventArgs e)
{
if(!IsPostBack)
{
ddColor.DataSource = Enum.GetNames(typeof(Color));
ddColor.DataBind();
}
}

Now if you want the Enum value Back on Selection ...

private void ddColor_SelectedIndexChanged(object sender, System.EventArgs e)
{
Color selectedColor = (Color)Enum.Parse(ddColor.SelectedValue);
}

Friday, 12 March 2010

Accessing checkbox state using jQuery

Use the attr() function in jQuery to get the state of a checkbox

Example:
$("#checkboxid").attr("checked")

returns true or false

Also
$("#checkboxid").attr("checked", true)

sets the state of the checkbox to selected

Initializing Multi-dimensional array in Javascript

Initializing 2-D array in Javascript

// Arrays within arrays:

var x = new Array(new Array(1,2,3),new Array('A','B','C'),new Array('x','y','z'));

alert(x[1][2]); // returns 'C'

Thursday, 11 March 2010

jQuery fadeIn/fadeOut IE cleartype glitch

When fading a html node with the .fadeIn() and .fadeOut() functions in jQuery, IE drops the windows Cleartype rendering; which results in very ugly text. This problem appears to be very common, but no one has a nice solution for the problem.

The most common way to solve this problem is by removing the filter CSS attribute. In normal javascript, it would look like this:

document.getElementById('node').style.removeAttribute('filter');

and in jQuery, it would look like this:

$('#node').fadeOut('slow', function() {
this.style.removeAttribute('filter');
});

This means that every single time we want to fade an element, we need to remove the filter attribute, which makes our code look messy.

Google AdWords Conversion Tracking(PPC Tracking) : How it works?

How it works?

Once you've defined an action, Google gives you a JavaScript snippet to paste on the pages you wish to track. This code builds a URL that passes parameters back to Google and also allows you to display the Google Site Stats text on your page if you opted in to show it on your conversion pages. The query string data within the JavaScript code snippet is used in the following way:

* google_conversion_id: A unique value that allows Google to identify the advertiser receiving the conversion.
* google_conversion_value: A numeric value defined by the advertiser equaling the value of the conversion.
* google_conversion_label: The type of conversion that occurred (purchase, sign-up, page view, or lead). Google does not currently support advertiser-defined conversion types. Consequently, you cannot customize this string.
* google_conversion_language: The language of the conversion tracking Google Site Stats text that appears on your website.

If you can see the code generated for your action, you can learn how to paste it into the pages you're tracking by reading our AdWords Conversion Tracking Setup Guide. Proper installation of the code on to your site activates conversion tracking. Here's how it should behave once it starts working:

1. A user clicks your AdWords ad.
2. Our googleadservices.com server places a temporary cookie on the user's computer or mobile device.
3. If the user reaches one of your designated conversion confirmation request pages, his or her computer or mobile device passes back the cookie and requests that our server send the conversion tracking text. If cookies are rejected for any reason, the conversions made from that user won't get recorded. Conversion tracking is also not supported if the mobile phone user disables images.
4. Google records the conversion event and correlates it with your campaign, ad group, URL and keyword.
5. At the next report update, you will see conversion statistics from the campaign level down to the keyword level.

How does Google use cookies in conversion tracking?

The cookie that Google adds to a user's computer when he/she clicks on an ad expires in 30 days. This measure, and the fact that Google uses separate servers for conversion tracking and search results, protects the user's privacy.

Users who don't wish to participate in tracking activities can easily not accept this cookie by setting their Internet browser user preferences. These users will simply not be included in your conversion tracking statistics.

After having activated Analytics within my AdWords account, my ads are linking to an Error page.

When Analytics is activated within AdWords, "Destination URL auto-tagging" is automatically turned on. This feature allows Analytics to track information about clicks on your AdWords ads by tagging your AdWords keyword Destination URLs with a "gclid=" parameter. This parameter is displayed in your landing page URL. For example, http://www.example.co.uk/?gclid=12345abcd

A small number of websites do not allow URL parameters and serve an error 404 page. If your site does not allow parameters, you can prevent this error from occurring by either turning "Auto-tagging" off in your account (see steps below) or asking your webmaster to allow URL parameters. You can also turn auto-tagging off if you do not want the "gclid=" parameter to appear in your URLs.

TURN AUTO-TAGGING OFF
1. Log in to your AdWords account
2. Navigate to My Account-->User Preferences
3. On this page under the Analytics section, click "Edit"
4. Turn Destination URL auto-tagging: "off"
5. Save changes