Tuesday, 4 December 2012

Developer-tools


Every SharePoint developer has their go to list of tools and utilities for making life easier. This is my list. I’ll keep this updated with the latest version of SharePoint and as I find new tools.
Current version is targeting: SharePoint 2010 / Visual Studio 2010 / Windows 7

VISUAL STUDIO ADD-INS

SHAREPOINT DEVELOPMENT

WEB DEVELOPMENT

GENERAL

SHAREPOINT UPGRADE UTILITIES

Read More

SharePoint Create Page Layouts for Custom Content Types


Hi All,

If you want to create custom content types and page layouts from your custom content types then refer to the links below-

http://www.dotnetcurry.com/ShowArticle.aspx?ID=620
http://www.dotnetcurry.com/ShowArticle.aspx?ID=638

Thanks Sumit for this wonderful post.

Thanks.
Read More

Monday, 3 December 2012

Pass Web Part Property Value to User Control


Introduction:
In this article I will describe that how to pass web part properties into user control.
To do so I will take base of my below article where I explained that how to create user control, load it using webpart and deploy using feature.
http://sharepoint.infoyen.com/2012/04/11/create-and-deploy-user-control-in-sharepoint-using-feature/

Detail Steps:-
Once you read my article http://sharepoint.infoyen.com/2012/04/11/create-and-deploy-user-control-in-sharepoint-using-feature/ then you will understand that how to create, deploy user control using feature.
To pass webpart property into webpart follow below steps:-
1. Create web part property for example “EmpoyeeName” in webpart class “GenericUserControlPicker” , as mentioned below:-
private string employeeName = string.Empty;
 
[WebBrowsable(), Personalizable(),
WebDisplayName("Employee Name"),
WebDescription("Employee Name")]
public string EmployeeName
{
 get
 {
  return employeeName;
 }
 set
 {
  employeeName = value;
 }
}

2. Create regular c# .net property in user control as “EmpoyeeName” in user control class “HelloWorld”, as mentioned below:-
public string EmployeeName {get;set;}

3. Pass webpart property “EmployeName” value to user control as mentioned below code:
// this is line number 51 in "GenericUserControlPicker" class
userControl = (UserControl)LoadControl(UserControlPath);
// Check usercontrol is loaded or not.
// Also check if Employee Name has been entered or not
if(userControl!= null && !String.IsNullEmpty(EmployeeName))
{
 userControl.EmployeeName = EmployeeName;
}

4. Display webpart property “EmployeName” in user control, as mentioned below code:
protected void Page_Load(object sender, EventArgs e)
{
 lblTest.Text = EmployeeName;
}

Hope It Helps...
Thanks
Nikhil S.


Read More

Sharepoint Object Model User Profiles



Introduction
In this article I am going to explain you that How to use User Profiles and profile properties in Sharepoint Object model.
In SharePoint 2007, a userid is uniquely identified by his/her username. The username is Tied to the membershipprovider that the site is configured to authenticate against. A user can also have other information like phone number, email etc.
Even if business require then they can add custom property like Origin, Race etc.
Detail:-
First, your code must have references to the Microsoft.SharePoint, Microsoft.Office.Server, and System.Web Assemblies. With those references available, you can use the SPSite class and the UserProfileManager class as entry points into the user profile subsystem within MOSS.
As per my opinion; there are few below important points while using user profiles programmatically:
1. Retrieving User Profiles
2. Read Profile Property
3. Modify User Profile
4. Create a User Profile
5. Create a User Profile property
The Code:-
Main class I am going to explain in only 1st point. In rest other point I will only highlight code block which is related to respective point.
1. Retrieving User Profiles
We can get user profile object by using GetUserProfile method of UserProfileManager.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Administration;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.SharePoint;
using System.Web;
 
namespace UserProfilesConsoleApp
{
 class Program
 {
   static void Main(string[] args)
   {
     using ( SPSite site = new SPSite("site url"))
     {
 ServerContext context = ServerContext.GetContext(site);
 UserProfileManager profileManager = new UserProfileManager(context);
 // you can also get current user from web object.
        // syntex: SPWeb.CurrentUser
 UserProfile profile = profileManager.GetUserProfile(@"domainuser");
 Console.WriteLine("Profile {0}", profile.MultiloginAccounts[0]);
        // you got user profile object. now you can use any property of it.
        // like profile.ID, profile.PersonalSite.RootWeb.Titl e, profile.PersonalSite.Url etc..
 
     }
   }
 }
}


2. Read Profile Property
We can read property using UserProfileManager.Properties
foreach (Property prop in profileManager.Properties)
{
  Console.WriteLine("t{0} : {1}",
  prop.DisplayName, profile[prop.Name].Value);
}

3. Modify User Profile
profile["Origin"] = "India";
//Make sure that you call the Commit method 
//when you are finished making changes to the profile
profile.Commit();

4. Create a User Profile
UserProfileManager profileManager = new
UserProfileManager(context);
string acId = @"domainavinash";
if (!profileManager.UserExists(acId))
{
  UserProfile profile = profileManager.CreateUserProfile(acId);
  if (profile == null)
 Console.WriteLine("ould not create user profile, an error occurred.");
  else
 Console.WriteLine("User profile has been created.");
}
else
 Console.WriteLine("User profile for this account " + acId + " already exists.");

5. Create user Profile Property
PropertyCollection pc = profileManager.Properties;
Property p = pc.Create(false);
p.Name = "TestProperty";
p.DisplayName = "Test Property";
p.Type = "String";
p.Length = 50;
p.PrivacyPolicy = PrivacyPolicy.OptIn;
p.DefaultPrivacy = Privacy.Organization;
pc.Add(p);

Reference:-

Thanks
Nikhil S.

Read More

Add User To SharePoint Group Programmatically


Introduction:

Below I found this article will describe that how to add Share point user to share point group programmatically.
This will use below terms:-
1. AllowUnsafeUpdates: Before we update we will set AllowUnsafeUpdates to true.
2. SPGroup: We will create object sharepoint group in which we need to user.
3. AddUser: SPGroup.AddUser will add user into group.

The Code:-

This going to detail about a generic function in which you pass group name and user name, then function will add user into group. For deployment, WSP creation and feature basic; please read below articles:-
http://sharepoint.infoyen.com/2012/04/01/create-webpart-in-sharepoint step by step using WSP/
http://sharepoint.infoyen.com/2012/04/22/feature-receiver-in-sharepoint/
See below detailed code:-
// groupName will be string for e.g. "Site Owner"
// userLoginAccName will be "DomainName\UserName" for e.g. "Infoyen\\avinash"
public void AddUserToGroup(string groupName, string userLoginAccName)
{
 // you can also use SPContext to get SPWeb object
 Uri sitePath = new Uri("http://localhost/");
 
    using (SPSite site = new SPSite(sitePath.ToString()))
    {
        using (SPWeb web = site.OpenWeb())
        {
            try
            {
                web.AllowUnsafeUpdates = true;
                SPUser requiredUser = web.EnsureUser[userLoginAccName];
 
                if (requiredUser != null)
                {
                    SPGroup requiredGroup = web.Groups[groupName];
                    if (requiredGroup != null)
                    requiredGroup.AddUser(requiredUser);
                }
            }
            catch (Exception ex){//Handle exception
            }
            finally
            {
                web.AllowUnsafeUpdates = false;
            }
        }
    }
}


Thanks
Nikhil S.


Read More

AllowUnsafeUpdates VS RunWithElevatedPrivileges

AllowUnsafeUpdates: If your code modifies Windows SharePoint Services data in some way, you may need to allow unsafe updates on the Web site, without requiring a security validation. You can do by setting the AllowUnsafeUpdates property.
For detail click here AllowUnsafeUpdates

RunWithElevatedPrivileges : There are certain object model calls model that require site-administration privileges. To bypass access-denied error, we use RunWithElevatedPrivileges property when request is initiated by a nonprivileged user. We can successfully make calls into the object model by calling the RunWithElevatedPrivileges method provided by the SPSecurity class.
For detail click here RunWithElevatedPrivileges

Thanks!
Nikhil S.
Read More

RunWithElevatedPrivileges in SharePoint

In this article I am going to explain you that How to use RunWithElevatedPrivileges in sharepoint object model.
RunWithElevatedPrivileges
Executes the specified method with Full Control rights even if the user does not otherwise have Full Control.The next example shows the syntax that is required to define an anonymous method in the call to RunWithElevatedPrivileges.




SPSecurity.RunWithElevatedPrivileges(delegate()

{

    // implementation details omitted

});




Detail:-
The RunWithElevatedPrivileges method accepts a delegate parameter that adds a reference to a method that containsthe code that is to be executed with elevated privileges.
SPSite siteColl = SPContext.Current.Site;
SPWeb site = SPContext.Current.Web;
SPSecurity.RunWithElevatedPrivileges(delegate() {
  using (SPSite ElevatedsiteColl = new SPSite(siteColl.ID)) {
    using (SPWeb ElevatedSite = ElevatedsiteColl.OpenWeb(site.ID)) {
      string SiteCollectionOwner = ElevatedsiteColl.Owner.Name;
      string Visits = ElevatedsiteColl.Usage.Visits.ToString();
      string RootAuditEntries =
          ElevatedSite.RootFolder.Audit.GetEntries().Count.ToString();
    }
  }
});

Must read it:
In RunWithElevatedPrivileges you must then create an instance of the SPSite class and the SPWeb class. You cannot use the objects available through the Microsoft.SharePoint.SPContext.Current property. That is because those objects were created in the security context of the current user.

Thanks!
Nikhil S.


Read More

SPWeb.AllowUnsafeUpdates



SPWeb.AllowUnsafeUpdates : It Gets or sets a Boolean value that specifies whether to allow updates to the database as a result of a GET request or without requiring a security validation. Whenever your code modifies SharePoint data in some way or Whenever we need to update SharePoint objects like SPWeb, SPList, SPListItem, etc , without requiring a security validation, we need to set SPWeb.AllowUnsafeUpdates = true. 


Following is the code snippet for the same.



SPWeb web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;
 
// Perform the list/list item/web update 
web.allowUnsafeUpdates = false;

Detail:- The Microsoft idea behind introducing the AllowUnsafeUpdates property is to protect YOU from cross-site scripting attacks. The way this works is that if your application is running in an HTTPContext (i.e. it’s a web part for instance) and the request is a GET request then SharePoint will refuse to do any changes unless the value of AllowUnsafeUpdates is set to true and by default it will be false for GET requests. If you try to do any updates to lists, webs or any SharePoint objects that require an SPSite to be created first, and if you don’t set AllowUnsafeUpdates to true you will get this exception: 

System.Exception: Microsoft.SharePoint.SPException: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. —> 


System.Runtime.InteropServices.COMException (0x8102006D): The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. 


Usually when you create your own SPSite or SPWeb objects, i.e. when you are not getting them from the SPContext (such as SPContext.Web), and when you try to update anything such as web or list properties, list items metadata etc, you may get the exception listed above. This is a clear indication thatAllowUnsafeUpdates of the SPWeb is false and this is preventing you from doing the update. This problem is resolved easily by setting theAllowUnsafeUpdates of the parent web object to true. 


Few examples:- Scenario 1 (using SPWeb.EnsureUser):- 

EnsureUser looks for the specified user login inside SPWeb.SiteUsers collection, and if the login isn’t found, turns toActiveDirectory for the purpose of retrieving the user information from there. If such information is found, it will be added to SPWeb.SiteUsers and for the next time it will be returned directly fromSPWeb.SiteUsers. That means we are modifying SPWeb by adding user. Therefore we need to use AllowUnsafeUpdates property to avoid exception.


public static SPUser VerifyUser(SPWeb web, string loginName)
{
    SPUser myUser = null;
try
{
web.AllowUnsafeUpdates = true;
myUser = web.EnsureUser(loginName);
}
catch (Exception ex) {// write to log}
finally
{
web.AllowUnsafeUpdates = oldAllowUnsafeUpdate;
}
    return myUser;
}



Scenario 2 (using BreakRoleInheritance):- 
When we use Methods BreakInheritance, ResetRoleInheritance and BreakRoleInheritance, it reset AllowUnsafeUpdates to false. 

using (SPSite spSite = new SPSite("url"))
{
    using (SPWeb spWeb = spSite.OpenWeb())
    {
        bool oldAllowUnsafeUpdates = spWeb.AllowUnsafeUpdates;
        try
        {
SPList spList = spWeb.Lists["some list"];
SPListItem spLisItem = spList.GetItemById(someId);
// need to set since we are going to modify SPListItem
spWeb.AllowUnsafeUpdates = true; 
spLisItem.BreakRoleInheritance(false);
SPRoleDefinition reader = spWeb.RoleDefinitions.GetByType(SPRoleType.Reader);
SPGroup someGrp = spWeb.Groups["some group"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(someGrp);
roleAssignment.RoleDefinitionBindings.Add(reader);
// need to set since BreakRoleInheritance method reset AllowUnsafeUpdates to false
spWeb.AllowUnsafeUpdates = true;
spListItem.RoleAssignments.Add(roleAssignment);
        }
        catch (Exception ex)
        {
            // logging
        }
        spWeb.AllowUnsafeUpdates = oldAllowUnsafeUpdates;
spWeb.Update();
    }
}



Scenario 3 (using SPListItem.Update):-

using (SPSite spSite = new SPSite("url"))
{
    using (SPWeb web = spSite.OpenWeb())
    {
        try
        {
SPList list = web.Lists["SomeList"];
SPListItem item = list.GetItemById(12);
item["Title"] = "Some Changes";
web.AllowUnsafeUpdates = true;
item.Update();
web.AllowUnsafeUpdates = false;
        }
        catch (Exception ex)
        {
            // handle exception
        }
     }
}

References:- 





Thanks! Nikhil S.
Read More

Translate

Total Pageviews

Powered By Blogger · Designed By Seo Blogger Templates