Thursday, December 31, 2009
Good article about running totals and need to store previous row values
Here is the link of it. Read it
http://www.sqlservercentral.com/articles/T-SQL/68467/
Friday, July 24, 2009
Few things about WCF
The DataContract attribute is applied at the class level and it controls the serialized name of the object as well as the namespace.
The DataMember attribute is applied to the specific properties you want to be included. It allows you to specify the serialized name of the property, the order in which it appears within the object as well as whether or not it is a required attribute
DataMember attribute works independently of the regular scope of the field or property. For instance, a private or internal property could be marked with the attribute and thus made available via a WCF service, even though it was inaccessible from elsewhere within the object hierarchy or client code.
XML serialization and data contract serailization
http://www.danrigsby.com/blog/index.php/2008/03/07/xmlserializer-vs-datacontractserializer-serialization-in-wcf/
XmlSerializer
Advantages:
1. Opt-out rather than opt-in properties to serialize. This mean you don’t have to specify each and every property to serialize, only those you don’t wan to serialize2. Full control over how a property is serialized including it it should be a node or an attribute
3. Supports more of the XSD standard
Disadvantages:
1. Can only serialize properties
2. Properties must be public
3. Properties must have a get and a set which can result in some awkward design
4. Supports a narrower set of types
5. Cannot understand the DataContractAttribute and will not serialize it unless there is a SerializableAttribute too
DataContractSerializer
Advantages:
1. Opt-in rather than opt-out properties to serialize. This mean you specify what you want serialize
2. Because it is opt in you can serialize not only properties, but also fields. You can even serialize non-public members such as private or protected members. And you dont need a set on a property either (however without a setter you can serialize, but not deserialize)
3. Is about 10% faster than XmlSerializer to serialize the data because since you don’t have full control over how it is serialize, there is a lot that can be done to optimize the serialization/deserialization process.
4. Can understand the SerializableAttribute and know that it needs to be serialized
5. More options and control over KnownTypes
Disadvantages:
1. No control over how the object is serialized outside of setting the name and the order
Tuesday, May 19, 2009
Whats new in Caching mechanism in VS2010
I read a great post reagrading caching mechanism in VS2010 today.
Here is brief synopsis if you want to know more please follow this linkhttp://www.asp.net/learn/whitepapers/aspnet40/
In traditional way cached content will be stored in memory, which hampers performance of heavily trafficked servers
In ASP.Net 4.0 WE can configure output cache providers. Out put cache providers use any storage mechanism to persist HTML content,ie we can store in local memory, remote disks, cloud storage and distributed cache engines
In order to create custom output cache provider as we have to derive System.Web.Caching.OutputCacheProvider and also we need to configure in web.config file
By default in ASP.NET 4.0 all HTTP responses, rendered pages and controls use in-memory output cache, we can select output cache providers per control and per request.
If we are customizing output cache provider in the page levelwe need to specifiy provier name attribute in OutputCache directive at page directives
If we are customizing out put cache provider per request. we need override GetOutputCacheProviderName in Gloabl.asaxfile
We can cache the top10 pages of a site in memory, while caching pages that get lower traffic on disk
Thursday, April 09, 2009
Factory Design pattern - Asp.net
It is useful when all related classes are grouped and we can decide which class needs to be instantiated at run time.
The Factory Design pattern is used when a class cannot anticipate the type of object it must create or when you want to delegate the responsibility of creations of object to another class so that you need not worry about the complexity involved in creation of the object. This reduces the code redundancy in the application.
Simple examples
1) int intValue = Convert.ToUInt16 (true);
This method internally checks parameter data type. It then converts this Boolean value into the integer value “1” and returns it.
2) SqlCommand
Classic examples of .NET are enumerators, such as
CommandType.StoredProcedure,
CommandType.TableDirect
CommandType.Text.
SqlCommand cmdobj = newSqlCommand (StoredProcedureName, Connection String);
cmdobj.CommandType =CommandType.StoredProcedure;
SqlCommand cmdobj = new SqlCommand (TableName, ConnectionString);
cmdobj.CommandType = CommandType.TableDirect;
SqlCommand cmdobj = new SqlCommand (SelectText, ConnectionString);
cmdobj.CommandType = CommandType.Text;
3) Custom Example
Every application uses logging to log messages for debugging, analyzing or auditing. There can be various types of logging like logging to text file, logging to event logger or to SQL server, etc. The application should not have the knowledge of which logger it is using and hence it should be abstracted from the creation of the logger component. For this to happen, the responsibility of creating the logger component is given to a special class knows as the LoggerFactory. This class knows how to create different kind of loggers, what are the parameters to be set for each type of logger, etc. Now the application need not know about the logger creation, it will ask the Factory to create a corresponding logger (which is configured) and start using it.
4) HTTP handlers
ASP.NET provides the capability of routing http requests to an object of the class that implements the IHttpHandlerFactory interface. Here, ASP.NET utilizes the Factory design pattern. This pattern provides an interface for creating families of related objects without specifying their concrete classes. In simple terms, you can consider such a class as a factory that creates http handler objects depending on the parameters passed to it. We don't have to specify a particular http handler class to instantiate; http handler factory takes care of it. The benefit of this is if in the future the implementation of the object that implements the IHttpHandler interface changes, the consuming client is not affected as long as the interface remains the same.
Thursday, March 19, 2009
tool tip div and pop up div using java script
java script for popup div
Binding java script with control in .cs page
protected void gvReceivedMessages_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
CheckBox chkAll = (CheckBox)e.Row.FindControl("chkSelectAll");
chkAll.Attributes.Add("onclick", "javascript:SelectAll('" + chkAll.ClientID + "','" + gvReceivedMessages.ClientID + "')");
strChekAll = chkAll.ClientID;
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
//string s=e.Row.Cells[
//step1: find preview control (hyperlink)
CheckBox chkSelect = (CheckBox)e.Row.FindControl("chkSelect");
chkSelect.Attributes.Add("onclick", "fnCheck('" + chkSelect.ClientID + "', '" + strChekAll + "')");
HyperLink hylnkMessage = (HyperLink)e.Row.FindControl("hylnkMessage");
hylnkMessage.Attributes.Add("onclick", "javascript:showDiv(event)");
//hylnkMessage.Attributes.Add("onMouseout","javascript:popclose()");
//onMouseover="ddrivetip('JavaScriptKit.com JavaScript tutorials','yellow', 300)";
//onMouseout="hideddrivetip()"
hylnkMessage.Attributes.Add("onMouseover","javascript:ddrivetip('this is testing')");
hylnkMessage.Attributes.Add("onMouseout", "javascript:hideddrivetip()");
//chkReply.Attributes.Add("onclick","javascript:Reply(this,)"
}
}
}
Linq- dataset - select - many columns
Here is my code
cn.Open();
SqlCommand cmd = new SqlCommand("Spname", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("ParameterName", value);
cmd.Parameters.AddWithValue("parametername", value);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
grddataset.DataSource = from t in ds.DataRecordSet()// we need to extend dataset as it does not implement ienumerable
select new {DataSetEmail = ds.Tables[0].Rows[0][4].ToString(), DataSetFirstName = ds.Tables[0].Rows[0][2].ToString(), LastName = ds.Tables[0].Rows[0][3].ToString() };
grddataset.DataBind();
cn.Close();
da.Dispose();
Implementation of Ienumerable for data set
public static class DataSetExtension
{
public static IEnumerable
Linq - Data reader - selecting more than one value
I used following code.
public void ShowAthletes()
{
cn.Open();
SqlCommand cmd = new SqlCommand("SpName", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("SubscriptionId", Parameter1);
cmd.Parameters.AddWithValue("EMail", "parametername");
SqlDataReader dr=cmd.ExecuteReader();
---------Linq part of query starts-----------------------------
grd.DataSource = from t in dr.DataRecord()// note data reader does implement IEnumberable Sowe need to extend it
where t[4].ToString() == "XXXXXX" // some specific email id
orderby t[2].ToString()
select new {Email = t[4].ToString(), FirstName = t[2].ToString() };
----------------Linq part query ends here--------------------------
grd.DataBind();
dr.Close();
cn.Close();
cmd.Dispose();
}
To implement Ienumerable for data reader
public static class DataReaderExtension
{
public static IEnumerable
Wednesday, November 19, 2008
Further on String type discussion
http://msdn.microsoft.com/en-us/library/aa691153.aspx
The string type is a sealed class type that inherits directly from object. Instances of the string class represent Unicode character strings.
Values of the string type can be written as string literals (Section 2.4.4).
The keyword string is simply an alias for the predefined class System.String.
String vs string
Sources i refered are
http://msdn.microsoft.com/en-us/library/system.string.aspxhttp://stackoverflow.com/questions/215255/string-vs-string-in-chttp://en.csharp-online.net/CSharp_String_Theory%E2%80%94string_versus_String
http://peterkellner.net/2007/12/29/incsharpwhentousestringversesstring/http://www.htmlforums.com/archive/index.php/t-53425.html
Use "String" to refer specifically to the String class.
Use "string" when referring to an object of the String class.
from msdn i found following points for String class
A string is a sequential collection of Unicode characters that is used to represent text. A String object is a sequential collection of System..::.Char objects that represent a string. The value of the String object is the content of the sequential collection, and that value is immutable.
A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification. If it is necessary to modify the actual contents of a string-like object, use the System.Text..::.StringBuilder class.
Each Unicode character in a string is defined by a Unicode scalar value, also called a Unicode code point or the ordinal (numeric) value of the Unicode character. Each code point is encoded using UTF-16 encoding, and the numeric value of each element of the encoding is represented by a Char object.
A single Char object usually represents a single code point; that is, the numeric value of the Char equals the code point. However, a code point might require more than one encoded element. For example, a Unicode supplementary code point (a surrogate pair) is encoded with two Char objects.
Indexes
An index is the position of a Char object, not a Unicode character, in a String. An index is a zero-based, nonnegative number starting from the first position in the string, which is index position zero. Consecutive index values might not correspond to consecutive Unicode characters because a Unicode character might be encoded as more than one Char object. To work with each Unicode character instead of each Char object, use the System.Globalization..::.StringInfo class.
Ordinal vs. Culture-Sensitive Operations
Members of the String class perform either an ordinal or linguistic operation on a String object. An ordinal operation acts on the numeric value of each Char object. A linguistic operation acts on the value of the String taking into account culture-specific casing, sorting, formatting, and parsing rules. Linguistic operations execute in the context of an explicitly declared culture or the implicit current culture. For more information about the current culture, see the CultureInfo..::.CurrentCulture topic.
Casing rules determine how to change a Unicode character between one case and another; for example, from lowercase to uppercase.
Formatting rules determine how to convert a value to its string representation, while parsing rules determine how to convert a string representation to a value.
Sort rules determine the alphabetic order of Unicode characters and how two strings compare to each other. For example, the Compare method performs a linguistic comparison while the CompareOrdinal method performs an ordinal comparison. Consequently, if the current culture is U.S. English, the Compare method considers 'a' less than 'A' while the CompareOrdinal method considers 'a' greater than 'A'.
The .NET Framework supports word, string, and ordinal sort rules. A word sort performs a culture-sensitive comparison of strings in which certain nonalphanumeric Unicode characters might have special weights assigned to them. For example, the hyphen ("-") might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list. A string sort is similar to a word sort, except that there are no special cases and all nonalphanumeric symbols come before all alphanumeric Unicode characters.
A culture-sensitive comparison is any comparison that explicitly or implicitly uses a CultureInfo object, including the invariant culture that is specified by the CultureInfo..::.InvariantCulture property. The current implicit culture is specified by the Thread..::.CurrentCulture property.
An ordinal sort compares strings based on the numeric value of each Char object in the string. An ordinal comparison is automatically case-sensitive because the lowercase and uppercase versions of a character have different code points. However, if case is not important in your application, you can specify an ordinal comparison that ignores case. This is equivalent to converting the string to uppercase using the invariant culture and then performing an ordinal comparison on the result.
For more information about word, string, and ordinal sort rules, see the System.Globalization..::.CompareOptions topic.
A culture-sensitive comparison is typically appropriate for sorting, whereas an ordinal comparison is not. An ordinal comparison is typically appropriate for determining whether two strings are equal (that is, for determining identity), whereas a culture-sensitive comparison is not.
The Remarks for comparison and search methods specify whether the method is case-sensitive and/or culture-sensitive. By definition, any string, including the empty string (""), compares as greater than a null reference, and two null references compare as equal to each other.
Normalization
Some Unicode characters have multiple equivalent binary representations consisting of sets of combining and/or composite Unicode characters. The Unicode standard defines a process called normalization that returns one binary representation when given any of the equivalent binary representations of a character. Normalization can be performed with several algorithms, called normalization forms, that obey different rules. The .NET Framework currently supports normalization forms C, D, KC, and KD. A pair of normalized strings is typically evaluated with an ordinal comparison.
Security Considerations
If your application makes a security decision about a symbolic identifier such as a file name or named pipe, or persisted data such as the text-based data in an XML file, the operation should use an ordinal comparison instead of a culture-sensitive comparison. This is because a culture-sensitive comparison can yield different results depending on the culture in effect, whereas an ordinal comparison depends solely on the binary value of the compared characters.
Functionality
The String class provides members to compare String objects, return the index of a character or string within a String object, copy the value of a String object, partition a string or combine strings, modify the value of string, format numbers, dates and times, or enumeration values into a string, and normalize a string.
Use the Compare, CompareOrdinal, CompareTo, Equals, EndsWith, and StartsWith methods for comparisons.
Use the IndexOf, IndexOfAny, LastIndexOf, and LastIndexOfAny methods to obtain the index of a substring or Unicode character in a string.
Use Copy and CopyTo to copy a string or substring to another string or an array of type Char.
Use the Substring and Split methods to create one or more new strings from portions of an original string, and the Concat and Join methods to create a new string from one or more substrings.
Use Insert, Replace, Remove, PadLeft, PadRight, Trim, TrimEnd, and TrimStart to modify all or part of a string.
Use the ToLower, ToLowerInvariant, ToUpper, and ToUpperInvariant methods to change the case of Unicode characters in a string.
Use Format to replace one or more format item placeholders in a string with the text representation of one or more numeric, date and time, or enumeration values.
Use the Length property to obtain the number of Char objects in a string, and the Chars property to access the actual Char objects in a string.
Use the IsNormalized method to test whether a string is normalized to a particular normalization form. Use the Normalize method to create a string that is normalized to a particular normalization form.
Strings and Embedded Nulls
In the .NET Framework, a String object can include embedded nulls, which count as a part of the string's length. However, in some languages, such as C and C++, a null character indicates the end of a string, is not considered a part of the string, and is not counted as part of the string's length. This means that the following common assumptions that C and C++ programmers or that libraries written in C or C++ might make about strings are not necessarily valid when applied to String objects:
The value returned by the strlen or wcslen functions does not necessarily equal String..::.Length.
The string created by the strcpy_s or wcscpy_s functions is not necessarily identical to the string created by the String..::.Copy method.
You should ensure that native C and C++ code that instantiates String objects, and code that is passed String objects through platform invoke, do not assume that an embedded null marks the end of the string.
Implemented Interfaces
The String class implements the IComparable, ICloneable, IConvertible, IEnumerable, and IComparable<(Of <(T>)>) interfaces. Use the Convert class for conversions instead of this type's explicit interface member implementation of IConvertible
Friday, August 15, 2008
Date time vs small datetime in sql server 2005
DATETIME column (or in a variable) are stored as two four-byte
integers. The first integer represents the date, and the second
integer represents the time.
We calculate the date integer against the base date January 1,
1900. The integer represents the number of days before or after
that date. As a result, the DATETIME data type supports only
dates that are represented by the integers supported by the
four-byte range. This means that a date in a DATETIME column must
fall within the range of January 1, 1753, through December 31,
9999.
The second integer in a DATETIME value, the time integer, stores
the number of 1/300-second units after midnight. This means that
the time is stored in milliseconds and is accurate to 3.33
milliseconds. Consequently, when you insert a value into a
DATETIME column, SQL Server rounds the time to .000, .003 or .007
seconds.
Small DateTimeA SMALLDATETIME value is stored as two two-byte integers. The
first integer represents the date, and the second integer
represents the time.
As with the DATETIME data type, the SMALLDATETIME date integer is
calculated against the base date January 1, 1900. However, the
integer represents only the number of days after the base date,
not the number before the date. This means that a date in a
SMALLDATETIME column must fall within the range of January 1,
1900, through June 6, 2079.
The second integer in a SMALLDATETIME value -- the time integer
-- stores the number of minutes after midnight. The time does not
reflect the number of seconds, and if seconds are included in the
value, they are rounded as follows:
Values of 29.998 seconds or less are rounded down to the nearest
minute. Values of 29.999 seconds or more are rounded up to the nearest
minute.
