Tuesday, August 24, 2010

Pull a column value from another list in your site in Sharepoint Portal Server


I have a list of Projects in SharePoint called as "Projects" and list contains following columns:

1. Project Name
2. Project Manager
3. Status

I want to make another list called "Project Milestones" where one of the fields in this list would be the name of the Project from the "Projects" list.
Is there a way to have this be a drop down that points to the "Project Name" field from the "Projects" List?

Of course, yes! We can pull data from other lists to be displayed in our list.

Here is the answer to the question emailed by the user:

1. Add a new column in your "ProjectMilestones" list. This is the list where you want to show data from the other list. This can a document library or a form library, depending on your needs.
2. Name the new column as "ProjectName".
3. Column type should be "Lookup"
4. In the "Get Information From:" drop down under "Optional Settings for
Column", select "Projects" list.
5. In "In this column" drop down, select "Project Name".
6. Click OK.



This newly added field will display project names from the "Projects" list.

Let's talk about the lookup field a bit. Lookup field refers to values from a field in another list as you saw above. It's a great way of linking two lists together. You can easily pull column values from different lists already available in your site. If you are a programmer like me, then you may want to look at the way how we can add a lookup field to the form programmatically. Here is the code:

SPSite site = SPControl.GetContextSite(Context);
SPFieldCollection fields = site.AllWebs["mysite"].Lists["mylist"].Fields;

SPList lookupList = site.AllWebs["mysite"].Lists["mylookuplist"];

Guid lkListID = lookupList.ID;

fields.AddLookup("Lookup_FieldName", lkListID, true);

If you work regularly with SharePoint, then you will find this tip to be very helpful.

Calculated column Formula- sharepoint

You can use the following examples in calculated columns. Examples that do not include column references can be used to specify the default value of a column.
Conditional formulas
Check if a number is greater than or less than another number
Use the IF function to do this task.
Column1 Column2 Formula Description
15000 9000 =Column1>Column2 Is Column1 greater than Column2? (Yes)
15000 9000 =IF(Column1<=Column2, "OK", "Not OK") Is Column1 less than or equal to Column2? (Not OK)
Return a logical value after comparing column contents
For a result that is a logical value (Yes or No), use the AND, OR, and NOT functions.
Column1 Column2 Column3 Formula Description
15 9 8 =AND(Column1>Column2, Column115 9 8 =OR(Column1>Column2, Column115 9 8 =NOT(Column1+Column2=24) Is 15 plus 9 not equal to 24? (No)
For a result that is another calculation, or any other value other than Yes or No, use the IF, AND, and OR functions.
Column1 Column2 Column3 Formula Description
15 9 8 =IF(Column1=15, "OK", "Not OK") If the value in Column1 equals 15, then return "OK". (OK)
15 9 8 =IF(AND(Column1>Column2, Column115 9 8 =IF(OR(Column1>Column2, Column1Display zeroes as blanks or dashes
Use the IF function to do this task.
Column1 Column2 Formula Description
10 10 =Column1-Column2 Second number subtracted from the first (0)
15 9 =IF(Column1-Column2,"-",Column1-Column2) Returns a dash when the value is zero (-)
Date and time formulas
Add dates
To add a number of days to a date, use the addition (+) operator. Note that when manipulating dates, the return type of the calculated column must be set to Date and Time.
Column1 Column2 Formula Description
6/9/2007 3 =Column1+Column2 Add 3 days to 6/9/2007 (6/12/2007)
12/10/2008 54 =Column1+Column2 Add 54 days to 12/10/2008 (2/2/2009)
To add a number of months to a date, use the DATE, YEAR, MONTH, and DAY functions.
Column1 Column2 Formula Description
6/9/2007 3 =DATE(YEAR(Column1),MONTH(Column1)+Column2,DAY(Column1)) Add 3 months to 6/9/2007 (9/9/2007)
12/10/2008 25 =DATE(YEAR(Column1),MONTH(Column1)+Column2,DAY(Column1)) Add 25 months to 12/10/2008 (1/10/2011)
To add a number of years to a date, use the DATE, YEAR, MONTH, and DAY functions.
Column1 Column2 Formula Description
6/9/2007 3 =DATE(YEAR(Column1)+Column2,MONTH(Column1),DAY(Column1)) Add 3 years to 6/9/2007 (6/9/2010)
12/10/2008 25 =DATE(YEAR(Column1)+Column2,MONTH(Column1),DAY(Column1)) Add 25 years to 12/10/2008 (12/10/2033)
To add a combination of days, months, and years to a date, use the DATE, YEAR, MONTH, and DAY functions.
Column1 Formula Description
6/9/2007 =DATE(YEAR(Column1)+3,MONTH(Column1)+1,DAY(Column1)+5) Add 3 years, 1 month, and 5 days to 6/9/2007 (1/14/2009)
12/10/2008 =DATE(YEAR(Column1)+1,MONTH(Column1)+7,DAY(Column1)+5) Add 1 year, 7 months, and 5 days to 6/9/2007 (7/15/2010)
Calculate the difference between two dates
Use the DATEDIF function to do this task.
Column1 Column2 Formula Description
01-Jan-1995 15-Jun-1999 =DATEDIF(Column1, Column2,"d") Return the number of days between the two dates (1626)
01-Jan-1995 15-Jun-1999 =DATEDIF(Column1, Column2,"ym") Return the number of months between the dates, ignoring the year part (5)
01-Jan-1995 15-Jun-1999 =DATEDIF(Column1, Column2,"yd") Return the number of days between the dates, ignoring the year part (165)
Calculate the difference between two times
For presenting the result in the standard time format (hours:minutes:seconds), use the subtraction operator (-) and the TEXT function. For this method to work, hours must not exceed 24, and minutes and seconds must not exceed 60.
Column1 Column2 Formula Description
06/09/2007 10:35 AM 06/09/2007 3:30 PM =TEXT(Column2-Column1,"h") Hours between two times (4)
06/09/2007 10:35 AM 06/09/2007 3:30 PM =TEXT(Column2-Column1,"h:mm") Hours and minutes between two times (4:55)
06/09/2007 10:35 AM 06/09/2007 3:30 PM =TEXT(Column2-Column1,"h:mm:ss") Hours,minutes, and seconds between two times (4:55:00)
For presenting the result in a total based on one time unit, use the INT function, or HOUR, MINUTE, and SECOND functions.
Column1 Column2 Formula Description
06/09/2007 10:35 AM 06/10/2007 3:30 PM =INT((Column2-Column1)*24) Total hours between two times (28)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =INT((Column2-Column1)*1440) Total minutes between two times (1735)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =INT((Column2-Column1)*86400) Total seconds between two times (104100)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =HOUR(Column2-Column1) Hours between two times, when the difference does not exceed 24. (4)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =MINUTE(Column2-Column1) Minutes between two times, when the difference does not exceed 60. (55)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =SECOND(Column2-Column1) Seconds between two times, when the difference does not exceed 60. (0)
Convert times
To convert hours from standard time format to a decimal number, use the INT function.
Column1 Formula Description
10:35 AM =(Column1-INT(Column1))*24 Number of hours since 12:00 AM (10.583333)
12:15 PM =(Column1-INT(Column1))*24 Number of hours since 12:00 AM (12.25)
To convert hours from a decimal number to the standard time format (hours:minutes:seconds), use the divisor operator and the TEXT function.
Column1 Formula Description
23:58 =TEXT(Column1/24, "hh:mm:ss") Hours, minutes, and seconds since 12:00 AM (00:59:55)
2:06 =TEXT(Column1/24, "h:mm") Hours and minutes since 12:00 AM (0:05)
Insert Julian dates
The phrase "Julian date" is sometimes used to refer to a date format that is a combination of the current year, and the number of days since the beginning of the year. For example, January 1, 2007 is represented as 2007001 and December 31, 2007 is represented as 2003356. This format is not based on the Julian calendar.
To convert a date to a Julian date, use the TEXT and DATEVALUE functions.
Column1 Formula Description
6/23/2007 =TEXT(Column1,"yy")&TEXT((Column1-DATEVALUE("1/1/"& TEXT(Column1,"yy"))+1),"000") Date in "Julian" format, with a two-digit year (07174)
6/23/2007 =TEXT(Column1,"yyyy")&TEXT((Column1-DATEVALUE("1/1/"&TEXT(Column1,"yy"))+1),"000") Date in "Julian" format, with a four-digit year (2007174)
To convert a date to a Julian date used in astronomy, use the constant 2415018.50. This formula only works for dates after 3/1/1901, and if you are using the 1900 date system.
Column1 Formula Description
6/23/2007 =Column1+2415018.50 Date in "Julian" format, used in astronomy (2454274.50)
Show dates as the day of the week
To convert dates to the text for the day of the week, use the TEXT and WEEKDAY functions.
Column1 Formula Description
19-Feb-2007 =TEXT(WEEKDAY(Column1), "dddd") Calculates the day of the week for the date and returns the full name of the day (Monday)
3-Jan-2008 =TEXT(WEEKDAY(Column1), "ddd") Calculates the day of the week for the date and returns the abbreviated name of the day (Thu)
Math formulas
Add numbers
To add numbers in two or more columns in a row, use the addition operator (+) or the SUM function.
Column1 Column2 Column3 Formula Description
6 5 4 =Column1+Column2+Column3 Add the values in the first three columns (15)
6 5 4 =SUM(Column1,Column2,Column3) Add the values in the first three columns (15)
6 5 4 =SUM(IF(Column1>Column2, Column1-Column2, 10), Column3) If Column1 is greater than Column2, add the difference and Column3. Else add 10 and Column3. (5)
Subtract numbers
Use the subtraction (-) operator to do this task.
Column1 Column2 Column3 Formula Description
15000 9000 -8000 =Column1-Column2 Subtract 9000 from 15000 (6000)
15000 9000 -8000 =SUM(Column1, Column2, Column3) Add numbers in the first three columns, including negative values (16000)
Calculate the difference between two numbers as a percentage
Use the subtraction (-) and division (/) operators, and the ABS function.
Column1 Column2 Formula Description
2342 2500 =(Column2-Column1)/ABS(Column1) Percentage change (6.75% or 0.06746)
Multiply numbers
Use the multipliation (*) operator or the PRODUCT function to do this task.
Column1 Column2 Formula Description
5 2 =Column1*Column2 Multiplies the numbers in the first two columns (10)
5 2 =PRODUCT(Column1, Column2) Multiplies the numbers in the first two columns (10)
5 2 =PRODUCT(Column1,Column2,2) Multiplies the numbers in the first two columns and the number 2 (20)
Divide numbers
Use the division operator (/) to do this task.
Column1 Column2 Formula Description
15000 12 =Column1/Column2 Divides 15000 by 12 (1250)
15000 12 =(Column1+10000)/Column2 Adds 15000 and 10000, and then divides the total by 12 (2,083)
Calculate the average of numbers
The average is also called the mean. To calculate the average of numbers in two or more columns in a row, use the AVERAGE function.
Column1 Column2 Column3 Formula Description
6 5 4 =AVERAGE(Column1, Column2,Column3) Average of the numbers in the first three columns (5)
6 5 4 =AVERAGE(IF(Column1>Column2, Column1-Column2, 10), Column3) If Column1 is greater than Column, calculate the average of the difference and Column3. Else calculate the average of the value 10 and Column3. (2.5)
Calculate the median of numbers
The median is the value at the center of an ordered range of numbers. Use the MEDIAN function to calculate the median of a group of numbers.
A B C D E F Formula Description
10 7 9 27 0 4 =MEDIAN(A, B, C, D, E, F) Median of numbers in the first 6 columns (8)
Calculate the smallest or largest number in a range
To calculate the smallest or largest number in two or more columns in a row, use the MIN and MAX functions.
Column1 Column2 Column3 Formula Description
10 7 9 =MIN(Column1, Column2, Column3) Smallest number (7)
10 7 9 =MAX(Column1, Column2, Column3) Largest number (10)
Count values
To count numeric values, use the COUNT function.
Column1 Column2 Column3 Formula Description
Apple 12/12/2007 =COUNT(Column1, Column2, Column3) Counts the number of columns that contain numeric values. Excludes date and time, text, and null values.(0)
12 #DIV/0! 1.01 =COUNT(Column1, Column2, Column3) Counts the number of columns that contain numeric values, but excludes error and logical values (2)
Increase or decrease a number by a percentage
Use the percentage (%) operator to do this task.
Column1 Column2 Formula Description
23 3% =Column1*(1+5%) Increases number in Column1 by 5% (24.15)
23 3% =Column1*(1+Column2) Increase number in Column1 by the percent value in Column2: 3% (23.69)
23 3% =Column1*(1-Column2) Decrease number in Column1 by the percent value in Column2: 3% (22.31)
Raise a number to a power
Use the exponent (^) operator or the POWER function to do this task.
Column1 Column2 Formula Description
5 2 =Column1^Column2 Calculates five squared (25)
5 3 =POWER(Column1, Column2) Calculates five cubed (125)
Round a number
To round up a number, use the ROUNDUP, ODD, and EVEN functions.
Column1 Formula Description
20.3 =ROUNDUP(Column1,0) Rounds 20.3 up to the nearest whole number (21)
-5.9 =ROUNDUP(Column1,0) Rounds -5.9 up (-6)
12.5493 =ROUNDUP(Column1,2) Rounds 12.5493 up to the nearest hundredth, two decimal places (12.55)
20.3 =EVEN(Column1) Rounds 20.3 up to the nearest even number (22)
20.3 =ODD(Column1) Rounds 20.3 up to the nearest odd number (21)
To round down a number, use the ROUNDDOWN function.
Column1 Formula Description
20.3 =ROUNDDOWN(Column1,0) Rounds 20.3 down to the nearest whole number (20)
-5.9 =ROUNDDOWN(Column1,0) Rounds -5.9 down (-5)
12.5493 =ROUNDDOWN(Column1,2) Rounds 12.5493 down to the nearest hundredth, two decimal places (12.54)
To round a number to the nearest number or fraction, use the ROUND function.
Column1 Formula Description
20.3 =ROUND(Column1,0) Rounds 20.3 down, because the fraction part is less than .5 (20)
5.9 =ROUND(Column1,0) Rounds 5.9 up, because the fraction part is greater than .5 (6)
-5.9 =ROUND(Column1,0) Rounds -5.9 down, because the fraction part is less than -.5 (-6)
1.25 =ROUND(Column1, 1) Rounds the number to the nearest tenth (one decimal place). Because the portion to be rounded is 0.05 or greater, the number is rounded up (result: 1.3)
30.452 =ROUND(Column1, 2) Rounds the number to the nearest hundredth (two decimal places). Because the portion to be rounded, 0.002, is less than 0.005, the number is rounded down (result: 30.45)
To round a number to the significant digit above 0, use the ROUND, ROUNDUP, ROUNDDOWN, INT, and LEN functions.
Column1 Formula Description
5492820 =ROUND(Column1,3-LEN(INT(Column1))) Rounds the number to 3 significant digits (5490000)
22230 =ROUNDDOWN(Column1,3-LEN(INT(Column1))) Rounds the bottom number down to 3 significant digits (22200)
5492820 =ROUNDUP(Column1, 5-LEN(INT(Column1))) Rounds the top number up to 5 significant digits (5492900)
Text formulas
Change the case of text
Use the UPPER, LOWER, or PROPER functions to do this task.
Column1 Formula Description
nancy Davolio =UPPER(Column1) Changes text to uppercase (NANCY DAVOLIO)
nancy Davolio =LOWER(Column1) Changes text to lowercase (nancy davolio)
nancy Davolio =PROPER(Column1) Changes text to title case (Nancy Davolio)
Combine first and last names
Use the ampersand (&) operator or the CONCATENATE function to do this task.
Column1 Column2 Formula Description
Nancy Fuller =Column1&Column2 Combines the two strings (NancyFuller)
Nancy Fuller =Column1&" "&Column2 Combines the two strings, separated by a space (Nancy Fuller)
Nancy Fuller =Column2&","&Column1 Combines the two strings, separated by a comma (Fuller,Nancy)
Nancy Fuller =CONCATENATE(Column2, ",", Column1) Combines the two strings, separated by a comma (Fuller,Nancy)
Combine text and numbers from different columns
Use the CONCATENATE and TEXT functions, and the ampersand (&) operator to do this task.
Column1 Column2 Formula Description
Buchanan 28 =Column1&" sold "&Column2&" units." Combines contents above into a phrase (Buchanan sold 28 units)
Dodsworth 40% =Column1&" sold "&TEXT(Column2,"0%")&" of the total sales." Combines contents above into a phrase (Dodsworth sold 40% of the total sales).
Note The TEXT function appends the formatted value of Column2 instead of the underlying value, which is .4.
Buchanan 28 =CONCATENATE(Column1," sold ",Column2," units.") Combines contents above into a phrase (Buchanan sold 28 units)
Combine text with a date or time
Use the TEXT function and the ampersand (&) operator to do this task.
Column1 Column2 Formula Description
Billing Date 5-Jun-2007 ="Statement date: "&TEXT(Column2, "d-mmm-yyyy") Combine text with a date (Statement date: 5-Jun-2007)
Billing Date 5-Jun-2007 =Column1&" "&TEXT(Column2, "mmm-dd-yyyy") Combine text and date from difference columns into one column (Billing Date Jun-05-2007)
Compare column contents
To compare one column to another column or a list of values, use the EXACT function.
Column1 Column2 Formula Description
BD122 BD123 =EXACT(Column1,Column2) Compare contents of first two columns (No)
BD122 BD123 =EXACT(Column1,"BD122") Compare contents of Column1 and the string "BD122" (Yes)
Check if a column value or a part of it matches specific text
To check if a column value or a part of it matches specific text, use the IF, FIND, SEARCH, and ISNUMBer functions.
Column1 Formula Description
Davolio =IF(Column1="Davolio", "OK", "Not OK") Checks to see if Column1 is Davolio (OK)
Davolio =IF(ISNUMBER(FIND("v",Column1)), "OK", "Not OK") Checks to see if Column1 contains the letter v (OK)
BD123 =ISNUMBER(FIND("BD",Column1)) Checks to see if Column1 contains BD (Yes)
Count nonblank columns
Use the COUNTA function to do this task.
Column1 Column2 Column3 Formula Description
Sales 19 =COUNTA(Column1, Column2) Counts the number of nonblank columns (2)
Sales 19 =COUNTA(Column1, Column2, Column3) Counts the number of nonblank columns (2)
Remove characters from text
Use the LEN, LEFT, and RIGHT functions to do this task.
Column1 Formula Description
Vitamin A =LEFT(Column1,LEN(Column1)-2) Return 7 (9-2) characters, starting from left (Vitamin)
Vitamin B1 =RIGHT(Column1, LEN(Column1)-8) Return 2 (10-8) characters, starting from right (B1)
Remove spaces from the beginning and end of a column
Use the TRIM function to do this task.
Column1 Formula Description
Hello there! =TRIM(Column1) Remove the spaces from the beginning and end (Hello there!)
Repeat a characater in a column
Use the REPT function to do this task.
Formula Description
=REPT(".",3) Repeats a period 3 times (...)
=REPT("-",10) Repeats a dash 10 times (----------)
Other formulas
Hide error values in columns
To display a dash, #N/A, or NA in place of an error value, use the ISERROR function.
Column1 Column2 Formula Description
10 0 =Column1/Column2 Results in an error (#DIV/0)
10 0 =IF(ISERROR(Column1/Column2),"NA",Column1/Column2) Returns NA when the value is an error
10 0 =IF(ISERROR(Column1/Column2),"-",Column1/Column2) Returns a dash when the value is an error
Did this article help you?

Saturday, August 21, 2010

Friday, August 6, 2010

ASP >NET FREE WEB HOSTING SITE

http://www.websamba.com 30
http://www.cfm-resources.com 30
http://www.brinkster.com 30
http://www.7host.com 50
http://www.maxipointservers.net 20
http://www.ionwd.com ?
http://www.1asphost.com 100
http://www.everanet.com ?

Wednesday, July 21, 2010

Tuesday, July 20, 2010

MSDN SHAREPOINT PART FOR U

http://msdn.microsoft.com/hi-in/office/cc990283(en-us).aspx

Creating a Contact Form Web Part for SharePoint

http://www.cinlogic.com/Articles/2/Creating-a-Contact-Form-Web-Part-For-SharePoint.aspx

Introduction
SharePoint is a powerful application that enables an organization to quickly implement a web based portal for managing and sharing information among groups of people. Out of the box it offers many components such as document libraries and configurable lists. For more advanced requirements, SharePoint provides the ability to create web parts, which are custom components that can plug into and interact with a SharePoint site. Web parts are a simple, yet powerful way to extend the capabilities of SharePoint to meet your organization’s unique requirements.

This article will show, step-by-step, how to create a simple SharePoint web part that implements a contact form. A contact form is typically used on a public website to provide a way for customers, business partners, and others outside the company to submit questions or request information by filling out fields on a web page and clicking a submit button. This web part will collect the user’s name, email address, phone number, and message, and send the information to an email address when the user clicks Submit.



Requirements
The web part created in this article will use Windows SharePoint Services (WSS) 3.0. It will also work with MOSS 2007, which is a more advanced version of SharePoint built on the same infrastructure as WSS 3.0. To create the web part, we will be using Visual Studio 2008 installed on Windows Server 2003, along with Windows SharePoint Services 3.0 Tools: Visual Studio 2008 Extensions, Version 1.2, which is a free download from the Microsoft Download Center.

Creating a Web Part Project
The first step is to create a new web part project using Visual Studio 2008. To do this, open Visual Studio 2008 and choose New – Project from the file menu. Select Visual C# - SharePoint from the Project Type List, and select the Web Part template from the list on the right. Enter ContactFormWebPart as the name and the solution name and choose a directory where you want the solution files to be saved. When you click OK, an empty web part project will be created and opened in Visual Studio.

The empty project has one web part, called WebPart1, but this isn’t what we want to call our web part, so the first step is to delete WebPart1 from the project by right clicking on the WebPart1 folder in Solution Explorer in Visual Studio and choosing Delete.

Next, let's add a new web part to the project, called ContactForm. Right click on the ContactFormWebPart project in solution explorer, and choose Add – New Item from the context menu. Select SharePoint from the categories list, and Web Part from the templates list. Enter ContactForm for the name and click Add.



This gives you a new source file called ContactForm.cs that has an empty class inheriting from WebPart with some TODO comments. In the next section, we are going to replace the CreateChildControls() function and add some additional code to this class.



Adding Code to Create the Controls
Now we are ready to begin writing code that will display the web part. Open ContactForm.cs and you will see a function called CreateChildControls(). This function is where we will add labels, textboxes, and a button to allow the user to interact with our web part.

But first, let's create some class-level variables for the controls that we will create. Declaring them at the class level as opposed to within the CreateChildControls() function will allow us to reference these controls from the button event handler later on.


TextBox txtContactName;
TextBox txtEmailAddress;
TextBox txtPhone;
TextBox txtMessage;
Button btnSendMessage;
Label lblMessageSent;

Now lets add the code to CreateChildControls to build the display. In order to keep it simple, an HTML table will be used to align the controls in a consistent manner. Each table row will have two cells: One for the field label and the other for the text boxes. Controls are created one at a time and added to a table cell, which is then added to a table row.


protected override void CreateChildControls()
{
base.CreateChildControls();

Table t;
TableRow tr;
TableCell tc;

// A table that is used to layout the controls
t = new Table();

// Label with instructions for the user
tr = new TableRow();
tc = new TableCell();
tc.ColumnSpan = 2;
tc.VerticalAlign = VerticalAlign.Top;
Label lblInstructions = new Label();
lblInstructions.Text = "Please enter your contact information and message below.";
tc.Controls.Add(lblInstructions);
tr.Controls.Add(tc);

t.Controls.Add(tr);

// Contact Name label
tr = new TableRow();
tc = new TableCell();
tc.Style["padding-top"] = "7px";
tc.VerticalAlign = VerticalAlign.Top;
Label lblContactName = new Label();
lblContactName.Text = "Name:";
tc.Controls.Add(lblContactName);
tr.Controls.Add(tc);

// Contact Name textbox
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
txtContactName = new TextBox();
txtContactName.ID = "txtContactName";
txtContactName.Width = Unit.Pixel(300);
tc.Controls.Add(txtContactName);
tr.Controls.Add(tc);

t.Controls.Add(tr);

// Email Address label
tr = new TableRow();
tc = new TableCell();
tc.Style["padding-top"] = "7px";
tc.VerticalAlign = VerticalAlign.Top;
Label lblEmailAddress = new Label();
lblEmailAddress.Text = "Email Address:";
tc.Controls.Add(lblEmailAddress);
tr.Controls.Add(tc);

// Email Address textbox
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
txtEmailAddress = new TextBox();
txtEmailAddress.ID = "txtEmailAddress";
txtEmailAddress.Width = Unit.Pixel(300);
tc.Controls.Add(txtEmailAddress);
tr.Controls.Add(tc);

t.Controls.Add(tr);

// Phone Number label
tr = new TableRow();
tc = new TableCell();
tc.Style["padding-top"] = "7px";
tc.VerticalAlign = VerticalAlign.Top;
Label lblPhone = new Label();
lblPhone.Text = "Phone Number:";
tc.Controls.Add(lblPhone);
tr.Controls.Add(tc);

// Phone Number textbox
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
txtPhone = new TextBox();
txtPhone.ID = "txtPhone";
txtPhone.Width = Unit.Pixel(300);
tc.Controls.Add(txtPhone);
tr.Controls.Add(tc);

t.Controls.Add(tr);

// Message label
tr = new TableRow();
tc = new TableCell();
tc.Style["padding-top"] = "7px";
tc.VerticalAlign = VerticalAlign.Top;
Label lblMessage = new Label();
lblMessage.Text = "Message:";
tc.Controls.Add(lblMessage);
tr.Controls.Add(tc);

// Message textbox
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
txtMessage = new TextBox();
txtMessage.ID = "txtMessage";
txtMessage.Height = Unit.Pixel(100);
txtMessage.Width = Unit.Pixel(400);
txtMessage.TextMode = TextBoxMode.MultiLine;
txtMessage.Wrap = true;
tc.Controls.Add(txtMessage);
tr.Controls.Add(tc);

t.Controls.Add(tr);

// Empty table cell
tr = new TableRow();
tc = new TableCell();
tr.Controls.Add(tc);

// Label for telling the user the message was sent
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
lblMessageSent = new Label();
lblMessageSent.Text = "Your message has been sent. Thank you.";
lblMessageSent.Font.Bold = true;
lblMessageSent.Visible = false;
tc.Controls.Add(lblMessageSent);
tr.Controls.Add(tc);

t.Controls.Add(tr);

// Empty table cell
tr = new TableRow();
tc = new TableCell();
tr.Controls.Add(tc);

// Send Message button
tc = new TableCell();
btnSendMessage = new Button();
btnSendMessage.Text = "Send Message";
btnSendMessage.Click += new EventHandler(btnSendMessage_Click);
tc.Controls.Add(btnSendMessage);
tr.Controls.Add(tc);

t.Controls.Add(tr);

this.Controls.Add(t);
}

Finally, we need to add an event handler to send the message as an email when the Send Message button is clicked by the user. In the code above, the event handler was already wired up with the line btnSendMessage.Click += new EventHandler btnSendMessage_Click);, so now we just need to create the btnSendMessage_Click function. This function simply builds an email message using text that was entered into the text boxes, and sends the email using SharePoint's SPUtility.SendEmail() function.

You will need to change the "to" and "from" fields in the message header for your specific situation. The "to" field specifies where the email will be sent, and the "from" field is the email address that the email should appear to be from. The "from" field isn't too important, but some mail servers may require this to be a valid email address.


protected void btnSendMessage_Click(object sender, EventArgs e)
{
// Build the email subject string
System.Text.StringBuilder subject = new System.Text.StringBuilder();
subject.Append("Contact Form Message from ");
subject.Append(txtContactName.Text);

// Build the email message string
System.Text.StringBuilder message = new System.Text.StringBuilder();
message.Append("Contact Name: ");
message.AppendLine(txtContactName.Text);
message.Append("Email Address: ");
message.AppendLine(txtEmailAddress.Text);
message.Append("Phone: ");
message.AppendLine(txtPhone.Text);
message.AppendLine();
message.AppendLine("Message:");
message.AppendLine(txtMessage.Text);

// Construct the message header
System.Collections.Specialized.StringDictionary messageHeader =
new System.Collections.Specialized.StringDictionary();
messageHeader.Add("to", "CustomerService@example.com"); // TODO: Where to send the email
messageHeader.Add("from", "ContactForm@example.com"); // TODO: Who the email should be "from"
messageHeader.Add("subject", subject.ToString());
messageHeader.Add("content-type", "text/plain");

// Send the email
Microsoft.SharePoint.Utilities.SPUtility.SendEmail(
SPContext.Current.Web, messageHeader, message.ToString());

// Let the user know the message was sent
lblMessageSent.Visible = true;

// Clear out the input fields
txtContactName.Text = "";
txtEmailAddress.Text = "";
txtPhone.Text = "";
txtMessage.Text = "";
}

Testing the Web Part
Now we are ready to test the web part. The easiest way to do this is to choose Deploy Solution from the Build menu in Visual Studio 2008. After it has built and deployed successfully, open a web browser and navigate to the SharePoint website. From the Site Actions menu, choose Edit Page. This will place the page into Edit Mode, where web parts can be added, removed, and configured.

For testing purposes, we don't care about the exact placement of the web part, so just click Add a Web Part in the main left zone. This will open up a Dialog box listing all of the web parts that are available for use on this SharePoint server. If you scroll down the list, you should see the ContactForm web part. Put a checkbox next to this web part and click the Add button.



You should now see the contact form displayed on the page. While still in Edit Mode, you can change other settings such as the title that is displayed above the web part, or the height and width. For testing we are going to leave everything as the default, so just click the Exit Edit Mode button. The page will now show the contact form and we are ready to test it. Enter a name, email address, phone number, and message, and click Send Message. If all is successful, you will see a message saying your message has been sent and within a few minutes receive the email that was generated by btnSendMessage_Click().



Checking the Outgoing E-Mail Settings
If your receive an error message when you click Send Message or if the email does not arrive within 5 or 10 minutes, it could be that the outgoing email settings have not been configured in SharePoint. This can be done by a SharePoint administrator using the Central Administration website. In Central Administration, go to the Operations tab and select Outgoing E-Mail Settings. Make sure the Outbound SMTP Server is configured with the name of the mail server.



Deploying the Web Part
Once you have tested the web part, it is ready to be deployed as a solution to the production SharePoint server. For this we will create a SharePoint solution package, which is a .cab file that has a .wsp extension. The .wsp file is created automatically when you choose Deploy from within Visual studio. Change the active configuration in Visual Studio from Debug to Release, and then choose Deploy Solution from the Build menu.

After it has successfully deployed the release version to your local SharePoint server, there will be a file called ContactFormWebPart.wsp in the /bin/Release subfolder of your project directory. Copy this file to a folder on your production SharePoint web server, or to a location that can be accessed from this server. Then, run the following commands from a command prompt on the production SharePoint web server. These commands will add the solution to SharePoint and then deploy the solution, making it available for use by all sites.


C:\>stsadm -o addsolution -filename ContactFormWebPart.wsp


C:\>stsadm -o deploysolution -name ContactFormWebPart.wsp -immediate -allowgacdeployment -allcontenturls

Now the web part is available for use on the production SharePoint server. Only one more thing is left to do. When you want to use it in a SharePoint site, you will need to add it to that site's web part gallery. To do this, navigate to your SharePoint site and go to Site Actions - Site Settings. Then clicking on the Web Parts link under the Galleries section. This opens up a web page listing the web parts that are currently available for this site. Click New to add a new web part to the list. The next web page shows the deployed web parts. Check the box next to ContactFormWebPart.ContactForm and then click the Populate Gallery button.

You should now see the Contact Form Web Part in the list of web parts in this site's gallery. Once the web part is in the gallery, you can edit a page in the site, and add the web part to the page, just as we did during testing.

Additional Improvements
There are some improvements that can be made to the Contact Form Web Part that we've created, but these are beyond the scope of this article. Here are some ideas for improving the Contact Form Web Part:

First, we could add validation to the fields to make sure that the required fields are filled in and that the data entered matches the expected format. For example, contact Name should be required, Message should be required, the email address should match the typical format of an email address, and the phone number should be in the format of a valid phone number.

Second, we could add properties to the web part to allow customization of the label text and the to and from addresses used for sending the email. These properties would allow changes to be made to the web part's appearance while editing the page in SharePoint instead of requiring those changes to be made in the source code.

Other Thoughts
Web parts can be created using Visual Studio 2005, but Visual Studio 2008 in conjunction with the downloadable extensions for WSS 3.0 make packaging and deploying your web part much easier. I highly recommend using Visual Studio 2008 for web part development if possible.

In order to use the WSS extensions for Visual Studio 2008, the development environment needs to run on a SharePoint server. But many developers use a client operating system for their development instead of a server operating system, which is required by SharePoint. This is where Microsoft Virtual PC can really be helpful. Virtual PC will allow you to run another computer instance virtually, on your development PC, so you can create a Virtual PC image for your SharePoint web part development environment.

If you are new to web part development and want to try it out without the work of setting up a full SharePoint environment, Microsoft provides a Windows SharePoint Services 3.0 SP1 Developer Evaluation VPC Image that has WSS 3.0, Visual Studio, and the extensions already installed. You can use this with Virtual PC for an "instant" SharePoint environment.

Conclusion
In this article you learned how to create a simple web part for SharePoint that implements a contact form that collects information and sends it as an email to a recipient. There are many more possibilities for the use of web parts, including communicating with other web parts in SharePoint and integrating with external databases and applications. The ability of SharePoint to use custom web parts is a powerful feature that can be used to extend the functionality of SharePoint beyond what is possible with basic customization.

Monday, July 5, 2010

Share Point Custmize Vidio

http://www.sharepointhostingprovider.com/sharepoint-tutorials/
http://blogs.sharepointhosting.com/Downloads/SharePoint-Tutorials.aspx
http://blog.sharepointhosting.com/Lists/SharePoint%20Tutorials/Screencast%20Tutorials.aspx

Monday, June 28, 2010

Sharepoint WORKFLOW

The majority of workflows involve a person in the process at some point. SharePoint is ideal for this. There are other types, such as ‘system’ workflows which pass messages between disparate systems, and there are specific tools to manage these, such as Microsoft BizTalk Server.
If you have purchased the enterprise SharePoint product Microsoft Office SharePoint Server (MOSS) 2007 then you will have seen that there are several workflows included , such as ‘Approval’, ‘Collect Feedback’, ‘Collect Signatures’ . However, at some point you are going to have to create and customise your own workflow. Fortunately, Microsoft has now provided you with Microsoft Office SharePoint Designer, which is a free product and makes this task simple and productive. To follow through the examples in this article you will need to download a copy of SharePoint Designer from Microsoft’s website.
You can customise SharePoint sites with SharePoint Designer. This is a tool for designing and developing custom workflows that then allows you to and attach these to your lists and libraries. This is done with a very simple wizard-like interface. Once you understand the concepts of creating workflow in this manner you will be surprised by what can be achieved without the need to turn to custom code and Visual Studio.
The easiest way of introducing workflow in SharePoint is to show you a simple example that makes small calculations and changes. This is slightly artificial because SharePoint also provides us with EventReceivers which are much better for small changes based upon an add/edit/delete within a list. The example used in this article would actually lend itself to an EventReceiver rather than a workflow, but serves to show the principles. To get things up and running quickly, I am going to add a custom workflow to the example begun in the first article in this series.
Planning a workflow
We are going to develop a simple workflow to manage the stock of our products and to alert a stock controller that we need more inventory when it runs short. In order to do this I have added a new column to the Products list called Inventory and set it to 500 for all our products.

Before we can begin designing this workflow, we must plan out exactly what it will do. The easiest way to do this is to draw out a flowchart-type diagram representing the process. Now you could go to town on this and use Microsoft Visio or some other drawing tool, but a simple hand drawn sketch is just as good, as long as you have an accurate idea of what your workflow needs to do. Below is a sketch of our workflow (please excuse my handwriting).

Once you have planned out your process then you need to design this in SharePoint Designer.
Creating a basic workflow
We need to attach our workflow to the Orders list so that the inventory is updated every time a new order is made.
To create a new custom workflow:
• Open SharePoint Designer.
• Select File > Open Site
• In the Site name: text box enter the full URL to your site.
• Click Open
• Select File > New > Workflow
At this point SharePoint Designer needs to retrieve some information from your site so this may take a few seconds.
You are now presented with the workflow designer. This is the main interface that you will use to create and modify your workflows. It is designed to work in stages.
• In the workflow designer type a name in the box labelled ‘Give a name to this workflow:’
• Select the Orders list from the drop down menu labelled ‘What SharePoint list should this workflow be attached to?’
• Within the options labelled ‘Select workflow start options for items in Orders:’ ensure that the checkbox labelled ‘Automatically start this workflow when a new item is created’ is checked, but none of the others.

• Click Next
You are now in a position to create a series of steps for this workflow. Each step consists of a number of lists of actions which can be executed depending upon a condition. Conditions can be selected from the list shown below. If none are specified then the actions listed will be executed regardless.

In your example you simply want to update the Inventory column for every new order so there is no condition to meet. However this is a powerful area of workflow and its worth exploring some of these different conditions.
• In the ‘Step Name’ box enter a name that indicates what this step will do. I have used ‘Update Inventory’
• Under Actions select ‘More Actions…’
• You should now see the workflow actions dialog. This will allow you to choose from a range of possible actions to perform within this workflow. If you select All Actions from the Select a Category drop down menu then you should see all available workflow actions.

• As per our workflow diagram we need to get the quantity field from our order into a variable. This is done using the ‘Set Workflow Variable’ action. So select this from the Choose an Action list, and click Add.
• You will notice that our action is represented by a sentence within the actions of this workflow step. This sentence contains links which enable you to configure the variables assigned to the action.

• Click on ‘workflow variable’ and select Create a new variable.

• In the Name box type ‘OrderQuantity’ and select Number from the Type drop down menu.
• Click OK
• In the actions list select the value link within our action.

• Now select the fx button in order to lookup a value.

• Leave Source set to Current Item
• Select Quantity in the Field drop down menu.
• You need to perform a calculation based on this, so click on Actions and select ‘Do Calculation’ you may need to select the More Actions option to find this action.
• There are three properties to set on this action so click the first ‘value’ and select the fx button.
• You need to look up the inventory of the purchased product from the Products list, so select Product in the Source drop down menu.

• Select Inventory in the Field drop down menu.
We have two additional options in this dialog now to allow us to identify the item in the products list that we want to get this value for. This type of operation is common within workflows in SharePoint so you should take some time to understand what is happening here.
Under ‘Find the List Item’ you need to choose a field and value which uniquely identify the product in question. Ideally this would be something like the ID column. However we do not have a method to retrieve the ID of the list item we are interested in, we only have the lookup column on our existing item and that contains the Product Name. However the product name should also be unique so we will use this.
• In the Field drop down menu under ‘Find the List Item’ select Products:ProductName

• Next to the Value box select the fx button to perform a lookup.
• Leave Source as Current Item, but in the Field drop down menu select Product
• Click OK to close the Define Workflow Lookup dialog.
• You will get a notification from SharePoint Designer. This is telling you that your lookup is not guaranteed to return a unique value (because you could enter the same Product Name twice); however in our situation this is acceptable so you can click Yes to continue.

• Click on the ‘plus’ within the action description and select minus.

• Click on the remaining ‘value’ within the action description and select the fx button.
• In the Source drop down menu on the Define Workflow Lookup dialog select Workflow Data.
• In the Field drop down menu select Variable: OrderQuantity

We now have a variable called Calc which contains the updated inventory count for our product. So the remaining part of our workflow is to update the Products list with the new inventory count.
• Under the actions drop down menu select Update List Item.
• Click on ‘this list’ in the action description.
• In the Update List Item dialog select Products from the List drop down menu.

• Click on Add to select a field on this list to update.
• Select Inventory under Set this field
• Click on the fx button to lookup the value.
• In the Source drop down menu on the Define Workflow Lookup dialog select Workflow Data.
• In the Field drop down menu select Variable: calc
• Click OK

• Click OK in the Value Assignment dialog
• You need to use exactly the same settings as you did previously to identify the list item within the Products list.

• Click on OK and click Yes on the warning dialog.
• Finally click Finish on the Workflow Designer dialog.
This workflow is now complete and SharePoint Designer will have attached this to the Orders list for you. If you now go and create an Order for a new Product you will see that the Inventory field on your associated Product list item is updated accordingly.
The purpose of this simple workflow has been to introduce you to the power within workflows and how they can quickly and easily simplify some of the more mundane tasks within your business processes. Now try creating a new workflow to ensure that the Total field for your order is calculated for you based on the Price field of the Products list. This uses the same skills you will have learned from this article and it will help to ‘cement’ this technique in your memory.
Next time I will be looking at how developers can create custom workflows within Visual Studio 2008 and harness the full power of Windows Workflow Foundation.



























Introduction
Workflows are now an integral part for any project. You can build a SharePoint work flow using the available templates, SharePoint designer and Visual Studio 2005 / 2008. This tutorial will mainly concentrate on workflow creation using SharepPoint designer. We will walk through the basic 8 steps needed to create workflows using SharePoint designer.

I have published some videos on SharePoint, WCF, WPF, WWF, design patterns, UML, FPA, Enterprise blocks, etc. You can watch the videos here. You can download my 400 .NET FAQ EBook from here.
8 Steps to Create Workflow using SharePoint Designer
SharePoint designer helps us to create workflows and attach the workflows to a content type like list, document, etc. In other words, SharePoint designer creates workflows and publishes the workflow on the SharePoint server site.

To understand it better, we will build a simple workflow of completed and incomplete tasks. We will create two lists, one is the incomplete tasks and the other the completed tasks. The workflow will flow something like this:
• User will create a task and enter the status of the task.
• If the task is incomplete, nothing will happen.
• Once the task is marked as complete, the task will be copied from incomplete task list to completed task list.
• The task will be deleted from the incomplete task list.

So let’s understand the eight important steps we will need to create the above workflow using SharePoint designer.
Step 1
Create a team site using the SharePoint team site template.
Step 2
Create two task lists, one is incomplete task list and the other completed task list.
To create task list, click on site action -> Create: Add a new library list -> create a task.
Step 3
Start the SharePoint designer.

Step 4
Open the site in your SharePoint designer using click on file -> open site.

Step 5
Go to workflows by clicking on file -> new -> SharePoint content and click ok as shown in the below figure:

Step 6
This is an important step. In this step, we define two important things. The first is this workflow will be attached to which list. Currently we have attached the workflow to incomplete tasks list. Second we need to define the events on which the workflow should be activated. For the current scenario, we have considered two events; one when the item is created and the second when the item is updated.

Step 7
This is one more crucial step where we need to define on what condition the workflow will execute and what action should take place if the condition is true. So when a task status is completed, two actions will take place. First the task will be copied from the incomplete task list to the completed task list. Second the task is deleted from the incomplete task list.

Once you click finish, you can see the workflow created in the SharePoint designer. This workflow is also published to the SharePoint server,

You can see if the workflow is associated with the incomplete task list. Go to incomplete tasks -> Settings -> List settings -> Workflow settings. You can see that the workflow is attached to the incomplete task list.

Step 8
Ok, now it’s time to see the workflow in action. So go to incomplete task list and create a task with status completed.

Once you click ok, you see the task for some seconds in the incomplete tasks list and then the task is copied to the completed task list and deleted from the incomplete task list.

Previous SharePoint QuickStart FAQ


















This article will show us how to use the Datalist in a webpart and embedding CSS file and classes in the webpart.

First we are creating the webpart. For that follow the below steps
1. Create a webpart solution
2. Create a child controls and add the related code in webpart cs file like below

DataList dlNews;
Label lblNewsTitle;
protected override void CreateChildControls()
{
// Create and add the controls that compose the
// user interface of the Web Part.
Controls.Clear();
dlNews = new DataList();
//CSS link calling as object
Microsoft.SharePoint.WebControls.CssLink cssLink = new Microsoft.SharePoint.WebControls.CssLink();
cssLink.DefaultUrl = "/_layouts/1033/styles/News.css";
this.Page.Header.Controls.Add(cssLink);
// Create the Datatable
DataTable dtItem = new DataTable();
// send the Data items from this datatable
//News Datalist view
fillResultsDatalist(dtItem);

}
private void fillResultsDatalist(DataTable dtItem)
{
// Create an instance of the DataGrid and set its
// DataSource property to the supplied DataSet.
dlNews = new DataList();
dlNews.DataSource = dtItem;
dlNews.CellPadding = 0;
dlNews.CellSpacing = 0;
dlNews.BorderWidth = 0;
dlNews.RepeatDirection = RepeatDirection.Vertical;
// Calling the Itemplete for data list bound columns
dlNews.ItemTemplate = new DatalistLabelColumn();
// Bind the data to the DataGrid.
dlNews.DataBind();
//Add the DataGrid to the controls.
Controls.Add(dlNews);
}

3. Add/Create the the ITemplate class
///
/// Intialize the Container controls
///

///
public void InstantiateIn(Control container)
{
Label lblNewsTitle = new Label();
lblNewsTitle.DataBinding += new EventHandler(this.BindLabelColumn);
container.Controls.Add(lblNewsTitle);
Label lblNewsText = new Label();
lblNewsText.DataBinding += new EventHandler(this.BindLabelColumn1);
container.Controls.Add(lblNewsText);
LinkButton lnkButton = new LinkButton();
lnkButton.DataBinding += new EventHandler(this.BindLabelColumn2);
container.Controls.Add(lnkButton);
}
///
/// BindLabelColumn for Title of the News
///

///
///
public void BindLabelColumn(object sender, EventArgs e)
{
Label lblTitle = (Label)sender;
DataListItem container = (DataListItem)lblTitle.NamingContainer;
String strVals = Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "Titre"));
lblTitle.Text = "
> " + strVals + "
";
}
///
/// BindLabelColumn1 for news Description label
///

///
///
public void BindLabelColumn1(object sender, EventArgs e)
{
Label lblText = (Label)sender;
DataListItem container = (DataListItem)lblText.NamingContainer;
String strVals = Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "Text"));
strVals = Regex.Replace(strVals, @"<(.\n)*?>", string.Empty);
strVals = RetComments(strVals);
lblText.Text = "
" + strVals + "
";
}
///
/// BindLabelColumn2 for Link button
///

///
///
public void BindLabelColumn2(object sender, EventArgs e)
{
LinkButton lnkButton = (LinkButton)sender;
DataListItem container = (DataListItem)lnkButton.NamingContainer;
String strVals = Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "Link"));
lnkButton.Text = @"
";
lnkButton.PostBackUrl = strVals;
}
///
/// Substring the text upto 60 characters
///

///
///
public string RetComments(string strCompanyName)
{
string sComments = string.Empty;
if (strCompanyName.Length > 50)
{
sComments = strCompanyName.Substring(0, 50).Trim() + "...";
}
else if (strCompanyName.Length == 0)
{
sComments = "--";
}
else
{
sComments = strCompanyName;
}
return sComments;
}

4. Create the CSS page News.css.

.HomeNewsTitle,.HomeNewsSubTitle,.HomeNewsLink,.HomeSeperator,.HomeNewsTitle2,.HomeNewsLink1,.HomeNewsLink2{
font-family: Trebuchet MS;
position: relative;
float: left;
left: 0px;
width: 172px;
}
.HomeNewsTitle,.HomeNewsTitle2{
color: #0099cc;
font-size: 13px;
}
.HomeNewsTitle2{
top:4px;
}
.HomeNewsSubTitle{
color: #333333;
font-size: 12px;
line-height:15px;
}
.HomeNewsLink,.HomeNewsLink1,.HomeNewsLink2{
color: #0099cc;
font-size: 11px;
text-decoration:underline;
text-align:right;
padding-bottom:1px;
}
.HomeNewsLink1{
padding-bottom:10px;
}
.HomeNewsLink2{
bottom:5px;
}

5. Add/Place the CSS file in to below folder
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\STYLES
6. you have to call the Default URL of the CSS file path like "/_layouts/1033/styles/News.css";
Now you can able to use embedded CSS classes and datalist in webpart.

I hope this will be useful for sharepoint developers.


Difference between Server.Transfer and Response.Redirect?

What is the difference between Server.Transfer and Response.Redirect?
Response.Redirect involves a roundtrip to the server whereas Server.Transfer conserves server resources by avoiding the roundtrip. It just changes the focus of the webserver to a different page and transfers the page processing to a different page.
Response.Redirect can be used for both .aspx and html pages whereas Server.Transfer can be used only for .aspx pages.
Response.Redirect can be used to redirect a user to an external websites. Server.Transfer can be used only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page running on a different server.
Response.Redirect changes the url in the browser. So they can be bookmarked. Whereas Server.Transfer retains the original url in the browser. It just replaces the contents of the previous page with the new one.

MVC

MVC
ASP.NET MVC
This is the C# tutorial (Switch to the Visual Basic tutorial)
Stephen Walther builds an entire database-driven ASP.NET MVC application from start to finish. This tutorial is a great introduction for people who are new to the ASP.NET MVC Framework and who want to get a sense of the process of building an ASP.NET MVC application.
Download the code for this tutorial
« Previous Tutorial | Next Tutorial »
Create a Movie Database Application in 15 Minutes with ASP.NET MVC (C#)
The purpose of this tutorial is to give you a sense of "what it is like" to build an ASP.NET MVC application. In this tutorial, I blast through building an entire ASP.NET MVC application from start to finish. I show you how to build a simple database-driven application that illustrates how you can list, create, and edit database records.
To simplify the process of building our application, we'll take advantage of the scaffolding features of Visual Studio 2008. We'll let Visual Studio generate the initial code and content for our controllers, models, and views.
If you have worked with Active Server Pages or ASP.NET, then you should find ASP.NET MVC very familiar. ASP.NET MVC views are very much like the pages in an Active Server Pages application. And, just like a traditional ASP.NET Web Forms application, ASP.NET MVC provides you with full access to the rich set of languages and classes provided by the .NET framework.
My hope is that this tutorial will give you a sense of how the experience of building an ASP.NET MVC application is both similar and different than the experience of building an Active Server Pages or ASP.NET Web Forms application.
Overview of the Movie Database Application
Because our goal is to keep things simple, we'll build a very simple Movie Database application. Our simple Movie Database application will allow us to do three things:
1. List a set of movie database records
2. Create a new movie database record
3. Edit an existing movie database record
Again, because we want to keep things simple, we'll take advantage of the minimum number of features of the ASP.NET MVC framework needed to build our application. For example, we won't be taking advantage of Test-Driven Development.
In order to create our application, we need to complete each of the following steps:
1. Create the ASP.NET MVC Web Application Project
2. Create the database
3. Create the database model
4. Create the ASP.NET MVC controller
5. Create the ASP.NET MVC views
Preliminaries
You'll need either Visual Studio 2008 or Visual Web Developer 2008 Express to build an ASP.NET MVC application. You also need to download the ASP.NET MVC framework.
If you don't own Visual Studio 2008, then you can download a 90 day trial version of Visual Studio 2008 from this website:
http://msdn.microsoft.com/en-us/vs2008/products/cc268305.aspx
Alternatively, you can create ASP.NET MVC applications with Visual Web Developer Express 2008. If you decide to use Visual Web Developer Express then you must have Service Pack 1 installed. You can download Visual Web Developer 2008 Express with Service Pack 1 from this website:
http://www.microsoft.com/downloads/details.aspx?FamilyId=BDB6391C-05CA-4036-9154-6DF4F6DEBD14&displaylang=en
After you install either Visual Studio 2008 or Visual Web Developer 2008, you need to install the ASP.NET MVC framework. You can download the ASP.NET MVC framework from the following website:
http://www.asp.net/mvc/
Instead of downloading the ASP.NET framework and the ASP.NET MVC framework individually, you can take advantage of the Web Platform Installer. The Web Platform Installer is an application that enables you to easily manage the installed applications are your computer:
http://www.microsoft.com/web/gallery/Install.aspx
Creating an ASP.NET MVC Web Application Project
Let's start by creating a new ASP.NET MVC Web Application project in Visual Studio 2008. Select the menu option File, New Project and you will see the New Project dialog box in Figure 1. Select C# as the programming language and select the ASP.NET MVC Web Application project template. Give your project the name MovieApp and click the OK button.

Figure 01: The New Project dialog box (Click to view full-size image)
Make sure that you select .NET Framework 3.5 from the dropdown list at the top of the New Project dialog or the ASP.NET MVC Web Application project template won't appear.
Whenever you create a new MVC Web Application project, Visual Studio prompts you to create a separate unit test project. The dialog in Figure 2 appears. Because we won't be creating tests in this tutorial because of time constraints (and, yes, we should feel a little guilty about this) select the No option and click the OK button.
Visual Web Developer does not support test projects.

Figure 02: The Create Unit Test Project dialog (Click to view full-size image)
An ASP.NET MVC application has a standard set of folders: a Models, Views, and Controllers folder. You can see this standard set of folders in the Solution Explorer window. We'll need to add files to each of the Models, Views, and Controllers folders in order to build our Movie Database application.
When you create a new MVC application with Visual Studio, you get a sample application. Because we want to start from scratch, we need to delete the content for this sample application. You need to delete the following file and the following folder:
• Controllers\HomeController.cs
• Views\Home
Creating the Database
We need to create a database to hold our movie database records. Luckily, Visual Studio includes a free database named SQL Server Express. Follow these steps to create the database:
1. Right-click the App_Data folder in the Solution Explorer window and select the menu option Add, New Item.
2. Select the Data category and select the SQL Server Database template (see Figure 3).
3. Name your new database MoviesDB.mdf and click the Add button.
After you create your database, you can connect to the database by double-clicking the MoviesDB.mdf file located in the App_Data folder. Double-clicking the MoviesDB.mdf file opens the Server Explorer window.
The Server Explorer window is named the Database Explorer window in the case of Visual Web Developer.

Figure 03: Creating a Microsoft SQL Server Database (Click to view full-size image)
Next, we need to create a new database table. From within the Sever Explorer window, right-click the Tables folder and select the menu option Add New Table. Selecting this menu option opens the database table designer. Create the following database columns:
Column Name Data Type Allow Nulls
Id Int False
Title Nvarchar(100) False
Director Nvarchar(100) False
DateReleased DateTime False
The first column, the Id column, has two special properties. First, you need to mark the Id column as the primary key column. After selecting the Id column, click the Set Primary Key button (it is the icon that looks like a key). Second, you need to mark the Id column as an Identity column. In the Column Properties window, scroll down to the Identity Specification section and expand it. Change the Is Identity property to the value Yes. When you are finished, the table should look like Figure 4.

Figure 04: The Movies database table (Click to view full-size image)
The final step is to save the new table. Click the Save button (the icon of the floppy) and give the new table the name Movies.
After you finish creating the table, add some movie records to the table. Right-click the Movies table in the Server Explorer window and select the menu option Show Table Data. Enter a list of your favorite movies (see Figure 5).

Figure 05: Entering movie records (Click to view full-size image)
Creating the Model
We next need to create a set of classes to represent our database. We need to create a database model. We'll take advantage of the Microsoft Entity Framework to generate the classes for our database model automatically.
The ASP.NET MVC framework is not tied to the Microsoft Entity Framework. You can create your database model classes by taking advantage of a variety of Object Relational Mapping (OR/M) tools including LINQ to SQL, Subsonic, and NHibernate.
Follow these steps to launch the Entity Data Model Wizard:
1. Right-click the Models folder in the Solution Explorer window and the select the menu option Add, New Item.
2. Select the Data category and select the ADO.NET Entity Data Model template.
3. Give your data model the name MoviesDBModel.edmx and click the Add button.
After you click the Add button, the Entity Data Model Wizard appears (see Figure 6). Follow these steps to complete the wizard:
1. In the Choose Model Contents step, select the Generate from database option.
2. In the Choose Your Data Connection step, use the MoviesDB.mdf data connection and the name MoviesDBEntities for the connection settings. Click the Next button.
3. In the Choose Your Database Objects step, expand the Tables node, select the Movies table. Enter the namespace MovieApp.Models and click the Finish button.


Figure 06: Generating a database model with the Entity Data Model Wizard (Click to view full-size image)
After you complete the Entity Data Model Wizard, the Entity Data Model Designer opens. The Designer should display the Movies database table (see Figure 7).

Figure 07: The Entity Data Model Designer (Click to view full-size image)
We need to make one change before we continue. The Entity Data Wizard generates a model class named Movies that represents the Movies database table. Because we'll use the Movies class to represent a particular movie, we need to modify the name of the class to be Movie instead of Movies (singular rather than plural).
Double-click the name of the class on the designer surface and change the name of the class from Movies to Movie. After making this change, click the Save button (the icon of the floppy disk) to generate the Movie class.
Creating the ASP.NET MVC Controller
The next step is to create the ASP.NET MVC controller. A controller is responsible for controlling how a user interacts with an ASP.NET MVC application.
Follow these steps:
1. In the Solution Explorer window, right-click the Controllers folder and select the menu option Add, Controller.
2. In the Add Controller dialog, enter the name HomeController and check the checkbox labeled Add action methods for Create, Update, and Details scenarios (see Figure 8).
3. Click the Add button to add the new controller to your project.
After you complete these steps, the controller in Listing 1 is created. Notice that it contains methods named Index, Details, Create, and Edit. In the following sections, we'll add the necessary code to get these methods to work.

Figure 08: Adding a new ASP.NET MVC Controller (Click to view full-size image)
Listing 1 – Controllers\HomeController.cs
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Mvc.Ajax;

namespace MovieApp.Controllers

{

public class HomeController : Controller

{

//

// GET: /Home/

public ActionResult Index()

{

return View();

}

//

// GET: /Home/Details/5

public ActionResult Details(int id)

{

return View();

}

//

// GET: /Home/Create

public ActionResult Create()

{

return View();

}

//

// POST: /Home/Create

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create(FormCollection collection)

{

try

{

// TODO: Add insert logic here

return RedirectToAction("Index");

}

catch

{

return View();

}

}

//

// GET: /Home/Edit/5

public ActionResult Edit(int id)

{

return View();

}

//

// POST: /Home/Edit/5

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Edit(int id, FormCollection collection)

{

try

{

// TODO: Add update logic here

return RedirectToAction("Index");

}

catch

{

return View();

}

}

}

}
Listing Database Records
The Index() method of the Home controller is the default method for an ASP.NET MVC application. When you run an ASP.NET MVC application, the Index() method is the first controller method that is called.
We'll use the Index() method to display the list of records from the Movies database table. We'll take advantage of the database model classes that we created earlier to retrieve the movie database records with the Index() method.
I've modified the HomeController class in Listing 2 so that it contains a new private field named _db. The MoviesDBEntities class represents our database model and we'll use this class to communicate with our database.
I've also modified the Index() method in Listing 2. The Index() method uses the MoviesDBEntities class to retrieve all of the movie records from the Movies database table. The expression _db.MovieSet.ToList() returns a list of all of the movie records from the Movies database table.
The list of movies is passed to the view. Anything that gets passed to the View() method gets passed to the view as view data.
Listing 2 – Controllers/HomeController.cs (modified Index method)
using System.Linq;

using System.Web.Mvc;

using MovieApp.Models;

namespace MovieApp.Controllers

{

public class HomeController : Controller

{

private MoviesDBEntities _db = new MoviesDBEntities();

public ActionResult Index()

{

return View(_db.MovieSet.ToList());

}

}

}
The Index() method returns a view named Index. We need to create this view to display the list of movie database records. Follow these steps:
You should build your project (select the menu option Build, Build Solution) before opening the Add View dialog or no classes will appear in the View data class dropdown list.
1. Right-click the Index() method in the code editor and select the menu option Add View (see Figure 9).
2. In the Add View dialog, verify that the checkbox labeled Create a strongly-typed view is checked.
3. From the View content dropdown list, select the value List.
4. From the View data class dropdown list, select the value MovieApp.Models.Movie.
5. Click the Add button to create the new view (see Figure 10).
After you complete these steps, a new view named Index.aspx is added to the Views\Home folder. The contents of the Index view are included in Listing 3.

Figure 09: Adding a view from a controller action (Click to view full-size image)

Figure 10: Creating a new view with the Add View dialog (Click to view full-size image)


The Index view displays all of the movie records from the Movies database table within an HTML table. The view contains a foreach loop that iterates through each movie represented by the ViewData.Model property. If you run your application by hitting the F5 key, then you'll see the web page in Figure 11.

Figure 11: The Index view (Click to view full-size image)
Creating New Database Records
The Index view that we created in the previous section includes a link for creating new database records. Let's go ahead and implement the logic and create the view necessary for creating new movie database records.
The Home controller contains two methods named Create(). The first Create() method has no parameters. This overload of the Create() method is used to display the HTML form for creating a new movie database record.
The second Create() method has a FormCollection parameter. This overload of the Create() method is called when the HTML form for creating a new movie is posted to the server. Notice that this second Create() method has an AcceptVerbs attribute that prevents the method from being called unless an HTTP POST operation is performed.
This second Create() method has been modified in the updated HomeController class in Listing 4. The new version of the Create() method accepts a Movie parameter and contains the logic for inserting a new movie into the Movies database table.
Notice the Bind attribute. Because we don't want to update the Movie Id property from HTML form, we need to explicitly exclude this property.
Listing 4 – Controllers\HomeController.cs (modified Create method)
//

// GET: /Home/Create

public ActionResult Create()

{

return View();

}

//

// POST: /Home/Create

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create([Bind(Exclude="Id")] Movie movieToCreate)

{

if (!ModelState.IsValid)

return View();

_db.AddToMovieSet(movieToCreate);

_db.SaveChanges();

return RedirectToAction("Index");

}
Visual Studio makes it easy to create the form for creating a new movie database record (see Figure 12). Follow these steps:
1. Right-click the Create() method in the code editor and select the menu option Add View.
2. Verify that the checkbox labeled Create a strongly-typed view is checked.
3. From the View content dropdown list, select the value Create.
4. From the View data class dropdown list, select the value MovieApp.Models.Movie.
5. Click the Add button to create the new view.


Figure 12: Adding the Create view (Click to view full-size image)
Visual Studio generates the view in Listing 5 automatically. This view contains an HTML form that includes fields that correspond to each of the properties of the Movie class.
Listing 5 – Views\Home\Create.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>



Create





Create



<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

<% using (Html.BeginForm()) {%>



Fields





<%= Html.TextBox("Id") %>

<%= Html.ValidationMessage("Id", "*") %>







<%= Html.TextBox("Title") %>

<%= Html.ValidationMessage("Title", "*") %>







<%= Html.TextBox("Director") %>

<%= Html.ValidationMessage("Director", "*") %>







<%= Html.TextBox("DateReleased") %>

<%= Html.ValidationMessage("DateReleased", "*") %>











<% } %>



<%=Html.ActionLink("Back to List", "Index") %>




The HTML form generated by the Add View dialog generates an Id form field. Because the Id column is an Identity column, we don't need this form field and you can safely remove it.
After you add the Create view, you can add new Movie records to the database. Run your application by pressing the F5 key and click the Create New link to see the form in Figure 13. If you complete and submit the form, a new movie database record is created.
Notice that you get form validation automatically. If you neglect to enter a release date for a movie, or you enter an invalid release date, then the form is redisplayed and the release date field is highlighted.

Figure 13: Creating a new movie database record (Click to view full-size image)
Editing Existing Database Records
In the previous sections, we discussed how you can list and create new database records. In this final section, we discuss how you can edit existing database records.
First, we need to generate the Edit form. This step is easy since Visual Studio will generate the Edit form for us automatically. Open the HomeController.cs class in the Visual Studio code editor and follow these steps:
1. Right-click the Edit() method in the code editor and select the menu option Add View (see Figure 14).
2. Check the checkbox labeled Create a strongly-typed view.
3. From the View content dropdown list, select the value Edit.
4. From the View data class dropdown list, select the value MovieApp.Models.Movie.
5. Click the Add button to create the new view.
Completing these steps adds a new view named Edit.aspx to the Views\Home folder. This view contains an HTML form for editing a movie record.

Figure 14: Adding the Edit view (Click to view full-size image)
The Edit view contains an HTML form field that corresponds to the Movie Id property. Because you don't want people editing the value of the Id property, you should remove this form field.
Finally, we need to modify the Home controller so that it supports editing a database record. The updated HomeController class is contained in Listing 6.
Listing 6 – Controllers\HomeController.cs (Edit methods)
//

// GET: /Home/Edit/5

public ActionResult Edit(int id)

{

var movieToEdit = (from m in _db.MovieSet

where m.Id == id

select m).First();

return View(movieToEdit);

}

//

// POST: /Home/Edit/5

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Edit(Movie movieToEdit)

{

var originalMovie = (from m in _db.MovieSet

where m.Id == movieToEdit.Id

select m).First();

if (!ModelState.IsValid)

return View(originalMovie);

_db.ApplyPropertyChanges(originalMovie.EntityKey.EntitySetName, movieToEdit);

_db.SaveChanges();

return RedirectToAction("Index");

}
In Listing 6, I've added additional logic to both overloads of the Edit() method. The first Edit() method returns the movie database record that corresponds to the Id parameter passed to the method. The second overload performs the updates to a movie record in the database.
Notice that you must retrieve the original movie, and then call ApplyPropertyChanges(), to update the existing movie in the database.
Summary
The purpose of this tutorial was to give you a sense of the experience of building an ASP.NET MVC application. I hope that you discovered that building an ASP.NET MVC web application is very similar to the experience of building an Active Server Pages or ASP.NET application.
In this tutorial, we examined only the most basic features of the ASP.NET MVC framework. In future tutorials, we dive deeper into topics such as controllers, controller actions, views, view data, and HTML helpers.

Shadow Fields, Override Virtual Methods

Shadow Fields, Override Virtual Methods
Well, I am going to finish this "nuts and bolts" chapter before I flame out! I promised that I would discuss overriding, so I am going to make good on this promise. In general when you extend a class, you shadow fields with the same name in the base class and override virtual methods with the same name and parameter list in the base class. Overriding makes the base class method invisible. Shadowing a field, only hides the field from view. You can still explicitly touch the hidden shadowed field if you wish. You cannot touch an invisible overridden method. To demonstrate the difference between shadowing and overriding I resort, as usual, to twisted code!
First, you can create a sample base class with a public read only field "toastTime" and a virtual method "MakeToast()":
class Base
{
public readonly int toastTime= 60;
public virtual void MakeToast()
{
System.Console.WriteLine("MakeToastInSeconds: " + toastTime.ToString());
}
}
Declaring the only method virtual explicitly allows a designer to override the MakeToast() method in a subclass. (Contrast this to the approach in Java in which all methods are virtual by default.) This is important, since you are explicitly allowing a subclass to completely rewrite the implementation of the MakeToast() method and in doing so make it totally invisible!
Shadow Fields, Override Methods in the Base Class
Now you can extend or subclass the class Base:
///
/// Summary description for SubClass
///

class SubClass : Base
{
public readonly new int toastTime= 1;
public override void MakeToast()
{
System.Console.WriteLine("MakeToastInMinutes:" + toastTime.ToString());
}
}
Note: You must explicitly tell the compiler that you are overriding the virtual base class method MakeToast() with the key word override and that you are hiding the base field with the key word new. (You cannot override a field in a base class.)
Overriding the method MakeToast makes the base class method with the same name and signature invisible to the caller of the class. This is in contrast to the base class field toastTime. The base class field toastTime is shadowed, but still potentially visible to the caller. You have shadowed a base class field and overridden a base class method.
You can demonstrate the behavior of shadowed fields with the following test code:
SubClass sc= new SubClass();
System.Console.WriteLine(sc.toastTime.ToString()); // --> 1
Base super= (Base)sc;
System.Console.WriteLine(super.toastTime.ToString()); // --> 60
In the above code snippet, the type of the reference variable determines which value of toastTime can be touched with the reference variable. Touching the field with a reference of type SubClass tells the compiler that you want to touch the the toastTime field of class SubClass. Casting the reference variable to the base type, tells the compiler that you want to touch the toastTime field of the type Base. Both fields are potentially visible to the caller. The base class field is shadowed, but still touchable.
You can demonstrate the behavior of an overridden method with the following test code. This code demonstrates that the overridden base class method MakeToast is invisible. You cannot touch the overridden method even if you cast the reference to the base type.
SubClass sc= new SubClass();
sc.MakeToast(); // --> MakeToastInMinutes: 1
Base super= (Base)sc;
super.MakeToast(); // --> MakeToastInMinutes: 1
Despite the cast, only the derived (specialized) class method is visible. If you think about it, this behavior is absolutely essential to polymorphism. Overriding insures that the "proper" implementation of a polymorphic method is called at runtime. You can demonstrate the proper polymorphic behavior with a little sample code. Here is yet another version of the Drawable class, now with a default implementation of DrawYourself.
class Drawable
{
public virtual void DrawYourself()
{
System.Console.WriteLine("Drawable");
}
}
class Square : Drawable
{
public override void DrawYourself()
{
System.Console.WriteLine("Square");
}
}
class Circle : Drawable
{
public override void DrawYourself()
{
System.Console.WriteLine("Circle");
}
}
Here is the sample code that demonstrates that the "proper" implementation is called at runtime.
Drawable draw= new Drawable();
draw.DrawYourself(); //--> Drawable
draw= new Square();
draw.DrawYourself(); //--> Square
draw= new Circle();
draw.DrawYourself(); //--> Circle
Overriding insures that the proper super class implementation is always called at runtime. The magic of polymorphism is secure.
You Can Hide a Method
For completeness sake, I will mention that you can hide a virtual method using the key word new instead of the key word override. Go ahead. Edit the previous code sample and replace the key word override with the key word new.
This is the new behavior that breaks polymorphism:
Drawable draw= new Drawable();
draw.DrawYourself(); //--> Drawable
draw= new Square();
draw.DrawYourself(); //--> Drawable
draw= new Circle();
draw.DrawYourself(); //--> Drawable

STATIC MEMBER …………….

STATIC MEMBER …………….
A C# class can contain both static and non-static members. When we declare a member with the help of the keyword static, it becomes a static member. A static member belongs to the class rather than to the objects of the class. Hence static members are also known as class members and non-static members are known as instance members.

In C#, data fields, member functions, properties and events can be declared either as static or non-static. Remember that indexers in C# can't declared as static.

Static Fields

Static fields can be declared as follows by using the keyword static.

class My Class
{
public static int x;
public static int y = 20;
}

When we declare a static field inside a class, it can be initialized with a value as shown above. All un-initialized static fields automatically get initialized to their default values when the class is loaded first time.
For example


// C#:static & non-static
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int x = 20;
public static int y;
public static int z = 25;
public MyClass(int i)
{
x = i;
y = i;
z = i;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);
MyClass mc = new MyClass(25);

Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y,MyClass.z);
}
}

The C# provides a special type of constructor known as static constructor to initialize the static data members when the class is loaded at first. Remember that, just like any other static member functions, static constructors can't access non-static data members directly.
The name of a static constructor must be the name of the class and even they don't have any return type. The keyword static is used to differentiate the static constructor from the normal constructors. The static constructor can't take any arguments. That means there is only one form of static constructor, without any arguments. In other way it is not possible to overload a static constructor.

We can't use any access modifiers along with a static constructor.

// C# static constructor
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int x;
public static int y;
static MyClass ()
{
x = 100;
Y = 200;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}",MyClass.x,MyClass.y);
}
}

Note that static constructor is called when the class is loaded at the first time. However we can't predict the exact time and order of static constructor execution. They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class is called.
Static Member Functions

Inside a C# class, member functions can also be declared as static. But a static member function can access only other static members. They can access non-static members only through an instance of the class.

We can invoke a static member only through the name of the class. In C#, static members can't invoked through an object of the class as like in C++ or JAVA.

// C#:static & non-static
// Author: rajeshvs@msn.com

using System;
class MyClass
{
private static int x = 20;
private static int y = 40;
public static void Method()
{
Console.WriteLine("{0},{1}",x,y);
}
}
class MyClient
{
public static void Main()
{
MyClass.Method();

}
}

Static Properties

The properties also in C# can be declared as static. The static properties are accessing using the class name. A concrete example is shown below.

// C#:static & non-static
// Author: rajeshvs@msn.com

using System;
class MyClass
{
public static int X
{
get
{
Console.Write("GET");
return 10;
}
set
{
Console.Write("SET");
}
}

}
class MyClient
{
public static void Main()
{
MyClass.X = 20; // calls setter displays SET
int val = MyClass.X;// calls getter displays GET
}
}

Static Indexers
In C# there is no concept of static indexers, even though static properties are there.

Static Members & Inheritance

A derived class can inherit a static member. The example is shown below.

// C#:static
// Author: rajeshvs@msn.com
using System;
class MyBase
{
public static int x = 25;
public static void Method()
{
Console.WriteLine("Base static method");
}

}
class MyClass : MyBase
{
}
class MyClient
{
public static void Main()
{
MyClass.Method(); // Displays 'Base static method'
Console.WriteLine(MyClass.x);// Displays 25
}
}

But a static member in C# can't be marked as override, virtual or abstract. However it is possible to hide a base class static method in a derived class by using the keyword new.
An example is shown below.

// C#:static & non-static
// Author: rajeshvs@msn.com

using System;
class MyBase
{
public static int x = 25;
public static void Method()
{
Console.WriteLine("Base static method");
}

}
class MyClass : MyBase
{
public new static int x = 50;
public new static void Method()
{
Console.WriteLine("Derived static method");
}
}
class MyClient
{
public static void Main()
{
MyClass.Method(); // Displays 'Derived static method'
Console.WriteLine(MyClass.x);// Displays 50
}
}

Finally remember that it is not possible to use this to reference static methods.

>> Static variables inside a class method (not in a class) shared among all instances of the class?
>>Even if you have a bunch of instances of this class, you only will have one copy of your static variable shared by all the instances

any variable marked as a static is considered a variable owned by the class. Even if you have a bunch of instances of this class, you only will have one copy of your static variable shared by all the instances.

This is the main difference with instance variables where each instance of your class have his own variables.

Example, if you have a class like this:

public class SoldCar{
public String model; //instance variable - each soldCar have its model
public int cost; //instance variable - each soldCar have its cost
public static int count; //class variable - all soldCars share this count

public SoldCar(){
count ++;
}

public static void main(String[] args){
SoldCar ferrari = new SoldCar();
ferrari.model = "fiorano";
ferrari .cost = 999999;

SoldCar beetle = new SoldCar();
beetle.model = "new beetle";
beetle.cost = 2222;

System.out.println( ferrari.model + "," + ferrari.count );
System.out.println( beetle.model + "," + beetle.count );
}

}

The output of this program is :
fiorano,2
new beetle,2


You can declare a static local variable in a class, that is, inside a procedure in that class. However, you cannot declare a static local variable in a structure.


We use static class when we have to separate data and behavior that will be independent of any object identity. The data and functions do not change regardless of what happens to the object.
A static class can only contain static members. We cannot create an instance of a static class. Static class is always sealed and they cannot contain instance constructor. Hence we can also say that creating a static class is nearly same as creating a class with only static members and a private constructor (private constructor prevents the class from being instantiated).
The advantage of using the static class is that compiler can check that no instance of the class is accidentally added. The complier will not allow any instance class of a static class. We also cannot inherit a static class since it is sealed. Static class do not have constructor, but can still declare static constructor to set up the initial values.
Static class also makes the implementation simpler and faster since we do not have make and instance of the class to call its method. An example of good use of static class would be a class like math, which does all the mathematic function, or a currency converter class to convert currency class for converting the currency.