Pages

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Wednesday, June 19, 2019

Read the Response message when a web request throws “500 Internal Server Error”

Introduction

When I call a SOAP request from Postman I got the response as “500 Internal Server Error”. I had to call the same api from C# and read the response and had to pass it from api to front end.

Here is the screenshot of the response.




Solution



   
                string soapResult = string.Empty;
                try
                {
                    using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
                    {
                        using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
                        {
                            soapResult = rd.ReadToEnd();
                        }
                    }
                }
                catch (WebException wex)
                {
                    soapResult = new StreamReader(wex.Response.GetResponseStream())
                                          .ReadToEnd();
                }
                return soapResult;

Tuesday, January 9, 2018

Invoke a code activity (Native Activity) and retrieve the results using code – Workflow Foundation 4.5

Introduction

We can create code activity as a part of workflow solutions using workflow foundation 4.5. In this post I will show how we can create a native code activity and access the results in asp.net controller. Native code activity

 

   //The string mentioned in NativeActivity is the resut type.  

     public sealed class MySampleNativeCode : NativeActivity     {

         // Define an activity input argument of type string

         public InArgument Name { get; set; }



         protected override void Execute(NativeActivityContext context)

         {

             var name = context.GetValue(Name);

             //Here we set the string value to the Result property in NativeCode

             context.SetValue(base.Result, "Hello from Native Code Activity " + name);



         }

     }
Invoke the code activity The code activity is invoked in asp.net web api controller.
 
 // GET: api/CustomerRegistration

         public string Get()

         {

             //Create a instance of the native code

             Activity wf = new MySampleNativeCode();



             //Define the input argumentes

             Dictionary arguments = new Dictionary();

             arguments.Add("Name", "Suhail");



             //Invoke the workflow

             IDictionary outputs = WorkflowInvoker.Invoke(wf, arguments);



             //Get the output value and assign to return string

             var returnString = outputs["Result"].ToString();



             return returnString;

         }

Conclusion

You can see the value in “returnString” which is returned from Native Code Activity.



Thursday, March 16, 2017

Add Web Application property bag using Power Shell and use them in SharePoint timer job

Introduction

SharePoint Web Application level property bag is used to store configuration setting data and information. I make use of the property bag when I write a timer job.

I store value in property bag as key, value using power shell and using C# server object model I retrieve and make use of it.

Set Web Application Level Property Bag

You can create a function in Power shell

 function SetWebApplicationPropertyBag ($webAppUrl, $key, $value) {

	$Web = Get-SPWebApplication -Identity $webAppUrl
	$Web.Properties.Add($key,$value) #add property bag
	$Web.Update()

	Write-host "Created new Property:" $Web.Properties[$key]
 
 }

And you can call the function like this.

$webAppUrl ="Web Application url goes here"
$PropertyName1 ="Key"
$PropertyValue1 ="Value"

SetWebApplicationPropertyBag $webAppUrl $PropertyName1 $PropertyValue1

You have to change the values of $webAppUrl, $PropertyName1 and #PropertyValue1.

Copy paste code in SharePoint Management shell and your web application property will be created.

Retrieve property bag value in SharePoint Timer Job

Since SharePoint Timer Jobs are created with the feature, in Web Application level scope, we can use the below code to retrieve the data.

var value = WebApplication.Properties["Key"].ToString();

You can make use of value and do operations.

Remove Property Bag

You can use below code to remove a value from property bag.

$Web = Get-SPWebApplication -Identity "Web Application Url"

$Web.Properties.Remove("Key")

$Web.Update()

Thursday, January 26, 2017

How to create a SharePoint webpart with custom webpart property/properties

Introduction

Recently one of colleague want to create a webpart for SharePoint using C# as programming language. One of his requirements is to that “user wants to pass values through custom webpart property.” So I created a sample for him.

Solution

Here is the code and also you can download the .sln file from my drive by clicking below URL.
https://drive.google.com/file/d/0ByEnOE8DAdvhLTFtd1oxWS1GNUU/edit?usp=sharing

     
namespace CustomProperty.CustomWebPartProperty
{
    [ToolboxItemAttribute(false)]
    public class CustomWebPartProperty : WebPart
    {
        private string _name = "Suhail";//The default value to display
        [WebBrowsable(true),
        WebDisplayName("Label Text"),//WebPart property display name
        WebDescription("Label Text to appear in Label"),//Property discription
        Category("Custom"),//Custom webpart property catogory
        Personalizable(PersonalizationScope.Shared)]
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }

        }
        protected override void CreateChildControls()
        {
            Label name = new Label();
            name.Text = Name;
            this.Controls.Add(name);

        }
    }
}
 


Conclusion

You can see your custom webpart property at the end of the webpart setting.

When you need values which should be able customize don’t save in web.config file; You may use custom webpart properties.

Tuesday, February 23, 2016

Facebook template is not found in Visual Studio 2015

Problem Background

Today I thought of creating a Facebook app using Facebook template which was available in Visual Studio 2013. Shockingly the template was not available once I select ASP.Net Web Application template and click OK (Screen shot attached).

1

Solution

Then I got to know by searching online that there is a new extension has been released for ASP.Net project templates.

Check out the below link and install the Visual Studio 2015 Extension for ASP.NET Project Templates.

https://blogs.msdn.microsoft.com/webdev/2015/02/08/introducing-the-visual-studio-2015-extension-for-asp-net-project-templates/

PS: I directly downloaded the extension from the below url and installed it.

https://visualstudiogallery.msdn.microsoft.com/9402d38e-2a85-434e-8d6a-8fc075068a42

2

Thursday, September 11, 2014

Client Side Rendering using JSLink – Post 02 – Customize List Forms

Introduction

In my last post I described how to startup with Client Side Rendering using JSLink with basic example. In this post I will describe “What are the places you can deploy JavaScript files in order to use in SharePoint development” and “How can we use rendering; in order to customize list forms”.

What are the places you can deploy JavaScript files in order to use in SharePoint development?

In my last post I had used layouts folder which is inside the 15 hive. But there are more options where we can deploy JavaScript files in order to use them in JSLink property. So these option can be useful for the developers who want to develop SharePoint hosted apps and who don’t have the access to local file system. JSLink property accepts below SharePoint tokens.

~site – The URL of the current website. (Recommended to use in SharePoint hosted apps development)

~sitecollection – The URL of the parent site collection of the current website.

~layouts – The URL of the Layouts virtual folder for the current website. You don’t have to worry about 14 hive or 15 hive.

~sitecollectionlayouts – The URL of Layouts folder in the current site collection (/sites/spsite/_layouts/15)

~sitelayouts – The URL of Layouts folder in the current site (/spsite/spweb/_layouts/15)

If you want to use multiple JavaScript file on a single JSLink property you can use “|” symbol.

Eg. ~layouts/folder001/test.js | ~layouts/folder002/test.js

How can we use rendering in order to customize list forms?

In the first post I described how to customize the default view form. In this post I will describe how to customize New form, Edit form and the Display form by changing the scope in JavaScript. I will show how to customize the New form and you can use the same for other forms as well.

Solution

  1. (function () {
  2.  
  3.     //   Initialize the variables for overrides objects
  4.     var overrideCtx = {};
  5.     overrideCtx.Templates = {};
  6.     overrideCtx.BaseViewID = "NewForm";
  7.     overrideCtx.ListTemplateType = "10000";
  8.  
  9.     /*
  10.    * Using the Fields override leaves the rest of the rendering intact, but
  11.    * allows control over one or more specific fields in the existing view
  12.    */
  13.     overrideCtx.Templates.Fields = {
  14.         'Title': { 'NewForm': 'Custom' }
  15.     };
  16.  
  17.     /*  
  18.      * Register the template overrides.
  19.      */
  20.     SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
  21.  
  22. })();

In the above code

BaseViewID: The form type. This can be NewForm, EditForm, DisplayForm.

ListTemplateType: This is List Template type. You can see your list template type in Elements.xml file belonging to the list definition in Visual Studio.

image image

The above JavaScript code shows how to modify the title value in the form.

Now you can save the JavaScript file in any locations as said under first heading.

We have one more thing to do. Reference the JavaScript file with the list for new form. 

Method 01 – Declaratively

I will show how to define JSLink in SPList Schema.xml file.

  1. Open the schema of List definition in your visual studio solution
  2. There at the bottom you can find the types of form.

image

3. Add a new property as JSLink and  give the location as mentioned below.

image

Now deploy the solution.

Method 02 – Programmatically in C#

Now I will show how to add JSLink property to NewForm programmatically through C#.

  1. SPWeb spWeb = SPContext.Current.Web;
  2.             SPList spList = spWeb.Lists.TryGetList("List Name");
  3.             SPForm newForm = spList.Forms[PAGETYPE.PAGE_NEWFORM];
  4.             SPFile page = spWeb.GetFile(newForm.Url);
  5.             using (SPLimitedWebPartManager wpManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
  6.             {
  7.                 // Enable Update
  8.                 wpManager.Web.AllowUnsafeUpdates = true;
  9.  
  10.                 //Check out the file
  11.                 SPFile file = wpManager.Web.GetFile(newForm.Url);
  12.                 if (file.CheckOutType == SPFile.SPCheckOutType.None)
  13.                     file.CheckOut();
  14.  
  15.  
  16.                 foreach (WebPart webpart in wpManager.WebParts)
  17.                 {
  18.                     if (webpart is ListFormWebPart)
  19.                     {
  20.                         var listFormWebPart = (ListFormWebPart)webpart.WebBrowsableObject;
  21.                         listFormWebPart.TemplateName = "ListForm";
  22.                         listFormWebPart.JSLink = "/_layouts/15/CSR002/test.js";
  23.                         wpManager.SaveChanges(listFormWebPart);
  24.                     }
  25.                 }
  26.  
  27.                 // Update  file
  28.                 file.Update();
  29.                 file.CheckIn("Added JSLink");
  30.                 wpManager.Web.AllowUnsafeUpdates = false;
  31.             }

Actually what we are doing is – we are setting the value to JSLink property in web part on NewForm.aspx page.

The code below will NOT WORK.

  1. SPWeb spWeb = SPContext.Current.Web;
  2.             SPList spList = spWeb.Lists.TryGetList("CustomList002");
  3.             SPForm newForm = spList.Forms[PAGETYPE.PAGE_NEWFORM];
  4.             if (null != newForm)
  5.             {
  6.                 newForm.JSLink = "/_layouts/15/CSR002/test.js";
  7.             }
  8.             spWeb.AllowUnsafeUpdates = true;
  9.             spList.Update();
  10.             spWeb.AllowUnsafeUpdates = false;

Method 03 – Browser user interface

Go to the NewForm.aspx page where we try to add new item by clicking add new item button. Please refer my first post where I have described how to set JSLink property.

Conclusion

Once we deploy and give reference to our JavaScript file we can see that our Title value is changed to the customized value.

image

Keep in touch. I will cover more advanced topics on this.

Friday, March 28, 2014

How to get the correct audit occurred time from SPAuditEntry

Introduction

I was assigned to a project where I had to retrieve audit data programmatically using C#. I used SPAuditQuery and SPAuditEntry in order to achieve this.

Problem Background

When I retrieve the audit occurred time by spAuditEntry.Occurred; it gives a different value from the actual time.

Solution Background

SharePoint save the audit data in content database in table dbo.AuditData. To see auditing data; open your content database and go to the table dbo.AuditData and see the column “Occurred” there you can see the UTC Date time of the actual audit time. 





I learnt from various blog posts that SharePoint usually store datetime in UTC DateTime format in the content database; and when it want to display the date time in SharePoint site the value stored in database is converted to webapplication’s time and then displays the time according to the time zone the person is in.

Solution

To get the web application time you have to call RegionalSettings.TimeZone.UTCToLocalTime() method.


   
spWeb.RegionalSettings.TimeZone.UTCToLocalTime(spAuditEntry.Occurred)
//spAuditEntry.Occurred is the time stored in content database which is a in DateTime format

Conclusion

So when you retrieve any data from content database programatically  which contains datetime;  please use the above method as you need. I have already blogged on a same kind of issue here. This was to retrieve the LastItemModifiedDate as Local Time.

Wednesday, March 12, 2014

Set application page heading dynamically in SharePoint

Introduction

I was had to set the heading of the application page dynamically from the code behind (server side).


Solution

Your application page will look something like this.

 Applicationpage

What you can do is simply replace "My Application Page" with a label and you can replace the text from the back end.

  1. <%-- This is Heading of the page --%>
  2. <asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
  3. <asp:Label runat="server" ID="labelPageTitle"></asp:Label>
  4. </asp:Content>

Now from the code behind you can access the label by its id and set the text as you need.

  1. labelPageTitle.Text = "From code behind";


Conclusion

Your page will look something like this.

apppage

Wednesday, February 19, 2014

Display notifications in SharePoint from code behind

Introduction

Sometimes we may need to display notifications in SharePoint; which appears on the right side of the page below the ribbon.

Problem Background

We may need to call the notification from the code behind which I will show how to achieve it.

Solution Background

We have to call SP.UI.Notify class to add and remove notification. This class contain two methods


  • addNotification – Add a notification to the page and returns the id of that notification.
  • removeNotification – Removes the notification from the page. 

Solution
 

   
private void ShowNotification()
        {
            var scriptTemplate = @"
ExecuteOrDelayUntilScriptLoaded(function(){{
    ExecuteOrDelayUntilScriptLoaded(function(){{
            var notificationId = SP.UI.Notify.addNotification(""{0}"", false);
//false here will remove the notification in 5 secs
//true will not remove until we remove it by calling removeNotification   
        }},
    'core.js'
    )}},
'sp.js'
);";
            //You can give the string in Hello World!!
            var script = string.Format(scriptTemplate, "Hello World!!");
            //Here Any String as the key of the client script to register
            Page.ClientScript.RegisterClientScriptBlock(GetType(), "Any String", script, true);
        }

Use removeNotification to remove the notification explicitly.

   
private void ShowNotification()
        {
            var scriptTemplate = @"
    ExecuteOrDelayUntilScriptLoaded(function(){{
        ExecuteOrDelayUntilScriptLoaded(function(){{
            var notificationId = SP.UI.Notify.addNotification(""{0}"", true);
            removeNotification(notificationId);//remove the notification. 
        }},
    'core.js'
    )}},
'sp.js'
);";
      
            var script = string.Format(scriptTemplate, "Hello World!!");
            Page.ClientScript.RegisterClientScriptBlock(GetType(), "Any String", script, true);
        }

Conclusion

Please go through below urls for more information on this. 

 

Thursday, February 13, 2014

Retrieve Author of SPListItem as SPUser in SharePoint; programmatically (C#)

Introduction
Updated on 15th July 2014

I was assigned in a project where I had to retrieve the author of the SPListItem as SPUser programmatically.

Solutions

In these solutions I’m returning the login name. But you can get the SPUser.

Solution 01

  1. public string GetListItemAuthorNameSPBuiltInFieldId(SPListItem spListItem)
  2.       {
  3.           string loginName = string.Empty;
  4.           SPWeb spWeb = SPContext.Current.Web;
  5.  
  6.           var fullUserName = spListItem[SPBuiltInFieldId.Author] as string;
  7.           var userName = fullUserName.Split('#')[1];//This is only to get the user name. My fullUserName was 1;#Setup Admin.
  8.           SPUser spUser = spWeb.EnsureUser(userName);//You can get SPUser from here
  9.           loginName = spUser.LoginName;
  10.           return loginName;
  11.  
  12.       }
It is recommended to SPBuiltInFieldId in order to retrieve build in fields.

Solution 02

  1. public string GetListItemAuthorName(SPListItem spListItem)
  2.   {
  3.       string loginName = string.Empty;
  4.       var spFieldUser = spListItem.Fields.GetFieldByInternalName("Author") as SPFieldUser;
  5.  
  6.       if (spFieldUser != null && spListItem["Author"] != null)
  7.       {
  8.           var fieldValue = spFieldUser.GetFieldValue(spListItem["Author"].ToString()) as SPFieldUserValue;
  9.           if (fieldValue != null)
  10.           {
  11.               var spUser = fieldValue.User;//Get the SPUser
  12.               loginName = spUser.LoginName;//Get the login name from SPUser
  13.           }
  14.       }
  15.       return loginName;
  16.   }


Conclusion

I will update how to retrieve values from SPField in future days.

Friday, February 7, 2014

Query all the documents by its file type from a Site and its all sub sites using SPSiteDataQuery

Introduction

I had to develop a web part where I had to query and display all the document items which the file extensions are “docx” under a particular site collection including its sub sites. I used SPSiteDataQuery class in order to achieve.

Solution

 
using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    SPSiteDataQuery spSiteDataQuery = new SPSiteDataQuery();

                    spSiteDataQuery.Query =
                    @"<Where>
      <Eq>
         <FieldRef Name='DocIcon' />
         <Value Type='Computed'>docx</Value>
      </Eq>
   </Where>";
                    spSiteDataQuery.ViewFields = "<FieldRef Name='FileLeafRef' /><FieldRef Name='Editor' /><FieldRef Name='ContentType' />";
                    spSiteDataQuery.Lists = "<Lists ServerTemplate='101'/>"; //Set the list template by providing its template type id

                    spSiteDataQuery.Webs = "<Webs Scope='Recursive'/>";//Recursive: Current site and any subsite
                    //Scope='SiteCollection': all webs in the current site collection

                    //Get the results into a datatable
                    DataTable resultsTable = spWeb.GetSiteData(spSiteDataQuery);

                    
                    //Bind the results in to a asp grid view
                    GridView spGridView = new GridView();
                    spGridView.AutoGenerateColumns = true;
                    spGridView.DataSource = resultsTable;
                    spGridView.DataBind();

                    Controls.Add(spGridView);
                }
            }

 
Conclusion 
The results will look something as below. 



I have posted the my sln file here. Please download in case if you need
https://drive.google.com/file/d/0ByEnOE8DAdvhSTlnMDBuWDRuWTA/edit?usp=sharing

Reference: http://msdn.microsoft.com/en-us/library/ms409088.aspx

Friday, January 3, 2014

Show SharePoint Search Results in SPGrid View - programmatically

Introduction

As I said in my earlier post I was working and trying some stuff related to SharePoint 2013 search server. Today I was trying to query and display search results in SPGrid view. I have uploaded my solution package in my drive; Please download and look for the code if you need. (Download)
I used certain blog posts as references.


Solution

Create a web part (I have created visual web part). On the .ascx page initiate a SPGridView. (For that you can use the below code)
On the ascx.cs page do the blow
On page load



   

        protected void Page_Load(object sender, EventArgs e)
        {

           string query = string.Format("Project*"); //You can give what ever query you need
           ExecuteFederatedQuery(query);
        }

 


And also you need below both methods. So please paste them also on the ascx.cs page


   

        void ExecuteFederatedQuery(string queryText)
        {
            long lastupdate;
            bool crawl;

            //Create Search service proxy
            SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy
       (SPServiceContext.GetContext(SPContext.Current.Site));

            
            LocationConfiguration locationConfig = null;
        
            LocationConfiguration[] locationConfigurations = proxy.GetLocationConfigurations(out lastupdate, out crawl);//Get all federated search locations. 
            Location location;
            LocationList locationList = new LocationList();
            QueryManager queryManager = new QueryManager();
            foreach (LocationConfiguration locationConfiguration in locationConfigurations)
            {
                //Specify any federated search location. Here default search location will be captured.  
                if (locationConfiguration.InternalName.Equals("LocalSearchIndex"))
                {
                    locationConfig = locationConfiguration;
                    break;
                }
            }
            location = new Location(locationConfig.InternalName, proxy);
            //Set the userQuery
            location.UserQuery = queryText;
            locationList.Add(location);
            queryManager.Add(locationList);
            queryManager.IsTriggered(locationList);
            XmlDocument xDoc = queryManager.GetResults(locationList);//Return the query
            if (xDoc != null)
            {
                DataSet resultSet = new DataSet();
                resultSet.ReadXml(new XmlNodeReader(xDoc));

                SortData(resultSet.Tables[1]);

            }


        }

        private void SortData(DataTable resultTable)
        {

            //Sort the results by Title name
            DataView dataView = resultTable.DefaultView;
            dataView.Sort = "Title ASC";
            DataTable resuDataTable = dataView.ToTable();


            var fileTable = new DataTable();

            DataRow fileRow;
            fileTable.Columns.Add("Title");
            fileTable.Columns.Add("Modified_Date");
            fileTable.Columns.Add("Authors");
            fileTable.Columns.Add("DocURL");

            foreach (DataRow resultRow in resuDataTable.Rows)
            {

                fileRow = fileTable.NewRow();
                fileRow["Title"] = resultRow["title"];
                fileRow["DocURL"] = resultRow["url"];
                fileRow["Modified_Date"] = resultRow["lastmodifiedtime"];
                fileRow["Authors"] = resultRow["author"];

                fileTable.Rows.Add(fileRow);
            }

            //Assign the datasource
            spGridView.DataSource = fileTable;
            spGridView.DataBind();

            
        }

 

Conclusion

The results will look something like this.


Monday, December 23, 2013

Migrate SharePoint 2010 code (custom solutions) to SharePoint 2013

Introduction

Recently I was assigned to Migrate code which used to develop SharePoint 2010 web parts to SharePoint 2013 web parts. Here I will illustrate how I did it.

Solution

Step 01: Open the Visual Studio 2010 (SharePoint 2010) solution in Visual Studio 2012. 




Step 02: Change the Target framework to .Net Framework 4.5

Step 03: Remove all the SharePoint 2010 assemblies and add SharePoint 2013 assemblies. This is because SharePoint 2010 assemblies are located in 14 hive and in SharePoint 2013 the assemblies are located on 15 hive. The SharePoint dlls can be


  • Microsoft.Office.Server.dll
  • Microsoft.SharePoint.dll 
  • Microsoft.SharePoint.Security.dll 

There are others as well. Please refer MSDN for other common used SharePoint assemblies.

Step 04: Change Control templates/ web part location as below.

From
~/_CONTROLTEMPLATES/{Folder Name}
To
~/_CONTROLTEMPLATES/15/{Folder Name}

Step 05: Change the _layouts location files to /_layouts/15/ location. Usually images, CSS and JavaScript files are added to _layouts folder.

Images
From
/_layouts/images/
To
/_layouts/15/images/

CSS
From
/_layouts/{Folder Name}/css
To
/_layouts/15/{Folder Name}/css

JavaScript
From
/_layouts/{Folder Name}/scripts
To
/_layouts/15/{Folder Name}/scripts

Step 06: In all aspx pages you have to change the reference from SharePoint 2010 asssembly to SharePoint 2013 assemblies. To do this change the assembly version from Version=14.0.0.0 to Version=15.0.0.0

Example.

           


<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>



To

           

<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>


Conclusion
Hope this will work for you and please note that sometimes you will need to change the deployment path according to SharePoint 2013. As the above add 15 hive after the mapped folder. If you have set the master page as v4.master you should change to seattle.master

Sunday, December 1, 2013

Adding Left Navigation for SharePoint Publishing site programmatically

Problem Background

I was working on creating a webtemplate based in SharePoint 2013 based on publishing site. There I had an requirement to create Left Navigation programmatic.

Solution Background

Here I have used "Structural Navigation" as the navigation type.

Solution

Below is the method to achieve it.

           
using (SPSite spSite = new SPSite("http://cd-sjamaldeen:23855/sites/002/"))
{
    using (SPWeb spWeb = spSite.OpenWeb())
    {

        //to remove pages from quick launch navigation
        PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(spWeb);
        // Current navigation 
        publishingWeb.Navigation.CurrentIncludePages = false;
        publishingWeb.Navigation.CurrentIncludeSubSites = false;
        publishingWeb.Navigation.GlobalIncludePages = false;
        publishingWeb.Navigation.GlobalIncludeSubSites = false;


        var webNavSettings = new WebNavigationSettings(spWeb);

        // Set the current navigation to Structural Navigation type
        webNavSettings.CurrentNavigation.Source = StandardNavigationSource.PortalProvider;

        // Set the global navigation to Structural Navigation type
        webNavSettings.GlobalNavigation.Source = StandardNavigationSource.PortalProvider;

        webNavSettings.Update();
      

        //add the settings page to the quick launch
        SPNavigationNodeCollection nodeColl = spWeb.Navigation.QuickLaunch;

        //Delete all the navigation nodes from QuickLaunch 
        for (int i = spWeb.Navigation.QuickLaunch.Count - 1; i > -1; i--)
        {
                        
            spWeb.Navigation.QuickLaunch[i].Delete();
        }


        publishingWeb.Update();

        SPNavigationNode googleNode = new SPNavigationNode("Google", "http://google.com");
        nodeColl.AddAsFirst(googleNode);


        SPNavigationNode yahooNode = new SPNavigationNode("Yahoo", "http://yahoo.com");
        nodeColl.AddAsLast(yahooNode);

        spSite.AllowUnsafeUpdates = true;
        spWeb.AllowUnsafeUpdates = true;
        spWeb.Update();
        spWeb.AllowUnsafeUpdates = false;
        spSite.AllowUnsafeUpdates = false;

    }
}
 
 

Conclusion

Hope your publishing site now will have the Navigation.
If you face any problems go to site setting ->  Navigation (Under Look and Feel section) see weather all your navigation setting exists.


Thursday, October 31, 2013

The Web application at "" could not be found in WCF with SharePoint server object model

Problem Background

I was creating a WCF in Visual Studio 2012 using C# as the programming language and when I call SharePoint server object model in the WCF there was an exception saying The Web application at "" could not be found.


Solution Background

Its because IIS hosted WCF sites use ApplicationPoolIdentity as its user. This is not authorized to SharePoint farm. So we have to give farm administrators credential in order to access SharePoint server.

Solution

  • Open IIS 
  • Go to "Application Pools" 
  • Click on your WCF Service site 
  • Click on "Advanced Setting"




  • Click the corner "Identity" under Process Model in order to change the identity

  • Select "Custom account" and click "Set"



  • There give your farm administrator user name and password.

Thursday, August 22, 2013

Create "Shared with Everyone" folder in Sky Drive Pro / Documents library - SharePoint 2013

Introduction

As I mentioned in my previous post our team faced issues in document migration from SharePoint 2010 to SharePoint 2013. The actions were not as expected.

Problem Background

In some profile we couldn't find "Shared with Everyone" which folder is having "Read" permission to "All Authenticated Users". So we created a console application which will create "Shared with Everyone" folder and set the permission as we needed.

Solution

Please pass your personal site (spWeb) to the method.

   
 public static void CreateSharedFolder(SPWeb web)
 {

    SPList list = (SPDocumentLibrary)web.Lists["Documents"];
    //Get the folders inside Documents library
    SPFolderCollection folders = web.GetFolder(list.RootFolder.Url).SubFolders;
    List<string> folderList = new List<string>();
    //Add the SPFolderCollection to a generic list
    foreach (SPFolder folder in folders)
    {
        folderList.Add(folder.Name);
    }
    //Check whether folder list has shared with everyone folder
    if (!folderList.Contains("Shared with Everyone"))
    {

       //Create folder inside Documents library 
       folders.Add("Shared with Everyone");

       //Greate users
       SPUser allUser = web.EnsureUser("NT AUTHORITY\\authenticated users");
       //Get folder
       SPListItem item = list.Folders[0];
       if (!item.HasUniqueRoleAssignments)
           item.BreakRoleInheritance(true);

       SPRoleAssignment roleAssignment = new SPRoleAssignment(allUser);
       SPRoleDefinition roleDefination = web.RoleDefinitions["Read"];
                //Add role assignment
       roleAssignment.RoleDefinitionBindings.Add(roleDefination);
       item.RoleAssignments.Add(roleAssignment);
       web.AllowUnsafeUpdates = true;
       item.Update();
       web.AllowUnsafeUpdates = false;

    }

}
 
 


Conclution
Now you can see "Shared with Everyone" folder inside SkyDrive pro.

Thursday, August 15, 2013

Move (Personal) Documents into SkyDrive Pro after migrating from SharePoint 2010 to SharePoint 2013

Introduction

If you have working on migrating SharePoint 2010 personal sites to SharePoint 2013 personal sites;  documents migration may become a headache. The expectation of the action is
"The Personal and Shared document libraries in SharePoint Server 2010 are combined into the SkyDrive Pro document library on the user's My Site in SharePoint Server 2013. Items from the Shared folder are stored in the Shared with Everyone folder in SharePoint Server 2013. Items from the Personal folder are stored at the root of the SkyDrive Pro document library and only shared with the owner of the My Site." - MicroSoft

Problem Background

But in our case, the documents didn't shift under SkyDrive but they were seen under site contents as another document library.

So I wrote a console application to move all the documents to SkyDrive. Here I'm presenting a simple code snippet which you have to modify to use other document library and sub folders under document library. 

Solution 

private static void MovePersonalDocuments(SPWeb web)
{
 SPFolder folder = web.GetFolder("Personal Documents");
 SPFileCollection collFile = folder.Files;
 ///*Copy the files to a generic List of type SPFile*/
 List listFiles = new List(collFile.Count);
 foreach (SPFile oFile in collFile)
 {
  listFiles.Add(oFile);
 }
 SPList list = (SPDocumentLibrary)web.Lists["Documents"];
 for (int i = 0; i &lt; listFiles.Count; i++)
 {
    SPFile movefile = collFile[0];
    Console.WriteLine("Moving File: " + movefile.Name);
           web.AllowUnsafeUpdates = true;
    byte[] fileBytes = movefile.OpenBinary();
    string destUrl = list.RootFolder.Url + "/" + movefile.Name;
    movefile.MoveTo(destUrl, true);
           web.AllowUnsafeUpdates = false;
   Console.WriteLine("Success");
 }
}

Conclusion 

  • Please note that I have only considered moving Personal Documents.
  • The code will help to move Shared Documents and Sub folders as well. 

Wednesday, July 24, 2013

Export and Import SharePoint Objects ( SPSite | SPWeb | SPList | SPListItem ) using C# code

Introduction

Currently I’m working on creating tool which needs to export SharePoint Objects such as SPSite, SPWeb,  SPList, SPListItem from one site to another.

Solution Background

There are SPExportObject, SPExportSettings,  SPExport, SPImportSettings, SPImport classes under Microsoft.SharePoint.Deployment namesspace. You have to simply assign the needed properties and call the appropirate methods.

Solution

I will describe how to export and import a SpWeb object so that you follow the same for other sharepoint objects as well.
Export SpWeb
public void exportSpWeb(SPWeb spWeb, string fileLocation)
{
  SPExportObject spExportObject = new SPExportObject();
  spExportObject.Id = spWeb.ID;
  spExportObject.IncludeDescendants = SPIncludeDescendants.All;
  spExportObject.Type = SPDeploymentObjectType.Web;
  //Here if it is a "SpSite - SPDeploymentObjectType.Site",
  //"SpList - SPDeploymentObjectType.List and the same for other objects"
  SPExportSettings settings = new SPExportSettings();
  settings.SiteUrl = spWeb.Url;
  settings.ExportMethod = SPExportMethodType.ExportAll;
  settings.FileLocation = fileLocation;
  //Location where your file should be stored Eg. C:
  settings.FileCompression = true;
  settings.IncludeSecurity = SPIncludeSecurity.All;
  settings.ExcludeDependencies = true;
  settings.BaseFileName = spExportObject.Id.ToString();
  //You can give any name
  settings.ExportObjects.Add(spExportObject);
  SPExport export = new SPExport(settings);
  export.Run();
}
After the execution of  method, you will find a .cmp file stored in fileLocation you gave (Eg. C:) named as you gave in the line settings.BaseFileName = spExportObject.Id.ToString();.
This is the you exported and which needs to be imported into another site.
This is the way you can import this file to another site.
public void importSites(string siteUrl, string fileLocation, string fileName)
{
  SPImportSettings settings = new SPImportSettings();
  settings.SiteUrl = siteUrl;
  //Destination site url.
  settings.FileLocation = fileLocation;
  //Where the file stored locally.
  settings.BaseFileName =  fileName + ".cmp";
  //Name fo the file you stored lacally.
  //.cmp is the extenstion of imported file.
  settings.FileCompression = true;

  SPImport export = new SPImport(settings);
  export.Run();
}
After the execution of this method your SharePoint Object will be available in destination site.

Conclusion 

SharePoint objects can be exported and imported using the above method.
PS: When concatenating a string with another string use String.Concat() function.