Tuesday, 24 April 2012

Modal Popup in SharePoint 2010

Hello,
To create a modal popup in sharepoint 2010, follow these steps:

1. Create a visual webpart project.
2. In .ascx, wrtie the following code:
   <script type="text/javascript">
   function OpenDialog(URL) {
    var NewPopUp = SP.UI.$create_DialogOptions();
    NewPopUp.url = URL;
    NewPopUp.width = 900;
    NewPopUp.height = 500;
    SP.UI.ModalDialog.showModalDialog(NewPopUp);
  }
 </script>
 <asp:Button ID="btnOpenDialog" Text="Open Dialog"  
      OnClientClick="javascript:OpenDialog('/_layouts/settings.aspx'); return false;" runat="server" />

3. Deploy the webpart.

When you add the webpart on a page, and click on "Open Dialog" button, we will be noticing the page is opening in a modal popup window.



Monday, 23 April 2012

SharePoint 2010 Master Pages - Retrieve, Upload and Apply programmatically


protected void Page_Load(object sender, EventArgs e)
{
 try
 { 
  if (!(Page.IsPostBack))
  {
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
     using (SPSite pageLoadSite = new SPSite(SPContext.Current.Site.ID))
     {
      pageLoadSite.AllowUnsafeUpdates = true;

      using (SPWeb pageLoadWeb = pageLoadSite.OpenWeb())
      {
       pageLoadWeb.AllowUnsafeUpdates = true;

       GetMasterPages(pageLoadWeb);
       UploadMasterPageInMasterPageGallery(pageLoadWeb);
       SetMasterPage(pageLoadWeb);

       pageLoadWeb.AllowUnsafeUpdates = false;
      }
     pageLoadSite.AllowUnsafeUpdates = false;
    }
   });
  }
 }
 catch (Exception ex)
 {
  Throw ex;
 }
}


/// <summary>
/// Retrieves master pages from the master page gallery
/// </summary>
/// <param name="web">spweb object</param>
private void GetMasterPages(SPWeb web)
{
 try
 {
  SPDocumentLibrary masterPageGallery =        
      (SPDocumentLibrary)web.GetCatalog(SPListTemplateType.MasterPageCatalog);

  foreach (SPListItem masterPage in masterPageGallery.Items)
  {
    string displayName = masterPage.DisplayName
    string name = masterPage.Name;
  }

   
   string currentMasterFileName =  
          web.MasterUrl.Substring(web.MasterUrl.LastIndexOf('/') +    
                                  1);
 }
 catch (Exception ex)
 {
  throw new Exception("Exception in RetrieveMasterPages(). Message: " +  
                      ex.Message);
 }
}


/// <summary>
/// Uploads the master page file to master page gallery.
/// </summary>
/// <param name="web">spweb object</param>
private void UploadMasterPageInMasterPageGallery(SPWeb web)
{
 try
 {
  // fuMasterPage is upload control in my project.
  SPDocumentLibrary masterPageGallery =     
       (SPDocumentLibrary)web.GetCatalog(SPListTemplateType.MasterPageCatalog);
  masterPageGallery.RootFolder.Files.Add(
                    masterPageGallery.RootFolder.ServerRelativeUrl 
                            + "/"  
                            + fuMasterPage.FileName, 
                    fuMasterPage.FileBytes,                        
                    true);
  masterPageGallery.Update();
 }
 catch (Exception ex)
 {
    Throw ex;
 }
}


/// <summary>
/// Sets master page for the site.
/// </summary>
/// <param name="web">Website for which master page is to be set.</param>
private void SetMasterPage(SPWeb web)
{
 try
 {
  web.MasterUrl = string.Format("{0}/_catalogs/masterpage/{1}",  
                                 web.ServerRelativeUrl.TrimEnd('/'),          
                                 "MyMater.Master");
  web.Update();
 }
 catch (Exception ex)
 {
  throw new Exception("Unable to set master page for site "
                        + web.Title   
                        + ". Error: " +  
                     ex.Message);
 }
}

SharePoint 2010 THEMES - Retrieve, Upload and Apply programmatically



protected void Page_Load(object sender, EventArgs e)
{
 try
 {
  if (!(Page.IsPostBack))
  {
   SPSecurity.RunWithElevatedPrivileges(delegate()
   {
    using (SPSite pageLoadSite = new SPSite(SPContext.Current.Site.ID))
    {
     pageLoadSite.AllowUnsafeUpdates = true;

     using (SPWeb pageLoadWeb = pageLoadSite.OpenWeb())
     {
      pageLoadWeb.AllowUnsafeUpdates = true;

      GetThemes(pageLoadWeb);
      UploadThemeFileInThemeGallery(pageLoadWeb)
      SetTheme(pageLoadWeb);

      pageLoadWeb.AllowUnsafeUpdates = false;
     }
    pageLoadSite.AllowUnsafeUpdates = false;
    }
   });
  }
 }
 catch (Exception ex)
 {
  Throw ex;
 }
}


/// <summary>
/// Gets the list of themes from themes gallery.
/// </summary>
/// <param name="web"></param>
private void GetThemes(SPWeb web)
{
 try
 {
  SPWeb rootWeb = web;
  //Themes are available only at root-web level.
  if (!web.IsRootWeb)
    rootWeb = web.Site.RootWeb;

  SPDocumentLibrary themeGallery =  
        (SPDocumentLibrary)
                rootWeb.GetCatalog(SPListTemplateType.ThemeCatalog);

  if (themeGallery != null)
  {
   foreach (SPListItem themeItem in themeGallery.Items)
   {
     string themeName = themeItem.Name;
   }
  }
  else { // "No themes available for site " }

  //gets current applied theme Name
  string currentAppliedTheme = string.Empty;

  string themeurl = ThmxTheme.GetThemeUrlForWeb(web); //gets current 
                                                      // theme

  if (!string.IsNullOrEmpty(themeurl))
  {
   ThmxTheme theme = ThmxTheme.Open(web.Site, themeurl);
   currentAppliedTheme = theme.Name; //Gets the name of theme
  }
 }
 catch (Exception ex)
 {
  throw new Exception("Unable to get theme for site " + web.Title + ". Error: " + ex.Message);
 }
}


/// <summary>
/// Sets theme for the site.
/// </summary>
/// <param name="web">Website for which master page is to be set.</param>
private void SetTheme(SPWeb web)
{
 try
 {
  ThmxTheme theme = ThmxTheme.Open(web.Site, "_catalogs/theme/" + "MyTheme.thmx");
theme.ApplyTo(web, false);
web.Update();
 }
 catch (Exception ex)
 {
 throw new Exception("Unable to set theme for site " + web.Title + ". Error: " + ex.Message);
 }
}


/// <summary>
/// Uploads new theme file in theme gallery, overwrites, if already exists.
/// </summary>
/// <param name="web">Website for which master page is to be set.</param>
private void UploadThemeFileInThemeGallery(SPWeb web)
{
 try
 {
  //fuTheme is a fileupload control in my project
  SPDocumentLibrary themeGallery = (SPDocumentLibrary)web.GetCatalog(SPListTemplateType.ThemeCatalog);
  themeGallery.RootFolder.Files.Add(themeGallery.RootFolder.ServerRelativeUrl + "/" + fuTheme.FileName, fuTheme.FileBytes, true);
  themeGallery.Update();
 }
 catch (Exception ex)
 {
  throw new Exception("Unable to upload theme for site " + web.Title + ". Error: " + ex.Message);
 }
}






Friday, 24 February 2012

Create cutom web service in sharepoint 2007.


Have you ever wondered how to create a web service in SharePoint 2007 and consume it in all the web applications.
E.g., “http://<sitename>/Lists.asmx” that available in all web applications.

A total of 3 steps required in creating custom service.

Step 1: Creating Asp.Net Web Service application
Step 2: convert the .asmx file to .aspx pages using disco command.
Step 3: Make entry of .asmx and .aspx files that can be discoverable by MOSS 2007.

Step 1: Creating ASP.Net Web Service application
Open Visual studio 2008 -> create project -> ASP.NET Web Service Application -> Name the project and click on OK.


It opens a window as:

Uncomment [System.Web.Script.Services.ScriptService], if  AJAX concept.


Don’t remove/change the default “HelloWorld()” method, as we need to test the application.

Rename the default “servie1” class to some meaningful “projectName” class. So let’s do it.



Click on OK -> Apply.
Also rename the class name.

Now, the solution explorer changes to:


Add the references “Microsoft.Sharepoint.dll” by right-clicking on “Add References”.

Select “Windows@SharePoint@Services” or you can select “Microsoft.Sharepoint.dll” from the location C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll.
Add the “using” statements:
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Net;
Open the service markup as right-clicking on “projectName.asmx” file and selecting “View MarkUp”.

It will be visible as:

Delete the “CodeBehind” entry.
Rename the Class value as “Assembly description”.
Assembly description format: <Full path of class>, <Assembly name>, Version=<version info>, Culture=neutral, PublicKeyToken=<token Number>

Next step is to Sign the project.
Right-Click the project, select “properties”.


Select the “Signing” tab on left side, click on “sign the assembly” checkbox, select <New…> from dropdown, give ‘key File name’, typically the name of the project.
Click on OK.
Rebuild the project, so that it will generate the public key token number.

Steps to fetch Public key token:


Copy the token number.
Change the markup as:


Right-Click on project, select “View in browser”.


You will be able to see the service running:

The localhost, port no depends on the current system.

Note: If you face error “Could not load file or assembly 'Microsoft.SharePoint.Search, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies. An attempt was made to load a program with an incorrect format. “, Go to bin folder of the project, delete “Microsoft.Sharepoint.Search.dll” and “Microsoft.Sharepoint.Search.xml” file. And refresh the page directly.

 

Now, Copy the “.asmx” file into the “LAYOUTS” folder, typically found in “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE” location.



Drag and Drop the project assembly(ddl) file to GAC.
Do an iisreset. (Important to reflect the changes).
Open the service in web-browser from layouts folder.
Type as: http://<webapplicationName>/_layouts/<serviceName>.asmx


Clicking on Invoke, will be viewed as:



This service is working because we have copied the .asmx to _layouts folder.

Step 2: convert the .asmx file to .aspx pages using disco command
Open Visual studio command prompt:
All Programs-> Microsoft Visual Studio 2008 -> Visual Studio Tools -> Visual Studio 2008 Command Prompt.


Type: cd C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\LAYOUTS & Enter.

Type: disco http://<webapplicationName/_LAYOUTS/<serviceName>.asmx
Following is the output:

Now, a total of 3 files were created in LAYOUTS folder:
1.       ProjectName.disco
2.       ProjectName.WSDL
3.       results.discomap
We need to change modification in both the files with extension .disco & .WSDL
i.                    Open projectName.disco:
You will be viewing as:
<?xml version="1.0" encoding="utf-8"?>
<discovery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/disco/">
  <contractRef ref="http://v2starnew/_LAYOUTS/projectName.asmx?wsdl" docRef="http://v2starnew/_LAYOUTS/projectName.asmx" xmlns="http://schemas.xmlsoap.org/disco/scl/" />
  <soap address="http://v2starnew/_LAYOUTS/projectName.asmx" xmlns:q1="http://tempuri.org/" binding="q1:projectNameSoap" xmlns="http://schemas.xmlsoap.org/disco/soap/" />
  <soap address="http://v2starnew/_LAYOUTS/projectName.asmx" xmlns:q2="http://tempuri.org/" binding="q2:projectNameSoap12" xmlns="http://schemas.xmlsoap.org/disco/soap/" />
</discovery>

1.       Replace <?xml version="1.0" encoding="utf-8"?>
 As
<%@ Page Language="C#" Inherits="System.Web.UI.Page"    %> <%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Import Namespace="Microsoft.SharePoint.Utilities" %> <%@ Import Namespace="Microsoft.SharePoint" %>
<% Response.ContentType = "text/xml"; %>
As
<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request) + "?wsdl"),Response.Output); %>
As
<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %>

4.       Replace http://v2starnew/_LAYOUTS/projectName.asmx
As
<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %>
5.       Replace http://v2starnew/_LAYOUTS/projectName.asmx
As
<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %>
We have made changes to the file, instead of save, click on “Save As”, save the file name as “<Filename>disco.aspx”

Eg., projectNamedisco, where projectName is our class.

i.                   Open projectName.WSDL file:
1.       Replace <?xml version="1.0" encoding="utf-8"?> that appears at the first line
                As
<%@ Page Language="C#" Inherits="System.Web.UI.Page"    %> <%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Import Namespace="Microsoft.SharePoint.Utilities" %> <%@ Import Namespace="Microsoft.SharePoint" %>
<% Response.ContentType = "text/xml"; %>
2.       Replace   <soap:address location="http://v2starnew/_LAYOUTS/projectName.asmx" /> 
As
<soap:address location=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> />
3.       Replace  <soap12:address location="http://v2starnew/_LAYOUTS/projectName.asmx" />
As
<soap12:address location=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> />
We have made changes to the .wsdl file, instead of save, click on “Save As”, save the file name as “<Filename>wsdl.aspx”


Until now, we have converted .asmx files to .aspx pages.

Step 3: Make entry of .asmx and .aspx files that can be discoverable by MOSS 2007.
Copy the 3 files
1.       projectNamedisco.aspx
2.       projectNamewsdl.aspx
3.       projectName.asmx
To C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI location.


Open a file named spdisco.aspx


Open the file in visual studio 2008:
Make entries for <ContractRef and <DiscoveryRef.


Insert as
<contractRef  ref=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(spWeb.Url + "/_vti_bin/projectName.asmx?wsdl"), Response.Output); %> docRef=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(spWeb.Url + "/_vti_bin/projectName.asmx"), Response.Output); %> xmlns="http://schemas.xmlsoap.org/disco/scl/" />
  <discoveryRef ref=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(spWeb.Url + "/_vti_bin/projectName.asmx?disco"),Response.Output); %> xmlns="http://schemas.xmlsoap.org/disco/" />

Do an iisreset. Done!!!

Check by typing

Now you can create our own methods and consume them in applications.
After changes done to ASP.NET Server Application, update the dll by dropping in GAC and do an iisreset. Done!!!