We are using WFFM 2.4 Version 151103, Sitecore 7.2. Created custom validation for MVC form. When it returns a failed ValidationResult, the field on the form does not highlight and the error message is not displayed in the information block under the field. Here is the Model code:
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Sitecore.Data.Items;
using Sitecore.Forms.Mvc.ViewModels;
using Sitecore.Forms.Mvc.ViewModels.Fields;
using Sitecore.Forms.Mvc.Validators;
using Frb.Atl.Extensions.WFFM.CustomValidators;
namespace Frb.Atl.Extensions.WFFM.Models
{
public class TourSingleLineTextField : SingleLineTextField
{
[AtlantaTourParticipantsAttribute("tourProperty")]
[DataType(DataType.Text)]
public override string Value { get; set; }
}
}
And the custom MVC validator:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Web.Mvc;
using System.Linq;
using Sitecore.Diagnostics;
using Sitecore.Forms.Mvc.Validators;
using Frb.Atl.Extensions.WFFM.Models;
using Sitecore.Forms.Mvc.Interfaces;
using Sitecore.Forms.Mvc.ViewModels;
using Sitecore.Forms.Mvc.Validators.Rules;
using Sitecore.Forms.Mvc.ViewModels.Fields;
namespace Frb.Atl.Extensions.WFFM.CustomValidators
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public class AtlantaTourParticipantsAttribute : DynamicValidationBase
{
public AtlantaTourParticipantsAttribute(string tourProperty)
{
Assert.ArgumentNotNullOrEmpty(tourProperty, "tourProperty");
this.TourProperty = tourProperty;
}
public string TourProperty { get; set; }
public string Participants { get; set; }
public int MaxParticipants { get; set; }
public string ErrorMessage = string.Empty;
public const int MinParticipants = 10;
public List<int> m60 = new List<int>(new int[] {12, 11, 10, 9, 5, 4, 3, 2, 1});
protected override ValidationResult ValidateFieldValue(IViewModel TourSingleLineTextField, object value, ValidationContext validationContext)
{
var fieldModel = this.GetModel<TourSingleLineTextField>(validationContext);
var tourSingleLineTextField = validationContext.ObjectInstance as TourSingleLineTextField;
var Month = DateTime.Now.ToString("MM");
int month = 0;
int participants = 0;
int.TryParse(Month, out month);
int.TryParse(fieldModel.Value.ToString(), out participants);
if (m60.Contains(month))
MaxParticipants = 60;
else
MaxParticipants = 30;
if (participants >= 10 && participants <= MaxParticipants)
{
return ValidationResult.Success;
}
else
{
ErrorMessage = "Number of participants must be between 10 and " + MaxParticipants.ToString() + ".";
return new ValidationResult(ErrorMessage);
}
}
}
}
Has anyone else experienced this behavior in WFFM? Any resolution if you have?
TIA
The cause of this issue was not in the custom field type or validation code. The problem was missing analytics config files. The form would fail before it ever got to the custom validation. Replaced the analytics files and the validation began working correctly.
Related
I am working in DyanmoDB.In My project i have to dynamically set the database name and i have to load the database dynamically. This is my code
using UnityEngine;
using System.Collections;
using Amazon.DynamoDBv2.DataModel;
using System.Collections.Generic;
using Amazon.DynamoDBv2;
using UnityEngine.UI;
using UnityEngine;
using System.Collections;
using Amazon.DynamoDBv2;
using UnityEngine.UI;
using Amazon;
namespace AWSSDK.Examples
{
public class HighLevel3 : DynamoDbBaseExample
{
private IAmazonDynamoDB _client;
private DynamoDBContext _context;
public Text resultText;
public Button back;
public Button createOperation;
public Button updateOperation;
public Button deleteOperation;
public string S_tablefieldset;
string bookID;
int bookID1 = 9;
public string Email;
private DynamoDBContext Context
{
get
{
if (_context == null)
_context = new DynamoDBContext(_client);
return _context;
}
}
void Awake()
{
back.onClick.AddListener(BackListener);
createOperation.onClick.AddListener(PerformCreateOperation);
_client = Client;
S_tablefieldset = "Orders";
HighLevelTableExample.GetDynamoDbOperationConfig(S_tablefieldset);
}
void Start()
{
bookID = SystemInfo.deviceUniqueIdentifier;
System.Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "Orders");
PerformCreateOperation();
}
public static DynamoDBOperationConfig GetDynamoDbOperationConfig(string dynamoDbTable)
{
Debug.Log("The Table name is " + dynamoDbTable);
var tableName = System.Environment.GetEnvironmentVariable("MONO_REFLECTION_SERIALIZER");
Debug.Log("The Table name is" + tableName);
DynamoDBOperationConfig config = new DynamoDBOperationConfig()
{
// OverrideTableName =
OverrideTableName = tableName
};
return config;
}
public void PerformCreateOperation()
{
Debug.Log(" I am in Perform Create Operation is working fine and good");
Book12 myBook = new Book12
{
OrderID = bookID,
OrderItem = 50,
};
// Save the book.
var tableName = System.Environment.GetEnvironmentVariable("TABLE_NAME");
Context.SaveAsync(myBook, new DynamoDBOperationConfig {
OverrideTableName = tableName });
}
}
public class Book12
{
[DynamoDBHashKey] // Hash key.
public string OrderID { get; set; }
[DynamoDBProperty]
public string UserName { get; set; }
[DynamoDBProperty]
}
}
While doing the above i received the error in
error CS1503: Argument 2: cannot convert from
'Amazon.DynamoDBv2.DataModel.DynamoDBOperationConfig' to
Amazon.DynamoDBv2.AmazonDynamoDBCallback'
How to solve the error.
I trained a model using pytorch
I exported it to onnx format and tested in python that it works (it does)
I want to know how I can use this in ml.net in c#
The usage in python looks like this
the model in netorn looks like
I found an example that uses
using the packages Microsoft.ML, Microsoft.ML.OnnxRuntime and Microsoft.ML.OnnxTransformer
and is able to use an onnx model but that works with images and since I am very new to this I am unable to figure out how to load the model and make a prediction and get the value of the action which is an array of float size 6.
I found this to be useful for this
you'll also have to define your model schema.
here is the class I ended up with for this model
using Microsoft.ML;
using Microsoft.ML.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace godot_net_server
{
class OnnxModelScorer
{
private readonly string modelLocation;
private readonly MLContext mlContext;
public OnnxModelScorer(string modelLocation, MLContext mlContext)
{
this.modelLocation = modelLocation;
this.mlContext = mlContext;
}
public class ModelInput
{
[VectorType(10)]
[ColumnName("input.1")]
public float[] Features { get; set; }
}
private ITransformer LoadModel(string modelLocation)
{
Console.WriteLine("Read model");
Console.WriteLine($"Model location: {modelLocation}");
// Create IDataView from empty list to obtain input data schema
var data = mlContext.Data.LoadFromEnumerable(new List<ModelInput>());
// Define scoring pipeline
var pipeline = mlContext.Transforms.ApplyOnnxModel(modelFile: modelLocation, outputColumnNames: new[] { "31","34" }, inputColumnNames: new[] { "input.1" });
// Fit scoring pipeline
var model = pipeline.Fit(data);
return model;
}
public class Prediction
{
[VectorType(6)]
[ColumnName("31")]
public float[] action{ get; set; }
[VectorType(1)]
[ColumnName("34")]
public float[] state { get; set; }
}
private IEnumerable<float> PredictDataUsingModel(IDataView testData, ITransformer model)
{
Console.WriteLine("");
Console.WriteLine("=====Identify the objects in the images=====");
Console.WriteLine("");
IDataView scoredData = model.Transform(testData);
IEnumerable<float[]> probabilities = scoredData.GetColumn<float[]>("31");
var a = probabilities.ToList();
a.Count.ToString();
return a[0];
}
public IEnumerable<float> Score(IDataView data)
{
var model = LoadModel(modelLocation);
return PredictDataUsingModel(data, model);
}
}
}
this is how I used it to get a prediction
MLContext mlContext = new MLContext();
// Load trained model
var modelScorer = new OnnxModelScorer("my_ppo_1_model.onnx", mlContext);
List<ModelInput> input = new List<ModelInput>();
input.Add(new ModelInput()
{
Features = new[]
{
3.036393f,11.0f,2.958097f,0.0f,0.0f,0.0f,0.015607f,0.684984f,0.0f,0.0f
}
});
var action = modelScorer.Score(mlContext.Data.LoadFromEnumerable(input));
The result is as I was expecting it to be
In one of my Sitecore Project, I have to create a Custom field in WFFM.
Field type must have Two Textbox and user can enter 5 digit in each text box (Example xxxxx xxxxx, as we enter credit card details in 4 text box).
As per the ref document “https://sdn.sitecore.net/upload/sitecore6/64/presentation_component_cookbook-a4.pdf” I have crated below code :-
Crated a .cs Class
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sitecore.Form.Web.UI.Controls;
using System.ComponentModel;
using System.ComponentModel.Design;
namespace Web.MySite.Fields
{
[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
public class SocialSecurityNumber : SingleLineText
{
private static readonly string baseCssClassName = "scfSingleLineTextBorder";
protected TextBox firstPart;protected TextBox lastPart;
public SocialSecurityNumber() : this(HtmlTextWriterTag.Div)
{
firstPart = new TextBox();
lastPart = new TextBox();
}
public SocialSecurityNumber(HtmlTextWriterTag tag) : base(tag)
{
this.CssClass = baseCssClassName;
}
protected override void OnInit(EventArgs e)
{
SetCssClasses();
SetTextBoxeWidths();
SetMaxLengths();
SetTextBoxModes();
AddChildControls();
base.OnInit(e);
}
private void SetCssClasses()
{
help.CssClass = "scfSingleLineTextUsefulInfo";
title.CssClass = "scfSingleLineTextLabel";
generalPanel.CssClass = "scfSingleLineGeneralPanel";
}
private void SetTextBoxeWidths()
{
firstPart.Style.Add("width", "40px");
lastPart.Style.Add("width", "50px");
}
private void SetMaxLengths()
{
firstPart.MaxLength = 3;
lastPart.MaxLength = 4;
}
private void SetTextBoxModes()
{
firstPart.TextMode = TextBoxMode.SingleLine;
lastPart.TextMode = TextBoxMode.SingleLine;
}
private void AddChildControls()
{
Controls.AddAt(0, generalPanel);
Controls.AddAt(0, title);
generalPanel.Controls.Add(firstPart);
generalPanel.Controls.Add(lastPart);
generalPanel.Controls.Add(help);
}
}
public class SocialSecurityNumberModel : Sitecore.Forms.Mvc.ViewModels.Fields.SingleLineTextField
{
}
}
Then I have Created a BootstrapEditorHtmlHelperExtension.CS and Crated a .CSHTML:-
using Sitecore.Forms.Mvc.Interfaces;
using Sitecore.Forms.Mvc.ViewModels.Fields;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace Web.MySite.Extensions
{
public static class BootstrapEditorHtmlHelperExtension
{
public static MvcHtmlString ExtendedBootstrapEditor(this HtmlHelper helper, string expression, string placeholderText, string inlineStyle, string[] classes)
{
var str = string.Empty;
var viewModel = helper.ViewData.Model as IViewModel;
if (viewModel != null)
{
var styleSettings = viewModel as IStyleSettings;
if (styleSettings != null)
{
str = styleSettings.CssClass;
}
if (string.IsNullOrEmpty(placeholderText))
{
placeholderText = viewModel.Title;
}
}
return helper.TextBox(expression,null, new
{
#class = (string.Join(" ", classes) + " form-control col-lg-2" + (string.IsNullOrEmpty(str) ? string.Empty : " " + str) + (helper.ViewData.Model is SingleLineTextField ? " dangerousSymbolsCheck" : string.Empty)),
placeholder = placeholderText,
style = (inlineStyle ?? string.Empty)
});
}
}
}
SocialSecurityNumberModel.CSHTML
#using Sitecore.Forms.Mvc.Html
#using Web.MySite.Extensions
#model Web.MySite.Fields.SocialSecurityNumberModel
#using (Html.BeginField())
{
#Html.ExtendedBootstrapEditor("value", " ", "width:50%", new[] { "" })
#Html.ExtendedBootstrapEditor("value", " ", "width:40%", new[] { "" })
}
After it ,I have Crated a Custom Field in Sitecore and gave Below dll ref. in
Assembly
Sitecore.Forms.Custom.dll
Class
Sitecore.Form.Web.UI.Controls.SingleLineText
MVC Type
Web.MySite.Fields.SocialSecurityNumberModel,Web.MySite
I am getting both the text box but ID is same for Both.
ID=wffm1755f6ce241245b7a1183288954ce0e7_Sections_0__Fields_0__value
You don't have to create an ASCX file for creating a custom field for WFFM
First of all you need to create an item of type:
/sitecore/templates/Web Forms for Marketers/Field Type
If you are using WFFM with MVC you need to fill MVC Type field.
You can look with Dot Peek how other Sitecore Wffm field are build.
You need to create your own class like in this example:
https://sitecorecorner.com/tag/wffm-custom-field/
http://elenazlateva.blogspot.ro/2012/09/custom-field-type-for-sitecore-web.html
https://divamatrix.wordpress.com/2011/12/20/wffm-custom-field-type-made-easy/
I try to have my WCF services always throw detailed faults, even when not throwing them explicitly. To achieve it, I implemented:
an ErrorHandler, whose IErrorHandler.ProvideFault wraps the non-fault error as FaultException
a ServiceBehavior extension, attaching this handler AND adding to each operation a fault description of this FaultException, so the client might catch it as such.
I've decorated my service with the error handler attribute (originally I had two distinct implementations of IServiceBehavior, for the ErrorHandler and for the Operation.Faults).
I also made sure the data set into the new FaultDescription is identical to the one I inspected when defining the FaultContract on my contract.
No matter what I try, when using the FaultContract as attribute on my contract, the fault is being properly caught by the client, but when having it attached at runtime through the ApplyDispatchBehavior, only a general FaultException is being caught. Apparently, everything else (error wrapping and throwing) is working, only the addition of a FaultContract to each action at runtime fails.
Please help...
here's the code:
ErrorHandling.cs
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Text;
using Shared.Contracts.Faults;
namespace Server.WcfExtensions
{
public class MyErrorHandler : IErrorHandler
{
#region IErrorHandler Members
public bool HandleError(Exception error)
{
return false;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
if (error is FaultException) return;
if (!error.GetType().IsSerializable) return;
FaultException<GeneralServerFault> faultExc = new FaultException<GeneralServerFault>(new GeneralServerFault(error), new FaultReason("Server Level Error"));
MessageFault messageFault = faultExc.CreateMessageFault();
fault = Message.CreateMessage(version, messageFault, faultExc.Action);
}
#endregion
}
class ErrorHandler : Attribute, IServiceBehavior
{
Type M_ErrorHandlerType;
public Type ErrorHandlerType
{
get { return M_ErrorHandlerType; }
set { M_ErrorHandlerType = value; }
}
#region IServiceBehavior Members
public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
IErrorHandler errorHandler;
try
{
errorHandler = (IErrorHandler)Activator.CreateInstance(ErrorHandlerType);
}
catch (MissingMethodException e)
{
throw new ArgumentException("Must have a public empty constructor.", e);
}
catch (InvalidCastException e)
{
throw new ArgumentException("Must implement IErrorHandler.", e);
}
foreach (ChannelDispatcherBase channelDispatcherBase in serviceHostBase.ChannelDispatchers)
{
ChannelDispatcher channelDispatcher = channelDispatcherBase as ChannelDispatcher;
channelDispatcher.ErrorHandlers.Add(errorHandler);
}
foreach (ServiceEndpoint ep in serviceDescription.Endpoints)
{
foreach (OperationDescription opDesc in ep.Contract.Operations)
{
Type t = typeof(GeneralServerFault);
string name = t.Name;
FaultDescription faultDescription = new FaultDescription(ep.Contract.Namespace + "/" + ep.Contract.Name + "/" + opDesc.Name + name + "Fault");
faultDescription.Name = name + "Fault";
faultDescription.Namespace = ep.Contract.Namespace;
faultDescription.DetailType = t;
opDesc.Faults.Add(faultDescription);
}
}
}
public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
}
#endregion
}
}
GeneralServerFault.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Shared.Contracts.Faults
{
[DataContract] //[Serializable]
public class GeneralServerFault
{
[DataMember]
public SerializableException Wrapped
{
get;
private set;
}
public GeneralServerFault()
: base()
{
Wrapped = new SerializableException();
}
public GeneralServerFault(Exception toWrap)
: base()
{
Wrapped = new SerializableException(toWrap);
}
}
[Serializable]
public class SerializableException
{
public string Type { get; set; }
public DateTime TimeStamp { get; set; }
public string Message { get; set; }
public string StackTrace { get; set; }
public SerializableException()
{
this.TimeStamp = DateTime.Now;
}
public SerializableException(string Message)
: this()
{
this.Message = Message;
}
public SerializableException(System.Exception ex)
: this(ex.Message)
{
if (ex == null) return;
Type = ex.GetType().ToString();
this.StackTrace = ex.StackTrace;
}
public override string ToString()
{
return this.Type + " " + this.Message + this.StackTrace;
}
}
}
IContractService.cs
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.ServiceModel;
using Shared.Contracts.Faults;
namespace Shared
{
internal static class Namespaces
{
internal static class Contracts
{
public const string ServiceContracts = "http://mycompany/services";
}
}
[ServiceContract(Namespace = Namespaces.Contracts.ServiceContracts, SessionMode = SessionMode.Required)]
public interface IContactServices
{
[OperationContract]
[FaultContract(typeof(DataNotFoundFault))]
//[FaultContract(typeof(GeneralServerFault))]
void DoSomething();
}
}
ContractService.cs
using System;
using System.Collections.Generic;
using System.ServiceModel;
using Shared;
using Shared.Contracts.Faults;
using Server.WcfExtensions;
namespace Server.Services
{
[ErrorHandler(ErrorHandlerType = typeof(MyErrorHandler))]
public class ContactSevices : IContactServices
{
[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = false)]
public void DoSomething()
{
throw new InvalidCastException("bla");
}
}
}
I omitted the code of client and host
I have configured a Orchard module to expose a service and have enabled it. I cannot work out the URL to use based on the following.
Routes.cs
namespace OrchardRestService
{
using System.Collections.Generic;
using System.ServiceModel.Activation;
using Orchard.Mvc.Routes;
using Orchard.Wcf;
public class Routes : IRouteProvider
{
#region Implementation of IRouteProvider
public IEnumerable<RouteDescriptor> GetRoutes()
{
return new[] {
new RouteDescriptor {
Priority = 20,
Route = new ServiceRoute(
"ContentService",
new OrchardServiceHostFactory(),
typeof(IContentService))
}
};
}
public void GetRoutes(ICollection<RouteDescriptor> routes)
{
foreach (var routeDescriptor in GetRoutes())
routes.Add(routeDescriptor);
}
#endregion
}
}
IContentService.cs:
namespace OrchardRestService
{
using System.ServiceModel;
using Orchard;
[ServiceContract]
public interface IContentService : IDependency
{
[OperationContract]
ContentResult GetContent(string contentPath);
}
}
ContentService.cs:
namespace OrchardRestService
{
using System.Collections.Generic;
using System.ServiceModel.Activation;
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ContentService : IContentService
{
public ContentResult GetContent(string contentPath)
{
var contentResult = new ContentResult
{ ContentValues = new Dictionary<string, string>(), Found = true, Path = contentPath };
return contentResult;
}
}
}
I've tried to follow what Bertrand Le Roy has written here and here but seem to be missing something.
My code is .Net 4 by the way so no need for an SVC file.
Closing as I'd be jumping through hoops to use N2 in this way rather than what it is designed for.