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;
                    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 Sharepoint -II

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

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;
return "Web part not found";
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);
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="//"></script>
<script type="text/javascript">
  var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
    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;
function onError(error) {

If you want Site Name, Here is the code:

<script src="//"></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.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());

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.

Thursday 27 November 2014

Get Site Template GUID using Powershell

Sometimes we need to find the GUID of save site template.

Open Power shell management shell in administrator mode.
 here is the power shell script that provide you the functionality. pate it.

 $url = "http://localhost:mysite/"

$site= new-Object Microsoft.SharePoint.SPSite($url )

$loc= [System.Int32]::Parse(1033)

$templates= $site.GetWebTemplates($loc)

foreach ($child in $templates){ write-host $child.Name "  " $child.Title}

click Enter. And you will get the list of site template with the GUID.

Friday 21 November 2014

How to delete the unused application pool From IIS?

Recently I had issue with user profile service. I delete it and try to recreate it. That time I got an error
An object of the type Microsoft.SharePoint.Administration.SPIisWebServiceApplicationPool named "User Profile Service App Pool" already exists under the parent Microsoft.SharePoint.Administration.SPIisWebServiceSettings named "SharePoint Web Services".  Rename your object or delete the existing object.

So I search for the resolution of the issue. I got two options
1. They say Try a  different name. - Which didn't help in my case.I would say try your luck also.
2. Delete current app pool and try again to create.

So here is the process:

IIS will not provide the interface for managing service application's application pools. But we can delete service application's application pool in SharePoint 2010/2013  using powershell.

Use these below cmd-let to get list of service application's application pools.

SharePoint 2010/2013 delete orphaned application pool: To delete a application pool of service application, use the cmdlet:

 1. Run "Sharepoint Management Shell " in administrator mode.
 2. Type "Get-SPServiceApplicationPool". It will give you list of app pool.
 3. Type "Remove-SPServiceApplicationPool". 
 4. It will ask you identity. Give the app pool name you want to remove from above list. Try not to make  spell mistake.
 5. Click Enter.
 6.It will ask for confirmation. Type "y". click Enter.

Thursday 20 November 2014

Linq query to datatable conversion

Recently I have encounter with Linq after a long time and I was required to convert linq result in to datatable. It take a while but I found the method i used in past. I hope it will help you too.

 1. use AsEnumerable() in your query.and you will be good to get a function CopyToDataTable() to get datatable.
var query =
    from order in orders.AsEnumerable()
    join detail in details.AsEnumerable()
    on order.Field<int>("SalesOrderID") equals
    where order.Field<bool>("OnlineOrderFlag") == true
    && order.Field<DateTime>("OrderDate").Month == 8
    select new
        SalesOrderID =
        SalesOrderDetailID =
        OrderDate =
        ProductID =

DataTable orderTable = query.CopyToDataTable(); 
Original Source :

2. use this coustom method to get datatable

public DataTable ToDataTable(System.Data.Linq.DataContext ctx, object query)
     if (query == null)
          throw new ArgumentNullException("query");
     IDbCommand cmd = ctx.GetCommand(query as IQueryable);
     SqlDataAdapter adapter = new SqlDataAdapter();
     adapter.SelectCommand = (SqlCommand)cmd;
     DataTable dt = new DataTable("sd");

          adapter.FillSchema(dt, SchemaType.Source);
     return dt;

For getting datatable

var vr = from country in objDataContext.CountryMaster
                        select new {country.CID,country.CName};

DataTable dt = ToDataTable(objDataContext,vr);

Original source :

Monday 17 November 2014

On-screen Keyboard in Windows

Sometimes soon we will have a touchscreen desktops in our work premises. If you want a on screen keyboard here are some shortcuts

Click the Start menu, point to All Programs, point to Accessories, point to Accessibility, and then click On-Screen Keyboard to open On-Screen Keyboard.
(link -

 2. My way start -> run -> type "osk". click ok. you can create shortcut on desktop writing osk in shotcut. and click on it.


Monday 6 October 2014

Free Operating Systems

Worried about licence OS?

Feel free of licence Microsoft OS and use this Linux based operating systems.
I have some free os name and their sites where you can download it.

No 5 PC-BSD9 : HTTP://
No 4 ArchBang Linux : HTTP://
No 3 Zorin OS 5 : HTTP://
No 2 CrunchBang : HTTP://
No 1 Puppy Linux : HTTP://
No 0 startos: HTTP://


Tuesday 30 September 2014

Play any video in HTML in IE.

"Play any kind of video ".
I was working on IE-8. Here is the code I use to integrate video in my page.

<link href="//" rel="stylesheet"></link>
<script src="//"></script>
<script src="//"></script>
<div class="flowplayer">
      <source src="" type="video/mp4"></source>

Friday 12 September 2014

Error occurred in deployment step 'Retract Solution': The language-neutral solution package was not found.

I was working on one project when i got this error while deployment and i have Google it. I found some solution which are as below

  1. Close Visual Studio Solution and completely exit out of it, then run it again and compile. This sometimes fixes the issue. 
  2. Right-Click on your Visual Studio Solution, select "Clean" Solution, then Right Click on SharePoint Project and choose "Retract". Rebuild and Deploy. 
  3. In PowerShell running as Administrator run Uninstall-SPSolution: 
  4. Unistall-SPSolution -identity {Name of WSP File} -allwebapplications
  5. In PowerShell running as Administrator run Remove-SPSolution:                                   Remove-SPSolution -identity {Name of WSP File} -force
  6. In PowerShell running as Administrator run the Delete() command:                                     (Get-SPSolution {Name of WSP File}).Delete() 

But In My problem I do not Find WSP to uninstall. so what to do in such condition:
Just Follow this step:
  1. Open Your solution and Publish the Project. This will create wsp in Bin folder of your project.
  2. Open cmd in Administrator mode and enter this path;  cd C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN\
  3. Then type following command to add wsp : stsadm -o addsolution -filename <path of .wsp file>.
  4. Then type following command to add wsp : stsadm -o deploysolution -name <name of .wsp file> -url  <site url>  - immediate -allowgacdeployment -force.

this work for me. when i deploy again it run as smoothly as it could.  

Thursday 11 September 2014

javascript keypress event

Sometimes we need to handle enter key event on textbox. For that we can use fiollowing code

    $('#myInput').keypress(function(event) {
        if (event.keyCode == 13) {
            alert('Entered'); // write your code here

myInput : textbox/ input control id
event.keyCode : The e key value you needed.
Here are some key values:
Key Code
backspace 8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
Key Code
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
Key Code
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222

Thursday 28 August 2014

Simple Encryption Decryption in

I was doing a log in mechanism on project where i required Encryption and Decryption code
Here is the simplest method i found:

private string Encryptdata(string password)
string strmsg = string.Empty;
byte[] encode = new byte[password.Length];
encode = Encoding.UTF8.GetBytes(password);
strmsg = Convert.ToBase64String(encode);
return strmsg;

private string Decryptdata(string encryptpwd)
string decryptpwd = string.Empty;
UTF8Encoding encodepwd = new UTF8Encoding();
Decoder Decode = encodepwd.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(encryptpwd);
int charCount = Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
decryptpwd = new String(decoded_char);
return decryptpwd;

Original Source :

Wednesday 27 August 2014

Binding / concatenating a string literal with eval

Recently i have a requirement where i have to bind an anchor tag with two parameters in repeater. I have search for few time and then one of my friend suggest  me the following solution

<a href='<%#string.Concat(siteURL,Convert.ToString(DataBinder.Eval(Container.DataItem,"TargetURL"))) %>'
 <%# Container.ItemIndex==0?"class=\"fc\"":string.Empty %>><%#DataBinder.Eval(Container.DataItem,"Title") %>

Thursday 10 April 2014

Calculated Column DateTime to date Convert

I was recently working with Calculated Column and i face a horrible nightmare type issue. I just need to copy date-time column value to a date type column. But it takes at least 3 to 4 hours of mine. Then I found this. I forget to get link but I get this much info which i want to share with you.

 =IF(TEXT(([End Time]-[Start Time])-TRUNC(([End Time]-[Start Time]),0),"0.000000000")="0.999305556",[Start Time]+1,[Start Time])
Basically, the formula checks whether the event is an all day event and if so increases the value by whatever you need. It determines whether the event is all day by checking the difference between the end time and smart time (12:00am to 11:59pm).
Here's the formula as I used it:
=IF(TEXT(([End Time]-[Start Time])-TRUNC(([End Time]-[Start Time]),0),"0.000000000")="0.999305556",[Start Time]+1,[Start Time])
So, get the difference between end time and start time, then subtract the truncated value of the same value (get rid of the value to the left of the decimal which would indicate that the all day event spans multiple days). If the difference is .999305556 then I'm adding 1 day to the value of start time (since I'm only interested in showing the date, not the time), otherwise leave the date/time as is.
Hope that helps someone else with calculated date columns.

Wednesday 9 April 2014

Hide/Show Result window

I have this question from long time in my mind. Whenever i run query in SQL result window acquire half the space.look at the figure.

 I generally decrease the size of the result window and continue to work on.  Now I get the solution. Just Press Ctrl + R and it hide. press it again and it shows up. I hope this shortcut will be useful to you too.

Crop In Paint

Generally I used to editing image in paint . So i just wanna saw how a functionality named crop make my work easy.

Long way

1. open image and select the part

2. Copy or cut the part


3. open new file


4. paste


5. save


shortcut using crop

1. open image and select the part


2. click the crop


3. save

 That's simple one but very useful when doing documentation for your project.

How to remove Security warning when using https.

Recently I was working on a project which uses the HTTPS for URL.I face a unique problem in that some of my pages contents are not fully loaded in the browser like model popup.


So I took some steps to avoid this problem.

1. go to internet options.


2. open security tab and click on custom tab.


3. slide down till option "Display Mixed content".


4. change it to "Enable" and save the changes.


5. refresh the page.

Note: I prefer to work with IE. This solution figures are from IE11.

Tuesday 8 April 2014

SQL StoreProcedure Change Report Generate

To Create SQL Procedure Change Report

 1. Select your Database Store procedure folder Your database -> Programmability -> Store Procedure 2.In ribbon , View-> Object Explorer Details or press F7 (as Shown in figure) 

That's it. You will See the Report. To check when modification has done Select the Date Last Modified column as shown in fig.

Sunday 16 March 2014

SharePoint Introduction

What Is SharePoint? 

Microsoft SharePoint is a Web application platform developed by Microsoft to provide intranet portals, document & file management, collaboration, social networks, extranets, websites, enterprise search, and business intelligence. It also has system integration, process integration, and workflow automation capabilities.

Means Its a Platform To develop SharePoint Based websites. All the other things are functionalists (such as document & file management, workflow etc.) or type (like enterprise search) of those websites. 

So how would we start? Lets start by installing SharePoint. Here is some links where you can download free or trial version for installation.

Microsoft SharePoint Server 2010 Trial version for 180 days- 560.5 MB