I am currently inserting / updating data in a SQL database using C# and linq. The following code works perfectly but i feel that it is messy and is duplicated.
Could you please have a look at the following code and tell me if there is a quicker to update data instead of me having to duplicate my code
Thank you
Incident inc = new Incident
{
AccountID = AccountID,
SiteID = siteID,
DepartmentID = departmentID,
LocationID = LocationID,
QuestionCategoryID = CategoryID,
IncidentSourceID = IncidentSourceID,
IncidentTypeID = IncidentTypeID,
NonConformanceTypeID = NonConID,
ProductGroupID = ProductGroupID,
ProductID = ProductID,
ComponentID = ComponentID,
ProductReference = prodRef,
CurrentAssignedUserID = UserId,
CurrentAssignedContactID = contactid,
OriginalAssignedUser = UserId,
OriginalAssignedContact = contactid,
LoggedByUserID = logUserId,
LoggedByContactID = logContactid,
IncidentTitleID = IncidentTitleID,
Title = IncidentTitle.ToString(),
Description = problemDesc,
Comments = comments,
ActionsRequired = actions,
RiskPriorityID = RiskPriorityTypeID,
AffectedPartyID = affectedPartyID,
ImpactLevel = Convert.ToInt32(impact),
Justification = justification,
EsculationDate = DateTime.Today,
PriorityID = PriorityID,
OriginalPriorityID = PriorityID,
CreatedByUser = Convert.ToInt32(loggedInUserID),
UpdatedBy = Convert.ToString(loggedInUserID),
RiskID = RiskID,
Active = true,
StatusID = 1,
DelayedDate = null,
IncidentCloseDate = null,
IncidentDate = DateTime.Now,
IncidentPendingDate = DateTime.Now,
LoggedDate = DateTime.Now,
LastUpdated = DateTime.Now,
LastActionTaken = DateTime.Now
};
// Save the data to the database
if (Request.QueryString["IncidentID"] == null)
{
// Insert a new incident.
db.Incidents.Add(inc);
db.SaveChanges();
}
else
{
//update an existing incident.
long ID = Convert.ToInt64(Request.QueryString["IncidentID"]);
var record = db.Incidents.Where(i => i.IncidentID == ID).FirstOrDefault();
record.AccountID = AccountID;
record.SiteID = siteID;
record.DepartmentID = departmentID;
record.LocationID = LocationID;
record.QuestionCategoryID = CategoryID;
record.IncidentSourceID = IncidentSourceID;
record.IncidentTypeID = IncidentTypeID;
record.NonConformanceTypeID = NonConID;
record.ProductGroupID = ProductGroupID;
record.ProductID = ProductID;
record.ComponentID = ComponentID;
record.ProductReference = prodRef;
record.CurrentAssignedUserID = UserId;
record.CurrentAssignedContactID = contactid;
record.OriginalAssignedUser = UserId;
record.OriginalAssignedContact = contactid;
record.LoggedByUserID = logUserId;
record.LoggedByContactID = logContactid;
record.IncidentTitleID = IncidentTitleID;
record.Title = IncidentTitle.ToString();
record.Description = problemDesc;
record.Comments = comments;
record.ActionsRequired = actions;
record.RiskPriorityID = RiskPriorityTypeID;
record.AffectedPartyID = affectedPartyID;
record.ImpactLevel = Convert.ToInt32(impact);
record.Justification = justification;
record.EsculationDate = DateTime.Today;
record.PriorityID = PriorityID;
record.OriginalPriorityID = PriorityID;
record.CreatedByUser = Convert.ToInt32(loggedInUserID);
record.UpdatedBy = Convert.ToString(loggedInUserID);
record.RiskID = RiskID;
record.Active = true;
record.StatusID = 1;
record.DelayedDate = null;
record.IncidentCloseDate = null;
record.IncidentDate = DateTime.Now;
record.IncidentPendingDate = DateTime.Now;
record.LoggedDate = DateTime.Now;
record.LastUpdated = DateTime.Now;
record.LastActionTaken = DateTime.Now;
db.SaveChanges();
}
Just set your properties the once, regardless of weather its an existing entity or not.
var id = Request.QueryString["IncidentID"];
var incidentId = String.IsNullOrEmpty(id) ? 0 : int.Parse(id);
var record = incidentId !=0 ?
db.Incidents.FirstOrDefault(i => i.IncidentID == incidentId); : new Incident();
record.AccountID = AccountID;
record.SiteID = siteID;
record.DepartmentID = departmentID;
//etc.......
if (incidentId == 0)
{
//set any fields here that are for add only
record.CreatedByUser = ...
db.Incidents.Add(record);
}
db.SaveChanges();
Incident inc;
if (Request.QueryString["IncidentID"] == null)
{
inc = new Incident();
// set properties that are specific to insert
db.Incidents.Add(inc);
}
else
{
long ID = Convert.ToInt64(Request.QueryString["IncidentID"]);
inc = db.Incidents.Where(i => i.IncidentID == ID).First();
// set properties that are specific to update
}
// set common properties
db.SaveChanges();
You could do the following:
var incidentInitializer = new Action<Incident>(incident =>
{
incident.AccountID = AccountID,
incident.SiteID = siteID,
...
};
// Save the data to the database
if (Request.QueryString["IncidentID"] == null)
{
// Insert a new incident.
var inc = new Incident();
incidentInitializer(inc);
db.Incidents.Add(inc);
db.SaveChanges();
}
else
{
//update an existing incident.
long ID = Convert.ToInt64(Request.QueryString["IncidentID"]);
var record = db.Incidents.Where(i => i.IncidentID == ID).FirstOrDefault();
incidentInitializer(record);
db.SaveChanges();
}
Related
My project has 2 part ClientSide and Server side. In Server side I have Controller that it needs query and command. I put both of them and my command has a handler but after I'd done my handler it throws a error that say: not all code paths return a value.
this is my handler:
public Task<ReturnCreateDataQuery> Handle(CreateCompletedActCommand request, CancellationToken cancellationToken)
{
var party = _dbContext.Parties.SingleOrDefault(t => t.PartyCode == request.PartyCode);
if (party == null) throw new Exception("");
if ((bool)request.ResonableType)
{
var departmentText = request.DepartmentIds.Any() ? string.Join(",", request.DepartmentIds.Distinct().OrderBy(t => t)) : string.Empty;
var cartableActs = new List<CartableActModel>();
var cartable = new CartableStateModel()
{
ClaimId = request.ClaimId,
CreationDate = DateTime.Now,
StatusCode = (int)Enumeration.StateType.Compeleted,
PreviouseCartableStateId = request.CartableStateId
};
var cartableAct = new CartableActCompleteModel()
{
ActCode = (int)Enumeration.ActType.CompleteCustomerData,
ActorId = party.PartyId,
CartableStateId = cartable.CartableStateId,
ChangeDate = DateTime.Now,
ClaimSubjectId = request.ClaimSubjectId,
ClaimType = request.ClaimType,
Departments = departmentText,
ExpertPartyId = request.ExpertPartyId,
ResonableType = request.ResonableType,
SubClaimSubjectId = request.SubClaimSubjectId,
CompletedDescription = request.CompletedDescription,
};
var attachments = request.Attachments.Select(t => new ActAttachmentModel
{
AttachmentContent = t.AttachmentContent,
ActAttachmentId = cartableAct.CartableActId,
ActId = cartableAct.CartableActId,
CreationDate = DateTime.Now,
Creator = party.PartyId,
FileExtension = t.FileExtension,
Title = t.Title,
MimeType = t.MimeType
}).ToList();
cartableAct.ActAttachments = attachments;
cartableActs.Add(cartableAct);
cartable.CartableActs = cartableActs;
_dbContext.Cartables.Add(cartable);
_dbContext.SaveChangesAsync(cancellationToken);
}
else
{
var cartableActs = new List<CartableActModel>();
var cartable = new CartableStateModel()
{
ClaimId = request.ClaimId,
CreationDate = DateTime.Now,
StatusCode = (int)Enumeration.StateType.Finished,
};
var cartableAct = new CartableActSatisficationModel()
{
ActCode = (int)Enumeration.ActType.SatisficationCustomer,
ActorId = party.PartyId,
CartableStateId = cartable.CartableStateId,
ChangeDate = DateTime.Now,
IsSatisfy = false,
SatisfyLevel = "1",
};
var attachments = request.Attachments.Select(t => new ActAttachmentModel
{
AttachmentContent = t.AttachmentContent,
ActAttachmentId = cartableAct.CartableActId,
ActId = cartableAct.CartableActId,
CreationDate = DateTime.Now,
Creator = party.PartyId,
FileExtension = t.FileExtension,
Title = t.Title,
MimeType = t.MimeType
}).ToList();
var outBox = new OutBoxModel
{
SentType = "SMS",
ClaimId = request.ClaimId,
IsSent = false,
PartyCode = request.PartyCode,
IsCustomer = true
};
cartableAct.ActAttachments = attachments;
cartableActs.Add(cartableAct);
cartable.CartableActs = cartableActs;
_dbContext.Cartables.Add(cartable);
_dbContext.OutBoxes.Add(outBox);
_dbContext.SaveChangesAsync(cancellationToken);
}
}
I don't know how can I fix this error I search a lot of source but I can't understand which value should return if you know this I would thank you.
Change your metod header
public async Task Handle(CreateCompletedActCommand request, CancellationToken cancellationToken)
{
....your code
}
That's when i need to use the Stripe API so when i need it, it will go wrong and make mistakes in the Stripe area as you can see here.
i have : v15.6.1 on Stripe.net
Where it goes wrong is here:
planservice.Create(new StripePlanCreateOptions()
to here:
PlanId = abn.PriceValueUnikId };
all the value I get by json eg userid, pric and pricId there is content in them.
[HttpPost]
public IActionResult Post([FromBody] JObject token)
{
var api = Settings.ConstName.StrinpAPIKeyTest;
StripeConfiguration.SetApiKey(api);
var chargeService = new StripeChargeService();
chargeService.ExpandBalanceTransaction = true;
chargeService.ExpandCustomer = true;
chargeService.ExpandInvoice = true;
//StripeCharge stripeCharge = chargeService.Get(api);
var customerSerive = new StripeCustomerService(api);
var subservice = new StripeSubscriptionService(api);
var planservice = new StripePlanService(api);
var pricId = (int)token.GetValue("pricid");
var pric = (int)token.GetValue("pric");
var userid = (int) Userid();
var abn = _dbContext.PriceValue.FirstOrDefault(i => i.PriceValueId == pricId || i.Price == pric);
//Finder information omkring pakken til den enkelte pakke.
var currentUser = _dbContext.Users.FirstOrDefault(i => i.UserId == userid);
if (currentUser != null)
{
if (abn != null)
{
var orderid = Settings.ValueWordsAndNumbers.OrdreValue();//Orderid
var planType = $"OrderId: {orderid} - Pris: {abn.Price} - Mdr: {abn.Months} UserId: {userid}";
planservice.Create(new StripePlanCreateOptions()//error from here
{
Amount = int.Parse(abn.Price.ToString()) * 100,
Nickname = planType,
Currency = "dkk",
Interval = "month",
IntervalCount = abn.Months,
Id = abn.PriceValueUnikId
});
var newCustomer = new StripeCustomerCreateOptions
{
SourceToken = token["id"].ToString(),
Email = token["email"].ToString(),
PlanId = abn.PriceValueUnikId,
};//error to here
var stripeCustomer = customerSerive.Create(newCustomer);
}
}
var planOptions = new StripePlanCreateOptions() {
Product = new StripePlanProductCreateOptions() {
Name = "planType"
},
Amount = int.Parse(abn.Price.ToString()) * 100,
Nickname = planType,
Currency = "dkk",
Interval = "month",
IntervalCount = abn.Months,
};
var planService = new StripePlanService();
StripePlan plan = planService.Create(planOptions);
API version to 2018-02-06 and add support for Product & Plan API
Now Product is REQUIRED.
you need past ID product or dictionary containing fields used to create a service product.
var planOptions = new StripePlanCreateOptions() {
ProductId ="Product Plan id",
Amount = int.Parse(abn.Price.ToString()) * 100,
Nickname = planType,
Currency = "dkk",
Interval = "month",
IntervalCount = abn.Months,
};
enter image description here
[WebMethod]
public void AddEmployementRequest(EmployementRequest emp)
{
EmployeeSkill employeeSkill = new EmployeeSkill
{
Skill = emp.,
Description = emp.
};
EmployeeLanguage employeeLanguage = new EmployeeLanguage
{
Name = emp.,
ConversationLevel = emp.
};
EmployeeCours employeeCours = new EmployeeCours
{
Date =emp. ,
Course = emp.,
Duration = emp.,
Association = emp.,
Description = emp.
};
EmployementRequest employementRequest = new EmployementRequest
{
Name = emp.Name,
Address = emp.Address,
Surnam = emp.Surnam,
Father = emp.Father,
IDNumber = emp.IDNumber,
IDCardNumber = emp.IDNumber,
IDCity = emp.IDCity,
Birthday = emp.Birthday,
Birthplace = emp.Birthplace,
Nationality = emp.Nationality,
Religion = emp.Religion,
Phone = emp.Phone,
Cell = emp.Cell,
EmergencyAddress = emp.EmergencyAddress,
EmergencyName = emp.EmergencyName,
EmergencyPhone = emp.EmergencyPhone,
ParentedPeople = emp.ParentedPeople,
Gender = emp.Gender,
MarriageStatus = emp.MarriageStatus,
Residency = emp.Residency,
InsuranceCode = emp.InsuranceCode,
InsuranceStatus = emp.InsuranceStatus,
VehicleType = emp.VehicleType,
MilitaryServiceStatus = emp.MilitaryServiceStatus,
EducatedFrom = emp.EducatedFrom,
EducationField = emp.EducationField,
EducationGrade = emp.EducationGrade,
ExtraWorkCapability = emp.ExtraWorkCapability,
LeisureTimeHobbies = emp.LeisureTimeHobbies,
Salary = emp.Salary,
IntroducerName = emp.IntroducerName,
IntroductionMethod = emp.IntroductionMethod,
Illness = emp.Illness,
VehicleStatus = emp.VehicleStatus,
PKEmploymentRequest = Guid.NewGuid(),
};
employementRequest.EmployeeLanguages.Add(employeeLanguage);
employementRequest.EmployeeSkills.Add(employeeSkill);
employementRequest.EmployeeCourses.Add(employeeCours);
using (var db = new UKN_DBNAMEEntities())
{
db.EmployementRequests.Add(employementRequest);
db.SaveChanges();
}
}
I want to insert to all parent and child tables at once ,As you can see I can't access the properties in child tables and also there's no intellisense to show the properties unlike the parent
I think I need a Linq query but I have no idea
have you tried
[WebMethod]
public void AddEmployementRequest(EmployementRequest emp) {
emp.PKEmploymentRequest = Guid.NewGuid();
using (var db = new UKN_DBNAMEEntities()) {
db.EmployementRequests.Add(emp);
db.SaveChanges();
}
}
It may/should do, but...
Consider:
using automapper or the like;
use some query to avoid recreation of Language or Skil
I've got the following code and I wish to set the AssignmentID and the ToDoAssignmentID to the same value. Setting AssignmentID to workOrder.AssignmentID works just fine, but setting ToDoAssignmentID to workOrder.AssignmentID results in ToDoAssignmentID being set to 0. Why is that?
workOrder.ClientID = this.Client.ClientID;
workOrder.AssignmentID = this.WorkOrderID;
workOrder.AssignmentNumber = this.GetNextWorkOrderNumber(this.Client);
workOrder.CustomerID = this._CustomerID;
workOrder.DateCreated = this.Created;
workOrder.DatoAvtaltStart = this.AgreedStart == DateTime.MinValue ? new DateTime().MinSDTValue() : this.AgreedStart;
workOrder.DatoAvtaltSlutt = this.AgreedEnd == DateTime.MinValue ? new DateTime().MinSDTValue() : this.AgreedEnd;
workOrder.DateStopped = this.Ended == DateTime.MinValue ? new DateTime().MinSDTValue() : this.Ended;
workOrder.CreatedByEmployeeID = this._CreatedByEmployeeID;
workOrder.ResponsibleEmployeeID = this._ResponsibleEmployeeID;
workOrder.KoordinatorAnsattId = this._CoordinatorEmployeeID;
workOrder.Description = this.Description;
workOrder.Notes = this.Notes;
workOrder.EstimertTimerFra = this.EstimatedHoursFrom;
workOrder.EstimertTimerTil = this.EstimatedHoursTo;
workOrder.EstimatedBillingDate = this.EstimatedBillingDate;
workOrder.Priority = (byte)this.Priority;
workOrder.OBS = this.OBS;
workOrder.CustomerReference = this.CustomersReference;
workOrder.InterntOrdrenr = this.InternalOrderNumber;
workOrder.EksterntOrdrenr = this.ExternalOrderNumber;
workOrder.AssignmentStatusID = this.WorkOrderStatusID;
foreach (var activity in this.Activities)
{
var ProductID = 0;
try
{
ProductID = activity.Product.ProductID;
}
catch (Exception ex)
{
}
workOrder.Activities.Add(new Activity()
{
ActivityID = activity.ActivityID,
ClientID = activity.Client.ClientID,
AssignmentID = workOrder.AssignmentID,
Description = activity.Description,
Notes = activity.Notes,
IsBillable = activity.Billable,
Priority = (byte)activity.Priority,
ActivityTypeID = activity.ActivityType.TypeID,
PerformedByEmployeeID = activity.PerformedByEmployee.EmployeeID,
ProductID = ProductID,
ToDo = activity.IsPlanned,
ToDoAssignmentID = workOrder.AssignmentID,
ToDoCustomerID = workOrder.CustomerID
});
}
workOrderContext.SubmitChanges();
The key is not to think database style, but ORM style.
So instead of setting keys, you assign entities.
so change
ToDoAssignmentID = workOrder.AssignmentID
to (most probable guess of tablenames, check the definition of your entity) the following assignment of entities
ToDoAssignment = workOrder
This will be handled during SubmitChanges as well.
I am using CRM 4 and the SDK to grab cases like so:
public List<Case> GetCases()
{
List<Case> cases = new List<Case>();
#region Retrieve Resolved Cases
try
{
InitSession();
RetrieveMultipleRequest req = new RetrieveMultipleRequest();
req.ReturnDynamicEntities = true;
//QueryExpression says what entity to retrieve from, what columns we want back and what criteria we use for selection
QueryExpression qe = new QueryExpression();
qe.EntityName = EntityName.incident.ToString();
List<string> attributes = new string[] {
"incidentid","title" ,"description", "ticketnumber", "statuscode",
"kez_allocatedhours",
"customerid",
"casetypecode"
}.ToList();
//columns to retireve
ColumnSet AvailabilityColumnSet = new ColumnSet();
AvailabilityColumnSet.Attributes = attributes.ToArray();
qe.ColumnSet = AvailabilityColumnSet;
//filter
FilterExpression fe = new FilterExpression();
fe.FilterOperator = LogicalOperator.And;
//condtion for filter
ConditionExpression isResolved = new ConditionExpression();
isResolved.AttributeName = "statuscode";
isResolved.Operator = ConditionOperator.NotEqual;
isResolved.Values = new string[] { "5" };
fe.Conditions = new ConditionExpression[] { isResolved }; //Add the conditions to the filter
qe.Criteria = fe; //Tell the query what our filters are
req.Query = qe; //Tell the request the query we want to use
//retrieve entities
RetrieveMultipleResponse resp = svc.Execute(req) as RetrieveMultipleResponse;
if (resp != null)
{
BusinessEntity[] rawResults = resp.BusinessEntityCollection.BusinessEntities;
List<DynamicEntity> castedResults = rawResults.Select(r => r as DynamicEntity).ToList();
foreach (DynamicEntity result in castedResults)
{
string id = GetProperty(result, "incidentid");
string title = GetProperty(result, "title");
string description = GetProperty(result, "description");
string ticket = GetProperty(result, "ticketnumber");
string customer = GetProperty(result, "customerid");
int statuscode = -1;
string statusname = "";
double estHours = 0.0;
string casetype = "";
int casetypecode = -1;
Property prop = result.Properties.Where(p => p.Name == "statuscode").FirstOrDefault();
if (prop != null)
{
StatusProperty status = prop as StatusProperty;
if (status != null)
{
statuscode = status.Value.Value;
statusname = status.Value.name;
}
}
prop = result.Properties.Where(p => p.Name == "kez_allocatedhours").FirstOrDefault();
if (prop != null)
{
CrmFloatProperty fl = prop as CrmFloatProperty;
if (fl != null)
{
estHours = fl.Value.Value;
}
}
prop = result.Properties.Where(p => p.Name == "casetypecode").FirstOrDefault();
if (prop != null)
{
PicklistProperty fl = prop as PicklistProperty;
if (fl != null)
{
casetype = fl.Value.name;
casetypecode = fl.Value.Value;
}
}
Case c = new Case();
c.ID = id;
c.Title = title;
c.Description = description;
c.StatusCode = statuscode;
c.StatusName = statusname;
c.TicketNumber = ticket;
c.CustomerName = customer;
c.EstimatedHours = estHours;
c.Type = casetype;
c.TypeCode = casetypecode;
bool allowedThroughStat = true;
bool allowedThroughType = true;
var userStatuses = SettingsManager.Get("CRMUserStatusReasons").Split(';').ToList().Where(p => p.Length > 0).ToList();
var userTypes = SettingsManager.Get("CRMUserCaseTypes").Split(';').ToList().Where(p => p.Length > 0).ToList();
if(userStatuses.Count > 0 && !userStatuses.Contains(c.StatusCode.ToString()))
{
allowedThroughStat = false;
}
if (userTypes.Count > 0 && !userTypes.Contains(c.TypeCode.ToString()))
{
allowedThroughType = false;
}
if(allowedThroughStat && allowedThroughType)
cases.Add(c);
}
}
}// end try
catch (Exception)
{
return null;
// The variable 'e' can access the exception's information.
// return "Error Message: " + e.Message.ToString() + " | Stack Trace: " + e.StackTrace.ToString();
}
return cases;
#endregion
}
However, now I need to be able to change the status and title of a case from C# given its incidentid.
Ive looked at the SDK docs and cannot find an example of this.
Anyone work with this before?
Thanks
Simply put, above is code to read an incident. Could I get an example of writing an incident field, Just one. Ex: How could I change the title of an incident.
You can call the Update method on the CrmService. Here is the SDK article.
Case c = new Case();
c.ID = id;
c.Title = title;
svc.Update(c);
To change the state of an entity you use the setstaterequest. If you want to do it to a dynamic entity there's a description in this blog