Friday, December 10, 2010

Check if list exist in sharepoint / Get specific List in Sharepoint 2010

SPSite site = "sitename"; SPWeb Web = site.OpenWeb(); if (Web != null) { SPList list = Web.Lists.TryGetList("Your List Title"); if (list != null) { //do something list.Title = "Working Documents"; list.Update(); } }

Monday, December 6, 2010

Sharepoint Document library Version History programmatically

Basically my requiremnt is to show version history and hitory log as mentioned below. 

History Section --------------- LastModifiedBy, LastModifiedOn, Comments,
 Version History Log Section --------------------- Time ...CheckoutBy X Person Time...CheckIn by Y Person


History Section : I have 2 problems... SPListItemVersion : it does not have property "comments" but i should show "comments" as well in the UI. SPFileVersion : If i use this object..everything is good...but its not showing up latest recrord. for ex..it is only showing 2 records even if there are 3 history records for the document.


 Here is the Solution --------------------- I am getting latest rows using SPListItem and old record using SPFile.Versions. 


finally i am adding to one temporary datatable and binded to datgrid I am not sure whether it is good practice.

---
 private bool checkdocumentExists(SPWeb web, string projectID, string taskID, string itemID, string contentType)
    {
        bool documentExists = false;
        string ContentTemplate = string.Empty;
       // string ContentTemplateName = string.Empty;
       SPSite parentSite = new SPSite(web.Url);
       
        try
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite ElevatedSite = new SPSite(parentSite.ID))
                //using (SPSite ElevatedSite = new SPSite("http://w2msmossmgn02:33980/sites/P000756/"))
                {
                    //Response.Write(ElevatedSiteCollection.ToString());
                    using (SPWeb ElevatedWeb = ElevatedSite.OpenWeb())
                    {
                        // Response.Write(ElevatedWeb.Title);
           
                        SPList documentList = ElevatedWeb.Lists["Working Documents"];
                        //SPList documentList = web.Lists["Test11"];

                        SPQuery qryPendingProjects = new SPQuery();

                        //qryPendingProjects.Query = string.Format("<Where><And><Eq><FieldRef Name='ContentType' /><Value Type='Computed'>" + contentType + "</Value></Eq><Eq><FieldRef Name='OPSProjectID'/><Value Type='Text'>" + projectID + "</Value></Eq></And></Where>");
                        qryPendingProjects.Query = string.Format("<Where><And><And><Eq><FieldRef Name='OPSItemID' /><Value Type='Computed'>" + itemID + "</Value></Eq><Eq><FieldRef Name='OPSCustomProjectID' /><Value Type='Text'>" + projectID + "</Value></Eq></And><Eq><FieldRef Name='OPSTaskID' /><Value Type='Text'>" + taskID + "</Value></Eq></And></Where>");

                        SPListItemCollection documentListCollection = documentList.GetItems(qryPendingProjects);
                      
                        ContentTemplate = "/_layouts/OPS/" + contentType;
                        SPListItem docListItem = null;

                        if (documentListCollection.Count > 0)
                        {

                            //SPListItem docListItem = documentListCollection[0];
                            docListItem = documentListCollection[0];

                            lblDocumentTitle.InnerText = docListItem["Name"].ToString();
                            lblProjectID.InnerText = docListItem["OPSCustomProjectID"].ToString();
                            SPFieldUserValue ModifiedBy = new SPFieldUserValue(web, docListItem["Editor"].ToString());
                            lblModifiedBy.InnerText = ModifiedBy.LookupValue;

                            lblModified.InnerText = docListItem["Modified"].ToString();
                            //lblModified.InnerText = String.Format("mm-dd-yyyy", (DateTime)docListItem["Modified"]);


                            lbldocumentVersion.InnerText = docListItem["_UIVersionString"].ToString();
                            //documentLink.InnerHtml = "<a href='javascript:void(0)' onclick=\"editDocumentWithProgID2('" + web.Url + "/" + documentList.Title.ToString() + "/" + docListItem["FileLeafRef"].ToString() + "' , '', 'SharePoint.OpenDocuments', '0', '" + web.Url + "', '0');\">View Document</a>";
                            documentLink.InnerHtml = "<a href='javascript:void(0)' onclick=\"editDocumentWithProgID2('" + web.Url + "/" + documentList.Title.ToString() + "/" + docListItem["FileLeafRef"].ToString() + "' , '', 'SharePoint.OpenDocuments', '0', '" + web.Url + "', '0');\">View Document</a>";
                            documentExists = true;
                            SPFile currentFile = docListItem.File;

                            if (currentFile.CheckOutType == SPFile.SPCheckOutType.None)
                            {
                                //CheckoutLink.InnerHtml = "<a href='#' onclick=\"editDocumentWithProgID2('" + web.Url + "/" + documentList.Title.ToString() + "/" + docListItem["FileLeafRef"].ToString() + "', '', 'SharePoint.OpenDocuments', '1', '" + web.Url + "', '0');\">Edit Document</a>";
                                CheckoutLink.InnerHtml = "<a onclick=\"editDocumentWithProgID2('" + web.Url + "/" + documentList.Title.ToString() + "/" + docListItem["FileLeafRef"].ToString() + "', '', 'SharePoint.OpenDocuments', '1', '" + web.Url + "', '0');\" href=\"#\">Edit Document</a> | ";
                            }
                            divcreateNewDocument.Visible = false;
                            divPage.Visible = true;
                            divDocumentData.Visible = true;

                        }
                        else
                        {
                            documentExists = false;
                            addQueryList(ElevatedWeb, SPContext.Current.Web.CurrentUser.LoginName, projectID, taskID, itemID);
                           
                            divcreateNewDocument.InnerHtml = "<A onclick=\"createNewDocumentWithProgID('" + web.Url + "/" + ContentTemplate + "', '" + web.Url + "/" + documentList.Title.ToString() + "', 'SharePoint.OpenDocuments', false);\" href=\"#\">Create New Document</A>";
                            divcreateNewDocument.Visible = true;
                            //divDocumentData.Visible = false;
                            divError.Visible = false;
                        }
                        //Response.Write(parentSite.ID);


                        //Response.Write(ElevatedSite.Title + "tiotle");
                        if (docListItem != null)
                        {
                            // Create new DataTable.
                            DataTable dtHistory = new DataTable();
                            try
                            {

                                //starts History section
                                // Declare DataColumn and DataRow variables.
                                DataColumn LastModifiedBy;
                                DataColumn LastModifiedOn;
                                DataColumn Comments;
                                DataColumn Version;
                                DataRow row;

                                // Create new DataColumn, set DataType, ColumnName
                                // and add to DataTable.   
                                //column.DataType = System.Type.GetType("System.Int32");
                                LastModifiedBy = new DataColumn();
                                LastModifiedBy.ColumnName = "LastModifiedBy";
                                dtHistory.Columns.Add(LastModifiedBy);

                                LastModifiedOn = new DataColumn();
                                LastModifiedOn.ColumnName = "LastModifiedOn";
                                dtHistory.Columns.Add(LastModifiedOn);

                                Comments = new DataColumn();
                                Comments.ColumnName = "Comments";
                                dtHistory.Columns.Add(Comments);

                                Version = new DataColumn();
                                Version.ColumnName = "Version";
                                dtHistory.Columns.Add(Version);

                                SPFieldUserValue ModifiedBy = new SPFieldUserValue(web, docListItem["Editor"].ToString());

                                row = dtHistory.NewRow();
                                row["LastModifiedBy"] = ModifiedBy.LookupValue;
                                //row["LastModifiedOn"] = docListItem["Modified"].ToString();

                                DateTime dt = (DateTime)docListItem["Modified"];
                                // row["LastModifiedOn"] =String.Format("{MMM-dd-yyyy}", docListItem["Modified"].ToString());
                                row["LastModifiedOn"] = dt.ToString("dd-MMM-yyyy hh:mm:ss tt"); // String.Format("{0:d/M/yyyy HH:mm:ss}", dt);

                                if (docListItem["_CheckinComment"] != null) //Check In Comment
                                {
                                    if (docListItem["_CheckinComment"].ToString().Length >= 3)
                                        row["Comments"] = docListItem["_CheckinComment"].ToString().Remove(0, 3);
                                }

                                row["Version"] = docListItem["_UIVersionString"];
                                dtHistory.Rows.Add(row);

                                for (int i = 0; i < docListItem.File.Versions.Count; i++)
                                //for (int i = 0; i < 1; i++)
                                {
                                    row = dtHistory.NewRow();
                                    row["LastModifiedBy"] = docListItem.File.Versions[i].CreatedBy.Name;

                                    row["LastModifiedOn"] = docListItem.File.Versions[i].Created.ToLocalTime().ToString("dd-MMM-yyyy hh:mm:ss tt");
                                    //row["LastModifiedOn"] = docListItem.File.Versions[i].Created.ToLocalTime().ToString();
                                    row["Comments"] = docListItem.File.Versions[i].CheckInComment;

                                    //Response.Write("2nd loop: " + docListItem.File.Versions[i].CheckInComment);

                                    row["Version"] = docListItem.File.Versions[i].VersionLabel;
                                    dtHistory.Rows.Add(row);
                                }

                                //grdHistory.DataSource = docListItem.Versions;

                                dtHistory.DefaultView.Sort = "Version ASC";
                                grdHistory.DataSource = dtHistory;
                                grdHistory.DataBind();

                            }
                            catch (Exception ex)
                            {
                                Response.Write(ex.Message);
                            }
                            finally
                            {
                                dtHistory.Dispose();
                            }


                            //Activity log section
                            SPAuditQuery wssQuery;
                            SPAuditEntryCollection auditCol;
                            wssQuery = new SPAuditQuery(ElevatedWeb.Site);
                            wssQuery.RestrictToListItem(docListItem = documentListCollection[0]);
                            auditCol = ElevatedWeb.Site.Audit.GetEntries(wssQuery);

                            DataTable dtActivity = new DataTable("ActivityLog");
                            DataColumn colLog = new DataColumn();
                            colLog.ColumnName = "Log";
                            DataRow drow;
                            dtActivity.Columns.Add(colLog);

                            foreach (SPAuditEntry entry in auditCol)
                            {
                                if (entry.Event == SPAuditEventType.CheckOut || entry.Event == SPAuditEventType.CheckIn || entry.Event == SPAuditEventType.FileFragmentWrite)
                                {

                                    drow = dtActivity.NewRow();
                                    // if (ParseVersionNumber(entry.EventData) != "N/A")
                                    // {
                                    drow[0] = entry.Occurred.ToLocalTime() + " : " + entry.Event + " by " + GetUserNameById(entry.UserId, site);
                                    dtActivity.Rows.Add(drow);
                                    //}
                                }
                            }
                            grdActivitylog.DataSource = dtActivity;
                            grdActivitylog.DataBind();
                            dtActivity.Dispose();

                        }
                    }

                }
            });
        }

        catch (Exception ex)
        {
            spanError.InnerText = "\n" + ex.Message + "\n";
        }
        return documentExists;
       
    }

Saturday, April 18, 2009

Enable debugging in SharePoint

Open C:\Inetpub\wwwroot\wss\VirtualDirectories\sitedir\web.config You should also configure your SharePoint site to display any error messages that are generated by setting the customErrors tag's mode attribute to Off (the default setting suppresses all error messages): To get the full list of called modules listed on the error screen, you'll also need to set the SafeMode's CallStack attribute to "true":

Insert data into the splist

Monday, April 13, 2009

Application pages in sharepoint

<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" %>

Saturday, April 11, 2009

difference between .dwp and .webpart

The difference is .dwp was the file extension used in version 2 of SharePoint and .webpart is a new extension used in version 3.

Sunday, April 5, 2009

SharePoint CAML Query

//Products list should have Price col, and productName col. it gets the data of products which r price >10 and <50 SPWeb web = new SPSite("http://spdevserver:12261/sites/spsite1/").OpenWeb(); SPList list = web.Lists["Products"]; SPQuery query = new SPQuery(); string str = "1050 10 40"; query.Query = str; SPListItemCollection items = list.GetItems(query); foreach (SPListItem item in items) { System.Console.Write(item.DisplayName); System.Console.Write("\n"); }

Followers