Search This Blog

Download Document from Sharepoint Library C#

This is the code from which we can allow the user to download the document without giving him any access rights.

This is the condition when want to give one functionality for downloading in site.

Function 1. In first function we need to pass filename, document Id and serverpath.

server path is a temperory path we need to copy file on server until user download it.

public string DownloadDocument(string FileName, int documentId, string serverpath)


ContractDataAccess cda = new ContractDataAccess();

Stream file;




file = cda.GetDocumentById(documentId);

FileStream fsDocFile;

StreamReader srWebSrc = new StreamReader(file);

string filepath = serverpath + FileName;


fsDocFile = System.IO.File.Open(filepath, FileMode.Truncate);


fsDocFile = System.IO.File.Open(filepath, FileMode.Create);




return filepath;



catch (Exception ex)


throw ex;



we need to pass sharepoint ID of the document to the function.

public Stream GetDocumentById(int documentId)


//The four values below are retrieved from config file. They gives the values for authenticated user, sharepoint website path, password, and server name. This can be used on same server only.

string user = ConfigurationManager.AppSettings["User"].ToString();

string webUrl = ConfigurationManager.AppSettings["WebUrl"].ToString();

string pass = ConfigurationManager.AppSettings["Password"].ToString();

string server = ConfigurationManager.AppSettings["Server"].ToString();

NetworkCredential credentials = new NetworkCredential(user, pass, server);

ListItem item = GetdocumentFromId(documentId);

if (item != null)


using (ClientContext clientContext = new ClientContext(webUrl))


clientContext.Credentials = credentials;

FileInformation fInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, item["FileRef"].ToString());

return fInfo.Stream;



return null;


public ListItem GetdocumentFromId(Int32 documentId)


Contract contract = null;

List resultlist = null;

ListItem contractItem = null;



//The four values below are retrieved from config file. They gives the values for authenticated user, sharepoint website path, password, and server name. This can be used on same server only.

string webUrl = ConfigurationManager.AppSettings["WebUrl"].ToString();

string user = ConfigurationManager.AppSettings["User"].ToString();

string pass = ConfigurationManager.AppSettings["Password"].ToString();

string server = ConfigurationManager.AppSettings["Server"].ToString();

NetworkCredential credentials = new NetworkCredential(user, pass, server);

using (var clientContext = new ClientContext(webUrl))


clientContext.Credentials = credentials;

resultlist = clientContext.Web.Lists.GetByTitle("<ListName>");

contractItem = resultlist.GetItemById(documentId);





contract = new Contract();


catch (Exception exception)




return contractItem;


Submitted By Nipesh Shah @ 9/26/2011 7:51:10 PM

Javascript Code to hide html object on webpage

Javascript code to hide any element for hiding the object.

This can also be good for Sharepoint.

<script type="text/javascript">

document.getElementById('ClientId of the Object').style.display="none";


Submitted By Nipesh Shah @ 9/22/2011 11:29:34 AM

Create Sequential Workflows for SharePoint 2010 in Visual Studio 2010?

Code to find Days between two dates in C#

Code to calculate no of days between two dates

DateTime date1 = new DateTime(1986, 8, 10);

DateTime date2 = new DateTime(2011, 3, 12);

TimeSpan ts = date2 - date1;

int days = ts.TotalDays;

Submitted By Nipesh Shah @ 9/20/2011 12:39:35 PM

Add Skype Button on your blog or website

Skype is widely used communication s/w.

Skype is providing Chat button for your website or blog.

You need to just fill the simple form on and it will generate one html.

Copy this html and paste it where ever you want.(On blog or on Website).

It helps people to directly chat with you.

Nipesh Shah
Submitted By Nipesh Shah @ 9/20/2011 12:30:37 PM

Show Content per user in sharepoint 2010

In sharepoint there is a Security control using which we can hide or show the page content according to the permissions of the user.

We can use SPSecurityTrimmedControl for doing so. Using this control is very easy. You need to add this tag before the code you want to hide.

Example :

<Sharepoint:SPSecurityTrimmedControl runat="server" Permissions="ManageLists">

Put your code, sharepoint control etc here


Permissions are the criteria from which we can Manage the security.

List of various permissions is as under.

EmptyMask - Has no permissions on the Web site. Not available through the user interface.

ViewListItems - View items in lists, documents in document libraries, and view Web discussion comments.

AddListItems - Add items to lists, add documents to document libraries, and add Web discussion comments.

EditListItems - Edit items in lists, edit documents in document libraries, edit Web discussion comments in documents, and customize Web Part Pages in document libraries.

DeleteListItems - Delete items from a list, documents from a document library, and Web discussion comments in documents.

ApproveItems - Approve a minor version of a list item or document.

OpenItems - View the source of documents with server-side file handlers.

ViewVersions - View past versions of a list item or document.

DeleteVersions - Delete past versions of a list item or document.

CancelCheckout - Discard or check in a document which is checked out to another user.

ManagePersonalViews - Create, change, and delete personal views of lists.

ManageLists - Create and delete lists, add or remove columns in a list, and add or remove public views of a list.

ViewFormPages - View forms, views, and application pages, and enumerate lists.

Open - Allow users to open a Web site, list, or folder to access items inside that container.

ViewPages - View pages in a Web site.

AddAndCustomizePages - Add, change, or delete HTML pages or Web Part Pages, and edit the Web site using a SharePoint Foundation-compatible editor.

ApplyThemeAndBorder - Apply a theme or borders to the entire Web site.

ApplyStyleSheets - Apply a style sheet (.css file) to the Web site.

ViewUsageData - View reports on Web site usage.

CreateSSCSite - Create a Web site using Self-Service Site Creation.

ManageSubwebs - Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites.

CreateGroups - Create a group of users that can be used anywhere within the site collection.

ManagePermissions - Create and change permission levels on the Web site and assign permissions to users and groups.

BrowseDirectories - Enumerate files and folders in a Web site using Microsoft Office SharePoint Designer 2007 and WebDAV interfaces.

BrowseUserInfo - View information about users of the Web site.

AddDelPrivateWebParts - Add or remove personal Web Parts on a Web Part Page.

UpdatePersonalWebParts - Update Web Parts to display personalized information.

ManageWeb - Grant the ability to perform all administration tasks for the Web site as well as manage content. Activate, deactivate, or edit properties of Web site scoped Features through the object model or through the user interface (UI). When granted on the root Web site of a site collection, activate, deactivate, or edit properties of site collection scoped Features through the object model. To browse to the Site Collection Features page and activate or deactivate site collection scoped Features through the UI, you must be a site collection administrator.

UseClientIntegration - Use features that launch client applications; otherwise, users must work on documents locally and upload changes.

UseRemoteAPIs - Use SOAP, WebDAV, or Microsoft Office SharePoint Designer 2007 interfaces to access the Web site.

ManageAlerts - Manage alerts for all users of the Web site.

CreateAlerts - Create e-mail alerts.

EditMyUserInfo - Allows a user to change his or her user information, such as adding a picture.

EnumeratePermissions - Enumerate permissions on the Web site, list, folder, document, or list item.

FullMask - Has all permissions on the Web site. Not available through the user interface.

Submitted By Nipesh Shah @ 9/20/2011 12:17:49 PM

Generate XML from directory Structure

The given code snippets is used to generate the Directory Structure to an XML File.

This XML File can be used in various ways, for appending in treeview, store as a file, export in string format etc.

public String getXMLFromDirectoryStructure()




string ProjectFolder = "Project"; //absolute path for project

string appPath = "C:\Project"; //absolute path for project

string bodyFile = Path.Combine(appPath, @"Snippets\");

XmlDocument doc = new XmlDocument();

doc.LoadXml("< $ProjectFolder$ name=\"$ProjectFolder$\" type=\"DIR\">" + "</$ProjectFolder$>");

DirectoryInfo mainDir = new DirectoryInfo(bodyFile);

foreach (DirectoryInfo dir in mainDir.GetDirectories())


XmlElement elem = GetData(dir.FullName, doc);



StringWriter sw = new StringWriter();

XmlTextWriter tx = new XmlTextWriter(sw);


doc.Save(bodyFile + "\\" + "Path.xml");

return sw.ToString();


catch (Exception)



return "";


private static XmlElement GetData(string dirName, XmlDocument doc)


//create a new node for this directory

XmlElement elem = doc.CreateElement("dir");

DirectoryInfo di = new DirectoryInfo(dirName);

elem.SetAttribute("name", di.Name);

elem.SetAttribute("type", "DIR");

foreach (DirectoryInfo dinf in di.GetDirectories())


//Recursively call the directory with all underlying dirs and files

XmlElement elemDir = GetData(dirName + "\\" + dinf.Name, doc);

if (dinf.GetDirectories().Count() + dinf.GetFiles().Count() == 0)


elemDir.InnerText = "";




return elem;


Submitted By Nipesh Shah @ 9/19/2011 4:56:27 PM

Jquery Server Control For ASP.NET

Jquery Server Controls From DotNetAge provides server side events.

Download DLLs from

Below is example for Accordion

<%@ Register Assembly="DNA.UI.JQuery" Namespace="DNA.UI.JQuery" TagPrefix="DotNetAge" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<link href="Jquery/jquery-ui-1.8.13.custom.css" rel="stylesheet" type="text/css" />

<link href="Jquery/dna.ui.css" rel="stylesheet" type="text/css" />


<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<asp:ScriptManager ID="ScriptManager1" runat="server">


<asp:LinkButton ID="lnkPopUp" runat="server" OnClientClick="return false;">Open PopUp Window</asp:LinkButton>

<DotNetAge:Accordion ID="Accordion1" runat="server" Navigation="true" AllowCollapseAllSections="true"

CollapseAnimation="EaseSlide" CssClass="ui-accordion-header" ContentCssClass="ui-accordion-content"



<DotNetAge:NavView ID="NavView1" runat="server" Text="Dashboard" NavigateUrl="About.aspx"



<DotNetAge:NavItem Text="Go to Dashboard" NavigateUrl="About.aspx" />



<DotNetAge:NavView ID="NavView2" runat="server" Text="Title 2">


<DotNetAge:NavItem Text="All Contacts" NavigateUrl="About.aspx" />

<DotNetAge:NavItem Text="Persional" />



<DotNetAge:NavView ID="NavView3" runat="server" Text="Title 3">


<DotNetAge:NavItem Text="All Contacts" />

<DotNetAge:NavItem Text="Persional" />



<DotNetAge:NavView ID="NavView4" runat="server" Text="Title 4">


<DotNetAge:NavItem Text="All Contacts" />

<DotNetAge:NavItem Text="Persional" />






for server side binding...

using DNA.UI.JQuery;

protected void Page_Load(object sender, EventArgs e)


DNA.UI.JQuery.View v1 = new DNA.UI.JQuery.View();

v1.Text = "My Mail"; //Title for accordion

NavView n1 = new NavView();

n1.ID = "nav1";

n1.Text = "Inbox"; // sub item for accordion




Visit for Documentation


Manthan Vyas
Submitted By manthan vyas @ 9/19/2011 4:25:21 PM

Code to send Email from C# Code

Code to send Email from C# Code
MailMessage msg = new MailMessage();
msg.From = new MailAddress(mailFrom);
msg.Subject = mailSubject;
msg.Body = mailBody;
msg.IsBodyHtml = true;
//msg.Attachments.Add(new Attachment(mailAttachment));
SmtpClient smtpclient = new SmtpClient();
NetworkCredential nc = new NetworkCredential("GMail Email ID", "GMail Password");
smtpclient.Credentials = nc;
smtpclient.EnableSsl = true;
smtpclient.Host = "";
smtpclient.Port = 587;
Link Within Related Posts Plugin for WordPress, Blogger...