Search This Blog

Sunday, November 15, 2015

Dependency feature 'PPSSiteCollectionMaster' for feature 'PPSSiteMaster' is not activated at this scope.

I was trying to create a new sub site under my site collection while working with Sharepoint 2013 and I got the below error message.

Dependency feature 'PPSSiteCollectionMaster' (id: a1cb5b7f-e5e9-421b-915f-bf519b0760ef) for feature
'PPSSiteMaster' (id:0b07a7f4-8bb8-4ec0-a31b-115732b9584d) is not activated at this scope.
[Cannot provision site: http://servername/sites/site1]

Solution:
1. Go Site Actions -> Site Settings ->Site Collection Administration ->Site collection features ->       PerformancePoint Services Site Collection Features  -> Activate

2. Go Site Actions -> Site Settings ->Site Actions ->Manage site features -> PerformancePoint Services Site Features -> Activate

Powershell to list all SharePoint Site Collections in a web application

Get-SPSite  -Limit All

Powershell to list Content Database details for SharePoint Site Collection

Get-SPContentDatabase -Site 'http://sharepointwebapplicationurl'

Id                           : Content DB ID
Name                     : WSS_Content_DBName
WebApplication    : SPWebApplication Name= XXX
Server                    : XXX
CurrentSiteCount  : 2

Powershell to list all SharePoint Site Collections and subsites a web application


Get-SPSite 'http://sharepointwebapplicationurl' | Get-SPWeb -Limit All

Backup and Restore SharePoint Site using Shell Command


Backup SharePoint Site Shell Command:
Backup-SPSite http://sitename -Path E:\Backup\site_name.bak

Description:
The Backup-SPSite cmdlet performs a backup of the site
collection when the Identity parameter is used. By default, the site collection
will be set to read-only for the duration of the backup to reduce the potential
for user activity during the backup operation to corrupt the backup.

Restore a SharePoint site Shell Command:
Restore-SPSite http://sitename -Path "E:\Backup\file.bak" -Force

Restore a SharePoint site to a specific database Shell Command:
Restore-SPSite http://sitename -Path "E:\Backup\file.bak" -Force -DatabaseName "Database"

Description:
The Restore-SPSite cmdlet performs a restoration of the
site collection to a location specified by the Identity parameter. A content
database may only contain one copy of a site collection. If a site collection
is backed up and restored to a different URL location within the same Web
application, an additional content database must be available to hold the
restored copy of the site collection.

List of all SharePoint custom solutions and deployed web applications in the farm


$File = "D:\SolutionandDeployedWebApplications.txt"
foreach ($solution in Get-SPsolution)
{
echo $solution.Name | Out-File $File -Append
echo $solution.DeployedWebApplications |Format-Table -Property Url | Out-File $File -Append
}


Saturday, November 14, 2015

How to find the Version, Culture and PublicKeyToken of an Assembly (DLL) using PowerShell


([system.reflection.assembly]::loadfile("c:\temp\test.dll")).FullName

The output of this PowerShell statement will provide the Version, Culture and PublicKeyToken as shown below.
Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=630d986a50055aa6


Install to global assembly cache without gacutil

In Windows Server 2012 you can't install a DLL to the GAC by drag/drop, but you can do it using GACUTIL.exe.
GacUtil.exe is not present on the server by default.
You can do it using the following script instead of Gacutil.exe

In Windows 2012 you can use the following PowerShell to install dll to GAC

Set-location "c:\temp"
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("c:\temp\test.dll")
iisreset

In Windows 2012 you can use the following PowerShell to remove dll from GAC:

Set-location "c:\temp"
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacRemove("c:\temp\test.dll")
iisreset


Thursday, November 5, 2015

Inside Update panel calendar picker controls are not working

When we are using update panel we may face some issues. In that one of the major issue is using calendar picker control inside update panel. 
To over come this issue we have to include the following script tag.

<script type="text/javascript" src="/_layouts/datepicker.js"></script>

Now we can use calendar picker inside update panel without any issues.

thanks,

Inside Update panel people editor is not working

When we are using update panel we may face some issues. In that one of the major issue is using people editor control inside update panel. Update panel does not allow post back. So people editor will not resolve the users.
To over come this issue we have to include the following script tag.

<script type="text/javascript" src="/_layouts/15/entityeditor.js"></script>

Now we can use people editor inside update panel without any issues.

thanks,

Wednesday, October 14, 2015

How to acces sharepoint 2013 user profile using C#

UserProfile profile;
SPServiceContext serviceContext = SPServiceContext.GetContext(SPContext.Current.Site);
string fromMail = string.Empty;

public void getEmailID()
{
    try
    {
        UserProfileManager upm = new UserProfileManager(serviceContext);
        profile = upm.GetUserProfile(currentUser.LoginName);
        if (profile != null)
         {
             if (!string.IsNullOrEmpty(Convert.ToString(profile[PropertyConstants.WorkEmail].Value)))
              {
                    fromMail = profile[PropertyConstants.WorkEmail].Value.ToString();            
              }
         }
    }
    catch (Exception ex)
    {
       throw;    
    }
 }

Using this UserProfileManger we can access all the details stored for a sharepoint user in User Profile Service Application.

thanks,

Tuesday, September 1, 2015

Get Values From Query String Using jQuery

 $(document).ready(function () {
            try {              
                var mode = GetParameterValues('Mode');
                alert(mode);
            } catch (e) {
                alert(e);
            }
        });

function GetParameterValues(param) {
            var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < url.length; i++) {
                var urlparam = url[i].split('=');
                if (urlparam[0] == param) {
                    return urlparam[1];
                }
            }
        }

Friday, August 7, 2015

The feature failed to activate because a list at 'PublishingImages' already exists in this site. Delete or rename the list and try activating the feature again.


The most common issue we may face when we try to activate SharePoint Publishing infrastructure Feature from Manage site features.

Try to activate that feature using Shell command. It will work out with out error:

 Enable-SPFeature -Identity PublishingWeb -URL http://test:1000/ -Force

thank you,

Monday, August 3, 2015

Adding User Permissions using Power shell script in SharePoint 2013


In SharePoint we are having permission level operations. To that SharePoint group we can add users through Site Settings -> Site Permissions.

And also we can give permissions using PowerShell scripts.

For Single User:

new-spuser -UserAlias "User1" -Web "http://test:100/sites/home1" -Group "TestUsers"

For Every One:

new-spuser -UserAlias "Everyone" -Web "http://test:100/sites/home1" -Group "TestUsers"

By executing this PowerShell script we can add users to the SharePoint groups.


thank you,

Friday, July 17, 2015

Change the "SharePoint" text in the top left corner


$webApp = Get-SPWebApplication http://tozit-sp:2015
$webApp.SuiteBarBrandingElementHtml = "New Text Here"
$webApp.Update()

Thursday, July 16, 2015

How to enable and disable Quick launch in SharePoint 2013


To display the Quick Launch menu using the SharePoint 2010 web interface, follow these steps:
  1. Navigate to Site Actions, Site Settings, Tree View (under Look and Feel).
  2. Select the Enable Quick Launch check box and click OK

This will enable and disable the quick launch.

View all Webparts on your SharePoint Page

All you need to do is add this string to the end of your URL "?contents=1" on any of your SharePoint Pages

How to Enable session in your web application

Change settings in your web.config file

change enable session as true

<pages enableSessionState="true">

add the following code with in the  <modules> tag

<add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition="" />

Thats it.. Now you can store values in session.

This content database has a schema version which is not supported in this farm

we usually face this issue when we try to mount content db.

It is because of the database version conflict.

Just go to your local database and open Versions table and check the version of your database.

now open the database which you are trying to mount and open the Versions table and change its version as per your database version.

now try to mount your database again.

Mount Content DB:

Mount-SPContentDatabase -Name WSS_Content_DB_ToAttach 
-WebApplicationhttp://mywebapplication:port

Dismount Content DB:

Dismount-SPContentDatabase -Identity WSS_Content_DB_ToAttach

Remove Content DB:

Remove-SPContentDatabase -Identity WSS_Content_DB_ToAttach




Thursday, July 9, 2015

link button property to open in new tab?

 By Adding following onClientClick even in your link button we can open the url in new tab.

OnClientClick="aspnetForm.target ='_blank';"

so on click it will call Javascript function an will open respective link in News tab.

<asp:LinkButton id="lbnkVidTtile1" OnClientClick="aspnetForm.target ='_blank';" runat="Server" Text="New Tab"  />

and another option is you can go for Hyper link control to achieve this. By default it has the Target property and you can set that to _blank.

thank you,

Monday, June 29, 2015

How to hide a Yes/No column in NewForm.aspx and EditForm.aspx in sharepoint 2013

We can't hide the Yes/No field using OOB in sharepoint. Better we go for script editor to hide the particular column. Apply the following steps.

Add in the Content Editor Web Part located under the Media and Content category.

Paste the following code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
    $('nobr:contains("TestColumn")').closest('tr').hide(); 
});

</script>

you can use this for multiple columns also.


thank you.



Wednesday, June 24, 2015

Two different timer job shows the same name in job definition

This usually happens when you add two or more timer jobs in single solution. This one tested me a lot. This issue usually comes when we go for two features for two timer jobs.
Guess what here is the place we do mistake usually.

When we copy paste the code for feature receiver from one feature to another one we just copy and paste it where we don't much care about any changes in that code. because it is already working fine. Of course its working fine but still it needs a little change.

Feature 1:
      Feature Activated:
       TestJob1 listLoggerJob = new TestJob1 (List_JOB_NAME, site.WebApplication);

Feature 2:
    Feature Activated:
      TestJob2 listLoggerJob = new TestJob2 (List_JOB_NAME, site.WebApplication);

So guys please don't forget to change the class name where you create your timer job. Don't just copy and paste, just review it at-least once. It took me some time to find this silly mistake.


thank you


Get Row ID of inserted data in SharePoint list

SPList spList = spWeb.Lists["Announcements"];
SPListItem spListItem = spList.Items.Add();
spListItem["Title"] = "Hello world";

spListItem.Update();
int RowID = spListItem.ID;  //This is the ID of the new item.

Tuesday, June 23, 2015

How to enable custom errors in Share point error

In share point while getting error we may see the correlation ID. But that is not really understandable i guess.
But we do have an option to enable custom error message which is understandable by anyone.

Here are the steps to enable that settings:

1. 15/Layouts folder we have a web.config file. In that file find Custom Errors and change its mode          as Off
    Ex: customErrors mode="Off"

2. Open your webapplication's web.config file.
     a) Find CallStack and change it's value as true
          Ex: CallStack="true"
     b) Find find Custom Errors and change its mode as Off
          Ex: customErrors mode="Off"
     c) Find debug and change its mode as true
          Ex: debug="true"

Once you finished these steps, hereafter you will get clean error message and you can solve it in your way..


thank you

Saturday, June 20, 2015

page.response.redirect is not working

In sharepoint some times we cant use the Response.Redirect.

So we can use SPUtility.Redirect to redirect to other pages.

SPUtility.Redirect("/SitePages/CustomAccessDenied.aspx", SPRedirectFlags.Static / SPRedirectFlags.Default / SPRedirectFlags.Trusted, HttpContext.Current);

Like this we can redirect to other pages in sharepoint

Friday, June 19, 2015

How to add Custom validation for Newform.aspx and Editform.aspx in Sharepoint 2013

I am using PreSaveAction() JavaScript function to check whether start day is lower than End day or not. If it is lower than greater than end day then it will show an alert message;

Add in the Content Editor Web Part located under the Media and Content category.

Paste the following code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
 var j = jQuery.noConflict(); 
 function PreSaveAction() { 
 var startDay= j(":input[title='Start_Day']").val(); 
var endDay= j(":input[title='End_Day']").val(); 
if(startDay=='')
{
alert("Please enter start day");
return false;
}
else if(endDay=='')
{
alert("Please enter end day");
return false;
}
else if(endDay < startDay)
{       
   alert("End day should be greater than start day");          
   return false;
}
else{
   return true;
    }
}

</script>

thank you..

How to Disable Quick Edit in SharePoint 2013 Lists


By default SharePoint 2013 lists allow you to quickly edit items by clicking "edit" from the view without opening it.

Now, if you want to disable this function follow these steps:
  1. Go to the list settings> Advanced settings page
  2. Scroll down and Under quick edit options just choose "No" and then click OK.
     3. Now you can see that quick edit is disabled from the list.

Saturday, May 30, 2015

Get the checkbox value is checked or not using Jquery

 $(document).ready(function () {
    $('#<%=chkValidateBabyName.ClientID%>').change(function () {
          if ($(this).is(":checked")) {
            alert("Check box checked");
          }
          else{
           alert("Check box un checked");
         }
    });
});

Include this code in document ready function. then you will get checkbox value when the check box value is changed..

Friday, May 29, 2015

Select Values from sql table with auto generated Serial number


select ROW_NUMBER() OVER (order by Modified_On desc) as SerialNumber, Name from StudentDetails

Monday, May 25, 2015

How to create a static variable at client side

Actually we cant create a static variable at client side. But we can keep the value even after page postback using Hidden field control.

First we need to create a hidden control and need to set ClientIDMode as "Static"

Ex: <asp:HiddenField ID="hndControl" ClientIDMode="Static" runat="server" />

After that we need to assign the value to that hidden field.

document.getElementById('<%= hndControl.ClientID %>').value = "Static";

Here after we can use that value until we change hidden field value.



Sunday, May 24, 2015

How to avoid alphabets and special character from text box using javascript

Use the following code OnKeyPress Event in your text box:

<asp:TextBox ID="txtNumber" runat="server" OnKeyPress="return IsNumeric(event);"></asp:TextBox>


function IsNumeric(e) {
    var keyCode = e.which ? e.which : e.keyCode
    var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
    document.getElementById("error").style.display = ret ? "none" : "inline";
    //TestOnTextChange();
    return ret;
}

Disable Copy, Cut and Paste options in text box

Include the following options in your text box:

onpaste="return false"
oncut="return false"
oncopy="return false"

it will avoid the cut, copy and paste options from your text box

Friday, May 22, 2015

DataTable does not contain definition for AsEnumerable


The method you want is in the System.Data namespace, so that using directive is fine, but you also need a reference to the System.Data.DataSetExtensions assembly.

Thursday, May 21, 2015

Timer Job Issues


This is the most common error in timer job.

Keep your scope as site

  public override void FeatureActivated(SPFeatureReceiverProperties properties)
  {
            SPSite site = properties.Feature.Parent as SPSite;
}

get the site as mentioned above.

If still you get the same error please check your code whether you are using any custom dll.
Because timer job sometimes will not accept custom dll files. so try to avoid those.



Wednesday, May 20, 2015

Timer Job with Sharepoint

Timer Job:

Timer Job is a background process that are run by SharePoint. It is a periodically executed task inside SharePoint Server. It provides us a task execution environment.

Default Timer Jobs inside SharePoint:

There are many timer jobs inside SharePoint which do internal tasks like:
    • Send emails
    • Validate sites
    • Delete unused sites
    • Health analysis
    • Product versioning
    • Diagnostics
These tasks will having execution periods like:
    • Minute
    • Hour
    • Day
    • Week
    • Month
Components of Connectable web parts : 
  1. Derive CustomTimerJob Class from SPJobDefinition
  2. Add the three Constructors of the derived class : When ever we create the object of CustomTimerJob  class, corresponding constructor will execute.
  3. Override the Execute method: When ever the timer job start running then the code inside the Execute method will run.
  4. We need to create a Feature and Feature Receiver so on activation of this feature we are going the add our timer job to SharePoint farm.

Sunday, May 10, 2015

Update managed meta data values into SPList

using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    TaxonomySession taxonomySession = new TaxonomySession(site);
                    TermStore termStore = taxonomySession.TermStores["Test_ManagedMetaData"];
                    Group group = termStore.Groups["College"];
                    TermSet termSet = group.TermSets["Karur"];
                    Term term = termSet.Terms["CCET"];
                    SPList list = web.Lists.TryGetList("TimerJobList");
                    if (list != null)
                    {
                        TaxonomyField taxonomyField = list.Fields["College"] as TaxonomyField;
                        TaxonomyFieldValue taxonomyFieldValue = new TaxonomyFieldValue(taxonomyField);
                        taxonomyFieldValue.TermGuid = term.Id.ToString();
                        taxonomyFieldValue.Label = term.Name;
                        SPListItem item = list.Items.Add();
                        item["Title"] = "Sample";
                        item["College"] = taxonomyFieldValue;
                        item.Update();
                        //list.Update();
                    }
                }
            }

Friday, April 17, 2015

How to check a value is SPGroup or SPUser

SPList olist = oweb.Lists.TryGetList("Test_List");
if (olist != null)
{
SPListItemCollection ocoll = olist.Items;
foreach(SPItem oitem in ocoll)
{
SPFieldUserValueCollection GetAllGroup = new SPFieldUserValueCollection(oweb, Convert.ToString(oitem["SPGroups"]));

for (int i = 0; i < GetAllGroup.Count; i++)
{
SPFieldUserValue singlevalue = GetAllGroup[i];
if (singlevalue.User == null)   // If it is GROUP condition is true
{
SPGroup group = oweb.Groups[singlevalue.LookupValue];
foreach (SPUser user in group.Users)
{
if (ouser.Name == user.Name)
{
isuserval = true;
break;
}
}
}
else
{
if (ouser.Name == singlevalue.User.Name) // Checks User is Current Login User
{
isuserval = true;
break;
}
}
}
}
}


Impersonation in Sharepoint

Although not recommended, there may be times when you need your code to perform certain functions that the current user does not have the necessary permissions to perform.

The SPSecurity class provides a method (RunWithElevatedPrivileges) that allows you to run a subset of code in the context of an account with higher privileges than the current user.
The premise is that you wrap the RunWithElevatedPrivileges method around your code.
And also In certain circumstances, such as when working with Web forms, you may also need to set the AllowSafeUpdates method to true to temporarily turn off security validation within your code.
If you use this technique, it is imperative that you set the AllowSafeUpdates method back to false to avoid any potential security risks.

Get values from People picker control

if (pplUser.Entities.Count > 0)
            {
                PickerEntity pe = (PickerEntity)pplUser.Entities[0];
                Username = pe.Key;
                ouser = SPContext.Current.Web.EnsureUser(Username);
                UserID = ouser.ID;
            }


Want A Proper Programming Style? Here Are Rules You Need To Follow

  1. Utmost readability of code

For a code to be readable and understandable, it needs to be formatted in a consistent manner. Plus, it should also use meaningful names for all the functions and variables with concise and accurate comments. It is important for you to make a clear note of all the tricky sections included within the code. You must be clear on the reasons as to why the software program will work and why it should work smoothly under all conceivable scenarios.

  1. Following the right naming conventions is mandatory

When to come to naming the classes, functions and variables, you need to follow the below mentioned guidelines:
  • Make sure to capitalize the first letter of a particular class name 
  • Use capitalization for separating multi-word names
  • Capitalize the names of constants and use underscores for separating the words
  • Make sure the first letter of a particular function or variable name is in lowercase.
  • Pay attention to the correct use of abbreviations. For example, use max instead of maximum.

  1. Use of white spaces is necessary

Although white spaces are meaningless for compilers, you can use them for improving the code readability. For instance, you can opt for leaving three blank lines between the functions. Also, you can use individual blank lines within the functions for separating the critical code sections.

  1. Proper maintainability of code must be ensured

You need to write the code in a manner that it is quite straightforward for a different programmer to make moderations to its functionality or fix bugs. Make sure to keep the functions general with all the key values being marked as constants that can be changed in the desired manner. All in all, the code must be robust and capable of handling any kind of input, followed by delivering the expected result without crashing.

  1. Easy-to-understand comments must be included within the code

Comments should be meaningful and clearly explain everything about the software program. While the volume of comments doesn’t matter, quality does. You must use /* comments*/ style for writing the comments, ensuring that they are included towards the top of every source file. Additionally, you can also opt for including your name, the date on which code was written and a brief description of the actual purpose of using the program. You must ensure that the block comments precede a majority of functions along with a good description of the function’s purpose. However, you may also opt for omitting the block comments for some obvious functions. The format that needs to be followed for writing inline comments is //comments.


  1. Proper usage of function is necessary

Each and every function included within the code snippet must be short and capable of accomplishing a specific task. You need to consider functions as “black boxes” which are independent and can handle almost any type of input efficiently. Never forget the rule of thumb i.e. “Ten Line Rule” which means that a function which is typically longer than ten lines can do a lot more and needs to be simplified in the most refined way. Not to forget, any repeated segments of the code must be drafted into a separate function. Doing this will shorten the length of program and improve its readability by great bounds and leaps.

  1. Code needs to be indented well

Indentation plays a vital role in marking the control flow within a software program. Every new while, for, if or switch structure will introduce a block which has been indented in the best manner. This is feasible also in case the brackets have been omitted for the one line statements. For instance, in case of if statements, the corresponding else statements must be lined up.

Wrapping Up

Writing software programs can turn to be a fun activity if you’re well familiar with the accurate programming style. Hope the above post would have enabled you to get acquainted with the rules that can allow you to adhere to a fabulous programming style.

Clear values from People picker control

pplUser.Entities.Clear();

Friday, April 3, 2015

Sharepoint


How to change the row index by clicking image up and down

You can get the row ID from OnRowCommand.

 protected void gridview_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            DataTable dt = new DataTable();
            dt = Getdetails();                  ///Get existing details from gridview
            int index = Convert.ToInt32(e.CommandArgument);     ///Get row ID
            string Command = Convert.ToString(e.CommandName); ///Get Commandname
            DataRow selectedRow = dt.Rows[index];                        ///Get the selected Row
            DataRow newRow = dt.NewRow();                                 ///Create a new row
            newRow.ItemArray = selectedRow.ItemArray;   ///Insert selected row into new row
            dt.Rows.Remove(selectedRow);                                      ///Remove selected row
            if (Command == "Up")
            {
                dt.Rows.InsertAt(newRow, index - 1);                    
            }
            else if (Command == "Down")
            {
                dt.Rows.InsertAt(newRow, index + 1);
            }
            gridview.DataSource = dt;
            gridview.DataBind();                             ///Set details into grid again
            ViewState["WFtable"] = dt;
            Setdetails(dt);                
        }


I hope this will help you guys.

thanks.

Degrade your IE browser

Some of your contents may not support in IE browser higher versions.
So we can degrade to down versions by following:

In your master page you can see a tag like:
<head runat="server">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
</head>

In content you can change the version of your browser:
<meta http-equiv="X-UA-Compatible" content="IE=9" />

Get sharepoint SPList ID

Navigate to the SharePoint list using the browser.
Select the Settings + List Settings menu command.
Copy the Url from the browser address bar into Notepad. It will look something like:
http://moss2007/ProjectX/_layouts/listedit.aspx?List=%7B26534EF9%2DAB3A%2D46E0%2DAE56%2DEFF168BE562F%7D

Delete everying before and including “List=”.
Change “%7B” to “{”
Change all “%2D” to “-“
Chnage “%7D” to “}”
You are now left with the Id:

{26534EF9-AB3A-46E0-AE56-EFF168BE562F}

Simple Ways to become a best programmer...

1. Never ever duplicate code

Avoid duplicating code at all costs. If you have a common code segment used in a few different places, refactor it out into its own function. Code duplication causes confusion among your colleagues reading your code, it causes bugs down the line when the duplicated segment is fixed in one location and not the others and it bloats the size of your code-base and executable. With modern languages its become possible to get really good at this, for example here is a pattern that used to be hard to solve before delegates and lambdas came along:

/// <summary>
/// Some function with partially duplicated code
/// </summary>
void OriginalA()
{
DoThingsA();

// unique code

DoThingsB();
}

/// <summary>
/// Another function with partially duplicated code
/// </summary>
void OriginalB()
{
DoThingsA();

// unique code

DoThingsB();
}
But now we can refactor the shared part of both functions and rewrite using a delegate:

/// <summary>
/// Encapsulate shared functionality
/// </summary>
/// <param name="action">User defined action</param>
void UniqueWrapper(Action action)
{
DoThingsA();

action();

DoThingsB();
}

/// <summary>
/// New implmentation of A
/// </summary>
void NewA()
{
UniqueWrapper(() =>
{
// unique code
});
}

/// <summary>
/// New implementation of B
/// </summary>
void NewB()
{
UniqueWrapper(() =>
{
// unique code
});
}

2. Notice when you start distracting yourself

When you find yourself flicking to facebook or twitter instead of working on a problem its often a sign that you need to take a short break. Go grab a coffee away from your desk and talk to your colleagues for 5 minutes or so. Even though this seems counter intuitive, you will be more productive in the long run.

3. Don’t rush the solution out the door

When under pressure to produce a solution to a problem, or to fix a bug, its very easy to get carried away and find yourself rushing, or even missing out your usual crucial testing cycle completely. This can often result in more problems and will make you look less professional in the eyes of your boss and colleagues.

4. Test your finished code

You know what your code is supposed to do, and you’ve likely tested that it works, but you really need to prove it. Analyse all the potential edge cases and make a test which confirms that your code performs as expected under all possible conditions. If there are parameters, send values outside of the expected range. Send null values. If you can, show your code to a colleague and ask them to break it. Unit testing is a formalised approach to this.

5. Code review

Before you promote your code into source control, sit down with a colleague and explain exactly what your change does. Often just by doing this you’ll recognise mistakes in your own code without your colleague saying a word. It’s much, much more effective than just reviewing your own work.

6. Write less code

If you find yourself writing a lot of code to do something simple, you’re probably doing it wrong. A good example is the lowly boolean:

if (numMines > 0)
{
   enabled=true;
}
else
{
   enabled=false;
}
When you could just write:

enabled = numMines > 0;
The less code you write the better. Less to debug, less to refactor, less to go wrong. Use with moderation; readability is just as important, you don’t want to make your code less readable by doing this.

7. Strive for elegant code

Elegant code is highly readable and solves the problem at hand with the smallest amount of code and machine action possible. Its quite difficult to achieve elegant code in all circumstances but after programming for a while you start to get a feel for what it looks like. Elegant code cannot be improved by refactoring anything. It makes you happy to look at it. You are proud of it. For example here is what I consider to be an elegant way of computing the area of a convex polygon:

static public double GetConvexPolygonArea(Vector2[] vertices)
{
double area = 0;
for (int i = 0; i < vertices.Length; i++)
{
Vector2 P0 = vertices[i];
Vector2 P1 = vertices[(i + 1) % vertices.Length];

area += P0.Wedge(P1);
}

return area / 2;
}

8. Write self documenting code

Comments are a very important part of programming for obvious reasons, but self documenting code can be even better because it makes it possible to understand code just by reading it. Function and variable names can often be deftly chosen so that when put together with the language semantics the code becomes readable even to non programmers. For example:

void DamagePlayer(Player player, int damageAmount)
{
if (!player.m_IsInvincible && !player.m_IsDead)
{
player.InflictDamage( damageAmount );
}
}
Self documenting code is not a substitute for comments. Use comments to describe ‘why’, self documenting code describes ‘what’.

9. Don’t use magic numbers

Numbers just inserted into the code are bad practice because there is nothing to describe what they represent. This is compounded by duplication; where the same number is used in multiple different places in the code. One will get changed and the others missed leading to bugs. Always use a named constant to describe the value you want to represent, even if it is only used in one place.

10. Don’t do manual labour

Humans are very good at making mistakes when doing a series of actions. If you have a build deployment process which is more than one step long, you’re doing it wrong. Automate as much as possible, reduce the chance of human error. This is especially important with tasks which you perform a lot.

11. Avoid premature optimisation

When you start optimising part of your already functioning code you risk breaking the functionality. Optimisation should only be performed in response to performance analysis, hopefully carried out towards the end of a project. Optimising before this analysis stage wastes time and can introduce bugs.

Monday, January 5, 2015

UpdatePanel control

The UpdatePanel control is probably the most important control in the ASP.NET AJAX package. It will AJAX'ify controls contained within it, allowing partial rendering of the area. We already used it in the Hello world example, and in this chapter, we will go in depth with more aspects of the control.

The <asp:UpdatePanel> tag has two childtags - the ContentTemplate and the Triggers tags. The ContentTemplate tag is required, since it holds the content of the panel. The content can be anything that you would normally put on your page, from literal text to web controls. The Triggers tag allows you to define certain triggers which will make the panel update it's content. The following example will show the use of both childtags.

1. AsyncPostBackTrigger

it is the one which enforces Asynchonous post back of the Page.., i.e. the AJAX way. The data will be transacted without full post back. When you are using functionalities like login, you may use this.

Ex. You are having two dropDowns Viz., Countries and States. the states should be loaded when a country is selected and it should be changed on Countries change.

You may use AsyncPostBackTrigger in this scinario., which will populate the states ddl without full post back.

2. PostBackTrigger

It is the one which does not follow the AJAX functioalities., but the full post back as usually(as Without using UpdatePanel). Situtions are there where you would not like to enforce Partial Post back (as explained in Point 1. above). Like you are having FileUpload Control withing the UpdatePanel and when you do it by AsyncPostBack, you will not get any values to the server. It requires Full PostBack. in such a case you should use this trigger.

thank you.

Have you ever wonder which country is the best to live for IT engineers?

Below a list of 10 best countries to live for software engineers.

10. Canada
I. Median annual pay for software engineer – $57500

II. Position in the world ranking of “Happiness Index – experienced well-being” - 2

III. Position in the ranking of  “Best for workers: Countries” – 11

9. New Zealand
I.Median annual pay for software engineer – $59600

II.Position in the world ranking of “Happiness Index” - 17

III.Position in the ranking of  “Best for workers: Countries” – 8

8. Sweden
I. Median annual pay for software engineer – $61400

II. Position in the world ranking of “Happiness Index” - 5

III. Position in the ranking of  “Best for workers: Countries” – 8

7. Germany
I. Median annual pay for software engineer – $63800

II. Position in the world ranking of “Happiness Index” - 27

III. Position in the ranking of  “Best for workers: Countries” – 20

6. Australia
I. Median annual pay for software engineer – $65900

II. Position in the world ranking of “Happiness Index” - 8

III. Position in the ranking of  “Best for workers: Countries” – 14

5. Israel
I. Median annual pay for software engineer – $70700

II. Position in the world ranking of “Happiness Index” - 10

III. Position in the ranking of  “Best for workers: Countries” – 10

4. Denmark
I. Median annual pay for software engineer – $71500

II. Position in the world ranking of “Happiness Index” - 1

III. Position in the ranking of  “Best for workers: Countries” – 4

3. United States
I. Median annual pay for software engineer – $76000

II. Position in the world ranking of “Happiness Index” - 16

III. Position in the ranking of  “Best for workers: Countries” – 7

2. Norway
I. Median annual pay for software engineer – $81400

II. Position in the world ranking of “Happiness Index” - 3

III.Position in the ranking of  “Best for workers: Countries” – 6

1. Switzerland
I. Median annual pay for software engineer – $104200

II. Position in the world ranking of “Happiness Index” - 6

III.Position in the ranking of  “Best for workers: Countries” – 24

For more: Click here

Friday, January 2, 2015

error: $Resources:core,ImportErrorMessage

Today i have faced an exception while importing webpart into a wiki page.

error: $Resources:core,ImportErrorMessage

we can overcome this issue.

Solution : Visual Studio -> Build -> Select 'Retract' -> Clean solution -> Build and deploy.

If it doesn't  solve this please check your connection string name is correct or not. it may cause the issue.


thank you.



Restricting Custom People Picker to only one Sharepoint group programatically

Refer the following script files in your page,     <!-- For People Picker -->     <script type="text/javascript" src...