Wednesday, 2 October 2013

Change Default Form Per Content Type

By default in SharePoint list, the following things happen:

  • When you click New Item, you will be redirected to /NewForm.aspx page.
  • When you click Edit Item, you will be redirected to /EditForm.aspx page.
  • When you click View Item, you will be redirected to /DispForm.aspx page.

If you don't want to use these default forms and you want to use a different form, you need to change the default form per content type of the SharePoint list. Basically, you can do it by using SharePoint designer but sometimes it is not working that's why I prefer doing it programmatically. And since I'm doing it always, I already created a console application (exe program) in order to change it via code.


The console application requires five input parameters as listed below:
  1. Full URL of the site
  2.          e.g. http://www.xc.com/sites/domain
  3. Name of the SharePoint list
  4.          e.g. Domain Account Request Application
  5. Name of the content type
  6.          e.g. Request
  7. Type of the form that you want to change. (You need to input here either new, edit or display.)
  8.          e.g. new
  9. Name of the different form
  10.          e.g. NewForm2.aspx


Here is the code that I used:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace ChangeDefaultFormPerContentType
{
    class Program
    {
        static void Main(string[] args)
        {

            if (args.Length != 5)
            {
                Console.WriteLine("Incomplete parameter");
                Console.WriteLine("Input the parameters. Format: <full site url> <listName> <content type Name> <Form Type: new | edit | display> <Form Name>");
                Console.WriteLine("e.g. http://www.abc.com/sites/Firewall Perimeter Request new NewForm2.aspx");
                return;
            }

            string siteUrl = args[0];  // "http://www.xc.com/sites/domain"; //
            string listName = args[1]; // "Domain Account Request Application"; //
            string contenType = args[2]; // "Request"; //
            string formType = args[3]; // "new"; //
            string formName = args[4]; // "NewForm2.aspx"; //

            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPList list = web.Lists[listName.Trim()];
                    string sz = list.RootFolder.Url;
                    SPContentType ct = list.ContentTypes[contenType.Trim()];

                    switch (formType.Trim())
                    {
                        case "new":
                            {
                                ct.NewFormUrl = sz + "/" + formName.Trim();
                                ct.Update();
                                list.Update();
                                Console.WriteLine(string.Format("NewFormUrl of {0} content type was updated successfully into {1}", contenType, formName));
                                break;
                            }
                        case "edit":
                            {
                                ct.EditFormUrl = sz + "/" + formName.Trim();
                                ct.Update();
                                list.Update();
                                Console.WriteLine(string.Format("EditFormUrl of {0} content type was updated successfully into {1}", contenType, formName));
                                break;
                            }
                        case "display":
                            {
                                ct.DisplayFormUrl = sz + "/" + formName.Trim();
                                ct.Update();
                                list.Update();
                                Console.WriteLine(string.Format("DisplayFormUrl of {0} content type was updated successfully into {1}", contenType, formName));
                                break;
                            }
                    }


                }
            }

        }
    }
}



Tuesday, 1 October 2013

Shrink Database Logs

Shrinking the transaction log file is a process of reducing the size of the transaction log. This process is important because if the transaction log file is left unchecked it can grow until it consumes the hard disk space of your server.

Listed below are the steps on how to truncate or shrink database log files (LDF) in your Development or Local Servers. In these steps we will set the database into a Simple Recovery Model which automatically reclaims log space. 
  1. Right click database >> Options >> Set Recovery Model to Simple >> OK
  2. Right click database >> Tasks >> Shrink >> Files
  3. Select File type = Log >> OK
  4. Set back the Recovery Model to Full

For more information about recovery model refer to http://msdn.microsoft.com/en-us/library/ms189275.aspx




Error - The site collection could not be restored

I encountered this error while restoring a site collection in a separate content database in another server. The complete error message is:

"The site collection could not be restored. If this problem persists, please make sure the content database are available and have sufficient free space."

Below are the steps that I've done to debug and fix the issue:

  1. I checked the size of the hard disk drives and it has sufficient free space. 
  2. I tried to restore it in another PC / server and I have restored it successfully. (That's why I wondered why this error happens only in that particular server)
  3. I checked the design of dbo.Sites table in the newly created content db and found out that there are two missing columns, namely FullUrl and UserAccountDirectoryPath. So, I added manually these columns and after that I have successfully restored the site collection in that server.

FullUrl column


UserAccountDirectoryPath column





Monday, 30 September 2013

Sharepoint Terms

This page provides definitions for common terms relating to SharePoint.

SharePoint
  • It helps team members to connect and exchange information in a collaborative manner. It helps to centralize enterprise information for efficient functioning.
  • It unites all the documents into one centralize place and unifies the data transport mechanism.
  • It is a central enterprise information portal.

Application Pages
  • Application pages are generic pages which will be used by all the sites in a site collection.
  • These are generic pages which are shared across sites.
  • These pages can be found in C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\Template\Layouts

Site Pages
  • Site pages are customized pages and are saved into content database.

SafeMode Parser
  • Safe mode parser is a page parser provided by SharePoint. It loads the page that is stored in the content database.
         When a page is requested, it first checks in the document table and then goes to the content table to load the page. If it does not find data of the page, it goes to the file directory to load the page. This loading is done by ASP.Net runtime itself. But if there is data present in the content table then it is loaded by the SafeMode parser.


Virtual Path Provider
  • It is an abstraction which loads the page from the content or the file system depending on whether it is customized or common pages and passes the same to the ASP.Net run time.

Web Part
  • It is a kind of a web control which can be deployed in a web part zone control.

Data View Web Part
  • It displays data with rich design support through SharePoint designer.

List View Web Part
  • It helps to display list content for any list in the SharePoint site.

Image Web Part
  • It helps to display image files.

Content Editor Web Part
  • It is use to display static HTML content using a WYSIWYG editor or to link to a text file. It supports writing JavaScript.

Members Web Part
  • It helps to display members of the site.

Page Viewer Web Part
  • It displays web page in an iframe.
  • It can be used to show an external application.

Shared Services Provider
  • It is a set of services provided by MOSS which can be shared across multiple server farms.

.eml
  • It is an industry standard use by email clients, servers and applications.
  • It contains the entire message, including body text and attachments.

XSLT
  • XSLT stands for Extensible Stylesheet Language Transformations. It is use to transform XML documents into other formats like XHTML.

CAML
  • CAML stands for Categorial Abstract Machine Language. This language is XML-based and is used to customize and build SharePoint sites.

jQuery
  • It can be defined as an easy JavaScript.
  • It is a JavaScript library or API that will able you to do script in one line of code instead of ten or more lines of JavaScript.

Content Database
  • It is where SharePoint stores all its data.

Event Handler
  • It is a server-side code that is called when registered events occur within the SharePoint environment. 
  • Custom event handlers can be added or attached to and have a scope of Web application, site collection, Web site, list, or document library.













Sunday, 29 September 2013

Examples of SharePoint Calculated Field Formulas

SharePoint calculated field is a SharePoint column where you can implement different types of formulas, such as conditional formulas, date and time formulas, mathematical formulas and text formulas.

These formulas have its own use. Conditional formulas are use to test the condition of a statement and return a Yes or No value. Date and time formulas are use to to perform calculations that are based on dates and times. Mathematical formulas are use to perform a variety of mathematical calculations, such as adding, subtracting, multiplying, and dividing numbers. Text formulas are use to manipulate text, such as combining or concatenating the values from multiple columns, comparing the contents of columns, removing characters or spaces, and repeating characters.


Below are sample formulas on how to:
  1. convert the datetime field value into different formats.

    • Month-Year (e.g. January-2013)

    =CHOOSE(MONTH([ValidityDate]),"January","February","March","April","May","June","July","August","September","October","November","December")&"-"&YEAR([ValidityDate])

    • Year (e.g. 2013)

    =TEXT(YEAR([ValidityDate]),"0000")

    • Month (e.g. 01-January)

    =TEXT(MONTH([ValidityDate]),"00")&"-"&CHOOSE(MONTH([ValidityDate]),"January","February","March","April","May","June","July","August","September","October","November","December")




  2. get the start and end day of the month of the datetime field value

    • start day of the month

    =DATE(YEAR([ValidityDate]),MONTH([ValidityDate]),1)

    • end day of the month

    =DATE(YEAR([ValidityDate]),MONTH([ValidityDate])+1,1)-1



To see more examples of common formulas, click here.





Friday, 27 September 2013

SPSecurityTrimmedControl

You can use SPSecurityTrimmedControl if you want to display the content (HTML code or other controls) based on the user's permission.

<SharePoint:SPSecurityTrimmedControl ID="SPSecurityTrimmedControl1" PermissionsString="ApproveItems" runat="server" >
         
</SharePoint:SPSecurityTrimmedControl>


The PermissionsString attribute of <SharePoint:SPSecurityTrimmedControl /> defines the permissions the user must have in order to view the content. Some of the built-in SharePoint permissions that you can use as a value of this attribute are ApproveItems, ManageLists, AddListItems, EditListItems, DeleteListItems, ViewListItems, ManageAlerts, ViewVersions, DeleteVersions and CancelCheckout. (To see the complete list of possible values, click here.)


In the below example, the current user will be able to see the Approve button only if he has "ApproveItems" permission defined in the PermissionsString.

<SharePoint:SPSecurityTrimmedControl ID="SPSecurityTrimmedControl1" PermissionsString="ApproveItems" runat="server" >
          <asp:Button runat="server" class="ms-ButtonHeightWidth2" OnClick="BtnApprove_Click" Text="Approve" id="btnApprove" />
</SharePoint:SPSecurityTrimmedControl>


Thursday, 26 September 2013

Some Code Optimizations

When we create programs, it is very important to make its code optimized. It is because having an optimized code will improve the program's performance, like execution time, code size, etc. It will make your code run faster, use fewer server resources, and make your code easier to debug and maintain.

Here are some ways to make your code optimized:

  1. Use string.format instead of string concatenation (+). The format function is faster than the + operator.

Example:
            szConfirmMsg = “Are you sure you want to change the store  number on audit id ” + auditId + “ from “ + oldStoreNo + “ to “ + newStoreNo + “?”;

            szConfirmMsg = string.Format(“Are you sure you want to change the store  number on audit id {0} from {1} to {2}?”, auditId, oldStoreNo, newStoreNo);


  1. Use System.IO.Path class if dealing with path and filenames.

Example:
            Searching if file is valid:        
            string fileExt = System.IO.Path.GetExtension(fileName);
            if (fileExt.ToLower().Equals(“.csv”))
            {
                        bValid = true;
            }


  1. Use string.Empty instead of ‘’ to initialize a string variable to an empty string. string.Empty is faster than ‘’ because it doesn’t create a new object while ‘’ actually creates an object.

Example:
            string userMessage = ‘’;

            string userMessage = string.Empty;


  1. Use string.Equals instead of the equal operator (= =) to test strings for equality.

Example:
            if (szName = = ‘’)
            if (a = = b)

            if (szName.Trim().Equals(string.Empty))

            if (a.Equals(b))