Jean Paul's Blog

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

    Advertisements
  • 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
  • Advertisements

Posts Tagged ‘c#’

Programmatically Read Discussion Board & Replies

Posted by Paul on October 21, 2014

I searched a lot for Server Object Code in reading Discussion Board Items & Replies. As cannot find one, following is created.

Challenge

You need to programmatically get all discussion items along with their replies.

Steps

This is our Discussion Board.

image

This is the code to retrieve all discussion items.

using (SPSite site = new SPSite(“http://hpvm”))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists.TryGetList(“Discussion Board”);

if (list != null)

{

SPQuery query = new SPQuery();

query.ViewFields = “<FieldRef Name=’Title’ />”;

SPListItemCollection itemColl = list.GetItems(query);

foreach (SPListItem item in itemColl)

{

System.Console.WriteLine(item[“Title”].ToString());

}

}

}

}

Make sure the code is returning values like this.

image

Now we are writing the code to return the replies.

private static void GetReplies(SPList list, SPListItem item)

{

SPQuery query = new SPQuery();

query.Folder = item.Folder;

SPListItemCollection collection = list.GetItems(query);

SPListItem replyItem = collection[0];

string body = (string)replyItem[“Body”];

string author = (string)replyItem[“Author”];

System.Console.WriteLine(body);

System.Console.WriteLine(author);

}

Following is the output on running the console application.

image

You can see the Author is returned mixing with ID. You can use the following method to extract the correct User Name from the string.

private static string GetUserName(string author, SPList list)

{

string result = author;

if (author.Contains(“;”))

{

int id = int.Parse(author.Split(‘;’)[0]);

SPUser user = list.ParentWeb.SiteUsers.GetByID(id);

result = user.Name;

}

return result;

}

Now the user name seems to be better.

image

image

I am creating a Console Application to retrieve the same.

References

http://bit.ly/1tIX5NV

Summary

In this article we have explored how to fetch Discussion Board Items & Replies. The source code is attached here with the article.

Advertisements

Posted in SharePoint, SharePoint 2013 | Tagged: , , , , | Leave a Comment »

Programmatically Refresh Content Query Web Part

Posted by Paul on September 17, 2013

In this article we can explore a real life scenario of refreshing Content Query Web Part programmatically.

clip_image002

I hope the reader is having good knowledge of:

1. SharePoint page editing

2. Web Part insertion

3. Web Part creation using Visual Studio

4. Web Part Deployment

Scenario

Following are the scenario items:

1. A home site with 2 web parts, project button web part & Content Query (CQ) web part

2. 2 project sites, each with Tasks list

3. On click of button, the particular project tasks should be shown in the CQ web part

How to achieve the same?

clip_image004

What is Content Query web part?

Content Query web part allows list querying & it is a part of Enterprise Content Management (ECM) functionality. You can add the web part from the Content Query category. You need to enable the Publishing feature to access the web part. Within code, the web part is called Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart

Step 1: Create Project Sites

Create 2 project sites of template Team Site & add some tasks into it. Make sure you remember the URLS.

The Project 1 Tasks list:

clip_image006

The Project 2 Tasks list:

clip_image008

Step 2: Design Project Buttons web part

Open Visual Studio & Perform the following:

1. Create a new Visual Web Part project of type Farm Solution

2. Add reference to Microsoft.SharePoint.Publishing namespace

3. Delete the existing web part inside the project

4. Create a new Visual Web Part & name it as ProjectButtonsWebPart

5. Replace the Page Load event with following code.

private static Dictionary<string, string> _projectUrl;

protected void Page_Load(object sender, EventArgs e)

{

_projectUrl = new Dictionary<string, string>();

_projectUrl.Add(“Project 1”, “/projectsite1”);

_projectUrl.Add(“Project 2”, “/projectsite2”);

// Create UI controls for Projects

foreach (string project in _projectUrl.Keys)

{

Button button = new Button();

button.Text = project;

button.Click += button_Click;

this.Controls.Add(button);

}

}

6. Add the following method for button click event handler.

private void button_Click(object sender, EventArgs e)

{

string url = _projectUrl[(sender as Button).Text];

SPSite site = SPContext.Current.Site;

SPWeb web = site.RootWeb;

web.AllowUnsafeUpdates = true;

SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(“SitePages/Home.aspx”, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

foreach (System.Web.UI.WebControls.WebParts.WebPart w in manager.WebParts)

if (w is Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart)

{

Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart cwp = (w as Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart);

SPWeb targetWeb = site.OpenWeb(url);

cwp.WebUrl = targetWeb.ServerRelativeUrl;

//set the guid of the list

cwp.ListGuid = targetWeb.Lists[“Tasks”].ID.ToString();

PublishingWeb pweb = PublishingWeb.GetPublishingWeb(targetWeb);

cwp.Update(pweb);

manager.SaveChanges(w);

}

ClientScriptManager cs = Page.ClientScript;

String csName = “ReloadClientScript”;

Type csType = this.GetType();

if (!cs.IsStartupScriptRegistered(csType, csName))

{

StringBuilder csText = new StringBuilder();

csText.Append(“<script type=”text/javascript”>”);

csText.Append(“this.location.reload(); </”);

csText.Append(“script>”);

cs.RegisterStartupScript(csType, csName, csText.ToString());

}

}

7. Ensure you have the following namespaces included.

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;

using Microsoft.SharePoint.Publishing;

using Microsoft.SharePoint.WebPartPages;

8. Resolve any namespace issues like System.Web.UI.WebControls.WebParts.WebPart

9. Build the project

10. Deploy the project

11. Insert the Project Buttons web part to the home page. It looks like below.

clip_image010

Step 3: Insert the Content Query web part

Now we can insert the Content Query web part into the home page. Open page in edit mode & insert web part from the Content Rollup group as shown below.

clip_image012

Edit the web part & make the Presentation > Link property as empty.

clip_image014

Now the page looks like:

clip_image016

Step 4: Test the buttons

Now click on the Project 1 button & you should see the Content Query web part updated with tasks.

clip_image018

Now click on the Project 2 button & you should see the tasks changed with Project Site 2.

clip_image002[1]

To summarize the activities, please note the following:

1. The Project Buttons web part have 2 hard coded paths inside it

2. On click of the button, the Content Query web part is refreshed by changing the List ID property

3. After the button click is processed, a client side startup script is registered to reload the page

4. Now on clicking the button, the content query web part will display tasks list from the corresponding project site.

References

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

Summary

In this article we have explored a typical real world scenario of refreshing a web part from another web part. I hope this will be useful to you in SharePoint development.

The source code can be downloaded here.

Posted in SharePoint, SharePoint 2010 | Tagged: , , , , , , , | Leave a Comment »

Create Site automatically when a List item is added

Posted by Paul on September 3, 2013

In this article I would like to take you through a real world scenario.

Scenario

In your company there are multiple projects going on. For each project, they require a separate site. The site creation has to be done through a list item creation.

A list named Projects exists in the root SharePoint site. A user can add a new item in the list along with the Project information.

1. Project Name

2. Project Description

3. Start Date

4. End Date

5. Team Members

Step 1: Create Projects list

Please go ahead & create a new list name Projects. Add the columns as displayed below.

Ensure that the Team Members column is of type User or Group & it allows multiple selections.

Step 2: Create SharePoint Project

Now we can start with our Event Handler Project. Open Visual Studio 2012 & create an empty SharePoint Project.

If you do not have Visual Studio 2012, you need to install it first. After that, install the Office Tools for Visual Studio 2012, it contains the SharePoint project templates.

In the next page, choose the Farm Solution option.

Now, right click on the project & add an Event Receiver.

Choose the custom list option & “item was added” event as given below:

In the item added event, place the following Site Creation code.

public override void ItemAdded(SPItemEventProperties properties)

{

base.ItemAdded(properties);

if (properties.List.Title == “Projects”)

{

// Get Properties

string name = properties.ListItem[“Title”].ToString();

string description = properties.ListItem[“Description”].ToString();

DateTime startDate = (DateTime)properties.ListItem[“Start Date”];

DateTime endDate = (DateTime)properties.ListItem[“End Date”];

// Create sub site

SPWeb web = properties.Site.AllWebs.Add(name.Replace(” “, string.Empty), name,

description, 0, SPWebTemplate.WebTemplateSTS, false, false);

web.Update();

}

}

Step 3: Execute Project

Now execute the project using F5 key& while debugging active, create a new project item inside Projects list.

You can see that a new sub site is created based on the input information.

Step 4: View sub site

Use the Site Contents link to view the sub sites.

Scrolling down to the bottom of the page, you can see our new site named Supercast.

On clicking the sub site, it opens as shown below:

In this example, we have stopped after creation of sub sites. In the real world projects we need to:

1. Create an Internal List with all project information

2. In the add event, create a web part display project information from list & add to home page

3. In the original Projects list, create a new property named URL & set that to the newly created site

4. In the new site, Owners & Members permission groups can be automatically created

5. Create common project library, list, meeting, discussion lists in the site.

In appropriate sense, the custom solution can include a custom site template with all pre-defined lists & libraries.

References

http://bit.ly/137vrNA

Summary

In this article we have explored a real world scenario of project site creation through list item adding event. The source code is attached with the article.

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

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

Posted by Paul 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();

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

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

Posted by Paul 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 »

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

Posted by Paul 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 Paul 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 Document Library

Posted by Paul 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 Paul 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 – Create List Definition using Visual Studio

Posted by Paul 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 »