send data to RoutingSlipCompleted consume method from activity - .net-core

I have some data in activity which I want to get it in RoutingSlipCompleted consume method. I know we can send data with CompletedWithVariables from a activity to b activity. But I was wondering how it is possible to get data from activity in RoutingSlipCompleted. so this is my activity:
public class CheckInventoryActivity : IActivity<ICheckInventoryRequest, CheckInventoryRequestCompensate>
{
private readonly IInventoryService _inventoryService;
private readonly IEndpointNameFormatter _formatter;
public CheckInventoryActivity(IInventoryService inventoryService, IEndpointNameFormatter formatter)
{
_inventoryService = inventoryService;
_formatter = formatter;
}
public async Task<ExecutionResult> Execute(ExecuteContext<ICheckInventoryRequest> context)
{
CheckInventoryRequest model = new CheckInventoryRequest()
{
PartCode = context.Arguments.PartCode
};
var response = await _inventoryService.CheckInventory(model);
var checkInventoryResponse = new CheckInventoryResponse()
{
PartCode = response.Data.PartCode ?? model.PartCode,
Id = response.Data.Id ?? 0,
InventoryCount = response.Data.InventoryCount ?? 0
};
var checkInventoryCustomActionResult = new CustomActionResult<CheckInventoryResponse>()
{
Data = checkInventoryResponse,
IsSuccess = true,
ResponseDesc = "success",
ResponseType = 0
};
var result = response.IsSuccess;
if (!result)
return context.CompletedWithVariables<CheckInventoryRequestCompensate>(
new
{
Result = result,
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
}, new
{
Result = result,
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
});
var queueName = _formatter.ExecuteActivity<CallSuccessActivity, ISuccessRequest>();
var uri = new Uri($"queue:{queueName}");
return context.ReviseItinerary(x => x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
}));
}
so by the following line of codes I can get data in CallSuccessActivity:
return context.ReviseItinerary(x => x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity",
CheckInventoryCustomActionResult = checkInventoryCustomActionResult
}));
}
so I can get this data here:
public class CallSuccessActivity : IExecuteActivity<ISuccessRequest>
{
private readonly IRequestClient<ISuccessRequest> _requestClient;
public CallSuccessActivity(IRequestClient<ISuccessRequest> requestClient)
{
_requestClient = requestClient;
}
public async Task<ExecutionResult> Execute(ExecuteContext<ISuccessRequest> context)
{
var iModel = context.Arguments;
var model = new SuccessRequest()
{
LogDate = iModel.LogDate,
MethodName = iModel.MethodName,
CheckInventoryCustomActionResult = iModel.CheckInventoryCustomActionResult
};
//CustomActionResult< CheckInventoryResponse > CheckInventoryResponse = new ();
var rabbitResult = await _requestClient.GetResponse<CustomActionResult<SuccessResponse>>(model);
return context.Completed();
}
}
I want to get this iModel.CheckInventoryCustomActionResult in RoutingSlipCompleted :
public async Task Consume(ConsumeContext<RoutingSlipCompleted> context)
{
var requestId =
context.Message.GetVariable<Guid?>(nameof(ConsumeContext.RequestId));
var checkInventoryResponseModel = context.Message.Variables["CheckInventoryResponse"];
var responseAddress =
context.Message.GetVariable<Uri>(nameof(ConsumeContext.ResponseAddress));
var request =
context.Message.GetVariable< ICheckInventoryRequest > ("Model");
throw new NotImplementedException();
}

Instead of putting the value into the activity arguments, add it as a variable:
return context.ReviseItinerary(x =>
{
x.AddActivity("CallSuccessActivity", uri, new
{
LogDate = DateTime.Now,
MethodName = "CheckInventoryActivity"
});
x.AddVariable("CheckInventoryCustomActionResult", checkInventoryCustomActionResult);
});

Related

How to parse this json in flutter?

This Is my Json How can I Fetch this Fetch in Flutter? How Can I Create model For This ?
This Is Json Url http://api.weatherstack.com/current?access_key={MY API}&query=jaipur
you can use this project https://javiercbk.github.io/json_to_dart/ or this one https://app.quicktype.io/ and select Dart language to help you create models based on json data
You can automatically parse JSON to Dart classes by using this
class Weather {
Request request;
Location location;
Current current;
Weather({this.request, this.location, this.current});
Weather.fromJson(Map<String, dynamic> json) {
request =
json['request'] != null ? new Request.fromJson(json['request']) : null;
location = json['location'] != null
? new Location.fromJson(json['location'])
: null;
current =
json['current'] != null ? new Current.fromJson(json['current']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.request != null) {
data['request'] = this.request.toJson();
}
if (this.location != null) {
data['location'] = this.location.toJson();
}
if (this.current != null) {
data['current'] = this.current.toJson();
}
return data;
}
}
class Request {
String type;
String query;
String language;
String unit;
Request({this.type, this.query, this.language, this.unit});
Request.fromJson(Map<String, dynamic> json) {
type = json['type'];
query = json['query'];
language = json['language'];
unit = json['unit'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['type'] = this.type;
data['query'] = this.query;
data['language'] = this.language;
data['unit'] = this.unit;
return data;
}
}
class Location {
String name;
String country;
String region;
String lat;
String lon;
String timezoneId;
String localtime;
int localtimeEpoch;
String utcOffset;
Location(
{this.name,
this.country,
this.region,
this.lat,
this.lon,
this.timezoneId,
this.localtime,
this.localtimeEpoch,
this.utcOffset});
Location.fromJson(Map<String, dynamic> json) {
name = json['name'];
country = json['country'];
region = json['region'];
lat = json['lat'];
lon = json['lon'];
timezoneId = json['timezone_id'];
localtime = json['localtime'];
localtimeEpoch = json['localtime_epoch'];
utcOffset = json['utc_offset'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['country'] = this.country;
data['region'] = this.region;
data['lat'] = this.lat;
data['lon'] = this.lon;
data['timezone_id'] = this.timezoneId;
data['localtime'] = this.localtime;
data['localtime_epoch'] = this.localtimeEpoch;
data['utc_offset'] = this.utcOffset;
return data;
}
}
class Current {
String observationTime;
int temperature;
int weatherCode;
List<String> weatherIcons;
List<String> weatherDescriptions;
int windSpeed;
int windDegree;
String windDir;
int pressure;
double precip;
int humidity;
int cloudcover;
int feelslike;
int uvIndex;
int visibility;
String isDay;
Current(
{this.observationTime,
this.temperature,
this.weatherCode,
this.weatherIcons,
this.weatherDescriptions,
this.windSpeed,
this.windDegree,
this.windDir,
this.pressure,
this.precip,
this.humidity,
this.cloudcover,
this.feelslike,
this.uvIndex,
this.visibility,
this.isDay});
Current.fromJson(Map<String, dynamic> json) {
observationTime = json['observation_time'];
temperature = json['temperature'];
weatherCode = json['weather_code'];
weatherIcons = json['weather_icons'].cast<String>();
weatherDescriptions = json['weather_descriptions'].cast<String>();
windSpeed = json['wind_speed'];
windDegree = json['wind_degree'];
windDir = json['wind_dir'];
pressure = json['pressure'];
precip = json['precip'];
humidity = json['humidity'];
cloudcover = json['cloudcover'];
feelslike = json['feelslike'];
uvIndex = json['uv_index'];
visibility = json['visibility'];
isDay = json['is_day'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['observation_time'] = this.observationTime;
data['temperature'] = this.temperature;
data['weather_code'] = this.weatherCode;
data['weather_icons'] = this.weatherIcons;
data['weather_descriptions'] = this.weatherDescriptions;
data['wind_speed'] = this.windSpeed;
data['wind_degree'] = this.windDegree;
data['wind_dir'] = this.windDir;
data['pressure'] = this.pressure;
data['precip'] = this.precip;
data['humidity'] = this.humidity;
data['cloudcover'] = this.cloudcover;
data['feelslike'] = this.feelslike;
data['uv_index'] = this.uvIndex;
data['visibility'] = this.visibility;
data['is_day'] = this.isDay;
return data;
}
}
convert json to dart by Weather.fromJson(json);

Mocking of Where method in Data Repository is returning null at its actual implementation in repository

I have written a test for edit model of a class in EF core.
public async Task<Expense> EditExpense(Expense model)
{
var expense = _dataRepository.Where<Expense>(x => x.Id == model.Id).ToList();
if(expense != null)
{
expense.ForEach(x =>
{
x.Name = model.Name;
x.AddedOn = model.AddedOn;
x.Amount = model.Amount;
x.Type = model.Type;
x.SplitOption = model.SplitOption;
x.Notes = model.Notes;
x.IsGroupExpense = model.IsGroupExpense;
});
return expense.FirstOrDefault();
}
else
{
return null;
}
}
I want to test this method using xUnit and Moq and I have also written a method for it as below.
[Fact]
public async void UnitTest_IsExpenseEdited_ReturnsTrue()
{
var expenseCurrent = new Expense()
{
Id = 5,
Name = "Test Expense",
Amount = 1500,
AddedBy = "44db32c3-ad6a-4d68-a683-862be363f59c",
AddedOn = DateTime.Now,
Notes = "",
IsDeleted = false,
IsGroupExpense = false,
SplitOption = 1,
Type = 0
};
var expenseList = (new List<Expense>{ expenseCurrent });
var expenseAfterEdit = new Expense()
{
Id = 5,
Name = "Test Expense Edited",
Amount = 2000,
AddedBy = "44db32c3-ad6a-4d68-a683-862be363f59c",
AddedOn = DateTime.Now,
Notes = "Edited !!!",
IsDeleted = false,
IsGroupExpense = true,
SplitOption = 2,
Type = 0
};
_dataRepositoryMock.Setup(x => x.Where<Expense>(a => a.Id == expenseCurrent.Id)).Returns(expenseList as IQueryable<Expense>);
var expenseEdited = await _exepenseRepository.EditExpense(expenseAfterEdit);
Assert.Equal(expenseEdited, expenseAfterEdit);
}
But here, the Where method is returning null
public async Task<Expense> EditExpense(Expense model)
{
var expense = _dataRepository.Where<Expense>(x => x.Id == model.Id).ToList(); in repository
}
I am getting var expense null in above code.
Please suggest what should I include in the code to get the value in above var expense?
To test this method, I want to create a fake data which is going to be updated. Please suggest how this thing needs to be written properly?

How to add Category names in search in Nopcommerce 3.8

Hi there i would like to let customers type a category name and get some search results. Currently when you type a category name it says no results.
public ActionResult AdvanceSearch(SearchModel model, CatalogPagingFilteringModel command)
{
//'Continue shopping' URL
_genericAttributeService.SaveAttribute(_workContext.CurrentCustomer,
SystemCustomerAttributeNames.LastContinueShoppingPage,
_webHelper.GetThisPageUrl(false),
_storeContext.CurrentStore.Id);
if (model == null)
model = new SearchModel();
var searchTerms = model.q;
if (searchTerms == null)
searchTerms = "";
searchTerms = searchTerms.Trim();
//sorting
PrepareSortingOptions(model.PagingFilteringContext, command);
//view mode
PrepareViewModes(model.PagingFilteringContext, command);
//page size
PreparePageSizeOptions(model.PagingFilteringContext, command,
_catalogSettings.SearchPageAllowCustomersToSelectPageSize,
_catalogSettings.SearchPagePageSizeOptions,
_catalogSettings.SearchPageProductsPerPage);
string cacheKey = string.Format(ModelCacheEventConsumer.SEARCH_CATEGORIES_MODEL_KEY,
_workContext.WorkingLanguage.Id,
string.Join(",", _workContext.CurrentCustomer.GetCustomerRoleIds()),
_storeContext.CurrentStore.Id);
var categories = _cacheManager.Get(cacheKey, () =>
{
var categoriesModel = new List<SearchModel.CategoryModel>();
//all categories
var allCategories = _categoryService.GetAllCategories(storeId: _storeContext.CurrentStore.Id);
foreach (var c in allCategories)
{
//generate full category name (breadcrumb)
string categoryBreadcrumb = "";
var breadcrumb = c.GetCategoryBreadCrumb(allCategories, _aclService, _storeMappingService);
for (int i = 0; i <= breadcrumb.Count - 1; i++)
{
categoryBreadcrumb += breadcrumb[i].GetLocalized(x => x.Name);
if (i != breadcrumb.Count - 1)
categoryBreadcrumb += " >> ";
}
categoriesModel.Add(new SearchModel.CategoryModel
{
Id = c.Id,
Breadcrumb = categoryBreadcrumb
});
}
return categoriesModel;
});
if (categories.Any())
{
//first empty entry
model.AvailableCategories.Add(new SelectListItem
{
Value = "0",
Text = _localizationService.GetResource("Common.All")
});
//all other categories
foreach (var c in categories)
{
model.AvailableCategories.Add(new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Breadcrumb,
Selected = model.cid == c.Id
});
}
}
IPagedList<Product> products = new PagedList<Product>(new List<Product>(), 0, 1);
// only search if query string search keyword is set (used to avoid searching or displaying search term min length error message on /search page load)
if (Request.Params["q"] != null)
{
if (searchTerms.Length < _catalogSettings.ProductSearchTermMinimumLength)
{
model.Warning = string.Format(_localizationService.GetResource("Search.SearchTermMinimumLengthIsNCharacters"), _catalogSettings.ProductSearchTermMinimumLength);
}
else
{
var categoryIds = new List<int>();
int manufacturerId = 0;
decimal? minPriceConverted = null;
decimal? maxPriceConverted = null;
bool searchInDescriptions = false;
int vendorId = 0;
if (model.adv)
{
//advanced search
var categoryId = model.cid;
if (categoryId > 0)
{
categoryIds.Add(categoryId);
if (model.isc)
{
//include subcategories
categoryIds.AddRange(GetChildCategoryIds(categoryId));
}
}
manufacturerId = model.mid;
//min price
if (!string.IsNullOrEmpty(model.pf))
{
decimal minPrice;
if (decimal.TryParse(model.pf, out minPrice))
minPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(minPrice, _workContext.WorkingCurrency);
}
//max price
if (!string.IsNullOrEmpty(model.pt))
{
decimal maxPrice;
if (decimal.TryParse(model.pt, out maxPrice))
maxPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(maxPrice, _workContext.WorkingCurrency);
}
if (model.asv)
vendorId = model.vid;
searchInDescriptions = model.sid;
}
//var searchInProductTags = false;
var searchInProductTags = searchInDescriptions;
//products
products = _productService.SearchProducts(
categoryIds: categoryIds,
manufacturerId: manufacturerId,
storeId: _storeContext.CurrentStore.Id,
visibleIndividuallyOnly: true,
priceMin: minPriceConverted,
priceMax: maxPriceConverted,
keywords: searchTerms,
//searchDescriptions: searchInDescriptions,
searchProductTags: searchInProductTags,
searchSku: true,
languageId: _workContext.WorkingLanguage.Id,
orderBy: (ProductSortingEnum)command.OrderBy,
pageIndex: command.PageNumber - 1,
pageSize: command.PageSize,
vendorId: vendorId);
model.Products = PrepareProductOverviewModels(products).ToList();
model.NoResults = !model.Products.Any();
//search term statistics
if (!String.IsNullOrEmpty(searchTerms))
{
var searchTerm = _searchTermService.GetSearchTermByKeyword(searchTerms, _storeContext.CurrentStore.Id);
if (searchTerm != null)
{
searchTerm.Count++;
_searchTermService.UpdateSearchTerm(searchTerm);
}
else
{
searchTerm = new SearchTerm
{
Keyword = searchTerms,
StoreId = _storeContext.CurrentStore.Id,
Count = 1
};
_searchTermService.InsertSearchTerm(searchTerm);
}
}
//event
_eventPublisher.Publish(new ProductSearchEvent
{
SearchTerm = searchTerms,
SearchInDescriptions = searchInDescriptions,
CategoryIds = categoryIds,
ManufacturerId = manufacturerId,
WorkingLanguageId = _workContext.WorkingLanguage.Id,
VendorId = vendorId
});
}
}
model.PagingFilteringContext.LoadPagedList(products);
return View(model);
}
A public action method 'AdvanceSearch' was not found on controller 'Nop.Web.Controllers.CatalogController'.

null104Invalid MailChimp "Invalid MailChimp API key: xxxx.."

I am trying this code for creating new campaign using MailChimp API in ASP.NET
public string CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 100;
string campaignID = string.Empty;
MailChimpManager mc = new MailChimpManager("sampleAPIKeyXXXXXXXXXXXXXX-us12");
// compaign Create Options
campaignCreateOptions campaignCreateOpt = new campaignCreateOptions();
campaignCreateOpt.list_id = listID;
campaignCreateOpt.subject = "subject";
campaignCreateOpt.from_email = "wisdomthnkrs#gmail.com";
campaignCreateOpt.from_name = "abc";
campaignCreateOpt.template_id = TemplateID;
campaignCreateOpt.authenticate = true;
campaignCreateOpt.auto_footer = false;
campaignCreateOpt.tracking.opens = true;
campaignCreateOpt.tracking.html_clicks = true;
campaignCreateOpt.tracking.text_clicks = true;
// Content
Dictionary<string, string> content = new Dictionary<string, string>();
content.Add("html_ArticleTitle1", "ArticleTitle1");
content.Add("html_ArticleTitle2", "ArticleTitle2");
content.Add("html_ArticleTitle3", "ArticleTitle3");
content.Add("html_Article1", "Article1");
content.Add("html_Article2", "Article2");
//Conditions
List<campaignSegmentCondition> csCondition = new List<campaignSegmentCondition>();
campaignSegmentCondition csC = new campaignSegmentCondition();
csC.field = "interests-" + 123; // where 123 is the Grouping Id from listInterestGroupings()
csC.op = "all";
csC.value = "";
csCondition.Add(csC);
// Options
campaignSegmentOptions csOptions = new campaignSegmentOptions();
csOptions.match = "all";
// Type Options
Dictionary<string, string> typeOptions = new Dictionary<string, string>();
typeOptions.Add("offset-units", "days");
typeOptions.Add("offset-time", "0");
typeOptions.Add("offset-dir", "after");
// Create Campaigns
campaignCreateParms campaignCreateParms = new campaignCreateParms(mc.APIKey, EnumValues.campaign_type.regular, campaignCreateOpt, content, csOptions, typeOptions);
campaignCreateInput campCreateInput = new campaignCreateInput(campaignCreateParms);
campaignCreate campaignCreate = new campaignCreate(campCreateInput);
//xyz();
//string abc = xxxxxxxxxxxxxxxxx;
campaignCreateOutput ccOutput = campaignCreate.Execute(campCreateInput);
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
string s = "null";
if (error.Count <= 0)
{
campaignID = ccOutput.result;
}
else
{
foreach (Api_Error ae in error)
{
Console.WriteLine("\n ERROR Creating Campaign : ERRORCODE\t:" + ae.code + "\t ERROR\t:" + ae.error);
s = s + ae.code;
s = s + ae.error;
}
}
return s;
}
but it shows an error while I am giving the right key.
here is the error,
null104Invalid MailChimp "Invalid MailChimp API key:
6ea29f158xxxxxxxxxxxx"

How to test custom Model Binders in ASP.NET MVC?

I've written some custom model binders (implementing IModelBinder) in our ASP.NET MVC application. I'm wondering what is a good approach to unittest them (binders)?
I did it this way:
var formElements = new NameValueCollection() { {"FirstName","Bubba"}, {"MiddleName", ""}, {"LastName", "Gump"} };
var fakeController = GetControllerContext(formElements);
var valueProvider = new Mock<IValueProvider>();
var bindingContext = new ModelBindingContext(fakeController, valueProvider.Object, typeof(Guid), null, null, null, null);
private static ControllerContext GetControllerContext(NameValueCollection form) {
Mock<HttpRequestBase> mockRequest = new Mock<HttpRequestBase>();
mockRequest.Expect(r => r.Form).Returns(form);
Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Expect(c => c.Request).Returns(mockRequest.Object);
return new ControllerContext(mockHttpContext.Object, new RouteData(), new Mock<ControllerBase>().Object);
}
And then I just passed in the bindingContext variable to the BindModel method of the object that implements the IModelBinder interface.
Here's a simple no-mocks way I wrote for you on my blog assuming you use the ValueProvider and not the HttpContext: http://www.hanselman.com/blog/SplittingDateTimeUnitTestingASPNETMVCCustomModelBinders.aspx
[TestMethod]
public void DateTime_Can_Be_Pulled_Via_Provided_Month_Day_Year_Hour_Minute_Second_Alternate_Names()
{
var dict = new ValueProviderDictionary(null) {
{ "foo.month1", new ValueProviderResult("2","2",null) },
{ "foo.day1", new ValueProviderResult("12", "12", null) },
{ "foo.year1", new ValueProviderResult("1964", "1964", null) },
{ "foo.hour1", new ValueProviderResult("13","13",null) },
{ "foo.minute1", new ValueProviderResult("44", "44", null) },
{ "foo.second1", new ValueProviderResult("01", "01", null) }
};
var bindingContext = new ModelBindingContext() { ModelName = "foo", ValueProvider = dict };
DateAndTimeModelBinder b = new DateAndTimeModelBinder() { Month = "month1", Day = "day1", Year = "year1", Hour = "hour1", Minute = "minute1", Second = "second1" };
DateTime result = (DateTime)b.BindModel(null, bindingContext);
Assert.AreEqual(DateTime.Parse("1964-02-12 13:44:01"), result);
}
dict could be refactored like this
FormCollection form = new FormCollection
{
{ "month1", "2" },
{ "day1", "12" },
{ "year1", "1964" },
{ "hour1", "13" },
{ "minute1", "44" },
{ "second1", "01" }
};
var bindingContext = new ModelBindingContext() { ModelName = "foo", ValueProvider = form.ToValueProvider() };

Resources