Sunday, January 25, 2009

Common (and simple) coding tasks in sharepoint

Well, everyone went to teched last week and I was left at work stuck with a project with a strict deadline. So out of boredom I decided that I will compile a small snippet database for beggining sharepoint developers.I see a lot of people in the microsoft public sharepoint developer forums asking these questions over and over again, so I thought I will save everyone some time by answering these right here.Some people may say these are RTFM questions, since the SDK contains all of these examples, but apperantly people dont bother with the SDK, or find it confusing to navigate through. So here is my 2 cents.
The purpose here is to give some code samples to common tasks like:
getting a reference to a site
Iterating over all lists in a site
getting a reference to a list
getting a reference to an item in a list
getting a reference to the item's properties
getting a reference to a document and its properties
adding a new item to a list
modifying an item in a list
If you feel I should add to this list, let me know and I will write some sample code. However, please remember this is for simple, common tasks and I wont start giving application samples here.
So, lets get down to it!
Getting a reference to a site
Ok, you have a sharepoint site in a URL "http://server/sites/site" and you want to get the object of the site from its URL. What do you do?using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
}
}
Now you have the SPWeb object, allowing you to get information about the site you used in the URL. For example, iterating all lists in the site:using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
string linksHtml = "";
foreach(SPList list in myWeb.Lists)
{
string listLink = "" + list.Title + "("+list.Items.Count+")
";
linksHtml += listLink;
}
}
}
The above example also showed how to get a reference to a list by iterating over the lists in a site. But what if you want a specific list called "contacts"? The following will show you how to get the object for a list that you know the name of:using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPList contactsList = myWeb.Lists["Contacts"];
}
}
Now lets iterate through the items in the list and get item's properties:using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPList contactsList = myWeb.Lists["Contacts"];
foreach (SPListItem contact in contactsList.Items)
{
string contactLastName = contact["Last Name"].ToString();
}
}
}
Now some of you are saying - "what about documents?", to which I answer that document libraries are the same as lists (ok, there are some differences but we will leave that for future articles). To get to a document in a document library you can either use the code above to iterate through the library and its files, or, if you know the file's URL, you can do this:
using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPFile file = myWeb.GetFile("http://server/sites/site/library/folder/file");
}
}
File properties are available through its Item property. If you have for example a text field in the document library called "My Custom String Property", and you want to know the value for that field in a specific file, use the following code:using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPFile file = myWeb.GetFile("http://server/sites/site/library/folder/file");
string filePropertyValue = file.Item["My Custom String Property"].ToString();
}
}
We now want to add a new item to a list:
using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPList contactsList = myWeb.Lists["Contacts"];
SPListItem newItem = contactsList.Items.Add();
newItem["First Name"] = "Ishai";
newItem["Last Name"] = "Sagi";
newItem.Update();
}
}
Lets change all items in the list to build the email address based on the first and last name (in the format of 'first.last@testing.com') :
using(SPSite mySite = new SPSite("http://server/sites/site"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
SPList contactsList = myWeb.Lists["Contacts"];
foreach(SPListItem existingItem in contactsList.Items)
{
existingItem["E-mail Address"] = existingItem["First Name"] + "." + existingItem["Last Name"] + "@testing.com";
newItem.Update();
}
}
}

Tuesday, January 20, 2009

Whats new in C# 4.0?


Whats new in C# 4.0?
Every new version of C# has a major improvement theme. 1.0 was about managed code; 2.0 was about generics; 3.0 introduced Functional Programming and LINQ.
And now 4.0 introduces dynamic programming.
A new keyword called dynamic which can be used to define a variable, function reurn type or a parameter, which the compiler will not bother to resolve calls during compilation, instead it will delay all method resolution to run time.

This technology dynamic lookup. The basis of the dynamic resolution is the IDynamicObject interface, shared with the Dynamic Language Runtime. This has on it methods like Invoke which the compiler will call to allow the object itself to participate in method resolution.


There are three primary scenarios that will be enabled by the new support for dynamic lookup:

Office automation and other COM Interop scenarios

Consuming types written in dynamic languages

Enhanced support for reflection .

Sunday, January 18, 2009

Generics
Generics are a new feature in version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations.


Generics Overview
Use generic types to maximize code reuse, type safety, and performance.
The most common use of generics is to create collection classes.
The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.
You can create your own generic interfaces, classes, methods, events and delegates.
Generic classes may be constrained to enable access to methods on particular data types.
Information on the types used in a generic data type may be obtained at run-time by means of reflection.

Sunday, January 4, 2009

Iterators in 3.5

Iterators
Iterators are a new feature in C# 2.0. An iterator is a method, get accessor or operator that enables you to support foreach iteration in a class or struct without having to implement the entire IEnumerable interface. Instead, you provide just an iterator, which simply traverses the data structures in your class. When the compiler detects your iterator, it will automatically generate the Current, MoveNext and Dispose methods of the IEnumerable or IEnumerable interface.
Iterators Overview
An iterator is a section of code that returns an ordered sequence of values of the same type.
An iterator can be used as the body of a method, an operator, or a get accessor.
The iterator code uses the yield return statement to return each element in turn. yield break ends the iteration. For more information, see
yield.
Multiple iterators can be implemented on a class. Each iterator must have a unique name just like any class member, and can be invoked by client code in a foreach statement as follows: foreach(int x in SampleClass.Iterator2){}
The return type of an iterator must be IEnumerable,
IEnumerator, IEnumerable, or IEnumerator.
The
yield keyword is used to specify the value, or values, returned. When the yield return statement is reached, the current location is stored. Execution is restarted from this location the next time the iterator is called.