How i fix this error? [closed] - asp.net

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have error in
plz help to convert json to rcpts.
string json = JsonConvert.SerializeObject(rcpts);
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace sdd.Contact
{
public partial class Cantact : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SabtButton_Click(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create("http://ippanel.com/services.jspd");
string[] rcpts = new string[] { "981111111" };
string json = JsonConvert.SerializeObject(rcpts);
request.Method = "POST";
string postData = "op=send&uname=aaaa&pass=0000&message=hello Test&to=" + json + "&from=+9810001010";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
System.Diagnostics.Debug.WriteLine(responseFromServer);
}
}
}

You can try Parse or DeserializeObject for this:
JObject json = JObject.Parse(rcpts);
Or
dynamic json = JsonConvert.DeserializeObject(rcpts);

Related

How can I redirect to other page once download is complete?

Following is my code to convert HTML into PDF, what I am trying to implement is as soon as pdf is downloaded I want the page to be redirected to another page: SendEmail.aspx through which I will email the downloaded pdf, Is there any way to do that ?
I tried using Response.Redirect("SendEmail.aspx"); and also removing Response.End but any one of them is working, either it redirects or it downloads pdf, Is there a way I can do both??
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.Text;
namespace HTMLtoPDF
{
public partial class HTMLtoPDF : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnClick_Click(object sender, EventArgs e)
{
DownloadAsPDF();
}
public void DownloadAsPDF()
{
try
{
string strHtml = string.Empty;
string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "CASEID2.pdf";
//string testPath = Server.MapPath("~/files/test.pdf");
string template = File.ReadAllText(Server.MapPath("~/Incomplete-Pdf-temp.html"));
string case_id = "12345";
string student_id = "";
string student_name_input = "";
string campus_input = "Falls Church";
string email_input = "xyz#gmail.com";
string phone_input = "";
string term = "2";
string address_input = "";
string course_input = "Mobile Application Development";
string reason_appeal = "Family Problems";
string faculty_name = "XYZ";
string remaining_work = "Task-1,Task-2,Task-3";
string deadline_date = "May 1st";
template = template.Replace("[CASEID]", case_id);
template = template.Replace("[STUDENTID]", student_id);
template = template.Replace("[STUDENTNAME]", student_name_input);
template = template.Replace("[CAMPUS]", campus_input);
template = template.Replace("[EMAIL]", email_input);
template = template.Replace("[PHONE]", phone_input);
template = template.Replace("[TERM]", term);
template = template.Replace("[ADDRESS]", address_input);
template = template.Replace("[COURSEID] [COURSENAME]", course_input);
template = template.Replace("[REASON]", reason_appeal);
template = template.Replace("[FACULTYNAME]", faculty_name);
template = template.Replace("[REMAININGCOURSEWORK]", remaining_work);
template = template.Replace("[DEADLINE]",deadline_date);
//template.Replace("[DEADLINE]", Request[deadline_date]);
//StringWriter sw = new StringWriter();
//HtmlTextWriter hw = new HtmlTextWriter(sw);
//dvHtml.RenderControl(hw);
//StringReader sr = new StringReader(sw.ToString());
//strHtml = sr.ReadToEnd();
//sr.Close();
//string temp2 = template.Replace("<!DOCTYPE html>\r\n<html>\r\n<head>\r\n <title></title>\r\n\t<meta charset=\"utf-8\" />\r\n</head>\r\n<body>\r\n", "");
CreatePDFFromHTMLFile(template, pdfFileName);
Response.ContentType = "application/x-download";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", "CASEID2.pdf"));
Response.AddHeader("Refresh", "2;URL=SendEmail.aspx");
Response.WriteFile(pdfFileName);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
public void CreatePDFFromHTMLFile(string HtmlStream, string FileName)
{
try
{
object TargetFile = FileName;
string ModifiedFileName = string.Empty;
string FinalFileName = string.Empty;
GeneratePDF.HtmlToPdfBuilder builder = new GeneratePDF.HtmlToPdfBuilder(iTextSharp.text.PageSize.A4);
GeneratePDF.HtmlPdfPage first = builder.AddPage();
first.AppendHtml(HtmlStream);
byte[] file = builder.RenderPdf();
File.WriteAllBytes(TargetFile.ToString(), file);
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(TargetFile.ToString());
ModifiedFileName = TargetFile.ToString();
ModifiedFileName = ModifiedFileName.Insert(ModifiedFileName.Length - 4, "1");
iTextSharp.text.pdf.PdfEncryptor.Encrypt(reader, new FileStream(ModifiedFileName, FileMode.Append), iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, "", "", iTextSharp.text.pdf.PdfWriter.AllowPrinting);
reader.Close();
if (File.Exists(TargetFile.ToString()))
File.Delete(TargetFile.ToString());
FinalFileName = ModifiedFileName.Remove(ModifiedFileName.Length - 5, 1);
File.Copy(ModifiedFileName, FinalFileName);
if (File.Exists(ModifiedFileName))
File.Delete(ModifiedFileName);
}
catch (Exception ex)
{
throw ex;
}
}
}
}

paypal ipn integration in asp.net application

Iam trying to integrate paypal ipn in my application,but Iam getting error like "An exception of type 'System.Net.WebException' occurred in System.dll" but was not handled in user code in streamwriter.I have tried the below code.Please suggest.
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
public partial class ipn : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Post back to either sandbox or live
string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
strRequest += "&cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
if (strResponse == "VERIFIED")
{
//check the payment_status is Completed
//check that txn_id has not been previously processed
//check that receiver_email is your Primary PayPal email
//check that payment_amount/payment_currency are correct
//process payment
}
else if (strResponse == "INVALID")
{
//log for manual investigation
}
else
{
//log response/ipn data for manual investigation
}
}
}
string Identity_Token = "zkiMk_t - XXXXXagbIDrzPAChXuWIYVS66TXXXXXXXXXXXXXXXXXXXXXXXXXX";//From you paypal account
string txToken = Request.QueryString["tx"];
string query = string.Format("cmd=_notify-synch&tx={0}&at={1}", txToken, Identity_Token);
string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
strRequest += query;
req.ContentLength = strRequest.Length;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
// If response was SUCCESS, parse response string and output details
if (strResponse.StartsWith("SUCCESS"))
{
Label1.Text = "OK";
}
else
{
Label1.Text = "NO";
}
}
}

Pushwoosh Remote API DOT NET Example

My Phonegap application can receive notifications from pushwoosh panel. I want to integrate it in my DOT NET Application with help of remote api.
You can find example at http://docs.pushwoosh.com/docs/createmessage
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string pwAuth = "YOUR_AUTH_TOKEN";
string pwApplication = "PW_APPLICATION_CODE";
JObject json = new JObject(
new JProperty("application", pwApplication),
new JProperty("auth", pwAuth),
new JProperty("notifications",
new JArray(
new JObject(
new JProperty("send_date", "now"),
new JProperty("content", "test"),
new JProperty("wp_type", "Toast"),
new JProperty("wp_count", 3),
new JProperty("data",
new JObject(
new JProperty("custom", "json data"))),
new JProperty("link", "http://pushwoosh.com/"),
new JProperty("conditions",
new JArray(
(object)new JArray("Color", "EQ", "black")))))));
PWCall("createMessage", json);
}
private void PWCall(string action, JObject data)
{
Uri url = new Uri("https://cp.pushwoosh.com/json/1.3/" + action);
JObject json = new JObject(new JProperty("request", data));
DoPostRequest(url, json);
}
private void DoPostRequest(Uri url, JObject data)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.ContentType = "text/json";
req.Method = "POST";
using (var streamWriter = new StreamWriter(req.GetRequestStream()))
{
streamWriter.Write(data.ToString());
}
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)req.GetResponse();
}
catch (Exception exc)
{
throw new Exception(string.Format("Problem with {0}, {1}", url, exc.Message));
}
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Page.Response.Write(responseText);
}
}
}
}

getting directed to ASP.NET home page on browser

I am trying to run the following HTTP POST API Call using ASP.NET on Visual studio 2013. I created a new web application project as mentioned here
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreateNewAPICall("test api abc");
}
private object CreateNewAPICall(string apiDesc)
{
object result = null;
var accessKey = "myaccesskey";
var secretKey = "mysecretkey";
var uRLapiList = "http://myurl.com";
byte[] bytes = Encoding.UTF8.GetBytes("apiListDesc=" + apiDesc);
var method = "POST";
var timeString = DateTime.UtcNow.GetDateTimeFormats()[104];
var signature = GetSignature(secretKey, method, timeString);
var authorization = accessKey + ":" + signature;
HttpWebRequest request = CreateWebRequest(uRLapiList, "POST", bytes.Length, timeString, authorization);
using (var requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
var responseReader = new StreamReader(request.GetResponse().GetResponseStream());
// Return List api Data
result = responseReader.ReadToEnd();
}
}
return result;
}
private HttpWebRequest CreateWebRequest(string endPoint, string method, Int32 contentLength, string timeString, string authorization)
{
// Some code here
}
private string GetSignature(string secretKey, string method, string timeString)
{
// Some code here
}
private byte[] HMAC_SHA1(string signKey, string signMessage)
{
// Some code here
}
private string CreateSignature(string stringIn, string scretKey)
{
// Some code here
}
}
Right now, I am confused as to where to put this file in the "Solution Explorer" in order to
run the file and get the output on my browser?
Right now I have this code inside "Models-->Class1.cs" directory as shown in the image below:
So, when I press F-5 key, I am getting directed to the home page of the ASP.NET with the URL http://localhost:4439/
Do I need to make any changes here?

How to get data from API on POST method

I have to accesss an get some data from one of API.This API has only mentoned this method.No documentation showing how to acess and all.Data will be returned as Json.
This is the product API
1. GetAllProducts
POST
http://api.domain.com/api/Products/All
Content-Type: application/json; charset=utf-8
{"Token":"EncryptedToken"}
I have generated the Token and I tried to access it like this.But nothing is recieving.I found an example and tried to do like this.May be this is wrong.Can any one show me how to access and get the data.Please see my code below and thanks in advanced.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Web.Script;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Text;
public partial class Products : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All?Token=U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_");
request.Method = "POST";
string postData = "Data to post here";
byte[] post = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = post.Length;
Stream reqdataStream = request.GetRequestStream();
reqdataStream.Write(post, 0, post.Length);
reqdataStream.Close();
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (Exception ex)
{
Response.Write("Error Occured.");
}
}
}
I think you should change these things:
content type
request.ContentType = "application/json";
the post data
string postData = "{\"Token\":\"U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_\"}";
the URI
WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All");

Resources