Adding and Editing using same connection in EF4 - c#

I'm using EF4 to look up a item in the database, to determine if it needs to be inserted or edited like so:
List<Campground> CampgroundEntities = new List<Campground>();
using (MiscEntities pd = new MiscEntities())
{
Campground kc = pd.Campground.FirstOrDefault(i => i.Name == name);
if (kc != null)
{
kc.StreetAddress = streetAddress;
kc.City = city;
kc.State = state;
kc.Zip = zip;
kc.URL = campgroundUrl;
kc.UpdatedDT = DateTime.Now;
CampgroundEntities.Add(kc);
}
else
{
kc = new Campground();
kc.Name = name;
kc.StreetAddress = streetAddress;
kc.City = city;
kc.State = state;
kc.Zip = zip;
kc.URL = campgroundUrl;
kc.AddedDateTime = DateTime.Now;
CampgroundEntities.Add(kc);
}
}
I'm adding my entities to a list, then after that, I want to commit those changes to the database:
using (MiscEntities pd = new MiscEntities())
{
foreach (var item in CampgroundEntities)
{
pd.Campground.AddObject(item);
}
pd.SaveChanges();
}
Now obviously that doesn't work, but if possible, I'd like to use that connection to handle both inserting and updating. Can it be done?

using (MiscEntities pd = new MiscEntities())
{
Campground kc = pd.Campground.FirstOrDefault(i => i.Name == name);
if (kc == null)
{
kc = new Campground();
pd.Campground.Add(kc);
}
kc.StreetAddress = streetAddress;
kc.City = city;
kc.State = state;
kc.Zip = zip;
kc.URL = campgroundUrl;
kc.UpdatedDT = DateTime.Now;
CampgroundEntities.Add(kc);
}

Related

Get duplicate Realtime Database Firebase results in Xamarin

I'm trying to build realtime chat through Realtime Database Firebase and Xamarin. However there is a problem like this, hope someone can help:
protected async void LoadChat()
{
string userid = "123456789";
var getroom = (await fc.Child("RecordsChat").OnceAsync<GetRoomChats>()).Select(x =>
new GetRoomChats
{
RoomID = x.Key
}).ToList();
List<GetRoomChats> listroomuser = new List<GetRoomChats>();
foreach (var room in getroom)
{
string str = null;
string[] strArr = null;
string roomget = room.RoomID;
str = roomget + "_";
char[] splitchar = { '_' };
strArr = str.Split(splitchar);
var getroomuser = strArr.Distinct().ToList();
foreach (var item in getroomuser)
{
if (item == userid)
{
var roomgetuser = new GetRoomChats()
{
RoomID = roomget
};
listroomuser.Add(roomgetuser);
}
}
}
if (listroomuser.Count() > 0)
{
var FirebaseClient = fc
.Child("RecordsChat")
.AsObservable<GetRoomChats>()
.Subscribe(async(dbevent) =>
{
//IteamGetRoomChats.Clear();
foreach (var room in listroomuser)
{
if (dbevent.Key == room.RoomID)
{
var lst = (await fc.Child("RecordsChat").Child(dbevent.Key).OrderByKey().LimitToLast(1).OnceAsync<MyDatabaseRecord>()).Select(x =>
new MyDatabaseRecord
{
NameUser = x.Object.NameUser,
Content = x.Object.Content,
RoomID = x.Object.RoomID,
DayCreate = x.Object.DayCreate,
AvatarUser = x.Object.AvatarUser,
sender_uid = x.Object.sender_uid,
receiver_uid = x.Object.receiver_uid,
receiver_read = x.Object.receiver_read
});
bool unread = false;
foreach (var i in lst)
{
if(i.sender_uid == userid)
{
i.Content = "You: " + i.Content;
var customerList = await apiServiceUserinfo.GetCustomersInfo(i.receiver_uid);
string nameget = customerList.NameStore;
string avatarget = customerList.AvatarStore;
i.NameUser = nameget;
i.AvatarUser = avatarget;
if (i.sender_read == true)
{
unread = false;
}
}
else
{
if (i.receiver_read == false)
{
i.BackgroundUser = "#f5f4f4";
unread = true;
}
}
var last = new GetRoomChats()
{
NameLast = i.NameUser,
ContentLast = i.Content,
RoomID = i.RoomID,
DayCreateLast = i.DayCreate,
AvatarLast = i.AvatarUser,
BackgroundUnread = i.BackgroundUser,
DotUnread = unread
};
IteamGetRoomChats.Add(last);
}
}
}
});
}
BindingContext = this;
}
In my example above, it actually gets the data. I try to check in the loop, to get the last content of the message. However, the displayed results are duplicated
Looking forward to everyone's help. Thank you!

How to add a Group of data with only one unique group ID using C# in MSSQL?

I want to create a group of registered clients using different products, categories and sub categories.
I am using asp.net C# and updating database using entity model.
int PID = Convert.ToInt32(ddProduct.SelectedValue);
if (isValidName(txtGroupName.Text))
{
if (ddBusinessCategory.SelectedValue == "0")
{
var clients = db.Client_Master.Where(c => c.InquiredFor == PID).ToList();
foreach (var clt in clients)
{
Group_Master gobj = new Group_Master();
gobj.GName = txtGroupName.Text;
gobj.ProductID = PID;
gobj.CatID = null;
gobj.SubCatID = null;
gobj.ClientID = clt.CID;
gobj.CreatedBy = Convert.ToInt32(((User_Master)Session["User"]).UID);
gobj.CreatedOn = DateTime.Now;
db.Group_Master.AddObject(gobj);
db.SaveChanges();
}
}
else
{
if (ddSubCategory.SelectedValue == "0")
{
int CID = Convert.ToInt32(ddBusinessCategory.SelectedValue);
var clients = db.Client_Master.Where(c => c.InquiredFor == PID && c.BusinessCategory == CID).ToList();
foreach (var clt in clients)
{
Group_Master gobj = new Group_Master();
gobj.GName = txtGroupName.Text;
gobj.ProductID = PID;
gobj.CatID = CID;
gobj.SubCatID = null;
gobj.ClientID = clt.CID;
gobj.CreatedBy = Convert.ToInt32(((User_Master)Session["User"]).UID);
gobj.CreatedOn = DateTime.Now;
db.Group_Master.AddObject(gobj);
db.SaveChanges();
}
}
else
{
int CID = Convert.ToInt32(ddBusinessCategory.SelectedValue);
int SID = Convert.ToInt32(ddSubCategory.SelectedValue);
var clients = db.Client_Master.Where(c => c.InquiredFor == PID && c.BusinessCategory == CID && c.SubCategory == SID).ToList();
foreach (var clt in clients)
{
Group_Master gobj = new Group_Master();
gobj.GName = txtGroupName.Text;
gobj.ProductID = PID;
gobj.CatID = CID;
gobj.SubCatID = SID;
gobj.ClientID = clt.CID;
gobj.CreatedBy = Convert.ToInt32(((User_Master)Session["User"]).UID);
gobj.CreatedOn = DateTime.Now;
db.Group_Master.AddObject(gobj);
db.SaveChanges();
}
}
}
Groups();
}
I tried to add Group ID using many ways but didn't succeed.
Please suggest me how can I solve this.
Thank you !!
You should create new table ClientsProducts, which will have reference to Client ID and Product ID. This is called One-to-Many Relationships.
You can read here about this here.
I Solved this by taking the ID of last data of list and save as a group ID so, with the help of this we get unique group ID.
if (ddBusinessCategory.SelectedValue == "0")
{
var clients = db.Client_Master.Where(c => c.InquiredFor == PID).ToList();
int GrpID = 0;
if (clients.Count() > 0)
{
foreach (var clt in clients)
{
if (ProductGrp(PID, clt.CID))
{
Group_Master gobj = new Group_Master();
gobj.GrpID = 0;
gobj.GName = txtGroupName.Text;
gobj.ProductID = PID;
gobj.CatID = null;
gobj.SubCatID = null;
gobj.ClientID = clt.CID;
gobj.CreatedBy = Convert.ToInt32(((User_Master)Session["User"]).UID);
gobj.CreatedOn = DateTime.Now;
db.Group_Master.AddObject(gobj);
db.SaveChanges();
GrpID = gobj.GID;
}
else
{
ScriptManager.RegisterStartupScript(Page, this.GetType(), "myscript()", "bootbox.alert({title: '<b>Error</b>',message: '<b>Group already exist.</b>',});", true);
break;
}
}
List<Group_Master> ggobj = db.Group_Master.Where(g => g.ProductID == PID && g.CatID == null && g.SubCatID == null).ToList();
foreach (var gid in ggobj)
{
if (gid.GrpID == 0)
{
Group_Master gmobj = db.Group_Master.Single(s => s.GID == gid.GID);
gmobj.GrpID = GrpID;
db.SaveChanges();
}
}
}
else
{
ScriptManager.RegisterStartupScript(Page, this.GetType(), "myscript()", "bootbox.alert({title: '<b>Error</b>',message: '<b>No Clients exist.</b>',});", true);
}
}

ASP.net Adding Multiple Table Entries to Database

I am using Visual Studio 2015 and Entity Framework 6. I am trying to add entries from inputted information into multiple tables.
This is what I have so far:
protected void btnOrder_Click(object sender, EventArgs e)
{
using (FlowerCompanyEntities flower = new FlowerCompanyEntities())
{
int rFlowers = 0;
Boolean rVase = false;
DateTime DeliveryDate = DateTime.Parse(tbDelivery.Text);
string flowerArrangement = ddlListFlowers.SelectedValue;
if (flowerArrangement == "f2")
{
rFlowers = 1;
}
if (flowerArrangement == "f3")
{
rFlowers = 2;
}
if (flowerArrangement == "f1")
{
rFlowers = 3;
}
if (flowerArrangement == "f4")
{
rFlowers = 4;
}
if (flowerArrangement == "f5")
{
rFlowers = 5;
}
string vase = rbList.SelectedItem.Value.ToString();
if (vase == "NO")
{
rVase = false;
}
if (vase == "YES")
{
rVase = true;
}
Customers cust = new Customers();
Addresses Addr = new Addresses();
Phone Pho = new Phone();
Delivery Del = new Delivery();
Arrangements arr = new Arrangements();
OrderStatus ordstat = new OrderStatus();
Orders ord = new Orders();
Pho.Phone1 = tbPhone.Text;
Addr.Street = tbStreet.Text;
Addr.City = tbCity.Text;
Addr.States = tbState.Text;
Addr.Zip = tbZip.Text;
cust.FirstName = tbFirstName.Text;
cust.LastName = tbLastName.Text;
Del.DeliverDate = DeliveryDate;
arr.FlowerID = rFlowers;
ordstat.OrderStatus1 = tbStatus.Text;
ord.Vase = rVase;
ord.OrderMessage = tbOrderMessage.Text;
try {
flower.Phone.Add(Pho);
flower.Addresses.Add(Addr);
flower.Customers.Add(cust);
flower.Delivery.Add(Del);
flower.Arrangements.Add(arr);
flower.OrderStatus.Add(ordstat);
flower.Orders.Add(ord);
flower.SaveChanges();
Response.Redirect("Orders.aspx");
}
catch { }
}
However, on the button click i get an exception error. I also just realized that some of those tables -- with those entries would need the foreign key of the other tables put in.
Question: How do I add all these entries to my database when there is multiple tables and foreign keys?

Prevent duplicate code while using linq

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

Writing to incidents in C#

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

Categories

Resources