Showing posts with label sp Programming. Show all posts
Showing posts with label sp Programming. Show all posts

Tuesday, May 4, 2010

Identify Restrict a Group User

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using Microsoft.Office.Server;

namespace RestrictGroup
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (IsUserAuthorized("Viewers"))
            {
                Response.Write("true");
            }
            else
            {
                Response.Write("False");
            }
        }
      


        public bool IsUserAuthorized(string groupName) //find user & check whether it belong to specific group
        {
           
            SPSite site = SPContext.Current.Site;

           
            using (SPWeb web = site.OpenWeb())
            {
              
                SPUser currentUser = web.CurrentUser;

             
                SPGroupCollection userGroups = currentUser.Groups;

               
                foreach (SPGroup group in userGroups)
                {
                                   
                    if (group.Name.Equals(groupName))  //Traverse all the group & check mentioned group
                        return true;
                }
            }
            return false;
        }
    }
}

Read more...

Friday, April 30, 2010

Manage Group permission programmatically

Hi All, I'm writing this post after long time.... but try to update blog frequently.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;

namespace GroupManagerDept
{
public partial class GManagerAdd : System.Web.UI.UserControl
{
PeopleEditor pe;
protected void Page_Load(object sender, EventArgs e)
{
btnADD.Click += new EventHandler(btnADD_Click);
btnClose.Click += new EventHandler(btnClose_Click);


if (!Page.IsPostBack)
{
GroupList();


}




pe = new PeopleEditor();


Panel panPeopleEditor = new Panel();
panPeopleEditor.Style.Add("padding", "1px");

panPeopleEditor.Style.Add("background-color", "#A9D0F5");


panPeopleEditor.Controls.Add(pe);

AddPeople1.Controls.Add(panPeopleEditor);
}
private string GetEmpDept(string LoginID)
{

string EmpID = "", EmployeeDept = "";
string[] UserLoginID;
if (LoginID.Contains("\\"))
{
UserLoginID = LoginID.Split('\\');
EmpID = UserLoginID[1];
}
else if (LoginID.Contains(":"))
{
UserLoginID = LoginID.Split(':');
EmpID = UserLoginID[1];
}

UserProfileManager profileManager = GetAllUserProfile();
foreach (Microsoft.Office.Server.UserProfiles.UserProfile userProfile in profileManager)
{

if (EmpID.ToLower().Equals(Convert.ToString(userProfile[PropertyConstants.UserName].Value).ToLower()))
{
EmployeeDept = Convert.ToString(userProfile[PropertyConstants.Department].Value).ToUpper();
if (EmployeeDept == "")
{
EmployeeDept = "NoDept";
}

}
if (EmployeeDept != "")
break;
}
return EmployeeDept;
}
private void addGroup(string GroupName)
{
ddGroup.Items.Add(new ListItem(GroupName));
}

private void addUserToGroup(string userLoginName, string userGroupName)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite spSite = new SPSite(Page.Request.Url.ToString()))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
try
{

spWeb.AllowUnsafeUpdates = true;


SPUser spUser = spWeb.EnsureUser(userLoginName);

if (spUser != null)
{
string testCond = (userExistInGroup(userLoginName, userGroupName));

SPGroup spGroup = spWeb.Groups[userGroupName];

if (spGroup != null && (testCond != "found"))
{

spGroup.AddUser(spUser);
lblMsg.Text = "User added successfully !";
}
else
{
lblMsg.Text = "User already exist !";
}
}

}
catch (Exception ex)
{

lblMsg.Text = "An error occured while adding user!";

}
finally
{

spWeb.AllowUnsafeUpdates = false;
}
}
}

});
}



private string userExistInGroup(string userLoginName, string userGroupName)
{
string ReturnValue = "notfound";
SPSecurity.RunWithElevatedPrivileges(delegate()
{

using (SPSite spSite = new SPSite(Page.Request.Url.ToString()))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
spWeb.AllowUnsafeUpdates = true;


SPUser spUser = spWeb.EnsureUser(userLoginName);


if (spUser != null)
{
SPGroup spGroup = spWeb.Groups[userGroupName];

if (spGroup != null)
{
foreach (SPUser user in spGroup.Users)
{
if ((Convert.ToString(user.LoginName)).ToLower().Equals(userLoginName.ToLower()))
ReturnValue = "found";

if (ReturnValue != "notfound")
break;

}
}

}

}
}
});
return ReturnValue;
}

private void GroupList()
{

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = SPContext.Current.Site)
{
using (SPWeb myWeb = site.OpenWeb())
{
string DepartmentName = GetEmpDept(Convert.ToString(myWeb.CurrentUser.LoginName));

SPList list = myWeb.Lists[""];
string strDept = string.Empty;
string[] strDeptArray;
foreach (SPListItem listItem in list.Items)
{
strDept = Convert.ToString(listItem["UserDepartments"]);
strDeptArray = strDept.Split(',');
foreach (string str in strDeptArray)
{
if (str.ToLower().Equals(DepartmentName.ToLower()))
{
addGroup(Convert.ToString(listItem["Title"]));
}
}
}



}
}
});

}

private UserProfileManager GetAllUserProfile()
{


SPSite site = SPContext.Current.Site;
SPWeb spWeb = site.OpenWeb();

ServerContext context = ServerContext.GetContext(SPContext.Current.Site);


if (HttpContext.Current != null)
{
if (HttpContext.Current.Items["HttpHandlerSPWeb"] == null)
HttpContext.Current.Items["HttpHandlerSPWeb"] = spWeb;
if (HttpContext.Current.Items["Microsoft.Office.ServerContext"] == null)
HttpContext.Current.Items["Microsoft.Office.ServerContext"] = context;
}

UserProfileManager profileManager = new UserProfileManager(context);

return profileManager;


}

protected void btnADD_Click(object sender, EventArgs e)
{
foreach (string ent in pe.CommaSeparatedAccounts.Split(','))
{
addUserToGroup(ent, ddGroup.SelectedItem.Text);

}

pe.Entities.Clear();
}

protected void btnClose_Click(object sender, EventArgs e)
{
Response.Redirect("");
}
}
}

Read more...

Sunday, May 17, 2009

Configuring Multiple Authentication(form based authentication) Providers for SharePoint 2007

Windows SharePoint Services (WSS) V3 contains several new features around authentication and authorization that make it easier to develop and deploy solutions in Internet facing environments, especially extranets. In the previous version of WSS, all security principals needed to resolve at some point to a Windows identity – either a user account or group. WSS V3 is built upon the ASP.NET 2.0 Framework, which allows the use of forms-based authentication (FBA) to authenticate users into the system. By riding on top of ASP.NET 2.0’s pluggable authentication provider model, you can now support users stored in Active Directory as well as SQL Server, an LDAP directory, or any other directory that has an ASP.NET 2.0 Membership provider. Although WSS V3 will not ship with any Membership providers, Microsoft Office SharePoint Server (MOSS) 2007 will include an LDAP V3 Membership provider, and ASP.NET 2.0 includes a SQL Server provider. But if you want to use a directory and can’t find a Membership provider for it, you can write your own! This is a key technology enabler for heterogeneous environments.

In a typical extranet environment, content will have two points of access: one on the intranet for employee use and the other on the extranet, where trusted partners can access specific sites, lists and libraries or individual items. Listed below are the WSS V3 features that support this scenario -- some are new while others are just terminology changes:

· Web Application: A web application is what was called a virtual server in the previous version of SharePoint. A single web application only supports a single authentication provider, such as Windows, Forms, etc.

· Zones: A zone is a way to map multiple web applications to a single set of content databases. It is also can be a division of authentication providers. For example, you can create a new web application, create a content database and configure it to use Windows authentication. You can then create a second web application and map it to the first. When you do that you need to assign a zone with which the second web application is associated, such as Intranet, Internet, Custom, or Extranet. The second web application can also use a completely different authentication mechanism, such as forms.

· Policies: A policy is useful in a number of different scenarios, including configuring a web application for forms authentication. It allows you to create policies to grant full access, read only access, deny write access or deny all access to a user or group on a web application. This policy grant applies to all sites in the web application, and it overrides any permissions established within individual sites, lists or items.

· Alternate Access Mappings: In the previous version of SharePoint, it wasn’t as important in an extranet scenario to create an alternate access mapping (AAM) because SharePoint would look to IIS to get some of that information. In WSS V3, it’s imperative to use AAM or things just flat out won’t work. AAM is a way to define the different URL namespaces that are associated with a set of content databases. It effectively manages the zones relationship described above.

· Authentication Providers: So far I’ve described how WSS V3 uses the ASP.NET 2.0 pluggable authentication provider model using the Membership provider interface. As well, SharePoint also supports the Role provider interface, which enables you to surface attributes, such as group membership, about your users as well.

At a high level, creating an extranet solution in WSS V3 requires you to do the following steps. I’ll walk through them briefly and then dive into more detail below. Since MOSS 2007 is built on top of WSS V3, all of the information below applies to MOSS as well. For this scenario, assume that you want to have an intranet style site used internally by your corporate users. They are all joined to your corporate Active Directory. In addition, you have a number of trusted partners to which you wish to give access via the Internet. Note that in this scenario I will not be touching on any aspects of securing your site with firewalls, proxy servers, segmented networks, DMZ Active Directory designs, security best practices around farm configuration, etc. You can read all about that in Joel’s recent blog entry here: http://blogs.msdn.com/sharepoint/archive/2006/08/08/691540.aspx.

The process you would go through to build out such a site would be as follows.

After installing WSS V3 (or MOSS 2007) and having configured all of the services and servers in the farm, create a new web application. By default this will be configured to use Windows authentication and will be the entry point through which your intranet users will access the site. We’ll refer to this site as http://intranet. Next, create a second web application. When you create the web application, select the option to Extend an existing Web Application. When you create your second web application, map it to the Extranet zone. Give it a Host Header name that you will configure in DNS for your extranet users to resolve against. We’ll refer to this site as http://extranet.contoso.com.

If you haven’t created and populated your directory of FBA users who will be accessing the site via the extranet, then you should do so at this time. For this scenario we’ll assume that you are using FBA with the SQL Server Membership and Role providers that are included with ASP.NET 2.0.

Manually modify the web.config for the extranet site and add in the information about your Membership and Role provider (the Role provider is technically optional, but most implementations will use it). Add this same information into the web.config for the Central Administration site. Save both config files and do an IISRESET.

In the Central Admin site, go to the Application Management page and select the Policy for Web Application link. Add a user from your SQL Server directory to the Extranet zone for your web application. You should be able to type in the user name and resolve it, or use the People Picker dialog to search and find the user name. If everything is configured correctly then SharePoint will be able to resolve the user name you add. Give the user account Full access to the web application.

Navigate to the site using either entry point -- Windows or Forms-based authentication. If you use FBA, then you will need to sign in with the credentials of the user that was granted full access rights via policy. After you navigate to the site, go into Site Settings, People and Groups. From there you can add both Windows and forms users and groups to SharePoint Site Groups. Your users should now be able to access the site.

Now let’s look at some of the above steps in more detail. Creating the web applications should be fairly straightforward using Central Administration, so I won't spend any time on that. The key takeaway here is that when you create the second web application, you need to make sure that you select the option to Extend an existing Web Application and map it to the Extranet zone. Also remember to give it a Host Header name that is in your external DNS – this is the URL that external users will use to access the site via the Internet.

Next, you need to create the aspnetdb database used for storing membership and role information if you don’t have one already set up. To create the database, do the following:

Open a command prompt and change to the .NET Framework directory (by default, it's C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727).

Run the following command: aspnet_regsql -A all –E

This will create the aspnetdb database on the local SQL Server. If you wish to install it on a different server, then run aspnet_regsql /? to determine the appropriate switch to use.

If you are creating your SQL Server provider database for the first time you will also need to create one or more users and optionally, one or more roles. These will be the security principals that you add to the Policy for the extranet web application as well as the SharePoint Site Groups. There are multiple ways to do this and a quick search on the web will highlight some of those tools and methods. That’s a bit out of scope for this already lengthy blog, so I'll continue on and assume that you’ve already created the users and roles for your SharePoint site.

Now we have our web applications as well as users and roles created in SQL Server, so we need to configure the web.config for the extranet and Central Administration web applications. The first step is to look for a connectionStrings element; if it doesn’t exist then you can add it below the and above the elements. The new element should look like the following:

AspNetSqlProvider" connectionString="server=yourSqlServerName; database=aspnetdb; Trusted_Connection=True" />

You’ll want to take note of the name attribute above, because you will use that attribute name when configuring the Membership and Role providers. Add that information as follows:

Open the web.config file for your extranet web application in a text editor such as Notepad.

Add your connectionString element described above as the last item in the connectionStrings section in the web.config file.

Add the Membership and Role configuration information to the web.config file. It must be added below the element and should look like the following:

AspNetSqlMembershipProvider">

AspNetSqlMembershipProvider" />

AspNetSqlProvider" passwordAttemptWindow="10" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="false" passwordFormat="Hashed" description="Stores and retrieves membership data from the Microsoft SQL Server database" name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

Save and close the web.config file.

The name attributes of the Membership and Role providers are highlighted above. You need to note what these names are because you will enter them in Central Administration when you configure FBA for the site.

You also need to make the same exact changes to the web.config for the Central Administration site, with one minor exception. The roleManager element for the extranet web application looks like the following:

You need to change this line to read as follows:

This change is necessary because the Central Administration site still uses Windows authentication for the role provider -- that’s why the AspNetWindowsTokenRoleProvider is set as the default provider.

Now you need to configure the Authentication provider for the extranet web application to use FBA. Open your browser and navigate to your farm’s Central Administration site, click on Application Management and then on Authentication Providers. Make sure that you are working on the web application for which you wish to enable FBA. (If the correct application is not already pre-selected, click the Change button in the upper right hand corner of the page to select the application.)

You should see a list of two zones that are mapped for this web application; both should say Windows. Click on the link that says Windows for the web application in the Extranet zone and do the following:

In the Authentication Type section, click on the Forms radio button. The page will post back and expose two new edit boxes.

In the Membership provider name edit box, type in the name of your web application’s Membership provider for the current zone. That is the value that was highlighted in the defaultProvider attribute of the Membership element above.

In the Role manager name edit box, type in the name of your web application’s Role provider. That is the value that was highlighted in the defaultProvider attribute of the roleManager element above.

Click the Save button.

Your extranet web application is now configured to use FBA. However, until users, who will be accessing the site via FBA, are given permissions for the site, it will be inaccessible to them. To do this, you could go directly to the default zone (i.e. http://intranet) of the site, login with your Windows credentials, and add the FBA users. However, I'll describe an alternative approach because it's the one that you are most likely to use if you ever configure an application that only has one web application, which uses FBA.

To get started, open your browser and navigate to your farm’s Central Administration site. Click on Application Management and then click on Policy for Web Application. Make sure that you are working on the extranet web application. Do the following steps:

Click on Add Users.

In the Zones drop down, select the appropriate Extranet zone. IMPORTANT: If you select the incorrect zone, you may not be able to resolve user names. Hence, the zone you select must match the zone of the web application that is configured to use FBA.

Click the Next button.

In the Users edit box, type the name of the FBA user whom you wish to have full control for the site.

Click the Resolve link next to the Users edit box. If the web application's FBA information has been configured correctly, the name will resolve and become underlined.

Check the Full Control checkbox.

Click the Finish button.

That’s it -- that’s all of the configuration needed! You can now navigate to either web application: http://intranet or http://extranet.contoso.com. Irrespective of which entry point you use, you can add, search and resolve both Windows and FBA users and groups and add them to SharePoint Site Groups. The People Picker is smart enough to know about all of the web applications that are mapped to the site and will try all of the authentication providers that those applications use.

Lastly, there are two other things for you to remember:

Resolving group names: The People Picker can only do wildcard searches for Windows group names. If you have a SQL Role provider group called "Readers" and enter "Read" in the People Picker search dialog, it will not find your group; if you enter "Readers" it will. This is not a bug -- the Role provider just doesn’t provide a good way to do wildcard group searching.

Use Policies sparingly: The concept described above for adding a user or group via the web application Policy should only be used to provide a way for an FBA administrator to access the site. Policies are very coarsely grained compared to the fine grain permissions that can be configured and granted within individual sites, lists and items. Once you’ve added your site administrator via Policy, all other users and groups should be added from within the site itself.

Admittedly, there are many steps involved in configuring multiple authentication providers for SharePoint, but I hope that by having read this blog entry, you now understand the reasoning behind each of the steps involved and are in a better position to implement or troubleshoot this particular SharePoint configuration.


This article was published by : Steve Peschka on Http://blogs.msdn.com


Read more...

Business Data Catalog (BDC) for the Power User – List Columns

Suppose, in a Document Library I was creating Proposals, Invoices, Credit Notes, Purchase orders etc. Against all of these documents, it would be useful to store the Company Name, City, Telephone Number etc so that should I want to chase an invoice, or follow up a proposal the information is at hand, and I don't have to go looking for it in my CRM application. So using a Lightning Tools sample Database as an example, I would like to show you how to create columns that use BDC data:

  1. Navigate to your Team Site where you would like to try this out.
  2. Create a new document library by choosing Site Actions, Create (Site Actions, View all Site Content, Create if you have publishing switched on).
  3. Choose the Document Library Template
  4. Name the Document Library 'Sales Documents'
  5. Accept the defaults and click Create.
  6. Choose Settings, Document Library Settings
  7. Under the Columns section click Create Column
  8. Name the Column Company
  9. Choose Business Data as the Type.
  10. In the Type field, click the address book icon.
  11. Choose the Entity that contains your customer data
  12. Select the column that contains the data you would like to store
  13. Check the columns you would like to display
  14. Click OK.
  15. Using the BreadCrumb trail choose the Sales documents link.
  16. Click New, to create a new document
  17. The Document Information Panel will display (Office 2007 required).
  18. Type a customer ID in the CustomerID column, and you will see the other information from BDC returned.
  19. Save and Close Word.
  20. Notice in the Document Library, that the Meta Data is displayed in the default view and can be filtered/sorted etc.


This Article was published by : Brett Lonsdale (Director – Lightning Tools Ltd) Http://sharepoint.microsoft.com

Read more...

Friday, May 1, 2009

Converting blob data from sql server to image in C#.NET

Byte[] bytImage=null;

//Change the ConnString as per your system.

string constring = @"Data Source=LOCAL;Initial Catalog=DA;Integrated Security=True;"; SqlCommand command = new SqlCommand(@"SELECT BlobData FROM Lib.LibBlob WHERE BlobID='04F24251-AE4C-4FDA-BDB7-0689C9616462'"); command.CommandType = CommandType.Text;

SqlConnection myconn = new SqlConnection(constring);

command.Connection = myconn;

myconn.Open();

SqlDataReader dr = command.ExecuteReader();

while(dr.Read())

{

bytImage = (byte[])dr["BlobData"];

}

if (bytImage !=null)

{

//saving this to bmp file

MemoryStream ms = new MemoryStream(bytImage);

System.Drawing.Bitmap BMP = new System.Drawing.Bitmap(ms);

BMP.Save("C:\\Temp\\Test.bmp");

//saving to jpg image

//System.Drawing.Image img = new System.Drawing.Bitmap(ms);

//img.Save("C:\\Temp\\Test1.jpeg", ImageFormat.Jpeg);

}

Read more...

Monday, April 27, 2009

WebParts and Audiences - Part 2: Create a custom ToolPart/EditorPart to configure audiences for your custom WebPart

This is part 2 of a series I will write on how to deal with audiences in your custom SharePoint WebParts.

In this post, I will show you how to create a custom ToolPart/EditorPart for your WebPart that allows to configure audience settings for the WebPart. In my example I've implemented to possible settings:

  • Audience targeting for the whole WebPart (if a user is not in the right audience the WebPart will be invisible --> see Part 1)
  • Audience targeting for the data items that are showed in the WebPart (see in a later part of the series).

In order to allow the user to pick the audiences, I am using the standard-SharePoint AudienceEditor web control:

_wpAudiences.Types = AudienceEditor.AudienceType.DL | AudienceEditor.AudienceType.GlobalAudience | AudienceEditor.AudienceType.SharePointGroup;
_wpAudiences.Visible = true;
_wpAudiences.Width = Unit.Pixel(0x182);
this.AddConfigurationOption("WebPart Audiences", "Members of these audiences can view the Web Part. If left blank, everyone can see the Web Part",
_wpAudiences);

here is full implementation:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint.WebPartPages;

namespace YourNameSpace
{

/// Base class for all custom ToolParts.

public class BaseToolPart : ToolPart, INamingContainer
{

#region Overridden Members


/// Called if a user has commited a configuration change.

public override void ApplyChanges()
{
this.OnAppliedChanges(EventArgs.Empty);
base.ApplyChanges();
}

#endregion

#region Protected Members
/// Creates a label and a corresponding control.



///
protected virtual void AddConfigurationOption(string title, Control inputControl)
{
this.AddConfigurationOption(title, null, inputControl);
}

///
/// Creates a label and a corresponding control.

protected virtual void AddConfigurationOption(string title, string description, Control inputControl)
{
this.AddConfigurationOption(title, description, new List(new Control[]{inputControl}));
}

///
/// Creates a label and a corresponding control.

protected virtual void AddConfigurationOption(string title, string description, IEnumerable inputControls)
{
HtmlGenericControl divSectionHead = new HtmlGenericControl("div");
divSectionHead.Attributes.Add("class", "UserSectionHead");
this.Controls.Add(divSectionHead);

HtmlGenericControl labTitle = new HtmlGenericControl("label");
labTitle.InnerHtml = HttpUtility.HtmlEncode(title);
divSectionHead.Controls.Add(labTitle);

HtmlGenericControl divUserSectionBody = new HtmlGenericControl("div");
divUserSectionBody.Attributes.Add("class", "UserSectionBody");
this.Controls.Add(divUserSectionBody);

HtmlGenericControl divUserControlGroup = new HtmlGenericControl("div");
divUserControlGroup.Attributes.Add("class", "UserControlGroup");
divUserSectionBody.Controls.Add(divUserControlGroup);

if (!string.IsNullOrEmpty(description))
{
HtmlGenericControl spnDescription= new HtmlGenericControl("div");
spnDescription.InnerHtml = HttpUtility.HtmlEncode(description);
divUserControlGroup.Controls.Add(spnDescription);
}

foreach (Control inputControl in inputControls)
{
divUserControlGroup.Controls.Add(inputControl);
}

HtmlGenericControl divUserDottedLine = new HtmlGenericControl("div");
divUserDottedLine.Attributes.Add("class", "UserDottedLine");
divUserDottedLine.Style.Add(HtmlTextWriterStyle.Width, "100%");
this.Controls.Add(divUserDottedLine);
}

#endregion

#region Events & Handlers
///
/// Fires after a user has commited a configuration change.
///
public event EventHandler AppliedChanges;

///
/// Called after a user has commited a configuration change (ApplyChanges).
///
protected virtual void OnAppliedChanges(EventArgs e)
{
if (this.AppliedChanges != null)
this.AppliedChanges(this, e);
}

#endregion
}
}

-----------------------------------------------------------

using System.Web.UI.WebControls;
using Microsoft.Office.Server.WebControls;

namespace YourNameSpace
{
public class AudiencesToolPart : BaseToolPart
{

#region Constants and Private Members
private AudienceEditor _wpAudiences = new AudienceEditor();
private CheckBox _chkFilterContentByAudience = new CheckBox();
private bool _showWebPartAudiences = true;
private bool _showFilterContentByAudiences = true;

#endregion

public AudiencesToolPart()
{
this.Title = "Audiences";
}

#endregion

#region Overridden members

protected override void CreateChildControls()
{
if (_showWebPartAudiences)
{
_wpAudiences.Types = AudienceEditor.AudienceType.DL | AudienceEditor.AudienceType.GlobalAudience | AudienceEditor.AudienceType.SharePointGroup;
_wpAudiences.Visible = true;
_wpAudiences.Width = Unit.Pixel(0x182);
this.AddConfigurationOption("WebPart Audiences", "Members of these audiences can view the Web Part. If left blank, everyone can see the Web Part",
_wpAudiences);
}

if (_showFilterContentByAudiences)
{
this._chkFilterContentByAudience.ID = "chkContentFiltering";
this.AddConfigurationOption("Content filtering", "If checked, audience-filtering will be applied to the contents of this Web Part",
this._chkFilterContentByAudience);
}

base.CreateChildControls();
}


#endregion

#region Public Members

public bool FilterContentByAudience
{
get
{
return this._chkFilterContentByAudience.Checked;
}
set
{
this._chkFilterContentByAudience.Checked = value;
}
}

public string WebPartAudiences
{
get
{
return this._wpAudiences.Text;
}
set
{
this._wpAudiences.Text = value;
}
}


public bool ShowWebPartAudiences
{
get { return this._showWebPartAudiences; }
set { this._showWebPartAudiences = value; }
}

public bool ShowFilterContentByAudiences
{
get { return this._showFilterContentByAudiences; }
set { this._showFilterContentByAudiences = value; }
}
#endregion

}
}







Read more...

WebParts and Audiences - Part 1: Show or hide a Web Part based on audiences

This is part 1 of a series I will write on how to deal with audiences in your custom SharePoint WebParts.

Some of the standard SharePoint WebParts implement audience filtering. I was wondering, what it takes to make my custom WebParts as well audience "sensitive". I wanted to apply the audience filtering at 2 different levels:

  • Show or hide the WebPart depending on audiences
  • Show or hide data items the WebPart displays depending on audiences.

As well, I wanted to enable administrators / power users to configure the WebPart to filter for audiences, which meant to create a custom ToolPart/EditorPart.

In this first part of the series, we will look at how hide a custom WebPart if the user is not in one of the necessary audiences that are allowed to see the WebPart.

In order to store the audiences that are allowed to see the WebPart, we must create a shared-property that will be configured using our custom ToolPart/EditorPart which I will describe in Part 2 of my series.

[WebBrowsable(false), FriendlyName("WebPart target audiences"), Description(""),
Category("Presentation"), DefaultValue(""), WebPartStorage(Storage.Shared), Personalizable(PersonalizationScope.Shared)]
public string TargetAudiences
{
get
{
return this._targetAudiences;
}
set
{
this._targetAudiences = value;
}
}

This property stores the value given back by the standard-SharePoint AudienceEditor control Text-property as I will describe in part 2. Given this WebPart-property, all we need to do is to override the OnPreRender-method of our WebPart with the following:

protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);

this.Hidden = false;

if (!string.IsNullOrEmpty(TargetAudiences))
{
if (ServerContext.Current == null)
return;

AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader();
if (!AudienceManager.IsCurrentUserInAudienceOf(audienceLoader, this.TargetAudiences, false))
{
this.Hidden = true;
}
}
}

Try it :) If the current user is not in one of the audiences that are configured for your WebPart - the whole WebPart will be hidden.

Read more...

Saturday, April 25, 2009

Adding WebParts programmatically to a WebPartZone

I had a very hard time finding information on the web on how to correctly add Web Parts programmatically to my SharePoint WebPartZone.

It's easy to get all the WebParts that are present in the current Site:

SPContext.Current.Site.GetCatalog(SPListTemplateType.WebPartCatalog

Since this is a normal SharePoint list it is also easy to extract the items, display them etc... Now, given that I have selected the WebPart that I want to add:

SPListItem selectedWebPartListItem = SPContext.Current.Site.GetCatalog(SPListTemplateType.WebPartCatalog).Items.GetItemById(selectedWebPartId);

I need now an instance of SPLimitedWebPartManager (Make sure you take the correct PersonalizationScope):

using (SPLimitedWebPartManager manager = SPContext.Current.Web.GetLimitedWebPartManager(this.Page.Request.Url.ToString(), PersonalizationScope.Shared))
{ ... code ... }

Now my trouble started... I found code to create an instance of the WebPart:

string typeName = selectedWebPartListItem.GetFormattedValue("WebPartTypeName");
string assemblyName = selectedWebPartListItem.GetFormattedValue("WebPartAssembly");
ObjectHandle webPartHandle = Activator.CreateInstance(assemblyName, typeName);
System.Web.UI.WebControls.WebParts.WebPart webPart = (System.Web.UI.WebControls.WebParts.WebPart)webPartHandle.Unwrap();

This looks nice - but is completely the WRONG thing to do!

If you are creating an instance of the WebPart like this, you are completely ignoring the (maybe) individual configuration that is set in the .webpart or .dwp file!

The right and (at least in my environment) working way is to import the WebPart like this:

string fileName = string.Format("{0}/{1}", selectedWebPartListItem.Web.Url, selectedWebPartListItem.File.Url);
XmlUrlResolver xmlResolver = new XmlUrlResolver();
xmlResolver.Credentials = CredentialCache.DefaultCredentials;
XmlTextReader reader = new XmlTextReader(fileName);

string errorMsg;
System.Web.UI.WebControls.WebParts.WebPart webPart = manager.ImportWebPart(reader, out errorMsg);

if (!string.IsNullOrEmpty(errorMsg)) {
// your exception handling goes here
}
else
{
manager.AddWebPart(webPart, _wpManager.Zones[_ddlWebPartZones.SelectedItem.Value].ID, Convert.ToInt32(rowIndex));
}


Read more...

Monday, April 20, 2009

Hide the Sign In link for the anonymous access user in anonymous access enabled site - Bend the Welcome.ascx - SharePoint MOSS

Lots of thing can be done by playing around the Welcome.ascx user control. I have came across one of the interesting thing on hiding the “Sign In” link for anonymous access users in the public facing internet site and thought of sharing with you.

 

Following are the two steps to implement this requirement in the supported way and its quite easy, thanks to master page and the SharePoint Application Page link control.

 

1.    Create a custom user control based on the OOB “WelCome.ascx” control. Override the “OnLoad” event and hide the “Sign In” application page link for the anonymous access user.

 

2.    Create a custom master page based on the any OOB parent master page with respect to your requirement and site definition. Render the Custom welcome control in the place of OOB welcome control.

 

 

You can find the Welcome.ascx user control under the “Control Templates” folder. Bunch of menu items are available for the authenticated user like My Settings, Sign in as different user, Log Out and Personalize the page. All these menu items are available as feature menu template and will be available only if the user was authenticated successfully. Following is the structure of the feature menu template and all the menu items are available under the ID “ExplicitLogOut”. You can see that the visibility of this Personal Actions control is false and the visibility will be made to true when the user is successfully authenticated.

 <SharePoint:PersonalActions AccessKey="<%$Resources:wss,personalactions_menu_ak%>"ToolTip="<%$Resources:wss,open_menu%>" runat="server" id="ExplicitLogout" Visible="false">

      <CustomTemplate>

       <SharePoint:FeatureMenuTemplate runat="server"

             FeatureScope="Site"

             Location="Microsoft.SharePoint.StandardMenu"

             GroupId="PersonalActions"

             id="ID_PersonalActionMenu"

             UseShortId="true"

             >

             <SharePoint:MenuItemTemplate runat="server" id="ID_PersonalInformation"

                         Text="<%$Resources:wss,personalactions_personalinformation%>"

                         Description="<%$Resources:wss,personalactions_personalinformationdescription%>"

                         MenuGroupId="100"

                         Sequence="100"

                         ImageUrl="/_layouts/images/menuprofile.gif"

                         UseShortId="true"

                         />

             <SharePoint:MenuItemTemplate runat="server" id="ID_LoginAsDifferentUser"

                         Text="<%$Resources:wss,personalactions_loginasdifferentuser%>"

                         Description="<%$Resources:wss,personalactions_loginasdifferentuserdescription%>"

                         MenuGroupId="200"

                         Sequence="100"

                         UseShortId="true"

                         />

             <SharePoint:MenuItemTemplate runat="server" id="ID_RequestAccess"

                         Text="<%$Resources:wss,personalactions_requestaccess%>"

                         Description="<%$Resources:wss,personalactions_requestaccessdescription%>"

                         MenuGroupId="200"

                         UseShortId="true"

                         Sequence="200"

                         />

             <SharePoint:MenuItemTemplate runat="server" id="ID_Logout"

                         Text="<%$Resources:wss,personalactions_logout%>"

                         Description="<%$Resources:wss,personalactions_logoutdescription%>"

                         MenuGroupId="200"

                         Sequence="300"

                         UseShortId="true"

                         />

             <SharePoint:MenuItemTemplate runat="server" id="ID_PersonalizePage"

                         Text="<%$Resources:wss,personalactions_personalizepage%>"

                         Description="<%$Resources:wss,personalactions_personalizepagedescription%>"

                         ImageUrl="/_layouts/images/menupersonalize.gif"

                         ClientOnClickScript="javascript:MSOLayout_ChangeLayoutMode(true);"

                         PermissionsString="AddDelPrivateWebParts,UpdatePersonalWebParts"

                         PermissionMode="Any"

                         MenuGroupId="300"

                         Sequence="100"

                         UseShortId="true"

                         />

             <SharePoint:MenuItemTemplate runat="server" id="ID_SwitchView"

                         MenuGroupId="300"

                         Sequence="200"

                         UseShortId="true"

                         />

             <SharePoint:MenuItemTemplate runat="server" id="MSOMenu_RestoreDefaults"

                         Text="<%$Resources:wss,personalactions_restorepagedefaults%>"

                         Description="<%$Resources:wss,personalactions_restorepagedefaultsdescription%>"

                         ClientOnClickNavigateUrl="javascript:MSOWebPartPage_RestorePageDefault()"

                         MenuGroupId="300"

                         Sequence="300"

                         UseShortId="true"

                         />

       SharePoint:FeatureMenuTemplate>

      CustomTemplate>

SharePoint:PersonalActions>

 

 

The another part of the welcome user control is “ExplicitLogin” which has been rendered as the SharePoint Application Page Link as follows.

 

<SharePoint:ApplicationPageLink runat="server" id="ExplicitLogin"

      ApplicationPageFileName="Authenticate.aspx" AppendCurrentPageUrl=true

      Text="<%$Resources:wss,login_pagetitle%>" style="display:none" Visible="false" />

 

 

This is the link which we need to concentrate for this requirement. By default this link visibility is false and will come alive when the user is not authenticated. This is what happens with the anonymous access user. When the anonymous user access the site this link is visible so that the unauthenticated user can sign in.

 

Fair enough on the post mortem of the welcome user control. Now copy this welcome user control and paste it under the Control templates folder as “CustomWelcome.ascx” control. In the “CustomWelcome.ascx” control add an In Line script and override the “OnLoad” event. In the “OnLoad” event for the unauthenticated user hide the  “ExplicitLogin” link.

 

protected override void OnLoad(EventArgs e)

    {

        //base.OnLoad(e);

        base.OnLoad(e);

        if (HttpContext.Current.User.Identity.IsAuthenticated)

        {

            this.ExplicitLogout.Visible = true;

        }

        else

        {

            this.ExplicitLogin.Visible = false;

            this.ExplicitLogin.Attributes.CssStyle.Add("display""block");

        }

 

    }

 

Now we are done with the custom welcome user control. Let us have a look on rendering it through the custom master page based on the “default.master” master page. Copy the default.master page and add the Tag prefix reference for the “CustomWelcom.ascx” control as follows in the custom master page :

 

<%@ Register TagPrefix="wssuc" TagName="CustomWelcome" src="~/_controltemplates/CustomWelcome.ascx" %>

 

Find the following entry in the master page :

 

<wssuc:Welcome id="IdWelcome" runat="server" EnableViewState="false">

                  wssuc:Welcome>

 

Replace the above entry with the following entry to replace the OOB welcome user control with your custom welcome user control :

 

<wssuc:CustomWelcome id="IdWelcome" runat="server" EnableViewState="false">

                  wssuc:Welcome>

 

Save the custom master page and use it for the public facing internet site and now “Sign In” link will not be available for the unauthenticated anonymous access user.

 

If you are aware of the whole welcome.ascx control and its structure then you can play with it for bending its behavior through custom user control. Happy customizing J

Read more...

Blog Popularty Partners

  ©All Right Reserved.

Back to TOP