I am facing issue in code coverage of a Batchable class in apex - apex

I am facing issue in code coverage of a Batchable class in apex
Below is the type of settings used
static resources are used
Custom settings are used
multiple API call outs are used IN EXECUTE method of batchable class.
Multiple calls because of API pagination like 50 records each time for a total of 3K records
The issue is related to APEX Test class.
Total test coverage getting as 63% not increasing.
Below is the test class:
#isTest
global class Core_XXXX_IntelProductDataTest {
#testsetup static void TestTestUp()
{
insertCustomSettings();
}
#isTest static void Core_XXXXXX_ProductDataTest200(){
Test.startTest();
Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
HTTPResponse res1 = getInfoFromExternalService('https://XXXXXX/services/products?localeGeoId=en-US&categoryId=873&includeAttributes=true&limit=1&offset=1');
StaticResource sr = [SELECT Id, Body FROM StaticResource WHERE Name = 'Product_XXXXXX' LIMIT 1];
String body = sr.Body.toString();
System.assertEquals(body, res1.getBody());
System.assertEquals(200, res1.getStatusCode());
Database.executeBatch(new Core_XXXX_IntelProductData());
Core_XXXXXXProductDataScheduler.Core_XXXXXXProductDataScheduler();
Test.stopTest();
}
public static HttpResponse getInfoFromExternalService(String endpoint) {
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('GET');
req.setTimeout(60000);
Http h = new Http();
HttpResponse res = h.send(req);
system.debug('httpMock:'+res);
return res;
}
public static void insertCustomSettings(){
List<Core_IQR_Endpoints__c> endPointList = new List<Core_IQR_Endpoints__c>();
Core_IQR_Endpoints__c e1 = new Core_IQR_Endpoints__c();
boolean customAPILoadFlag= true;
DateTime todaysDate = System.today()-1;
DateTime customAPILoaddate =System.today()-2;
String todaysDateStr='';
if (customAPILoadFlag)
{
todaysDateStr = customAPILoaddate.format('yyyy-MM-dd');
todaysDateStr =todaysDateStr + 'T00:00:00Z';
}
else
{
todaysDateStr = todaysDate.format('yyyy-MM-dd');
todaysDateStr =todaysDateStr + 'T00:00:00Z';
}
e1.name = 'authtoken';
e1.Endpoint__c='client_id=ec3dc7a0-5f81-4846-8b34-d288386dc520&client_secret=6Cr7Q~j1Zbsw3psK8K_xlqcSll7CZlx0n7a7l&grant_type=client_credentials';
Core_IQR_Endpoints__c e2 = new Core_IQR_Endpoints__c();
e2.name = 'authtokenURL';
e2.Endpoint__c='https://XXXX.com/v1/auth/token';
Core_IQR_Endpoints__c e3 = new Core_IQR_Endpoints__c();
e3.name = 'Product_XXX_Integration_IQR';
e3.Endpoint__c='https://XXXX.com/v1/services/products?localeGeoId=en-US&categoryId=873&includeAttributes=true&limit=1';
e3.IQR_PIM_Custom_DataLoad__c= true;
e3.IQR_PIM_Custom_DataLoad_Date__c= System.today()-2;
Core_IQR_Endpoints__c e4 = new Core_IQR_Endpoints__c();
e4.name = 'Product_PIM_Integration_IQR1';
e4.Endpoint__c='https://XXXX.com/v1/services/products?localeGeoId=en-US&categoryId=873&includeAttributes=true&limit=1&offset=2&filters=updatedDateTime gt '+ todaysDateStr;
endPointList.add(e1);
endPointList.add(e2);
endPointList.add(e3);
endPointList.add(e4);
insert endPointList;
}
public static void recordInsertSetUp(){
List<Core_IQR_Endpoints__c> endPointList = new List<Core_IQR_Endpoints__c>();
Core_IQR_Endpoints__c e11 = new Core_IQR_Endpoints__c();
e11.name = 'authtoken';
e11.Endpoint__c='client_id=ec3dc7a0-5f81-4846-8b34-d288386dc520&client_secret=6Cr7Q~j1Zbsw3psK8K_xlqcSll7CZlx0n7a7l&grant_type=client_credentials';
Core_IQR_Endpoints__c e22 = new Core_IQR_Endpoints__c();
e22.name = 'authtokenURL';
e22.Endpoint__c='https://XXXX.com/v1/auth/token';
Core_IQR_Endpoints__c e33 = new Core_IQR_Endpoints__c();
e33.name = 'Product_XXX_Integration_IQR';
e33.Endpoint__c='https://XXXX.com/pim/v1/services/products?localeGeoId=en-US&categoryId=873&includeAttributes=true&limit=1&offset=1';
endPointList.add(e11);
endPointList.add(e22);
endPointList.add(e33);
insert endPointList;
HTTPResponse res = getInfoFromExternalService('https://XXXX.com/v1/auth/token');
HTTPResponse res1 = getInfoFromExternalService('https://XXXX.com/v1/services/products?localeGeoId=en-US&categoryId=873&includeAttributes=true&limit=1&offset=1');
HTTPResponse res2 = getInfoFromExternalService('https://XXXX.com/services/products?localeGeoId=en-US&categoryId=873&includeAttributes=true&limit=1&offset=2');
HTTPResponse res3 = getInfoFromExternalService('https://XXXX.com/services/products?localeGeoId=en-US&categoryId=873&includeAttributes=true&limit=1&offset=3');
HTTPResponse res4 = getInfoFromExternalService('https://XXXX.com/services/products?localeGeoId=en-US&categoryId=873&includeAttributes=true&limit=1&offset=4');
HTTPResponse res5 = getInfoFromExternalService('https://XXXX.com/services/products?localeGeoId=en-US&categoryId=873&includeAttributes=true&limit=1&offset=5');
}
public class MockHttpResponseGenerator implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
StaticResource sr = [SELECT Id, Body FROM StaticResource WHERE Name = 'Product_XXX_Integration_IQR' LIMIT 1];
res.setBody(sr.Body.toString());
res.setStatusCode(200);
System.assert(res != null);
return res;
}
}
}

Related

Error while reading body of request message through JSON

I need to read content of message from the request body in WCF REST service like -
SERVICE SIDE CODE
string request = Encoding.UTF8.GetString(OperationContext.Current.RequestContext.RequestMessage.GetBody<byte[]>());
But I am getting an error on the service side, no matter what I try:
Expecting element 'base64Binary' from namespace 'http://schemas.microsoft.com/2003/10/Serialization/'.. Encountered 'Element' with name 'Human', namespace 'http://numans.hr-xml.org/2007-04-15'.
and the service contract is defined as:
//[OperationContract(Name = "LoadMessages", IsOneWay = true)]
[WebInvoke(Method = "POST",
UriTemplate = "/LoadMessages",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
[Description("Inbound Message")]
void LoadMessages();
and the implementation is as:
public void LoadMessages()
{
string content = string.Empty;
//var request = OperationContext.Current.RequestContext.RequestMessage.GetBody<FileState>();
string request = Encoding.UTF8.GetString(OperationContext.Current.RequestContext.RequestMessage.GetBody<byte[]>());
}
CLIENT SIDE CODE
Content that I'm sending is:
string jsonData = "{ \"categoryid\":\"" + file.CategoryId + "\",\"fileId\":\"" + file.FileId + "\" }";
I tried many options to send data from the client like:
var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
var content = new ByteArrayContent(buffer);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
and also tried this:
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
Posting request:
HttpResponseMessage executionResult = httpClient.PostAsync($"{url}/LoadMessages", content).Result;
I also tried serializing/de-serializing at client/server end, but that also is not working.
Can someone please suggest code samples what I can try that might work? Or point out what am I doing wrong.
A few more examples of what I tried with the JSON data :
var jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
var details = JObject.Parse(data);
Pasting my client side function for clarity:
HttpClient httpClient = new HttpClient(new HttpClientHandler());
HttpStatusCode statusCode = HttpStatusCode.OK;
string auditMessage = string.Empty;
using (httpClient)
{
var url = ConfigurationManager.AppSettings["APIURL"];
try
{
string jsonData = "{ \"categoryid\":\"" + file.CategoryId + "\",\"fileId\":\"" + file.FileId + "\" }";
//var jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);
//var details = JObject.Parse(data);
//var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var buffer = System.Text.Encoding.UTF8.GetBytes(jsonData);
var content = new ByteArrayContent(buffer);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage executionResult = httpClient.PostAsync($"{url}/LoadMessages", content).Result;
statusCode = executionResult.StatusCode;
if (statusCode == HttpStatusCode.Accepted)
{
file.Status = "Success";
}
}
catch (Exception ex)
{
}
}
Here is my demo:
This is the interface document of the service:
This is the request:
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8012/ServiceModelSamples/service/user");
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-16";
string Json = "{\"Email\":\"123\",\"Name\":\"sdd\",\"Password\":\"sad\"}";
request.ContentLength = Encoding.UTF8.GetByteCount(Json);
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(Json);
myStreamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
//myResponseStream.ResponseSoapContext
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
Console.WriteLine(retString);
Console.ReadKey();
}
}
Feel free to let me know if the problem persists.
UPDATE
Define the Test class:
[DataContract]
public class Test {
[DataMember]
public string categoryid { get; set; }
[DataMember]
public string fileId { get; set; }
}
the implementation is as:
public void LoadMessages(Test test)
{
Test dataObject = OperationContext.Current.RequestContext.RequestMessage.GetBody<Test>(new DataContractJsonSerializer(typeof(Test)));
Console.WriteLine(dataObject.categoryid);
}

Unable to access REST API’s in Camunda

In our project , we are trying to use camunda BPMN. using camunda standalone distro and deployed and running in Tomcat.
login as a admin user and able to access cockpit and task lists.But,when we try access the APIs using a Java client . we are getting an unauthorized (401) error. Though we are sending JSESSIONID as a “Cookie”
Tried both DefaultHttpClient and HttpURLConnection - It didn’t work out
Note : JSESSIONID is retrieved by calling the login api with admin username and password.
Help me to solve the issue
Attached below is the java client code
public static void main(String[] args) {
CamundaBMPNClient bpmnClient = new CamundaBMPNClient();
Map<Integer, String> cookieHeader = bpmnClient.getCookieHeader();
bpmnClient.getListofTasks(cookieHeader);
}
public Map<Integer, String> getCookieHeader() {
String jSessionID = null;
Map<Integer, String> headerValues = new HashMap<Integer, String>();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/"
+ "api/admin/auth/user/default/login/cockpit");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.addHeader("Accept", "application/json");
String jsonString = new Gson()
.toJson("username=admin&password=admin#123");
StringEntity params;
try {
params = new StringEntity(jsonString);
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
Header[] cookieheader = response.getHeaders("Set-Cookie");
for (Header s : cookieheader) {
// Do your stuff here
System.out.println(s.getValue());
String[] str = s.getValue().split(";");
int i = 1;
for (String s1 : str) {
headerValues.put(i, s1.trim());
i++;
}
}
System.out.println("jSessionID::" + jSessionID);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return headerValues;
}
public void getListofTasks(Map<Integer, String> cookieHeader) {
int id = 0;
// DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost(
"http://localhost:8090/camunda-webapp-tomcat-standalone-7.2.0/api/engine/engine/default/task");
request.addHeader("Content-type", "application/json");
String[] arrJSessionID = cookieHeader.get(1).split("=");
System.out.println("" + arrJSessionID[1]);
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID=",
arrJSessionID[1]);
cookie.setDomain("http://localhost:8090");
cookie.setPath("/camunda-webapp-tomcat-standalone-7.2.0/");
// cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");
cookieStore.addCookie(cookie);
// httpclient.setCookieStore(cookieStore);
HttpClient httpclient = HttpClientBuilder.create()
.setDefaultCookieStore(cookieStore).build();
String jsonString = new Gson().toJson("{}");
StringEntity jsonStr;
try {
jsonStr = new StringEntity(jsonString);
request.setEntity(jsonStr);
HttpResponse response = httpclient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
Header[] header = response.getHeaders("Set-Cookie");
for (Header h : header) {
System.out.println(h.getValue());
}
System.out.println("statusCode::" + statusCode);
} catch (Exception e) {
e.printStackTrace();
}
}

Springfox not generating Swagger docs for Spring MVC Rest versioned API

We are facing our REST API versioning and after having read a lot about the different options (URI versioning, mime type versioning) have decided to use the latter approach.
I was expecting that Springfox generates the following doc:
v1:
get /api/architecture/mails - application/vnd.arch.mails.v1+json
get /api/architecture/services - application/vnd.arch.service.v1+json
v2:
get /api/architecture/services - application/vnd.arch.service.v2+json
However, in the v2 I also get this:
get /api/architecture/services - application/vnd.arch.service.v1+json
It shouldn't be there since I configured the v2 Docklet with
.produces(new HashSet<String>(Arrays.asList(new String[]{"application/vnd.arch.service.v2+json"}))) so that it filters the services according to the versioned mime type. Why isn't is working?
Here is our springfox config:
#Bean
public Docket arqV1Api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex("/api/architecture/.*"))
.build()
.apiInfo(new ApiInfo("Architecture Rest Api","Architecture REST Services","v1","","","",""))
.produces(new HashSet<String>(Arrays.asList(new String[]{"application/vnd.arch.service.v1+json","application/vnd.arch.mail.v1+json"})))
.securitySchemes(newArrayList(apiKey()))
.securityContexts(newArrayList(securityContext()))
.groupName("Arq v1 group");
}
#Bean
public Docket arqV2Api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex("/api/architecture/.*"))
.build()
.apiInfo(new ApiInfo("Architecture Rest Api","Architecture REST Services","v2","","","",""))
.produces(new HashSet<String>(Arrays.asList(new String[]{"application/vnd.arch.service.v2+json"})))
.securitySchemes(newArrayList(apiKey()))
.securityContexts(newArrayList(securityContext()))
.groupName("Arq v2 group");
}
And these is the REST Controller:
private static final String serviceArqV1MediaType = "application/vnd.arch.service.v1+json";
private static final String serviceArqV2MediaType = "application/vnd.arch.service.v2+json";
private static final String mailsArqV1MediaType = "application/vnd.arch.mail.v1+json";
#ApiOperation(value = "Gets architecture services",
notes = "",
produces = serviceArqV1MediaType)
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Request OK"),
#ApiResponse(code = 400, message = "Bad Request")})
#RequestMapping(value = {"/services"}, method = RequestMethod.GET,
produces = serviceArqV1MediaType)
public List<ServicioArquitectura> getServices() {
return Arrays.asList(new ServiceArch[]{new ServicioArquitectura("Support"), new ServicioArquitectura("Kickoff")});
}
#ApiOperation(value = "Gets architecture services",
notes = "",
produces = serviceArqV2MediaType)
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Request OK"),
#ApiResponse(code = 400, message = "Bad Request")})
#RequestMapping(value = {"/services"}, method = RequestMethod.GET,
produces = {serviceArqV2MediaType})
public List<ServicioArquitecturaV2> getServicesV2() {
return Arrays.asList(new ServiceArchV2[]{new ServiceArchV2("Support", Boolean.TRUE), new ServiceArchV2("Kickoff", Boolean.FALSE)});
}
#ApiOperation(value = "Gets mails",
produces = mailsArqV1MediaType)
#ApiResponses(value = {
#ApiResponse(code = 200, message = "Request OK"),
#ApiResponse(code = 400, message = "Bad Request")})
#RequestMapping(value = {"/mails"}, method = RequestMethod.GET,
produces = {mailsArqV1MediaType})
public List<String> getMails() {
return Arrays.asList(new String[]{"xxxcompany.com"});
}
I opened an issue in Springfox's github and they pointed out how to correctly configure it. Here's the solution:
Helper static methods:
public static Predicate<RequestHandler> withMediaType(final MediaType[] mediaTypes){
return new Predicate<RequestHandler>() {
#Override
public boolean apply(RequestHandler input) {
if(mediaTypes!=null){
ProducesRequestCondition producesCondition = input.getRequestMapping().getProducesCondition();
Set<MediaType> producibleMediaTypes = producesCondition.getProducibleMediaTypes();
for (MediaType mt : producibleMediaTypes) {
for (int i = 0; i < mediaTypes.length; i++) {
if(mt.equals(mediaTypes[i])){
return true;
}
}
}
}
return false;
}
};
}
public static Set<String> mediaTypesToStringSet(MediaType[] mediaTypes){
Set<String> mediaTypesSet = new HashSet<String>();
if(mediaTypes!=null){
for (int i = 0; i < mediaTypes.length; i++) {
mediaTypesSet.add(mediaTypes[i].toString());
}
}
return mediaTypesSet;
}
Docket definitions:
#Bean
public Docket arqV1Api() {
MediaType[] validMediaTypes = new MediaType[]{new MediaType("application","vnd.arch.service.v1+json"),
new MediaType("application","vnd.arch.mails.v1+json")};
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(withMediaType(validMediaTypes))
.paths(PathSelectors.regex("/api/architecture/.*"))
.build()
.apiInfo(new ApiInfo("Architecture Rest Api","Architecture REST Services","v1","","","",""))
.produces(mediaTypesToStringSet(validMediaTypes))
.securitySchemes(newArrayList(apiKey()))
.securityContexts(newArrayList(securityContext()))
.groupName("Arq v1 group");
}
#Bean
public Docket arqV2Api() {
MediaType[] validMediaTypes = new MediaType[]{new MediaType("application","vnd.arch.service.v2+json")};
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(withMediaType(validMediaTypes))
.paths(PathSelectors.regex("/api/architecture/.*"))
.build()
.apiInfo(new ApiInfo("Architecture Rest Api","Architecture REST Services","v2","","","",""))
.produces(mediaTypesToStringSet(validMediaTypes))
.securitySchemes(newArrayList(apiKey()))
.securityContexts(newArrayList(securityContext()))
.groupName("Arq v2 group");
}

org.hibernate.search.bridge.BridgeException: Exception while calling bridge#objectToString

I am able to insert record and able index them but i am facing an exception while searching
org.hibernate.search.bridge.BridgeException: Exception while calling bridge#objectToString
class: com.edoors.formBean.Hib_cons_Cv
path: cons_cv
I am able search on all coulmn of table except blob column
Field Bridge
public class ByteArrayBridge implements TwoWayStringBridge {
public String objectToString(Object object) {
byte[] data = (byte[]) object;
StringWriter writer = new StringWriter();
InputStream is = null;
try {
is = new ByteArrayInputStream(data);
new AutoDetectParser().parse(is,new WriteOutContentHandler(writer),new Metadata(),new
ParseContext());
return is.toString();
} catch (Exception e) {
System.out.println("Exception "+e);
}
return writer.toString();
}
public Object stringToObject(String string) {
byte[] data=string.getBytes();
Object obj=data;
return obj;
}
}
DAO Class ::
public List searchConsultantByTitle(String jobtitle)
{
List list=null;
Session session = hiberUtil.openSession();
Transaction tx = null;
try{
tx = session.beginTransaction();
FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryBuilder queryBuilder =
fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Hib_cons_Cv.class).get();
org.apache.lucene.search.Query luceneQuery = null;
luceneQuery =
queryBuilder.keyword().fuzzy().withThreshold(0.7f).onField("cons_cv").matching(jobtitle).createQuery();
FullTextQuery hibernateQuery = fullTextSession.createFullTextQuery(luceneQuery, Hib_cons_Cv.class);
int resultSize = hibernateQuery.getResultSize();
System.out.println(".....resultSize..............................."+resultSize);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
POJO Class
#Entity
#AnalyzerDef(name = "customanalyzer", tokenizer = #TokenizerDef(factory =
KeywordTokenizerFactory.class), filters = {
#TokenFilterDef(factory = LowerCaseFilterFactory.class),
#TokenFilterDef(factory = SnowballPorterFilterFactory.class, params = {
#Parameter(name = "language", value = "English") }) })
#Indexed
public class Hib_cons_Cv {
#Column(name = "cons_cv", unique = false, nullable = false, length = 59296)
#Lob
#Field(analyze = Analyze.NO, store = Store.YES)
#FieldBridge(impl = ByteArrayBridge.class)
private Blob cons_cv;
//setters and getters
}
I also got this error (with no stack trace). Turned out i put in the wrong field name. It was actually using a field with no bridging.

ASP.NET MVC Web API 4 REST Webservice: PUT/POST - ing a List of objects

Wondering if its possible and/or supported to put/post an entire object to REST Webservice, as opposed to just some name/value pairs ?
If so, can a List of objects be put/post-ed as well ?
I figured it may be possible, since a GET request is able to return a List of objects, I'd like to do the "reverse" operation with the updated objects (and not send them one at a time, or worse, in individual pieces via name/value pairs) ?
I understand this is a very basic question, but the approach I've taken so far was to just try and code the PUT and get it working (which works if the PUT function has no arguments, like:
public class AObjectController : ApiController
{
public List<int[]> Put()
{
List<int[]> ret = new List<int[]>();
ret.Add(new int[] {-1, 1111});
ret.Add(new int[] {-2, 2222});
return ret;
}
If I specify a single object, or list of objects, I get exceptions:
public List<int[]> Put(AObject object) **CASE 1**
public List<int[]> Put(List<AObject> objects) **CASE 2**
{
List<int[]> ret = new List<int[]>();
ret.Add(new int[] { -1, 1111 });
ret.Add(new int[] { -2, 2222 });
return ret;
}
CASE 1: public List(int[]) Put(AObject object)
CASE 2: public List(int[]) Put(List(AObject) objects)
Heres the code on the client side that is making the call:
public int writeAll(List<T> data)
{
_sendBuffer =
JsonConvert.SerializeObject(
tabletData,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }
);
byte[] b = StringHelper.GetBytes(_sendBuffer);
string url = ContructUrlRequest(null, null);
WebRequest request = WebRequest.Create(url);
request.Method = "PUT";
request.ContentType = "application/json";
request.ContentLength = b.Length;
request.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)request).UserAgent = "...";
//((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(b, 0, b.Length);
requestStream.Flush();
requestStream.Close();
}
WebResponse response = request.GetResponse();
if (response == null)
{
return -1;
}
StreamReader sr = new StreamReader(response.GetResponseStream()); ;
_recieveBuffer = sr.ReadToEnd();
List<int[]> _resultData = JsonConvert.DeserializeObject<List<int[]>>(
_recieveBuffer,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }
);
return data.Count;
}
Thank you.
Used the serialization write code from server on my client side and it worked
public int writeAll(List<AObject> aObjects)
{
string url = ContructUrlRequest(null, null);
WebRequest request = WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Put;
request.ContentType = "application/json; charset=utf-8";
request.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)request).UserAgent = "going insane";
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.TypeNameHandling = TypeNameHandling.Objects | TypeNameHandling.Arrays;
serializerSettings.Converters.Add(new IsoDateTimeConverter());
JsonSerializer serializer = JsonSerializer.Create(serializerSettings);
using (Stream requestStream = request.GetRequestStream())
{
using (StreamWriter streamWriter = new StreamWriter(requestStream, new UTF8Encoding(false, true)))
{
using (JsonTextWriter jsonTextWriter = new JsonTextWriter(streamWriter))
{
serializer.Serialize(jsonTextWriter, aObjects);
}
}
}
WebResponse response = request.GetResponse();
if (response == null)
{
Log.Info(FIDB.TAG_WSBUFFER, "WSBuffer.writeAll: response = NULL");
return -1;
}
StreamReader sr = new StreamReader(response.GetResponseStream());
_recieveBuffer = sr.ReadToEnd();
_resultData = JsonConvert.DeserializeObject<List<int[]>>(
_recieveBuffer,
new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }
);
return tabletData.Count;
}