Wednesday, 31 December 2014

Add Custom Webppart to MySite Sharepoint -I

Recently I have requirement to modify the About Me page in My Site.I have create a site feature and in its event receiver added some code. Here is the solution if you have same requirement :


If you want to add Content Editor web part :

string Username = SPContext.Current.Web.CurrentUser.Name;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPWeb web = siteCollection.OpenWeb())
                    {
                        if (web.WebTemplate == "SPSMSITEHOST")
                        {
                            //About Me Webpart
                            ContentEditorWebPart contentEditor = new ContentEditorWebPart();

                            XmlDocument xmlDoc = new XmlDocument();
                            XmlElement xmlElement = xmlDoc.CreateElement("HtmlContent");
                            xmlElement.InnerText = "<strong>About " + Username + "</strong>";
                            contentEditor.Content = xmlElement;
                            contentEditor.ChromeType = PartChromeType.None;
                            using (SPLimitedWebPartManager manager =
                              web.GetLimitedWebPartManager("Person.aspx", PersonalizationScope.Shared))
                            {
                                manager.AddWebPart(contentEditor, "TopZone", 2);
                            }                          
                        }
                    }
                });

If you want to add custom web part to page:
Add-custom-webppart-to-mysite

Add Custom Webppart to MySite Sharepoint -II

If you want to modify MySite with custom web part, here is the solution.


SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb web = siteCollection.OpenWeb())
{
if (web.WebTemplate == "SPSMSITEHOST")
{
//User Info Webpart
AddWebPartToPage(web, "Person.aspx", "UserInformation", "TopZone", 1);                          
}
}
});

Support Methods:

/// <summary>
/// Method to Get the custom web part
/// </summary>
/// <param name="web">web Url</param>
/// <param name="pageUrl">Page Name</param>
/// <param name="webPartName">Webpart name</param>
/// <param name="zoneID">Zone where you want to deploy webpart</param>
/// <param name="zoneIndex">Zone index</param>
/// <returns></returns>
public static string AddWebPartToPage(SPWeb web, string pageUrl, string webPartName, string zoneID, int zoneIndex)
{
using (SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared))
{
IList<System.Web.UI.WebControls.WebParts.WebPart> _listFormWebParts = (from _wp in manager.WebParts.Cast<System.Web.UI.WebControls.WebParts.WebPart>()
  where string.Compare(_wp.Title, webPartName, true) == 0
  select _wp).ToList();

//Check if there are any web parts found
if (_listFormWebParts == null || _listFormWebParts.Count == 0)
{
using (System.Web.UI.WebControls.WebParts.WebPart webPart = CreateWebPart(web, webPartName, manager))
{
if (webPart != null)
{
manager.AddWebPart(webPart, zoneID, zoneIndex);
return webPart.ID;
}
else
return "Web part not found";
}
}
else
return "exists";
}
}

/// <summary>
/// Create webpart from webpart template
/// </summary>
/// <param name="web">Web Url</param>
/// <param name="webPartName">webpart template name</param>
/// <param name="manager">SPLimitedWebPartManager object</param>
/// <returns></returns>
public static System.Web.UI.WebControls.WebParts.WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager manager)
{
SPQuery query = new SPQuery();
//query.Query = String.Format(CultureInfo.CurrentCulture, "&lt;Where&gt;&lt;Eq&gt;&lt;FieldRef Name='FileLeafRef'/&gt;&lt;Value Type='File'&gt;{0}&lt;/Value&gt;&lt;/Eq&gt;&lt;/Where&gt;", webPartName);

query.Query = String.Concat("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + webPartName + "</Value></Eq></Where>");
SPList webPartGallery = null;
if (null == web.ParentWeb)
{
webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);
}
else
{
webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
}          

SPListItemCollection webParts = webPartGallery.GetItems(query);
if (webParts == null)
{
return null;
}
XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
string errorMessage;
System.Web.UI.WebControls.WebParts.WebPart webPart = manager.ImportWebPart(xmlReader, out errorMessage);
webPart.ChromeType = PartChromeType.None;
return webPart;
}

Tuesday, 30 December 2014

Error : "Thread was being aborted" - Resolution

sometimes when we try to create sub site using site template or we might have some code that takes longer time to debug, it will time out and the error will show that "Thread was being aborted".

In my case I follow following steps and get rid from it.

1.    In a basic text editor such as Notepad, open the web.config file
2.    Press CTRL + F to open the Find dialog box.
3.    Find the following tag:
 <httpRuntime maxRequestLength="51200" />
4.    Replace it with this tag:
 <httpRuntime executionTimeout="6000" maxRequestLength="51200" />


Original Post: thread-was-being-aborted-error.

Get UserInformation/ Site Information Using client side script

Recently I have to display client info on a page. I have two options, either with webpart (server side control) or  use script editor webpart (client object modal).

Here is the script i use:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
  var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
    url : requestUri,
    contentType : "application/json;odata=verbose",
    headers : requestHeaders,
    success : onSuccess,
    error : onError
});

function onSuccess(data, request){
    var Logg = data.d;    
document.getElementById('welcomediv').innerHTML="Hello, "+Logg.Title;
document.getElementsByTagName('title')[0].innerHTML='Home';  
}
function onError(error) {
    alert("error");
}
</script>


If you want Site Name, Here is the code:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () { SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getWebProperties); $('.userprofilpic').hide();});
    function getWebProperties() {
        var ctx = new SP.ClientContext.get_current();
        this.web = ctx.get_web();
       ctx.load(this.web,'Title');
        ctx.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
            Function.createDelegate(this, this.onFail));
    }
    function onSuccess(sender, args) {
document.getElementById('welcomediv').innerHTML="Site Name: "+this.web.get_title();    
    }
    function onFail(sender, args) {
        alert('failed to get list. Error:'+args.get_message());
    }
</script>

That's it for now.

Wednesday, 3 December 2014

"Sign in as Different User" in SharePoint 2013

One of features used in testing of permissions in SharePoint is "Sign in as Different User" which allows you to log in as an another user.  With SharePoint 2013 this option is missing.

To get this feature back follow the following steps :

1. Locate and then open the following file in a text editor:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\TEMPLATE\CONTROLTEMPLATES\Welcome.ascx

2.Add the following element before the existing "ID_RequestAccess" element:

<SharePoint:MenuItemTemplate runat="server" ID="ID_LoginAsDifferentUser" Text="<%$Resources:wss,personalactions_loginasdifferentuser%>" Description="<%$Resources:wss,personalactions_loginasdifferentuserdescription%>" MenuGroupId="100" Sequence="100" UseShortId="true" />

3.Save the file.