Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Posts Tagged ‘c#’

How to create a List in SharePoint using Client Object Model?

Posted by JP on June 30, 2012

ClientContext clientContext = new ClientContext(“http://url”);

ListCreationInformation listCreationInformation = new ListCreationInformation();
listCreationInformation.Title = “New List Title”;
listCreationInformation.TemplateType = (int)ListTemplateType.Tasks;

list = clientContext.Web.Lists.Add(listCreationInformation);

clientContext.ExecuteQuery();

Advertisements

Posted in C# | Tagged: , , | 2 Comments »

C#–Get EDMX Property Names and Class Names of Entities

Posted by JP on June 7, 2012

This is a short tip to get the property name sand class names of entities inside an EDMX Context.

For eg: you have context name as MyContext and you have mapped 2 tables Article  and Person

The property names will be: Articles, People (getting pluralized)

The class names will be still: Article, Person

Please let me know any queries you have.

code to get property names:

        private void button1_Click(object sender, EventArgs e)
        {
            listBox.DataSource = GetPropertyNames(typeof(MyContext));
        }

        public IList<string> GetPropertyNames(Type type)
        {
            return type.GetProperties().Where(p => (p.PropertyType.Name  == "ObjectSet`1") && (p.PropertyType.GetGenericArguments().Count() == 1)).Select(p => p.Name).ToList();
 }

code to get class names:

        private void button2_Click(object sender, EventArgs e)
        {
            listBox.DataSource = GetClassNames(typeof(MyContext ));
        }

        private object GetClassNames(Type type)
        {
            return type.GetProperties().Where(p => (p.PropertyType.Name == "ObjectSet`1") && (p.PropertyType.GetGenericArguments().Count() == 1)).Select(p => p.PropertyType.GetGenericArguments().First().Name).ToList();
         }

Posted in C# | Tagged: , | Leave a Comment »

SharePoint 2010 – Create Document Library

Posted by JP on June 4, 2012

In this article we can explore the creation of Document Library through code. Here we are using existing Document Templates inside SharePoint to create a new document library.

Following are the activities involved in Document Library creation:

· Find the List Template

· Find the Document Template

· Create Document Library

Inside Visual Studio

Create a new console application and name it as DocLibCreation. Make sure you change the target framework to .Net 3.5.

Add the following code into the Program.cs file:

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPListTemplate listTemplate = web.ListTemplates["Document Library"];

SPDocTemplate docTemplate = (from SPDocTemplate dt in web.DocTemplates

where dt.Type == 122

select dt).FirstOrDefault();

Guid guid = web.Lists.Add("My Docs", "My Documents", listTemplate, docTemplate);

SPDocumentLibrary library = web.Lists[guid] as SPDocumentLibrary;

library.OnQuickLaunch = true;

library.Update();

}

}

Now run the application and you can see the new Document Library created inside SharePoint.

clip_image002


Document Templates

Following are the SharePoint 2010 document templates available:

Template ID

Description

100

No Template

101

Word 2003 document

103

Excel 2003 document

104

PowerPoint 2003 document

121

Word document

122

Excel document

123

PowerPoint document

111

OneNote Notebook

102

SharePoint Designer HTML document

105

ASPX Web Page

106

ASPX Web Part Page

1000

InfoPath document

Uploading Document

Now we can try uploading a document to the above library programmatically. Use the following code to upload an excel file. Make sure the application bin folder contains a file named sample.xlsx.

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPDocumentLibrary library = web.Lists["My Docs"] as SPDocumentLibrary;

SPFile file = library.RootFolder.Files.Add("sample.xlsx", File.ReadAllBytes("sample.xlsx"));

}

}

You can see that the file is uploaded into SharePoint:

clip_image004

Downloading Document

Now we can try downloading a document from the above library programmatically. Use the following code:

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPDocumentLibrary library = web.Lists["My Docs"] as SPDocumentLibrary;

SPFile file = web.GetFile(library.RootFolder.Url + "/sample.xlsx");

Stream stream = file.OpenBinaryStream();

FileStream fileStream = new FileStream("out.xlsx", FileMode.OpenOrCreate, FileAccess.Write);

int buffer = 4096;

int read = buffer;

byte[] bytes = new byte[buffer];

while (read == buffer)

{

read = stream.Read(bytes, 0, buffer);

fileStream.Write(bytes, 0, read);

if (read < buffer) break;

}

stream.Dispose();

fileStream.Dispose();

}

}

After running the program, you can see that the file is created in the bin folder.

clip_image006

This concludes the following activities:

1. Create Document Library

2. Upload a Document

3. Download a Document

References

http://www.learningsharepoint.com/2010/06/30/programatically-creating-document-sets-in-sharepoint-2010/

Summary

In this article we have the creation of document library through code. Please note that using the Document Type we can create different types of document library.

Posted in C#, SharePoint | Tagged: , , , | 6 Comments »

SharePoint 2010 – Create List Definition using Visual Studio

Posted by JP on June 4, 2012

In this article we can explore the List Definition creation using Visual Studio. Please note that the same can be achieved through SharePoint Designer as well.

Create List Definition Project

For starting use the List Definition project inside New Project dialog.

clip_image002

Enter the name as Coders. Select the site from the wizard as shown below.

clip_image004

Choose Custom List in the next step.

clip_image006

Enter the details as shown above and click the Finish button to close the wizard. Now the Solution Explorer looks like below:

clip_image008

Open the ListDefinition1>ListInstance1>Elements.xml (Please note that there are 2 Elements.xml inside the Solution Explorer)

Change the Title and Url attributes as following:

<?xml version="1.0" encoding="utf-8"?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/"&gt;

<ListInstance Title="Coders"

OnQuickLaunch="TRUE"

TemplateType="10000"

Url="Lists/Coders"

Description="My List Instance">

</ListInstance>

</Elements>

Now click the Build button and on succeed, right click the Project and click Deploy. If no error messages are there, the Deployment succeeded and you can see the new List inside SharePoint.

clip_image010

On clicking the Coders list you can see the new list opened in SharePoint.

Now we need to add a custom column to the List Definition. Our column is of Single line and name as CoderName. Following are the activities included in the Column Creation.

· Create a new Field

· Specify the properties like ID (GUID), Name etc.

· Add the Field Reference inside Default View

Inside the Fields section of Schema.xml add the following Field definition

<Field Type="Note" Name="CoderName" DisplayName="CoderName" Required="FALSE" ID="{1D54AAC6-DBB8-4454-91B7-E2FAE7697D6A}"></Field>

Inside the ViewFields section of the second View, add the following FieldRef node.

<FieldRef Name="CoderName"></FieldRef>

You can go back to SharePoint and Refresh the Coders List. The changes are visible there:

clip_image012

The new CoderName property is visible now. This concludes our List creation using Visual Studio. For adding more columns, use the Schema.xml file.

References

http://msdn.microsoft.com/en-us/library/ms466023.aspx

http://onlinecoder.blogspot.com/2011/03/simple-way-of-creating-sharepoint-2010.html

Summary

In this article we have explored the List Definition creation using Visual Studio. The attached source code contains the example we discussed. You can try building and deploying it.

Posted in C#, SharePoint | Tagged: , , , | Leave a Comment »

SharePoint 2010 – List – Add, Edit, Delete using code

Posted by JP on June 4, 2012

In this article we can experiment List manipulations through code. Following are the list operations to perform:

1. Add

2. Edit

3. Delete

Pre-Requisite

For proceeding with we need to create a List named Tasks using template Tasks.

clip_image002

Now create a new SharePoint Console Application project inside Visual Studio.

clip_image004

Make sure you changed the Application Target Framework to .Net 3.5 version.

Adding an Item

For adding a new Task Item execute the following code:

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items.Add();

item["Title"] = "New Task";

item["Description"] = "Description of Task";

item.Update();

}

}

Now you can check the Tasks list inside SharePoint and you can see the new item there.

clip_image006

Editing an Item

For editing an existing Task use the following code. Here we are changing the first item Title and Description.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item["Title"] = "Edited Task";

item["Description"] = "Description of Task (edited)";

item.Update();

}

}

Going back to SharePoint you can see the Edited Task

clip_image008

Deleting an Item

For deleting an item use the following code.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item.Delete();

}

}

Now you can go back to SharePoint and see that the item was deleted.

clip_image010

References

http://suguk.org/blogs/tomp/archive/2006/09/28/Adding_SPListItems.aspx

Summary

In this article we have experimented List manipulations Add, Edit, Delete through code. In real life we will be needed to automate List manipulations and programming will be a help in this regard.

Posted in C#, SharePoint | Tagged: , , , | Leave a Comment »

SharePoint 2010 – List – Add, Edit, Delete using code

Posted by JP on June 2, 2012

In this article we can experiment List manipulations through code. Following are the list operations to perform:

1. Add

2. Edit

3. Delete

Pre-Requisite

For proceeding with we need to create a List named Tasks using template Tasks.

clip_image002

Now create a new SharePoint Console Application project inside Visual Studio.

clip_image004

Make sure you changed the Application Target Framework to .Net 3.5 version.

Adding an Item

For adding a new Task Item execute the following code:

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items.Add();

item["Title"] = "New Task";

item["Description"] = "Description of Task";

item.Update();

}

}

Now you can check the Tasks list inside SharePoint and you can see the new item there.

clip_image006

Editing an Item

For editing an existing Task use the following code. Here we are changing the first item Title and Description.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item["Title"] = "Edited Task";

item["Description"] = "Description of Task (edited)";

item.Update();

}

}

Going back to SharePoint you can see the Edited Task

clip_image008

Deleting an Item

For deleting an item use the following code.

using (SPSite site = new SPSite("http://appes-pc&quot;))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Tasks"];

SPListItem item = list.Items[0];

item.Delete();

}

}

Now you can go back to SharePoint and see that the item was deleted.

clip_image010

References

http://suguk.org/blogs/tomp/archive/2006/09/28/Adding_SPListItems.aspx

Summary

In this article we have experimented List manipulations Add, Edit, Delete through code. In real life we will be needed to automate List manipulations and programming will be a help in this regard.

Posted in C#, SharePoint | Tagged: , , , | 2 Comments »

SharePoint 2010 – LINQ and SPMetal

Posted by JP on June 1, 2012

In this article we can explore some of the advanced programming areas.

· LINQ to SharePoint

· SPMetal

LINQ to SharePoint is a new feature of SharePoint 2010. LINQ stands for Language Integrated Query which is a part of .NET Language. The aim of LINQ is to support different data sources using the same Typed Query Syntax. Presently it supports Objects, Datasets, SQL, Entities, XML etc.

Why we need LINQ?

You might have noted that the previous List Programming examples did not used proper column name access. LINQ allows us to access the List in a Typed manner. Adding more clarity we can access the list items based on the column names which we usually do with the databases.

Example: var result = from c in Citizen where c.Name == “John” select c;

What is SPMetal?

As we will be creating custom lists having custom column names, we need to generate the Entity Model. The SPMetal.exe is the tool which helps in generating the Model classes.

Although we can create the Model classes manually, it will be a tedious job and error prone. Using SPMetal would be the right approach to model classes.

Activities

Following are the activities performed in this article:

1. Manager List Creation

2. Entity Creation

3. Read using LINQ

4. Insert Entity

5. Update Entity

6. Delete Entity

Experimenting with LINQ and SPMetal

To start with create a custom list inheriting from Custom List and name it as Manager. Add the following custom columns and data:

clip_image002

Generating the Entity Models

Now we can generate the Entity Model for the above List.

You can get the SPMetal.exe inside the following folder:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

Open a command prompt and go to the specified folder:

clip_image004

Now run the following command:

SPMetal.exe /web: http://YOURSITE /code: SiteEntities.cs

Wait for a while and you will be ready with the new file. Open the file SiteEntities and you can see the Manager class is contained inside.

clip_image006

Create Application

Create a new SharePoint > 2010 > Console Application (targeting .Net 3.5 framework) and add the SiteEntities.cs file into it.

clip_image008

Add reference to the following assembly:

clip_image010

You can try with the following operations Read, Insert, Update, Delete using LINQ to SharePoint

 

Selecting an Item

Now we are trying to select the managers with country as USA:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(“http://appes-pc&#8221;))

{

var result = context.Manager.Where(m => m.Country == “USA”);

foreach (ManagerItem manager in result)

{

Console.WriteLine(manager.Name);

}

}

Note: You can use LINQ or Lambda Expression to do the query. In the above example I have used Lambda.

On executing the application you can see the following results.

clip_image012

Inserting an Item

For inserting a new item into the Manager list, use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(“http://appes-pc&#8221;))

{

ManagerItem manager = new ManagerItem();

manager.Name = “New Manager”;

manager.Address = “New Address”;

manager.Country = “New Country”;

context.Manager.InsertOnSubmit(manager);

context.SubmitChanges();

}

After executing the application, open the Manager list inside SharePoint as shown below:

clip_image014

Updating an Item

For updating an item inside SharePoint use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(“http://appes-pc&#8221;))

{

ManagerItem manager = context.Manager.Where(m =>

string.IsNullOrEmpty(m.Title)).FirstOrDefault();

if (manager != null)

manager.Title = “New Title”;

context.SubmitChanges();

}

You can see the updated entity inside SharePoint:

clip_image016

Deleting an Item

For deleting an item inside SharePoint use the following code:

using (SiteEntitiesDataContext context = new SiteEntitiesDataContext(“http://appes-pc&#8221;))

{

ManagerItem manager = context.Manager.Where(m => m.Title.Length > 3).FirstOrDefault();

if (manager != null)

context.Manager.DeleteOnSubmit(manager);

context.SubmitChanges();

}

You can see that the item is deleted inside SharePoint:

clip_image018

This concludes our Read, Insert, Update, Delete operations using LINQ to SharePoint. Hope the topics are understood by the reader.

References

http://msdn.microsoft.com/en-us/library/ee535491.aspx

http://msdn.microsoft.com/en-us/library/ee538255.aspx

Summary

In this article we have explored LINQ and SPMetal tool. This information is necessary in the real world programming scenarios. The attachment contains the source code we discussed.

Posted in C#, SharePoint | Tagged: , , , , | 2 Comments »

SharePoint 2010 – Lists and Event Handlers

Posted by JP on May 31, 2012

In this article we can explore the Event Handling features of List through code. Using the SPList in Server Object Model we can access event handling for a list.

We can use the event to perform the following activities:

· Validate the Item

· Log the information

· Create associated items

There are multiple Event Types for a List:

· List Events

· List Item Events (Add, Edit, Delete)

· Web Events

· Feature Events

· Workflow Events

Create Event Receiver Project

For starting with create an Event Receiver project inside Visual Studio.

clip_image002

You will be prompted for the site:

clip_image004

By default the machine site will be shown in the dialog box. Leave the default option of Sandboxed solution and click the Next button.

clip_image006

Select the List Item Events and use event source as Contacts. Check the check boxes for added, updated and deleted events and click the Finish button.

Note: The site url can be changed later. For time being we are using hard coded urls.

On clicking Finish button, the code will be generated for the List Event Receiver and you can place a break point in the ItemAdding event as shown below.

clip_image008

Now execute the application and your Event will be added and activated.

Try adding a new contact inside SharePoint:

clip_image010

On clicking the Save button, the breakpoint inside Visual Studio will get hit:.

clip_image012

SPItemEventProperties

You can cancel the operation by using the Cancel property.

You can report an error message using the ErrorMessage property.

Cancel for Delete

You can cancel and item delete by setting the properties.Cancel = true;

public override void ItemDeleting(SPItemEventProperties properties)

{

properties.ErrorMessage = "Deleting Item is not permitted!";

properties.Cancel = true;

}

Try deleting an item from the Contacts inside SharePoint:

clip_image014

You will get the following message prompted:

clip_image016

Deploying the Event Receiver

You can take a note that while you stop Visual Studio, the item deletion is allowed inside SharePoint. To make the event receiver permanent, use the project Deploy option.

clip_image018

Now try Deleting an item without Visual Studio Debugging. You will get the same Error Message Dialog and this concludes the Event Creation and Deployment to a SharePoint site.

Properties of Project

You can change the Url and other properties created through the Wizard. Use Project > Properties to access/modify these properties.

clip_image020

Features

The event receiver is actually deployed as a feature inside SharePoint. You can view the Feature properties and the associated xml file under Features special folder as shown below.

clip_image022

The Event code and Elements.xml reside inside the EvntReceiver1 group as shown below.

clip_image024

References

http://msdn.microsoft.com/en-us/library/bb736146(v=office.12).aspx

Summary

In this article we have explored the List Event facility of SharePoint. In advanced List Management these flexibilities are great tool for a SharePoint Developer.

Posted in C#, SharePoint | Tagged: , , , | 2 Comments »

C# code to find your motherboard serial number

Posted by JP on May 30, 2012

ManagementScope ms = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2");
ms.Connect();
ManagementObject wmiClass = new ManagementObject(ms, new ManagementPath("Win32_BaseBoard.Tag=\"Base Board\""), new ObjectGetOptions());
string sn = wmiClass.Properties.Cast<PropertyData>().Where(p => p.Name == "SerialNumber").FirstOrDefault().Value.ToString();
Console.WriteLine(sn);
Console.ReadKey(false);

// Please add reference to System.Management

Posted in C# | Tagged: , , | Leave a Comment »

SharePoint 2010 – Server Object Model

Posted by JP on May 30, 2012

For programming against the SharePoint items, we need to retrieve the properties and the methods to operate on them. The SharePoint Object Model provides various classes to accomplish this. In this article we can discuss the Object Model with the core classes involved with little amount of coding.

Please note that there are 2 Object Models in SharePoint 2010

1. Server Object Model

2. Client Object Model

Here we are discussing only about the Server Object Model. Server Object Model classes are used for server side programming and will be executed on the SharePoint Server Farm.

Namespace

The Server Object Model classes are residing in the Microsoft.SharePoint assembly. The general classes are available inside Microsoft.SharePoint namespace and the administration classes inside Microsoft.SharePoint.Administration namespace.

Core Classes

Following are the important classes and their corresponding SharePoint items.

Class

SharePoint Item

SPFarm

Farm

SPServer

Server

SPSite

Site Collection

SPWeb

Web site

SPControl

Control

SPList

List

SPDocumentLibrary

Document Library

SPContentType

Content Type

SPUser

User

SPException

SharePoint Exception

Programming

Now we can start with experimenting some of the above classes. For starting with we can create a SharePoint Console Application. Use the New Project > SharePoint > Console Application project item.

clip_image002

Accessing the List Items in a List

For proceeding with this example create a list derived from the Contacts template and name it as “My Contacts”. Add some items inside it with First Name and Last Name set.

Use the following code inside the Console application and execute it.

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet&quot;)) // Site Collection

{

using (SPWeb web = site.OpenWeb()) // Site

{

SPList list = web.Lists["My Contacts"]; // List

int i = 1;

foreach (SPListItem item in list.Items)

{

Console.WriteLine("Item: " + (i++).ToString());

Console.WriteLine(item.Name);

Console.WriteLine(item.Title);

Console.WriteLine(item.GetFormattedValue("First Name"));

Console.WriteLine(item.GetFormattedValue("Last Name"));

Console.WriteLine(string.Empty);

}

}

}

Console.ReadKey(false);

If you receive any build errors regarding namespace, change the Project Properties > Target to .Net Framework 3.5.

clip_image004

Now try building the application and it should work fine. You can see the following output.

clip_image006

Please note the usage of Title, Name properties and the GetFormattedValue() method.

Accessing the items in a Library

Now we can proceed with accessing the document library items programmatically. For proceeding with you need to create a document library inheriting from Document Library template and name it as “My Docs”. Upload one or two documents into it. We are proceeding to get the file name and length in this example.

Enter the following code in the console application.

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet&quot;)) // Site Collection

{

using (SPWeb web = site.OpenWeb()) // Site

{

SPDocumentLibrary library = web.Lists["My Docs"] as SPDocumentLibrary; // Library

int i = 1;

foreach (SPListItem item in library.Items)

{

Console.WriteLine("Item: " + (i++).ToString());

Console.WriteLine(item.File.Name);

Console.WriteLine(item.File.Length);

Console.WriteLine(string.Empty);

}

}

}

Executing the application you can see the following results.

clip_image008

SPControl

The SPControl class acts as the base class while developing server controls. It reseides in the namespace Microsoft.SharePoint.WebControls.

SPControl provides static methods that returns reference to the current site, web, web application, module. The methods are:

SPControl.GetContextSite()

SPControl.GetContextWeb()

SPControl.GetContextWebApplication()

SPControl.GetContextModule()

SPException

The SPException class can be used to handle exception inside a try catch block. It represents the exceptions thrown by the server object model.

try

{

// Code here

}

catch (SPException ex)

{

// Handle Exception

}

SPUser

The SPUser class can be used to access user information for a SharePoint site. Enter the following code to get the number of users and their names.

using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet&quot;))

{

using (SPWeb web = site.OpenWeb())

{

foreach (SPUser user in web.AllUsers)

Console.WriteLine("User: " + user.Name);

}

}

On running the code you can see the results based on your machine users.

clip_image010

Note

You can add a new list item or library item using the Items.Add() method. For updation and deletion use the item.Update() and item.Delete() methods respectively. More code coverage on these areas will be provided later.

References

http://msdn.microsoft.com/en-us/library/ms473633.aspx

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.spcontrol.aspx

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spuser.aspx

Summary

In this article we have explore the SharePoint Object Model and some basic coding examples with List and Library. The advanced coding examples will be provided at later point of time.

Posted in C#, SharePoint | Tagged: , , | 2 Comments »