Tuesday 25 December 2012

Convert Html control to string

eg: In server side, through coding, we have created a HTMLAnchor. Adding this to a Label's text requires in string format.
 
private static string GetControlsAsString(Control ulControl)
{
 string contents = null;
 using (System.IO.StringWriter swriter = new System.IO.StringWriter())
 {
 HtmlTextWriter writer = new HtmlTextWriter(swriter);
 ulControl.RenderControl(writer);
 contents = swriter.ToString();
 }
 return contents;
}

Gets thumbnail, full, large size url images from a sharepoint picture library


///Provides the url to a picture provided the picture library list item.
private static string GetPictureUrl(SPListItem listItem, ImageSize imageSize)
{
 StringBuilder url = new StringBuilder();

 // Build the url up until the final portion
 url.Append(SPEncode.UrlEncodeAsUrl(listItem.Web.Url));
 url.Append('/');
 url.Append(SPEncode.UrlEncodeAsUrl(listItem.ParentList.RootFolder.Url));
 url.Append('/');

 // Determine the final portion based on the requested image size
 string filename = listItem.File.Name;

  if (imageSize == ImageSize.Full)
 {
   url.Append(SPEncode.UrlEncodeAsUrl(filename));
 }
 else
 {
 string basefilename = Path.GetFileNameWithoutExtension(filename);
 string extension = Path.GetExtension(filename);
 string dir = (imageSize == ImageSize.Thumbnail) ? "_t/" : "_w/";  url.Append(dir);
 url.Append(SPEncode.UrlEncodeAsUrl(basefilename));
 url.Append(SPEncode.UrlEncodeAsUrl(extension).Replace('.', '_'));
 url.Append(".jpg");
 }
return url.ToString();
}

 // Enum
public enum ImageSize
{
 Thumbnail,
 Full,
 Large
}

Monday 24 December 2012

Configure Advance Search to limit to a scope

I have read many articles to configure Advance Search webpart, but i want to search those items from a particular list, document library, site etc.,
I have faced many hurdles in limiting to those scopes, so i want to post this as other developers or admins can easily refer this and implement on their own.




To provide the end user with advance search, 3 steps need to be followed.



Step 1: Create Scopes

Go to 'Central Administration' → Shares Service Provider(SSP) → 'Search Settings' under search → 'View Scopes' under 'Scopes'.

Click on 'New Scope'.






Provide Title, Description. Click on ok.

Next step is to create rules.

Click on newly created scope → New Rule → provide 'Scope Rule Type'.
Eg.,

1. If to limit to a sharepont list, type the url of the list:

2. If to limit to a Site:

Click on Ok!!



Step 2: Create Display groups

Type the following url:

It will be displaying the existing scopes and 'Display groups'.
Based on requirement, create a new display group or edit the existing one.




Click on 'New Display group', type the Title, Description, scopes to be included, and the default scope.
Click on Ok.


Step 3: Add Webpart

On any custom page, Add out-of-the-box webpart 'Advance Search Box' under 'Search' category.



Go to webpart properties:

I. Under 'Scopes' section, provide the 'Display group' name.


  1. Under 'Miscellaneous' section, provide the url to redirect the page on click of 'Search' button.


    Click on ok!!

    The provided url will be a custom .aspx page which has the Out-Of-the-box webpart 'Search Core Results'. No need to do any settings for this page.


    Done.

    References:

















Thursday 4 October 2012

Remove elements from a XML file



private static XDocument GetFilteredData(XDocument resultXML)
{
 //Remove elements of xpath item/title
 //that doesn't contains the title value as 'genome'
 resultXML.Descendants("item").Descendants("title").Where(x => !(x.Value.ToLower().Contains("genome"))).Select(tit => tit.Parent).Remove();

 return resultXML;
}


Merge XML files as one


private static XDocument MergeXMLDocs()
{
 XDocument resultXML = new XDocument();

 resultXML = XDocument.Load("RSSLink(XML data)");

 IEnumerable<XElement> newElements = XDocument.Load("New RSS Link(XML data)").Root.Elements();

 resultXML.Root.Add(newElements);

 return resultXML;
}

Add List Item in SharePoint



SPSecurity.RunWithElevatedPrivileges(delegate()
{
 using (SPSite site = new SPSite("http://mySite:4444/site1"))
 {
  using (SPWeb web = site.OpenWeb())
  {
   web.AllowUnsafeUpdates = true;

   SPList list = web.Lists.TryGetList("Tasks");

   if (list != null)
   {
    //Creates the structure
    SPListItem newListItem = list.Items.Add();

    //Check whether the column is in sharepoint list.
    if(newListItem.Fields.ContainsField("Title"))
     newListItem["Title"] = "Aditya";
    
    if (newListItem.Fields.ContainsField("Last Name"))
     newListItem["Last Name"] = "Reddy";

    if (newListItem.Fields.ContainsField("Employee ID"))
     newListItem["Employee ID"] = "34";

    //Updates the changes in content database
    newListItem.Update();
   }
  web.AllowUnsafeUpdates = false;
  }
 }
});


Thursday 27 September 2012

Convert Excel sheet to DataTable

 /// <summary>
/// Gets the DataTable
/// </summary>
/// <param name="excelExtension">file extension. either xls or xlsx</param>
/// <param name="excelFilePath">Excel file path</param>
/// <param name="sheetName">Name of the sheet</param>
/// <returns>DataTable</returns>
private static DataTable GetExcelDataTable(string excelExtension, string excelFilePath, string sheetName)
{
DataTable dt = new DataTable();
try
{
string query = String.Format("select * from [{0}$]", sheetName);

string connectionString = string.Empty;

if (excelExtension.ToLower().Trim() == "xls")
connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 8.0""", excelFilePath);

if (excelExtension.ToLower().Trim() == "xlsx")
connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml""", excelFilePath);

using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, connectionString))
{
dataAdapter.Fill(dt);
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return dt;
}


If you get the following error :

The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.

Install 'AccessDatabaseEngine.exe for 32-bit or '_x64' for 64-bit OS from
http://www.microsoft.com/en-us/download/details.aspx?id=13255

Thursday 12 July 2012

Convert DataTable to XML and XML to DataTable.

/// <summary>
/// Gets the xml as string.
/// </summary>
/// <param name="dt">DataTable that need to be converted to xml.</param>
/// <returns>XML as string with schema.</returns>
private static string GetXML(DataTable dt)
{
 if (string.IsNullOrEmpty(dt.TableName))
 {
  dt.TableName = "My DataTable";
  }

 StringWriter writer = new StringWriter();
 dt.WriteXml(writer, XmlWriteMode.WriteSchema, true);
 return writer.ToString();
}



/// <summary>
/// Gets the DataTable from XML.
/// </summary>
/// <param name="xmlData">XML as string.</param>
/// <returns>DataTable with the schema.</returns>
private static DataTable GetDataTable(string xmlData)
{
 DataTable dt = new DataTable("My Data");
 try
 {
  StringReader stringReader = new StringReader(xmlData);
  dt.ReadXml(stringReader);
 }
 catch (Exception ex)
 {
 throw new Exception(ex.Message);
 }
return dt;
}



Monday 4 June 2012

Change 'System Account' to logged in 'User Name'.


Sometimes in SharePoint 2010, we come across a situation where, instead of showing the user name of logged in, the site is displayed as 'System Account'.

Here are the steps to change it:

Step 1:
Open 'SharePoint 2010 Central Administration'.
Goto 'Security' → 'Configure service accounts'.









Step2:
Select the 'web application' from 1st dropdown list, where you want to change the display name.
Change 'managed account' from 2nd dropdown list.




It will ask to do IISReset, click on OK.

Now goto the 'web application', see the reflected changes.






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);
 }
}