Wednesday, May 26, 2010

How to attach,delete,upload files to SharePoint List Item using Object Model

Snippet code of deleting attachment from SharePoint list item : private void DeleteAttachment(int NodeID, String strFileName)
{
SPContext.Current.Web.AllowUnsafeUpdates = true;
SPListItem delItem = lstAudit.GetItemById(NodeID);
SPAttachmentCollection atCol = delItem.Attachments;
foreach (string strDelfileName in atCol)
{
if (strDelfileName == strFileName)
{
atCol.Delete(strDelfileName);
delItem.Update();
lstAudit.Update();
return;
}}}

Snippet code for downloading attachment from SharePoint List Item :

private void DownloadAttachment(string FileName)

{

try

{

string AttachmentURL = string.Empty;

AttachmentURL = FileName;

string strName = AttachmentURL.Substring(AttachmentURL.LastIndexOf(“/”) + 1);

string sbURL = AttachmentURL.Trim();

System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;

Response.AppendHeader(“Content-disposition”, “attachment; filename=” + strName);

Response.AppendHeader(“Pragma”, “cache”);

Response.AppendHeader(“Cache-control”, “private”);

Response.WriteFile(sbURL);

Response.End();

}

catch (Exception eDwn)

{

Response.Write(eDwn.Message);

}

}



Snippet code of uploading document to SharePoint List Item :



protected void btnUpload_Click(object sender, EventArgs e)

{

try

{

string fileName = “”;

string strExtensionName = “”;



fileName = System.IO.Path.GetFileName(FileUpload.PostedFile.FileName);



if (fileName != “”)

{

strExtensionName = fileName.Substring(fileName.IndexOf(“.”) + 1);

if (strExtensionName.Equals(“webpart”)

strExtensionName.Equals(“dll”)

strExtensionName.Equals(“bat”)

strExtensionName.Equals(“exe”))

{

lblMessage.Visible = true;

lblMessage.Text = “Invalid fileName!!”;

}

else

{

string _fileTime = DateTime.Now.ToFileTime().ToString();



string _fileorgPath = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);



if (txtFileName.Text.Trim().Length > 0)

{

fileName = fileName.Replace(fileName.Substring(fileName.LastIndexOf(“\\”) + 1), txtFileName.Text) + “.” + strExtensionName;

}

string _newfilePath = _fileTime + “~” + fileName;



string tempFolder = Environment.GetEnvironmentVariable(“TEMP”);





string _filepath = tempFolder + _newfilePath;



FileUpload.PostedFile.SaveAs(_filepath);



AddRow(fileName, _filepath, 0, true);

}

}

else

{



lblMessage.Visible = true;

lblMessage.Text = “Please Selct file Name”;



}



}

catch (Exception Ex)

{

Response.Write(Ex.Message);

}



}





protected void dgdUpload_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

int recordToDelete = e.RowIndex;



//dt = (DataTable)Page.Session["Files"];

dt = (DataTable)ViewState["Files"];



int cn = dt.Rows.Count;



if (Convert.ToInt32(dt.Rows[recordToDelete].ItemArray[0]) != 0)

{

DeleteAttachment(Convert.ToInt32(dt.Rows[recordToDelete].ItemArray[0]), dt.Rows[recordToDelete].ItemArray[1].ToString());

}



dt.Rows.RemoveAt(recordToDelete);



dt.AcceptChanges();

//Page.Session["Files"] = dt;

ViewState["Files"] = dt;

dgdUpload.DataSource = dt;

dgdUpload.DataBind();

}

private void AddMoreColumns()

{



dt = new DataTable(“Files”);



dc = new DataColumn(“ID”, Type.GetType(“System.Int16″));

dt.Columns.Add(dc);



dc = new DataColumn(“FileName”, Type.GetType(“System.String”));

dt.Columns.Add(dc);



dc = new DataColumn(“FilePath”, Type.GetType(“System.String”));

dt.Columns.Add(dc);



//Page.Session["Files"] = dt;

ViewState["Files"] = dt;



}

private void AddRow(string file, string path, int ID, Boolean bolCheckForfiles)

{



Boolean bolAddRow = true;

//dt = (DataTable)Page.Session["Files"];

dt = (DataTable)ViewState["Files"];



if (dt == null)

{

AddMoreColumns();



}

if (bolCheckForfiles)

{



if (dt.Rows.Count > 0)

{

foreach (DataRow drExistingrow in dt.Rows)

{



if (drExistingrow["FileName"].ToString() == file)

{

bolAddRow = false;

}

}

}

}

if (bolAddRow)

{



dr = dt.NewRow();







dr["ID"] = ID;

dr["FileName"] = file;

dr["FilePath"] = path;







dt.Rows.Add(dr);



//Page.Session["Files"] = dt;

ViewState["Files"] = dt;



dgdUpload.DataSource = dt;



dgdUpload.DataBind();//bind in grid



}

else

{

lblMessage.Visible = true;

lblMessage.Text = “Same File Name already exists!!!”;

}

}









protected void dgdUpload_RowCommand(object sender, GridViewCommandEventArgs e)

{

if (e.CommandName == “View”)

{

string file = e.CommandArgument.ToString();

DownloadAttachment(file);



}

}







if (dt != null)

{



int _dtcnt = dt.Rows.Count;

foreach (DataRow dr in dt.Rows)

{



Boolean bolAddAttachment = true;

fileName = dr["FileName"].ToString();

if (itmCorrectiveActionFinding.Attachments.Count > 0)

{

foreach (string strAttachedname in itmCorrectiveActionFinding.Attachments)

{



if (fileName == strAttachedname)

{

bolAddAttachment = false;



}

}

}

if (bolAddAttachment)

{

string strFilepath = dr["FilePath"].ToString();



StreamReader sr = new StreamReader(strFilepath);



Stream fStream = sr.BaseStream;



contents = new byte[fStream.Length];



fStream.Read(contents, 0, (int)fStream.Length);



fStream.Close();



itmCorrectiveActionFinding.Attachments.Add(fileName, contents);



itmCorrectiveActionFinding.Update();

lstCorrectiveActionFinding.Update();

SPContext.Current.Web.Update();

System.IO.File.Delete(strFilepath);



}

}

}

Wednesday, May 12, 2010

Introducing the SharePoint Object Model

As an alternative to programming against the SharePoint web services you can use the SharePoint object model. The object model can be used when the application will run on the server where SharePoint is installed (such as a console or WinForm application) or in assemblies that are run within a site (such as a Web Part or Web User Controls).

How to the SharePoint Object Model ?
First, you will need to create a reference to “SharePoint.dll” assembly in your Visual Studio 2005/2008 project. This is located at: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll

1. Get Attachment Name                                                                                                                      
public string getAttachmentName(string ItemID)
{
string strDocName = "";
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();
SPList List = myWeb.Lists["MyList"];
SPListItem splstItem = List.Items.GetItemById(Convert.ToInt32(ItemID));
if (splstItem.Attachments.Count > 0)
{
SPAttachmentCollection spColl = splstItem.Attachments;
strDocName = spColl[0];
}
return strDocName;
}
2. Get Items count from the list using SPQuery
public int GetItemsCount(string strStatus)
{
StringBuilder strQuery = new StringBuilder();
strQuery.Append("<Where>");
strQuery.Append("<Eq>");
strQuery.Append("<FieldRef Name='Status' />");
strQuery.Append("<Value Type='Choice'>" + strStatus+ "</Value>");
strQuery.Append("</Eq>");
strQuery.Append("</Where>");

SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();
SPList List = myWeb.Lists["MyList"];
SPQuery oSPQuery = new SPQuery();
oSPQuery.Query = strQuery.ToString();
SPListItemCollection items = List.GetItems(oSPQuery);
return items.Count;
}
3. Insert New Item in the list
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();
SPList myList = myWeb.Lists["MyList"];
SPListItem item = myList.Items.Add();
item["Title"] = "Amit Phule";
item.Update();
4. Get List Items count
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();
SPList List = myWeb.Lists["MyList"];
return List.Items.Count;
5. Update List Item from Item ID
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();
SPList List = myWeb.Lists["DCCDocs"];
SPListItem oListItem = List.Items.GetItemById(Convert.ToInt32(ItemID));
oListItem["Title"] = "New Title";
oListItem.Update();
6. Delete List Item from Item ID
Code Here
7. Send Email from SharePoint
private void SendMail(string To, string Subject, string Body)
{
SPSite mySite = SPContext.Current.Site;
SPWeb oWeb = mySite.OpenWeb();
SPUtility.SendEmail(oWeb, true, true, To, Subject, Body);
}
8. Get List Item from CAML Query
StringBuilder strQuery = new StringBuilder();
strQuery.Append("<Where>");
strQuery.Append("<Eq>");
strQuery.Append("<FieldRef Name='Status' />");
strQuery.Append("<Value Type='Choice'>" + strStatus+ "</Value>");
strQuery.Append("</Eq>");
strQuery.Append("</Where>");
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();
SPList List = myWeb.Lists["MyList"];
SPQuery oSPQuery = new SPQuery();
oSPQuery.Query = strQuery.ToString();
SPListItemCollection items = List.GetItems(oSPQuery);
foreach (SPItem item in items)
{
  TxtTitle.text=item["Title"].ToString();
}
9. Get User Groups
private Boolean IsCurrentUserGroup(string strGroupName)
{
Boolean isGroupPresent=false;
SPUser oCurrentUser = SPContext.Current.Web.CurrentUser;
foreach (SPGroup oSPGroup in oCurrentUser.Groups)
{
if (oSPGroup.Name.Equals(strGroupName))
isGroupPresent= true;
}
return isGroupPresent;
}
10. Title
Code Here


Monday, May 3, 2010

How to delete a timer job in SharePoint or Solution is always remain in Retracting state.

Problem : A deployment or retraction is already under way for the solution "xxx.wsp" , and only one deployment or retraction at a time is supported


Sometime this error has been occured from Windows SharePoint Services Administration command when the user do retractsolution or deploysolution like the follwing

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN>stsadm -o retractsolution -name "%PackageName%" -local -url %TargetWebUrl%

or

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN>stsadm -o deploysolution -name "%PackageName%" -local -allowGacDeployment -url %TargetWebUrl%

it occurs if anomalies deployment is running for the same package in the backend due to some previous deployment has been crashed before for some reason.

Solution:
To avoid this problem do the followings:

1. Look for the deploy jobId to break the running by the following command:

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN>stsadm-o enumdeployments

2. Cancel the deploy typing the following command:

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN>stsadm-o canceldeployment-id "GUID jobId"

3. Check that deploy has been canceled by typing the following command:

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN>stsadm-o enumdeployments

Hope it should work.