Monday, July 21, 2014

Create Publishing page using Client Object Model

   // Get Publishing Page Layouts

 List publishingLayouts = context.Site.RootWeb.Lists.GetByTitle("Master Page Gallery");
ListItemCollection allItems = publishingLayouts.GetItems(CamlQuery.CreateAllItemsQuery());

context.Load(allItems, items => items.Include(item => item.DisplayName).Where(obj => obj.DisplayName ==  "BlankwepartPage"));
 context.ExecuteQuery();

 ListItem layout = allItems.Where(x => x.DisplayName == "BlankwepartPage").FirstOrDefault();
                        context.Load(layout);

                        // Create a publishing page

                        PublishingPageInformation publishingPageInfo = new PublishingPageInformation();
                        publishingPageInfo.Name = "Newpage.aspx";
                        publishingPageInfo.PageLayoutListItem = layout;



                        PublishingPage publishingPage = web.AddPublishingPage(publishingPageInfo);
                        publishingPage.ListItem.File.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                        publishingPage.ListItem.File.Publish(string.Empty);
                   
                        context.Load(publishingPage);
                        context.Load(publishingPage.ListItem.File, obj => obj.ServerRelativeUrl);
                        context.ExecuteQuery();
                     
                        Console.WriteLine("Newpage.aspx  Created and check-in completed");

Adding Content Editor Webpart on Publishing Page using Client Object Model

 using (ClientContext context = new SP.ClientContext(new Uri("http://contoso.com/")))
                {

                    Web webSite = context.Web;
                    context.Load(webSite);
                    SP.File page = webSite.GetFileByServerRelativeUrl("/sites/publishingsite/page.aspx");
                    page.CheckOut();
                    Console.WriteLine(pagename + "Page has been checked out for adding webpart");
                    var limitedWebPartManager = page.GetLimitedWebPartManager(SP.WebParts.PersonalizationScope.Shared);
                    SP.WebParts.LimitedWebPartManager manager = page.GetLimitedWebPartManager(Microsoft.SharePoint.Client.WebParts.PersonalizationScope.Shared);

                    string xmlWebpart = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                        "<WebPart xmlns=\"http://schemas.microsoft.com/WebPart/v2\">" +
                                        "<Assembly>Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>" +
                                        "<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>" +
                                        "<Title>Sample Webpart</Title>" +
                                        "<Description>$Resources:core,ContentEditorWebPartDescription;</Description>" +
                                        "<ContentLink xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\" />" +
                                        "<Content xmlns=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">" +
                                        "<![CDATA[webpart content here]]></Content>" +
                                        "<PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge>" +
                                        "</WebPart>";

                    Microsoft.SharePoint.Client.WebParts.WebPartDefinition oWebPartDefinition = manager.ImportWebPart(xmlWebpart);
                    SP.WebParts.WebPart webpartCE = oWebPartDefinition.WebPart;

                    context.Load(manager.AddWebPart(webpartCE, WebpartZone, Convert.ToInt16(WebpartZoneIndex)));
                    context.ExecuteQuery();

                    page.CheckIn("checking in", CheckinType.MajorCheckIn);
                    page.Publish(string.Empty);
                    context.Load(page);
                    context.ExecuteQuery();
                    Console.WriteLine(pagename + "Added webpart Check-in completed");
                    Console.WriteLine("Webpart has been added");

Wednesday, December 25, 2013

JQuery hints

Set a field value: $('input[title=Email]').attr({value:'test email'});

Hide a row: $('h3:contains("Title")').closest('tr').hide();

Change event on choice field: $('select[title=Display]').change(function(){alert($('select[title=Display]').val())});

Condition: if($('select[title=Display]').val()=="Yes") {alert($('input[title=Email]').val());}

Tuesday, August 13, 2013

Add Custom Attachment Control & Disable Attachment button on Ribbon

<!-- Add Attachment File control -->

<table width="100%">
<tbody><tr>
<td width="190" class="ms-formlabel" valign="top" style="font-family: verdana; color: #525252; font-size: 1em; font-weight: normal">Add Attachments: </td>
<td class="ms-formbody" id="attachmentsOnClient" valign="bottom">
<span dir="ltr">
<input name="fileupload0" title="Name  " class="ms-fileinput" id="onetidIOFile" type="file" style="width: 386px"/> </span>
</td></tr>
<tr><td>&#160;</td>
<td class="ms-attachUploadButtons">
<input id="attachOKbutton" onclick="OkAttach()" type="button" value="OK  " style="width: 5.8em; height: 1.8em"/> <span id="idSpace"></span></td>

</tr></tbody></table>
 

<!-- Hide File Attachment Button on Ribbon-->

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script><script type="text/javascript">
$("span.ms-cui-ctl-largelabel:contains('Attach')").parent("a").hide();

$("span.ms-cui-groupTitle:contains('Actions')").hide();
 </script><!-- Hide File Attachment Button -->

Use in list forms & Enjoy :) 

Saturday, July 20, 2013

Save Site as template using Object Model

public void savesiteastemplate(string webname)
{
 string templatename;
string templatetitle;
string templatedesc;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite _site = new SPSite(SPContext.Current.Site.ID))
{
_site.AllowUnsafeUpdates =true;
using (SPWeb oweb = _site.RootWeb)
{
SPWebCollection _webcol = _site.AllWebs;
oweb.AllowUnsafeUpdates = true;
foreach (SPWeb _web in _webcol)
{
if (string.IsNullOrEmpty(txtwebname.Text))
{
msg = "Enter the name of a web";
}
else if (_web.Name.ToLower() == txtwebname.Text.ToLower())
{
templatetitle = _web.Name + "Template";
templatename = _web.Name + "Template";
_web.SaveAsTemplate(templatename, templatetitle, templatedesc,false);
msg = "Template Saved Successfully";
txtwebname.Text = "";
break;
}
else
{
msg = "web is not available";
}
}
oweb.AllowUnsafeUpdates= false;
PnlMain.Controls.Add(new LiteralControl(msg));
_site.AllowUnsafeUpdates =false;
}
}
});
}
catch (Exception ex )
{
lblmsg.Text = ex.Message;
}
}


Where
strTemplateName
Type: System.String
The name to use for the template on the Create form and also for the file name of the solution package (.wsp) that contains the template. If a solution package with the same file name already exists, a numeric suffix is added to the name when the solution file name is formed. For example, if you pass "Test", the method tries to create a template file named "Test.wsp". If that name is taken, it tries "Test2.wsp". If that name is in use, it tries "Test3.wsp" and so on.
strTemplateTitle
Type: System.String
A string that contains the display name of the site template.
strTemplateDescription
Type: System.String
A string that contains the description of the site template.
fSaveData
Type: System.Boolean
true if data on the website is saved as part of the site template; otherwise, false.

Thursday, April 11, 2013

Difference Between SharePoint Application Pages Vs Site Pages


Difference Between SharePoint Application Pages Vs Site Pages

Application Pages:
  • Application pages are stored in the server’s file system. 
  • SharePoint Designer tool cannot be used with application pages. 
  • Application pages cannot be used within sandboxed solutions. 
  • An Application page cannot be customized and modified by end user, instead a developer is required. 
  • These are the normal .aspx pages deployed within SharePoint. Most common of them are the admin pages found in _layouts folder.
  • These are deployed either at the farm level or at application level. If they are deployed within _layouts folder or global SharePoint Virtual Directory, then they can be used by any SharePoint application (available at farm level), otherwise they can be deployed at application level only by creating a virtual directory.
  • These are typical ASP.Net aspx pages and can utilize all of the functionalities available within ASP.Net including code-behind, code-beside, inline coding etc.
  • These are compiled by .Net runtime like normal pages.
  • If you deploy your custom ASPX pages within _layouts folder or within SharePoint application using a virtual directory, you will not be able to use SharePoint master pages and have to deploy your master page within the virtual directory or _layouts folder.
  • Application Pages cannot use contents as this concept is associated with SharePoint Page Layouts not with ASP.Net.
  • Since application pages are compiled once, they are much faster
  • Normally application pages are not web part pages, hence can only contain server controls or user controls and cannot be personalized by users.
  • Easiest way to deploy your existing ASP.Net web site within SharePoint is to deploy its pages as Application Pages within SharePoint. In this way you can convert any ASP.Net web solution as SharePoint application with minimal efforts.
  • SharePoint specific features like Information Management Policies, Workflows, auditing, security roles can only be defined against site pages not against application pages.
  • Application pages can be globalized using Resource files only. 
Site Pages:
  • Site Pages is a concept where complete or partial page is stored within content database and then actual page is parsed at runtime and delivered to end-users.
  • Site pages can be edited by using SharePoint Designer tool.
  • Site pages are used within Sandboxed solutions. 
  • A site page can be customized and modified by end user. 
  • Pages stored in Pages libraries or document libraries or at root level within SharePoint (Wiki pages) are Site Pages
  • You must be thinking why we should use such pages? There are many reasons for this. One of the biggest catch of the SharePoint is the page layouts, where you can modify page once for a specific content type and then you can create multiple pages using the same page layout with different contents. In this case, contents are stored within database for better manageability of data with all the advantages of a data driven system like searching, indexing, compression, etc and page layouts are stored on file system and final page is created by merging both of them and then the outcome is pared by SharePoint not compiled.
  • Site Pages can contain web parts as well as contents placeholders, and all of them are stored per page-instance level within database and then retrieved at run time, parsed and rendered.
  • Another advantage is they are at user-level not at web-application or farm level and can be customized per site level.
  • Since their definition is retrieved from database, they can utilize master pages stored within SharePoint masterpages library and merged with them at run time for rendering.
  • They are slower as compared to Application pages as they are parsed everytime they are accessed.
  • SharePoint specific features like Information Management Policies, Workflows, auditing, security roles can only be defined against site pages not against application pages.
  • Since they are rendered not compiled hence it is not easy to add any inline code, code behind or code beside. Best way of adding code to these pages is through web-parts, server controls in master pages, user controls stored in "Control Templates" folder or through smart parts. If you want to add any inline code to master page, first you need to add following configuration within web.config:<PageParserPaths>
            <PageParserPath VirtualPath="/_catalogs/masterpage/*" CompilationMode="Always" AllowServerSideScript="true" IncludeSubFolders="true" />
    </PageParserPaths>
  • To add code behind to SharePoint master pages or page layouts.
  • Since Site pages are content pages, hence all SharePoint specific features like Information Management Policies, Workflows, auditing, security roles can only be defined against site pages.
  • Variations can only be applied against Site pages for creating multilingual sites.
  • "SPVirtualPathProvider" is the virtual path provider responsible for handling all site pages requests. 

How to launch a document by clicking a link to the file?

Word: <a href='ms-word:ofe|u|path/to/web/word/document.docx'>Link to document</a> Excel: <a href='ms-excel:o...