Use array to add new entry in model in asp.net mvc - arrays

I'm using asp.net mvc 4 and Entity Framework 6 to make a website where I can store data in MSSQL database. I want to make a function where it'll make a copy of an entry with different id. I want to put those copied values in an array and push it to the model to make the back-end processing faster. But I'm not sure how to do it.
Here are my codes:
public ActionResult FlatCopy(FlManagement FlTable, int FlId = 0)
{
var getOwner = rentdb.OwnerRegs.Where(a => a.username == User.Identity.Name).FirstOrDefault();
var getId = getOwner.serial;
var getLimit = getOwner.limit;
var getPosted = getOwner.posted;
FlInfo model = FlTable.Flats;
if (ModelState.IsValid)
{
if (getLimit != 0)
{
try
{
getOwner.limit = getLimit - 1;
getOwner.posted = getPosted + 1;
var dbPost = rentdb.FlatInfoes.Where(p => p.serial == FlId).FirstOrDefault();
if (dbPost == null)
{
TempData["flat_edit_fail"] = "Error! Information update failed!";
return RedirectToAction("FlatManager", new { FlPanelId = "AllFl" });
}
model.flatno = "Copy of " + dbPost.flatno;
model.type = dbPost.type;
model.owner_id = getId;
model.t_id = 0;
model.t_name = "N/A";
model.t_phone = "N/A";
model.basic = dbPost.basic;
model.electric = dbPost.electric;
model.gas = dbPost.gas;
model.water = dbPost.water;
model.total = dbPost.total;
model.advancerent = dbPost.advancerent;
model.currency = dbPost.currency;
model.title = dbPost.title;
model.status = "N/A";
db.FlatInfoes.Add(model);
db.SaveChanges();
TempData["success"] = "Information Added Successfully!";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
catch
{
TempData["fail"] = "Error! Please Provide Valid Information.";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
}
else
{
TempData["fail"] = "You've reached your post limit!";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
}
else
{
TempData["fail"] = "Error! Please Provide Valid Information.";
return RedirectToAction("FlManager", new { FlPanelId = "AllFl" });
}
}
How can I put the values in an array and push the array in model to add a new entry?

You could detach the entity from the DbContext then re-add it to the EntityCollection.
rentdb.Entry(dbPost).State = EntityState.Detached;
rentdb.FlatInfoes.Add(dbPost);
solution 2:(is better)
var model = new FlInfo();
rentdb.FlatInfoes.Add(model);
var sourceValues = rentdb.Entry(dbPost).CurrentValues;
rentdb.Entry(model).CurrentValues.SetValues(sourceValues);
rentdb.SaveChanges();

Related

System.Threading.Timer: A second operation was started on this context with

I have Console Application on .NET 5 which is Discord Bot.
While start the application i have the problem with this:
System.InvalidOperationException: A second operation was started on
this context before a previous operation completed. This is usually
caused by different threads concurrently using the same instance of
DbContext. For more information on how to avoid threading issues with
DbContext
And this is happens in Timer
This is in constructor:
_approveTimer = new Timer(async delegate
{
await CheckApproveAsync();
}, null, TimeSpan.Zero,
TimeSpan.FromSeconds(30));
public async Task CheckApproveAsync()
{
var pendingUsers = await _pendingUsers.GetAllAsync();
if (pendingUsers is null || !pendingUsers.Any())
return;
Program.Log.Debug($"Checking {pendingUsers.Count} pending users...");
foreach (var user in pendingUsers)
{
var expired = DateTime.UtcNow > user.ExpirationTime;
if (!expired) continue;
await _pendingUsers.DeleteWithDetachAsync(user);
IonicHelper.GetGuildUserById(_mainGuildId, user.UserId, out var sgUser);
try
{
var msg = await _messageService.GetMessageAsync("register-pending-expired", new FormatData(user.UserId));
await sgUser.SendIonicMessageAsync(msg);
}
catch (Exception ex)
{
await _serverHelper.SendLogAsync(_mainGuildId, "Error", $"{nameof(CheckApproveAsync)} - {ex.Message}");
}
}
var usersValidated = 0;
foreach (var user in pendingUsers)
{
RequestResult codeResult;
string code;
try
{
(codeResult, code) = await GetThirdPartyCodeByEncryptedSummonerIdAsync(user.Region, user.SummonerId);
}
catch (Exception)
{
continue;
}
if (code is null || codeResult != RequestResult.Success)
continue;
var sanitizedCode = new string(code.Where(char.IsLetterOrDigit).ToArray());
if (sanitizedCode != user.ConfirmationCode)
continue;
var (requestResult, summoner) = await GetSummonerByEncryptedPuuIdAsync(user.Region, user.PlayerUUID);
if (requestResult != RequestResult.Success)
{
await _pendingUsers.DeleteWithDetachAsync(user);
continue;
}
var (rankResult, rankData) = await GetLeaguePositionsByEncryptedSummonerIdAsync(user.Region, summoner.Id);
var soloqRank = GetRankModelFromEntry(rankData.FirstOrDefault(x => x.QueueType == "RANKED_SOLO_5x5"));
var summonerIcon = GetSummonerIconUrlById(summoner.ProfileIconId);
var lolData = new LeagueData
{
UserId = user.UserId,
SummonerRegion = user.Region,
PlayerUUID = summoner.Puuid,
AccountId = summoner.AccountId,
SummonerId = summoner.Id,
SummonerName = summoner.Name,
SummonerIcon = summonerIcon,
SummonerLevel = summoner.SummonerLevel,
SummonerRank = $"{soloqRank.Tier} {soloqRank.Rank}"
};
_ = IonicHelper.GetGuildUserById(_mainGuildId, user.UserId, out var sgUser);
await AssignRoleFromRankAsync(sgUser, soloqRank.Tier);
var data = await _leagueRepository.GetByIdAsync(user.UserId);
if (data == null)
{
await _leagueRepository.AddAsync(lolData);
}
usersValidated++;
user.SummonerName = lolData.SummonerName;
await PostValidateAsync(user);
}
Program.Log.Information($"{usersValidated} users validated.");
}
I read that it can be problem that if some method is not awaited, but i've checked it's all awaited. Which suggestions about this?

contentVersion (image/png) created is empty

//lightning controller- Here I am capturing the signature in a hidden canvas and extracting the base64 data from it , and sending it to the server side apex
var tCtx = document.getElementById('textCanvas').getContext('2d'),
imageElem = document.getElementById('Signimage');
tCtx.canvas.width = 720;
tCtx.canvas.height= 100;
tCtx.font = "italic 30px monospace";
var theSignature = n; // name of person - the text that is to be converted to an img
tCtx.fillText(theSignature,10, 50);
imageElem.src = tCtx.canvas.toDataURL();
var base64Canvas = tCtx.canvas.toDataURL().split(';base64,')[1];
component.set('{!v.storeApplicantSign}',base64Canvas);
//lightning helper
uploadonSubmit: function(component,event,helper) {
// call the apex method 'saveChunk'
var action = component.get("c.saveChunk");
action.setParams({
parentId: component.get("v.recordId"),
base64Data: component.get("v.storeApplicantSign"), // contains the base64 data
});
// set call back
action.setCallback(this, function(response) {
// store the response / Attachment Id
var result = response.getReturnValue();
var state = response.getState();
if (state === "SUCCESS") {
alert("Success");
// this.showtheToast();
} else if (state === "INCOMPLETE") {
alert("From server: " + response.getReturnValue());
} else if (state === "ERROR") {
var errors = response.getError();
if (errors) {
if (errors[0] && errors[0].message) {
console.log("Error message: " + errors[0].message);
}
} else {
console.log("Unknown error");
}
}
});
// enqueue the action
$A.enqueueAction(action);
},
// apex class
//Here decoding the data from the lightning and creating content version
#AuraEnabled
public static Id saveChunk(Id parentId,String base64Data) {
String fileId = saveTheFile(parentId,base64Data,'Signature.png');
return Id.valueOf(fileId);
}
public static Id saveTheFile(Id parentId,String base64Data,String fileName) {
base64Data = EncodingUtil.urlDecode(base64Data,'UTF-8');
ContentVersion contentVersion = new ContentVersion(
versionData = EncodingUtil.base64Decode(base64Data),
title = fileName,
pathOnClient = 'Signature'+'.'+'png',
ContentLocation='S',
FirstPublishLocationId = parentId);
system.debug('contentversion data=> '+contentVersion+'version data ----> '+contentVersion.VersionData);
insert contentVersion;
return contentVersion.Id;
}
// File is being created but it's empty that is image is not there / can't be opened as img
The issue was in apex side :
just removed the line :
`base64Data = EncodingUtil.urlDecode(base64Data,'UTF-8'); // this wasn't required
removing the above line solved it .

How to call async Task<ActionResult> from angular controller

This is my angular controller
//Save AddNewEmployee functionality
EDC.SaveNewEmployee = function () {
if (EDC.AddNewEmployeeFormValidator.validate()) {
var UserID = '0',
CandidateSubmit = '';
if (EDC.isEdit) {
UserID = EDC.rowIdToEdit;
}
EmployeeDetailService.SaveNewEmployee(EDC.NewEmpAdd, UserID, CandidateSubmit).then(function (response) {
//Close popup window
EDC.AddNewEmployeeWindow.data("kendoWindow").close();
//EDC.NewEmpSave = response;
EDC.EmployeeDetailsGrid.dataSource.read();
});
}
};
Andthis one is my MVC Controller.
public async Task<ActionResult> SavePermanentEmployee(Employee model)
{
//Sending mail to BU
string DisplayName = "New Employee";
//Sending mail to Employee
string EmpDisplayName = "Price credentials";
BAL_Employee objBalEmp = new BAL_Employee();
Price_PMS_DAL.Employee emp = new Price_PMS_DAL.Employee();
emp.ID = model.ID;
emp.EmpID = model.employeeID ?? Convert.ToString(model.employeeID).ToUpper();
emp.ReferredBy = model.referredby;
emp.DOJ = model.dateOfJoining;
emp.Status = 1;
emp.Email = model.email;
emp.BUID = model.businessUnitID;
emp.ShiftID = model.ShiftID;
emp.ModifiedBy = Session["EmpID"].ToString();
var lstNewEmployeeCreated = BAL_Employee.GetEmployees();
var result = lstNewEmployeeCreated.Where(s => s.employeeID == emp.EmpID).FirstOrDefault();
if (result != null)
{
return Json("Employee ID already exists.", JsonRequestBehavior.AllowGet);
}
else
{
int empSave = objBalEmp.UpdateEmployee(emp);
BAL_Login objBalLog = new BAL_Login();
if (empSave == 1)
{
TempData["Datarefresh"] = "refresh";
lstemp = null;
string[] datastr = emp.Email.Split(new string[] { "#" }, StringSplitOptions.None);
int empLoginSave = objBalLog.AddUser(new Price_PMS_DAL.Login { UserName = datastr[0].Trim(), EmpID = emp.EmpID, BUID = emp.BUID, ShiftID = emp.ShiftID });
if (empLoginSave == 1)
{
var data = BAL_Employee.FilterEmployeeByParam("Select TOP 1 * FROM Employee where Status=1 order by EmpID desc");
Price_PMS_DAL.Emp_Leave modelBal = new Price_PMS_DAL.Emp_Leave();
modelBal.EmpID = emp.EmpID;
int empLeavebalSave = objBalEmp.CreateEmployeeLLeaveBalRec(modelBal);
if (empLeavebalSave == 1)
{
Price_PMS_BAL.Models.BusinessUnit.BU Bus = BAL_BU.GetSPBUs().Where(b => b.ID == model.businessUnitID).First();
if (Bus != null)
{
//Sending Mail to BU when new Permanent employee added into the system
StringBuilder str = new StringBuilder();
StringBuilder cc = new StringBuilder();
StringBuilder to = new StringBuilder();
to.Append(#" " + Bus.BUHeadEmailId);
str.Append(#"Hello,<br><br> New Employee named <b>" + model.name + "</b> has been added to " + Bus.BUName + " BU " + " on " + DateTime.Now.ToShortDateString() + ".<br><br> Regards,<br> PRICE");
bool x = await Price_PMS_BAL.Models.Email.Email.SendEmail(cc, to, "New Employee Added", str.ToString(), DisplayName);
//End
}
//Sending Mail to Employee when new Permanent employee added into the system
if (emp != null)
{
StringBuilder str = new StringBuilder();
StringBuilder cc = new StringBuilder();
StringBuilder to = new StringBuilder();
to.Append(#" " + emp.Email);
//Username with last name Split
String[] Emailstring = emp.Email.Split(new[] { '#' });
String username = Emailstring[0];
//Username split with out last name
String[] Uname = username.Split(new[] { '.' });
String Unamestr = Uname[0];
Unamestr = Unamestr.Substring(0, 1).ToUpper() + Unamestr.Substring(1);
var PriceURL = "https://price.dreamorbit.com/";
str.Append(#"Hi " + Unamestr + ",<br><br> Welcome to DreamOrbit. Please login to PRICE (Projects, Resource Information & Cost Estimation) to apply for your leaves and to see your ratings etc. on a regular basis with following credentials:<br><br><br> <b><u>URL</u></b> : <a href=" + PriceURL + " target=_blank>" + PriceURL + "</a> <br> <b><u>Username</u></b> : " + username + "<br> <b><u>Password</u></b> : [Your System Password]<br><br><br> We wish you a long and mutually beneficial association with DreamOrbit. For any queries please reach out to Panchali (panchali.bharali#dreamorbit.com).<br><br> Regards,<br> PRICE");
bool x = await Price_PMS_BAL.Models.Email.Email.SendEmail(cc, to, "PRICE Credentials", str.ToString(), EmpDisplayName);
}
//End
return Json("Saved Successfully", JsonRequestBehavior.AllowGet);
}
else { return Json("Error occurred while saving data ", JsonRequestBehavior.AllowGet); }
}
else
return Json("Error occurred while saving data ", JsonRequestBehavior.AllowGet);
}
else
{
return Json("Error occurred while saving data ", JsonRequestBehavior.AllowGet);
}
}
}
Usually javascript code execute synchronously(default) and javascript has core promise object which is use to make function asynchronous.
Angularjs has core service $q which is use to make function asynchronous.
Angularjs simple example :
angular.module("starter", [])
.controller("myCtrl", function($scope, $q, $http){
var GetData = function(){
var root = 'https://jsonplaceholder.typicode.com';
var defer = $q.defer();
$http({
method: "GET",
url: root + '/posts/1'
}).then(function(response){
//success call back
defer.resolve(response);
}, function(error){
//error callbcall
defer.reject();
});
return defer.promise;
};
$scope.AsynchCall = function(){
GetData().then(function(response){
//success call back
console.log(response);
alert(JSON.stringify(response));
}, function(error){
//error callbcall
console.log(JSON.stringfy(error));
alert(error);
});
};
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="starter" ng-controller="myCtrl">
<button ng-click="AsynchCall()"> Asynch call </button>
</body>
</html>
This is because JSON.stringify will return the return value of the toJSON function if it exists.

angular's equivalent of ko.utils.arrayMap or adding extra properties to returned data array?

Im in the process of converting a knockout app to angular, I currently get an array of objects from the server but I would like to extend each object by adding some extra properties.
In knockout I would do the following:
var mappedResults = ko.utils.arrayMap(results, function(item) {
item.selected = ko.observable(true);
item.viewPreview = ko.observable(false);
return new reed.search.Candidate(item, self.viewModel.fileDownloadFailCookieName);
});
and the Candidate viewmodel:
reed.search.Candidate = function(data, fileDownloadFailCookieName) {
debugger
if (data == null) {
throw 'Error: cannot initiate candidate';
}
this.fileDownloadFailCookieName = fileDownloadFailCookieName;
this.candidateId = data.CandidateId;
this.name = data.Name;
this.surname = data.Surname;
this.forename = data.Forename;
this.displayLocation = data.DisplayLocation;
this.lastJobDetails = data.LastJobDetails;
this.displayPayRate = data.DisplayPayRate;
this.lastSignIn = data.LastSignIn;
this.downloadCVUrl = data.DownloadCVUrl;
this.additionalInfo = data.AdditionalInfo;
this.isAvailable = (data.IsAvailable) ? "Availability confirmed" : "";
this.availableMornings = data.AvailableMornings;
this.availableAfternoons = data.AvailableAfternoons;
this.availableEvenings = data.AvailableEvenings;
this.availableWeekends = data.AvailableWeekends;
this.availableShiftWork = data.AvailableShiftWork;
this.availableNights = data.AvailableNights;
this.availabilityUpdatedOn = data.AvailabilityUpdatedOn;
this.availabilityUpdatedOnDate = "| <strong>Availability updated</strong> " + data.AvailabilityUpdatedOn;
this.isAvailableForSomething =
this.availableMornings
|| this.availableAfternoons
|| this.availableEvenings
|| this.availableWeekends
|| this.availableShiftWork
|| this.availableNights;
this.viewPreview = ko.observable(false);
this.selected = ko.observable(false);
this.hasBeenNotified = ko.observable(false);
this.select = function() {
this.selected(true);
};
this.deSelect = function() {
this.selected(false);
};
this.HasFlagSet = function(availability) {
return availability ? "availabilitySelected" : "availabilityNotSelected";
};
this.ajaxCvDownload = function() {
var path = window.location.href,
iframeError,
cookieName = this.fileDownloadFailCookieName;
// download path
path = path.match(/(.+\/)/ig)[0];
if (path.match(/home/ig)) {
path = path.replace('home', this.downloadCVUrl);
} else {
path = this.downloadCVUrl;
};
$('<iframe />').attr('src', path)
.hide()
.appendTo('body').load(function() {
var message = decodeURIComponent(reed.shared.utils.getCookie(cookieName));
message = message.replace(/\+/g, " ");
if (message.length > 0 && message != "null") {
reed.shared.utils.showMessage(message, "Download Failed");
}
});
}
}
how can I achieve the same functionality in angular?
You don't need angular for this array itself contains a map function and all modern browsers support it.
var mappedResults = results.map(function(item) {
item.selected = true;
item.viewPreview = false;
return new reed.search.Candidate(item,
self.viewModel.fileDownloadFailCookieName);
});
Some other things you can improve. Firstly if you are using webapi to return data, use a formatter that fixes casing.Check this blog http://blogs.msmvps.com/theproblemsolver/2014/03/26/webapi-pascalcase-and-camelcase/
Once you have the formatter lines such as these are not required
this.surname = data.Surname;
You can then use angular.extend to copy properties into your class.

Rendering a child page in a parent page

is it possible to render a specific page in a razor function. I tried #RenderPage but i cant figure out the path. Are there any built in functions to accomplish this?
Thanks Johan
Not really a C1 specific approach, but personally my best approach has been to just make a separate web-request for the page in question, parse out the html and render it.
This code can serve as an example, its a 1:1 of what i'm using. As you can see the trick is to find the element that wraps your content, in my example its the element inside that has an id equals to ContentColumnInner
public static string GetContentFromPage(Guid pageId)
{
var DomainName = HttpContext.Current.Request.Url.Authority;
var Uri = String.Format("http://{0}/page({1})", DomainName, pageId);
var request = WebRequest.Create(Uri);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
using (var response = (HttpWebResponse)request.GetResponseWithoutException())
{
if (response.StatusCode != HttpStatusCode.OK)
{
LogError("StatusCode: " + response.StatusCode);
return null;
}
// Get the stream containing content returned by the server.
using (var responseStream = response.GetResponseStream())
{
if (responseStream == null)
{
LogError("ResponseStream is null");
return null;
}
// Open the stream using a StreamReader for easy access.
using (var stream = new StreamReader(responseStream))
{
// Read the content.
var responseFromServer = stream.ReadToEnd();
var beforeBodyStartIndex = responseFromServer.IndexOf("<body", StringComparison.Ordinal);
var afterBodyEndIndex = responseFromServer.LastIndexOf("</body>", StringComparison.Ordinal) + 7;
var body = responseFromServer.Substring(beforeBodyStartIndex, afterBodyEndIndex - beforeBodyStartIndex);
try
{
var xmlDocument = XElement.Parse(body);
var content = xmlDocument.Descendants().FirstOrDefault(o => o.Attribute("id") != null && o.Attribute("id").Value.EndsWith("ContentColumnInner"));
if (content == null || !content.HasElements)
{
return null;
}
var reader = content.CreateReader();
reader.MoveToContent();
return reader.ReadInnerXml();
}
catch (XmlException ex)
{
LogError("Error parsing xml: " + ex.Message);
return null;
}
}
}
}
}

Resources