Monday, November 17, 2014

SharePoint Status Notification

It is very important to notify end users about the actions that are going on. Doing it in SharePoint standard style is the way to go. In this article we will see how to display notification and status messages using sp.js support with Visual Studio 2010.

What are those?

The following figure shows the notification and status messages in a SharePoint site during different operations:

How to do it

We will create a visual web part that will perform some server side actions. After that it will show notification and status messages to inform the user, just like above. This will work in the standard web part as well.
Creating Visual Web Parts in Visual Studio 2010:
  1. Go to File-New-Project. Under SharePoint 2010 project templates, select Visual Web Part template. Choose name, location and click ok.
  2. Next, choose an existing SharePoint site for debugging and choose Deploy as Farm Solution.
  3. This will add various project items that you could see in the solution explorer. One of them is VisualWebPart1 that is the actual visual web part.
  4. Expand it and you will see the web user control files, VisualWebPart1UserControl.ascx and VisualWebPart1UserControl.ascx.cs. As we know, VisualWebPart is a web user control (.ascx) being loaded using a standard web part.
  5. Go to the source view of the VisualWebPart1UserControl.ascx and add the following JavaScript:

  6. 01<script language="javascript" type="text/javascript">  
    02     var statusID;
    03     function showNotif() {
    04         SP.UI.Notify.addNotification('Done with the processing...', false);
    05         statusID = SP.UI.Status.addStatus("Title:", "Your request has been processed.");
    06         SP.UI.Status.setStatusPriColor(statusID, 'green');
    07         setTimeout(function () { SP.UI.Status.removeStatus(statusID); },4000);
    08       
    09     }
    10 </script>

    IMPORTANT:
    The above JavaScript code is using SP.UI namespace to show notification and status. SP.UI.Notify class has a method addNotification() that will display a notification and it takes 2 parameters: first is the text (html) that you want to display and second is a Boolean parameter that will specify whether the notification stays as sticky notification or not. In this case false means, it should disappear after a few seconds.
    SP.UI.Status class has a method addStatus() that will display a status message and it takes 2 parameters; the first one is title, which is always rendered in bold and second is the actual text (html). Since status message will not disappear automatically, we need to save its ID in a variable and later remove it. SP.UI.Status.setStatusPriColor() method is used to set the background color of the message.
    After a delay of 4 seconds, the status message is removed using SP.UI.Status.removeStatus() method that takes the id of the status.
  7. Next, add the following markup below the script which will add a button with 2 labels:


  8. 1 <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click Me" />
    2 <p>
    3     <asp:Label ID="Label1" runat="server" Text="Waiting for click...and will show notification "></asp:Label>
    4     <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
    5   
    6 </p>

  9. Label1 will be used to display some server side processed messages, and Label2 will be used to run JavaScript function showNotif() to display notification and status messages.
  10. Go to the code behind file VisualWebPart1UserControl.ascx.cs and add the following code in the Button1_Click() event handler so that it looks like: (Double Click on the Button1 in design view to create following event handler)


  11. 1 protected void Button1_Click(object sender, EventArgs e)
    2         {
    3   
    4             this.Label1.Text = "Finished processing on " + DateTime.Now.ToString()+   ". [Set from code behind]";
    5             //set the script over the label using SP.SOD.ExecuteOrDelayUntilScriptLoaded
    6             //this method will wait for sp.js to be loaded fully before calling 
    7             //showNotif javascript method
    8             this.Label2.Text = "<script>ExecuteOrDelayUntilScriptLoaded(showNotif,'sp.js');</script>";            
    9         }

  12. In the above code, on the first label, we are simply setting a message concatenated with current date and time. In a real application, this can be any valid allowed SharePoint processing. On the second label we are setting a script call as text that will cause our JavaScript function to run.
  13. IMPORTANT: We have to use ExecuteOrDelayUntilScriptLoaded() to invoke the JavaScript function so that sp.js is fully loaded before the function tries to run. If we do not use it, we will run into a JavaScript error.
  14. That’s it for the development. In the Visual Studio solution explorer right click and say Deploy.

Testing the web part:


  1. Open the SharePoint site in the browser for which the project was built and deployed.
  2. On the home page, or any page, Edit and insert the visual web part. You will find the web part in Custom category by default.
  3. We will see the following after adding the web part on the page:

  4. Click on the Button and we will see the following:

  5. In the above image we can see the notification and status message.
  6. After 4 seconds the status message will be removed and after a few more seconds, the notification will be removed as well.

Thursday, November 13, 2014

 Sharepoint Object Model


What is a SPSite and SPWeb object, and what is the difference between each of the objects? 

The SPSite object represents a collection of sites (site collection [a top level sites and all its subsites]). The SPWeb object represents an instance SharePoint Web, and SPWeb object contains things like the actual content. A SPSite object contains the various subsites and the information regarding them.

How would you go about getting a reference to a site?

Select For Unformatted Code
C#:
oSPSite = new SPSite("http:/server");
oSPWeb = oSPSite.OpenWeb();
Internet Explorer 6, Netscape Navigator 6.2 or later.

What does a SPWebApplication object represent? 

The SPWebApplication objects represents a SharePoint Web Application, which essentially is an IIS virtual server. Using the class you can instigate high level operations, such as getting all the features of an entire Web Application instance, or doing high level creation operations like creating new Web Applications through code.

Would you use SPWebApplication to get information like the SMTP address of the SharePoint site?
Yes, since this is a Web Application level setting. You would iterate through each SPWebApplication in the SPWebApplication collection, and then use the appropriate property calls (OutboundMailServiceInstance) in order to return settings regarding the mail service such as the SMTP address.

How do you connect (reference) to a SharePoint list, and how do you insert a new List Item? 

Select For Unformatted Code
C#:
1. using(SPSite mySite = new SPSite("yourserver"))
2. {
3. using(SPWeb myWeb = mySite.OpenWeb())
4. {
5. SPList interviewList = myWeb.Lists["listtoinsert"];
6. SPListItem newItem = interviewList.Items.Add();
7. 8. newItem["interview"] = "interview";
9. newItem.Update();
10. }
11. }

How would you loop using SPList through all SharePont List items, assuming you know the name (in a string value) of the list you want to iterate through, and already have all the site code written? 

Select For Unformatted Code
C#:
1. SPList interviewList = myWeb.Lists["listtoiterate"];
2. foreach (SPListItem interview in interviewList)
3. {
4.  Here you put any condition to filter the values
            If(Interview[“name”].ToString()==”test”)
{
Add to ArrayList
}

“name” is column name in particular list
}

Another method use can CAML Query to get values from list. This method is faster compared to above

SPList interviewList = web.Lists["listtoiterate"];
SPQuery spQuery = new SPQuery();
spQuery.Query = @”<Where>
  <Eq>
    <FieldRef Name="name" />
      <Value Type="Text">test</Value>
  </Eq>
</Where>”;

SPListItemCollection queryitems = interviewList.GetItems(spQuery);

What does AllowUnsafeUpdates do ?

If your code modifies Windows SharePoint Services data in some way, you may need to allow unsafe updates on the Web site, without requiring a security validation. You can do by setting the AllowUnsafeUpdates property.

C#:
using(SPSite mySite = new SPSite("yourserver"))
{
using(SPWeb myWeb = mySite.OpenWeb())
{
myWeb.AllowUnsafeUpdates = true;
SPList interviewList = myWeb.Lists["listtoinsert"];
SPListItem newItem = interviewList.Items.Add();

newItem["interview"] = "interview";
newItem.Update();
}
}

What does RunWithElevatedPrivileges do?

Assume that you have a Web Part in which you want to display information obtained through the Windows SharePoint Services object model, such as the name of the current site collection owner, usage statistics, or auditing information. These are examples of calls into the object model that require site-administration privileges. Your Web Part experiences an access-denied error if it attempts to obtain this information when the current user is not a site administrator. The request is initiated by a nonprivileged user. you can still successfully make these calls into the object model by calling the RunWithElevatedPrivileges method provided by the SPSecurity class.
C#:
SPSite siteColl = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate() {

using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID)) {
using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID)) {
string SiteCollectionOwner = ElevatedsiteColl.Owner.Name;
string Visits = ElevatedsiteColl.Usage.Visits.ToString();
string RootAuditEntries =
ElevatedSite.RootFolder.Audit.GetEntries().Count.ToString();
}
}

});

In some place you will get error “Access Denied”  like when you try to execute caml query or something in that case if ypu place you caml query code inside this RunWithElevatedPrivileges delegate then automatically it will take system account rights and run the code.

What is ServerUpdate() and SystemUpdate() ?

Any changes in the list, i.e. new addition or modification of an item.. the operation is complete by calling the Update method.


But if a List is set to maintain versions .. and you are editing an item, but don't want to save it as a new version, then use the SystemUpdate method instead and pass in 'false' as the parameter.

Monday, November 10, 2014

SharePoint Backup old way

It's critical to develop and document a tested back-up schedule and disaster recovery plan which will replicate both the database content of SharePoint, as well as the web server(s) settings and customizations. In spite of SharePoint's database-centric content storage system, most deployments contain a healthy number of enhancements and customizations to their SharePoint instance inextricably linked to the state of their web server(s). Failing to replicate and store back-ups of the web server(s) themselves will likely dramatically increase recovery and restoration downtime.


Since data loss disasters come in multiple levels of severity, it's important to have recovery procedures that address each. I suggest a 3-tiered approach:
  1. Entire server farm restoration process (complete web server and database loss).
  2. Web application, site, and site collection restoration process (database content loss).
  3. Individual content object restoration process (recycle bin).
If possible, backing up the entire web server(s) with an image of the box (or VM) is ideal, at an interval appropriate for your system's size and rate of change. I also suggest creating an image of the box immediately before applying any patches/updates. In addition to imaging the entire SharePoint web server(s), I also backup the servers' individual 12 hive directories (C:\Program Files\Common Files\Microsoft Shared\Web server extensions\12) and Inetpub directories (C:\Inetpub). These directories hold most of the pertinent files involved in SharePoint customizations and configuration, and provide another layer of security in the case the server images are lost or damaged. The following is a list of potential SharePoint settings and configurations maintained within the web server(s):
  • Application Pool settings, including service accounts (all accounts that run as Web applications, including the crawler account and the search account).
  • Secure Sockets Layer (SSL) certificates
  • Alternate access mapping settings
  • Farm-level search settings
  • Activated features
  • 12 hive - (C:\Program Files\Common Files\Microsoft Shared\Web server extensions\12)
  • GAC – global assembly cache; a protected operating system location where .NET framework code assemblies are installed to provide full system access (C:\WINNT\assembly)
In addition, it is generally a good idea to maintain a complete and up-to-date list of SharePoint databases and the web application(s)/site collection(s) they map to. SharePoint databases should be backed up appropriately based on the frequency of content changes within your system, generally a daily incremental and weekly full SQL back-up schedule is a good starting point. The weekly (or daily) database back-ups should be stored somewhere off-site in the event recovery from a catastrophic loss (i.e. your office or datacenter burns down).


Ensuring your recycle bin settings are correctly configured will often save you major headaches when users (inevitably) accidentally delete content. Navigate to Central Admin > Application Management > Web Application General Settings and scroll down to the bottom of the page to find the recycle bin settings for the current selected web application (change selection at the top of the page). By default, SharePoint activates web application recycle bins and stores deleted content in it for 30 days, after which the deleted content is moved to the 2nd stage recycle bin (the site collection level recycle bin) where it is stored indefinitely unless the 2nd stage space quota is reached. The space quota is set by default to 50% of the total space allocated to the web application itself.


An important point to note about recycle bins (so important I'm putting it in bold): Site and site collection deletion is not managed through the Recycle Bins – content contained within deleted sites/site collections will be permanently lost. (One reason I don't allocate full permissions to sites as part of my governance policy.)


I hope these points of preponderance provide you with some inspiration and/or guidance when devising your own SharePoint back-up schedule and recovery procedure because (at the risk of sounding super-cliche) - when it comes to SharePoint - failing to plan is planning to fail.