Unable to send POST data of a form - c#

i have a problem with a Web Post Form.
I have download the page, I extrapolated the two required values (form_build_id and form_token), but once sent the POST the server does not receive anything in POST.
Excluded errors:
Wrong link (can download the page).
Incorrect extrapolated data (verified).
Wrong string myParameters (verified).
I have tested the Form manually and it work fine.
Some idea? There I slam my head for two days!
using (WebClientEx wc = new WebClientEx())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HTMLPage = wc.DownloadString(CREAT_TICKET_URL);
string form_build_id = SearchValue(HTMLPage, "<input type=\"hidden\" name=\"form_build_id\"", "value=\"", "\" />");
string form_token = SearchValue(HTMLPage, "<input type=\"hidden\" name=\"form_token\"", "value=\"", "\" />");
string myParameters = "macchina=" + cmacExtID + "&utente=" + custExtID + "&oggetto=" + Title + "&body=" + Note + "&op=Conferma&form_build_id=" + form_build_id + "&form_token=" + form_token + "&form_id=app_form_new_ticket";
string HtmlResult = wc.UploadString(CREAT_TICKET_URL, myParameters);
}
Note: WebClientEx class inherits WebClient. I used this approach to other forms such as login and work.
The final question is: if this approach is wrong, what is the best way to do this sequence of operations "download the page, extract the values from the HTML, send post form"?

The problem was the header!
The header should be set for each call, while I thought it was enough to set only the first time.
using (WebClientEx wc = new WebClientEx())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HTMLPage = wc.DownloadString(CREAT_TICKET_URL);
string form_build_id = SearchValue(HTMLPage, "<input type=\"hidden\" name=\"form_build_id\"", "value=\"", "\" />");
string form_token = SearchValue(HTMLPage, "<input type=\"hidden\" name=\"form_token\"", "value=\"", "\" />");
string myParameters = "macchina=" + cmacExtID + "&utente=" + custExtID + "&oggetto=" + Title + "&body=" + Note + "&op=Conferma&form_build_id=" + form_build_id + "&form_token=" + form_token + "&form_id=app_form_new_ticket";
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(CREAT_TICKET_URL, myParameters);
}

Related

Yahoo Weather API by Lat and Lon

I'm writing a weather app in Xamarin.Form. I am using the Yahoo API. I have no problem getting the weather by the city name parameter. However, when I change the code to use longitude and latitude, the weather does not appear.
To download the weather I use the example from the page: https://developer.yahoo.com/weather/documentation.html#oauth-csharp
I processed it in the following way:
lSign = string.Format(
"format={0}&" +
"lat={1}&" +
"lon={2}&" +
"oauth_consumer_key={3}&" +
"oauth_nonce={4}&" +
"oauth_signature_method={5}&" +
"oauth_timestamp={6}&" +
"oauth_version={7}&" +
"u={8}",
cFormat,
szerokosc,
dlugosc,
cConsumerKey,
lNonce,
cOAuthSignMethod,
lTimes,
cOAuthVersion,
jednostka.ToString().ToLower()
(...)
url = cURL + "?lat=" + szerokosc + "&lon=" + dlugosc + "&u=" + jednostka.ToString().ToLower() + "&format=" + cFormat;
According to the documentation, lSign is used for authentication. It should not be changed, remove these "lat={1}&" + "lon={2}&" from that strings.
It says Please don't simply change value of any parameter without
re-sorting.
The location information should be involved in the request url and the authorization information is added in the header.
// Add Authorization
lClt.Headers.Add ( "Authorization", _get_auth () );
// The request URL
lURL = cURL + "?" + "lat=" + szerokosc + "&lon=" + dlugosc + "&format=" + cFormat;
Unfortunately, the simple removal of " lat = {1} & " + " lon = {2} & " from variable lSign does not solve the problem.
For example, to get weather data by the city name I use:
lSign = string.Format(
"format={0}&" +
"location={1}&" +
"oauth_consumer_key={2}&" +
"oauth_nonce={3}&" +
"oauth_signature_method={4}&" +
"oauth_timestamp={5}&" +
"oauth_version={6}&" +
"u={7}",
cFormat,
miasto,
cConsumerKey,
lNonce,
cOAuthSignMethod,
lTimes,
cOAuthVersion,
jednostka.ToString().ToLower()
and
url = cURL + "?location=" + Uri.EscapeDataString(miasto) + "&u=" + jednostka.ToString().ToLower() + "&format=" + cFormat;
and
string headerString = _get_auth();
WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/" + cFormat;
webClient.Headers[HttpRequestHeader.Authorization] = headerString;
webClient.Headers.Add("X-Yahoo-App-Id", cAppID);
byte[] reponse = webClient.DownloadData(url);
string lOut = Encoding.ASCII.GetString(reponse);

Http Post request Without encoding parameters in C# Windows phone 8.1

I have made a post request with comma separated values. But my form contents changes and "," replace with "%2C". So request does not receive at server side.
I just want to replace "%2C" with ",".
I tried with different codes but that code are for string.
//Uri.EscapeDataString(formContent).Replace("%2C", ",");
Above line is for string but I need same for FormContent.
Here is my Code.
Windows.Web.Http.HttpClient clientOb = new Windows.Web.Http.HttpClient();
Uri connectionUrl = new Uri("http://www.helloworld.com/istar/fileupload/Lip?");
string framURL = UTCdatetime + "," + lng + "," + lat + "," + speed + alt + "," + "," + battery_level + "," + accuracy;
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("name", Image_file_name);
pairs.Add("frame", framURL);
//Here is My Content Form.
Windows.Web.Http.HttpFormUrlEncodedContent formContent = new Windows.Web.Http.HttpFormUrlEncodedContent(pairs);
I'm getting FormContent encoded. like
{name=WP_20160224_002.jpg&frame=927858b101b71083f37549517819d6ac%2C20160225125928%2C%2C%2C%2C%2C%2C%2C100%2C%2C2%2C%2C%2C0}
I need to send request with Comma's so I want to remove "%2C". Please help out in this problem.
I Required above contentform like this...
{name=WP_20160224_002.jpg&frame=927858b101b71083f37549517819d6ac,20160225092908,74.253794,31.471193,-1,-1,0,,100,103,2,-1,0}
Here I send post request.
Windows.Web.Http.HttpResponseMessage response = await clientOb.PostAsync(connectionUrl, formContent);
You're confusing form encoding with URL encoding. Given your example, there's little need to encode this query string. Forms and query strings have a similar key=value syntax, but there are differences in format.
You're right to use the Uri class - but you can wait until the very end to construct it from a string, as this will ensure the given string is fully sanitized - see the remarks section of MSDN documentation of Uri class.
Here's an untested example:
string framURL = UTCdatetime + "," + lng + "," + lat + "," + speed + alt + "," + "," + battery_level + "," + accuracy;
Dictionary<string, string> pairs = new Dictionary<string, string>();
pairs.Add("name", Image_file_name);
pairs.Add("frame", framURL);
var queryString = String.Join("&", pairs.Select(kvp => kvp.Key + "=" + kvp.Value));
Uri connectionUrl = new Uri("http://www.helloworld.com/istar/fileupload/Lip?" + queryString);
Let me know how you get on!

Filling PDF with multiple ASP.NET webforms using iTextSharp

I'm currently building a small website that takes data from 6 different web forms written in ASP.NET and C#. I need all of the information to be written to a PDF at the end of Page 6. I currently have all fields mapped, but each time the page changes, the information gets wiped. i have the information set to pass the values using a query string, but it seems to keep getting lost. Any advice?
EDIT
Sorry for not posting the code the first time, this is my first question i ever posted here. Also, I know my code isn't very efficient, I'm more or less trying to get the grasp of iTextSharp and WebForms. Thanks
Page 1
AcroFields af = ps.AcroFields;
af.SetField("Name", name.Text);
af.SetField("Email", email.Text);
af.SetField("state", state.Text);
af.SetField("city", city.Text);
af.SetField("Address", address.Text);
af.SetField("Phone", phone.Text);
af.SetField("zip", zip.Text);
Response.Redirect("Default.aspx?name=" + this.name.Text + "&Email=" + this.email.Text
+ "&state=" + this.state.Text + "&city=" + this.city.Text + "&Address=" + this.address.Text +
"&Phone=" + this.phone.Text + "&zip=" + this.zip.Text);
Response.Redirect("Page2.aspx");
Page 2
AcroFields af = ps.AcroFields;
af.SetField("Degree", degree.Text);
af.SetField("Grad", gradDate.Text);
af.SetField("Obj", objective.Text);
Response.Redirect("Default.aspx?Degree=" + this.degree.Text + "&Grad=" + this.gradDate.Text
+ "&Obj=" + this.objective.Text);
Response.Redirect("Page3.aspx");
//ps.FormFlattening = true;
Page 3
AcroFields af = ps.AcroFields;
af.SetField("jobStart1", jobStart1.Text);
af.SetField("jobEnd1", jobEnd1.Text);
af.SetField("jobTitle1", jobTitle1.Text);
af.SetField("coName1", coName1.Text);
af.SetField("coAdd1", coAdd1.Text);
af.SetField("Details1", details1.Text);
Response.Redirect("Default.aspx?jobStart1" + this.jobStart1.Text + "&jobEnd1=" + this.jobEnd1.Text
+ "&jobTitle1=" + this.jobTitle1.Text + "&coName1=" + this.coName1.Text + "&coAdd1=" + this.coAdd1.Text +
"&Details1=" + this.details1.Text);
Response.Redirect("Page4.aspx");
Page 4
AcroFields af = ps.AcroFields;
af.SetField("jobStart2", jobStart2.Text);
af.SetField("jobEnd2", jobEnd2.Text);
af.SetField("jobTitle2", jobTitle2.Text);
af.SetField("coName2", coName2.Text);
af.SetField("coAdd2", coAdd2.Text);
af.SetField("Details2", details2.Text);
Response.Redirect("Default.aspx?jobStart2" + this.jobStart2.Text + "&jobEnd2=" + this.jobEnd2.Text
+ "&jobTitle2=" + this.jobTitle2.Text + "&coName2=" + this.coName2.Text + "&coAdd2=" + this.coAdd2.Text +
"&Details2=" + this.details2.Text);
Response.Redirect("Page5.aspx");
Page 5
AcroFields af = ps.AcroFields;
af.SetField("jobStart3", jobStart3.Text);
af.SetField("jobEnd3", jobEnd3.Text);
af.SetField("jobTitle3", jobTitle3.Text);
af.SetField("coName3", coName3.Text);
af.SetField("coAdd3", coAdd3.Text);
af.SetField("Details3", details3.Text);
Response.Redirect("Default.aspx?jobStart3" + this.jobStart3.Text + "&jobEnd3=" + this.jobEnd3.Text
+ "&jobTitle3=" + this.jobTitle3.Text + "&coName3=" + this.coName3.Text + "&coAdd3=" + this.coAdd3.Text +
"&Details3=" + this.details3.Text);
Response.Redirect("Page6.aspx");
Page 6
string name = Request.QueryString["Name"];
string address = Request.QueryString["Address"];
string phone = Request.QueryString["Phone"];
string email = Request.QueryString["Email"];
string city = Request.QueryString["city"];
string state = Request.QueryString["state"];
string zip = Request.QueryString["zip"];
string degree = Request.QueryString["Degree"];
string gradDate = Request.QueryString["Grad"];
string objective = Request.QueryString["Obj"];
string jobStart1 = Request.QueryString["jobStart1"];
string jobEnd1 = Request.QueryString["jobEnd1"];
string jobTitle1 = Request.QueryString["jobTitle1"];
string coName1 = Request.QueryString["coName1"];
string coAdd1 = Request.QueryString["coAdd1"];
string details1 = Request.QueryString["Details1"];
string jobStart2 = Request.QueryString["jobStart2"];
string jobEnd2 = Request.QueryString["jobEnd2"];
string jobTitle2 = Request.QueryString["jobTitle2"];
string coName2 = Request.QueryString["coName2"];
string coAdd2 = Request.QueryString["coAdd2"];
string details2 = Request.QueryString["Details2"];
string jobStart3 = Request.QueryString["jobStart3"];
string jobEnd3 = Request.QueryString["jobEnd3"];
string jobTitle3 = Request.QueryString["jobTitle3"];
string coName3 = Request.QueryString["coName3"];
string coAdd3 = Request.QueryString["coAdd3"];
string details3 = Request.QueryString["Details3"];
AcroFields af = ps.AcroFields;
af.SetField("Name", name);
af.SetField("Email", email);
af.SetField("state", state);
af.SetField("city", city);
af.SetField("Address", address);
af.SetField("Phone", phone);
af.SetField("zip", zip);
af.SetField("Degree", degree);
af.SetField("Grad", gradDate);
af.SetField("Obj", objective);
af.SetField("jobStart1", jobStart1);
af.SetField("jobEnd1", jobEnd1);
af.SetField("jobTitle1", jobTitle1);
af.SetField("coName1", coName1);
af.SetField("coAdd1", coAdd1);
af.SetField("Details1", details1);
af.SetField("jobStart2", jobStart2);
af.SetField("jobEnd2", jobEnd2);
af.SetField("jobTitle2", jobTitle2);
af.SetField("coName2", coName2);
af.SetField("coAdd2", coAdd2);
af.SetField("Details2", details2);
af.SetField("jobStart3", jobStart3);
af.SetField("jobEnd3", jobEnd3);
af.SetField("jobTitle3", jobTitle3);
af.SetField("coName3", coName3);
af.SetField("coAdd3", coAdd3);
af.SetField("Details3", details3);
af.SetField("Skills", skills.Text);
ps.FormFlattening = true;
}
Response.End();
Response.Redirect("Default.aspx?name=" + this.name.Text + "&Email=" + this.email.Text
+ "&state=" + this.state.Text + "&city=" + this.city.Text + "&Address=" + this.address.Text +
"&Phone=" + this.phone.Text + "&zip=" + this.zip.Text);
Response.Redirect("Page2.aspx"); //this will never be reached because the line before it ends the current execution context
You're redirecting back to Default.aspx, but judging by your question the intention is to go to Page2.aspx. But Response.Redirect("Page2.aspx"); is never reached because the response ends after the first redirect. When you call response redirect (the standard overload) the current request context ends, the client is sent an HTTP redirect. So no further code will be executed.
Instead, replace both of those lines with this one:
Response.Redirect("Page2.aspx?name=" + this.name.Text + "&Email=" + this.email.Text
+ "&state=" + this.state.Text + "&city=" + this.city.Text + "&Address=" + this.address.Text +
"&Phone=" + this.phone.Text + "&zip=" + this.zip.Text);
Then on Page 2, you'll need code in Page_Load to pull the values out of the request query string, and additional code so that when you leave the page you pass the values from page 1 and the new values from page 2. And so on.
You should UriEncode your values before putting them in the query string. And concatenating a bunch of strings is really ugly. Perhaps a format string would be appropriate here.
Also, if I were you, I'd abandon the query string approach entirely. That's really messy, passing them around like that because after several pages, you're going to have a ton of parameters and it's going to be a messy URL and a lot of boilerplate code. And neither of those is good. Instead, you should create a Model to represent all the information you want to gather, then store the model somewhere such as Session to pass it between pages. On the function where you build your PDF, have it accept the model as a parameter and generate the PDF according to the values in your model.
The model is simply a C# class that represents the values your PDF needs. For example, here's a starting point:
public class ApplicantInformationModel
{
public string Name {get; set;}
public string Email {get; set;}
public List<Job> Jobs {get; set;}
public string PhoneNumber {get; set;}
}
public class Job
{
public DateTime StartDate {get; set;}
public DateTime EndDate {get; set;}
public string Title {get; set;}
public string Company {get; set;}
}
Your PDF creation function will accept this:
public static Document GeneratePdfForApplicant(ApplicantInformationModel model)
{
//use iTextSharp to generate and return PDF based on the model
}

Code for Google Analytic product hit in c#

I'm new in google analytic. I go through some regarding this. I found that there is no direct method to hit a windows application in google analytic. But i found some solutions in stackoverflow. I tried that, but didn't work for me. Below is the code that I'm using.
private void analyticsmethod4(string trackingId, string pagename)
{
Random rnd = new Random();
long timestampFirstRun, timestampLastRun, timestampCurrentRun, numberOfRuns;
// Get the first run time
timestampFirstRun = DateTime.Now.Ticks;
timestampLastRun = DateTime.Now.Ticks - 5;
timestampCurrentRun = 45;
numberOfRuns = 2;
// Some values we need
string domainHash = "123456789"; // This can be calcualted for your domain online
int uniqueVisitorId = rnd.Next(100000000, 999999999); // Random
string source = "Shop";
string medium = "medium123";
string sessionNumber = "1";
string campaignNumber = "1";
string culture = Thread.CurrentThread.CurrentCulture.Name;
string screenRes = Screen.PrimaryScreen.Bounds.Width + "x" + Screen.PrimaryScreen.Bounds.Height;
string statsRequest = "http://www.google-analytics.com/__utm.gif" +
"?utmwv=4.6.5" +
"&utmn=" + rnd.Next(100000000, 999999999) +
// "&utmhn=hostname.mydomain.com" +
"&utmcs=-" +
"&utmsr=" + screenRes +
"&utmsc=-" +
"&utmul=" + culture +
"&utmje=-" +
"&utmfl=-" +
"&utmdt=" + pagename + // Here i passed my profile name "MyWindowsApp"
"&utmhid=1943799692" +
"&utmr=0" +
"&utmp=" + pagename +
"&utmac=" + trackingId + //Tracking id : ie "UA-XXXXXXXX-X"
"&utmcc=" +
"__utma%3D" + domainHash + "." + uniqueVisitorId + "." + timestampFirstRun + "." + timestampLastRun + "." + timestampCurrentRun + "." + numberOfRuns +
"%3B%2B__utmz%3D" + domainHash + "." + timestampCurrentRun + "." + sessionNumber + "." + campaignNumber + ".utmcsr%3D" + source + "%7Cutmccn%3D(" + medium + ")%7Cutmcmd%3D" + medium + "%7Cutmcct%3D%2Fd31AaOM%3B";
try
{
using (var client = new WebClient())
{
//byte[] bt = client.DownloadData(statsRequest);
Stream data = client.OpenRead(statsRequest);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
MessageBox.Show(s);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This example is also got from this site itself. I don't know where was the problem. Please direct me, how can i make it. This is the output i'm getting "GIF89a".
Thanks
Bobbin Paulose
So it's working. The Google Analytics call loads a tiny GIF image, and the querystring parameters provided in the request trigger all the Google Analytics goodness. If you're getting a response back, you have registered your event successfully with Google.

how to open vCard bydefault in outlook 2007/03?

I have generated the the vCard from asp.net + c# application. While ending up. browsers pops up for "open with /Save as" box. I don't want to appear this box. rather than that , I want to directly set the generated .vcf file to open with outlook 2007 or 03. what hae to do ?
My code is:
S
ystem.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
//vCard Begin
stringWrite.WriteLine("BEGIN:VCARD");
stringWrite.WriteLine("VERSION:2.1");
//Name
stringWrite.WriteLine("N:" + nameLast + ";" + nameFirst +
";" + nameMiddle + ";" + nameTitle);
//Full Name
stringWrite.WriteLine("FN:" + nameFirst + " " +
nameMiddle + " " + nameLast);
//Organisation
stringWrite.WriteLine("ORG:" + company + ";" + department);
//URL
stringWrite.WriteLine("URL;WORK:" + uRL);
//Title
stringWrite.WriteLine("TITLE:" + title);
//Profession
stringWrite.WriteLine("ROLE:" + profession);
//Telephone
stringWrite.WriteLine("TEL;WORK;VOICE:" + telephone);
//Fax
stringWrite.WriteLine("TEL;WORK;FAX:" + fax);
//Mobile
stringWrite.WriteLine("TEL;CELL;VOICE:" + mobile);
//Email
stringWrite.WriteLine("EMAIL;PREF;INTERNET:" + email);
//Address
stringWrite.WriteLine("ADR;WORK;ENCODING=QUOTED-PRINTABLE:" + ";" +
office + ";" + addressTitle + "=0D" +
streetName + ";" + city + ";" +
region +
";" + postCode + ";" + country);
//Revision Date
//Not needed
//stringWrite.WriteLine("REV:" + DateTime.Today.Year.ToString() +
// DateTime.Today.Month.ToString() + DateTime.Today.Day.ToString() + "T" +
// DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +
// DateTime.Now.Second.ToString() + "Z");
//vCard End
stringWrite.WriteLine("END:VCARD");
response.Write(stringWrite.ToString());
response.AppendHeader("Hi", "PMTS");
response.End();
If I'm understanding you correctly, the issue is that you're getting a run-or-download dialog when you mean for the vCard to simply open from the web.
Assuming that is actually what you're wanting, I believe you need only to set your response to one of the vCard MIME types (text/x-vcard, text/directory;profile=vCard, or text/directory).
Response.ContentType = "text/x-vcard";
I hope that helps.
- EDIT -
Using the following code, I am properly prompted to Open or Save (and Open opens the file in Outlook) in Internet Exploder. Unfortunately, Chrome still does not support opening files it seems, and so there is a download box somewhat permanently it seems. Try the following code out in IE and you'll see what I mean; it works. Also, on a side note - I would have been able to replicate your code somewhat easier if properly formatted. Any chance you can edit your post, highlight the code, and hit the "101010" icon? Thanks much, and good luck!
using System;
using System.IO;
using System.Web.UI;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
private string nameLast = "May";
private string nameFirst = "Lance";
private string nameMiddle = "R.";
private string nameTitle = "Mr.";
private string company = "CoreLogic";
private string department = "Development";
private string uRL = "http://www.lancemay.com";
private string title = "Application Developer Senior";
private string profession = "Developer";
private string telephone = "(123) 555-1212";
private string fax = "(321) 555-1212";
private string mobile = "(555) 555-1212";
private string email = "lancemay#gmail.com";
private string office = "Louisville";
private string addressTitle = "";
private string streetName = "123 Easy St.";
private string city = "Louisville";
private string region = "KY";
private string postCode = "40223";
private string country = "US";
protected void Page_Load(object sender, EventArgs e)
{
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
//vCard Begin
stringWrite.WriteLine("BEGIN:VCARD");
stringWrite.WriteLine("VERSION:2.1");
//Name
stringWrite.WriteLine("N:" + nameLast + ";" + nameFirst + ";" + nameMiddle + ";" + nameTitle);
//Full Name
stringWrite.WriteLine("FN:" + nameFirst + " " + nameMiddle + " " + nameLast);
//Organisation
stringWrite.WriteLine("ORG:" + company + ";" + department);
//URL
stringWrite.WriteLine("URL;WORK:" + uRL);
//Title
stringWrite.WriteLine("TITLE:" + title);
//Profession
stringWrite.WriteLine("ROLE:" + profession);
//Telephone
stringWrite.WriteLine("TEL;WORK;VOICE:" + telephone);
//Fax
stringWrite.WriteLine("TEL;WORK;FAX:" + fax);
//Mobile
stringWrite.WriteLine("TEL;CELL;VOICE:" + mobile);
//Email
stringWrite.WriteLine("EMAIL;PREF;INTERNET:" + email);
//Address
stringWrite.WriteLine("ADR;WORK;ENCODING=QUOTED-PRINTABLE:" + ";" + office + ";" + addressTitle + "=0D" + streetName + ";" + city + ";" + region + ";" + postCode + ";" + country);
stringWrite.WriteLine("END:VCARD");
Response.ContentType = "text/x-vcard";
Response.Write(stringWrite.ToString());
Response.AppendHeader("Hi", "PMTS");
Response.End();
}
}
}

Categories

Resources