Wednesday, December 19, 2007

ASP.net Performance, Tips & Tricks Thread

1. http://samples.gotdotnet.com/quickstart/aspplus/doc/perftuning.aspx

2. http://www.realsoftwaredevelopment.com/2007/08/20-tips-to-impr.html

3. http://msdn2.microsoft.com/en-us/library/ms973839.aspx

4. http://msdn.microsoft.com/msdnmag/issues/05/01/ASPNETPerformance/

5. http://msdn.microsoft.com/msdnmag/issues/05/01/ASPNETPerformance/

6.. http://www.sql-server-performance.com/tips/asp_net_performance_p1.aspx ( SQL )


7. http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx

TIPS & TRICKS

ASP.NET 2.0 is an awesome framework for developing Web applications. If you've worked with it for awhile then that's no secret. It offers some great new features that you can implement with a minimal amount of code. I wanted to start a list of some of the most simple (yet cool) things you could do with it that required little or no C#/VB.NET code. If you have other suggestions add a comment and I'll update the list if the suggestion is a simple task that can be applied easily.

1. Maintain the position of the scrollbar on postbacks: In ASP.NET 1.1 it was a pain to maintain the position of the scrollbar when doing a postback operation. This was especially true when you had a grid on the page and went to edit a specific row. Instead of staying on the desired row, the page would reload and you'd be placed back at the top and have to scroll down. In ASP.NET 2.0 you can simply add the MaintainScrollPostionOnPostBack attribute to the Page directive:
@ Page Language="C#" MaintainScrollPositionOnPostback="true" AutoEventWireup="true" CodeFile="..." Inherits="..."

2. Set the default focus to a control when the page loads: This is another extremely simple thing that can be done without resorting to writing JavaScript. If you only have a single textbox (or two) on a page why should the user have to click in the textbox to start typing? Shouldn't the cursor already be blinking in the textbox so they can type away? Using the DefaultFocus property of the HtmlForm control you can easily do this.
form id="frm" DefaultFocus="txtUserName" runat="server"
...
form

3. Set the default button that is triggered when the user hits the enter key: This was a major pain point in ASP.NET 1.1 and required some JavaScript to be written to ensure that when the user hit the enter key that the appropriate button on the form triggered a "click" event on the server-side. Fortunately, you can now use the HtmlForm control's DefaultButton property to set which button should be clicked when the user hits enter. This property is also available on the Panel control in cases where different buttons should be triggered as a user moves into different Panels on a page.
form id="frm" DefaultButton="btnSubmit" runat="server"
...
form

4. Locate nested controls easily: Finding controls within a Page's control hierarchy can be painful but if you know how the controls are nested you can use the lesser known "$" shortcut to find controls without having to write recursive code. If you're looking for a great way to recursively find a control (in cases where you don't know the exact control nesting) check out my good buddy Michael Palermo's blog entry. The following example shows how to use the DefaultFocus property to set the focus on a textbox that is nested inside of a FormView control. Notice that the "$" is used to delimit the nesting:
form id="form1" runat="server" DefaultFocus="formVw$txtName"
div
asp:FormView ID="formVw" runat="server"
ItemTemplate
Name:
asp:TextBox ID="txtName" runat="server"
Text='<%# Eval("FirstName") + " " + Eval("LastName") %>'
ItemTemplate
asp:FormView
div
form

This little trick can also be used on the server-side when calling FindControl(). I blogged about this awhile back if you'd like more details. Here's an example:

TextBox tb = this.FindControl("form1$formVw$txtName") as TextBox;
if (tb != null)
{
//Access TextBox control
}

5. Strongly-typed access to cross-page postback controls: This one is a little more involved than the others, but quite useful. ASP.NET 2.0 introduced the concept of cross-page postbacks where one page could postback information to a page other than itself. This is done by setting the PostBackUrl property of a button to the name of the page that the button should postback data to. Normally, the posted data can be accessed by doing something like PreviousPage.FindControl("ControlID"). However, this requires a cast if you need to access properties of the target control in the previous page (which you normally need to do). If you add a public property into the code-behind page that initiates the postback operation, you can access the property in a strongly-typed manner by adding the PreviousPageType directive into the target page of the postback. That may sound a little confusing if you haven't done it so let me explain a little more.

If you have a page called Default.aspx that exposes a public property that returns a Textbox that is defined in the page, the page that data is posted to (lets call it SearchResults.aspx) can access that property in a strongly-typed manner (no FindControl() call is necessary) by adding the PreviousPageType directive into the top of the page:

@ PreviousPageType VirtualPath="Default.aspx"

By adding this directive, the code in SearchResults.aspx can access the TextBox defined in Default.aspx in a strongly-typed manner. The following example assumes the property defined in Default.aspx is named SearchTextBox.
TextBox tb = PreviousPage.SearchTextBox;

This code obviously only works if the previous page is Default.aspx. PreviousPageType also has a TypeName property as well where you could define a base type that one or more pages derive from to make this technique work with multiple pages. You can learn more about PreviousPageType here.

6. Strongly-typed access to Master Pages controls: The PreviousPageType directive isn't the only one that provides strongly-typed access to controls. If you have public properties defined in a Master Page that you'd like to access in a strongly-typed manner you can add the MasterType directive into a page as shown next (note that the MasterType directive also allows a TypeName to be defined as with the PreviousPageType directive):

@ MasterType VirtualPath="MasterPage.master"

You can then access properties in the target master page from a content page by writing code like the following:
this.Master.HeaderText = "Label updated using MasterType directive with VirtualPath attribute.";

You can find several other tips and tricks related to working with master pages including sharing master pages across IIS virtual directories at a previous blog post I wrote.

7. Validation groups: You may have a page that has multiple controls and multiple buttons. When one of the buttons is clicked you want specific validator controls to be evaluated rather than all of the validators defined on the page. With ASP.NET 1.1 there wasn't a great way to handle this without resorting to some hack code. ASP.NET 2.0 adds a ValidationGroup property to all validator controls and buttons (Button, LinkButton, etc.) that easily solves the problem. If you have a TextBox at the top of a page that has a RequiredFieldValidator next to it and a Button control, you can fire that one validator when the button is clicked by setting the ValidationGroup property on the button and on the RequiredFieldValidator to the same value. Any other validators not in the defined ValidationGroup will be ignored when the button is clicked. Here's an example:

form id="form1" runat="server"

Search Text: asp:TextBox ID="txtSearch" runat="server"

asp:RequiredFieldValidator ID="valSearch" runat="Server"
ControlToValidate="txtSearch" ValidationGroup="SearchGroup"

asp:Button ID="btnSearch" runat="server" Text="Search"
ValidationGroup="SearchGroup"
....
Other controls with validators and buttons defined here
/form

8. Finding control/variable names while typing code: This tip is a bit more related to VS.NET than to ASP.NET directly, but it's definitely helpful for those of you who remember the first few characters of control variable name (or any variable for that matter) but can't remember the complete name. It also gives me the chance to mention two great downloads from Microsoft. First the tip though. After typing the first few characters of a control/variable name, hit CTRL + SPACEBAR and VS.NET will bring up a short list of matching items. Definitely a lot easier than searching for the control/variable definition. Thanks to Darryl for the tip. For those who are interested, Microsoft made all of the VS.NET keyboard shortcuts available in a nice downloadable and printable guide. Get the C# version here and the VB.NET version here.

That's all for now. There are a lot of other things that could be mentioned and I'll try to keep this post updated. Have a great (simple) ASP.NET 2.0 tip or trick? Post the details in the comments and I'll add it if the content is appropriate for the list. Make sure to list your name so I can give proper credit.

For those who are interested, you can also view videos I've put together that show how to accomplish different tasks from working with AJAX, to ASP.NET to Web Services and WCF at the following URL:

http://weblogs.asp.net/dwahlin/archive/tags/Video/default.aspx

Wednesday, December 12, 2007

Tuesday, December 11, 2007

Widows / XP & OS thread

XP tips

http://www.prbcorp.com/workshop/ws/full/Windows_XP_Tips/

100 Windows Command


Accessibility Controls
access.cpl

Add Hardware Wizard
hdwwiz.cpl

Add/Remove Programs
appwiz.cpl

Administrative Tools
control admintools

Automatic Updates
wuaucpl.cpl

Bluetooth Transfer Wizard
fsquirt

Calculator
calc

Certificate Manager
certmgr.msc

Character Map
charmap

Check Disk Utility
chkdsk

Clipboard Viewer
clipbrd

Command Prompt
cmd

Component Services
dcomcnfg

Computer Management
compmgmt.msc

Date and Time Properties
timedate.cpl

DDE Shares
ddeshare

Device Manager
devmgmt.msc

Direct X Control Panel (If Installed)*
directx.cpl

Direct X Troubleshooter
dxdiag

Disk Cleanup Utility
cleanmgr

Disk Defragment
dfrg.msc

Disk Management
diskmgmt.msc

Disk Partition Manager
diskpart

Display Properties
control desktop

Display Properties
desk.cpl

Display Properties (w/Appearance Tab Preselected)
control color

Dr. Watson System Troubleshooting Utility
drwtsn32

Driver Verifier Utility
verifier

Event Viewer
eventvwr.msc

File Signature Verification Tool
sigverif

Findfast
findfast.cpl

Folders Properties
control folders

Fonts
control fonts

Fonts Folder
fonts

Free Cell Card Game
freecell

Game Controllers
joy.cpl

Group Policy Editor (XP Prof)
gpedit.msc

Hearts Card Game
mshearts

Iexpress Wizard
iexpress

Indexing Service
ciadv.msc

Internet Properties
inetcpl.cpl


IP Configuration (Display Connection Configuration)
ipconfig /all

IP Configuration (Display DNS Cache Contents)
ipconfig /displaydns

IP Configuration (Delete DNS Cache Contents)
ipconfig /flushdns

IP Configuration (Release All Connections)
ipconfig /release

IP Configuration (Renew All Connections)
ipconfig /renew

IP Configuration (Refreshes DHCP & Re-Registers DNS)
ipconfig /registerdns

IP Configuration (Display DHCP Class ID)
ipconfig /showclassid

IP Configuration (Modifies DHCP Class ID)
ipconfig /setclassid


ava Control Panel (If Installed)
jpicpl32.cpl

Java Control Panel (If Installed)
javaws

Keyboard Properties
control keyboard

Local Security Settings
secpol.msc

Local Users and Groups
lusrmgr.msc

Logs You Out Of Windows
logoff

Mcft Chat
winchat

Minesweeper Game
winmine

Mouse Properties
control mouse

Mouse Properties
main.cpl

Network Connections
control netconnections

Network Connections
ncpa.cpl

Network Setup Wizard
netsetup.cpl

Notepad
notepad

Nview Desktop Manager (If Installed)
nvtuicpl.cpl

Object Packager
packager

ODBC Data Source Administrator
odbccp32.cpl

On Screen Keyboard
osk

Opens AC3 Filter (If Installed)
ac3filter.cpl

Password Properties
password.cpl

Performance Monitor
perfmon.msc

Performance Monitor
perfmon

Phone and Modem Options
telephon.cpl

Power Configuration
powercfg.cpl

Printers and Faxes
control printers

Printers Folder
printers

Private Character Editor
eudcedit

Quicktime (If Installed)
QuickTime.cpl

Regional Settings
intl.cpl

Registry Editor
regedit

Registry Editor
regedit32

Remote Desktop
mstsc

Removable Storage
ntmsmgr.msc

Removable Storage Operator Requests
ntmsoprq.msc

Resultant Set of Policy (XP Prof)
rsop.msc

Scanners and Cameras
sticpl.cpl

Scheduled Tasks
control schedtasks

Security Center
wscui.cpl

Services
services.msc

Shared Folders
fsmgmt.msc

Shuts Down Windows
shutdown

Sounds and Audio
mmsys.cpl

Spider Solitare Card Game
spider

SQL Client Configuration
cliconfg

System Configuration Editor
sysedit

System Configuration Utility
msconfig

System File Checker Utility (Scan Immediately)
sfc /scannow

System File Checker Utility (Scan Once At Next Boot)
sfc /scanonce

System File Checker Utility (Scan On Every Boot)
sfc /scanboot

System File Checker Utility (Return to Default Setting)
sfc /revert

System File Checker Utility (Purge File Cache)
sfc /purgecache

System File Checker Utility (Set Cache Size to size x)
sfc /cachesize=x

System Properties
sysdm.cpl

Task Manager
taskmgr

Telnet Client
telnet

User Account Management
nusrmgr.cpl

Utility Manager
utilman

Windows Firewall
firewall.cpl

Windows Magnifier
magnify

Windows Management Infrastructure
wmimgmt.msc

Windows System Security Tool
syskey

Windows Update Launches
wupdmgr

Windows XP Tour Wizard
tourstart

Tuesday, December 4, 2007

.Net architecture & core concepts


.Net Framework basics

When we speak about .Net, we mean by .NET framework. .NET Framework is made up of the Common Language Runtime (CLR), the Base Class Library (System Classes). This allows us to build our own services (Web Services or Windows Services) and Web Applications (Web forms Or Asp .Net), and Windows applications (Windows forms). We can see how this is all put together.?


Above Picture shows overall picture, demonstrating how the .NET languages follows rules provided by the Common Language Specifications (CLS). These languages can all be used?Independently to build application and can all be used with built-in data describers (XML) and data assessors (ADO .NET and SQL). Every component of the .NET Framework can take advantage of the large pre- built library of classes called the Framework Class Library (FCL). Once everything is put together, the code that is created is executed in the Common Language Runtime. Common Language Runtime is designed to allow any .NET-compliant language to execute its code. At the time of writing, these languages included VB .Net, C# and C++ .NET, but any language can become .NET- compliant, if they follow CLS rules. The following sections will address each of the parts of the architecture.

.Net Common Language Specifications (CLS):

In an object-oriented environment, everything is considered as an object. (This point is explained in this article and the more advanced features are explained in other articles.) You create a template for an object (this is called the class file), and this class file is used to create multiple objects.
TIP: Consider a Rectangle. You may want to create many Rectangle in your lifetime; but each Rectangle will have certain characteristics and certain functions. For example, each rectangle will have a specific width and color. So now, suppose your friend also wants to create a Rectangle. Why reinvent the Rectangle? You can create a common template and share it with others. They create the Rectangle based on your template. This is the heart of object-oriented programming?the template is the class file, and the Rectangle is the objects built from that class. Once you have created an object, your object needs to communicate with many other Objects.

Even if it is created in another .NET language doesn?t matter, because each language follows the rules of the CLS. The CLS defines the necessary things as common variable types (this is called the Common Type System CTS ), common visibility like when and where can one see these variables, common method specifications, and so on. It doesn?t have one rule which tells how C# composes its objects and another rule tells how VB .Net does the same thing . To steal a phrase, there is now ?One rule to bind them all.? One thing to note here is that the CLS simply provides the bare rules. Languages can adhere to their own specification. In this case, the actual compilers do not need to be as powerful as those that support the full CLS.
The Common Language Runtime (CLR):

The heart of .net Framework is Common Language Runtime (CLR). All .NET-compliant languages run in a common, managed runtime execution environment. With the CLR, you can rely on code that is accessed from different languages. This is a huge benefit. One coder can write one module in C#, and another can access and use it from VB .Net. Automatic object management, the .NET languages take care of memory issues automatically. These are the few listed?benefits which you get from CLR.
Microsoft Intermediate Language (MSIL):

So how can many different languages be brought together and executed together??Microsoft Intermediate Language (MSIL) or, as it?s more commonly known, Intermediate Language (IL). In its simplest terms, IL is a programming language.?If you wanted to, you could write IL directly, compile it, and run it. But why would want to write such low level code? Microsoft has provided with higher-level languages, such as C#, that one can use. Before the code is executed, the MSIL must be converted into platform-specific code. The CLR includes something called a JIT compiler in which the compiler order is as follows.

Source Code => Compiler => Assembley =>Class Loader =>Jit Compiler =>Manged Native Code=>Execution.

The above is the order of compilation and execution of programs. Once a program is written in a .Net compliant language, the rest all is the responsibility of the frame work.

--------------------------------------------------

ASSEMBLIES

Assemblies are basically the compiled code in .Net which contains the code in Microsoft Intermediate Langauge and one more thing that assembiles do for us as compared to dlls is they can maintain versioning with the help of the manifest.
You dont need to register the assemblies after compiling like we needed in dlls. you can put the assemblies in the bin folder and refer the namespaces from there.
In short find the assembly description as :
Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.

Differences Between Shared and Private Assemblies and how to use them.

Shared and Private Assembly: A private assembly is a assembly that is available to particular applications where they are kept. And cannot be references outside the scope of the folder where they are kept.
In contrast, Shared Assemblies are the assemblies that are accessible globally/shared across the machine to all the applications. For using the shared assemblies you need to register the assembly with a strong name in the global assembly cache(GAC) using gacutil.exe. GAC can be found on all the computers with .Net framework installed.

----------------------------------
Assembly vs DLL

1.Dot NET assembly is the component standard specified by the .NET, so dot net assemblies are understandable to only Microsoft.NET and can be used only in .NET managed applications.

DLL contains library code to be used by any program running on Windows. A DLL may contain either structured or object oriented libraries.

2. assembly :

An assembly is the smallest unit that you use to define the version of an application. The version of an assembly determines the version of the types and the other resources that it contains. The .NET Framework allows the execution of multiple versions of the same assembly on the same machine. The side-by-side execution of assemblies overcomes the problem known as "DLL hell," which is one of the major problems associated with COM applications.

DLL:

A Dynamic Link Library (DLL) is a file that is loaded at runtime, and its functions linked
dynamically at that time. This allows for multiple applications that use the same library functions to all share one DLL, and if the code in the DLL needs to be fixed, the DLL can be replaced, and all applications that use it will get the benefit of the update. Static libraries are different from DLLs in that each application gets its own copy of the functions, and they are embedded into the Exe at compile/link time. If the library functions need to be fixed, every application that uses them must be recompiled to get the fixes.

Assembly ..... concept ... :-)

http://www.dnzone.com/ShowDetail.asp?NewsId=698

OOPS concepts .....

Constructor

C# supports two types of constructor, a class constructor (static constructor) and an instance constructor (non-static constructor).

Static constructor is used to initialize static data members as soon as the class is referenced first time, whereas an instance constructor is used to create an instance of that class with keyword. A static constructor does not take access modifiers or have parameters and can't access any non-static data member of a class.

Since static constructor is a class constructor, they are guaranteed to be called as soon as we refer to that class or by creating an instance of that class.

You may say, why not initialize static data members where we declare them in the code. Like this :

private static int id = 10;
private static string name = "jack";

Static data members can certainly be initialized at the time of their declaration but there are times when value of one static member may depend upon the value of another static member. In such cases we definitely need some mechanism to handle conditional initialization of static members. To handlesuch situation, C# provides static constructor.

Let me explain you with examples :

//File Name : Test.cs
using System;
namespace Constructor
{
class Test
{
//Declaration and initialization of static data member
private static int id = 5;
public static int Id
{
get
{
return id;
}
}
public static void print()
{
Console.WriteLine("Test.id = " + id);
}
static void Main(string[] args)
{
//Print the value of id
Test.print();
}
}
}

In the above example, static data member is declared and initialized in same line. So if you compile and run this program your output would look similar to this :

Test.id = 5

Lets create one more class similar to class Test but this time the value of its static data member would depend on the value of static data member of class Test.id.

//File Name : Test1.cs
using System;
namespace Constructor
{
class Test1
{
private static int id ;
//Static constructor, value of data member id is set conditionally here.
//This type of initialization is not possible at the time of declaration.
static Test1()
{
if( Test.Id < id =" 20;">
{
id = 100;
}
Console.WriteLine("Static Constructor for Class Test1 Called..");
}
public static void print()
{
Console.WriteLine("Test1.id = " + id);
}
static void Main(string[] args)
{
//Print the value of id
Test1.print();
}
}
}

As you can see in the above static constructor, static data member is initialized conditionally. This type of initialization is not possible at the time of declaration. This is where static constructor comes in picture. So if you compile and run this program your output would look similar to this :

Static Constructor for Class Test1 Called..
id = 20

Since in class Test was initialized with a value of 5, therefore in class Test1 got initialized to a value of 20.

Some important point regarding static constructor from C# Language Specification and C# Programmer's Reference :

1) The static constructor for a class executes before any instance of the class is created.
2) The static constructor for a class executes before any of the static members for the class are referenced.
3) The static constructor for a class executes after the static field initializers (if any) for the class.
4) The static constructor for a class executes at most one time during a single program instantiation
5) A static constructor does not take access modifiers or have parameters.
6) A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
7) A static constructor cannot be called directly.
8) The user has no control on when the static constructor is executed in the program.
9) A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Hopefully, this would clear the confusion some of developers have about static constructor.

Friday, November 30, 2007

What is Garbage Collection(GC) ?

One of the major causes of program failure today, particularly in applications that run for long time is due to manual memory management. Which leads two main problems

First one is, a programmer allocates a block of memory in a data storage area Of operating system (i.e. in Random Accesses Memory) intending to Free it latter, some time he mistakenly forget to release memory it No longer needs, this condition known as ‘Memory leak’

If this application run long enough, these leaks accumulate and the application runs out of memory, that is not big deal in a programs like ‘notepad’, that user runs for a few minutes an then shutdown. But a fatal application like web server that are supposed to run continuously for days or week this will leads accumulation of memory leaks and which leads to application fail.

Second one is programmer manually delete an object but then mistakenly or other objects try to access this memory location later. This will leads to hanging of application, and more over some times transistor that had make up the deleted object memory would still contain ‘Plausible’ values, and program continue to run with corrupted data.

These two above mentioned bugs are worse than most other application bugs because what the consequences will be and when those consequences will occur are typically unpredictable. That is making our application perform in unpredictable ways at unpredictable times. For other bugs, when we see our application misbehaving, we can just fix it

Microsoft.NET Made solution for above mentioned bugs. That is Microsoft made automatic memory management has part of .Net common language runtime (CLR), which allows it is to be used in any .Net language. That is in .Net application if CLR detects that, a Application is no longer using the memory and that it no longer needed. Then CLR release that memory. (i.e. Application does not have to explicitly free Memory that allocated). This mechanism runs automatically in background and is known as Garbage Collection

It solves the problem of manual memory management with out having to write any single line of code. You can’t forget to delete an object because the system cleans it for you when it is not required and you can’t access deleted object through an invalid reference because the object won’t be deleted as long as you hold a reference it

This Garbage Collection is like an automatic seat belt. The passengers couldn’t forget to buckle it. More over we know that automatic belt require more space and mechanism than manual one. Similarly .net application Require more system resources than ordinary application.

Really the garbage collection changes programming. we don't have all that Free What we Create overhead, so our code is smaller and clearer and easier to write. Garbage collection also makes programming even more object oriented.

Main aim of .Net is that faster development with fewer bugs That is we want programmer only think about program logic. Not any other Things like memory management or else.

NOTE: The memory used by heap variables is freed via a process garbage collection. Stack variables is automatically freed when the method in which they were created returns( ie Grabage collection is applied only for Heap Variable)

Thursday, November 29, 2007

Generics in VB.NET

Generics are very useful if you know what they are and how to use them. C++ was one of the first languages, which used some types of generics, however they were called “templates”. C# uses a similar syntax as the C++ templates, however in C# they are much easier to use. <> is used in C# to define a generic. However in VB.NET we use the keyword “Of”. In this article we will only discuss the VB.NET syntax.

What are Generics?

The term “generic” means not to be bound to any specific type regardless of whether we are referring it to any programming language or not! Just think of a “glass”, which can be filled with the following types: water, juice, soda etc. As you can see it is not bound to one type. It can be filled with any type. In the same way we can refer it to VB.NET. We could create a class called “Glass” which could store any of these types depended on the users choice.

Generics can be used to store collections, which are not bound to any data type.
Why should I use Generics?

ust imagine that you are working in a class where you would need to store different data types in a collection. Of course you could use an array, but don’t forget that you will need to create different arrays for different data types. Furthermore your code will be unnecessary longer than needed. In that case we can use generics. We could use one generic class that could handle all of data types, without requiring writing the code again and again. This will increase the performance, because the user would not need to cast the data types. In summary we can say that generics are used for the following reasons:

* Performance
* Type Safe
* Code Reuse

Performance:
How can generics help the developer to get a better performance? This is simple. The data-types are checked in the compile-timer rather than in run-time. Simply this change will improve the performance. No type casting necessary at run-time. However you should know that performance and speed are not the main aspects to use generics, but in maintainability and cleaner code.

Type Safe:
This means that whenever you add an object to the collection it is checked at compile time. That means that the data type should be safe and if you pass a wrong data-type to the collection, it will throw an error during the compile time and not in the run time. This way you can make sure to handle all errors so that they don’t appear at run time, when the client is using the application.

Code Reuse:
If you want to store different data types in a (non-generic) collection, than you won’t have any other option than declaring different collections for that. For example: You will need to declare a collection for integers, another for strings and another for double data types. When using generics you just need to set the data type as a parameter and viola you can use it with whatever type you like.

Simple Example

We have read a lot by now. It’s time to see some code. To demonstrate how simple it is to use we have chosen a simple example. Lets see how it looks like:

Our Gen Class:

Public Class Gen(Of T)
Dim dataType As T
Public Property Val() As T
Get
Return dataType
End Get
Set(ByVal value As T)
dataType = value
End Set
End Property
End Class

Our Main:

Sub Main()
' This one accepts strings
Dim mystring As New Gen(Of String)
mystring.Val = "hello world"
System.Console.WriteLine(mystring.Val)
' Change the declaration so that it accepts now an integer
Dim myInt As New Gen(Of Integer)
myInt.Val = 5
System.Console.WriteLine(myInt.Val)
Console.WriteLine("Press Enter to finish ... ")
Console.Read()
End Sub

Our Output:

hello world
5

How it works:
As you can see above we have only two main parts. The first is the class “Gen” and the second is the main function. The “Gen” class is generic. As already described in the introduction we need the “Of” keyword to declare it as generic. In C# and C++ we can use <> to create generic classes.

The “T” next right to the “Of” represents our data-type which we will pass when we create a new instance of that class. The rest of the code should be familiar to you.

The interesting part is going on in the main function where we create two instances of the “Gen” class. In the first instance we are using a String. This will allow passing string values to the class variables.

Dim mystring As New Gen(Of String)
mystring.Val = "hello world"
System.Console.WriteLine(mystring.Val)

In the second instance we are using an Integer. Here we can use integer values to pass to the class variables.

Dim myInt As New Gen(Of Integer)
myInt.Val = 5
System.Console.WriteLine(myInt.Val)

As you can see this was our first simple generic example. To get the same result without using generic, will cost you two classes. The first one would need a string and the second one could use an integer, but what if you decide to create a third data-type, lets say a double? Well then you will need to create a third class, which will again make your code longer than it already is. While using generics you only need one class for any data-type.

CLI, CLR, MSIL, JIT, .NET, C#, CLS and CTS ....


To most .NET programmers, there will be nothing new in this particular post. But, it only seems fitting that the initial post to this blog should be this simplified overview, just to make sure we're all on the same page.

The Common Language Infrastructure (CLI) is an international standard defined in ECMA-335. The CLI specifies the common mechanics for high-level, CLI-compliant programming languages. This standard is neither language specific nor platform specific.

The Common Language Runtime (CLR) is Microsoft's implementation of the CLI standard. The CLR executes a type of bytecode known as the Microsoft Intermediate Language (MSIL). At run-time, that MSIL bytecode is turned into native, executable code by the Just-In-Time compiler (JIT compiler). In theory, any CLI-compliant programming language is supported on any platform with the appropriate compiler and runtime.

The term ".NET" refers to a Microsoft product that includes the CLR, JIT compiler, source code compilers, and an entire framework of CLI-compliant components targetted for the Windows platform.

C# is a CLI-compliant programming language defined by the C# Language Specification (C#LS) known as ECMA-334. C#.NET is Microsoft's implementation of the C#LS for use with the Microsoft CLR, JIT compiler and framework components on Windows platforms. Since C#.NET is the only real implementation of the C# programming language (aside from the Mono open source project), the terms "C#" and "C#.NET" are often used interchangeably.

There are several .NET languages, including C#.NET and VB.NET. Even though both of those languages are CLI-compliant, the languages themselves have different capabilities. The Common Language Specification (CLS) is a Microsoft specification that defines the guaranteed subset of common functionality that is useable by all .NET programming languages. For example, the CLS defines the Common Type System (CTS), and the CTS does not include unsigned integers because the VB.NET programming language does not support unsigned integers.

Wednesday, November 28, 2007

Monday, November 12, 2007

Saturday, October 27, 2007

Thursday, October 18, 2007

Visual Studio thread ....

work around to fix some issues in VS 2008 .. it also includes AJAX , AJAX TOOL KIT installation issues ...

http://blogs.msdn.com/webdevtools/rss_tag_.NET.xml

Wednesday, October 17, 2007

Wednesday, October 3, 2007

Monday, October 1, 2007

innerWorkings Developer a ajax based add-in

Check out InnerWorkings Developer, the best way to build skills by writing code & solving problems. Our ASP.NET AJAX Drills are fully integrated within Visual Studio. Download a free trial.

free download here

Wednesday, September 19, 2007

add a SEARCH textbox to ur website ...

This is the website which provide a FREE search textbox to our webiste , and they w'l search our website and list results.

CLICK here : Search textbox to ur website LINK

test it , if it useful then njoy smile.gif

Tuesday, September 18, 2007

whats new in asp.net 2.0

  • Cross Page Posting - ASP.NET 2.0 allows you to post back from one page to another and you can obtain the source page values from the target page.
  • Wizard Control - The wizard control allows you to easily add multi-step form entry scenarios to your pages.
  • Validation Groups - Validation groups allow multiple forms on a page to be separately validated.
  • Focus API - The Focus API enables you to set focus to any control on the page, specify default buttons to submit for input controls, and more.
  • Compilation Build Providers - ASP.NET 2.0 includes support for compiling declarative file formats when they are placed in the App_Code directory.
  • No Compile Pages - Pages in ASP.NET 2.0 can be excluded from the compilation process, to be interpreted at runtime instead.
  • Securing Non-ASP.NET content - Under IIS 6, you can easily secure non-ASP.NET files such as static images or classic ASP pages from within an ASP.NET application.
  • Client-Script Features - ASP.NET 2.0 includes several new features that take advantage of client-side script.

pls click this LINK

Tuesday, August 21, 2007

All Tutorials

a huge collection of examples in JAVA , Java script ....

http://www.java2s.com/

Monday, July 23, 2007

Java Script Collection ...

Javascript in asp.net page

http://msdn2.microsoft.com/en-us/library/aa479011.aspx#aspnet-usingjavascript_topic05


some windows function in JS ....


http://www.infimum.dk/HTML/JSwindows.html#ref_2_2


Time and Date showing ....

http://www.quirksmode.org/js/date.html



page redirect using JS try this two examples :-)

function contactRedirect()
{
window.location.replace("contactUs.aspx");
}

OR

function contactRedirect()

{
window.location.href("contactUs.aspx");
}


java script popup

window.open(URL, '" + id + "', 'toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,width=1024,height=768,left = 0,top = 0');");

link to this website

java script Tuto

java script Tutorial website

Wednesday, July 11, 2007

Monday, July 2, 2007

C# and vb.net Comparison ....

http://www.harding.edu/fmccown/vbnet_csharp_comparison.html

Sunday, June 24, 2007

Important Links ......

www.indianrail.gov.in ( Railways website )


Wednesday, June 13, 2007

Null Check

Always check Null before use that Object or values


ex..
If IsNothing(Session("mainID")) = True Then
'Do this Job
End IF

if its database value means u must check isNull ( if the field allowed null value )

If IsDBNull(reader("mainNameMiddle")) = False Then
'Do this Job
End If

Tuesday, June 12, 2007

Monday, June 11, 2007

Nested Repeater with Parent child relations

Nested Repeater with Parent child relations ....

if u want to bind two table with relations in a nested repeater .... u can check this links ....

http://www.dotnetspider.com/kb/Article1039.aspx

http://support.microsoft.com/kb/306154

Friday, June 8, 2007

Some basic Diff between MS Access and MS SQL Server

Do u need to know Some basic Diff between MS Access and MS SQL Server in Queries ..... pls visit below link .....

http://weblogs.sqlteam.com/jeffs/archive/2007/03/30/Quick-Access-JET-SQL-to-T-SQL-Cheatsheet.aspx

You Tube Collections ......

http://www.youtube.com/watch?v=LU8DDYz68kM

Thursday, June 7, 2007

Importing Data from MS Access to SQL Server ...

If u want to import data from MS Access to SQL Server ....

please refer this link ...

http://www.microsoft.com/technet/prodtechn...access.mspx#EGC

go to SQL server Enterprise manager

1. Select a database and right click and u w'l find All Task --- > Import data
2. Select a Source Database in our case .mdb ( access database )
3. Select a Destination Database ... in our case SQL server db ...
4. Check the radio button Copy Table(s) and view(s) from the source database ..
5. Click next next and Finish .... done

you may get this Error during import ...

---------------------------
Copy Data from tblMembers to [asny].[dbo].[tblMembers] Step
---------------------------
Error at Destination for Row number 446. Errors encountered so far in this task: 1.

Insert error, column 9 ('mainDateThrough', DBTYPE_DBTIMESTAMP), status 6: Data overflow.
Invalid character value for cast specification.

Reason for this Error is Access automatically convert all datatime to smalldatetime in SQL Server ... so if Access table have some invalid dates it may difficult to covert by SQL server ....

Solution First u create a table ( which table have this error during importing ) in SQL server make all Date Fields in DATETIME .. dont keep in smalldatetime

and then import that particular table from Access to SQL server through DTS the problem will be solved .....

Sunday, June 3, 2007

Session in asp.net

if u want to know basic details about sessions please go to this link ...

http://www.codeproject.com/aspnet/ASPNETSession.asp

Friday, June 1, 2007

About SQL server DB

NVARCHAR versus VARCHAR


SQL Server provides both datatypes to store character information. For the most part the two datatypes are identical in how you would work with them within SQL Server or from an application. The difference is that nvarchar is used to store unicode data, which is used to store multilingual data in your database tables. Other languages have an extended set of character codes that need to be saved and this datatype allows for this extension. If your database will not be storing multilingual data you should use the varchar datatype instead. The reason for this is that nvarchar takes twice as much space as varchar, this is because of the need to store the extended character codes for other languages from Ask The Database Expert: Questions & Answers


What are Candidate, alternate and composite keys?


A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is called composite key.

-------------------------------------------------

how to view or see our TRIGGERS in our table

It's a bit cludgy, but in Enterprise Manager, on the database you are
looking at,
Right click on a particular table and
select [generate SQL scripts].

Untick [Script All Objects]
Tick [All Tables]
Under the [Formatting Tab] untick everything.
Under the [Options] tab, tick [Script Triggers]
(.) Create one file
Then [OK]




Thursday, May 31, 2007

out look from a href ......



sample one with subject , Bcc ,Cc

---- A HREF="mailto:info@uiconsulting.com?subject=Good%20Morning
&cc=bill_gates@microsoft.com&bcc=harry_potter@hogwarts.com"
Send an email to us /a---

Errors List .....

vbc : Command line error BC2017 : could not find library 'c:\windows\microsoft.net\framework\v1.1.4322\temporary asp.net files\vbwebapp\093b8894\b238cf87\assembly\dl\c0d82e1f\043d'

vbc : Fatal error BC2000 : compiler initialization failed unexpectedly: The filename, directory name, or volume label syntax is incorrect.

If u getting this ERROR pls visit ......

http://support.microsoft.com/default.aspx?scid=kb;en-us;897299

http://www.kbalertz.com/070173/receive.Command.error.BC2017.could.error.message.compile.application.Visual.Basic.aspx

------------------------------------------------------------------------

The name " " does not exist in the current context ( mostly it w'l happen in C# codebehind file - master content page )

if any control ( presented in aspx ) could't referenced in codebehind ( .aspx.cs )

try this one


TextBox txtEmail;
txtEmail = (TextBox)Page.Master.FindControl("ContentPlaceHolder1").FindControl("txtEmail");


---------------------------------------------------------------------

Name '__o' not declared ERROR mostly it w'l happen design time logic in asp.net

go through this link & find it

http://forums.asp.net/p/070173/0701735.aspx

------------------------------------------------------------------------

Tuesday, May 22, 2007

Free SMS sites ....

http://www.mobik.com
http://www.smskwik.com/Default.aspx
http://www.way2sms.com
http://www.free--sms.com/index.go

Thursday, May 17, 2007

How does Google collect and rank results?

http://www.google.com/librariancenter/articles/0512_01.html

Tuesday, May 15, 2007

sendmail using System.Net.Mail ....

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;
using System.Drawing;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ }
}
protected void btSend_Click(object sender, EventArgs e)
{
try
{

MailMessage mM = new MailMessage();
mM.From = new MailAddress(txtFrom.Text);
mM.To.Add(txtTo.Text);
mM.Subject = txtSub.Text;
mM.Body = txtMsg.Text;
mM.IsBodyHtml = true;
mM.Priority = MailPriority.High;
SmtpClient sC = new SmtpClient("smtp.mail.yahoo.com");
sC.Port = 587;
sC.Credentials = new NetworkCredential("YahooId", "Yahoo Password");
//sC.EnableSsl = true;
sC.Send(mM);
lbReport.Text = "Mail Send Successfully";
lbReport.ForeColor = Color.Green;

}
catch(Exception ex)
{
lbReport.Text = ex+"Mail Sending Fail's";
lbReport.ForeColor = Color.Red;
}

}
}

Query string

How to transfer variable between pages ? better u can use query string ....

example : u can use ? this question mark after the link page ....like below and pass ur variable

for passing -----> www.test.com/removemember.aspx?custid=342

for getting that variable ----> request.querystring("custid")

Wednesday, May 9, 2007

Ajax control intellisense did't work in Content Page??

Ajax control intellisense did't work in Content Page?? showing red underline in ScriptManager, UpdatePanel and ContentTemplate tags have the little red-squiggly lines underneath them...

http://weblogs.asp.net/scottgu/archive/2006/11/16/gotcha-lost-html-intellisense-within-asp-net-ajax-controls.aspx


The problem apparently comes from a failed attempt to wrap all AJAX controls with same asp: prefix as it is with the regular ASP.NET controls. So once you teach AJAX not to use asp: prefix, but for example the good ol' atlas:, confusion disappears and things start working fine again.

To fix that, you need to visit web.config, section system.web / pages / controls and replace all tagPrefix="asp" attributes with, for example, tagPrefix="atlas". After that, you need to use the same prefix throughout the application, thus no more asp:UpdatePanel, but atlas:UpdatePanel. After this operation intellisense starts working again, and no more screwed up markup or compilation errors.

Monday, May 7, 2007

Stored Procedure

http://www.sql-server-performance.com/tn_stored_procedures.asp


Stored Procedures Optimization Tips


* Use stored procedures instead of heavy-duty queries.
This can reduce network traffic, because your client will send to server only stored procedure name (perhaps with some parameters) instead of large heavy-duty queries text. Stored procedures can be used to enhance security and conceal underlying data objects also. For example, you can give the users permission to execute the stored procedure to work with the restricted set of the columns and data.


*****

* Include the SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a Transact-SQL statement.
This can reduce network traffic, because your client will not receive the message indicating the number of rows affected by a Transact-SQL statement.


*****

* Call stored procedure using its fully qualified name.
The complete name of an object consists of four identifiers: the server name, database name, owner name, and object name. An object name that specifies all four parts is known as a fully qualified name. Using fully qualified names eliminates any confusion about which stored procedure you want to run and can boost performance because SQL Server has a better chance to reuse the stored procedures execution plans if they were executed using fully qualified names.


*****

* Consider returning the integer value as an RETURN statement instead of an integer value as part of a recordset.
The RETURN statement exits unconditionally from a stored procedure, so the statements following RETURN are not executed. Though the RETURN statement is generally used for error checking, you can use this statement to return an integer value for any other reason. Using RETURN statement can boost performance because SQL Server will not create a recordset.


*****

* Don't use the prefix "sp_" in the stored procedure name if you need to create a stored procedure to run in a database other than the master database.
The prefix "sp_" is used in the system stored procedures names. Microsoft does not recommend to use the prefix "sp_" in the user-created stored procedure name, because SQL Server always looks for a stored procedure beginning with "sp_" in the following order: the master database, the stored procedure based on the fully qualified name provided, the stored procedure using dbo as the owner, if one is not specified. So, when you have the stored procedure with the prefix "sp_" in the database other than master, the master database is always checked first, and if the user-created stored procedure has the same name as a system stored procedure, the user-created stored procedure will never be executed.


*****

* Use the sp_executesql stored procedure instead of the EXECUTE statement.
The sp_executesql stored procedure supports parameters. So, using the sp_executesql stored procedure instead of the EXECUTE statement improve readability of your code when there are many parameters are used. When you use the sp_executesql stored procedure to executes a Transact-SQL statements that will be reused many times, the SQL Server query optimizer will reuse the execution plan it generates for the first execution when the change in parameter values to the statement is the only variation.


*****

* Use sp_executesql stored procedure instead of temporary stored procedures.
Microsoft recommends to use the temporary stored procedures when connecting to earlier versions of SQL Server that do not support the reuse of execution plans. Applications connecting to SQL Server 7.0 or SQL Server 2000 should use the sp_executesql system stored procedure instead of temporary stored procedures to have a better chance to reuse the execution plans.


*****

* If you have a very large stored procedure, try to break down this stored procedure into several sub-procedures, and call them from a controlling stored procedure.
The stored procedure will be recompiled when any structural changes were made to a table or view referenced by the stored procedure (for example, ALTER TABLE statement), or when a large number of INSERTS, UPDATES or DELETES are made to a table referenced by a stored procedure. So, if you break down a very large stored procedure into several sub-procedures, you get chance that only a single sub-procedure will be recompiled, but other sub-procedures will not.


*****

* Try to avoid using temporary tables inside your stored procedure.
Using temporary tables inside stored procedure reduces the chance to reuse the execution plan.


*****

* Try to avoid using DDL (Data Definition Language) statements inside your stored procedure.
Using DDL statements inside stored procedure reduces the chance to reuse the execution plan.


*****

* Add the WITH RECOMPILE option to the CREATE PROCEDURE statement if you know that your query will vary each time it is run from the stored procedure.
The WITH RECOMPILE option prevents reusing the stored procedure execution plan, so SQL Server does not cache a plan for this procedure and the procedure is recompiled at run time. Using the WITH RECOMPILE option can boost performance if your query will vary each time it is run from the stored procedure because in this case the wrong execution plan will not be used.


*****

* Use SQL Server Profiler to determine which stored procedures has been recompiled too often.
To check the stored procedure has been recompiled, run SQL Server Profiler and choose to trace the event in the "Stored Procedures" category called "SP:Recompile". You can also trace the event "SP:StmtStarting" to see at what point in the procedure it is being recompiled. When you identify these stored procedures, you can take some correction actions to reduce or eliminate the excessive recompilations.

*****

Tuesday, April 24, 2007

Maximum Capacity Specifications for SQL Server 2005

there is no row limit in the sql sever 2005 ...

find more in below link ...

http://msdn2.microsoft.com/en-us/library/ms143432.aspx



1. 32,767 database per instance of sql server
2. 2 billion tables per database
3. 1024 columns per table
4. 65,535 secondary datafiles per database
5. 256 filegroup per database
6. bytes per row - 8060
7. clustered index per table - 1
8. columns per index - 16
9. columns per select statement - 4096
10. files per database - 32,767
11. maximum file size of data - 32 TB
12. nested subqueries, transactions, Stored Procedures, triggeres - 32
13. rows per table - limited to storage space
14. tables per select statement - 256
15. Non clustered index - 249

Wednesday, April 18, 2007

Monday, April 16, 2007

Validation using asp.net validation control ....

These are the examples how to validate the input by using RegularExpressionValidator ...


Expressions --------- > Validation

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* ---------> E- Mail validation

http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)? ---------> webURL validation with htttp

([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)? ---------> webURL validation without htttp

\w{4}.* --------->Atleast 4 digits validation ( password )

^\d{6}$ ---------> Atleast 5 Numeric values ( pincode )

[a-zA-Z0-9\-_]{3,15} 3 to 15 range ... a to z lower & upper case allowd plus '-' allowed u
should a ' &' and other spl char means u should add like this
[ a-zA-Z0-9\-&*$_]

Monday, April 2, 2007

File DownLoad in asp.net ....

if u have upaloaded file path in dbtable means u can download that file using the following code .....

Put a Link Button in Gridview ....



tr
td align="left"

b Attachment : /b
asp:LinkButton ID="lnkbtnpath" runat="server" CommandName="test" CommandArgument=%#Eval("Filepath")% CausesValidation="false"

DownLoad
/asp:LinkButton
/td
/tr




call that file path in Rowcommand Event of Gridview ......

Protected Sub gvAppealperson_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvAppealperson.RowCommand
Dim filepath As String
Dim fileobj As FileInfo

' checking the Linkbutton's commandname is valid or not
If e.CommandName = "test" Then

' getting the commandarugment as path from database ( <%#Eval("Filepath")%>) in a string
filepath = e.CommandArgument

' assigning that string to FileInfo's object
fileobj = New FileInfo(filepath)
Response.Clear()

'Add the header that specifies the default filename for the Download/SaveAs dialog
Response.AddHeader("Content-Disposition", "attachment; filename=" & fileobj.Name)

'Add the header that specifies the file size, so that the browser can show the download progress
Response.AddHeader("Content-Length", fileobj.Length.ToString())

' Specify that the response is a stream that cannot be read by the client and must be downloaded
Response.ContentType = "application/octet-stream"

' Send the file stream to the client
Response.WriteFile(fileobj.FullName)
Response.Flush()

' Stop execution
Response.End()
End If
End Sub

Thursday, March 29, 2007

How to Get Users Hostaddress ( IP address ) ....

U can get the user IP address by using this Code

Dim strRemoteAddress As String
strRemoteAddress = CStr(Request.UserHostAddress)
Response.Write(strRemoteAddress)

Tuesday, March 27, 2007

Repeater with Paging Support .....

By default Repeater did't support Paging go through this link to find solution

http://www.dotnethero.com/hero/Repeater/paging.aspx

Wednesday, March 14, 2007

Tuesday, March 13, 2007

Best quotes ......

** If you want a thing done well, do it yourself. ** ( Gnanam Prakash na )

** Success Doesn't Need Hard Work It needs Smart Work
Make your anger very expensive and your smile very cheap ** ( Joseph na )


** Love is not finding the right person...building the right relationship... ** ( Karthik )


Wednesday, March 7, 2007

Right Click Disable in Javascript ...

u can disable the right click ..( ex disable Copy,Past, Save as picture )

http://www.acjavascripts.com/mouseeffects_norightclick.html

Sunday, March 4, 2007

What is business logic?

Before I proceed further, let's exactly define what business logic is. While presenting this at conferences and to companies I have become aware of the fact that not everyone agrees to what business logic actually is, and in many cases it's not even been well thought out what business logic is and what it is not.

The database server is a storage layer. Databases are designed to store, retrieve, and update data as quickly and efficiently as possible. This functionality is often referred to as CRUD (Create, Retrieve, Update, Delete). Certainly some databases are CRUD, but that is another topic.

Databases are designed to be very fast and efficient with CRUD operations. They are not designed to format telephone numbers, calculate optimum usage and peak periods of utility usage, determine geographic destinations and routings of shipments, and so on. Yet, I have seen all of these cases, and even more complex ones implemented mostly or even wholly inside stored procedures.
Delete customer

Business Logic Layer ...

Very good introduction about purpose of Business Logic Layer

http://msdn2.microsoft.com/en-us/library/ms978496.aspx
http://www.codeproject.com/gen/design/DudeWheresMyBusinessLogic.asp

And good example of implementation Business Logic Layer in ASP .NET application
(MUST READ):

http://www.asp.net/learn/dataaccess/tutorial02cs.aspx?tabid=63

Friday, March 2, 2007

Entertainment ....

Suriyan FM ...

http://84.16.227.100:9000/listen.pls

Lollu sabha Vijay Tv ....

http://lollu-sabha.blogspot.com/

fun video let see ...

http://video.google.com/videoplay?docid=-1525727123299209389

Wednesday, February 21, 2007

how to Get version from Appication's assembly

U can get version of a application by coding .... just follow the steps...

1. include below namespace

Imports System.Deployment
Imports System.Reflection.Assembly

2. include the below code

Dim strVersion As String
Dim AssVersion As Version = GetExecutingAssembly.GetName.Version
strVersion = AssVersion.Major & "." & AssVersion.MajorRevision & "." & AssVersion.Minor
& "." & AssVersion.MinorRevision
lblVersionNo.Text = strVersion

Fetching Connctionstring From Web.config for DBClass

One of the Best Practise in website is Keeping Your Connection string in Web.config

1.Adding Connection string in Web.config

""appSettings""
""add key ="dbstring" value ="Connectionstring""
""appSettings ""

2.Adding the above connection string to Your DB Class

Imports System.Configuration

Imports System.Data.SqlClient

Public dbcon As New SqlConnection
dbcon.ConnectionString = ConfigurationManager.AppSettings("dbstring")

Tuesday, February 6, 2007

Creating Script File for Database & Tables

If a developed a Desktop Application in Dot.net & u want run this application in different M/c means Follow these steps .......


1.Create a SQL script file.
2.Copy the exe file to the target machine.
3.Execute the SQL script in the Query Window of the target machine.
4.Modify the connection string according to the target machine.

Thursday, January 18, 2007

ERROR .. 'InitializeCulture' is not a member

BC30456: 'InitializeCulture' is not a member of 'ASP.default_aspx'


1. for that u have to add web.config file ....

2. in that change to -- compliation Debug = "False"

3 . avoid the debug =" false" in all .aspx page ... make it in a global that is use the line in web.config file ....

4 . add this line globlaization iuculture = "auto" culture="auto"

Wednesday, January 10, 2007

my own GetData function for Datasource

this is the function i wrote for datasource for databound control like
..bullettedlist ,datagrid.. etc...

Fuction Definition

Function getdata(ByVal qry As String, ByVal tablename As String) As DataSet
Dim da As SqlDataAdapter
Dim ds As New DataSet
da = New SqlDataAdapter(qry, obj.dbcon)
da.Fill(ds, "tablename")
Return ds
End Function


Fuction Calling

bllTest.DataSource = getdata("SELECT Name, AVG(Salary) AS avg_salar FROM tblTest GROUP BY Name", "tblTest")

" bllTest " is the sample bulletted list control ID .... then u can add this 2 lines

bllTest.DataTextField = "Name" ( Only for List Databound control --" only one column" )
bllTest.DataBind() ( For all Databound control )

note :
If u write this Function in public class u can access the function in any where ur application ...

Monday, January 8, 2007

Error in Web.Config ....

If u have any error notification like ...localhost can't run ..or error mode in false .....


try to add these lines in web.config



should " debug = true "

with regards

RameshRamalingam

a sample DB Class

my own database class


Public Class Dbclass
Public dbcon As SqlConnection
Sub Opencon()
dbcon = New SqlConnection("Data Source=WEBSERVER;Initial Catalog=RameshTest;User ID=sa; pwd=sql; Pooling=False")
If dbcon.State = ConnectionState.Closed Then
dbcon.Open()
End If
End Sub
Sub Closecon()
If dbcon.State = ConnectionState.Open Then
dbcon.Close()
End If
End Sub
End Class

SQL Querys...

To retrive last one month or last few days ..means u can use this query

if u have table ( Id , Name , date , City ) means ...
The query is ..

SELECT Id, Name, Date, City FROM tblTest
WHERE (Date > DATEADD(day, - 30, GETDATE()))

------------------------------------------------------------

To retrive recently Updated row's data means u can use this qry

SELECT userID, username FROM Tbl_Test
WHERE userID = ( SELECT MAX(userid) FROM Tbl_Test )


i used this qry in my application like below one ..

SELECT Id, Name, Phone, Email, DonorIp, DateofRegFROM Tbl_DonorWHERE
(Id = (SELECT MAX(Id) AS Expr1 FROM Tbl_Donor AS Tbl_Donor_1))

----------------------------------------------------------------

To Delete More then one Row using Primary Key ....


delid &= id.Text & ","
delid &= "0"
obj.SaiExcuteNonQry("DELETE FROM Tbl_Appeal where Appealid in
(" & delid &")")


-------------------------------------------------------------

to make bit fields as other name ...in page .... for example the bit fiels or 0 ,1 if u want to show 1 = male and 0 = female then u can use this query using CASE


SELECT CASE isApproved WHEN 1 THEN 'male' WHEN 0 THEN 'female'

END AS Expr1, Tbl_Donor.* FROM Tbl_Donor

------------------------------------------------------------

this qry shows how to use CASE with SQL query Fucntion Like DATEDIFF,DATEADD...

SELECT CASE isApproved WHEN 1 THEN 'Approved' WHEN 0 THEN 'Pending' END AS Expr1, CASE isApproved WHEN 1 THEN (DATEDIFF(dd, Postedon,
GETDATE())) WHEN 0 THEN '0' END AS FinishedDAYS, Appealid, Name, Address, City, State, Contactno, Email, Pincode, Refperson1, Refperson2,
Appeal, Filepath, Postedon, Userip, isResolved, isApproved
FROM Tbl_Appeal
WHERE (isApproved = 0)

----------------------------------------------------------------

if u want copy a record or row from a old table to new table u can use this Query

if u want copy all the data including ID ( primary key ) then u should set
auntoincrement to NO else u should retrieve all data ( except ID of old table ) and insert into new table .....

i am following the first case ( auto increment = no ie identity = no )

example

INSERT INTO Tbl_AppealBackup
SELECT Tbl_Appeal.*
FROM Tbl_Appeal
WHERE (Appealid = 135)

---------------------------------------------------------------



If u want to Check NULL values in SQL Queries here is the Example
ISNULL(expression,ValueifNULL)as expression

SELECT ISNULL(addID, '') AS addID,ISNULL(addType, '') AS addType, ISNULL(addPracticeName, '') AS addPracticeName, ISNULL(addAddress, '') AS addAddress, ISNULL(addStreet, '') AS addStreet, ISNULL(addCity, '') AS addCity," & _
"ISNULL(addState, '') AS addState, ISNULL(addZip, '') AS addZip, ISNULL(addCountry, '') AS addCountry, ISNULL(addMailTo, '') AS addMailTo FROM tblAddress WHERE(addMemID = " & mainID &
---------------------------------------------------------------------------------


all DATE FORMAT SQL query pls visit the below link

the DATE format query link
http://www.sql-server-helper.com/tips/date-formats.aspx ( data format link )
a example :

SELECT CASE Frequency WHEN 0 THEN 'Zero' WHEN 1 THEN 'one' WHEN 10 THEN 'Ten' END AS Frequency, CONVERT(char(10),tblInteractions.NextChargeDate, 105) AS NextChargeDate, CONVERT(char(10), tblInteractions.LastChargeDate, 105) AS LastChargeDate," & WHERE (tblInteractions.Vnum <> '') AND (tblInteractions.CreditCard <> '')


Fetching N th row from a table

SELECT * FROM tblMembers AS a
WHERE (@num =
(SELECT COUNT(*) AS Expr1
FROM tblMembers AS b
WHERE (a.mainID >= b.mainID)))


Finding and Deleting Duplicate rows from a TABALE


Here tblAdderss ---> table which have duplicate rows
tmpKey,tmpData ----> temp tables used for this process



Findind duplicate rows in a table
----------------------------------

SELECT addId, count(*)
FROM tblAddress
GROUP BY addId
HAVING count(*) > 1 /*** here addID is identity ro Primary key ****/



Deleting duplicate rows steps
-----------------------------

STEP 1 : Copy the duplicate IDs to temKey table
------------------------------------------------

SELECT addID,count(*) as count
INTO tmpKey
FROM tblAddress
GROUP BY addID
HAVING count(*) > 1


STEP 2: Copy the Distinct data from tblAddress to tmpData table with help of tmpKey
-----------------------------------------------------------------------------------

SELECT DISTINCT tblAddress.*
INTO tmpData
FROM tblAddress, tmpKey
WHERE tblAddress.addID= tmpKey.addID


STEP 3: Check tmpData table have any duplicate Rows
---------------------------------------------------

SELECT addID, count(*)
FROM tmpData
GROUP BY addID


STEP 4: Delete all duplicate rows in tblAddress
-----------------------------------------------

DELETE tblAddress
FROM tblAddress, tmpKey
WHERE tblAddress.addID= tmpKey.addID


STEP 5: Copy the non-dupicate rows to tblAddress from tmpData
--------------------------------------------------------------

SET IDENTITY_INSERT [tblAddress] ON

INSERT tblAddress([addID],[addMemID],[addType],[addPracticeName],[addAddress],[addStreet],[addCity],[addState],[addZip],[addCountry],[addMailTo]) SELECT [addID],[addMemID],[addType],[addPracticeName],[addAddress],[addStreet],[addCity],[addState],[addZip],[addCountry],[addMailTo] FROM tmpData

SET IDENTITY_INSERT [tblAddress] OFF



STEP 6: Drop the temp tables we used
-------------------------------------
DROP TABLE tmpKey,tmpData


SQL Functions

http://doc.ddart.net/mssql/sql70/fa-fz_15.htm


Super SQL server LINK

http://blog.sqlauthority.com/



to know about JOIN concept pls go to below link

link 1

link 2


http://en.wikipedia.org/wiki/Join_(SQL)#Sample_tables


how to improve the performance of the Query

http://technet.microsoft.com/en-us/library/ms172984.aspx



SQL TUTO LINK

http://www.1keydata.com/sql/sql.html

SQL FAQ

http://spaces.msn.com/ziauldotnet/

SQL Indexing

http://www.mssqlcity.com/Articles/Tuning/IndexOptimTips.htm
http://www.odetocode.com/Articles/70.aspx


SQL server Versions
or excute this Query to know - " SELECT @@VERSION"


@@VersionSQL Server VersionReleased
6.50.201SQL Server 6.5 RTM
6.50.213SQL Server 6.5 with Service Pack 1
6.50.240SQL Server 6.5 with Service Pack 2
6.50.258SQL Server 6.5 with Service Pack 3
6.50.281SQL Server 6.5 with Service Pack 4
6.50.415SQL Server 6.5 with Service Pack 5
6.50.416SQL Server 6.5 with Service Pack 5a
7.00.623SQL Server 7.0 / MSDE 1.0 RTM
7.00.699SQL Server 7.0 SP1July 1999
7.00.842SQL Server 7.0 SP2March 20th, 2000
7.00.961SQL Server 7.0 SP3December 15th, 2000
7.00.1063SQL Server 7.0 SP4
8.00.194SQL Server 2000 RTM
8.00.384SQL Server 2000 SP1
8.00.534SQL Server 2000 SP2November 30th, 2001
8.00.760SQL Server 2000 SP3
8.00.2039SQL Server 2000 SP4
2005.90.1399SQL Server 2005 RTMNovember 2005
2005.90.2047SQL Server 2005 SP1
2005.90.3042.00SQL Server 2005 SP2February 2007
2005.90.3042.01SQL Server 2005 "SP2a"5 Mar 2007
2005.90.3054.00KB934458 - Fix to check database in maintenance plans. Also read Bob Ward's post on SP2 for a great description of what to install.5 Apr 2007



To know the Rows count of all tables in a database


SELECT
[TableName] = so.name,
[RowCount] = MAX(si.rows)
FROM
sysobjects so,
sysindexes si
WHERE
so.xtype = 'U'
AND
si.id = OBJECT_ID(so.name)
GROUP BY
so.name
ORDER BY
2 DESC


To know the Columns count, Row size of all tables in a database


SELECT sysobjects.name, sysobjects.id, COUNT(syscolumns.name) AS ColumnCount, SUM(syscolumns.length) AS MaxLength
FROM sysobjects INNER JOIN
syscolumns ON sysobjects.id = syscolumns.id
WHERE (sysobjects.type = 'U')
GROUP BY sysobjects.name, sysobjects.id


SQL Injection Cheat Sheet

http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/



Case Sensitive or Insensitive SQL Query


Suppose you need to perform a SQL query and you need for it to be case sensitive or case insensitive, and Uppercase and Lowercase letter aeither your database is set up the opposite way or you're smart and you're trying to write your query so that it will work regardless of how the database may or may not be configured. For instance, consider this query:

SELECT UserId, email
FROM aspnet_membership
WHERE email =
'billg@microsoft.com'

If your database contains an email for Bill like this one: BillG@microsoft.com then whether or not your query will return any rows will depend on the COLLATION for the database. If you want to ensure that you DO get results, you can force it to use a CASE INSENSITIVE collation like so:

SELECT UserId, email
FROM aspnet_membership
WHERE email =
'biilg@microsoft.com' COLLATE SQL_Latin1_General_CP1_CI_AS

Similarly, if you don't want it to return any rows unless you specify the correct case for the email, you would change the collation to replace _CI_ with _CS_ where CI is short for Case Insensitive and CS is short for Case Sensitive. The following query would not match BillG@microsoft.com because it is using a case sensitive collation.

SELECT UserId, email
FROM aspnet_membership
WHERE email =
'billg@microsoft.com' COLLATE SQL_Latin1_General_CP1_CS_AS



To reset the identity field after testing in a TABLE

DBCC CHECKIDENT ('[dbo].[tblCalendar_Payment]' , RESEED, 0)



Listing / Dropping ALL stored procedures from a database in SQL Server 2005


I) List all Stored procedures in a database:

Select * from sys.procedures where [type] = 'P' and is_ms_shipped = 0 and [name] not like 'sp[_]%diagram%'

OR

Select * from sys.objects where type='p' and is_ms_shipped=0 and [name] not like 'sp[_]%diagram%'

Please note that I have added the 'NOT LIKE' part to get rid of stored procedures created during database installation.

II) Delete all [user created] Stored procedures in a database:

Select 'Drop Procedure ' + name from sys.procedures Where [type] = 'P' and is_ms_shipped = 0 and [name] not like 'sp[_]%diagram%'

This would list down all the user defined Stored procedure as 'Drop Procedure procedureName' in the result pane. Just copy-paste it into the query window and execute it once.
Select by Date part only ( not time )
WHERE (REGDATE = CONVERT(varchar(8), GETDATE(), 112))