Thursday, August 25, 2011

Web Part Caching

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Microsoft.SharePoint;
using System.Web;
namespace Zimmergren.WebParts.SampleCachePart
{
public class SimpleCache : System.Web.UI.WebControls.WebParts.WebPart
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
base.Render(writer);

List lists = new List();
string status = "";

if (HttpRuntime.Cache["SimpleSampleCache"] == null)
{
status = "The following items are NOT fetched from the cache

";

SPWeb web = SPContext.Current.Web;
foreach (SPList list in web.Lists)
lists.Add(list);

HttpRuntime.Cache.Add("SimpleSampleCache",
lists,
null,
DateTime.MaxValue,
TimeSpan.FromMinutes(10),
System.Web.Caching.CacheItemPriority.Default, null);
}
else
{
status = "The following items ARE fetched from the cache!

";
lists = (List)HttpRuntime.Cache["SimpleSampleCache"];
}

writer.Write(status);
foreach (SPList l in lists)
writer.WriteLine(l.Title + " - " + l.ItemCount + " items
");
}
}
}

Programmatically add or remove item level permission in Sharepoint

In this article I will show you how to Add or Remove Item Level Permissions programmatically. I will show you this thing in console application. You can use it anywhere based upon your requirements.

Sometimes we are having a business requirement like if someone is adding any item to a list or document library than some users should have read permissions to it, some of them should have write permissions and some of the users should not have any access to that particular list item.

Then how to achieve this kind of requirements.

In ideal situations we are writing Item Adding event handlers and based upon business rules we are giving the access and removing the access because whenever any user is adding any item than that item will inherit the site level permissions. So on this event we can add or remove the permissions to that list item.

Let's see how we can add or remove permissions at item level.

Step 0: Create one list named Check and add 2-3 items in it.

Click on Manage Permissions link and see who all are having permissions to that particular list item.

In my case on "Ravish" list item this much user or Groups are having access. Now our task is to remove all the users or groups who are having the access and add only administrator to it. i.e. only administrator should have the access.

We are doing this through sharepoint object model. Below are the steps of doing this.

Step 1: Create one console application.

Step 2: Add refernce to Microsoft.Sharepoint.dll

Step 3: Navigate to the List item by using sharepoint object model.
//Connect to Sharepoint Site
SPSite oSPSite = new SPSite("http://spdevserver:1002/");
//Open Sharepoint Site
SPWeb oSPWeb = oSPSite.OpenWeb();
//get the Sharepoint List
SPList oSPList = oSPWeb.Lists["Check"];
//Get the Sharepoint list item for giving permission
SPListItem oSPListItem = oSPList.Items[0];
Console.WriteLine(oSPListItem["Title"]);
Console.Read();
Step 4: Now we have navigated to List Item Ravish. Next step is to remove all the permissions for this list item.

Function Call

RemoveAllPermissions(oSPListItem);

Function Definition:

private static void RemoveAllPermissions(SPListItem CurrentlistItem)
{
//The below function Breaks the role assignment inheritance for the list and gives the current list its own copy of the role assignments
CurrentlistItem.BreakRoleInheritance(true);
//Get the list of Role Assignments to list item and remove one by one.
SPRoleAssignmentCollection SPRoleAssColn = CurrentlistItem.RoleAssignments;
for (int i = SPRoleAssColn.Count - 1; i >=0 ; i--)
{
SPRoleAssColn.Remove(i);
}
Console.WriteLine("All Permissions Removed");
}

After this check List Item permissions once agin by clicking on Manage Permissions Link.

You will see there are no items to show in this view. Means all the permissions for this list item has been removed.

Step 5: Next step is to add permissions to the same list item.

//Create new user to grant access
SPUserCollection users = oSPWeb.Users;
SPUser CurrentUser = users["Domain\\Administrator"];
//Add new permissions to List Items
//If you want to give access to a Group than pass SPGroup instead of SPUser. The same function will give access.
GrantPermission(oSPListItem, oSPWeb, SPRoleType.Contributor, CurrentUser);

Function Definition:

private static void GrantPermission(SPListItem CurrentListItem, SPWeb oSPWeb, SPRoleType SPRoleType, SPPrincipal SPPrincipal)
{
//Create one Role Definition i.e Full Controls, Contribute rights or Read rights etc.
SPRoleDefinition oSPRoleDefinition = oSPWeb.RoleDefinitions.GetByType(SPRoleType);
//Create one Role Assignment for the specified SP user or group.
SPRoleAssignment oSPRoleAssignment = new SPRoleAssignment(SPPrincipal);
//Bind the role definition to the role assignment object created for the user or group.
oSPRoleAssignment.RoleDefinitionBindings.Add(oSPRoleDefinition);
//Add it to the specified list item.
CurrentListItem.RoleAssignments.Add(oSPRoleAssignment);
//update the list item so that specified user assignment will have the access.
CurrentListItem.Update();
Console.WriteLine("All Permissions Removed");
Console.Read();

}


After this check List Item permissions once again by clicking on Manage Permissions Link.

You will see that new user has been added to the particular list item.

In this way we can add or remove the permission at Item Level in a sharepoint site.



Hope this helps..

STSADM commands


1. stsadm -o activatefeature {-filename | -name | -id } [-url ] [-force]
2. stsadm -o activateformtemplate -url [-formid
] [-filename ]
3. stsadm -o addalternatedomain -url -incomingurl -urlzone -resourcename
4. stsadm -o addcontentdb -url -databasename [-databaseserver ] [-databaseuser ] [-databasepassword ] [-sitewarning ] [-sitemax ]
5. stsadm -o adddataconnectionfile -filename [-webaccessible ] [-overwrite ] [-category ]
6. stsadm -o add-ecsfiletrustedlocation -Ssp -Location -LocationType SharePoint|Unc|Http -IncludeChildren True|False [-SessionTimeout

Perform a case insensitiv​e string comparison in InfoPath 2007 web based forms


Perform a case insensitiv​e string comparison in InfoPath 2007 web based forms

translate(InsertFieldHere, "ABCDEFGHIJKLMNOPQRSTUVWYXZ", "abcdefghijklmnopqrstuvwyxz")


Hope this helps...

Serial Number column for a repeating table Infopath form


Serial Number column for a repeating table
Below is the formula to get the serial number in
a repeating table

Fx:: count(../preceding-sibling::*/my:Controlname) + 1




Hope this helps...

TaskItem URL-sequen​tial work flow

string taskID = Convert.ToString(GetNextAvailableIdFromList(workflowProperties.Site, workflowProperties.TaskListId));


string constructURL = returnTaskUrl(taskID);


private string returnTaskUrl(string taskId)
{
string fulltaskUrl = string.Empty;
string htmlTaskLink = string.Empty;
try
{
//Use this to return the relevant URL's for use in e-mail of tasks.
string weburl = workflowProperties.WebUrl;
string taskUrl = "/_layouts/WrkTaskIP.aspx?List=";
string listId = workflowProperties.TaskListId.ToString();
fulltaskUrl = weburl + taskUrl + listId + "&ID=" + taskId;
htmlTaskLink = "here";
}
catch (System.Exception ex)
{
}
return htmlTaskLink;
}



public static int GetNextAvailableIdFromList(SPSite site, Guid listId)
{
int NextAvailableId = -1;
if (site.WebApplication.ContentDatabases.Count > 0)
{
string DBConnString = site.WebApplication.ContentDatabases[0].DatabaseConnectionString;
SqlConnection con = new SqlConnection(DBConnString);
try
{
con.Open();
SqlCommand com = con.CreateCommand();
com.CommandText = String.Format("select tp_NextAvailableId from AllLists where tp_ID = '{0}'", listId.ToString());
NextAvailableId = (int)com.ExecuteScalar();
}
finally
{
con.Close();
}
}
return NextAvailableId;
}



Programatically get task item url sequential workflow

This post will be helpful if you wanna get task item url and append in custom mail body while notifying the approver about the task. Approver instead of opening the task from the task list,he/she can abe able to open the task directly from the mail by the link what you have provided.

Removing the Powered by: InfoPath Forms Services

Below is the piece of code in order to achieve the same.



To determine whether the logo is turned on or whether the logo is turned off

stsadm -o getformsserviceproperty -pn AllowBranding



To turn off the logo

stsadm -o setformsserviceproperty -pn AllowBranding -pv false



To turn on the logo

stsadm -o setformsserviceproperty -pn AllowBranding -pv true



Hope this helps....

Adding ToolTip for drop down List Item.

In Some cases, you have a restricted design that forces you to place a DropDownList control inside a "td" or "div" element, which has a fixed width. if that DropDownList contains long pieces of text then the user will not be able to read the whole text as you can see in Figure1.

Figure 1

The best solution to overcome this problem is to add a ToolTip for the item to display the whole text. As we know the regular DropDownList does not support that which is the main goal of this post.

Lest us say that we have a DropDownList that contains three list items.

Code 1


<asp:DropDownList ID="DropDownList1" runat="server" Width="119px">
<asp:ListItem Value="1">Technical Departmentasp:ListItem>
<asp:ListItem Value="2">Production Departmentasp:ListItem>
<asp:ListItem Value="3">HR Departmentasp:ListItem>
asp:DropDownList>

As I said, the regular DropDownList does not support a ToolTip for each list item, so we will add a new attribute for each list item which is the "title" attribute.

Code 2


foreach (ListItem _listItem in this.DropDownList1.Items)


{

_listItem.Attributes.Add(
"title", _listItem.Text);

}

As you can see in the above code, we wrote a foreach loop to walk through the DropDownList item-by-item to add the title attribtue.

You can enter any text to represent the ToolTip for the item as description; here in our example I am using the list item text to be its ToolTip.

We need to add a title attribute for the selected item too, as shown in below code.

Code 3

DropDownList1.Attributes.Add("onmouseover", _ 
 "this.title=this.options[this.selectedIndex].title");

if you view your code in a browser, right click on the page and choose view source, take a look at the HTML generated element for our DropDownList, in Code 4, note that a new title attribute is added for each item in the list.

Code 4



Figure 2

The above figure shows you how our new tooltip works when the mouse goes over the list item.

Conclusion

in this article, we have added a new tooltip attribute for each item in the DropDownList which will help the users to read the whole text. I hope you found this useful and informative. If you have any questions, please write your comments below.

Print Command asp.net

To Print the window screen you need to add a java script function on the onclick property of the button.
Example::

<
li class="print"><span class="ms-rteCustom-ExtraSmallText"><a href="#" onclick="javascript:window.print();">Print this pagea>span>li>

Popular Posts