Tuesday 18 February 2014

Add new element in the web.config file using sharepoint

If you can add new element the web.config file using sharepoint administration SPWebConfigModificationObject that have open web.config file and find the appropriate element tag in the web.config file and add new element in the web.config.

You can use this code in the feature actived.


try

{
SPWebApplication app = null;
SPWeb web = null;
SPSiteCollection site = properties.Feature.Parent as SPSiteCollection;
if (site == null)
{
web = properties.Feature.Parent as SPWeb;
if (web != null)
app = web.Site.WebApplication;
}
else
app = site.WebApplication;
SPWebConfigModification modification = new SPWebConfigModification();
modification.Name = "add [@Assembly='System.DirectoryServices'] [@Version='2.0.0.0'][@Culture='neutral'][@PublicKeyToken='B03F5F7F11D50A3A']";
modification.Path = "configuration/system.web/compilation/assemblies";
modification.Value = @"DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A'/> ";
modification.Owner = Assembly.GetExecutingAssembly().FullName;
modification.Sequence = 0;
modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
app.WebConfigModifications.Add(modification);
SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}
catch (Exception ex)
{

}

The example code could be changed easily to remove the configuration change, as in the following example:
app.WebConfigModifications.Remove(modification);

DateTime in CAML Query

Caml query not using the time part in datetime. If your are doing a caml query and you see that your time is being ignored in datetime try this:

<Value Type=”DateTime” IncludeTimeValue=”TRUE”><Today /></Value>

You have to use IncludeTimeValue=”TRUE”.

You can use greator or equal like above and less or equal filter with AND operator in CAML above to work with date range.

If the date value is coming from your variable etc then you need to use SPUtility function and get the string required by CAML for date time variable.

DateTime CustomDate = DateTime.Now;
string strCustomDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(CustomDate);

This CAML Query below return the items based on MyDate with less than 10 days.
Basically using a Greator or Equal operatior and providing Today date - 10 days as a filter.

<Query>
<Where>
<Geq>
<FieldRef Name="MyDate" />
<Value Type="DateTime">
<Today OffsetDays="-10" />
</Value>
</Geq>
</Where>
</Query>
==========================================================

SPListItem.Update() throws error Operation is not valid due to the current state of the object.

Problem:
When running SPListItem.Update commands inside SPSecurity.RunWithElevatedPrivileges block in the .net application in the sharepoint virtual directory environment then you get error: Operation is not valid due to the current state of the object.

When you can add the procedure in the SPSecurity.RunWithElevatedPrivileges block then some time also Call Stack error has occured.
When you can install your webpart or Usercontrol in the sharepoint page then this type error is not occurred.
Instead you should instantiate the SPSite or SPWeb there and call Update afterwards.

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

SPSecurity.RunWithElevatedPrivileges to update SPRoleAssignment of an SPListItem

When you write custom code in Sharepoint webparts, your code will run with your credentials.
Not everybody has Full Control, so when a user has only read rights, the code will throw an access denied error when the code needs access to objects that are not in the scope of the user credentials.... (example: add the username in the ReadBy properties of an item).
What you need is impersonation, run your code with the help of a user who has just enough rights to run it. Sharepoint has a built-in function to accomplish this: SPSecurity.RunWithElevatedPrivileges, it runs with the System Account User.
Some things you should know when using SPSecurity.RunWithElevatedPrivileges:
  • in the delegate function, you must build a new SPSite/SPWeb object (like SPSite siteColl = new SPSite(App.SITE_COLLECTION_URL)) and you can't use the SPContext.Current.Web, because the SPContext runs with the current context (with current user).
  • Also set the AllowUnsafeUpdates property of the site/web where you will be updating/accessing stuff to true, to be sure you don't get an error like "The security validation for this page is invalid" (see more below). If you don't do it, you code will work, but when returning from the delegate function, the error will arise..
Code sample:
I run the "Elevated code" when the button btn is clicked in a webpart:

void btn_Click(object sender, EventArgs e)
{
{
SPSecurity.RunWithElevatedPrivileges(TestSec);
}
catch (Exception ex)
{
throw ex;
}
}

public void TestSec()
{
SPSite siteColl = new SPSite(App.SITE_COLLECTION_URL);SPWeb site = siteColl.AllWebs[App.WEB_NAME];
SPList list = site.Lists["Test"];

SPListItem testItem = list.GetItemById(1);
site.AllowUnsafeUpdates = true;SPRoleDefinition roleDefinitionContributor = site.RoleDefinitions.GetByType(SPRoleType.Contributor);
SPRoleAssignment roleAssignment = new SPRoleAssignment("DOMAIN\\USERNAME", "", "", "");
roleAssignment.RoleDefinitionBindings.Add(roleDefinitionContributor);
////Check for permission inheritance, and break if necessary
if (!testItem.HasUniqueRoleAssignments)
{
testItem.BreakRoleInheritance(false); //pass true to copy role assignments from parent, false to start from scratch
}
testItem.RoleAssignments.Add(roleAssignment);
testItem.Update();
site.AllowUnsafeUpdates = false;
siteColl.Close();
site.Close();

}
==================================================

some useful links....

No comments:

Post a Comment