I new with Xamarin , I am trying to convert my list of generic type to single string. I can comfortably performs this task in Android using below code.
Gson gson = new Gson();
Type collectionType = new TypeToken<ArrayList<Response_bean>>() {}.getType();
JsonElement element = gson.toJsonTree(response_data, collectionType);
JsonArray jsonArray = element.getAsJsonArray();
String strjsonarray = jsonArray.toString();
But I cant found its replacement in Xamarin.
Please help Thanks in advance.
I think you can use json.net
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
string json = JsonConvert.SerializeObject(product);
// {
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Sizes": [
// "Small"
// ]
// }
As Alessandro Caliaro said, json.net can help you.
List<Product> list = new List<Product>();
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
Product product2 = new Product();
product2.Name = "Banana";
product2.Expiry = new DateTime(2010, 12, 28);
product2.Sizes = new string[] { "Big" };
Product product3 = new Product();
product3.Name = "Pear";
product3.Expiry = new DateTime(2012, 12, 28);
product3.Sizes = new string[] { "Huge" };
list.Add(product);
list.Add(product2);
list.Add(product3);
string json = JsonConvert.SerializeObject(list);
Output
[
{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Sizes":["Small"]},
{"Name":"Banana","Expiry":"2010-12-28T00:00:00","Sizes":["Big"]},
{"Name":"Pear","Expiry":"2012-12-28T00:00:00","Sizes":["Huge"]}
]
Related
Good day
I am creating a SOAP contract base connection to Acumatica.
I am getting an error: "System.ArgumentNullException: Value cannot be null."
I am not sure why I am getting the error.
Here is my code
using (var soapClient = new DefaultSoapClient())
{
try
{
soapClient.Login();
InventoryReceipt NewinventoryReceipt = new InventoryReceipt
{
ReferenceNbr = new StringValue { Value = "<NEW>" },
Hold = new BooleanValue { Value = true },
Date = new DateTimeValue { Value = DateTime.Now },
PostPeriod = new StringValue { Value = DateTime.Now.ToString("DD-yyyy") },
TransferNbr = new StringValue { Value = "" },
//External Ref
Description = new StringValue { Value = "" },
Details = new InventoryReceiptDetail[]
{
new InventoryReceiptDetail
{
//branch
InventoryID = new StringValue{Value = "NIS777"},
WarehouseID = new StringValue{Value = "FBTZEST"},
Location = new StringValue {Value = "BULK"},
Qty = new DecimalValue{Value = 1},
UOM = new StringValue{Value = "PALLET"},
UnitCost = new DecimalValue{Value = 91},
ExtCost = new DecimalValue{Value = 91},
LotSerialNbr = new StringValue{Value = "PLN12345"},
ExpirationDate = new DateTimeValue{Value = DateTime.Now},
// ReasonCode
Description = new StringValue{Value = ""}
}
},
};
InventoryReceipt putInventoryReceipt = (InventoryReceipt)soapClient.Put(NewinventoryReceipt);
}
catch (Exception ex)
{
soapClient.Logout();
throw;
}
finally
{
soapClient.Logout();
}
soapClient.Logout();
}
Console.ReadLine();
}
Is there any way to see what is null or what I am missing to post this data?
Have you tried manually entering the data into the UI? The Validation on the web service should be the same as the UI, so you might get more info from the UI. You have a lot of dependent values here since you're referencing a specific Lot perhaps a value is missing. Other than that, you might try adding Project = X.
I'm trying to use the Acumatica API to return a list of Sales Order and Sales Order Details, while limiting the fields returned.
So far, I have :
SalesOrder filter = new SalesOrder
{
//Filter the SOs returned
OrderType = new AcumaticaOpticsExt.StringValue { Value = salesOrder.Split('/').First() },
OrderNbr = new AcumaticaOpticsExt.StringValue { Value = salesOrder.Split('/').Last() },
//Specify return behavior
ReturnBehavior = ReturnBehavior.OnlySpecified,
//Specify the fields to be returned on the SO
Hold = new BooleanReturn(),
CustomerName = new StringReturn(),
SchedShipment = new DateTimeReturn(),
QtyAllocatedM = new DecimalReturn(),
QtyAllocatedNotCompletedM = new DecimalReturn(),
//And from the SO Line Detail
};
It's not clear how I can specify the fields from the Details and I haven't found any multi-level uses in the documentation.
Does anyone have an example?
Here is an example that works for me :
SalesOrder so = new SalesOrder
{
ReturnBehavior = ReturnBehavior.OnlySpecified,
OrderType = new StringSearch { Value = "SO", Condition = StringCondition.Equal },
OrderNbr = new StringSearch { Value = "001253", Condition = StringCondition.Equal },
Details = new SalesOrderDetail[]
{
new SalesOrderDetail
{
ReturnBehavior = ReturnBehavior.OnlySpecified,
InventoryID = new StringReturn(),
LineNbr = new IntReturn(),
UOM = new StringReturn(),
UnitPrice = new DecimalReturn(),
Quantity = new DecimalReturn()
}
}
};
You just have to define the array of detail items, in the first one define the return behavior level that you want and if it applies the field(s) that you want to be returned.
Re-entering the code as follows, with combined suggestions from #bknights & #prasun
function main_GetVendorItems(request, response) {
response.write(JSON.stringify(getVendorItems(request)));
}
function getVendorItems(request) {
var vendorid = request.getParameter('vendor');
nlapiLogExecution('DEBUG', 'searchRes', 'Searching For Vendor ID: '+vendorid );
var filters = new Array();
var columns = new Array();
filters[0] = new nlobjSearchFilter('vendorcost', null, 'greaterthan', 0);
filters[1] = new nlobjSearchFilter('othervendor', null, 'is', [vendorid] );
columns[0] = new nlobjSearchColumn('itemid');
columns[1] = new nlobjSearchColumn('entityid', 'vendor');
columns[2] = new nlobjSearchColumn('vendorcost');
columns[3] = new nlobjSearchColumn('vendorcode');
columns[4] = new nlobjSearchColumn('vendorpricecurrency');
var searchresults = nlapiSearchRecord('item', null, filters, columns );
//for test test each element of the array
(searchresults || []).forEach(function(res){
nlapiLogExecution('DEBUG', 'searchRes', res instanceof nlobjSearchResult);
})
return searchresults;
}
The calling function as below:
function test () {
var vendorID = nlapiGetFieldValue('custrecordvpr_supplier'); alert('searching for vendor ID: '+vendorID );
var url = nlapiResolveURL('SUITELET', 'customscriptls_getvendoritems', 'customdeployls_getvendoritems', true);
var params = {}
params['vendor'] = vendorID;
var response = nlapiRequestURL(url, params);
var VendorItemsSublist = response.getBody();
nlapiSetFieldValue('custrecordvpr_comment',VendorItemsSublist );
}
I've got a comment field on my custom record/form which shows the returned object. On the code above, what's really strange, is I'm not getting any information being added to the execution log,even the first entry where it should post the vendor id being searched for.
I've checked the script and deployment records, and there is nothing untoward or amiss there... I have got to be missing something extremely simple.
Incidentally, the code is being called by a "Test" button on my custom form.
It looks like you are not writing properly to the response object in Suitelet.
function main_GetVendorItems(request, response) {
response.write(JSON.stringify(getVendorItems(request)));
}
function getVendorItems(request) {
var vendorid = request.getParameter('vendorid');
var filters = new Array();
var columns = new Array();
filters[0] = new nlobjSearchFilter('vendorcost', null, 'greaterthan', 0);
//filter should be on vendor
filters[1] = new nlobjSearchFilter('vendor', null, 'anyof', vendorid );
columns[0] = new nlobjSearchColumn('itemid');
columns[1] = new nlobjSearchColumn('entityid', 'vendor');
columns[2] = new nlobjSearchColumn('vendorcost');
columns[3] = new nlobjSearchColumn('vendorcode');
columns[4] = new nlobjSearchColumn('vendorpricecurrency');
var searchresults = nlapiSearchRecord('item', null, filters, columns );
//for test test each element of the array
(searchresults || []).forEach(function(res){
nlapiLogExecution('DEBUG', 'searchRes', res instanceof nlobjSearchResult);
})
return searchresults;
}
Also, make sure vendor id is specified in request parameter
var url = nlapiResolveURL('SUITELET', 'customscriptls_getitemvendors', 'customdeploy_getitemvendors', true);
var params = {}
params['itemid'] = itemID ; // itemID is passed to this function.
params['vendorid'] = vendorID ; // vendorID is passed to this function.
var response = nlapiRequestURL(url, params);
var itemVendorSublist = response.getBody();
If you're trying to query on item vendor then simply try
filters[1] = new nlobjSearchFilter('vendor', null,'anyof', vendorid );
This works in a console window. I suspect you are not supplying the numeric internal id in your parameter:
var vendorid = 43; // or 32 values from my test account. Want to confirm that the code works whether vendor is item's preferred vendor or not.
nlapiSearchRecord('item', null, [
new nlobjSearchFilter('vendorcost', null, 'greaterthan', 0),
new nlobjSearchFilter('internalid', 'vendor', 'anyof', [vendorid]), //numeric value
new nlobjSearchFilter('internalid', null, 'is', '42') // limit results for testing
], [
new nlobjSearchColumn('itemid'),
new nlobjSearchColumn('entityid', 'vendor'),
new nlobjSearchColumn('vendorcost'),
new nlobjSearchColumn('vendorcode'),
new nlobjSearchColumn('vendorpricecurrency')
]).forEach(function(it) {
console.log("%s from %s", it.getValue('itemid'), it.getValue('entityid', 'vendor'));
});
Although I've been working with Netsuite since 2002 I've never returned a set of search results directly from a Suitelet. I've seen that a couple of times recently in people's answers on this forum but I still find it a bit amusing.
If I were writing this I'd have tended to do the following:
var results = (nlapiSearchRecord(...) || []).map(function(res){
return { id:res.getId(), vendorName: res.getValue('entityid', 'vendor')...};
});
response.setContentType('JAVASCRIPT');
response.write(JSON.stringify(results));
Actually there's generally a little more. I have a sublime text snippet that I use for suitelet responses that handles a couple of common JSONP patterns (e.g. if you were calling this from a website):
function _sendJSResponse(request, response, respObject){
response.setContentType('JAVASCRIPT');
var callbackFcn = request.getParameter("jsoncallback") || request.getParameter('callback');
if(callbackFcn){
response.writeLine( callbackFcn + "(" + JSON.stringify(respObject) + ");");
}else response.writeLine( JSON.stringify(respObject) );
}
I have a Document Library with column type Hyperlink or Picture (Signature).
How to insert (Signature) into your Word document?
Images from a SharePoint list or library can be inserted into a library using the 'Document Property' under 'Quick Parts'. Images and URLs are not normally supported for this but a quick conversion of the URL to a text field gets around this issue.
You should read about Word Automation Services. They allow you to merge different documents into one.
Also you can always build your own Word document: Generating Documents from SharePoint with Open XML Content Controls
I use this code
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using A = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
you can call the InsertAPicture method by passing in the path of the word document, and the path of the file that contains the picture.
string document = #"C:\Users\Public\Documents\Word9.docx";
string fileName = #"C:\Users\Public\Documents\MyPic.jpg";
InsertAPicture(document, fileName);
public static void InsertAPicture(string document, string fileName)
{
using (WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Open(document, true))
{
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
imagePart.FeedData(stream);
}
AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
}
}
private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
{
// Define the reference of the image.
var element =
new Drawing(
new DW.Inline(
new DW.Extent() { Cx = 990000L, Cy = 792000L },
new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L,
RightEdge = 0L, BottomEdge = 0L },
new DW.DocProperties() { Id = (UInt32Value)1U,
Name = "Picture 1" },
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks() { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{ Id = (UInt32Value)0U,
Name = "New Bitmap Image.jpg" },
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{ Uri =
"{28A0092B-C50C-407E-A947-70E740481C1C}" })
)
{ Embed = relationshipId,
CompressionState =
A.BlipCompressionValues.Print },
new A.Stretch(
new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = 990000L, Cy = 792000L }),
new A.PresetGeometry(
new A.AdjustValueList()
) { Preset = A.ShapeTypeValues.Rectangle }))
) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
) { DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U, EditId = "50D07946" });
// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
}
I have a method that calls stored procedure and returns the data after executing DataReader.
I am trying to test the method using mock. I am not sure how to return value?
Anyone did this? Appreciate your responses.
Here is my code:
// Call the StoredProcedure
public List<string> GetCompletedBatchList(int fileId)
{
List<string> completedBatches = new List<string>();
StoredProcedure sp = new StoredProcedure("GetDistributedBatches", this.dataProvider);
sp.Command.AddParameter("FileID", fileId, DbType.Int32, ParameterDirection.Input);
sp.Command.AddParameter("Result", null, DbType.Int32, ParameterDirection.InputOutput);
using (var rdr = sp.ExecuteReader())
{
while (rdr != null && rdr.Read())
{
if (rdr[0] != null)
{
completedBatches.Add(rdr[0].ToString());
}
}
}
return completedBatches;
}
Here is the Test Method:
[Test]
public void Can_get_completedBatches()
{
var file = new File() { FileID = 1, DepositDate = DateTime.Now };
repo.Add<File>(file);
CompletedBatches completedBatches = new CompletedBatches(provider.Object);
//Here I am not sure how to Return
provider.Setup(**x => x.ExecuteReader(It.IsAny<QueryCommand>())).Returns** =>
{
cmd.OutputValues.Add(0);
});
var completedBatchesList = completedBatches.GetCompletedBatchList(file.FileID);
Assert.AreEqual(0, completedBatchesList.Count());
}
If you want to create a DataReader of a certain shape and size then I suggest you look at DataTable.CreateDataReader DataTable.CreateDataReader. You can then setup the ExecuteReader in your example to return this datareader.
The following link helped me...
How to mock an SqlDataReader using Moq - Update
I used MockDbDataReader method to mock the data
[Test]
public void Can_get_completedBatches_return_single_batch()
{
var date = DateTime.Now;
var file = new File() { FileID = 202, DepositDate = DateTime.Now };
var batch1 = new Batch() { FileID = 202, BatchID = 1767, LockboxNumber = "1", IsLocked = true, LockedBy = "testUser" };
var transaction1 = new Transaction() { BatchID = 1767, TransactionID = 63423, CheckAmount = 100.0 };
var distribution1 = new Distribution() { TransactionID = 63423, InvoiceNumber = "001", Amount = 100.0, DateCreated = date, DateModified = date, TransType = 2 };
repo.Add<File>(file);
repo.Add<Batch>(batch1);
repo.Add<Transaction>(transaction1);
repo.Add<Distribution>(distribution1);
CompletedBatches completedBatches = new CompletedBatches(provider.Object);
provider.Setup(x => x.ExecuteReader(It.IsAny<QueryCommand>())).Returns(MockDbDataReader());
var completedBatchesList = completedBatches.GetCompletedBatchList(202);
Assert.AreEqual(1, completedBatchesList.Count());
}
// You should pass here a list of test items, their data
// will be returned by IDataReader
private DbDataReader MockDbDataReader(List<TestData> ojectsToEmulate)
{
var moq = new Mock<DbDataReader>();
// This var stores current position in 'ojectsToEmulate' list
int count = -1;
moq.Setup(x => x.Read())
// Return 'True' while list still has an item
.Returns(() => count < ojectsToEmulate.Count - 1)
// Go to next position
.Callback(() => count++);
moq.Setup(x => x["BatchID"])
// Again, use lazy initialization via lambda expression
.Returns(() => ojectsToEmulate[count].ValidChar);
return moq.Object;
}