public static bool DataCheck(string RefNo, out string region)
{
region = "";
try
{
string url = "https://plugin.comapny.com/api/DataCheck";
using (var client = new WebClient())
{
Jobvalidation JVObj = new Jobvalidation();
JVObj.RefNo = RefNo.ToUpper();
JVObj.ConnectionString = Configration.DMSConfig.Connectionstring;
JVObj.Zone = Configration.DMSConfig.ZONE;
client.Headers.Add("Content-Type:application/json");
client.Headers.Add("Accept:application/json");
string result = client.UploadString(url, JsonConvert.SerializeObject(JVObj));
JVObj = JsonConvert.DeserializeObject<Jobvalidation>(result);
region = JVObj.region;
bool flag = Convert.ToBoolean(JVObj.flag);
return flag;
}
}
catch (Exception ex)
{
//string result;
region = "Exception:" + ex.Message;
return false;
}
}
when we hit the service from local machines we are getting the above error. above is my code could you please check and help for this
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 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.
I am working on Delayed Chained Payments Module in Adaptive Payments in Paypal. I am Using AdaptivePaymentsCoreSdk for it and it is working fine on LocalHost as well as one web Server. All working is going Fine. But when I Deploy my application on another Server than On Service.Pay I am Getting an Exception. Exception is as Follows:-
PayPal.Exception.ConnectionException: Invalid HTTP response The underlying connection was closed: An unexpected error occurred on a receive.
at PayPal.HttpConnection.Execute(String payLoad, HttpWebRequest httpRequest)
at PayPal.APIService.MakeRequestUsing(IAPICallPreHandler apiCallHandler)
at PayPal.BasePayPalService.Call(IAPICallPreHandler apiCallHandler)
at PayPal.AdaptivePayments.AdaptivePaymentsService.Pay(PayRequest payRequest, String apiUserName)
at PayPal.AdaptivePayments.AdaptivePaymentsService.Pay(PayRequest payRequest)
at Payme101.Controllers.HomeController.Order_Pay(Order_Pay single) in d:\Completed\Payme10\Payme101\Payme101\Controllers\HomeController.cs:line 2404
My Code is As Follows:-
PayRequest request = new PayRequest();
RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
ReceiverList receiverList = new ReceiverList();
request.requestEnvelope = requestEnvelope;
Receiver receiver1 = new Receiver();
receiver1.amount = 10;
receiver1.email = "Primary Email ID";
receiver1.primary = true;
receiver1.invoiceId = str;
Receiver receiver2 = new Receiver();
receiver2.amount = 8;
receiver2.email = SellerMail;
receiver2.primary = false;
receiver2.invoiceId = str;
receiverList.receiver.Add(receiver1);
receiverList.receiver.Add(receiver2);
request.receiverList = receiverList;
request.actionType = "PAY_PRIMARY";
request.currencyCode = "USD";
request.returnUrl = "http://ServerIP/Home/complete/?payKey=${payKey}";
request.cancelUrl = "http://ServerIP/Home/cancel?payKey=${payKey}";
//request.returnUrl = "http://localhost:1735/Home/complete/?payKey=${payKey}";
//request.cancelUrl = "http://localhost:1735/Home/cancel?payKey=${payKey}";
AdaptivePaymentsService service = null;
PayResponse response = null;
try
{
Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();
service = new AdaptivePaymentsService(configurationMap);
response = service.Pay(request);
}
catch (Exception ex)
{
//Here I am getting Exception.
return RedirectToAction("Order_Pay2", "Home", new { id = ex.ToString() });
}
Dictionary<string, string> responseValues = new Dictionary<string, string>();
string redirectUrl = null;
if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
{
redirectUrl = "https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_ap-payment&paykey=" + response.payKey;
return Redirect(redirectUrl);
}
Can Anybody tell me what I am doing wrong and What should i change to Remove this Exception And Make Payment Successfull.
Thanks in Advance...
I have been trying a way to get the data in the next page of the result set of GET followers/list API call. I can get the default data set with the data of first 20 followers and not the others. To get the data of other followers i have to access the next page using the next_cursor but it's not working. I tried using the pseudo-code mentioned in this link. https://dev.twitter.com/docs/misc/cursoring
Is it a must to use this(this is mentioned in the dev. site):
var api-path = "https://api.twitter.com/1.1/endpoint.json?screen_name=targetUser"
Because I have been using the resource URL as,
var resource_url = "https://api.twitter.com/1.1/followers/list.json";
and I tried appending the next_cursor to the same resource URL.
var url_with_cursor = resource_url + "&cursor=" + 1463101490306580067;
and then created the request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url_with_cursor);
but I'm getting an exception in this line when getting the response.
WebResponse response = request.GetResponse();
The error I'm getting is
The Remote Server returned an Error 401 Unauthorized
Can someone tell the exact way to do cursor-ing, or the exact way to include the cursor in the request. I'm using a asp.net C# web application.
Here's my code, The oauth_token, oauth_token_secret, oauth_consumer_key, oauth_consumer_secret, oauth_version and oauth_signature_method are defined in my application
var resource_url = "https://api.twitter.com/1.1/followers/list.json";
var cursor = "-1";
do
{
var url_with_cursor = resource_url + "&cursor=" + cursor;
// unique request details
var oauth_nonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
// create oauth signature
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version
//,Uri.EscapeDataString(status)
);
baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
// make the request
ServicePointManager.Expect100Continue = false;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url_with_cursor);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
JObject j = JObject.Parse(result);
JArray data = (JArray)j["users"];
cursor = (String)j["next_cursor_str"];
} while (!cursor.Equals("0"));
Thanks.
Tweetinvi would make it somewhat easier for you.
Please visit https://github.com/linvi/tweetinvi/wiki/Get-All-Followers-Code to have an idea on how to do it including RateLimit handling.
Without considering the RateLimits, you could simply use the following code.
long nextCursor = -1;
do
{
var query = string.Format("https://api.twitter.com/1.1/followers/ids.json?screen_name={0}", username);
var results = TwitterAccessor.ExecuteCursorGETCursorQueryResult<IIdsCursorQueryResultDTO>(query, cursor: cursor).ToArray();
if (results.Any())
{
nextCursor = results.Last().NextCursor;
}
else
{
nextCursor = -1;
}
}
while (nextCursor != -1 && nextCursor != 0);
you should make a different call to authenticate, by an authorization request. Once that has been granted, you can call the webresponse with the cursor. See my sample code below (Take special note to the StartCreateCall method, where the authentication is done. The data from Twitter is then retrieved by the CallData method):
public partial class twitter_followers : System.Web.UI.Page
{
public string strTwiterFollowers { get; set; }
private List<TwiterFollowers> listFollowers = new List<TwiterFollowers>();
private string screen_name = string.Empty;
// oauth application keys
private string oauth_consumer_key = string.Empty;
private string oauth_consumer_secret = string.Empty;
// oauth implementation details
private string resource_urlFormat = "https://api.twitter.com/1.1/followers/list.json?screen_name={0}&cursor={1}";
// unique request details
private string oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
protected void Page_Load(object sender, EventArgs e)
{
//just get your request parameters from the config file.
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[GetVariableName(() => screen_name)])) {
screen_name = ConfigurationManager.AppSettings[GetVariableName(() => screen_name)];
}
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[GetVariableName(() => oauth_consumer_key)]))
{
oauth_consumer_key = ConfigurationManager.AppSettings[GetVariableName(() => oauth_consumer_key)];
}
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[GetVariableName(() => oauth_consumer_secret)]))
{
oauth_consumer_secret = ConfigurationManager.AppSettings[GetVariableName(() => oauth_consumer_secret)];
}
StartCreateCall();
}
// Do the authenticate by an authorization request
private void StartCreateCall() {
// You need to set your own keys and screen name
var oAuthUrl = "https://api.twitter.com/oauth2/token";
// Do the Authenticate
var authHeaderFormat = "Basic {0}";
var authHeader = string.Format(authHeaderFormat,
Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oauth_consumer_key) + ":" +
Uri.EscapeDataString((oauth_consumer_secret)))
));
var postBody = "grant_type=client_credentials";
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (Stream stream = authRequest.GetRequestStream())
{
byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
stream.Write(content, 0, content.Length);
}
authRequest.Headers.Add("Accept-Encoding", "gzip");
WebResponse authResponse = authRequest.GetResponse();
// deserialize into an object
TwitAuthenticateResponse twitAuthResponse;
using (authResponse)
{
using (var reader = new StreamReader(authResponse.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objectText = reader.ReadToEnd();
twitAuthResponse = JsonConvert.DeserializeObject<TwitAuthenticateResponse>(objectText);
}
}
//now we have been granted access and got a token type with authorization token from Twitter
//in the form of a TwitAuthenticateResponse object, we can retrieve the data recursively with a cursor
CallData(twitAuthResponse, authHeader, cursor);
int totalFollowers = listFollowers.Count;
lblTotalFollowers.Text = screen_name + " has " + listFollowers.Count + " Followers";
Random objRnd = new Random();
List<TwiterFollowers> randomFollowers = listFollowers.OrderBy(item => objRnd.Next()).ToList<TwiterFollowers>();
foreach (TwiterFollowers tw in randomFollowers)
{
strTwiterFollowers = strTwiterFollowers + "<li><a target='_blank' title='" + tw.ScreenName + "' href=https://twitter.com/" + tw.ScreenName + "><img src='" + tw.ProfileImage + "'/><span>" + tw.ScreenName + "</span></a></li>";
}
}
//Retrieve the data from Twitter recursively with a cursor
private void CallData(TwitAuthenticateResponse twitAuthResponse, string authHeader, string cursor)
{
try {
JObject j = GetJSonObject(twitAuthResponse, authHeader, cursor);
JArray data = (JArray)j["users"];
if (data != null)
{
foreach (var item in data)
{
TwiterFollowers objTwiterFollowers = new TwiterFollowers();
objTwiterFollowers.ScreenName = item["screen_name"].ToString().Replace("\"", "");
objTwiterFollowers.ProfileImage = item["profile_image_url"].ToString().Replace("\"", "");
objTwiterFollowers.UserId = item["id"].ToString().Replace("\"", "");
listFollowers.Add(objTwiterFollowers);
}
JValue next_cursor = (JValue)j["next_cursor"];
if (long.Parse(next_cursor.Value.ToString()) > 0)
{
//Get the following data from Twitter with the next cursor
CallData(twitAuthResponse, authHeader, next_cursor.Value.ToString());
}
}
} catch (Exception ex)
{
//do nothing
}
}
private JObject GetJSonObject(TwitAuthenticateResponse twitAuthResponse, string authHeader, string cursor)
{
string resource_url = string.Format(resource_urlFormat, screen_name, cursor);
if (string.IsNullOrEmpty(cursor))
{
resource_url = resource_url.Substring(0, resource_url.IndexOf("&cursor"));
}
HttpWebRequest fRequest = (HttpWebRequest)WebRequest.Create(resource_url);
var timelineHeaderFormat = "{0} {1}";
fRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token));
fRequest.Method = "Get";
WebResponse response = fRequest.GetResponse();
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
return JObject.Parse(result);
}
private string GetVariableName<T>(Expression<Func<T>> expr)
{
var body = (MemberExpression)expr.Body;
return body.Member.Name;
}
private class TwitAuthenticateResponse
{
public string token_type { get; set; }
public string access_token { get; set; }
}
private class TwiterFollowers
{
public string ScreenName { get; set; }
public string ProfileImage { get; set; }
public string UserId { get; set; }
}
}
You are getting "401 Unauthorized"
Did you check you are setting everything right?
Credentials? Check both queries on fiddler.