Sitecore WFFM Save To Database failed - sitecore

I get the following error in the Sitecore log file. On the Save To Database action in a WFFM form. Web Forms for Marketers 2.4 rev. 141008.
I have a custom WFMDataProvider that just return a connectionString. I get the error on production CD and not on CMS. (i'm not using the remoteWfmService) What am I missing?
3292 09:42:32 ERROR Save To Database failed.
Exception: System.Reflection.ReflectionTypeLoadException
Message: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
Source: mscorlib
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
at System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadTypesFromAssembly()
at System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load()
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData)
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage, Object& loaderCookie, Dictionary`2& typesInLoading, List`1& errors)
at System.Data.Metadata.Edm.ObjectItemCollection.LoadTypesExpensiveWay(Assembly assembly)
at System.Data.Objects.DataClasses.RelationshipManager.TryGetRelationshipType(IEntityWrapper wrappedOwner, Type entityClrType, String relationshipName, AssociationType& associationType)
at System.Data.Objects.DataClasses.RelationshipManager.GetRelatedEndInternal(String relationshipName, String targetRoleName)
at System.Data.Objects.DataClasses.RelationshipManager.GetRelatedReference[TTargetEntity](String relationshipName, String targetRoleName)
at Sitecore.Forms.Data.Field..ctor(IField field, Form form)
at Sitecore.Forms.Data.DataProviders.WFMDataProvider.<>c__DisplayClass7.<InsertForm>b__6(IField f)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at Sitecore.Forms.Data.DataProviders.WFMDataProvider.InsertForm(IForm form)
at Sitecore.Forms.Data.DataManager.InsertForm(ID formId, AdaptedResultList fields, ID sessionID, String data)
at Sitecore.Form.Submit.SaveToDatabase.Execute(ID formid, AdaptedResultList fields, Object[] data)
3292 09:42:32 WARN Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
Exception: System.Reflection.ReflectionTypeLoadException
Message: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
Source: mscorlib
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
at System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadTypesFromAssembly()
at System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load()
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData)
at System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage, Object& loaderCookie, Dictionary`2& typesInLoading, List`1& errors)
at System.Data.Metadata.Edm.ObjectItemCollection.LoadTypesExpensiveWay(Assembly assembly)
at System.Data.Objects.DataClasses.RelationshipManager.TryGetRelationshipType(IEntityWrapper wrappedOwner, Type entityClrType, String relationshipName, AssociationType& associationType)
at System.Data.Objects.DataClasses.RelationshipManager.GetRelatedEndInternal(String relationshipName, String targetRoleName)
at System.Data.Objects.DataClasses.RelationshipManager.GetRelatedReference[TTargetEntity](String relationshipName, String targetRoleName)
at Sitecore.Forms.Data.Field..ctor(IField field, Form form)
at Sitecore.Forms.Data.DataProviders.WFMDataProvider.<>c__DisplayClass7.<InsertForm>b__6(IField f)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at Sitecore.Forms.Data.DataProviders.WFMDataProvider.InsertForm(IForm form)
at Sitecore.Forms.Data.DataManager.InsertForm(ID formId, AdaptedResultList fields, ID sessionID, String data)
at Sitecore.Form.Submit.SaveToDatabase.Execute(ID formid, AdaptedResultList fields, Object[] data)
at Sitecore.Form.Core.Submit.SubmitActionManager.ExecuteSaving(ID formID, ControlResult[] list, ActionDefinition[] actions, Boolean simpleAdapt, ID sessionID)
3292 09:42:32 WARN Web Forms for Marketers: an exception: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. has occured while trying to execute an action.

I have found that the MSCaptcha.dll is not deployed. Normally you get a Exception when this file is missing. But in this case the App_Config\include\Captcha.config was also missing.
If you remove this 2 files it looks like everything works fine with a form (without captcha) but the save to database action does not work and needs this MSCaptcha.dll. And so gives the error mentioned in the question.
I am almost certain that this is the issue. I only need a deploy to confirm.

Related

Sitecore Commerce Business Tools doesn't load

I'm facing a problem with loading the Sitecore Commerce Business Tools on my local machine. I don't get any error in my browser which you can check on the following screenshoot, but the page is not initialized:
Seems like the operations GetNavigationView() and GetLanguageView() are stuck on getting data, but I couldn't figure out what could be the problem.
As preparation steps, I did the Sitecore Commerce Bootstrap, and Environment Initialization via Postman and everything went ok.
In the CommerceAuthoring_Sc9\wwwroot\config.json I set up the certificate thumbprint and here is what I have in the AppSettings:
"AppSettings": {
...
"SitecoreIdentityServerUrl": "https://localhost:5050",
"AllowedOrigins": [
"https://localhost:4200",
"https://sxa.storefront.com"],
"AntiForgeryEnabled": false,
"UseHttpsInKestrel": true,
"SslPort": 5000,
"SslPfxPath": "wwwroot/localhost.pfx",
"SslPfxPassword": "sitecore"
}
Also in the CommerceAuthoring_Sc9\wwwroot\bootstrap\Global.json I added all the environments I use.
Here you can check some of the errors I noticed in the CommerceAuthoring logs:
ERROR ImportMinion Error Access to the path 'C:\Import.lock' is denied. Inner
...
ERROR SitecoreConnectionManager.Error: Message=Invalid URI: The hostname could not be parsed.|Trace=
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at Sitecore.Commerce.Plugin.Management.SitecoreConnectionManager.ProcessRequest(CommerceContext commerceContext, String action, String method, ItemModel itemModel) System.UriFormatException: Invalid URI: The hostname could not be parsed.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at Sitecore.Commerce.Plugin.Management.SitecoreConnectionManager.ProcessRequest( CommerceContext commerceContext, String action, String method, ItemModel itemModel)
...
ERROR SitecoreConnectionManager.Error: Message=One or more errors occurred.|Trace= at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at Sitecore.Commerce.Plugin.Management.SitecoreConnectionManager.ProcessRequest(CommerceContext commerceContext, String action, String method, ItemModel itemModel)
System.AggregateException: One or more errors occurred. ---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at Sitecore.Commerce.Plugin.Management.SitecoreConnectionManager.ProcessRequest(CommerceContext commerceContext, String action, String method, ItemModel itemModel)
---> (Inner Exception #0) System.Threading.Tasks.TaskCanceledException: A task was canceled.<---
...
ERROR Management.block.getitemsbypath: Sitecore Item Service Get item failed, Item /sitecore/Commerce/Commerce Control Panel/Commerce Engine Settings/Commerce Terms/BusinessTools/ViewNames not found.
I checked some solutions that were already mentioned across the forums but no luck fo far.
I'll very appreciate if you have any advice for me!
Updated
After some time, we got the following error on the UAT env. but I'm not sure if we can do a Commerce Bootstrap there without losing our data:
INFO Management.block.getitembypath./sitecore/Commerce/Commerce Control Panel/Storefront Settings/Storefronts/CommerceEngineDefaultStorefront|en
INFO Management.block.getitembypath./sitecore/Commerce/Commerce Control Panel/Storefront Settings/Storefronts/CommerceEngineDefaultStorefront: Language=en
ERROR SitecoreConnectionManager.Error: Message=Unexpected character encountered while parsing value: <. Path '', line 0, position 0.|Trace= at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Sitecore.Commerce.Plugin.Management.SitecoreConnectionManager.GetItemByPath(CommerceContext commerceContext, String path, String language)
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
at Newtonsoft.Json.JsonTextReader.ParseValue()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
at Sitecore.Commerce.Plugin.Management.SitecoreConnectionManager.GetItemByPath(CommerceContext commerceContext, String path, String language)
ERROR Management.block.getitembypath: Sitecore Item Service Get item failed, Item /sitecore/Commerce/Commerce Control Panel/Storefront Settings/Storefronts/CommerceEngineDefaultStorefront not found.
ERROR CtxMsg.Error.InvalidShop: Text=Shop 'CommerceEngineDefaultStorefront' does not exist.
ERROR PipelineAbort:Shop 'CommerceEngineDefaultStorefront' does not exist.
ERROR CtxMsg.Error.InvalidShop: Text=Shop 'CommerceEngineDefaultStorefront' does not exist.
ERROR CommerceController.OnActionExecuting.BadRequest: Code=Error|TermKey=InvalidShop|Text=Shop 'CommerceEngineDefaultStorefront' does not exist.
Also, the storefront item 'CommerceEngineDefaultStorefront' exist in the database that is specified in the PlugIn.Content.PolicySet-1.0.0.json file. I feel some of the json files has invalid params/values or the formatting is wrong, but I couldn't find any lead, furthermore, they haven't been changed recently.
Answer
Eventualy, it appeared the our CD was down for some period.

Sitecore: Value cannot be null. Parameter name: uri

Exception: System.ArgumentNullException
Message: Value cannot be null.
Parameter name: uri
Source: Sitecore.Kernel
I was editing a placeholder item in a local
Sitecore 8.1 (rev. 151207) instance when I got this error. Now I can't edit, delete, or reset it (or its parent folders). I also can't read the item in the content editor as the error pops up when I click on the parent folder. I've tried deleting/editing it and it's parent folder from the content editor, through code, and through PowerShell commands but the same error always shows.
I've also tried replacing my configs and bin folders with my backup copies, clearing cache, restarting IIS and the app pool, but nothing has helped.
I'm completely stuck. Does anyone know how to fix this?
Edit:
The full error in the logs is:
Exception: System.ArgumentNullException
Message: Value cannot be null.
Parameter name: uri
Source: Sitecore.Kernel
at Sitecore.Diagnostics.Assert.ArgumentNotNull(Object argument, String argumentName)
at Sitecore.Data.ItemUri..ctor(ItemUri uri)
at Sitecore.Data.Items.Item.GetItemUriFromSourceItem()
at Sitecore.Data.Items.Item.get_SourceUri()
at Sitecore.Data.Items.Item.get_Source()
at Sitecore.Data.Fields.Field.GetSourceItem()
at Sitecore.Data.Fields.Field.GetInheritedValue(Boolean allowStandardValue)
at Sitecore.Pipelines.GetFieldValue.GetInheritedValue.Process(GetFieldValueArgs args)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Data.Fields.Field.GetValue(Boolean allowStandardValue, Boolean allowDefaultValue, Boolean allowFallbackValue, Boolean allowInheritValue, Boolean allowInnerValue)
at Sitecore.Pipelines.ItemProvider.GetItem.GetLanguageFallbackItem.IsItemFallbackEnabled(Item item)
at Sitecore.Pipelines.ItemProvider.GetItem.GetLanguageFallbackItem.Process(GetItemArgs args)
at (Object , Object[] )
at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)
at Sitecore.Data.Managers.PipelineBasedItemProvider.ExecuteAndReturnResult[TArgs,TResult](String pipelineName, String pipelineDomain, Func`1 pipelineArgsCreator, Func`1 fallbackResult)
at Sitecore.Data.Managers.ItemManager.GetItem(ID itemId, Language language, Version version, Database database, SecurityCheck securityCheck)
at Sitecore.Nexus.Data.DataCommands.GetChildrenCommand.Execute(Item )
at Sitecore.Data.Engines.EngineCommand`2.Execute()
at Sitecore.Data.Managers.ItemProvider.GetChildren(Item item, ChildListOptions options)
at Sitecore.Data.Managers.ItemProvider.GetChildren(Item item, SecurityCheck securityCheck, ChildListOptions options)
at Sitecore.Data.Managers.PipelineBasedItemProvider.ExecuteAndReturnResult[TArgs,TResult](String pipelineName, String pipelineDomain, Func`1 pipelineArgsCreator, Func`1 fallbackResult)
at Sitecore.Data.Managers.PipelineBasedItemProvider.GetChildren(Item item, SecurityCheck securityCheck)
at Sitecore.Collections.ChildList.Populate(ChildListOptions options)
at Sitecore.Shell.Framework.Pipelines.DeleteItems.GetItemClones(Item item, Boolean processChildren)
at Sitecore.Shell.Framework.Pipelines.DeleteItems.GetItemClones(Item item, Boolean processChildren)
at Sitecore.Shell.Framework.Pipelines.DeleteItems.GetItemClones(List`1 items)
at Sitecore.Shell.Framework.Pipelines.DeleteItems.GetCheckCloneLinksMessage(List`1 items)
at Sitecore.Shell.Framework.Pipelines.DeleteItems.CheckCloneLinks(ClientPipelineArgs args)
The exception you provided occurs because you have nonempty invalid value in the __Source Item - {19B597D3-2EDD-4AE2-AEFE-4A94C7F10E31} field in your item. __Source Item is responsible for storing the original item URI for the clone items.
I don't know how you achieved that because there is a processor ValidateCloneSourceModifications in the saveItem pipeline that prevents of saving items with invalid __Source Item field.
I was able to reproduce your exception by changing the field value in the DB.
How to fix:
Find you broken field in the master DB -> SharedFields table. The FieldId is '19B597D3-2EDD-4AE2-AEFE-4A94C7F10E31'.
Fix it. It should be something like sitecore://master/{AE76A034-9491-4B83-99F5-39F227D6FB59}, where the ID is the original item id. You could also just set '' as a value, but it will remove the binding to the original item.
Clear cache.
It must help.
You can try the DB Browser /sitecore/admin/dbbrowser.aspx with this tool you can also delete items.
If this DB Browser admin tools fail, then I'm curious what's in the master database, check directly in sql what make this item special is than an option.

Sitecore 8: Getting application error when removing broken links

I try to remove broken links on my master database using the tool provided by the following url.
http://mysite/sitecore/admin/RemoveBrokenLinks.aspx
After some time the process being interrupted and I got the following error on Sitecore log.
6220 10:56:26 INFO Removing broken link- Database: master, Item: /sitecore/content/Home/blog/2012/January/13/totaljobs-group-benefit-from-expert-sitecore-consultancy-delivered-by-codehouse, Field: __Renderings, Target item database: master, Target item path: /sitecore/content/global/Codehouse Widgets/Mini Form Widgets/newsletter-subscription
6220 10:56:26 INFO Done
6220 10:56:26 INFO Removing broken link- Database: master, Item: /sitecore/content/Home/blog/2012/January/13/totaljobs-group-benefit-from-expert-sitecore-consultancy-delivered-by-codehouse, Field: __Renderings, Target item database: master, Target item path: /sitecore/content/global/Codehouse Widgets/Mini Form Widgets/sitecore-demo-text-only
6220 10:56:26 INFO Done
6220 10:56:26 ERROR Error looking up template field. Field id: {00000000-0000-0000-0000-000000000000}. Template id: {0437FEE2-44C9-46A6-ABE9-28858D9FEE8C}
Exception: System.ArgumentOutOfRangeException
Message: Null ID is not allowed.
Parameter name: fieldID.
Actual value was {00000000-0000-0000-0000-000000000000}.
Source: Sitecore.Kernel
at Sitecore.Data.Templates.TemplateSection.GetField(ID fieldID)
at Sitecore.Data.Templates.Template.DoGetField(ID fieldID, String fieldName, Stack`1 stack)
at Sitecore.Data.Templates.Template.DoGetField(ID fieldID, String fieldName, Stack`1 stack)
at Sitecore.Data.Templates.Template.DoGetField(ID fieldID, String fieldName, Stack`1 stack)
at Sitecore.Data.Templates.Template.GetField(ID fieldID)
6220 10:56:26 ERROR Application error.
Exception: System.Web.HttpUnhandledException
Message: Exception of type 'System.Web.HttpUnhandledException' was thrown.
Source: System.Web
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Nested Exception
Exception: System.ArgumentOutOfRangeException
Message: Null ID is not allowed.
Parameter name: fieldID.
Actual value was {00000000-0000-0000-0000-000000000000}.
Source: Sitecore.Kernel
at Sitecore.Data.Templates.TemplateSection.GetField(ID fieldID)
at Sitecore.Data.Templates.Template.DoGetField(ID fieldID, String fieldName, Stack`1 stack)
at Sitecore.Data.Templates.Template.DoGetField(ID fieldID, String fieldName, Stack`1 stack)
at Sitecore.Data.Templates.Template.DoGetField(ID fieldID, String fieldName, Stack`1 stack)
at Sitecore.Data.Templates.Template.GetField(ID fieldID)
at Sitecore.Data.Fields.Field.GetTemplateField()
at Sitecore.Data.Fields.FieldTypeManager.GetField(Field field, String runtimeValue)
at Sitecore.sitecore.admin.RemoveBrokenLinks.FixBrokenLinksInDatabase(Database database, Boolean serializeItem)
at Sitecore.sitecore.admin.RemoveBrokenLinks.FixBrokenLinksOnClick(Object sender, EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Can you made a cleanup database before doing RemoveBrokenLinks?
Tu clean up database go to ->Control Panel->Database->Clean up Database
I guess you have some orphaned items (items without templates)
When you are doing a Cleanup Database next tasks are executed:
Removes items that have parents, but the parents are not in the item
tree.
Removes invalid language data.
Removes fields for non existing items.
Removes orphaned items.
Removes unused blob records.
Removes fields from orphaned items removed in step 4.
Rebuilds the Descendants table (which stores parent/child relationships).
Clears all caches.
It's quite odd that it didn't resolve the issue by using Clean up Database or by Rebuilding the link database.
Few questions:
During the clean up and rebuilding process, did you find any
relevant entry related to the issue in your Sitecore log? If yes, could you please paste it here, as well.
Reading the stack traces you provided, it looks like that there is/are orphaned template(s) and that's the reason why it throws an Exception: System.ArgumentOutOfRangeException. Could you please repeat the same rebuild and clean up process, and let us know the result of the 2nd run?
Alternatively, if you find repeating the process a very time consuming and performance heavy then you might want to consider creating a LinkDatabaseRefreshTool.aspx file, put it inside the \Website\admin folder with the following code as your processor:
foreach (var specificItem in itemList)
{
specificItem.Editing.BeginEdit();
Sitecore.Globals.LinkDatabase.UpdateReferences(specificItem);
specificItem.Editing.EndEdit();
}
Create an asp:Textbox and a submit button that invokes this method OnClick. Open the tool by accessing the http:\\YOUR_WEBSITE\admin\LinkDatabaseRefreshTool.aspx
I experienced the same issue before, and I just rebuild it again and that resolved the issue. Maybe just the same solution on your end, still worth a try.

Sitecore|WFFM| Custom Error Message with details| on Same Page with Form

I have a Web Form for Marketer set up done for one of my Pages.
I have Custom Submit Action written for it as shown below in the code snippet -
public class **CustomFormSubmit : ISaveAction**
{
public void Execute(ID formid, AdaptedResultList fields, params object[] data)
{
try
{
**//var returnValue= Custom Logic to save form data // returns true or false**
}
catch (Exception ex)
{
Logger.Log(ex.Message + ":" + builder, ExceptionCategory.Error);
throw;
}
}
In my above Web form - Success Mode is - SuccessMode/Redirect and I have a success Page configured for it.
My requirement in above scenario is to keep user on the same Page(with Form) if returnValue is false . (as shown in above code snippet)
Can anyone Please guide me in the above scenario as - how to keep user on the same Page with values filled in the form so that user can submit it again.
Product Details - 7.2 rev. 141226 , Web Forms for Marketers 2.4 rev.140117
To add further details -
I am not sure how can I go back to my page instead of the redirection in case if return is false in the above code snippet.
As soon the submit button is clicked the above function- Execute- gets called.
How do I go back to the Page - Do I need to override any function or customize something.
If any exception comes while saving data- then the control goes back to the same Page with all values filled by user retained -with the Save Action Failed Message which is configured in Sitecore .
So my requirement will be to go to to the form as happening in case of Exception when false comes as return value while saving data and to put customised Error Messages which might change each time, so not statically configured ,rather a dynamic one.
Thanks!
Saurabh
One option will be to redirect to the original page with the Form on.
Enable your form to populate the fields via Query String using the ReadQueryString property, via Presentation Details of the Form Renderer:
So on false of your Save Action you create a collection of query strings with the name of each Field, as it appears in the Form, followed by the User's value.
The code below will loop through all your fields and arrange them into a QueryString with its FieldName and Value;
string urlOfForm = HttpContext.Current.Request.Url.AbsolutePath;
var queryString = new StringBuilder("?");
foreach (AdaptedControlResult field in fields)
{
queryString.Append(string.Format("{0}={1}&", field.FieldName, field.Value));
}
urlOfForm = urlOfForm + queryString;
HttpContext.Current.Response.Redirect(urlOfForm);
Sitecore will then automatically populate the appropriate fields with the values, achieving your requirement.
EDIT
I have found that most Exceptions thrown will take the user back to the Form with their values populated. You can then pass in the cause of the failure to write to your CRM. See below for Example
if (submitFailed)
{
throw new Exception("The email address entered already exists in our System");
}
The complexity then comes in dynamically swapping out the Save Action Failed Message to show this Exception Message. All posts I find about custom Save Action Message state the only real approach is to redirect via your Custom Save Action to a different page showing a different message. Which is not suitable to your requirements.
I have found the pipeline Args you are going to need to patch FormSubmitFailedArgs and SubmitFailedArgs. The Former will need the following change
public FormSubmitFailedArgs(ID formID, AdaptedResultList fields, ID actionFailed, Exception ex)
: base(formID, actionFailed, ex)
{
this.Fields = fields;
this.ErrorMessage = ex.Message;
}
and the Latter will need
public SubmitFailedArgs(ID formID, ID actionFailed, string errorMessage, Exception innerException)
{
this.FormID = formID;
this.ActionFailed = actionFailed;
this.ErrorMessage = innerException.Message;
this.InnerException = innerException;
}
Location and Styling of Submit Message:
You need to find the FormRender sublayout file, this is defaulted to website\sitecore modules\Web\Web Forms for Marketers\Control\SitecoreSimpleFormAscx.ascx inside there you will find a compont called SubmitSummary this renders out the submit message so move it to where you require.
Also note it references the CssClass scfSubmitSummary this is what you will need to target to change the styling of the Message. This Answer is already REALLY long so I won't give a blow by blow how to change the styling of that class, see here for example - http://www.awareweb.com/awareblog/10-1-13-wffmguide
Pipeline Patching
I've dug in deeper, in order to use the custom Args we created for using the exception error message you will need to control the Pipeline which ultimately uses those Args, this is the processor Sitecore.Form.Core.Pipelines.FormSubmit.FormatMessage, Sitecore.Forms.Core in the <errorSubmit> Pipeline.
From my investigation it shouldn't take much effort then its a matter of patching it, you can modify if the Sitecore.Forms.config directly or use patch:instead from a config file within the App_Config/Includes folder - see here for more info.
One option would be to create a Custom Form Verification Action. You could save the data here, although it would be better to verify the data against your API here and then save the data in custom save action, simply since this seems more logical as to how WFFM was meant to function.
using Sitecore.Data;
using Sitecore.Form.Core.Controls.Data;
using Sitecore.Form.Core.Submit;
using System;
using System.Collections.Generic;
namespace Custom.WFFM
{
public class CustomVerificationStep : BaseCheckAction
{
public string FailedMessage { get; set; }
public override void Execute(ID formid, IEnumerable<ControlResult> fields)
{
// Call your API
// You have access to the fields, so you can pass them through as parameters to your if needed
bool flag = ServiceAPI.ValidateUserData(param1, param2, etc);
if (!flag)
{
throw new Exception(string.Format(this.FailedMessage ?? "There was an error while verifying the data against the service call"));
}
}
public override ActionState QueryState(ActionContext context)
{
return ActionState.DisabledSingleCall;
}
}
}
Create the corresponding Verification Action under /sitecore/system/Modules/Web Forms for Marketers/Settings/Actions/Form Verification:
You can change the error message by setting it in the Parameters field as <FailedMessage>Custom Failed Error Message</FailedMessage>.
And then add your verification step to your form:
If you need a different error message per form then you can set the error message to display from the Error Messages tab.
The user will then be returned to the same without any of the save actions being called and the form fields still filled in.

SharePoint SoapServerException calling GetListItems web service

I have the following statement in my code:
System.Xml.XmlNode items = lstWebs.GetListItems(
"Tasks", string.Empty, listQuery, listViewFields,
string.Empty, listQueryOptions, WorkspaceId);
When executing this, the following exception occurs:
Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.
Exception Source is:
System.Web.Services
Stack Trace:
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at ImpersonationConsoleApp.MossLists.Lists.GetListItems(String listName, String viewName, XmlNode query, XmlNode viewFields, String rowLimit, XmlNode queryOptions, String webID) in C:\Documents and Settings\david\My Documents\_Dew02SiteCreator\DeWProjectStarter\ImpersonationConsoleApp\Web References\MossLists\Reference.cs:line 435
at ImpersonationConsoleApp.Program.DeleteTasksIfNotExist(DataRow[] drTasksdel, String siteURL) in C:\Documents and Settings\david\My Documents\_Dew02SiteCreator\DeWProjectStarter\ImpersonationConsoleApp\Program.cs:line 1384
I have confirmed the site URL and it is fine.
Could you please help on why the exception is occurring? Do I need to reset IIS?
please find the detail.
SoapException.InnerException is Null.
However the soapExcetion.Detail.InnerText is showing: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
Is the name tasks also the actual listname in the url? i.e. http://siteurl/lists/tasks? is the list in a subsite and are you using the service under the site-collection?
IF the list is in a subsite the use http://sitecollectionurl/subsite/_vti_bin/lists.asmx as the Service url, otherwise the lists.asmx will try to find the tasks list in the rootweb instead of the subsite.
The signature for GetListItems is
GetListItems(ListID, "", queryNode, viewFieldsNode, Nothing, queryOptionsNode, Nothing)
Try simplifying queryNode, viewFieldsNode and queryOptionsNode to the minimal.
In VB.NET
Dim caml = New XmlDocument
Dim queryNode = caml.CreateElement("Query")
Dim viewFieldsNode = caml.CreateElement("ViewFields")
Dim queryOptionsNode = caml.CreateElement("QueryOptions")
queryOptionsNode.InnerXml = "<ViewAttributes Scope=""Recursive"" /><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>"
In C#
var caml = new XmlDocument();
var queryNode = caml.CreateElement("Query");
var viewFieldsNode = caml.CreateElement("ViewFields");
var queryOptionsNode = caml.CreateElement("QueryOptions");
queryOptionsNode.InnerXml = "<ViewAttributes Scope=\"Recursive\" /><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>";
If it works, then the web service setup is correct.
When I had the mentioned problem, it was my invalid XML that caused it. There is a missing 'type' attribute on the 'Value' element of the 'Where' element in queryNode. I found it here from Microsoft.
Type | Required Text. Specifies the data type for the value contained by this element.
It works after adding the Type attribute. Check if any missing requirements for the xml in one of the nodes mentioned above?
Have you tried running with elevated permissions, it looks like the running user does not hav sufficient privileges to query the data...
SPSecurity.RunWithElevatedPrivileges