Monday, March 22

SQL String Functions

Sql string function is a built-in string function.
It perform an operation on a string input value and return a string or numeric value.
Below is All built-in Sql string function :
ASCII, NCHAR, SOUNDEX, CHAR, PATINDEX, SPACE, CHARINDEX, REPLACE, STR, DIFFERENCE, QUOTENAME, STUFF, LEFT, REPLICATE, SUBSTRING, LEN, REVERSE, UNICODE, LOWER, RIGHT, UPPER, LTRIM, RTRIM


Example SQL String Function - ASCII
- Returns the ASCII code value of a keyboard button and the rest etc (@,R,9,*) .
Syntax - ASCII ( character)
SELECT ASCII('a') -- Value = 97
SELECT ASCII('b') -- Value = 98
SELECT ASCII('c') -- Value = 99
SELECT ASCII('A') -- Value = 65
SELECT ASCII('B') -- Value = 66
SELECT ASCII('C') -- Value = 67
SELECT ASCII('1') -- Value = 49
SELECT ASCII('2') -- Value = 50
SELECT ASCII('3') -- Value = 51
SELECT ASCII('4') -- Value = 52
SELECT ASCII('5') -- Value = 53


Example SQL String Function - SPACE
-Returns spaces in your SQL query (you can specific the size of space).
Syntax - SPACE ( integer)
SELECT ('SQL') + SPACE(0) + ('TUTORIALS')
-- Value = SQLTUTORIALS
SELECT ('SQL') + SPACE(1) + ('TUTORIALS')
-- Value = SQL TUTORIALS


Example SQL String Function - CHARINDEX
-Returns the starting position of a character string.
Syntax - CHARINDEX ( string1, string2 [ , start_location ] )
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial')
-- Value = 27
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial', 20)
-- Value = 27
SELECT CHARINDEX('SQL', 'Well organized understand SQL tutorial', 30)
-- Value = 0 (Because the index is count from 30 and above)


Example SQL String Function - REPLACE
-Replaces all occurrences of the string2 in the string1 with string3.
Syntax - REPLACE ( 'string1' , 'string2' , 'string3' )
SELECT REPLACE('All Function' , 'All', 'SQL')
-- Value = SQL Function


Example SQL String Function - QUOTENAME
-Returns a Unicode string with the delimiters added to make the input string a valid Microsoft® SQL Server™ delimited identifier.
Syntax - QUOTENAME ( 'string' [ , 'quote_character' ] )
SELECT QUOTENAME('Sql[]String')
-- Value = [Sql[]]String]


Example SQL String Function - STUFF
- Deletes a specified length of characters and inserts string at a specified starting index.
Syntax - STUFF ( string1 , startindex , length , string2 )
SELECT STUFF('SqlTutorial', 4, 6, 'Function')
-- Value = SqlFunctional
SELECT STUFF('GoodMorning', 5, 3, 'good')
-- Value = Goodgoodning


Example SQL String Function - LEFT
-Returns left part of a string with the specified number of characters.
Syntax - LEFT ( string , integer)
SELECT LEFT('TravelYourself', 6)
-- Value = Travel
SELECT LEFT('BeautyCentury',6)
-- Value = Beauty


Example SQL String Function - RIGHT
-Returns right part of a string with the specified number of characters.
Syntax - RIGHT( string , integer)
SELECT RIGHT('TravelYourself', 6)
-- Value = urself
SELECT RIGHT('BeautyCentury',6)
-- Value = Century


Example SQL String Function - REPLICATE
-Repeats string for a specified number of times.
Syntax - REPLICATE (string, integer)
SELECT REPLICATE('Sql', 2)
-- Value = SqlSql


Example SQL String Function - SUBSTRING
-Returns part of a string.
Syntax - SUBSTRING ( string, startindex , length )
SELECT SUBSTRING('SQLServer', 4, 3)
-- Value = Ser


Example SQL String Function - LEN
-Returns number of characters in a string.
Syntax - LEN( string)
SELECT LEN('SQLServer')
-- Value = 9


Example SQL String Function - REVERSE
-Returns reverse a string.
Syntax - REVERSE( string)
SELECT REVERSE('SQLServer')
-- Value = revreSLQS


Example SQL String Function - UNICODE
-Returns Unicode standard integer value.
Syntax - UNICODE( char)
SELECT UNICODE('SqlServer')
-- Value = 83 (it take first character)
SELECT UNICODE('S')
-- Value = 83


Example SQL String Function - LOWER
-Convert string to lowercase.
Syntax - LOWER( string )
SELECT LOWER('SQLServer')
-- Value = sqlserver


Example SQL String Function - UPPER
-Convert string to Uppercase.
Syntax - UPPER( string )
SELECT UPPER('sqlserver')
-- Value = SQLSERVER


Example SQL String Function - LTRIM
-Returns a string after removing leading blanks on Left side.
Syntax - LTRIM( string )
SELECT LTRIM(' sqlserver')
-- Value = 'sqlserver' (Remove left side space or blanks)


Example SQL String Function - RTRIM
-Returns a string after removing leading blanks on Right side.
Syntax - RTRIM( string )
SELECT RTRIM('SqlServer ')
-- Value = 'SqlServer' (Remove right side space or blanks)

SQL UNION ALL

SQL UNION ALL

SQL UNION ALL is combine the results of two queries together without filter out the same value(no distinct behavior).
The difference between UNION ALL and UNION is UNION only selects distinct values and UNION ALL selects all values.

Syntax - UNION ALL
(SQL Statement 1)
UNION ALL
(SQL Statement 2)

Below is example for SQL UNION


Company

Sales($)
Website

Sql Traniner 2500 http://www.sqltutorials.blogspot.com
BeautyCentury 3000 http://beautycentury.blogspot.com
TravelYourself 2800 http://travelyourself.blogspot.com
Table1

Sales
Website

2900 http://www.sqltutorials.blogspot.com
3000 http://beautycentury.blogspot.com
2800 http://travelyourself.blogspot.com
Table2

SQL UNION ALL Statement
SELECT Sales FROM TABLE1
UNION ALL
SELECT Sales FROM TABLE2

Result
Sales
2500
3000
2800
2900
3000
2800

Qry to get first and last date of months

SELECT DATEADD(dd, -DAY(DATEADD(month, 0, getDate())), DateADD(month, 0, getDate())+1)
SELECT DATEADD(dd, -DAY(DATEADD(month, 0, getDate())), DateADD(month, 0, getDate()))

SQL DATEDIFF & DATEADD Functions

SQL DATEDIFF Function

Returns the number of date and time boundaries crossed between two dates

SQL DATEDIFF Syntax
DATEDIFF ( DatePart , StartDate , EndDate )

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate ='2007-06-05'
SET @EndDate ='2007-08-05'

SELECT DATEDIFF(Year, @StartDate, @EndDate) AS NewDate
Return Value = 0 Year


SELECT DATEDIFF(quarter, @StartDate, @EndDate) AS NewDate
Return Value = 1 quarter


SELECT DATEDIFF(Month, @StartDate, @EndDate) AS NewDate
Return Value = 2 Month


SELECT DATEDIFF(dayofyear,@StartDate, @EndDate) AS NewDate
Return Value = 61 day


SELECT DATEDIFF(Day, @StartDate, @EndDate) AS NewDate
Return Value = 61 Day


SELECT DATEDIFF(Week, @StartDate, @EndDate) AS NewDate
Return Value = 9 Week


SELECT DATEDIFF(Hour, @StartDate, @EndDate) AS NewDate
Return Value = 1464 Hour


SELECT DATEDIFF(minute, @StartDate, @EndDate) AS NewDate
Return Value = 87840 minute


SELECT DATEDIFF(second, @StartDate, @EndDate) AS NewDate
Return Value = 5270400 second


DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate ='2007-06-05'
SET @EndDate ='2007-06-06'

SELECT DATEDIFF(millisecond, @StartDate, @EndDate) AS NewDate
Return Value = 86400000 millisecond

SQL DATEDIFF Function
SqlTutorials

Posted by Emil Chang at 6:18 AM 12 comments

Labels: SQL DateADD and DateDiff, SQL Dynamic Get Last and First Day

Monday, June 4, 2007

SQL DATEADD Function

Returns a new datetime value based on adding an interval to the specified date.

SQL DATEADD Syntax
DATEADD ( datepart , number, date )


DECLARE @DateNow DATETIME
SET @DateNow='2007-06-04'
SELECT DATEADD(Year, 3, @DateNow) AS NewDate
Return Value = 2010-06-04 00:00:00.000


SELECT DATEADD(quarter, 3, @DateNow) AS NewDate
Return Value = 2008-03-04 00:00:00.000


SELECT DATEADD(Month, 3, @DateNow) AS NewDate
Return Value = 2007-09-04 00:00:00.000


SELECT DATEADD(dayofyear,3, @DateNow) AS NewDate
Return Value = 2007-06-07 00:00:00.000


SELECT DATEADD(Day, 3, @DateNow) AS NewDate
Return Value = 2007-06-07 00:00:00.000


SELECT DATEADD(Week, 3, @DateNow) AS NewDate
Return Value = 2007-06-25 00:00:00.000


SELECT DATEADD(Hour, 3, @DateNow) AS NewDate
Return Value = 2007-06-04 03:00:00.000


SELECT DATEADD(minute, 3, @DateNow) AS NewDate
Return Value = 2007-06-04 00:03:00.000


SELECT DATEADD(second, 3, @DateNow) AS NewDate
Return Value = 2007-06-04 00:00:03.000


SELECT DATEADD(millisecond, 3, @DateNow) AS NewDate
Return Value = 2007-06-04 00:00:00.003

SQL Case

http://sqltutorials.blogspot.com

SQL Case evaluates a list of conditions and returns one possible result expressions.

CASE has two formats:
1. Simple CASE Function - Compares an expression to determine the result.
2. Searched CASE Function - Evaluates a set of Boolean expressions to determine the result.

CASE Syntax
1. Simple CASE function:
CASE input_expression
WHEN when_expression THEN Result
ELSE result_expression
END

2. Searched CASE function:
CASE
WHEN Boolean_expression THEN Result
ELSE result_expression
END

1. Simple CASE Function
Evaluates input_expression and find the match with when_expression. If found, it will return the Result and if not found, it will return the ELSE result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified.

DECLARE @Type varchar(20)
SET @Type = 'Programming'

SELECT
CASE @Type
WHEN 'Sql' THEN 'sqltutorials.blogspot.com'
WHEN 'Programming' THEN 'programmingschools.blogspot.com'
WHEN 'Travel' THEN 'travelyourself.blogspot.com'
ELSE 'Not yet categorized'
END
Value = programmingschools.blogspot.com

If SET @Type = 'Picture', then Return value = Not yet categorized



2.Searched CASE Function
Evaluates Boolean_expression for each WHEN clause and returns result_expression of the first Boolean_expression that evaluates to TRUE.
If no Boolean_expression evaluates to TRUE, SQL Server returns the ELSE result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified.

DECLARE @Price integer
SET @Price = (20-9)

SELECT
CASE
WHEN @Price IS NULL THEN 'Not yet priced'
WHEN @Price < color="#ff0000">THEN 'Very Reasonable Price'
WHEN @Price >= 10 AND @Price < color="#ff0000">THEN 'Reasonable Price'
ELSE 'Expensive book!'
END
Value = Reasonable Price

SQL CAST and CONVERT

SQL CAST and CONVERT

It converts an expression from one data type to another.
CAST and CONVERT have similar functionality.

SQL CAST and CONVERT Syntax
Using CAST:
CAST ( expression AS data_type )

Using CONVERT:
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

Example of SQL Cast and Convert

SQL Cast and Convert - String
SELECT SUBSTRING('CAST and CONVERT', 1, 3)
Return Value = CAS (it get from index 1 to 3)

SELECT CAST('CAST and CONVERT' AS char(3))
Return Value = CAS (it get 3 char only)


SQL Cast and Convert - Date Time
-Converting date time to character data(vachar)
-The default values (style 0 or 100, 9 or 109, 13 or 113, 20 or 120, and 21 or 121) always return the Without century year(yy).
-Add 100 to a style value to get a four-place year that includes the century year(yyyy).
-Below is example for converting 1 format of date time to different format of date time, so that it can be use in various condition.

Value of current Date Time GETDATE()
SELECT (GETDATE()) = 2007-06-06 23:41:10.153


SELECT CONVERT(varchar,GETDATE(),0)
Return Value = Jun 6 2007 11:07PM
SELECT CONVERT(varchar,GETDATE(),100)
Return Value = Jun 6 2007 11:07PM


SELECT CONVERT(varchar,GETDATE(),1)
Return Value = 06/06/07
SELECT CONVERT(varchar,GETDATE(),101)
Return Value = 06/06/2007


SELECT CONVERT(varchar,GETDATE(),2)
Return Value = 07.06.06
SELECT CONVERT(varchar,GETDATE(),102)
Return Value = 2007.06.06


SELECT CONVERT(varchar,GETDATE(),3)
Return Value = 06/06/07
SELECT CONVERT(varchar,GETDATE(),103)
Return Value = 06/06/2007


SELECT CONVERT(varchar,GETDATE(),4)
Return Value = 06.06.07
SELECT CONVERT(varchar,GETDATE(),104)
Return Value = 06.06.2007


SELECT CONVERT(varchar,GETDATE(),5)
Return Value = 06-06-07
SELECT CONVERT(varchar,GETDATE(),105)
Return Value = 06-06-2007


SELECT CONVERT(varchar,GETDATE(),6)
Return Value = 06 Jun 07
SELECT CONVERT(varchar,GETDATE(),106)
Return Value = 06 Jun 2007


SELECT CONVERT(varchar,GETDATE(),7)
Return Value = Jun 06, 07
SELECT CONVERT(varchar,GETDATE(),107)
Return Value = Jun 06, 2007


SELECT CONVERT(varchar,GETDATE(),8)
Return Value = 23:38:49
SELECT CONVERT(varchar,GETDATE(),108)
Return Value = 23:38:49


SELECT CONVERT(varchar,GETDATE(),9)
Return Value = Jun 6 2007 11:39:17:060PM
SELECT CONVERT(varchar,GETDATE(),109)
Return Value = Jun 6 2007 11:39:17:060PM


SELECT CONVERT(varchar,GETDATE(),10)
Return Value = 06-06-07
SELECT CONVERT(varchar,GETDATE(),110)
Return Value = 06-06-2007


SELECT CONVERT(varchar,GETDATE(),11)
Return Value = 07/06/06
SELECT CONVERT(varchar,GETDATE(),111)
Return Value = 2007/06/06


SELECT CONVERT(varchar,GETDATE(),12)
Return Value = 070606
SELECT CONVERT(varchar,GETDATE(),112)
Return Value = 20070606


SELECT CONVERT(varchar,GETDATE(),13)
Return Value = 06 Jun 2007 23:40:14:577
SELECT CONVERT(varchar,GETDATE(),113)
Return Value = 06 Jun 2007 23:40:14:577


SELECT CONVERT(varchar,GETDATE(),14)
Return Value = 23:40:29:717
SELECT CONVERT(varchar,GETDATE(),114)
Return Value = 23:40:29:717


SELECT CONVERT(varchar,GETDATE(),20)
Return Value = 2007-06-06 23:40:51
SELECT CONVERT(varchar,GETDATE(),120)
Return Value = 2007-06-06 23:40:51


SELECT CONVERT(varchar,GETDATE(),21)
Return Value = 2007-06-06 23:41:10.153
SELECT CONVERT(varchar,GETDATE(),121)
Return Value = 2007-06-06 23:41:10.153


SELECT CONVERT(varchar,GETDATE(),126)
Return Value = 2007-06-06T23:41:10.153


SELECT CONVERT(varchar,GETDATE(),131)
Return Value = 21/05/1428 11:41:10:153PM

LastDay_PreviousMonth

SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
LastDay_PreviousMonth
----Last Day of Current Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0))
LastDay_CurrentMonth
----Last Day of Next Month
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0))
LastDay_NextMonth
--Last Day of Any Month and Year
DECLARE @dtDate DATETIME
SET @dtDate = '8/18/2007'
SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@dtDate)+1,0))
LastDay_AnyMonth

Saturday, March 20

WCF EndPoint

Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.

The Endpoint is the fusion of Address, Contract and Binding.

The main components of WCF

The main components of WCF are

1. Service class
2. Hosting environment
3. End point

What was the code name for WCF?

The code name of WCF was Indigo .

WCF is a unification of .NET framework communication technologies which unites the following technologies:-

NET remoting
MSMQ
Web services
COM+

Major ways of hosting a WCF services

There are three major ways of hosting a WCF services

• Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class.

• Host in application domain or process provided by IIS Server.

• Host in Application domain and process provided by WAS (Windows Activation Service) Server.

WCF 3 major points

We Should remember ABC.

Address --- Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.

Binding --- Specifies how the two paries will communicate in term of transport and encoding and protocols

Contract --- Specifies the interface between client and the server.It's a simple interface with some attribute.

webService Vs WCF

Web Services

1.It Can be accessed only over HTTP
2.It works in stateless environment

WCF

WCF is flexible because its services can be hosted in different types of applications. The following lists several common scenarios for hosting WCF services:
IIS
WAS
Self-hosting
Managed Windows Service

WPF, WCF, WWF, WCS

1. WPF (Windows Presentation Foundation).
2. WCF (Windows Communication Foundation)
3. WF (Windows Workflow Foundation)
4. WCS (Windows Card Space)


1. WPF (Windows Presentation Foundation)


New era for Windows Desktop Application UI designing. Following are some of the main features

• Now onwards there are no WinForm Controls that we are using till .net 2.0. Everything is XML. Whatever you write will be the XML for the desigining. Officially Microsoft gives its name XAML

• Because of this XML everything you can do in Html pages will now possible in Winform design also

• Cascading Style like web is possible in Winform also

• Designer draw the screen in Photoshop just like they where doing for web page. And then you can do the same step as you were doing to convert that layout in html

• Provides new type of application known as "WPF Browser based application", which can run in Internet Explorer just like the ActiveX and Applets are running

• 3D modeling.

• Animation like GIF file can be possible for the windows form.

Links
WPF Architecures and functionality
http://msdn.microsoft.com/library/en-us/dnlong/html/wpf101.asp
WPF for beginners
http://wpf.netfx3.com/
Find the features in detail for WPF
http://en.wikipedia.org/wiki/Windows_Presentation_Foundation
Introduction Videos
http://msdn.microsoft.com/msdntv/episode.aspx?xml=episodes/en/20060817wpfkg/manifest.xml
First Hands on lab
http://www.microsoft.com/downloads/details.aspx?FamilyID=05755a9d-98fa-4f16-bfdc-023e3fd34763&DisplayLang=en
2. WCF (Windows Communication Foundation)


New era for Communication methods for the Distributed application development and Grid Computing with much flexibility that we never have before. This is something they are calling Service Oriented Application Architecture.

• Web service, WSE, Remorting, MSMQ... all of this is now a mapped in single API

• Easy to deploy and integration with Application.

• XML web service access speed will no more issue with the help of WCF.

Links
Learning WCF (Architecture and Foundation)
http://msdn.microsoft.com/library/en-us/dnlong/html/wcfarch.asp
Introduction of Developing WCF
http://msdn.microsoft.com/library/en-us/dnlong/html/introtowcf.asp
3. WF (Windows Workflow Foundation)


This is really really very cool features that Microsoft comes up with .net 3.0. With the help of this foundation you can implement any complex Business logic which you could not even think for it. Just within a few hours you can implement few weeks of work. The features are

• Draw the Flow chart and the coding part will be written automatically. Of course you have to feed some line of code

• Represent your logic on document which is actually the code you implement

• No more syntax and commenting for Code, because your logic is in form of Flow charts

• Maintain the State of Object (Application Objects) with the Help of State Chart. Draw the state diagram for your Object and it will reach exactly in the state as per you have drawn with in IDE

• I could not believe on my eyes when I saw the demonstration of Parallel Computing and Multi threading application development. Just to draw the flow chart with some parallel Flow in sequence, that’s all to do. Not to think anything for the thread and multi process management

Links
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnlong/html/hmnwkfwwf.asp
Understanding Components in WF
http://msdn.microsoft.com/msdnmag/issues/06/12/windowsworkflow/
4. WCS (Windows Card Space)


It is formerly known as the code named "InfoCard" that helps to protect user’s digital identities against spoofing, phishing and tampering. It enables end users to provide digital identity to online services in a simple and trusted way.
Here is how it works…
Instead of authenticating users with passwords, websites authenticate users with security tokens. Submit identity token to the website with just a few clicks of a mouse. The website accepts this token presented by the user, decrypts the token, validates this credential and uses this information internally to identify the user. Cryptographic techniques along with responsible protocols are used for identification of the user. CardSpace includes a self-issued identity provider, which runs on the local Windows system and it can produce information cards just like any other identity provider.
Users download cards from identity providers such as their bank, employer, government agency, membership organization, or create their own self-issued cards. When a Website or Web service requests a user’s credentials, CardSpace will be invoked and allow the user to select a card to present. CardSpace then retrieves a verifiable credential from the selected identity provider, or the self-issuing authority as the case may be, utilizing interoperable protocols. It then forwards the credential to the target application. This provides users with a simple, secure and familiar sign-on experience that is consistent across all Websites and Web services.
We can enjoy the technology, simplicity, consistency and mainly security that Card Space gifts us.

WCF

Wcf is the windows communication foundation, which comes in dotnet 3.0 and 3.5,
you can communicate using http,tcp,msmq,It is service oriented architecture.

WCF is the Architecture, its divided into three types.

Using this you can communicate multiple platform, multifle servicies.

A-Address-when to communicate
B-Binding-how to communicate.
C-Contract-where to communicate

read ABC of WCF

Note:Webservice you can communicate only through http.

WCF comes up as a replacement for Remoting and Web service in dotnet.
The main feature of WCF is it's security. It can use the protocols like basice,wsHttp,tcp...wsHttp comes with default windows based security feature. WRT web services WCF works with the industry standard Contract based protocols. The componets WCF are data contract, Service Contract and the Service programme.

Wednesday, March 10

ASP.Net Page Life Cycle - Stage Description:

Page request:
The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start:
In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.

Page initialization:
During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

Load:
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

Validation:
During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

Postback event handling:
If the request is a postback, any event handlers are called.

Rendering:
Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.

Unload:
Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

Cookies Vs Sessions

As far as my knowledge is concerned, cookies are stored on client side where as sessions are server variables. The storage limitations are also there (like IE restricts the size of cookie to be not more than 4096 bytes). We can store only a string value in a cookie where as objects can be stored in session variables. The client will have to accept the cookies in order to use cookies, there is no need of user's approval or confirmation to use Session variables cos they are stored on server. The other aspect of this issue is cookies can be stored as long as we want(even for life time) if the user accepts them, but with session variables we can only store something in it as long as the session is not timed out or the browser window is not closed which ever occurs first.

Coming to usage you can use both cookies and session in the same page.

We should go for cookies to store something that we want to know when the user returns to the web page in future (eg. remember me on this computer check box on login pages uses cookies to remember the user when he returns). Sessions should be used to remember something for that particular browser session (like the user name, to display on every page or where ever needed).

how to write and read cookies.

This eample code belongs to web site www.gotdotnet.com visit the following link for full example code and demo.

http://samples.gotdotnet.com/quickstart/aspplus/doc/stateoverview.aspx

Protected Sub Page_Load(sender As Object, e As EventArgs)
If Request.Cookies("preferences1") = Null Then
Dim cookie As New HttpCookie("preferences1")
cookie.Values.Add("ForeColor", "black")
...
Response.AppendCookie(cookie)
End If
End Sub

Protected Function GetStyle(key As String) As String
Dim cookie As HttpCookie = Request.Cookies("preferences1")
If cookie <> Null Then
Select Case key
Case "ForeColor"
Return(cookie.Values("ForeColor"))
Case ...
End Select
End If
Return("")
End Function

How to write and read session variables.

This example belongs to www.eggheadcafe.com visit the following link for quick summary and list of FAQs on Session State.

http://www.eggheadcafe.com/articles/20021016.asp

Basic use of Session in ASP.NET (C#):

STORE:
DataSet ds = GetDataSet(whatever parameters);
Session["mydataset")=ds;

RETRIEVE:
DataSet ds = (DataSet)Session["mydataset"];



web application is stateless protocol.
If we want some information to be travle from one page to another page in asp.net then we can use cookies as well as session.
cookies:-with the help of cookies we cal transfer the information from one page to another page but the value should be simple text,bt session can use any type of serialize data.
only 20 cookies for one host
session may be lot.
we can use multiple cookies.
cookies value can be change by user but session value is vary secure.

Thread Vs Process

Thread - is used to execute more than one program at a time.
process - executes single program

EXE Vs DLL

An EXE can run independently, whereas DLL will run within an EXE. DLL is an in-process file and EXE is an out-process file

What is the difference between ADO and ADO.NET?

1. ADO objects are COM objects. ADO.Net objects are represented using XML
2. ADO objects have difficulty travelling through firewalls. ADO.Net objects represented as text (XML) travel easily through all kinds of network restrictions.
3. ADO recordsets are heavier than the ADO.Net counterparts datasets.
4. ADO recordsets can hold data from one data source at a time. ADO.Net datasets can hold data from various sources and integrate the data and write it back to one / several data sources.
5. ADO.Net dataset represents in memory representation of a database. ADO recordsets is merely a set of rows retrieved from a data source.

What is COM, DCOM objects in DotNet

The dot net frameworks allow you to build serviced components that can use com+ services. These components of dot net framework runs in the manages execution environment of dot net framework that is share their content with com+ application.

Now the question arise what com+ and what is doing how is its comes in existence. Before com+ comes into existence. COM (Component Object Model) is first programming model that provide component based approach to software development. This component based approach of com allowed us to develop small logical reusable and stand alone modules that integrates into a single application. But these components could not be display on over network.

So these drawback produce another model that is DCOM (distributes COM). DCOM programming model enabled you to display com components over network and distribute application easily across platforms. DCOM components also help in two-tier client/server applications. These models also have some drawback that helps to development of COM+ approach. What these drawbacks are…

These two-tier architecture helps us to sharing of resources and data but these approach have some drawbacks that are as follows.

The DCOM approach overburdened client computer with the responsibility of performing all processing functions while the server merely acted as traffic controller helps movement of data to and from the client and server components. So availability of resources was therefore always a problem and the performance of application suffered. Multiple request of data cause to network traffic. So performance of application decreases.

How dot net differs from other programming languages?

Other programming languages get compiled and run in their own specific run time environments and are not inter-operable.Where Dot Net supports programming languages run in a common runtime environment called CLR and get compiled into MSIL code which is interoperable with other programming languages supported by CLR.JIT is then used to convert MSIL to native code based on the operating system.CLR supports many utilities like Garbage Collection MemoryManagement and so on that make it a more efficient run time environment.


.NET is a framework and not a programming language. Hence we cannot compare .NET with other programming languages.

.NET framework has CLR (Common language runtime) which has the runtime libraries for all the languages supported by .NET. It is the responisbility of the runtime to take care of the code execution of the programs written using programming language.

.NET framework performs responsibilities like garbage collection (memory management) code access security code verification etc. In case of other programming languages these responsibilities has to be carried out by a programmer or s/w developer developing the application.

Advantage of using .NET is you can still continue programming in the language you are comfortable with.

Monday, March 8

Why choose C# over Visual Basic (VB)?

http://en.csharp-online.net/CSharp_FAQ:_Why_choose_CSharp_over_Visual_Basic_%28VB%29

The choice between C# and Visual Basic .NET is a subjective one based on prior experience. C++, Java, and J++ programmers will prefer the non-nonsense, terse syntax of C#. Visual Basic (VB) programmers may prefer to stick with the devil they know—Visual Basic .NET's case-insensitive, pseudo-natural language approach.

Both languages can access the identical .NET Framework libraries. Both perform largely similarly. In fact, with few exceptions, they perform almost the same assuming VB.NET has Option Strict turned on. Generally, C# is the favorite language of all but die-hard Visual Basic programmers.

The learning curve is steeper for the .NET Framework than for either language. Actually, it would be a simple matter to become fluent in both languages. Nevertheless, there are a few differences between C# and VB .NET as follows:
[edit]
C# advantages

* Explicit interface implementation - an interface implemented in a base class can be reimplemented in a derived class. Of course, this makes the class more obscure in the same way that member hiding does.
* Language support for unsigned types. Unsigned types can be used from VB .NET, but they are not supported by the language itself. This feature is available in VB .NET with Visual Studio 2005.
* Operator overloading. This feature is available in VB.NET with Visual Studio 2005.
* Unsafe code. This allows "pointer arithmetic", etc., and may improve performance in some situations. But, unsafe code circumvents most of the normal safety of features of C#. However, unsafe code is still managed code in a sense, i.e. it is compiled to IL, JITted, and run within the Common Language Runtime (CLR).
* using statement which makes unmanaged resource disposal simple. (Available in VB.NET with Visual Studio 2005.)
* Volatile variables.
* XML documentation generated from source code comments. This feature is available in VB.NET with Visual Studio 2005.

[edit]
Visual Basic.NET advantages

* Catch-When clauses allow exception filtering based upon runtime expressions in addition to by type.
* Late binding with Option Strict off makes legacy libraries without strongly typed interfaces easier to use; but, compile-time, type safety is not available.
* Named indexers - parameterized properties.
* Optional parameters - sometimes useful for COM interoperability
* Simpler event handling in which a method can declare that it handles an event instead of the handler being set up by code.
* Changing method names when implementing interfaces can cause readability and maintenance problems.
* Source code is compiled in the background by the VB.NET part of Visual Studio .NET. Unfortunately, Visual Studio slows down significantly as projects grow larger.
* Legacy Visual Basic functions - The Microsoft.VisualBasic namespace provides various legacy methods which can be used by other .NET languages using a reference to Microsoft.VisualBasic.dll. However, such methods can be detrimental to performance. Therefore, use them wisely or, perhaps, not at all. Readability is also a factor. The use of VB functions may make the source code easier to read for an old-time VB programmer. But, the code will be harder to read for a programmer trained in other .NET languages.