Showing posts with label SharePoint 2013. Show all posts
Showing posts with label SharePoint 2013. Show all posts

Wednesday, September 26, 2012

SharePoint – How to get Site Usage Information Using Client Object Model

Getting site usage information using client object model is very simple.
We have to load “Usage” property of site and use “UsageInfo” class provided in client object model.
Data type of Usage property is UsageInfo. We can get information related to usage like hits, site visits and also storage for the site.
Here I have written sample method which will give us required usage data.
private void GetSiteUsageData()
        {
            string usageData = string.Empty;
            clientContext.Load(clientContext.Site,
            s => s.Usage);
            clientContext.ExecuteQueryAsync((s, args) =>
            {
                UsageInfo usageInfo = clientContext.Site.Usage;
                usageData = "No. of hits: " + Convert.ToString("" + usageInfo.Hits) + "; ";
                usageData += "No. of visits: " + Convert.ToString("" + usageInfo.Visits) + "; ";
                usageData += "Storage: " + Convert.ToString("" + usageInfo.Storage) + "; ";
                usageData += "Storage Percentage Used: " + Convert.ToString("" + usageInfo.StoragePercentageUsed) + "; ";
            },
            (s, args) =>
            {
                //"Error loading usage information.
            });           
        }
 
Here are the details of properties,
 
Property Name
Data Type
Description
Hits
Long
Gives total number of hits to the site
Visits
Long
Gives number of page visits
Storage
Long
Gives total storage used in MB
StoragePercentageUsed
Double
Gives percentage of storage used by site
 
This is handy when you want to get usage information using client object model.

Tuesday, September 25, 2012

SharePoint - Get List Item Versions Using Client Object Model


In last few posts I talked about how to work on file versions using web service and using client object model. Those posts described how to play around versions of file in document library. What if I want to get, delete or restore versions of list item?

Obviously, first thing we will do is to find any property related to version for “ListItem” class. But there is no such property available. L

What to do now?

There is a simple way, use methods in my last post and trick is to pass “fileUrl” parameter.

In case of file in document library, I suggested to pass this parameter like:
 

"/sites/prasad/teamsite/MyLibrary/testexcel.xlsx"
 

For list item we have to tweak this and pass “fileUrl” parameter as:
 

"/sites/prasad/teamsite/Lists/MyList/30_.000”
 

Here 30 is item id for item of which I want to get version history.
Yes, we are good to go now. We can play around versions of list items also. Hurray!!!

SharePoint - Get File Versions Using Client Object Model


In two of my previous posts I discussed how to get, delete and resore file versions programmatically.
I suggested way of getting versions using web service. Now let’s do the same thing with Silverlight client object model. Same thing can be done with JavaScript object model with some syntax changes.
Here I am considering same scenarios which we considered when we used web service. To put this in other way I have written sample methods for the operations which are possible by client object model.
These are some sample methods:
I have placed clientcontext object to App level. So I am using App.clientContext in my code.

Remember to load clientcontext before using these methods.

Get all versions:

private void GetAllFileVersions(string fileUrl)

{  

    FileVersionCollection fileVersionCollection;

    file = App.clientContext.Web.GetFileByServerRelativeUrl(fileUrl);

    fileVersionCollection = file.Versions;

    App.clientContext.Load(file);

    App.clientContext.Load(fileVersionCollection);

    App.clientContext.ExecuteQueryAsync((s, args) =>

    {

        int numberOfVersions = fileVersionCollection.Count;

    },

    (s, args) =>

    {

        //"Error loading versions.

    });

}
 

Usage:

GetAllFileVersions("/sites/prasad/teamsite/MyLibrary/testexcel.xlsx");
 

Description:

This method will load file version collection. You can iterate through each file version and get values for various properties which will give you date of creation, user object of user who created version, url of file for that version and Boolean value that tells if it is a current version of file.

  
Delete Specific Version Using Version ID:

        private void DeleteSpecificFileVersion(string fileUrl, int versionId)

        {

            file = App.clientContext.Web.GetFileByServerRelativeUrl(fileUrl);

            App.clientContext.Load(file);

            file.Versions.DeleteByID(versionId);

            App.clientContext.ExecuteQueryAsync((s, args) =>

            {

                //"Deleted file version successfuly.

            },

            (s, args) =>

            {

                //"Error deleting file version.

            });

        }
 

Usage:

DeleteSpecificFileVersion("/sites/prasad/teamsite/MyLibrary/testexcel.xlsx",512);
 

Description:

This method deletes specific version of file when version Id is provided. Interesting fact here is what is version id?

While iterating through versions of file you can get version id from “ID” property of “FileVersion” class.

Version ids are in multiple of 512.i.e. for first version it is 512, for second version it is 1024, for third version it is 1536 and so on.
 

Delete Specific Version Using Version Label:

        private void DeleteSpecificFileVersion(string fileUrl, string versionLabel)

        {

            file = App.clientContext.Web.GetFileByServerRelativeUrl(fileUrl);

            App.clientContext.Load(file);

            file.Versions.DeleteByLabel(versionLabel);

            App.clientContext.ExecuteQueryAsync((s, args) =>

            {

                //"Deleted file version successfuly.

            },

            (s, args) =>

            {

                //"Error deleting file version.

            });

        }
 

Usage:

DeleteSpecificFileVersion("/sites/prasad/teamsite/MyLibrary/testexcel.xlsx", "2.0");
 

Description:

This method deletes specific version of file when version label is provided. Version label means version number which you see on UI. i.e. “1.0”, “2.0”,”3.0” and so on.

While iterating through versions of file you can get version label from “VersionLabel” property of “FileVersion” class.

 

Delete All File Versions:

        private void DeleteAllFileVersions(string fileUrl)

        {

            file = App.clientContext.Web.GetFileByServerRelativeUrl(fileUrl);

            App.clientContext.Load(file);

            file.Versions.DeleteAll();

            App.clientContext.ExecuteQueryAsync((s, args) =>

            {

                //"Deleted all file versions successfuly.

            },

            (s, args) =>

            {

                //"Error deleting old file versions.

            });

        }
 

Usage:

DeleteAllFileVersions("/sites/prasad/teamsite/MyLibrary/testexcel.xlsx");
 

Description:

This simply deletes all the versions of file but current version.
 

Restore Specific Version:

        private void RestoreSpecificFileVersion(string fileUrl, string versionLabel)

        {

            file = App.clientContext.Web.GetFileByServerRelativeUrl(fileUrl);

            App.clientContext.Load(file);

            file.Versions.RestoreByLabel(versionLabel);

            App.clientContext.ExecuteQueryAsync((s, args) =>

            {

                //"Restored file version successfuly.

            },

            (s, args) =>

            {

                //"Error restoring old file versions.

            });

        }
 

Usage:

RestoreSpecificFileVersion("/sites/prasad/teamsite/MyLibrary/testexcel.xlsx", "3.0");
 

Description:

This method restores specific version of file when version label is provided.
 
To get current version of file use “UIVersion” or “UIVersionLabel” properties of “File” class. These properties will return you version id and version label respectively.

Interesting fact is version ids which SharePoint maintains. As I mentioned earlier, these are in multiples of “512”. URL of file version contains this version id in it. E.g.–

URL of first Version:                      http://[My Site URL]/_vti_history/512/MyLibrary/testexcel.xlsx

URL of second Version:               http://[My Site URL]/_vti_history/1024/MyLibrary/testexcel.xlsx

URL of third Version:                    http://[My Site URL]/_vti_history/1536/MyLibrary/testexcel.xlsx

Getting this path is nothing fancy. If you look at the version history of any file you can get this.
Just mouse over the link for each version and observe URL, you will get URL in above mention format.
Most important thing, current version of file will not include version id in its URL.
I learned many things from above exercise. Did you?

Wednesday, September 19, 2012

SharePoint Client Object Model: Using lambda expression for ExecutequeryAsync

When using "ExecuteQueyAsync" method of client object model we genarally write two different callback methods for success and failure. Instead of that we can use "Lambda Expression" and avoid two separate methods. This will also avoid class level variables and we  can access parameters of calling method in callback too.
Here is one simple example of usage of lambda expression.

private void UpdateItem(int itemId, string fieldName, object fieldValue)

{
ListItem item = clientContext.Web.Lists.GetByTitle("MyList").GetItemById(itemId);

item[fieldName] = fieldValue;

item.Update();

clientContext.ExecuteQueryAsync((sender, args) =>

{
//On update success

MessageBox.Show("Item with id "+ itemId.ToString()+" updated successfuly");

},

(s, args) =>

{
//on update failure

MessageBox.Show("Error occurred updating item: " + itemId.ToString());

});

}
Hope this helps to those who are unaware of using lambda expression.

Thursday, August 9, 2012

Delete and Restore File Versions Programmatically Using Web Service

In my last post I talked about "How to get file versions programatically". In this post, I want to extend the same with other things we can do with "Versions.asmx".

For this exercise add reference of webservice in your application like:
http://<SiteURL>/_vti_bin/versions.asmx

Enter namespace name for service reference. In my case I entered 'VersionService'.
Instantiate SoapClient wherever appropriate in your code.

VersionService.VersionsSoapClient versionServiceClient = new VersionsSoapClient();


Now, we are ready to write code for different operations we can do.

Delete All Versions of File

To delete all the versions but current one call this method in your code.

                 /// <summary>
        /// Returns XElement with metadata of current version of file
        /// </summary>
        /// <param name="FileUrl">Document library name/file name with extension</param>
        /// <returns>XElement for current version</returns>
        public XElement DeleteAllFileVersions(string FileUrl)
        {
            try
            {
                XElement versionElement = versionServiceClient.DeleteAllVersions(FileUrl);
                return versionElement;
            }
            catch
            {
                return null;
            }
        }


Usage:
XElement currentVersionElement = DeleteAllFileVersions("myDocLib/myDocument.docx");

Delete Specific Version of File

To delete specific file version use following method in your code.

            /// <summary>
        /// Deletes specific version of file
        /// </summary>
        /// <param name="FileUrl">Document library name/file name with extension</param>
       /// <param name="FileVersion">Version to delete</param>
        /// <returns>XElement with metadata of remaining versions of file</returns>
        public XElement DeleteSpecificFileVersion(string FileUrl, string FileVersion)
        {
            try
            {
                XElement versionElement = versionServiceClient.DeleteVersion(FileUrl, FileVersion);
                return versionElement;
            }
            catch
            {
                return null;
            }
        }


Usage:
XElement versionElement = DeleteSpecificFileVersion("myDocLib/myDocument.docx","5");

Restore Specific Version of File

To restore specific version use following method.

                 /// <summary>
        /// Restores specific version of file
        /// </summary>
        /// <param name="FileUrl">Document library name/file name with extension</param>
       /// <param name="FileVersion">Version to restore</param>
        /// <returns>XElement with metadata of remaining versions of file</returns>
        public XElement RestoreSpecificFileVersion(string FileUrl, string FileVersion)
        {
            try
            {
                XElement versionElement = versionServiceClient.RestoreVersion(FileUrl, FileVersion);
                return versionElement;
            }
            catch
            {
                return null;
            }
        }


Usage:
XElement versionElement = RestoreSpecificFileVersion("myDocLib/myDocument.docx","9");

As I mentioned in my last post, we can use these methods in Silverlight application and through javascript too.

Wait for next VERSION of my versioning related post :)

Tuesday, August 7, 2012

SharePoint - Get file versions programmatically

In SharePoint, we can enable versioning for a document library. SharePoint will take care of maintaining versions and also it allows to view, restore and delete previous versions. This feature helps a lot in document management. To enable versioning on a document library go to 'Library Settings ->Versioning Settings'. You will get following settings page where you can easily enable versioning.




You can see there are very good options provided OOB which help us in maintaining major and minor versions and also check out option.

You can get more information related to versioning here.

This is about versioning and settings. But, as a developer we need more. There are many scenarios when we want to get version history of the document programmatically. Here is very simple solution - web service. We can use 'versions.asmx' to get version history of file.
We can consume this web service from JavaScript and Silverlight application also. Here we will consider C# code.

Create windows form or silverlight application and add service reference as:
http://<SiteURL>/_vti_bin/versions.asmx

Enter namespace name for service reference. In my case I entered 'VersionService'.
Instantiate SoapClient wherever appropriate in your code.

VersionService.VersionsSoapClient versionServiceClient = new VersionsSoapClient();

Now, let's write a method which will return version history in xml format.


        /// <summary>
        /// Returns XElement with version history of file using web service
        /// </summary>
        /// <param name="FileUrl">Relative url of file</param>
        /// <returns>XElement for version</returns>
        public XElement GetFileVersions(string FileUrl)
        {
            try
            {
                XElement versionElement = versionServiceClient.GetVersions(FileUrl);
                return versionElement;
            }
            catch
            {
                return null;
            }
        }

'GetVersions' method returns version history in xml format as XElement.
Isn't it easy to get versions of a file?

FileUrl parameter should be like "document library name/file name with extension".

Now, let's do more with this method. Consider the scenario where you want current version of file. I have written a method which will use Linq to XML query and return current version of file.

        /// <summary>
        /// Returns current version of file
        /// </summary>
        /// <param name="FileUrl">Server relative url of file</param>
        /// <returns></returns>
        public string GetCurrentFileVersion(string FileUrl)
        {
            string CurrentFileVersion = string.Empty;
            XElement versionElement = GetFileVersions(FileUrl);
            if (versionElement != null)
            {
                //Get child element with name 'result' and whose attribute named 'version' contains '@'
                var resultElements = versionElement.Elements();
                var rows = from row in resultElements
                           where row.Name.LocalName == "result" &&
                           row.Attribute("version").Value.Contains("@")
                           select row;
                foreach (var row in rows)
                {
                    CurrentFileVersion = row.Attribute("version").Value;
                }
                CurrentFileVersion = CurrentFileVersion.Replace("@", string.Empty);
            }
            return CurrentFileVersion;
        }

For my code I required version in string format. You can covert it to integer.
Simple way to get file version history!!

Tuesday, July 24, 2012

SharePoint Designer 2013 Workflows: Part 3 – Start another workflow


Do you want to start another workflow from your workflow? That tot using SharePoint Designer?Can you do that?
Answer is yes. Yes, you can start another workflow from your workflow using SharePoint Designer 2013.
You can find following actions under the group of ‘Coordination actions’.


Action text is “Start SharePoint 2010 workflow”. This clearly indicates that you can only start workflow created for platform type ‘SharePoint 2010 Workflow’.

While selecting the workflow you can only select workflow created for 2010 platform.
For using this action:
       1.      Create workflow for SharePoint 2010 platform.


2.      Create another workflow which will start previous workflow. This workflow need not to be 2010 workflow. Why this platform dependency is there? It is still a question to me and I am waiting for answer. May be I will be able to get it in MSDN documentation. Till then let’s move ahead and explore this feature. I will post updates as soon as I get more information.

3.      Add various stages as per your requirement.

4.      In stage having logic to start another workflow add ‘Start List Workflow’ action within required condition.

5.      Select workflow to be started.



       6.      Configure parameters.

7.      Select the item on which the workflow needs to be started.


8.      Check for errors, save and publish workflow.

Test your workflow. Similarly, you can start site workflow.

SharePoint Designer 2013 Workflows: Part 2 – Loop


Ever stuck at the question “How to implement loop in SharePoint Designer workflow?”

Most of us had this question and we found various workarounds for this.

All the workarounds were really painful. But thanks to SharePoint Designer product team. Now we have looping option available in SharePoint Designer 2013.

There are two options available.

·         Loop n times.

·         Loop with condition.



We can add multiple actions as loop content and these actions get executed till the looping condition is true.

Loop n Times

We can provide integer value for number of times the actions should get executed.

We can also set value using workflow lookup to any list/variable.




Loop with condition

This provides ‘While’ loop kind of functionality. Actions within loop get executed while given condition is true. For configuration of condition we have the flexibility of comparing values from any lists.




Enjoy looping in designer workflows!!