How to save a List of objects to Firestore - c#

I need to save my list of objects to Firestore database. Below is my code:
How I Create the List of object
private async void LoadPlazaListAndSummary()
{
_plazaList = await _dc.GetPlazas();
foreach(var item in _plazaList)
{
var par = new ParameterManualTags
{
Plaza = item.Code,
Lane = item.Lane,
DateTo = System.DateTime.Now,
DateFrom = System.DateTime.Today
};
var manualCount = await _dc.GetManualAndTransactionCount(par);
var model = new Summary
{
Name = item.Name,
Lane = item.Lane,
Code = item.Code,
DateRun = System.DateTime.Now,
ManualAverage = 100.00,
ManualCount = manualCount[0],
ReadCount = 1,
TotalTransaction = manualCount[1],
Type = item.Type,
Plaza = item,
DateFrom = par.DateFrom,
DateTo = par.DateTo,
RfidAddress = item.ReaderIpAddress,
IsDedicated = item.IsDedicated ? "Dedicated" : "Mixed"
};
model.ManualAverage = Math.Round(ComputeManualPercentage(model), 2);
_summaryList.Add(model);
DgSummary.Items.Add(model);
}
}
This is my sample to save data to Firestore:
public void SetData()
{
if (_isConnected)
{
try
{
var doc = _database.Collection("MyCollection").Document("myDocument");
Dictionary<string, object> data = new Dictionary<string, object>()
{
{"FirstName", "MyFirstName"},
{"LastName", "MyLastName"},
{"PhoneNumber", "PhoneNumber"}
};
var x = doc.SetAsync(data);
Console.WriteLine("Saved");
}
catch (Exception ex)
{
Console.WriteLine($#"An error occured in saving the data: {ex.Message}");
}
}
}
Using my sample code, I can insert one at a time to Firestore but, I do not know how to save a list of objects to Firestore.

Related

Acumatica rest API PUT for sales order line keeps returning a 500 error

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.

C# Solr query - how to only get future dates?

I have a search method that queries Solr for event items. I need to modify it to only get events where the date has not already passed (i.e. Where(x => x.EventDate.Date >= DateTime.Now.Date), but I'm not sure how to add this because I'm not very familiar with Solr. Here's my search function:
public SearchQueryResults Search(string keywords, int page,int perPage, List<Guid> contentTypeFilters, List<Guid> otherFilters, ISortBuilder<SearchResultItem> sortBuilder)
{
var searchFilters = new List<IPredicateBuilder<SearchResultItem>>()
{
new IsSearchablePredicateBuilder()
};
if (contentTypeFilters.Any())
{
var contentTypePredicateBuilder = new ContentTypePredicateBuilder();
contentTypePredicateBuilder.ContentTypes = contentTypeFilters;
searchFilters.Add(contentTypePredicateBuilder);
}
if (otherFilters.Any())
{
var tagFilterBuilder = new TagsAndPredicateBuilder(otherFilters,_sitecoreContext);
searchFilters.Add(tagFilterBuilder);
}
if (string.IsNullOrWhiteSpace(keywords))
{
keywords = "";
}
SearchRequest searchRequest = new SearchRequest();
var queryParams = new Dictionary<string, string>() { };
queryParams.Add("q", keywords);
searchRequest.QueryParameters = queryParams;
searchRequest.SortBy = "";
searchRequest.SortOrder = "";
SearchQuery<SearchResultItem> queryArguments = new SearchQuery<SearchResultItem>();
queryArguments.FilterBuilders = searchFilters;
queryArguments.Page = page;
queryArguments.PerPage = perPage;
queryArguments.FacetsBuilder = new SearchFacetBuilder<SearchResultItem>();
queryArguments.SearchRequest = searchRequest;
queryArguments.IndexName = _indexName;
if (string.IsNullOrWhiteSpace(keywords))
{
queryArguments.QueryBuilders =new List<IPredicateBuilder<SearchResultItem>>();
}
else
{
queryArguments.QueryBuilders = new[] { new KeywordPredicateBuilder<SearchResultItem>(new[] { keywords }) };
}
queryArguments.SortBuilder = sortBuilder;
try
{
var results = _searchManager.GetResults<SearchResultItem>(queryArguments);
SearchQueryResults queryResults = new SearchQueryResults();
queryResults.ResultItems = results.Results;
queryResults.CurrentPage = page;
queryResults.TotalResults = Int32.Parse(results.TotalResults.ToString());
queryResults.TotalPages = (queryResults.TotalResults + perPage - 1) / perPage; ;
return queryResults;
}
catch (Exception exc)
{
Sitecore.Diagnostics.Log.Error("Error with FilteredSearch, could be a loss of connection to the SOLR server: " + exc.Message, this);
return null;
}
}
and here is how it's being called:
Results = _searchService.Search(searchTerm, CurrentPage - 1, 10, contentTypes, searchFilters,
new GenericSortBuilder<SearchResultItem>(q => q.OrderByDescending(r => r.SearchDate)));
How do I add in date filtering so that it only returns items where the date is in the future?
I would add filter query to the list of existing ones filtering the date field. On the documentation page, I was able to find information about fluent API, which could help here
Query.Field("date").From(DateTime.Now)
I'm not C# developer, that this code could have some mistakes, but I think the main idea is clear what needs to be done.

C# (Xamarin iOS) How to loop son data on Custom UITableViewCell?

Any Help will be appreaciated :) Thank you in advance
I tried to loop other object inside of the function and its working but on this, it can't loop. Help. this is rush, and I'm not that familiar with creating iOS app.
public override void ViewDidLoad()
{
base.ViewDidLoad();
using (var web = new WebClient())
{
var url = "http://www.creativeinterlace.com/smitten/maintenance/api/feeds/get-miss-location/101";
json = web.DownloadString(url);
}
json = json.Replace("{\"location\":", "").Replace("}]}", "}]");
var ls = JArray.Parse(json);
if (ls.Count != 0)
{
foreach (var x in ls)
{
var name = x.SelectToken("location");
name1 = Convert.ToString(name);
var loc = x.SelectToken("address");
loc1 = Convert.ToString(loc);
var time = x.SelectToken("time_ago");
time1 = Convert.ToString(time);
locations = new List<Locations>
{
new Locations
{
shopname = name1,
address= loc1,
time = time1
},
};
}
nmtable.Source = new LocationSource(locations);
nmtable.RowHeight = 60;
nmtable.ReloadData();
}
}
You initialize the locations every time in the loop,so the list updates with only the newest object. You should initialize the list outside of the loop , and add object every time.
locations = new List<Locations>();
if (ls.Count != 0)
{
foreach (var x in ls)
{
var name = x.SelectToken("location");
name1 = Convert.ToString(name);
var loc = x.SelectToken("address");
loc1 = Convert.ToString(loc);
var time = x.SelectToken("time_ago");
time1 = Convert.ToString(time);
locations.Add(new Locations{ shopname = name1,address= loc1,time = time1});
};
}

null Amount value salesorderdetail on crm 2011-Silverlight

I'm trying to insert data on SalesOrderDetail entity, everything works fine, except for the Amount field which remains null. I don't get any error message.
Here is an example of my code :
private void beginCreateSalesOrderDetail()
{
SalesOrderDetail orderDetail = new SalesOrderDetail();
orderDetail.SalesOrderId = new EntityReference()
{
Id = id,
LogicalName = "salesorder"
};
orderDetail.Quantity = element.QuantityOnHand;
orderDetail.ProductId = new EntityReference()
{
Id = element.ProductId,
LogicalName = "product"
};
orderDetail.UoMId = new EntityReference()
{
Id = new Guid("8DDD2AFB-73CF-E111-8140-00155D55B216"),
LogicalName = "uom"
};
orderDetail.TransactionCurrencyId = new EntityReference()
{
Id = new Guid("77D695B5-ACB4-E111-97BC-00155D55B216"),
LogicalName = "transactioncurrency"
};
Money Taxe = new Money();
Money Amount = new Money();
Taxe.Value = Convert.ToDecimal(element.totalCharges);
Amount.Value = Convert.ToDecimal(InvoiceTotal);
orderDetail.Tax = Taxe;
orderDetail.BaseAmount = Amount;
orderDetail.PricePerUnit = element.Price;
orderDetail.Description = element.PDesc;
_context.AddToSalesOrderDetailSet(orderDetail);
_context.BeginSaveChanges(EndCreateSalesOrderDetail, orderDetail);
}
private void EndCreateSalesOrderDetail(IAsyncResult result)
{
try
{
_context.EndSaveChanges(result);
}
catch (Exception ex)
{
}
}
Please note that only the amount which remains null
I get the solution.
Actually, there is a restrictions in crm 2011 to calcul the amounts of products,
We have to create a Price List, and associate each product in the list.
Thank you.

Google calendar (v3) event format

I've been trying to update a calendar with an event but it doesn't seem to be going through. could you comment on whether I'm formatting my event correctly? I've been struggling with this for some time now.
private void InsertEventIntoCalendar()
{
List<EventAttendee> ef = new List<EventAttendee>();
ef.Add(new EventAttendee{ Email = "event#gmail.com"});
List<EventReminder> eventReminder = new List<EventReminder>();
eventReminder.Add(new EventReminder{ Minutes = 4, Method = "email"});
Event.RemindersData de = new Event.RemindersData();
de.Overrides = eventReminder;
Event newEvent = new Event
{
Attendees = ef,
Reminders = de,
Summary = "Tin Roof",
Description = "Its gonna be epic",
Location = "Claremont",
Start = new EventDateTime
{
Date = "2012-09-30",
DateTime = "2012-09-30T10:00:00.000-02:00",
TimeZone = "Cape Town"
},
End = new EventDateTime
{
Date = "2012-09-30",
DateTime = new DateTime( "2012-09-30T10:25:00.000-02:00",
TimeZone = "Cape Town"
},
};
_service.Events.Insert(newEvent, "event#gmail.com").Fetch();
}
Just in case it helps anyone else. I figured out how to solve this. I was looking for the answer as well and stumbled on a solution:
public static void GCalAdd(string summary, string location, string description,
DateTime start, DateTime end, List<EventAttendee> attendees)
{
try
{
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = ClientCredentials.ClientID,
ClientSecret = ClientCredentials.ClientSecret
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthentication);
var service = new CalendarService(auth);
var curTimeZone = TimeZone.CurrentTimeZone;
var dateOffsetStart = new DateTimeOffset(start, curTimeZone.GetUtcOffset(start));
var dateOffsetEnd = new DateTimeOffset(end, curTimeZone.GetUtcOffset(end));
var startTimeString = dateOffsetStart.ToString("o");
var endTimeString = dateOffsetEnd.ToString("o");
var evt = new Event
{
Summary = summary,
Location = location,
Description = description,
Start = new EventDateTime { DateTime = startTimeString },
End = new EventDateTime { DateTime = endTimeString },
Attendees = attendees,
};
var insert = service.Events.Insert(evt, "primary").Fetch();
if (insert != null)
{
MessageBox.Show(#"calendar item inserted");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
And, to use it, do something like the following:
var ea = new EventAttendee
{
DisplayName = "testname",
Email = "email#gmail.com",
Organizer = false,
Resource = false
};
var ea2 = new EventAttendee
{
DisplayName = "testname2",
Email = "email2#gmail.com",
Organizer = true,
Resource = false
};
var list = new List<EventAttendee> { ea, ea2 };
var now = DateTime.Now;
var t30 = now + TimeSpan.FromMinutes(30);
Program.GCalAdd("test event", "test location", "test description", now, t30, list);
I think error in reminder data. Look here - Google Calendar API v3 with C# - Unable to insert recurrence exceptions.

Categories

Resources