How to prevent duplicate validation while updating the value without any changes? - spring-mvc

#RequestMapping(value = "/updateYearMaster", method = RequestMethod.POST)
public String updateYearmaster(#RequestParam(value = "id", required = false) Long id,
#RequestParam(value = "fromyear", required = false) Date fromyear,
#RequestParam(value = "toyear", required = false) Date toyear,
#RequestParam(value = "status", required = false) String status,
#RequestParam(value = "yeardescription", required = false) String yeardescription, Model model) {
Yearmaster yearmaster = new Yearmaster(fromyear, toyear, status, yeardescription);
yearmaster.setId(id);
List val = yearmasterService.duplicateEditYear(fromyear, toyear, id);
if (!val.isEmpty()) {
model.addAttribute("yearmaster", yearmaster);
errorMessage = "fromyear and toyear combination is already exist";
model.addAttribute("errorMessage", errorMessage);
return "edit-year-master";
} else {
yearmasterService.save(yearmaster);
return "redirect:/yearmaster";
}
}

Related

send data to RoutingSlipCompleted consume method from activity

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);
});

File extension not being detected for file upload

Ok I have the following extensions I am checking in my code.
FileAttachments.FileAttachmentTypes fileAttachmentType = FileAttachments.FileAttachmentTypes.None;
The strings below in the conts are helled in a constants file
public const string wordExtensions = "docx;docm;doc";
public const string imageExtensions = "gif;tiff;tif;png;eps;raw;bmp;jpeg;jpg";
public const string excelExtensions = "csv;xml;xls;xlsb;xlsm;xlsx";
Which is then parsed down here
I am getting my extension from the File Info class as such
foreach (var fileAttachments in FormFile) {
if (fileAttachments.Length > 0) {
string filePath = Path.Combine(hostingEnvironment.WebRootPath, "Uploads");
var tennantId = GetCurrentTennantId().Result;
var settings = _context.SystemSetup.FirstOrDefault().UploadFolderPath;
string uniqueFilename = Guid.NewGuid().ToString() + "_" + fileAttachments.FileName;
string savedFileName = Path.Combine(filePath, uniqueFilename);
FileInfo infoFile = new FileInfo(savedFileName);
string extension = infoFile.Extension.Replace(".","");
Here I check the file extension Parameter above in the semi colan separated strings
if (extension.Contains(Constants.imageExtensions)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Image;
} else if (extension.Contains("pdf")) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.PDF;
} else if (extension.Contains(Constants.videoFormats)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Video;
} else if (extension.Contains(Constants.excelExtensions)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Excel;
} else if (extension.Contains(Constants.wordExtensions)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Word;
} else if (extension.Contains(Constants.audioExtensions)) {
fileAttachmentType = FileAttachments.FileAttachmentTypes.Voice;
}
}
Types is just an area for categorizing them into tabs for front end display
public enum FileAttachmentTypes {
[Display(Name = "Microsoft Word")]
Word = 1,
[Display(Name = "Microsoft Excel")]
Excel = 2,
[Display(Name = "Image")]
Image = 3,
[Display(Name = "Voice Recordings")]
Voice = 4,
[Display(Name = "PDF")]
PDF = 5,
[Display(Name = "Video")]
Video = 6,
[Display(Name = "Evidence")]
Evidence = 7,
[Display(Name = "None")]
None = 8,
[Display(Name = "Notes")]
NOTES = 9,
[Display(Name = "Shared Case")]
SharedCase = 10,
[Display(Name = "Created Case")]
CreatedCase = 11
}
My Question is why is it not finding it for a word document of extension docx when its clearly there

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?

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"

Resources