Pages

Showing posts with label Sharepoint 2007. Show all posts
Showing posts with label Sharepoint 2007. Show all posts

Monday, May 19, 2014

Count Related Field

How many times we have cursed SharePoint for not able to get the item count natively without writing code or using workflow. There is an easier way which I stumbled up recently but may be some of you have already figured this out earlier. I wanted to document this so this can be useful for someone like me who is always interested in code.

Recently when I was working on a project where there is absolutely no server side code, pretty much everything was done at the client side. There was a need to get item count per category. This is simple on the list because we could just do a group by and we would know how many items in a particular category, but we wanted to use those number to draw chart. The group by numbers will not be useful and we cannot use char web part (yes I know chart part is gone in 2013 but this project is still in 2010).

How do we do this? We had a lists of categories in a list which is used as lookup for the categories column. We initially thought of writing a client side script that would count items and add it to a field. But this needs to be triggered every time a new item is added to the list. I was trying to create a new field and accidentally I chose lookup field and I noticed that there is a field called count related in the options when i chose the looked up list a source. When I created a field I could immediately see item count for all the items in the lookedup list. Form now on this becomes easy to use this chart part or anything you want even in code that would need to do count.

Figure shows how to create Count Related field

Create new List column Lookup









Item count corresponding to categories



Please leave your feedback in comments.

Friday, May 11, 2012

File Name is Locked for editing by another user

Yesterday I was at a client place trying to steer them in getting there processes automated with SharePoint and Workflow. I already have created a test workflow for them to do a Demo to their executives. It was a simple workflow that sends the document for approval and publishes it to PDF. The IT team was preparing for demo by testing the workflow. When they kicked the workflow one of the reviewer opened the document for review and added his comment and about to check in but the Microsoft Word crashed and he had to close the application. When he tried to open the document again from the library he started getting the error shown below.






The Library is not force checkout enabled nor the document is checked out. Further the document shows is checked out to the same person.

The reason why he was seeing the error is because in SharePoint when you open a document for editing SharePoint places a write lock on the document. If Word crashes or the application is force closed the lock is not released and there is no manual way to unlock the document. The solution is to wait for 10 minutes before trying to edit the document. If you wait for 10 minutes SharePoint releases it lock and the document returns to normal state.




Hope this helps some one. You can find more information on this in this KB article here.


Monday, May 7, 2012

Understanding runwithelevatedprivilege in SharePoint 2010

SharePoint is been around for sometime now and there are substantial amount of developer community behind SharePoint. There is also huge push on the enterprise to adopt SharePoint for variety of applications varying from single farm to large scale implementation.Everyone of us would have written code in SharePoint that requires to run with elevated privileges. There are times we tend to miss the fact that run with elevated privilege is a delegate which requires all the SharePoint objects to be created again.  I wanted to write down some of the best practices that one should keep in mind while using run with elevated privilege and which objects should be created again within the elevated context.

Please feel free to add your suggestions in comments.



Primitive ojects
SharePoint Objects
Primitive Objects Viz: String, int, Float etc
 All sharepoint objects Viz: SPSite, SPWeb, SPListItem, SPSList etc
Can be passed from call outside elevated privileges
Cannot pass these objects because of different context where it is created

Always create new SPSite and SPWeb Object

Dispose all the objects once it is used or while leaving the delegate.

Use only when needed and do not use it to bypass security. Instead use impersonation using SPUser Token




Tuesday, February 7, 2012

Export and Import Site in Sharepoint

 Many have faced a situation of exporting a site and importing in another site collection. There are times where you need to move a subsite in a site collection to another site collection or into a subsite of same site collection. Recently I was involved in the project where the client moves the site into a subsite or reversal more often. They in fact  wanted this as a part of the application itself. Further, they don't want to run STSADM or power shell command and depend on IT for doing this. To add complexity to the situation the client had 2 different environment

1. Hosted externally
2. Hosted Internally

The reason for having this set up is the client do not have a big IT team to manage the infrastructure as external environment hosts some of there client information and they wanted to have backup and disaster recovery capabilities, which they don't want to own.

Having given the background of situation now let us see how we can achieve this operation. The easiest solution I think and which I worked on to implement was using Sharepoint webservices. This I think is good solution because there is less code to manage and there is a huge support from Microsoft as it is there code and this approach can also be used from Client object model.

Code :

                   SharepointSiteServices.Sites siteWs = new SharepointSiteServices.Sites();
                   siteWs.Url = SPContext.Current.Web.Url + "/_vti_bin/sites.asmx";

                   siteWs.Credentials = System.Net.CredentialCache.DefaultCredentials;
                  string[] datafiles = new string [] { site.Url + "/TemplateLibrary/"+ SPContext.Current.Web.Name +".cmp"};
                  int i = siteWs.ExportWeb(SPContext.Current.Web.Name, SPContext.Current.Web.Url, site.Url + "/TemplateLibrary", true, true, true, Int32.MaxValue);
                  siteWs.Url = site.Url + "/_vti_bin/sites.asmx";
                  int j = siteWs.ImportWeb(SPContext.Current.Web.Name, site.Url + "/" + SPContext.Current.Web.Name, datafiles, site.Url + "/TemplateLibrary", true, true);

The code above shows how you can export and import the site or subsite. But the things that needs to considered are

There is minimum documentation for the web service calls export and import opeartion. I managed to get a PDF document that contains the error codes and implementation details from technet after tearing google away for any sort of information. Finally i got hold of a former microsoft guy and he shared this PDF with me. I am uploading it any body else who need it may use it.
  • Web services needs to pointed to the site that needs to exported
  • set the web service credentials. May be you can run with elevated privileges if you know this operation is going to be performed by some one else in the system other than administrator.
  • datafiles which is string array represents the file name that you want to use when exporting the site. I am using the default site name as file name here. You can change this to any thing you want. Important thing that needs to conscious of is the path of the file name should be a SharePoint library. It does not let you pick a directory path.
  • Change the Site URL for the import site and now you can import the sites.
 Reference

Sites Web Service

Thursday, December 15, 2011

User Information List

This past week we are were getting ourselves ready for the christmas party and holidays. We are done with one of our big project and wanted to chill out during this holiday. Ironically this happened that one of our developer brought up an interesting question about sharepoint. In our project we had to see whetehr user exists and since we had sites and subsite present in the site structure we were using 


     Web.Users["username"]  and web.SiteUser["username"]

The question was

  is there a nice way to get the user information than using users?

The reason he wanted to know was these objects were uses interchangeably and some time the web.users throw an exception and then had to go through siteusers. I set to investigate further and I also remembered that there is list in sharepoint where users are stored. But I totally forgot about it. It is the userinformation List. Here you have information about the user as soon as the user is created and Sharepoint is using this list for its operation like when you have a document or item created in sharepoint CreatedBy and ModifiedBy is all getting information from this List. This List is what used to by sharepoint to track the changes and user who performs it (Audit).

Here is a code to get information from usre information list.
Remember, this list is hidden and you need to be an administrator to access this list.

Here is how you can access the list from UI

URL : [SiteURL]/_catalogs/users/detail.aspx 


I am not using the Name in my CAML rather email field to run the query. Also getting the user like this will be more useful if you are performing other operation with the user information.

Code:

SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {


                        int userId = SPContext.Current.Web.CurrentUser.ID;
                        string userName = SPContext.Current.Web.CurrentUser.Email;

                        SPList userInformationList = SPContext.Current.Web.SiteUserInfoList;


                       SPListItem userItem = userInformationList.Items.GetItemById(userId);

                        SPQuery query = new SPQuery();

                         string queryString =  string.Format("<Where><Eq><FieldRef Name='EMail' /><Value Type='Text'>{0}</Value></Eq></Where>",userName);
                        query.Query = queryString;
                        SPListItemCollection userItems = userInformationList.GetItems(query);

                        if (userItems != null && userItems.Count > 0)
                        {
                            console.Writeline("User Found");
                        }
}
}
});