So I have action Method in my controller which get data from the CSV file which I uploaded through web
I want to pass that data to Insert controller so data from the CSV will automatically inserted to tables in my DB and pass it to view
I'm using CSV HELPER, MVC
public ActionResult ImportCSV(HttpPostedFileBase file, int compID)
{
var compName = db.CourierCompanies.Find(compID);
string path = null;
List<MyViewModel> csvD = new List<MyViewModel>();
try
{
if(file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
path = AppDomain.CurrentDomain.BaseDirectory + "upload\\" + fileName;
file.SaveAs(path);
var csv = new CsvReader(new StreamReader(path));
var invoCSV = csv.GetRecords<ImportCsV>();
foreach(var i in invoCSV)
{
MyViewModel iCSV = new MyViewModel();
iCSV.CustID = i.cust_id;
iCSV.Fullname = i.fullname;
iCSV.CustComp = i.company;
iCSV.InvoiceNo = i.rec_no;
iCSV.InsertDate = DateTime.Parse(i.doc_dt);
iCSV.Road = i.w_addr1;
iCSV.City = i.w_city;
iCSV.Zip = i.w_zip;
iCSV.Phone = i.w_phone;
iCSV.Status = "BelumTerkirim";
iCSV.compID = compID;
iCSV.CompName = compName.CompName;
iCSV.StatDate = DateTime.Now;
csvD.Add(iCSV);
}
}
}
catch
{
ViewData["Error"] = "Upload Failed";
}
return View();
}
Insert Controller
public ActionResult Create( MyViewModel model, int compID, HttpPostedFileBase file)
{
if (file != null)
{
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
model.Image = ms.GetBuffer();
}
}
var cust = new Customer()
{
CustID = model.CustID,
Phone = model.Phone,
CustComp = model.CustComp,
Fullname = model.Fullname
};
var addrDet = new AddrDetail()
{
Road = model.Road,
City = model.City,
Zipcode = model.Zip
};
var invoice = new Invoice()
{
InvoiceNo = model.InvoiceNo
};
var stat = new Status()
{
Status1 = model.Status,
StatDate = model.StatDate,
Ket = model.Ket
};
var image = new Models.Image()
{
Image1 = model.Image
};
var detail = new DetailPengiriman()
{
NamaPenerima = model.NamaPenerima,
StatusPenerima = model.StatusPenerima,
TrDate = model.TrDate,
InsertDate = model.InsertDate
};
if (ModelState.IsValid )
{
//customer
db.Customers.Add(cust);
detail.CustID = cust.CustID;
invoice.CustID = cust.CustID;
//addrDet
db.AddrDetails.Add(addrDet);
cust.AddrDetID = addrDet.AddrDetID;
//invoice
db.Invoices.Add(invoice);
stat.InvoiceNo = invoice.InvoiceNo;
image.InvoiceNo = invoice.InvoiceNo;
detail.InvoiceNo = invoice.InvoiceNo;
//status
db.Status.Add(stat);
detail.StatusID = stat.StatusID;
////image
db.Images.Add(image);
detail.ImageID = image.ImageID;
//detail
detail.CompID = compID;
db.DetailPengirimen.Add(detail);
db.SaveChanges();
return RedirectToAction("Index", new { compID = detail.CompID});
}
return View();
}
You can abstract that business logic in another class and instantiate it inside your CSV action.
This way your can call your methods for inserting customers from both actions!
Related
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!
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
}
I've been trying to upload a sales order with their sales line on Acumatica with a REST API, but I keep getting a 500 error.
I am using the default Sales Order endpoint. When I comment out the SalesOrderDetail list, it succeeds, so I think that's where the problem is.
PUT method:
public async Task<bool> PutSalesOrdersAsync(Models.AcumaticaSalesOrder customer)
{
if (await Login() == false) return false;
var uri = new Uri(settings.url + settings.endpoint + "SalesOrder"); //?$filter=Location eq 'MAIN'&$top=10");
try
{
var json = JsonConvert.SerializeObject(customer);
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PutAsync(uri, stringContent);
if (response.IsSuccessStatusCode)
{
//var content = await response.Content.ReadAsStringAsync();
//Customers = JsonConvert.DeserializeObject<List<Models.AcumaticaCustomer>>(content);
}
else
{
err = await response.Content.ReadAsStringAsync();
try
{
ResponseMessage msg = JsonConvert.DeserializeObject<ResponseMessage>(err);
if (msg != null && msg.exceptionMessage != "") err = msg.exceptionMessage;
return false;
}
catch (Exception ex)
{
err = ex.Message;
return false;
}
}
}
catch (Exception ex)
{
Debug.WriteLine(#" ERROR {0}", ex.Message);
err = ex.Message;
return false;
}
return true;
}
Acumatica Sales order setup:
public async Task<AcumaticaSalesOrder> ToAcumaticaSalesOrderAsync()
{
AcumaticaSalesOrder c = new AcumaticaSalesOrder();
c.CurrencyID = new StringField { value = this.CurrencyID };
c.CustomerID = new StringField { value = this.CustomerID };
// c.OrderSummaryCustomerName = new StringField { value = this.OrderSummaryCustomerName };
c.CustomerOrder = new StringField { value = this.CustomerOrder };
c.Date = new DateTimeField { value = this.Date };
c.Description = new StringField { value = this.Description };
c.FinancialSettings = new Models.AcumaticaSalesOrderFinancialSettings();
c.FinancialSettings.InvoiceNbr = new StringField { value = this.InvoiceNbr };
c.LocationID = new StringField { value = this.LocationID };
c.OrderNbr = new StringField { value = this.OrderNbr };
c.OrderTotal = new DecimalField { value = this.OrderTotal };
c.OrderedQty = new DecimalField { value = this.OrderedQty };
c.OrderType = new StringField { value = this.OrderType };
c.Status = new StringField { value = this.Status };
c.Totals = new Models.AcumaticaSalesOrderTotals();
c.Totals.LineTotalAmount = new DecimalField { value = this.LineTotalAmount };
c.Totals.MiscTotalAmount = new DecimalField { value = this.MiscTotalAmount };
c.TaxTotal = new DecimalField { value = this.TaxTotal };
c.Details = new List<AcumaticaSalesOrderDetail>();
c.Details = await GetSalesOrderLineAsync();
return c;
}
private async Task<List<AcumaticaSalesOrderDetail>> GetSalesOrderLineAsync()
{
AASDatabase db = new AASDatabase();
List<Models.AcumaticaSalesOrderDetail> asols = new List<AcumaticaSalesOrderDetail>();
List <Models.SalesOrderDetail> sols = await db.GetSalesOrderDetailByOrderNbrAsync(OrderNbr);
foreach (Models.SalesOrderDetail sol in sols)
{
Models.AcumaticaSalesOrderDetail c = new AcumaticaSalesOrderDetail();
c.LineNbr = new IntField { value = sol.LineNbr };
c.DiscountAmount = new DecimalField { value = sol.DiscountAmount };
c.LineType = new StringField { value = sol.LineType }; ;
c.LineDescription = new StringField { value = sol.LineDescription };
c.InventoryID = new StringField { value = sol.InventoryID };
c.UOM = new StringField { value = sol.UOM };
c.WarehouseID = new StringField { value = sol.WarehouseID };
c.OrderQty = new DecimalField { value = sol.OrderQty };
c.UnitPrice = new DecimalField { value = sol.UnitPrice };
asols.Add(c);
}
return asols;
}
The code is correct. The the json that I was sending over was not the right type of sales order. Thisput only dose type SO.
i am new to travelport universal api. i receive response from api. I perform LOW FARE SEARCH and in response the fare information and the flight information return in two different list.the problem is that i don't find any relationship in these LIST's. and also WHAT IS THE BEST WAY TO DECODE THE WSDL RESPONSE. i am using WSDL below is my code
string TargetBranch = "P7004961";
string OriginApplication = "uAPI";
string Origin="DXB";
string Destination="LHR";
string Departuredate = "2014-03-25T00:00:00";
string FlightStatus = "One-way";
string url = "https://americas-uapi.copy-webservices.travelport.com/B2BGateway/connect/uAPI/AirService";
string ReturnDate = "2014-04-05T00:00:00";
string UserName = "Universal API/uAPI6035036525-8ff7f8fc", Password = "DSXSEDn3fme9d6m2DfKP5rEaW";
LowFareSearchReq req = new LowFareSearchReq();
req.TargetBranch = TargetBranch;
BillingPointOfSaleInfo biPOS = new BillingPointOfSaleInfo();
biPOS.OriginApplication = OriginApplication;
req.BillingPointOfSaleInfo = biPOS;
/////////// Origin to Destination////////////////
SearchAirLeg airLeg = new SearchAirLeg();
Airport fromAirPort = new Airport() { Code = Origin };
typeSearchLocation fromTypLoc = new typeSearchLocation() { Item = fromAirPort };
airLeg.SearchOrigin = new typeSearchLocation[1] { fromTypLoc };
Airport toAirPort = new Airport() { Code = Destination };
typeSearchLocation toTypLoc = new typeSearchLocation() { Item = toAirPort };
airLeg.SearchDestination = new typeSearchLocation[1] { toTypLoc };
typeTimeSpec origDep = new typeTimeSpec() { PreferredTime = Departuredate };
airLeg.Items = new typeTimeSpec[1] { origDep };
/////////////////// Destination to Origin ////////////////////
SearchAirLeg returnLeg = new SearchAirLeg();
Airport RetfromAirport = new Airport() { Code = Destination };
typeSearchLocation fromLocation = new typeSearchLocation() { Item = RetfromAirport };
returnLeg.SearchOrigin = new typeSearchLocation[1] { fromLocation };
Airport retToAirpot = new Airport() { Code = Origin };
typeSearchLocation tolocation = new typeSearchLocation() { Item = retToAirpot };
returnLeg.SearchDestination = new typeSearchLocation[1] { tolocation };
typeTimeSpec retdate = new typeTimeSpec() { PreferredTime = ReturnDate };
returnLeg.Items = new typeTimeSpec[1] { retdate };
///////// checking for one way or return//////////////////////////
if (FlightStatus == "One-way")
{
req.Items = new object[] { airLeg };
}
else
{
req.Items = new object[] { airLeg, returnLeg };
}
AirSearchModifiers AirsearchModifier = new AirSearchModifiers()
{
DistanceType = typeDistance.KM,
IncludeFlightDetails = true,
PreferNonStop = true,
MaxSolutions = "300",
PreferredProviders= new Provider[1]{ new Provider(){ Code="1G"}}
};
req.AirSearchModifiers = AirsearchModifier;
SearchPassenger pass1 = new SearchPassenger() { Code = "ADT" };
req.SearchPassenger = new SearchPassenger[] { pass1 };
string Currency = "PKR";
AirPricingModifiers AirPriceMode = new AirPricingModifiers() { CurrencyType = Currency, };
req.AirPricingModifiers = AirPriceMode;
LowFareSearchRsp response = new LowFareSearchRsp();
AirLowFareSearchBinding binding = new AirLowFareSearchBinding();
binding.Url = url;
binding.Credentials = new NetworkCredential(UserName, Password);
response = binding.service(req);
Thanks to all.Finally i found result which is below quit easy in fact In the LowFareSearch response you get back among other info a list of AirSegments and a list of AirPricingSolutions. Each AirPricingSolution contains AirPricingInfo with the applicable SegmentRef keys and BookingCode info. Each SegmentRef key corresponds to a flight in the AirSegment list. This is how you know which flights (AirSegments) correspond to a specific price (AirPricingSolution).
I need to insert a new invoice for a particular customer , I can able to insert , but i don't have any idea about how to insert multiple items in invoice. How to use the property Items and ItemsElementName to insert multiple items.
If my question is unclear please let me know. I have attached the snapshot and code for reference.
Code:
protected void btnsendInvoiceDetails_Click(object sender, EventArgs e)
{
string accessToken = "lvprdRM1HLr6o11Bnip2fGizlXWbFfADnS1Btvm2L4VPOTRI";
string appToken = "297db54bb5526b494adb86fb2a41063192cd";
string accessTokenSecret = "JfSTrprW83JTXrSVHD3uf7th23gP0SOzBQcn4Nrt";
string consumerKey = "qyprdKLN5YHpCPSlWQZTiKVc28dywR";
string consumerSecret = "JPMNB37YnCPGU9m9vuXkF2M71lbDb7blhcLB7HeF";
string companyID = "813162085";
OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
ServiceContext context = new ServiceContext(oauthValidator,appToken,companyID, IntuitServicesType.QBO);
DataServices service = new DataServices(context);
InvoiceHeader a = new InvoiceHeader();
a.CustomerName = "Antivirus Norton Security";
a.CustomerId = new IdType { idDomain = idDomainEnum.QBO, Value = "6" };
a.TotalAmt = 157.00m;
a.SubTotalAmt = 37.00m;
a.ShipMethodName = "Gmail";
a.ShipMethodId = new IdType { idDomain = idDomainEnum.QBO, Value = "41" };
a.DocNumber = "1040";
a.DueDateSpecified = true;
// a.Item = 10.00m;
//a.ItemElementName = ItemChoiceType2.DiscountAmt;
DateTime dt = Convert.ToDateTime("08/07/2013");
a.DueDate = dt;
InvoiceLine mnm = new InvoiceLine();
mnm.Desc = "Antivirus Norton Security The Best Security ";
mnm.Id = new IdType { idDomain = idDomainEnum.QBO, Value = "25" };
mnm.Amount = 65.00m;
mnm.AmountSpecified = true;
// mnm.Items = "Europe";
//mnm.ItemsElementName = "Zebronic";
InvoiceLine[] invline = new InvoiceLine[] { mnm };
var invoices = new Intuit.Ipp.Data.Qbo.Invoice();
invoices.Header = a;
invoices.Line = invline;
var addedInvoice = service.Add(invoices);
var qboInvoices = service.FindAll(invoices, 1,10);
foreach (var qboinv in qboInvoices)
{
string id = Convert.ToString(qboinv.Id.Value);
}
GridView1.DataSource = invoices;
GridView1.DataBind();
}
Image:
Try this:
InvoiceLine i = new InvoiceLine();
i.ItemsElementName = new ItemsChoiceType2[1];
i.ItemsElementName[0] = ItemsChoiceType2.ItemId;
i.Items = new Intuit.Ipp.Data.Qbd.IdType[1];
i.Items[0] = new Intuit.Ipp.Data.Qbd.IdType() { idDomain = Intuit.Ipp.Data.Qbd.idDomainEnum.QBO, Value = "6" };