The security validation for this page is invalid error trying to add sharepoint approval workflow to List in ListAdded eventreceiver - sharepoint-2010

What I am trying to do is to attach the OOTB sharepoint workflow [Approval Sharepoint - 2010] to each and every document library that ever gets created. To accomplish this I created a List Added event reciever and put this code in it -
public override void ListAdded(SPListEventProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUtility.ValidateFormDigest();
using (SPSite site = new SPSite(properties.SiteId))
{
using (SPWeb web = site.OpenWeb())
{
try
{
base.ListAdded(properties);
if (currentList is SPDocumentLibrary)
{
SPDocumentLibrary docLib = (SPDocumentLibrary)properties.List;
//workflows need a tasks and history list. Here we assume they exist
SPList taskList = web.Lists["Tasks"];
SPList historyList = web.Lists["Workflow History"];
//loop through the workfows in the web and grab the one we want by name
SPWorkflowTemplate wfTemp = null;
foreach (SPWorkflowTemplate wt in web.WorkflowTemplates)
{
if (wt.Name == "Approval - SharePoint 2010")
{
wfTemp = wt;
Common.AddToLog(web, "Found " + wt.Name + " in current web " +
web.Url, false);
break;
}
}
//Now add the workflow to the doc library
SPWorkflowAssociation workFlow = SPWorkflowAssociation.CreateListAssociation(wfTemp, wfTemp.Name, taskList, historyList);
workFlow.AllowManual = true;
workFlow.AutoStartChange = false;
workFlow.AutoStartCreate = true;
workFlow.AssociationData = null;
web.AllowUnsafeUpdates = true;
web.ValidateFormDigest();
docLib.WorkflowAssociations.Add(workFlow);
docLib.EnableModeration = true;
docLib.Update();
web.Update();
web.AllowUnsafeUpdates = false;
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
web.AllowUnsafeUpdates = false;
}
}
}
});
}
I am getting this error-
The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.
at this line
docLib.WorkflowAssociations.Add(workFlow);
Any any have any suggestions please ? Thanks for your feedback.

Why do you need "SPUtility.ValidateFormDigest()" at all?
Your code was running in an event receiver, not on a form or aspx page, there is nothing to validate.
Could you remove this line and try again?

I believe updating this code block:
web.AllowUnsafeUpdates = true;
web.ValidateFormDigest();
docLib.WorkflowAssociations.Add(workFlow);
docLib.EnableModeration = true;
docLib.Update();
web.Update();
web.AllowUnsafeUpdates = false;
and replacing it with:
web.Site.WebApplication.FormDigestSettings.Enabled = false;
docLib.WorkflowAssociations.Add(workFlow);
docLib.EnableModeration = true;
docLib.Update();
web.Update();
web.Site.WebApplication.FormDigestSettings.Enabled = true;
Let me know if this works for you or if you still encounter the same error.

Related

terminate button in console of my eclipse plugin

I have developed an eclipse plugin in xtext and I need to write some messages in console.
To do that, I have seen this site http://wiki.eclipse.org/FAQ_How_do_I_write_to_the_console_from_a_plug-in%3F and then I have implemented this code:
private static MessageConsole findConsole(String name) {
if (ConsolePlugin.getDefault() == null)
return null;
ConsolePlugin plugin = ConsolePlugin.getDefault();
IConsoleManager conMan = plugin.getConsoleManager();
IConsole[] existing = conMan.getConsoles();
for (int i = 0; i < existing.length; i++)
if (name.equals(existing[i].getName())) {
conMan.showConsoleView(existing[i]);
return (MessageConsole) existing[i];
}
// no console found, so create a new one
MessageConsole myConsole = new MessageConsole(name, null);
conMan.addConsoles(new IConsole[] { myConsole });
return myConsole;
}
public MessageConsoleStream getMessageStream() {
MessageConsole myConsole = findConsole("console");
if (myConsole != null) {
IWorkbench wb = PlatformUI.getWorkbench();
IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
IWorkbenchPage page = win.getActivePage();
String id = IConsoleConstants.ID_CONSOLE_VIEW;
IConsoleView view;
try {
view = (IConsoleView) page.showView(id);
view.display(myConsole);
return myConsole.newMessageStream();
} catch (PartInitException e) {
e.printStackTrace();
}
}
return null;
}
I have added org.eclipse.ui.console to plugin.xml > dependencies > required plugins.
When I want to print some message:
MessageConsoleStream out = getMessageStream();
out.println(...);
And it is working. But I need a "terminate button" in my console and it seems that this code isn't enough.
How can I do that?
Thanks.
That has nothing to do with the console at all. You want to create a viewContribution, which simply adds a button to the tool bar area of an existing view. There is also an example on stackoverflow. Or you might want to consult the Eclipse help on that topic.

Sharepoint 2010 EventReceiver for SPFolder adding

I have a document library in which we have added a custom folder content type in order to keep the Folder Owner in a custom field.
Now I am asked to set the default value of the "Add new" form to the Parent Folder Owner. I have tried this code below but the event fires after saving the new Folder. Could anyone pls help me? How can I set this default value before opening the form?
public override void ItemAdding(SPItemEventProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
try
{
this.EventFiringEnabled = false;
base.ItemAdding(properties);
if (properties.List.RootFolder.Name == "Documents")
{
SPWeb web = properties.List.ParentWeb;
SPList List = properties.List;
SPField fld = List.Fields["Folder Owner"];
SPUser usr = web.CurrentUser;
SPFieldUserValue curUser = new SPFieldUserValue();
curUser.LookupId = usr.ID;
SPFolder parentFolder = web.GetFolder(properties.AfterUrl.Substring(0,properties.AfterUrl.LastIndexOf("/")));
if (parentFolder.Item["Folder Owner"] == null)
{
fld.DefaultValue = curUser.ToString();
}
else
{
fld.DefaultValue = parentFolder.Item["Folder Owner"].ToString();
}
fld.Update();
List.Update();
}
}
catch (Exception)
{
}
finally
{
this.EventFiringEnabled = true;
}
});
}

Set the value of custom webpart property in c#

How to set the value of custom webpart property Programatically in C#.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite SiteCollection = new SPSite(mySiteGuid))
{
SPWeb myWeb = SiteCollection.OpenWeb(myWebGuid);
myWeb .AllowUnsafeUpdates = true;
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = null;
mgr = myWeb.GetLimitedWebPartManager ("default.aspx",System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
foreach (System.Web.UI.WebControls.WebParts.WebPart myWebPart in mgr.WebParts)
{
if (myWebPart.Title == "Other Webpart Name")
{
myWebPart.Visible = ! myWebPart.Visible;
myWeb.Update();
break;
}
}
}
});
I have a custom property in the webpart of type string to get the input from the user.
I wanted to updated the value of the property from c#.
Is there any way to set the value?
TIA
Try myWebPart.Update() instead of myWeb.Update().
Maybe it's a bit late for the answer, but here i let a piece of code i used for this.
var webCollection = new SPSite("http://mySharePointSite").AllWebs;
foreach (SPWeb web in webCollection)
{
var landingPageReference = #"/Pages/default.aspx";
var page = web.GetFile(landingPageReference);
if (!page.Exists)
continue;
page.CheckOut();
var spLimitedWebPartManager = web.GetLimitedWebPartManager(page.ServerRelativeUrl, PersonalizationScope.Shared);
foreach (WebPart webPartItem in spLimitedWebPartManager.WebParts)
{
if (webPartItem.Title.Equals("myWebPartTitle"))
{
// Specify Properties to change here
webPartItem.ChromeType = PartChromeType.Default;
webPartItem.Description = "AGAIN CHANGED";
// Save made changes
spLimitedWebPartManager.SaveChanges(webPartItem);
break;
}
}
page.CheckIn("Add Comment if desired");
page.Publish("Add Comment if desired");
web.Update();
web.Dispose();
}

How to programmatically set the task outcome (task response) of a Nintex Flexi Task?

Is there any way of set a Nintex Flexi task completion through Sharepoint's web services? We have tried updating the "WorkflowOutcome", "ApproverComments" and "Status" fields without success (actually the comments and status are successfully updated, however I can find no way of updating the WorkflowOutcome system field).
I can't use the Nintex Web service (ProcessTaskResponse) because it needs the task's assigned user's credentials (login, password, domain).
The Asp.net page doesn't have that information, it has only the Sharepoint Administrator credentials.
One way is to delegate the task to the admin first, and then call ProcessTaskResponse, but it isn't efficient and is prone to errors.
In my tests so far, any update (UpdateListItems) to the WorkflowOutcome field automatically set the Status field to "Completed" and the PercentComplete field to "1" (100%), ending the task (and continuing the flow), but with the wrong answer: always "Reject", no matter what I try to set it to.
Did you try this code: (try-cacth block with redirection does the trick)
\\set to actual outcome id here, for ex. from OutComePanel control
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldDecision] = 0;
taskItem[Nintex.Workflow.Common.NWSharePointObjects.FieldComments] = " Some Comments";
taskItem.Update();
try
{
Nintex.Workflow.Utility.RedirectOrCloseDialog(HttpContext.Current, Web.Url);
}
catch
{
}
?
Here are my code to change outcome of nintex flexi task. My problem is permission. I had passed admin token to site. It's solve the problem.
var siteUrl = "...";
using (var tempSite = new SPSite(siteUrl))
{
var sysToken = tempSite.SystemAccount.UserToken;
using (var site = new SPSite(siteUrl, sysToken))
{
var web = site.OpenWeb();
...
var cancelled = "Cancelled";
task.Web.AllowUnsafeUpdates = true;
Hashtable ht = new Hashtable();
ht[SPBuiltInFieldId.TaskStatus] = SPResource.GetString(new CultureInfo((int)task.Web.Language, false), Strings.WorkflowStatusCompleted, new object[0]);
ht["Completed"] = true;
ht["PercentComplete"] = 1;
ht["Status"] = "Completed";
ht["WorkflowOutcome"] = cancelled;
ht["Decision"] = CommonHelper.GetFlexiTaskOutcomeId(task, cancelled);
ht["ApproverComments"] = "cancelled";
CommonHelper.AlterTask((task as SPListItem), ht, true, 5, 100);
task.Web.AllowUnsafeUpdates = false;
}
}
}
}
}
}
public static string GetFlexiTaskOutcomeId(Microsoft.SharePoint.Workflow.SPWorkflowTask task, string outcome)
{
if (task["MultiOutcomeTaskInfo"] == null)
{
return string.Empty;
}
string xmlOutcome = HttpUtility.HtmlDecode(task["MultiOutcomeTaskInfo"].ToString());
if (string.IsNullOrEmpty(xmlOutcome))
{
return string.Empty;
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlOutcome);
var node = doc.SelectSingleNode(string.Format("/MultiOutcomeResponseInfo/AvailableOutcomes/ConfiguredOutcome[#Name='{0}']", outcome));
return node.Attributes["Id"].Value;
}
public static bool AlterTask(SPListItem task, Hashtable htData, bool fSynchronous, int attempts, int milisecondsTimeout)
{
if ((int)task[SPBuiltInFieldId.WorkflowVersion] != 1)
{
SPList parentList = task.ParentList.ParentWeb.Lists[new Guid(task[SPBuiltInFieldId.WorkflowListId].ToString())];
SPListItem parentItem = parentList.Items.GetItemById((int)task[SPBuiltInFieldId.WorkflowItemId]);
for (int i = 0; i < attempts; i++)
{
SPWorkflow workflow = parentItem.Workflows[new Guid(task[SPBuiltInFieldId.WorkflowInstanceID].ToString())];
if (!workflow.IsLocked)
{
task[SPBuiltInFieldId.WorkflowVersion] = 1;
task.SystemUpdate();
break;
}
if (i != attempts - 1)
{
Thread.Sleep(milisecondsTimeout);
}
}
}
var result = SPWorkflowTask.AlterTask(task, htData, fSynchronous);
return result;
}

Adding site collection to Web Application logged in as FBA in SharePoint 2010

Hi
I am trying to create Site collection under web application which is configured as Claim based authentication and the code is as follow:
SPSecurity.RunWithElevatedPrivileges(delegate {
using (SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.RootWeb)
{
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
try
{
SPWebApplication web_App = web.Site.WebApplication;
web_App.Sites.Add(SiteUrl, SiteTitle, Description, Convert.ToUInt32(Constants.LOCALE_ID_ENGLISH), SiteTemplate, OwnerLogin, "testuser", OwnerEmail);
}
catch (Exception ex)
{
string s = ex.Message + " " + ex.StackTrace;
throw;
}
finally
{
web.AllowUnsafeUpdates = false;
site.AllowUnsafeUpdates = false;
}
}
}
});
Here I am passing "OwnerLogin" as "CustomMembership:UserName". But web_App.Sites.Add is throwing a wierd error like "ex = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.}". Any help in this regard is really appreciated.
Regards,
Paddy
Your elevation code is wrong, you need to create completely new SPSite and SPWeb references. I normal prefix them with "c" to show me that it is in a different context.
SPSecurity.RunWithElevatedPrivileges(delegate() {
using (SPSite csite = new SPSite(SPContext.Current.Site.ID)) {
using (SPWeb cweb = csite.OpenWeb(SPContext.Current.Site.RootWeb.ID)) {
//do stuff
}
}
});
The OwnerLogin parameter should not contain the CustomMembership: prefix - pass plain UserName as a value of this parameter.
By the way, your method of getting the Web Application object is unnecessarily complicated - use something like this:
SPWebApplication webApplication = SPWebApplication.Lookup(new System.Uri("Web-Application-URL"));