I am sending request to a web service though my c# code. I'm able to get successful request and response in Fiddler and also can get response back in SOAP UI by using Fiddler's request. But while debugging in code, I get Response object as null "Object reference not set to an instance of an object".
Below is my c# code :
public List<MailOutResponse> SendMailOrder(OrderEntity objOrderEnty)
{
List<MailOutResponse> lsteDemandResp = new List<MailOutResponse>();
MailOutResponse objMailOutResp = null;
string strPayloadType = objOrderEnty.PayloadType;
string strMailType = objOrderEnty.MailType;
eDemandService.Order eDemandOrder = null;
try
{
LogProcess.WriteLog("Processing item--" + objOrderEnty.OrderItemList[0].UniqueId.ToString(), strMailType);
eDemandOrder = new eDemandService.Order();
eDemandOrder.UniqueOrderId = "UD" + objOrderEnty.OrderItemList[0].UniqueId.Replace(":", "").ToString();
eDemandOrder.OrderHeader = createOrderHeader(objOrderEnty.OrderItemList[0]);
eDemandService.OrderOrderItem orderItem = new eDemandService.OrderOrderItem();
orderItem.ItemDetailStructure = new eDemandService.OrderOrderItemItemDetailStructure();
orderItem.ItemDetailStructure.Item = strItemDetailStructVal;
orderItem.UniqueOrderItemId = "OB" + objOrderEnty.OrderItemList[0].UniqueId.Replace(":", "");
XmlDocument f = new XmlDocument();
f = (XmlDocument)GetXmlNode(objOrderEnty.OrderItemList[0].PayLoad.Root);
orderItem.PreFillPayload = f.DocumentElement;
eDemandService.OrderOrderItem[] orderItems = new eDemandService.OrderOrderItem[1];
orderItems[0] = orderItem;
eDemandOrder.OrderDetail = orderItems;
eDemandService.eDemand eDemand = new eDemandService.eDemand();
eDemandService.edemandService edemandClient = new eDemandService.edemandService();
eDemand.PayloadType = strPayloadType;
eDemand.OriginatingSysRef = strOriginatingSysRef;
eDemand.Order = eDemandOrder;
eDemandService.eDemandResponse myResponse = new eDemandService.eDemandResponse();
LogProcess.WriteLog("---------------Calling the eDemand service-----------------", strMailType);
LogProcess.WriteLog(eDemand, DateTime.Now.Ticks.ToString(), strMailType);
myResponse = edemandClient.e(eDemand);
LogProcess.WriteLog(myResponse, DateTime.Now.Ticks.ToString(), strMailType);
eDemandService.eDemandResponseOrderResponse[] rspns = new eDemandService.eDemandResponseOrderResponse[1] ;
rspns = myResponse.OrderResponse;
for (int i = 0; i < myResponse.OrderResponse.Length; i++)
{
objMailOutResp = new MailOutResponse();
if (myResponse.OrderResponse.Length > 0)
{
objMailOutResp.OrderResponseCode = myResponse.OrderResponse[i].OrderResponseCode;
objMailOutResp.ExecutionStatus = myResponse.OrderResponse[i].OrderResponseText;
if (myResponse.OrderResponse[i].OrderResponseCode == "2000")
{
if (myResponse.OrderResponse[i].OrderItemResponse[0] != null)
{
objMailOutResp.ResponseUID = myResponse.OrderResponse[i].OrderItemResponse[0].UniqueOrderItemId;
objMailOutResp.IDBID = myResponse.OrderResponse[i].OrderItemResponse[0].IDBID;
}
}
}
lsteDemandResp.Add(objMailOutResp);
}
}
catch (Exception ex)
{
LogProcess.WriteLog("Error calling the eDemand service - " + ex.Message, strMailType);
}
return lsteDemandResp;
}
Here's the wsdl response type:
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Bare)]
[return: System.Xml.Serialization.XmlElementAttribute("eDemandResponse", Namespace="http://edemand.fmr.com/eDemandRequest")]
public eDemandResponse e([System.Xml.Serialization.XmlElementAttribute(Namespace="http://edemand.fmr.com/eDemandRequest")] eDemand eDemand) {
object[] results = this.Invoke("e", new object[] {
eDemand});
return ((eDemandResponse)(results[0]));
}
And here's what I get from fiddler:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<Resp:eDemandResponse B2BID="3322277" xmlns:Resp="http://eDemand.fmr.com/eDemandResponse">
<StatusCode>2000</StatusCode>
<StatusText>Processing was successful</StatusText>
<OrderResponse UniqueOrderId="UDTA_ID429636">
<OrderResponseCode>2000</OrderResponseCode>
<OrderResponseText>Processing was successful</OrderResponseText>
<OrderItemResponse IDBID="154464360" UniqueOrderItemId="OBTA_ID429636">
<DeliveryMethod>
<Delivery type="Postal">
<ExecutionStatus>
<ReturnCode>2000</ReturnCode>
<ReturnText>Postal Delivery Method Successful</ReturnText>
</ExecutionStatus>
</Delivery>
</DeliveryMethod>
</OrderItemResponse>
</OrderResponse>
</Resp:eDemandResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
My wsdl url is : https://dgedmdrtp1.fmr.com:12000/eDemand/edemand/
So basically when I debug the client, I see that the request goes in properly populated, but the response isn't being unmarshaled into the stub response object that was generated when the web reference was made.
Related
I have a C# code that consumes a web service data from an external site. it was working and displaying the weather data on my page but now it throws "An exception occurred during a WebClient request" error. I was trying to research this but no luck.
protected void GetWeatherInfo(string url)
{
string url1 = string.Format(url);
using (WebClient client = new WebClient())
{
WebProxy proxyObj = new WebProxy(url1);
proxyObj.Credentials = CredentialCache.DefaultCredentials;
client.Proxy = proxyObj;
try
{
string json = client.DownloadString(url1);
WeatherInfo weatherInfo = (new JavaScriptSerializer()).Deserialize<WeatherInfo>(json);
lblCity_Country.Text = weatherInfo.city.name + "," + weatherInfo.city.country;
imgCountryFlag.ImageUrl = string.Format("http://openweathermap.org/images/flags/{0}.png", weatherInfo.city.country.ToLower());
lblDescription.Text = weatherInfo.list[0].weather[0].description;
imgWeatherIcon.ImageUrl = string.Format("http://openweathermap.org/img/w/{0}.png", weatherInfo.list[0].weather[0].icon);
lblTempMin.Text = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.min, 1));
lblTempMax.Text = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.max, 1));
lblTempDay.Text = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.day, 1));
lblTempNight.Text = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.night, 1));
lblHumidity.Text = weatherInfo.list[0].humidity.ToString();
tblWeather.Visible = true;
}
catch (Exception ex)
{
string excep = ex.Message;
}
}
}
I Have to Upload the file to my teamdrive, the file has been created to team drive but I can not upload the file chunks to it. So, please help to solve it.
On Writing a Chunk I am facing the Error of "The remote server returned an error: (404) Not Found."
I am getting the Teamdrive ID and the File ID which has been created.
/*** Creation of a File to Team Drive ***/
f_ObjFile.TeamDriveId = "/*TeamDrive ID*/";
try
{
f_ObjNewFile.Parents = f_ObjFile.Parents; // f_ObjFile = <Team Driv ID>
f_ObjNewFile.Name = f_ObjFile.Name;
f_ObjNewFile.MimeType = f_ObjFile.MimeType;
f_ObjNewFile.TeamDriveId = f_ObjFile.TeamDriveId;
f_CreateRequest = GoogleHelper.InvokeApiCall(() => { return this.DriveServiceObj.Files.Create(f_ObjNewFile); }, this);
if (f_CreateRequest != null)
{
f_CreateRequest.SupportsTeamDrives = true;
f_CreateRequest.Fields = "*";
f_ObjNewFile = GoogleHelper.InvokeApiCall(() => { return f_CreateRequest.Execute(); }, this);
}
f_ObjDocumentItem = new DocumentItem(UserEmailID, f_ObjNewFile);
f_ObjDocumentItem.ItemID = f_ObjNewFile.Id;
string f_Url = GoogleHelper.CreateChunkURL("https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable", f_ObjNewFile.Id);
f_ObjDocumentItem.ChunkUploadURL = InitiateResumeRequest(f_Url, f_ObjNewFile.Id);
}
catch(Exception ex) { }
finally
{
f_ObjNewFile = null;
f_CreateRequest = null;
}
/* Writing the chunks to the file in TeamDrive */
try
{
httpRequest = GoogleHelper.CreateHttpWebRequestObj(f_ObjChunkData.ChunkUploadURL,true);
httpRequest.Method = GoogleConstant.PATCH;
httpRequest.ContentLength = f_ObjChunkData.FileData.Length;
httpRequest.SendChunked = true;
httpRequest.Headers["Content-Range"] = "bytes " + f_ObjChunkData.StartOffset +
"-" +
f_ObjChunkData.EndOffset + "/" +
f_ObjChunkData.FileSize.ToString();
using (System.IO.Stream f_ObjHttpStream = GoogleHelper.InvokeApiCall(() => { return httpRequest.GetRequestStream(); }, this))
{
if (f_ObjHttpStream != null)
{
System.IO.MemoryStream f_ChunkStream = null;
f_ChunkStream = new System.IO.MemoryStream(f_ObjChunkData.FileData);
f_ChunkStream.CopyTo(f_ObjHttpStream);
f_ObjHttpStream.Flush();
f_ObjHttpStream.Close();
f_ChunkStream.Close();
f_ChunkStream = null;
}
}
using (HttpWebResponse httpResponse = GoogleHelper.InvokeApiCall(() => { return (HttpWebResponse)(httpRequest.GetResponse()); }, this))
{
if (httpResponse != null)
{
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
httpResponse.Close();
}
}
}
}
catch (Exception ex) { }
In Followin Line :
string f_Url = GoogleHelper.CreateChunkURL("https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable", f_ObjNewFile.Id);
Insted Of
"https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable"
Use following URL :
https://www.googleapis.com/upload/drive/v3/files/{0}?uploadType=resumable&supportsTeamDrives=true
and its Done...
Now you can upload the chunks...
So i made a Windows Service API to Php from biometrics .everytime i send data via Web Client it sends Duplicate data instead of only sending 1 data ex:
Web Service -> Sends -> 1.Cardo Dalisay 01/01/2018 1:01:10PM -> 1.Cardo Dalisay 01/01/2018 1:01:10PM
//Get Data from biometric
ICollection<MachineInfo> lstmachineInfo = manipulator.GetLogData(objZkeeper, int.Parse(MachineNo));
//if its not null
if (lstmachineInfo != null && lstmachineInfo.Count > 0)
{
//new list for new updated data
List<MachineInfo.Datasend>zkteco = new List<MachineInfo.Datasend>();
const string encryptionkey = #"ZREpfb7s2q0+Jq598jTlGTSHovHMJ1ok";
//lambda which fetch only new data
var result = lstmachineInfo.ToList().Where(a => a.datetime >= DateTime.Now.AddMinutes(-1)).ToList();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//webclient is here
using (var webclient = new WebClient())
{
//fetch the newly data
foreach (var data in result)
{
//store then to new list
zkteco.Add(new MachineInfo.Datasend
{
_machineNumber = data.MachineNumber,
_subscription = Subscription,
_branchid = BranchID,
_userid = data.UserID,
_DateTimeRecord = data.DateTimeRecord,
_Checktype = data.InOut,
_Accesstoken = AccessToken
});
string JsonResponse = JsonConvert.SerializeObject(zkteco);
}
//fetch the newly stored data
foreach (var zktecolist in zkteco)
{
//namevaluecollection for webclient
var values = new NameValueCollection();
values["machineid"] = zktecolist._machineNumber.ToString();
values["subscription"] = zktecolist._subscription.ToString();
values["branchid"] = zktecolist._branchid.ToString();
values["userid"] = zktecolist._userid.ToString();
values["datetime"] = zktecolist._DateTimeRecord;
values["checktype"] = zktecolist._Checktype.ToString();
values["accesstoken"] = zktecolist._Accesstoken.ToString();
//Request follows
//below is the webclient request
var request = webclient.UploadValues("http://192.168.1.119/api/biometric_activity?data", values);
var response = Encoding.UTF8.GetString(request);
var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(response);
if (apiResponse.status == "Ok")
{
WriteToFile("test" + apiResponse.description + " -> " + apiResponse.message + "status -> " + apiResponse.status);
}
else if (apiResponse.status != "Ok")
{
WriteToFile("No Data has been fetch");
}
}
}
}
else
{
objZkeeper = new ZkemClient(RaiseDeviceEvent);
isDeviceConnected = objZkeeper.Connect_Net(IPAddress, Port);
WriteToFile("failed in connecting with device, reconnecting ....");
}
}
I am using PushSharp 4.0.10.0 library to send the notification on iOS devices but it's not working. I have debugged it and found there is some ApnsConfiguration connection problem.
I am using this code to send the notificaiton:
public IHttpActionResult Notify()
{
HttpResponseMessage response = new HttpResponseMessage();
HttpContent requestContent = Request.Content;
string errorMessage = "Some error occured.please try again later";
HttpStatusCode responseCode = HttpStatusCode.Unauthorized;
string requestParameter = requestContent.ReadAsStringAsync().Result;
string tokan = "";
var r = Request;
var header = r.Headers;
try
{
if (requestParameter != null)
{
PushNotificationModel complaintModel = JsonConvert.DeserializeObject<PushNotificationModel>(requestParameter);
JsonConvert.DeserializeObject<PushNotificationModel>(requestParameter);
var appleCert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/User/xyz.pem"));
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Production,
appleCert, "xyz");
// Create a new broker
var push = new ApnsServiceBroker(config);
int DeviceType = 1;
string deviceId = Convert.ToString(complaintModel.deviceToken);
string message = "New notification!!";
Guid complaintId = complaintModel.ComplaintId;
string detail = complaintModel.detail;
try
{
//System.Web.Hosting.HostingEnvironment.MapPath("~/Images/User/")
// var appleCert = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/Images/User/CTPwd.pem"));
push.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
message = ex.Message;
}
else
{
message = "Not an APNSException";
}
// Mark it as handled
return true;
});
};
try
{
push.OnNotificationSucceeded += (notification) =>
{
message = "New Notification";
};
push.Start();
string appleJsonFormat = "{\"aps\": {\"alert\":" + '"' + message + '"' + ",\"sound\": \"default\"}}";
//string appleJsonFormat = "{\"aps\": {\"alert\": " + "Hello World" + ",\"sound\": \"default\"}}";
push.QueueNotification(new ApnsNotification
{
DeviceToken = deviceId,
Payload = JObject.Parse(appleJsonFormat)
});
push.Stop();
}
catch(Exception ex)
{
}
I have searched on google, but did not find any relevant answer. Is there any syntax problem ?
Thanks in advance.
Please use .P12 file format for push notification happy coding:)
I'm using OWIN with WebAPI integration as WebApp. Future plan is to use OWIN self-hosting which is working fine but the OWIN testserver implementation is not working together with RestSharp:
Sample without RestSharp:
https://blogs.msdn.microsoft.com/webdev/2013/11/26/unit-testing-owin-applications-using-testserver/
First attempt is to use a mock class derived from RestClient class:
public class MockRestClient : RestClient
{
public TestServer TestServer { get; set; }
public MockRestClient(TestServer testServer)
{
TestServer = testServer;
}
public override IRestResponse Execute(IRestRequest request)
{
// TODO: Currently the test server is only doing GET requests via RestSharp
var response = TestServer.HttpClient.GetAsync(request.Resource).Result;
var restResponse = ConvertToRestResponse(request, response);
return restResponse;
}
private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResponseMessage httpResponse)
{
RestResponse restResponse1 = new RestResponse();
restResponse1.Content = httpResponse.Content.ReadAsStringAsync().Result;
restResponse1.ContentEncoding = httpResponse.Content.Headers.ContentEncoding.FirstOrDefault();
restResponse1.ContentLength = (long)httpResponse.Content.Headers.ContentLength;
restResponse1.ContentType = httpResponse.Content.Headers.ContentType.ToString();
if (httpResponse.IsSuccessStatusCode == false)
{
restResponse1.ErrorException = new HttpRequestException();
restResponse1.ErrorMessage = httpResponse.Content.ToString();
restResponse1.ResponseStatus = ResponseStatus.Error;
}
restResponse1.RawBytes = httpResponse.Content.ReadAsByteArrayAsync().Result;
restResponse1.ResponseUri = httpResponse.Headers.Location;
restResponse1.Server = "http://localhost";
restResponse1.StatusCode = httpResponse.StatusCode;
restResponse1.StatusDescription = httpResponse.ReasonPhrase;
restResponse1.Request = request;
RestResponse restResponse2 = restResponse1;
foreach (var httpHeader in httpResponse.Headers)
restResponse2.Headers.Add(new Parameter()
{
Name = httpHeader.Key,
Value = (object)httpHeader.Value,
Type = ParameterType.HttpHeader
});
//foreach (var httpCookie in httpResponse.Content.)
// restResponse2.Cookies.Add(new RestResponseCookie()
// {
// Comment = httpCookie.Comment,
// CommentUri = httpCookie.CommentUri,
// Discard = httpCookie.Discard,
// Domain = httpCookie.Domain,
// Expired = httpCookie.Expired,
// Expires = httpCookie.Expires,
// HttpOnly = httpCookie.HttpOnly,
// Name = httpCookie.Name,
// Path = httpCookie.Path,
// Port = httpCookie.Port,
// Secure = httpCookie.Secure,
// TimeStamp = httpCookie.TimeStamp,
// Value = httpCookie.Value,
// Version = httpCookie.Version
// });
return restResponse2;
}
Unfortunatly I stuck with Post events, which needs html body from restResponse.
Has anybody done something similar.
BTW: I can also use OWIN unit tests with self-hosting OWIN, but this will not work on Teamcity automatic builds.
I changed the mock rest Client to work with Post/Put/Delete methods too. It is not 100% complete (missing auth, Cookies, files etc.), but in my case it is sufficient:
public class MockRestClient : RestClient
{
public TestServer TestServer { get; set; }
public MockRestClient(TestServer testServer)
{
TestServer = testServer;
}
public override IRestResponse Execute(IRestRequest request)
{
// TODO: Currently the test server is only doing GET requests via RestSharp
HttpResponseMessage response = null;
Parameter body = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
HttpContent content;
if (body != null)
{
object val = body.Value;
byte[] requestBodyBytes;
string requestBody;
if (val is byte[])
{
requestBodyBytes = (byte[]) val;
content = new ByteArrayContent(requestBodyBytes);
}
else
{
requestBody = Convert.ToString(body.Value);
content = new StringContent(requestBody);
}
}
else
content = new StringContent("");
string urladd = "";
IEnumerable<string> #params = from p in request.Parameters
where p.Type == ParameterType.GetOrPost && p.Value != null
select p.Name + "=" + p.Value;
if(!#params.IsNullOrEmpty())
urladd = "?" + String.Join("&", #params);
IEnumerable<HttpHeader> headers = from p in request.Parameters
where p.Type == ParameterType.HttpHeader
select new HttpHeader
{
Name = p.Name,
Value = Convert.ToString(p.Value)
};
foreach (HttpHeader header in headers)
{
content.Headers.Add(header.Name, header.Value);
}
content.Headers.ContentType.MediaType = "application/json";
switch (request.Method)
{
case Method.GET:
response = TestServer.HttpClient.GetAsync(request.Resource + urladd).Result;
break;
case Method.DELETE:
response = TestServer.HttpClient.DeleteAsync(request.Resource + urladd).Result;
break;
case Method.POST:
response = TestServer.HttpClient.PostAsync(request.Resource + urladd, content).Result;
break;
case Method.PUT:
response = TestServer.HttpClient.PutAsync(request.Resource + urladd, content).Result;
break;
default:
return null;
}
var restResponse = ConvertToRestResponse(request, response);
return restResponse;
}
private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResponseMessage httpResponse)
{
RestResponse restResponse1 = new RestResponse();
restResponse1.Content = httpResponse.Content.ReadAsStringAsync().Result;
restResponse1.ContentEncoding = httpResponse.Content.Headers.ContentEncoding.FirstOrDefault();
restResponse1.ContentLength = (long)httpResponse.Content.Headers.ContentLength;
restResponse1.ContentType = httpResponse.Content.Headers.ContentType.ToString();
if (httpResponse.IsSuccessStatusCode == false)
{
restResponse1.ErrorException = new HttpRequestException();
restResponse1.ErrorMessage = httpResponse.Content.ToString();
restResponse1.ResponseStatus = ResponseStatus.Error;
}
restResponse1.RawBytes = httpResponse.Content.ReadAsByteArrayAsync().Result;
restResponse1.ResponseUri = httpResponse.Headers.Location;
restResponse1.Server = "http://localhost";
restResponse1.StatusCode = httpResponse.StatusCode;
restResponse1.StatusDescription = httpResponse.ReasonPhrase;
restResponse1.Request = request;
RestResponse restResponse2 = restResponse1;
foreach (var httpHeader in httpResponse.Headers)
restResponse2.Headers.Add(new Parameter()
{
Name = httpHeader.Key,
Value = (object)httpHeader.Value,
Type = ParameterType.HttpHeader
});
//foreach (var httpCookie in httpResponse.Content.)
// restResponse2.Cookies.Add(new RestResponseCookie()
// {
// Comment = httpCookie.Comment,
// CommentUri = httpCookie.CommentUri,
// Discard = httpCookie.Discard,
// Domain = httpCookie.Domain,
// Expired = httpCookie.Expired,
// Expires = httpCookie.Expires,
// HttpOnly = httpCookie.HttpOnly,
// Name = httpCookie.Name,
// Path = httpCookie.Path,
// Port = httpCookie.Port,
// Secure = httpCookie.Secure,
// TimeStamp = httpCookie.TimeStamp,
// Value = httpCookie.Value,
// Version = httpCookie.Version
// });
return restResponse2;
}