Multiple parameter in Get Method - asp.net-web-api2

[Route("api/LoginValues/itemcode/{username}/{password}")]
[HttpGet]
public IEnumerable<AC_Attendance> Get(string username, string password )
{
**var list = from g in db.AC_Attendances where g.username == username select g;**
return list;
}
How i want to make " g.username == username AND g.password== password "

For example I have taken employee(userID and password) as parameter.
public IEnumerable<Employee> Get(int Id, string password)
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
return entities.Employees.Where(tem => tem.ID == Id && tem.password
== password).ToList();
}
}

public IEnumerable<AC_Attendance> Get(string username, string password)
{
var a = db.AC_Attendances
.Where(s => s.username == username && s.password == password)
.ToArray();
if (a != null)
{
return a;
}
else
{
return null;
}
}

Related

how to pass two or three values to fluent validation Must function?

my code :
public class MandatoryValidator : AbstractValidator<Entity.EigenSchema.AttributeSet>
{
private string Keyvalue = string.Empty;
public MandatoryValidator(string keyvalue)
{
Keyvalue = keyvalue;
RuleFor(record => record.Mandatory).Must(Mandatory);
}
protected bool Mandatory(bool val)
{
if (val)
{
if(Keyvalue!=null || Keyvalue!="")
{
return true;
}
return false;
}
else
{
return true;
}
}
}
this checks if the field is mandatory or not.
Now I need a function that takes more than one parameter to mandatory function, something like this..
protected bool Mandatory(bool val, string strval, int val)
{
//strval = record.LocalUnique
//val = record.Size
}
You can do it like this
RuleFor(record => record.Mandatory).Must(mandatoryField => Mandatory(mandatoryField, Keyvalue, 012));
You can also
RuleFor(record => record).Must(WholeObject=> Mandatory(WholeObject))
.WithName("Mandatory");
//.WithName(x => x.MandatoryFieldName) optional
//and now
private bool MandatorChecker(MyRecordType obj)
{
strval = obj.LocalUnique;
val = obj.Size;
}
This one will use the name you provided if this rule breaks.

How to create url with complex query

I use dart and flutter for mobile app. I use my api to get data from server. But I found a problem, maybe its dart core problem.
I need to add complex queryParams to my URL like
Map<String, Map<String, List<String>>>{"a": {"b": ["c","d"]}, "e": {}}
I use Uri.parse(url).replace(queryParams: myQueryParams).toString()
But Uri.replace() accepts only Map<String, Iterable<String>> and throws an error
Unhandled Exception: type '_InternalLinkedHashMap<String, List<String>>' is not a subtype of type 'Iterable<dynamic>'
I found method which throws this error
static String _makeQuery(String query, int start, int end,
Map<String, dynamic /*String|Iterable<String>*/ > queryParameters) {
if (query != null) {
if (queryParameters != null) {
throw ArgumentError('Both query and queryParameters specified');
}
return _normalizeOrSubstring(query, start, end, _queryCharTable,
escapeDelimiters: true);
}
if (queryParameters == null) return null;
var result = StringBuffer();
var separator = "";
void writeParameter(String key, String value) {
result.write(separator);
separator = "&";
result.write(Uri.encodeQueryComponent(key));
if (value != null && value.isNotEmpty) {
result.write("=");
result.write(Uri.encodeQueryComponent(value));
}
}
queryParameters.forEach((key, value) {
if (value == null || value is String) {
writeParameter(key, value);
} else {
Iterable values = value;
for (String value in values) {
writeParameter(key, value);
}
}
});
return result.toString();
}
So my question is there is some method in dart to add my queryParams to url or I need to create it by my own?
I have modified original method and now its work.
class UrlCreator {
static String addQueryParams(String url, Map<String, dynamic> queryParams) {
var result = StringBuffer();
var separator = "";
void writeParameter(String key, String value) {
result.write(separator);
separator = "&";
result.write(Uri.encodeQueryComponent(key));
if (value != null && value.isNotEmpty) {
result.write("=");
result.write(Uri.encodeQueryComponent(value));
}
}
void buildQuery(Map queryParams, {parentKey}){
queryParams.forEach((key, value){
print("parentKey = $parentKey Key = $key value = $value");
if (value == null || value is String) {
var newKey = parentKey != null ? "$parentKey[$key]" : key;
writeParameter(newKey, value);
} else if (value is Map) {
buildQuery(value, parentKey: key);
} else {
Iterable values = value;
var newKey = parentKey != null ? "$parentKey[$key][]" : "$key[]";
for (String value in values) {
writeParameter(newKey, value);
}
}
});
}
buildQuery(queryParams);
return url + "?" + result.toString();
}
}

Swashbuckle Swagger - Pulling information from Attributes and putting it into the Schema definition

I am trying to have pull the DisplayAttribute and the DescriptionAttribute from parts of the Swagger Model. For example I may have a Body Parameter which has properties with attributes, which I would also want to be generated in the swagger.json and visible in SwaggerUI.
So far I think the approach that should work would be using a custom filter with swashbuckle. I got a proof of concept using the IParameterFilter which displays the description attribute, not sure if another filter would be better.
Issues:
Finding the key for the schemaRegistry fails for some types, like list.
Need to get the key for the parameter to be generated the same as swagger.
Might need recursion to loop through child properties that contain complex objects.
public class SwaggerParameterFilter : IParameterFilter
{
private SchemaRegistrySettings _settings;
private SchemaIdManager _schemaIdManager;
public SwaggerParameterFilter(SchemaRegistrySettings settings = null)
{
this._settings = settings ?? new SchemaRegistrySettings();
this._schemaIdManager = new SchemaIdManager(this._settings.SchemaIdSelector);
}
public void Apply(IParameter parameter, ParameterFilterContext context)
{
try
{
if (context.ApiParameterDescription?.ModelMetadata?.Properties == null) return;
if (parameter is BodyParameter bodyParameter)
{
string idFor = _schemaIdManager.IdFor(context.ApiParameterDescription.Type);
var schemaRegistry = (SchemaRegistry)context.SchemaRegistry;
//not perfect, crashes with some cases
var schema = schemaRegistry.Definitions[idFor];
//bodyParameter.Schema, this doesn't seem right, no properties
foreach (var modelMetadata in context.ApiParameterDescription.ModelMetadata.Properties)
{
if (modelMetadata is DefaultModelMetadata defaultModelMetadata)
{
//not sure right now how to get the right key for the schema.Properties...
var name = defaultModelMetadata.Name;
name = Char.ToLowerInvariant(name[0]) + name.Substring(1);
if (schema.Properties.ContainsKey(name))
{
var subSchema = schema.Properties[name];
var attributes = defaultModelMetadata.Attributes.Attributes.Select(x => (Attribute)x);
var descriptionAttribute = (DescriptionAttribute)attributes.FirstOrDefault(x => x is DescriptionAttribute);
if (descriptionAttribute != null)
subSchema.Description = descriptionAttribute.Description;
}
}
}
}
}
catch (Exception e)
{
//eat because above is broken
}
}
}
Edit add looping.
public class SwaggerParameterFilter : IParameterFilter
{
private SchemaRegistrySettings _settings;
private SchemaIdManager _schemaIdManager;
public SwaggerParameterFilter(SchemaRegistrySettings settings = null)
{
this._settings = settings ?? new SchemaRegistrySettings();
this._schemaIdManager = new SchemaIdManager(this._settings.SchemaIdSelector);
}
public void Apply(IParameter parameter, ParameterFilterContext context)
{
try
{
if (context.ApiParameterDescription?.ModelMetadata?.Properties == null) return;
//Only BodyParameters are complex and stored in the schema
if (parameter is BodyParameter bodyParameter)
{
var idFor = _schemaIdManager.IdFor(context.ApiParameterDescription.Type);
//not perfect, crashes with some cases
var schema = context.SchemaRegistry.Definitions[idFor];
UpdateSchema(schema, (SchemaRegistry) context.SchemaRegistry, context.ApiParameterDescription.ModelMetadata);
}
}
catch (Exception e)
{
//eat because above is broken
}
}
private void UpdateSchema(Schema schema, SchemaRegistry schemaRegistry, ModelMetadata modelMetadata)
{
if (schema.Ref != null)
{
var schemaReference = schema.Ref.Replace("#/definitions/", "");
UpdateSchema(schemaRegistry.Definitions[schemaReference], schemaRegistry, modelMetadata);
return;
}
if (schema.Properties == null) return;
foreach (var properties in modelMetadata.Properties)
{
if (properties is DefaultModelMetadata defaultModelMetadata)
{
//not sure right now how to get the right key for the schema.Properties...
var name = defaultModelMetadata.Name;
name = Char.ToLowerInvariant(name[0]) + name.Substring(1);
if (schema.Properties.ContainsKey(name) == false) return;
var subSchema = schema.Properties[name];
var attributes = defaultModelMetadata.Attributes.Attributes.Select(x => (Attribute) x).ToList();
var descriptionAttribute =
(DescriptionAttribute) attributes.FirstOrDefault(x => x is DescriptionAttribute);
if (descriptionAttribute != null)
subSchema.Description = descriptionAttribute.Description;
var displayAttribute = (DisplayAttribute) attributes.FirstOrDefault(x => x is DisplayAttribute);
if (displayAttribute != null)
subSchema.Title = displayAttribute.Name;
if (modelMetadata.ModelType.IsPrimitive) return;
UpdateSchema(subSchema, schemaRegistry, defaultModelMetadata);
}
}
}
}
Operation Filter
public class SwaggerOperationFilter : IOperationFilter
{
private SchemaRegistrySettings _settings;
private SchemaIdManager _schemaIdManager;
private IModelMetadataProvider _metadataProvider;
public SwaggerOperationFilter(IModelMetadataProvider metadataProvider, SchemaRegistrySettings settings = null)
{
this._metadataProvider = metadataProvider;
this._settings = settings ?? new SchemaRegistrySettings();
this._schemaIdManager = new SchemaIdManager(this._settings.SchemaIdSelector);
}
public void Apply(Operation operation, OperationFilterContext context)
{
try
{
foreach (var paramDescription in context.ApiDescription.ParameterDescriptions)
{
if (paramDescription?.ModelMetadata?.Properties == null)
{
continue;
}
if (paramDescription.ModelMetadata.ModelType.IsPrimitive)
{
continue;
}
if (paramDescription.ModelMetadata.ModelType == typeof(string))
{
continue;
}
var idFor = _schemaIdManager.IdFor(paramDescription.Type);
var schema = context.SchemaRegistry.Definitions[idFor];
UpdateSchema(schema, (SchemaRegistry)context.SchemaRegistry, paramDescription.ModelMetadata);
}
}
catch (Exception e)
{
//eat because above is broken
}
}
private void UpdateSchema(Schema schema, SchemaRegistry schemaRegistry, ModelMetadata modelMetadata)
{
if (schema.Ref != null)
{
var schemaReference = schema.Ref.Replace("#/definitions/", "");
UpdateSchema(schemaRegistry.Definitions[schemaReference], schemaRegistry, modelMetadata);
return;
}
if (schema.Type == "array")
{
if (schema.Items.Ref != null)
{
var schemaReference = schema.Items.Ref.Replace("#/definitions/", "");
var modelTypeGenericTypeArgument = modelMetadata.ModelType.GenericTypeArguments[0];
modelMetadata = _metadataProvider.GetMetadataForType(modelTypeGenericTypeArgument);
UpdateSchema(schemaRegistry.Definitions[schemaReference], schemaRegistry, modelMetadata);
}
return;
}
if (schema.Properties == null) return;
foreach (var properties in modelMetadata.Properties)
{
if (properties is DefaultModelMetadata defaultModelMetadata)
{
//not sure right now how to get the right key for the schema.Properties...
var name = defaultModelMetadata.Name;
name = Char.ToLowerInvariant(name[0]) + name.Substring(1);
if (schema.Properties.ContainsKey(name) == false) return;
var subSchema = schema.Properties[name];
var attributes = defaultModelMetadata.Attributes.Attributes.Select(x => (Attribute)x).ToList();
var descriptionAttribute =
(DescriptionAttribute)attributes.FirstOrDefault(x => x is DescriptionAttribute);
if (descriptionAttribute != null)
subSchema.Description = descriptionAttribute.Description;
var displayAttribute = (DisplayAttribute)attributes.FirstOrDefault(x => x is DisplayAttribute);
if (displayAttribute != null)
subSchema.Title = displayAttribute.Name;
if (defaultModelMetadata.ModelType.IsPrimitive) return;
UpdateSchema(subSchema, schemaRegistry, defaultModelMetadata);
}
}
}
}
So after some troubleshooting this seems to work for me but may need modification for other cases.
public class SwashbuckleAttributeReaderDocumentFilter : IDocumentFilter
{
private readonly SchemaIdManager _schemaIdManager;
private readonly IModelMetadataProvider _metadataProvider;
private List<string> _updatedSchemeList;
public SwashbuckleAttributeReaderDocumentFilter(IModelMetadataProvider metadataProvider, SchemaRegistrySettings settings = null)
{
_metadataProvider = metadataProvider;
var registrySettings = settings ?? new SchemaRegistrySettings();
_schemaIdManager = new SchemaIdManager(registrySettings.SchemaIdSelector);
}
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
_updatedSchemeList = new List<string>();
foreach (var apiDescription in context.ApiDescriptions)
{
foreach (var responseTypes in apiDescription.SupportedResponseTypes)
{
ProcessModelMetadata(context, responseTypes.ModelMetadata);
}
foreach (var paramDescription in apiDescription.ParameterDescriptions)
{
ProcessModelMetadata(context, paramDescription.ModelMetadata);
}
}
}
private void ProcessModelMetadata(DocumentFilterContext context, ModelMetadata currentModelMetadata)
{
if (currentModelMetadata?.Properties == null)
{
return;
}
if (currentModelMetadata.ModelType.IsValueType)
{
return;
}
if (currentModelMetadata.ModelType == typeof(string))
{
return;
}
if (currentModelMetadata.ModelType.IsGenericType)
{
foreach (var modelType in currentModelMetadata.ModelType.GenericTypeArguments)
{
var modelMetadata = _metadataProvider.GetMetadataForType(modelType);
UpdateSchema(context.SchemaRegistry, modelMetadata);
}
}
else if (currentModelMetadata.IsCollectionType)
{
var modelType = currentModelMetadata.ModelType.GetElementType();
var modelMetadata = _metadataProvider.GetMetadataForType(modelType);
UpdateSchema(context.SchemaRegistry, modelMetadata);
}
else
{
UpdateSchema(context.SchemaRegistry, currentModelMetadata);
}
}
public static void SetSchema(Schema schema, ModelMetadata modelMetadata)
{
if (!(modelMetadata is DefaultModelMetadata metadata)) return;
var attributes = GetAtributes(metadata);
SetDescription(attributes, schema);
SetTitle(attributes, schema);
}
private static List<Attribute> GetAtributes(DefaultModelMetadata modelMetadata)
{
return modelMetadata.Attributes.Attributes.Select(x => (Attribute)x).ToList();
}
private static void SetTitle(List<Attribute> attributes, Schema schema)
{
//LastOrDefault because we want the attribute from the dervived class.
var displayAttribute = (DisplayNameAttribute)attributes.LastOrDefault(x => x is DisplayNameAttribute);
if (displayAttribute != null)
schema.Title = displayAttribute.DisplayName;
}
private static void SetDescription(List<Attribute> attributes, Schema schema)
{
//LastOrDefault because we want the attribute from the dervived class. not sure if this works.
var descriptionAttribute = (DescriptionAttribute)attributes.LastOrDefault(x => x is DescriptionAttribute);
if (descriptionAttribute != null)
schema.Description = descriptionAttribute.Description;
}
private void UpdateSchema(ISchemaRegistry schemaRegistry, ModelMetadata modelMetadata, Schema schema = null)
{
if (modelMetadata.ModelType.IsValueType) return;
if (modelMetadata.ModelType == typeof(string)) return;
var idFor = _schemaIdManager.IdFor(modelMetadata.ModelType);
if (_updatedSchemeList.Contains(idFor))
return;
if (schema == null || schema.Ref != null)
{
if (schemaRegistry.Definitions.ContainsKey(idFor) == false) return;
schema = schemaRegistry.Definitions[idFor];
}
_updatedSchemeList.Add(idFor);
SetSchema(schema, modelMetadata);
if (schema.Type == "array")//Array Schema
{
var metaData = _metadataProvider.GetMetadataForType(modelMetadata.ModelType.GenericTypeArguments[0]);
UpdateSchema(schemaRegistry, metaData);
}
else//object schema
{
if (schema.Properties == null)
{
return;
}
foreach (var properties in modelMetadata.Properties)
{
if (!(properties is DefaultModelMetadata defaultModelMetadata))
{
continue;
}
var name = ToLowerCamelCase(defaultModelMetadata.Name);
if (schema.Properties.ContainsKey(name) == false)
{
//when this doesn't match the json object naming.
return;
}
var subSchema = schema.Properties[name];
SetSchema(subSchema, defaultModelMetadata);
UpdateSchema(schemaRegistry, defaultModelMetadata, subSchema);
}
}
}
private static string ToLowerCamelCase(string inputString)
{
if (inputString == null) return null;
if (inputString == string.Empty) return string.Empty;
if (char.IsLower(inputString[0])) return inputString;
return inputString.Substring(0, 1).ToLower() + inputString.Substring(1);
}
}

Undesired logout in MVC 4

I have this issue after publish project in host, in development environment everything is OK!
In my published MVC 4.0 website when an authenticated user try to upload a picture, the user has been logged off and redirected to the Login Page.
I've used the following code to upload pictures and successfully work in local:
private void TryUploadImages(Product product)
{
const string emptyImage = "empty.jpg";
try
{
for (int idx = 0; idx < 3; idx++)
{
if ((Request.Files.Count < 3) ||
(Request.Files[idx] == null) ||
(Request.Files[idx].ContentLength > 1024 * 1024 * 5) ||
(Request.Files[idx].ContentLength <= 0))
{
if ((idx == 0 && string.IsNullOrEmpty(product.ImageFilename)) ||
(idx == 1 && string.IsNullOrEmpty(product.ThumbnailImage)) ||
(idx == 2 && string.IsNullOrEmpty(product.AttributesImage)))
throw new Exception(GlobalResources.Global_Image_Restrictions_Error);
continue;
}
HttpPostedFileBase uploadedFile = Request.Files[idx];
string fileName = Path.GetFileName(uploadedFile.FileName);
using (var img = Image.FromStream(uploadedFile.InputStream))
{ bool temp = img.Width > 0; }
if (!string.IsNullOrEmpty(fileName))
{
string[] filenames = {"product", "product-thumb", "attribute"};
fileName = string.Format("{0}-{1}{2}",
filenames[idx],
Guid.NewGuid().ToString().Replace("-", string.Empty),
Path.GetExtension(fileName));
var physicalPath = Path.Combine(Server.MapPath("~/Images/sitepx/products/"), fileName);
uploadedFile.SaveAs(physicalPath);
switch (idx)
{
case 0:
product.ImageFilename = fileName;
break;
case 1:
product.ThumbnailImage = fileName;
break;
case 2:
product.AttributesImage = fileName;
break;
}
}
else
{
switch (idx)
{
case 0:
product.ImageFilename = emptyImage;
break;
case 1:
product.ThumbnailImage = emptyImage;
break;
case 2:
product.AttributesImage = emptyImage;
break;
}
}
}
}
catch (Exception ex)
{
ViewBag.UploadError = ex.Message;
product.ImageFilename = emptyImage;
}
}
and call it in this action method:
[AllowUploadSafeFiles]
[AllowUploadSpecialFilesOnly(".jpg,.jpeg,.gif,.png,.bmp")]
[HttpPost]
public virtual ActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
TryUploadImages(product);
product.ModifiedOn = DateTime.Now;
_db.Entry(product).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction(MVC.Product.ActionNames.Index);
}
ViewBag.CategoryId = new SelectList(_db.Categories, "CategoryId", "Name", product.CategoryId);
ViewBag.ProductTypeId = new SelectList(_db.ProductTypes, "ProductTypeId", "Name", product.ProductTypeId);
return View(product);
}
Moreover I authorize controller for particular Roles and also disable Sessions in Web.config for security reasons :
<httpModules>
<-- blah blah blah ... -->
<!-- Disable Session -->
<remove name="Session" />
</httpModules>
<sessionState mode="Off" />
If you still need additional information, feel free to tell.
Thanks
===== EDITED (Add authentication detail) =====
Maybe I looking for trouble in the wrong place, my login method is something like this:
[AllowAnonymous]
public virtual ActionResult Login(string returnUrl)
{
if (User.Identity.IsAuthenticated)
if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
return RedirectToLocal(returnUrl);
else
return Redirect(ReturnRedirectUrl(returnUrl));
ViewBag.ReturnUrl = returnUrl;
ViewBag.Roles = GetAllAccountRoles();
return View();
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public virtual ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, model.RememberMe))
{
var location = ReturnRedirectUrl(returnUrl);
return string.IsNullOrEmpty(location)
? RedirectToAction(MVC.Account.Login())
: RedirectToLocal(location);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", GlobalResources.Account_Login_ModelError);
return View(model);
}
and this is Role base ReturnRedirectUrl used in login function:
private string ReturnRedirectUrl(string returnUrl)
{
if (string.IsNullOrEmpty(returnUrl) || !Url.IsLocalUrl(returnUrl))
{
foreach (var role in Roles.GetAllRoles().Where(Roles.IsUserInRole))
{
switch (role)
{
case "info":
returnUrl = Url.Action(MVC.SiteManage.Index(1));
break;
case "support":
returnUrl = Url.Action(MVC.SiteManage.Index(2));
break;
case "sales":
returnUrl = Url.Action(MVC.SiteManage.Index(3));
break;
case "admin":
returnUrl = Url.Action(MVC.SiteManage.Index(6));
break;
case "club-member":
returnUrl = Url.Action(MVC.SiteManage.Index());
break;
case "vendor-reseller":
returnUrl = Url.Action(MVC.SiteManage.Index());
break;
case "sales-reseller":
returnUrl = Url.Action(MVC.SiteManage.Index());
break;
}
}
}
return returnUrl;
}

NServicebus Test.Handler ExpectSend does not give expected result

I asked this some time ago on the yahoogroup but unfortunately no answer.
When ExpectSend is added to the unittest, the test fails with this message:
Rhino.Mocks.Exceptions.ExpectationViolationException: IBus.Send(callback method:
<>c__DisplayClass2`1.<ExpectSend>b__1); Expected #1, Actual #0
.
This looks like the Bus.Send method is never called. But it is.
When the line with .ExpectSend is not used, the test succeeded.
[TestMethod()]
public void Should_Handle_Goedkeuring_Which_Results_In_VolledigGoedgekeurdeFactuur()
{
int inkoopFactuurId = 5;
Test.Initialize();
var mock = new Mock<IProcesGoedkeuringDataService>();
mock.Setup(x => x.IsFactuurVolledigGoedgekeurd(inkoopFactuurId)).Returns(true);
Test.Handler<GoedkeuringDoorGebruikerCommandHandler>()
.WithExternalDependencies(h => h.DataService = mock.Object)
.ExpectSend<FactuurVolledigGoedgekeurdCommand>(c =>
c.InkoopFactuurId == inkoopFactuurId)
.OnMessage<GoedkeuringDoorGebruikerCommand>(m =>
SetupMessage(m)); ;
}
The handler: The IsFactuurVolledigGoedgekeurd method returns true in this case.
public class GoedkeuringDoorGebruikerCommandHandler : IHandleMessages<GoedkeuringDoorGebruikerCommand>
{
public IBus Bus { get; set; }
public IProcesGoedkeuringDataService DataService { get; set; }
public void Handle(GoedkeuringDoorGebruikerCommand message)
{
RegistreerGoedkeuring(message.InkoopFactuurId, message.GebruikerId);
bool volledigGoedgekeurd = IsFactuurVolledigGoedgekeurd(message.InkoopFactuurId);
if (volledigGoedgekeurd)
{
Bus.Send(new FactuurVolledigGoedgekeurdCommand(message.InkoopFactuurId));
}
}
}
Check this code (based on RequestResponse NServiceBus sample):
[TestFixture]
public class Tests
{
[Test]
public void TestHandler()
{
var assemblies = new[]
{
typeof(RequestDataMessageHandler).Assembly,
typeof(RequestDataMessage).Assembly
};
Test.Initialize(assemblies);
var dataId = Guid.NewGuid();
var str = "hello";
WireEncryptedString secret = "secret";
Test.Handler<RequestDataMessageHandler>()
.WithExternalDependencies(m => m.Repository = (new Mock<IRepository>()).Object)
.ExpectSend<RequestDataMessage>(m => m.DataId == dataId && m.String == str && m.SecretQuestion == secret)
.OnMessage<RequestDataMessage>(m => { m.DataId = dataId; m.String = str; m.SecretQuestion = secret; });
}
[Test]
public void TestHandler2()
{
var assemblies = new[]
{
typeof(RequestDataMessageHandler).Assembly,
typeof(RequestDataMessage).Assembly
};
Test.Initialize(assemblies);
var dataId = Guid.NewGuid();
var str = "hello";
WireEncryptedString secret = "secret";
Test.Handler<RequestDataMessageHandler>()
.WithExternalDependencies(m => m.Repository = (new Mock<IRepository>()).Object)
.ExpectSend<RequestDataMessage>(Check)
.OnMessage<RequestDataMessage>(m => { m.DataId = dataId; m.String = str; m.SecretQuestion = secret; });
}
private static bool Check(RequestDataMessage m)
{
var dataId = Guid.NewGuid();
var str = "hello";
WireEncryptedString secret = "secret";
return m.DataId == dataId && m.String == str && m.SecretQuestion == secret;
}
[Test]
public void TestHandler3()
{
var assemblies = new[]
{
typeof(RequestDataMessageHandler).Assembly,
typeof(RequestDataMessage).Assembly
};
Test.Initialize(assemblies);
var dataId = Guid.NewGuid();
var str = "hello";
WireEncryptedString secret = "secret";
Test.Handler<RequestDataMessageHandler>()
.WithExternalDependencies(m => m.Repository = (new Mock<IRepository>()).Object)
.ExpectSend<RequestDataMessage>(m => m.DataId == dataId && m.String == str && m.SecretQuestion == secret)
.OnMessage<RequestDataMessage>(m => SetUp(m));
}
private static void SetUp(RequestDataMessage m)
{
var dataId = Guid.NewGuid();
var str = "hello";
WireEncryptedString secret = "secret";
m.DataId = dataId;
m.String = str;
m.SecretQuestion = secret;
}
Output:
1. Pass
2. Fail
3. Fail
(Rhino.Mocks.Exceptions.ExpectationViolationException : IBus.Send(callback method: <>c_DisplayClass2`1.b_1); Expected #1, Actual #0.)
Probably the using of your method applied as an action to ExpectSend/OnMessage method it breaks the RhinoMocks expectation. I do not know why, but it is the reason why exception appeared.