In a Xamarin project I am trying to post data to Lumen API. The API takes this data:
item[0][ProductId] = 1
item[0][ProductName] = Test
and so on.
The idea here is that there can be more than one productline that will be added to an invoice by the api.
The challenge here is now how to add the item[i] before the product.
Here is the productDTO:
product = new ProductDto
{
ProductId = i.ProductId,
ProductName = i.ProductName,
Price = i.Price,
Quantity = i.Quantity,
TaxPercetage = i.TaxPercetage,
Total = i.Total,
TotalTaxes = i.TotalTaxes
};
And then finally posting to the API
var url = "https://localhost/Lumen/registerSale";
using var client = new HttpClient();
string token = Preferences.Get("token", "");
string jsonstringremake = "";
var request = new HttpRequestMessage(HttpMethod.Post, url);
var json = JsonConvert.SerializeObject(product);
This code give me this json encoded data:
"{"ProductId":1,"ProductName":"Coca Cola","Quantity":1.0,"Price":3.0,"TaxPercetage":25,"Total":3.0,"TotalTaxes":0.75}"
The question is, how can I create a function that give me this json data:
"{"item[0]ProductId":1,"item[0]ProductName":"item[0]Coca Cola","item[0]Quantity":1.0,"item[0]Price":3.0,"item[0]TaxPercetage":25,"item[0]Total":3.0,"item[0]TotalTaxes":0.75}"
where item is item[i]?
I ran your expected JSON through a linter & I was actually quite surprised it is valid. However, when it was formatted a bit better I saw why I thought it was odd.
First keep in mind that JSON is just name/value pairs.
In your case you have names which include array-type brackets [].
{
"item[0]ProductId": 1,
"item[0]ProductName": "item[0]Coca Cola",
"item[0]Quantity": 1,
"item[0]Price": 3,
"item[0]TaxPercetage": 25,
"item[0]Total": 3,
"item[0]TotalTaxes": 0.75
}
Basically, this means that you have a string name which includes array brackets. For example : item[0]ProductId
Well, to get the one named item[1]ProductId you it is going to be odd because the index value is a part of the name.
You'd have to iterate over the names, inserting the appropriate index values or something.
I agree with comment which said you probably need a List<productDTO>
List<ProductDTO> allProducts = new List<ProductDTO>();
product = new ProductDto
{
ProductId = i.ProductId,
ProductName = i.ProductName,
Price = i.Price,
Quantity = i.Quantity,
TaxPercetage = i.TaxPercetage,
Total = i.Total,
TotalTaxes = i.TotalTaxes
};
allProducts.Add(product);
// Keep adding products
JsonConvert.SerializeObject(allProducts);
Related
I've got a string fdf=232232&lid=19974832&number=1&aa_result1_1=someId1&aa_resuuuuuult2_2=someId2&aa_resuuuult3_3=someId3
and if aa exists I need to take values and add them to dictionary like:
var dict = extendedIds.Add("result1", new Dictionary<string, int[]>()
{
{
"someId1",
new int[]{ 1 }
}, ...
});
however I am having a difficult time deciding how to parse it properly? I need to accept multiple aa values (the ones that come as resultN, someIdN and a number (which is the number after resultN_NUMBER).
I tried to use substring but that doesn't work as I dont't now the length of word result
Basically it is
var parameters = $"pam=805700&laaid=19974832&kpm=1&{HttpUtility.UrlEncode("aa_{result}_{number}={id}&aa_{result}_{number}={id}&aa_{result}_{number}={id}", Encoding.UTF8)}";
So I decode it and get string:
var decoded = input.ToString().UrlDecode();
I need to accept multiple aa values, so in this example there would be three values, two of them comes from in bertween _ one after = but I wonder how to take these values then there could be something else also split by _...
also I could var parsed = HttpUtility.ParseQueryString(decoded); parse to NameValueCollection. but I can't use parsed.GetValues("aa") because the key would be e.g. aa_result1_1 and I never know beforehand what it is
this is a query string, you can use HttpUtility.ParseQueryString to parse it
see
https://learn.microsoft.com/en-us/dotnet/api/system.web.httputility.parsequerystring?view=net-5.0
Would this set you on the right track?
var qs = "fdf=232232&lid=19974832&number=1&aa_result1_1=someId1&aa_resuuuuuult2_2=someId2&aa_resuuuult3_3=someId3";
var nvc = System.Web.HttpUtility.ParseQueryString(qs);
foreach (var key in nvc.AllKeys.Where(k => k.StartsWith("aa")))
{
var id = nvc[key];
var parts = key.Split('_');
var result = parts[1];
var number = parts[2];
Console.WriteLine($"result = '{result}', number = '{number}' => id = '{id}'");
}
Use ParseQueryString to convert your string into a NameValueCollection.
Then use each key that starts with "aa"
Get its value - this is your "id"
Split the key on the _
Ignore the first part (which would be "aa") and use the next two parts
Of course you would want to add some safety: I now assume that there always are 3 parts in that key. Plus you want to do something useful with the results.
The above code prints this
result = 'result1', number = '1' => id = 'someId1'
result = 'resuuuuuult2', number = '2' => id = 'someId2'
result = 'resuuuult3', number = '3' => id = 'someId3'
Task:
List all defects in the backlog of a project by their rank/index.
Here is my code:
var myRequest = new Request()
{
ArtifactName = "defect",
Limit = 2000,
Query = new Query("Project.OID", Query.Operator.Equals, MyDefectProjectOID),
Fetch = new List<string>() { "true" }
};
QueryResult queryMyResult = api.Query(myRequest);
Question:
1) How do I get the result set back in the order my users have organised them in Rally.
2) Is there a value on the defect item that tells me the rank/index (for example the Task item has a TaskIndex property)
1) Order by the DragAndDropRank field, ASC.
2) As long as you fetch DragAndDropRank as well that's your rank value. It's encoded as a string which is sortable in client code. The overall numeric index will be its index in your result set.
Another quick note- rather than specifying a query on Project.ObjectID to control scoping, you can just set the Project, ProjectScopeUp and ProjectScopeDown values:
Project = "/project/" + MyDefectProjectOID,
ProjectScopeUp = false,
ProjectScopeDown = false
I have list that have values like"
[0] = "{ id = ES10209005, views = 501 }"
[1] = "{ id = HYT0209005, views = 5678}"
[3] = "{ id = POI0209005, views = 4568}"
I would like to pass the values(id,views) to a method using a for each loop.
method(id,views)
Something like:
foreach (string v in updatereponse)
{
method()
}
How do I isolate each value(id,views) from each row in the list then pass it to the method?
The list contains just a bunch of strings, anything based on this to fix the problem would be just a workaround (e.g. string parsing). You should really switch to a strongly typed model, e.g. define a class ViewCount:
public class ViewCount
{
public string Id {get;set;}
public int Views {get;set;}
}
You can then use a List<ViewCount> populate the list:
List<ViewCount> viewcounts = new List<ViewCount>();
viewCounts.Add(new ViewCount() { Id = "ES10209005", Views = 501 });
Since each ViewCount instance has Id and Views properties you can now do the proper thing:
foreach (var item in updatereponse)
{
method(item.Id, item.Views);
}
If you are saving this data in a file, an alternative would be to use XML instead of custom strings, then you could use Linq to XML to populate a List<ViewCount>, e.g. using a simple XML like this:
<ViewCounts>
<ViewCount id="ES10209005" views="501" />
</ViewCounts>
You can then load your list:
XElement viewXml = XElement.Load("test.xml");
List<ViewCount> viewCounts = viewXml.Descendants("ViewCount")
.Select(x => new ViewCount()
{
Id = (string)x.Attribute("id"),
Views = (int)x.Attribute("views")
}).ToList();
foreach (string v in updateresponse)
{
var values = v.Split(",");
var id = values[0].Replace("{ id = ", "").Trim();
var view = values[1].Replace("views = ", "").("}","").Trim();
method(id, value);
}
Here's another way...you may want to add error checking:
String Data = "{ id = ES10209005, views = 501 }";
String[] Segments = Data.Split(new char[] { ' ', ',' });
string ID = Segments[3];
int views = int.Parse(Segments[7]);
Assuming the structure of your String is like you showed us always, this can work for you.
// First split id and views part.
String[] firstSplit = v.Split(',');
// Get the respected value for each part.
String id = firstSplit[0].Split('=')[1].Trim();
String views = firstSplit[1].Split('=')[1].Trim().Replace("}","");
You can use String methods to retrieve the items (use Split and SubString for example) or you can use a regular expression.
E.g.
var list = UpdateResponse[0].Split("=,} ") ;
will result in a list split by all these characters (including space).
Then check the correct indices to use (use a debugger for that). Then you get something like:
var id = list[5];
var views = list[8];
(note: check the indices 5 or 8, they are just a guess).
I have set of records in a database table lets call it Components Table which is defined as follows.
The administrator can disable some of the components using disableflag which is the last column of the table. If a particular component is disabled it should not appear in the gridview of the user.
I'm getting the data from the database and presenting through the gridview as shown here, if you observe the SNo values are not in order.
The linq query that i'm using to retrieve the data is:
var gridViewResults = from results in db.Components where results.DisableFlag == false
select new { SNo = results.SNo, ComponentNames = results.Component_Name, Size = results.Size__in_MB_, Price = results.Price__in_SEK_, TotalDownloads = results.Total_Downloads, Description = results.Description };
But I want the data to be shown in order meaning with SNo to be 1, 2, 3, 4 with out dependency on the database table SNO values: for reference look at this.
I'm not able to figure out how to use the linq query to achieve this:
I have tried this query:
(db.Components.AsEnumerable().Select((iterator)=> new{iterator.SNo + 1})
But i think it is absurd. Can some one help me out on this.
Thanks in anticipation.
If you're absoutely certain you want to ignore the database numbers (why output the numbers if they don't actually correspond to anything?) you may be able to try the following:
var gridViewData = from results in db.Components
where results.DisableFlag == false
select new
{
ComponentNames = results.Component_Name,
Size = results.Size__in_MB_,
Price = results.Price__in_SEK_,
TotalDownloads = results.Total_Downloads,
Description = results.Description
};
var gridViewResults = gridViewData.AsEnumerable().Select((item, index) => new
{
SNo = index + 1,
ComponentNames = item.ComponentNames,
Size = item.Size,
Price = item.Price,
TotalDownloads = item.TotalDownloads,
Description = item.Description
});
EDIT: Alternate solution from How To Project a Line Number Into Linq Query Results
EDIT2: Fix for unsupported select by SQL: Linq error - "NotSupportedException: Unsupported overload used for query operator 'Select'"
Hi everyone here is the final answer. Joshua did all of the work. A big thanks to him. Just want to highlight the answer to anyone with the same problem for the future. If any one want to vote up please vote for Joshua
var gridViewData = from results in db.Components
where results.DisableFlag == false
select new
{
ComponentNames = results.Component_Name,
Size = results.Size__in_MB_,
Price = results.Price__in_SEK_,
TotalDownloads = results.Total_Downloads,
Description = results.Description
};
var gridViewResults = gridViewData.AsEnumerable().Select((item, index) => new
{
SNo = index + 1,
ComponentNames = item.ComponentNames,
Size = item.Size,
Price = item.Price,
TotalDownloads = item.TotalDownloads,
Description = item.Description
}).ToList();
This should work.
My working envirnment is Visual Studio 2008 + C#
I am working on Amazon WebService, I want to fetch the data from Amazon using SOAP but when I am trying to pass IDType = UPC it gives me below error message, so what can I do for this ?
Error:
036725229884 is not a valid value for ItemId. Please change this value and retry your request
MyCode:
ItemLookupRequest request1 = new ItemLookupRequest();
request1.IdType = ItemLookupRequestIdType.UPC;
request1.IdTypeSpecified = true;
request1.ItemId = new string[] { ProductID };
request1.ResponseGroup = new string[] { "Request", "Large", "OfferFull", "BrowseNodes" };
request1.MerchantId = "All";
request1.Condition = Condition.All;
request1.SearchIndex = "Books";
Note:
How can I add multiple SearchIndex like ("Books","Photo","Video")?
I have used following WebService:
http://webservices.amazon.com/AWSECommerceService/2009-11-01/US/AWSECommerceService.wsdl
Also be weary of the difference between UPC and EAN.
UPC = 12 digits,
EAN = 13 digits
If you just punch in a UPC 738678251584 (12 digits) or EAN 3253581057803 (13 digits) to Amazon.com it will show both as being UPC in the description, but using the API you must specify EAN when searching.
We have products with both and you need to specify the search type accordingly or it won't get found.
Edit: OR you can just prepend a 0 to any 12 digit numbers and always search for EAN. This is probably the best solution. By definition "0" + UPC = EAN
This request worked for me (searchType is either UPC or EAN):
ItemLookup itemLookup = new ItemLookup()
{
AssociateTag = "XXXXX-20",
};
itemLookup.AWSAccessKeyId = ACCESS_ID;
ItemLookupRequest itemLookupRequest = new ItemLookupRequest();
itemLookupRequest.IdTypeSpecified = true;
itemLookupRequest.IdType = searchType;
itemLookupRequest.SearchIndex = "All";
itemLookupRequest.ItemId = upcEanList;
itemLookupRequest.ResponseGroup = new[] { "OfferSummary", "ItemAttributes" };
itemLookup.Request = new ItemLookupRequest[] { itemLookupRequest };
I don't think Amazon supports queries across multiple search indices. However, there is a special index named All that you can use with UPC lookups. There are some limitations on the parameters used with this index but since you are specifying All for MerchantId and Condition it may work. If not, you could do the query without those parameters and then issue a new query once you have the ASINs for the UPCs you are interested in.