Friday, June 24, 2016

Prepare and configure SharePoint 2013 for App development and debugging Steps

Prepare and configure SharePoint 2013 for App development and debugging Steps


Source: https://blogs.msdn.microsoft.com/how24/2013/06/14/prepare-your-sharepoint-2013-farm-for-app-development-and-debugging/
There are many great articles that talks about how to configure your SharePoint 2013 farm for apps development. At the end of this article I will list a lot of these great references. I’m going to try to summarize the important things you need to know and also cover few FAQs along the way.
First of all, you need to know that there are two main types of SharePoint apps you can develop on prim in your local SharePoint 2013 farm:
  1. SharePoint hosted apps
  2. SharePoint provider hosted apps
The third type SharePoint Auto hosted (Azure auto hosted apps) is only available on SharePoint online tenants part of Office 365. Also it’s important to note that if you plan to publish your SharePoint app into the SharePoint store to make some money the above mentioned types (Hosted & provider hosted) are the only allowed ones as long as they don’t request full control permission. For more details about the submission requirements check this link.
In order to make your SharePoint 2013 farm ready to develop and deploy apps you need the following:
  1. Turn on\create required services and service applications
  2. Configure DNS records along with SharePoint Web Applications
  3. Configure required service applications
  4. Prepare your tools\environment
I’m going to go through the above steps quickly.
First: Turn on\Create required services and service applications
You need to turn on the following services:
  1. App Management Service
  2. Microsoft SharePoint Foundation Subscription Settings service
 
Next step is to create the following service applications:
1. App Management Service Application:
This service application is responsible of tracking app licenses and app permissions …etc. This service application can be created from Central admin or via PowerShell.
2. Subscription settings service:
This service is responsible of generating the apps url, it also maintains tenants subscriptions in a multitenant deployment. This service application cannot be created from Central Admin. You will need to use PowerShell commands to create it. Use the following commands <Source: TechNetArticle>:
# Gets the name of the managed account and sets it to the variable 
# $account for later use
  $account = Get-SPManagedAccount “<AccountName>”
   # Create an application pool for the Subscription Settings service application.
# Use a managed account as the security account for the application pool.
# Store the application pool as a variable for later use.
  $appPoolSubSvc = New-SPServiceApplicationPool
   -Name SettingsServiceAppPool -Account $account

# Create the Subscription Settings service application, using the 
# variable to associate it with the application pool that was created earlier.
# Store the new service application as a variable for later use.
  $appSubSvc = New-SPSubscriptionSettingsServiceApplication
  –ApplicationPool $appPoolSubSvc –Name SettingsServiceApp
  –DatabaseName <SettingsServiceDB>

# Create a proxy for the Subscription Settings service application.
  $proxySubSvc = New-SPSubscriptionSettingsServiceApplicationProxy
  –ServiceApplication $appSubSvc
Where:
  • <AccountName> is the name of the managed account in the SharePoint farm.
  • <SettingsServiceDB> is the name of the Subscription Settings service database.
At the end of this step I want to mention that you *have* to start and create these two service applications to enable apps deployment and development in your farm. So this step is mandatory in case you are wondering.
Second: Configure DNS records along with SharePoint Web Applications
Since I’m talking about a development environment here, I’m going to assume that your dev box is hosted in your company’s domain or at your local virtual environment. So you will not need to purchase any domain names or anything. This step confuses a lot of developers specially the ones who don’t have a lot of experience in with windows domain and active directory services. To keep it simple I’m going to suggest a specific setup that you can follow.
There are two things you need to touch in this step:
  1. DNS manager
  2. Central Admin (probably)
First thing you need to do is to setup the required domain names you are going to use for your apps and SharePoint sites …etc. You will need a separate domain name for your apps (recommend to be totally separate and not a sub-domain of a domain you use to host SharePoint applications that will use the apps – this is for security physical isolation purposes). Let’s dig a little deeper into this:
I want to have one domain name created for my intranet:
DNS: Intranet.SWRanger.com
IP: 192.168.0.113
I want to have another domain name created for my apps:
DNS: Apps.com
IP: 192.168.0.113
Note: I’m using the same IP-address for both domain names since I only have one SharePoint box in my 2013 farm and one network card (NIC).
I will use my Intranet site (which is a team site) for developing my apps. So I will use the root site collection under that Sharepoint application to deploy and debug my apps.
In order to create these domain names you need to login to your domain controller and open DNS manager. First thing you need to do is to create the domain name for Intranet. To do this follow the steps:
 
  1. Expand Forward lookup Zones then select your domain SWRanger.com
  2. Then right click on the selected domain node
  3. Select net Host (A or AAAA)… option
  4. Enter the name Intranet
  5. Enter the IP-Address (SharePoint box IP address) 192.168.0.113
  6. Hit Add Host
Now the next step is to create the apps domain name and have it point to the SharePoint box, follow the steps:
 
  1. Right click on Forward lookup zones the select New Zone
  2. In the New Zone Wizard click Next.
  3. In the Zone Type page click Next.
  4. In the Active Directory Zone Replication Scope page, select the appropriate replication method then click Next (The Default setting is fine in dev environments with one DC).
  5. In the Zone Name page, in the Zone name box type the name for your new app domain name Apps.com, and then click Next.
  6. The New Zone Wizard shows the new domain name for apps.
  7. On the Completing the New Zone Wizard page, review the settings, and then click Finish.
Now you need to create a wildcard alias for the new apps domain name so that SharePoint can generate any alias (app instance id) under your domain and still resolve to your SharePoint server. Follow the steps:
 
  1. Expand Forward Lookup Zones
  2. Select your new Apps domain Apps.com
  3. Right click and select New Alias (CNAME)
  4. Type “*” in the Alias name field
  5. Under Fully qualified domain name (FQDN) for target host: Click Browse
  6. In the Look in field select your domain name that contains your intranet domain name
  7. In the Records section double click on the records until you find your Host (A) record pointing to your intranet site Intranet.SWRanger.com
  8. Select your intranet domain name Intranet.SWRanger.com
  9. Click OK
  10. Click OK
Now your DNS records are ready. All you need to do is to make sure that you have the appropriate settings on IIS\SharePoint so that IIS will listen on your apps domain name Apps.com and rout the request to a SharePoint application which will redirect your app accordingly.
Before we configure IIS\SharePoint you want to make sure that your DNS configuration for the App domain name is working properly. To test that, ping the new apps domain name with a random sub-domain for instance ping the following: abc1234567.Apps.com if you get a response back with the IP Address of your SharePoint box that means you are golden and ready to go to the next step.
In this step instead of changing IIS settings by adding more bindings to an existing site (if possible) we will just create a new SharePoint application on port 80 thatdoesn’t have a host name. This way this SharePoint application will work as a catch all for any DNS name created for the deployed app instances. Here are the important settings\configuration for the new SharePoint application you will create:
Name: Anything – I would call it something that identifies it as a catch all for apps requests
Port: 80
Host Header: <Empty>
Claims Type: Enable Windows Authentication | Integrated Windows authentication | NTLM (Note SharePoint Apps don’t support Claims\Kerberos combination)
App Pool: Use the same account as the one used for your SharePoint Applications that will use the apps or an account that has access to these SharePoint application’s content databases
Database Name: Anything – We will not create any site collections for this SharePoint application nor will need a content db. So make sure you remove this content database after the application is created
 

This step is complete now.
Third: Configure required service applications
Now you are ready to configure your App Management settings for the farm. Follow the steps below:
 
  1. Open Central Admin
  2. Navigate to Apps from the left nav then click on App Management | Configure App URLs
  3. Enter the App DNS you created in the previous step Apps.com in the App domain field
  4. Enter an App prefix, in my case I’m going to enter app
  5. Click OK
This step is complete. Now your farm is ready to deploy new apps.
Fourth: Prepare your tools\environment
There are few things you need to know about before your start developing apps for SharePoint. The two main thing I would highlight here are:
1. Use a Developer Site for deploying and testing your apps or enable the Developer feature
Visual studio 2012 will complain about a missing feature Developer if you attempt to deploy an application to a SharePoint site that is not created with the “Developer Site” template since it will be missing required lists and content types. So if you for example try to deploy your app (Using Visual Studio F5) to a team site or a publishing portal you will get the following error in Visual studio’s Error List:
Error occurred in deployment step ‘Install app for SharePoint’: Sideloading of apps is not enabled on this site.
 
In order to overcome this issue you need to enable the Developer feature on your Site collection where you want to deploy and test your apps using Visual Studio. Since this feature is hidden you will not see it in the list of the site collection feature, so you will need to enable it using PowerShell:
Enable-SPFeature e374875e-06b6-11e0-b0fa-57f5dfd72085 -url http://Intranet.SWRanger.com
  
2. Don’t use Farm admin (System Account) to deploy and test apps
SharePoint will not allow you to install nor uninstall apps using the farm account (System Account). If you try to deploy your app using Visual Studio F5you will get one of the following errors if you do it using System Account:
1. Error occurred in deployment step ‘Install app for SharePoint’: The System Account cannot perform this action.
 
2. Cannot perform this action
3. Sorry, something went wrong Please refresh the page and try again.
 
So avoid this issue you need to log in to SharePoint with a different account (not the farm admin) and\or running Visual studio with a different account other than the farm admin. Since in SharePoint 2013 we have removed the Sign in a different user menu option, you can get to it through the following URL:
/_layouts/closeConnection.aspx?loginasanotheruser=true

So the URL of our site should look like this:
Check this link for a list of other handy SharePoint links
This will prompt you for credentials that allows you to switch users.
Here are some other issues you might encounter and how to address them:
1. When deploying an app through Visual Studio you get the following error:
In the Error List:
Error occurred in deployment step ‘Install app for SharePoint’: Failed to install app for SharePoint. Please see the output window for details.
 
In the output window:
CorrelationId: 7ec1dfb0-4a04-46f6-8b22-1f4f28f6dd0a
        ErrorDetail: There was a problem applying the web template for the app web.
        ErrorType: App
        ErrorTypeName: App Related
        ExceptionMessage: Feature with Id ‘23330bdb-b83e-4e09-8770-8155aa5e87fd’ is not installed in this farm, and cannot be added to this scope.
        Source: AppWeb
        SourceName: App Web Deployment
Error occurred in deployment step ‘Install app for SharePoint’: Failed to install app for SharePoint. Please see the output window for details.
 
 That error suggests that SharePoint is trying to activate a web scoped feature called AppLockdown feature on the app web but it couldn’t find thatfeature installed in the farm in the first place. All you need to do is to install that feature to the farm using PowerShell:
Install-SPFeature Applockdown
 
 That is going to solve your problem.
2. When you try to deploy your app using a different developer account you used before or using a copy of the app VS project you get the following error:
Error occurred in deployment step ‘Install app for SharePoint’: The provided App differs from another App with the same version and product ID.
 
In order to overcome that issue, navigate to your target site collection and do the following steps:
1. Install the app if existed by navigating to Site Contents then hovering on the app and clicking Remove (Remember don’t do this with the System Account or it won’t work)
 
2. Navigate to Apps in Testing library and remove the app from there as well
3. Navigate to App Packages library and remove the app from there if existed
Lastly before I conclude here I would like to mention that you definitely want to plan to use SSL certificates to secure your SharePoint sites and apps traffic since they use clear text for the Auth tokens. It’s however not required, so your apps will work fine without SSL. That might be acceptable in in Dev environments butnever acceptable in production. I’m planning to include the steps of configuring self-services SSLs in development environments soon.
With that you should have all the information you need to start developing SharePoint apps. If you have any questions please leave me a comment.
Good luck :)

Here are some great references:

Monday, May 2, 2016

Delete items from SharePoint list and document libraries

Tuesday, June 14, 2011

Delete items from SharePoint list and document libraries


Some days ago I had a problem to delete all items from standard SharePoint list. There are the following possible ways to do it:
  1. Delete list at all and create it once again. This option is very fast but we need to create the list again with all fields, views etc. It is a rounite operation and could take much time. Also it can be item event receiver for delete action that makes some changes. The delete list operation without delete all items may cause some problems depending on the logic in the receiver.
  2. Select all list items and delete it.
Option 2 was more preferable for me. I had a Classes list with timetable for English courses. The list had about11.000 items and sometimes I had to delete them for my purposes. Also this list had one item event receiver for delete action - to delete classes from classes workspaces. So I've started to implement this solution as console application. The code was very simple - create SPSite, SPWeb objects, find list and select all items using empty SPQuery. After implementation I've started to test my solution. The overall performance was about50-90 items per minute. I was very surprised but in a short time I've found the problem. The item event receiver execution was too long. In this case the only one way is to delete items from list in threads. I've added a required parameter - number of threads. Each of them delete its portion of list items. After implemenation and testing the overall performance was 2000-3000 items per minute using 15 threads. So the whole delete operation is taking about 3-4 minutes now. This is a good result for me. The following code split all list items to batches for an every thread:

for (int i = 0; i < threadCount; i++)
                   {
                       var itemIds = new List<Guid>();
                       if (i != threadCount - 1)
                       {
                           itemIds.AddRange(
                               (from SPListItem item in items select item.UniqueId)
.Skip(i * batchCount).Take(batchCount));
}
                       else
                       {
                           itemIds.AddRange(
                               (from SPListItem item in items select item.UniqueId)
.Skip(i * batchCount));
}
                       ThreadPool.QueueUserWorkItem(DeleteAllItems, 
                             new ThreadParams {Event = events[i], ItemsIds = itemIds});
                   }
                   WaitHandle.WaitAll(events);
 
The application has 2 required parameters: listUrl and threadCount.
Usage example: clearlist.exe -listUrl http://localhost/sites/project/Lists/Classes/AllItems.aspx -threadCount 10
https://drive.google.com/file/d/0B7fUHMbH4ISkODVkMzFiMjUtY2VmMC00NjcyLWEzM2ItZjE4MTcxOTA2OTZk/view?ddrp=1&hl=ru#

Friday, April 22, 2016

Best Practices: Using Disposable Windows SharePoint Services Objects




1. https://msdn.microsoft.com/en-us/library/aa973248(v=office.12).aspx
2. https://msdn.microsoft.com/en-us/library/bb687949(v=office.12).aspx

SharePoint Best Practices Coding


SharePoint Best Practices Coding

Description: mail-image

If you are developer of any specific technology, you should know about best practices of that technology. You may ask why best practices important? Best practices are based on real time experience. so if you are unaware about it, you will end up writing unmaintainable, buggy or unoptimized code.

Lets start discussion about SharePoint best practices with real time example.


  1. Don't cache SharePoint objects that are not Thread Safe
Let's take real time scenario, we have to bind dropdown list with the SharePoint list. We know SharePoint list which we are binding with dropdown list is not going to change frequently, so caching will be better option to improve the performance of theapplication. Sample code is mentioned below:
                      SPListItemCollection colItems;
            if(null != HttpRuntime.Cache[key])
            {
                ddlItems = (SPListItemCollection)HttpRuntime.Cache[key];
            }
            else
            {
                // Do query on sharepoint listand cach SPListItemCollection object
            }
But we are unaware that SPListItemCollection object contains an embedded SPWeb object that is not thread safe and should not be cached.

Good Coding Practice is to cache DataTable in place of SPListItemCollection object.
Sample Code:
         private static object _lock =  new object();
          private DataTable GetDropDownItems()
         {
         DataTable dtDropDownItems;
   SPListItemCollection objListItems;
   lock(_lock)
   {
             dtDropDownItems= (DataTable)Cache["CachedDropDownItems"];
           if(dtDropDownItems== null)
           {
              objListItems = //Do query onSharePoint List
              dtDropDownItems= objListItems.GetDataTable();
              Cache.Add("CachedDropDownItems ", dtDropDownItems,..); // provide rest of the parameter of this method
           }
   }
   }

Note: There are various methods to cache object like HttpRuntime, System.Web.Caching.Cache,  and HttpContext.Current.Cache. Choose one to the method to cache depending upon your application requirement.

    2.
 Retrieve or fetch SPList instance from SPWeb object: There might be the multiple approach to get the instance of SPList in SharePoint. But while developing an application we should keep in mind about performance of the application. Mentioned below are two approach to achieve the same. 

        Approach 1:
 Not Recommended
       
 SPList objSpList = <SPWeb>.Lists["<List Title>"];   

        Approach 2:
 Recommended
       
 SPList objSpList = <SPWeb>.GetList("<List URL>");
    
        In the first approach, SharePoint loads "metadata" of all the SharePoint lists of current
 SPWeb object and then create SPList instance by Title comparison and also if Title of SharePoint list gets changed, There will be a code change. But in the second approach, SharePoint fetches GUID of the SharePoint list by list url and then loads the "metadata" of that particular list. User can not update the list URL after SharePoint list creation. So there is no possibility of any code change in this approach. 

    3.
 JavaScript methods call on page load in SharePoint: Sometime we need to call JavaScript methods on page to change UI or to set some controls value. we can use window.onload event to achieve this functionality. But I personally recommend that to use "_spBodyOnLoadFunctionNames" method provided by SharePoint because sometimes window.onload don't work properly.
        Approach 1:
 Not Recommended
        window.onload = funcation(){//JavaScript code};
        window.onload =
 <JavaScript method name>;

        Approach 2:
 Recommended
        
_spBodyOnLoadFunctionNames.push('<JavaScript method name>');

     4. Set RowLimit, ViewFields, and ViewFiledsOnly properties while fetching data from SharePoint list:
        Let take me take an example to make understand importance of these properties.

      Scenario: Suppose there isa list to store employee details. Following fields are present in this list:
·    Name
·    Designation
·    Domain
·    Address
·    Email
·    Contact Number
·    Rating
      We have to create a webpart to show top 5 employees name, designation and email in the home page of site based on employee rating.

        To achieve above mention scenario, we will end up with mentioned below code sample:

         Bad coding:
using (SPSite objSite = new SPSite("<Site URL>"))
{
    using (SPWeb objWeb = objSite.OpenWeb())
    {
        SPList objList = objWeb.GetList("<List URL>");
        SPQuery objQuery = new SPQuery();
        objQuery.Query = @"<OrderBy>
                                <FieldRef Name='ID' Ascending='False' />
                            </OrderBy>";
        SPListItemCollection employeeCollection = objList.GetItems(objQuery);
    }
}

In the above mentioned codeblock, we will fetch all the fields data but we have to display only 3 fieldsdata in the webpart. So there will be performance hit. As a good practice weshould pass ViewFields also. so that our query will return required fields data only.

            Add following line of code to improve the performation:
         Good coding
//We have specified view fields, now our query will fetch value of these three fields data.
objQuery.ViewFields = @"<FieldRef Name='Name'/>
                        <FieldRef Name='Designation'/>
                        <FieldRef Name='Email'/>";

Even though we have specified view fields, still SharePoint fetches following fields data:

·     ID
·    Created
·   Modified
As per problem statement, we do not want these fields data. SPQuery object has property called ViewFieldsOnly. If we set this property to true, these fields data will not come with the query result. It means, to improve our query performance, we will have to add one more line in our code:

Good coding:


   objQuery.ViewFieldsOnly = true;                                                                                      
   
Note: If you have to do write operation on fetched records by our query, do not set ViewFieldsOnly property to true otherwise while updating any item you will get following exception: "Value does not fall within the expected range."

Still we can improve our code. Here we need to show only 5 employees details and our query will fetch all employee details. So we can improve our code by providing RowLimit to 5.

Good coding:

  objQuery.RowLimit = 5;                                                                                                    
 
 

Note:
  Most of the time we do not know how many records will fetch after query execution. But as best practice we should set RowLimit if we know the threshold of our query.

Now we know, when to set which property and why these properties are important.



https://sureshunakka87.wordpress.com/2014/05/03/best-practices-using-disposable-windows-sharepoint-services-objects/

 

Best Practices: Using Disposable Windows SharePoint Services Objects

Posted on by nakkasuresh
 SPWeb.Lists Vs SPWeb.GetList
 There are many posts on this topic. So why I am writing one more post? Well just to share my experience and hope others will benefit from this.
SPWeb.GetList (string strUrl) – Good
using (SPSite site = new SPSite(strSite))
{
using (SPWeb web = site.OpenWeb())
{
SPList oList = web.GetList(http://Site/list/AllItem.aspx)
}
}
In this case, first retrieves the list GUID from the url (database hit), then it loads the metadata* for that specific list.
SPWeb.Lists (“name”) – Not Good 
using (SPSite site = new SPSite(strSite))
{
using (SPWeb web = site.OpenWeb())
{
SPList oList = web.Lists [“MyList”]
}
}
Please reffer the url for more Disposing sharepoint objects .
Cheers!!!!