I a trying to web scraping from http://hydro.imd.gov.in/hydrometweb/(S(e4xftrnoogdzzz55q2l23i55))/Argaws.aspx. I am novice web-scraper in web pages with ViewState-generator and event validation. So far I have tried with the following code and it is returning the same page instead of redirecting to new page. Any help regarding it will be highly appreciated.
string link = "http://hydro.imd.gov.in/hydrometweb/(S(e4xftrnoogdzzz55q2l23i55))/Argaws.aspx";
WebClient client = new WebClient();
string intiHtml = client.DownloadString(link);
string viewStateNameDelimiter = "__VIEWSTATE";
string valueDelimiter = "value=\"";
int viewStateNamePosition = intiHtml.IndexOf(viewStateNameDelimiter);
int viewStateValuePosition = intiHtml.IndexOf(valueDelimiter, viewStateNamePosition);
int viewStateStartPosition = viewStateValuePosition + valueDelimiter.Length;
int viewStateEndPosition = intiHtml.IndexOf("\"", viewStateStartPosition);
string viewstatePos = intiHtml.Substring(viewStateStartPosition, viewStateEndPosition - viewStateStartPosition);
Console.WriteLine(viewstatePos);
Console.ReadKey();
string eventValidationNameDelimiter = "__EVENTVALIDATION";
int eventValidationNamePosition = intiHtml.IndexOf(eventValidationNameDelimiter);
int eventValidationValuePosition = intiHtml.IndexOf(valueDelimiter, eventValidationNamePosition);
int eventValidationStartPosition = eventValidationValuePosition + valueDelimiter.Length;
int eventValidationEndPosition = intiHtml.IndexOf("\"", eventValidationStartPosition);
string eventvalidate = intiHtml.Substring(eventValidationStartPosition, eventValidationEndPosition - eventValidationStartPosition);
Console.WriteLine(eventvalidate);
Console.ReadKey();
string viewgeneratorNameDelimiter = "__VIEWSTATEGENERATOR";
int viewgeneratorNamePosition = intiHtml.IndexOf(viewgeneratorNameDelimiter);
int viewgeneratorValuePosition = intiHtml.IndexOf(valueDelimiter, viewgeneratorNamePosition);
int viewgeneratorStartPosition = viewgeneratorValuePosition + valueDelimiter.Length;
int viewgeneratorEndPosition = intiHtml.IndexOf("\"", viewgeneratorStartPosition);
string viewgenerator = intiHtml.Substring(viewgeneratorStartPosition, viewgeneratorEndPosition - viewgeneratorStartPosition);
Console.WriteLine(viewgenerator);
Console.ReadKey();
string postData = viewStateNameDelimiter + "=" + viewstatePos + "&" + viewgeneratorNameDelimiter + "=" + viewgenerator + "&" + eventValidationNameDelimiter + "=" + eventvalidate + "&DropDownList2=17-01-2018&DropDownList1=07&GoBtn=Go";
Console.WriteLine(postData);
WebRequest req = WebRequest.Create(link);
//string postData = "";
//postData = "";
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
Console.Write(returnvalue);
Console.ReadKey();
Related
I am trying to create credit card payment page.
I am posting the form in code behind (C#) and successfully get the verification sms from bank.
But it does not redirect to bank sms verification page so there is no where to enter verification code.
So what should i do?
Here is my code under the Pay button:
String shopCode = "SHOPCODE";
String purchaseAmount = "ORDER PRICE";
String currency = "CURRENCY";
String orderId = "ORDERID";
String okUrl = "REDIRECT PAGE AFTER SMS VERIFICATION COMPLETED SUCCESSFULLY";
String failUrl = "REDIRECT PAGE IF SMS VERIFICATION FAILS";
String rnd = DateTime.Now.ToString();
String installmentCount = "3";
String txnType = "txnType";
String merchantPass = "merchantpass";
String str = shopCode + orderId + purchaseAmount + okUrl + failUrl + txnType + installmentCount + rnd + merchantPass;
System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] bytes = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(str);
byte[] hashingbytes = sha.ComputeHash(bytes);
String hash = Convert.ToBase64String(hashingbytes);
String cardnumber = "CREDIT CARD NUMBER";
String expiry = "EXPIRY DATE";
String CVCCVV = "CVCNUMBER";
String securetype = "3DPay";
String lang = "language";
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "Pan=" + cardnumber;
postData += ("&Expiry=" + expiry);
postData += ("&Cvv2=" + CVCCVV);
postData += ("&ShopCode=" + shopCode);
postData += ("&PurchAmount=" + purchaseAmount);
postData += ("&Currency=" + currency);
postData += ("&OrderId=" + orderId);
postData += ("&OkUrl=" + okUrl);
postData += ("&FailUrl=" + failUrl);
postData += ("&Rnd=" + rnd);
postData += ("&Hash=" + hash);
postData += ("&TxnType=" + txnType);
postData += ("&InstallmentCount=" + installmentCount);
postData += ("&SecureType=" + securetype);
postData += ("&Lang=" + lang);
byte[] data = encoding.GetBytes(postData);
HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create("POSURL");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
EDIT:
It works fine if i do it in client (html) side, but i want to do it in server side.
we need json information from the bank
try
{
HttpClient clients = new HttpClient();
clients.Timeout = TimeSpan.FromSeconds(2);
HttpResponseMessage _response = await clients.GetAsync("banksmspage");
_response.EnsureSuccessStatusCode();
string responseBody = await _response.Content.ReadAsStringAsync();
dynamic json = JObject.Parse(responseBody);
string smscode = json.jsontitle.smscode;
if (smscode != null)
{
if (smscode == UsersmsEnterString)
{
Response.Redirect("BankpageURL");
}
else
{
Response.Redirect("ErrorURL");
}
}
}
catch {}
I'm trying to figure out how to post a new task to a user in asana, but I keep getting the 400 error code. Can anyone tell me what I am doing wrong.
This is what I have so far:
string apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string ID = "xxxxxxxxxxxxx";
string url = #"https://app.asana.com/api/1.0/tasks";
Data dat = new Data();
dat.workspace = ID;
dat.name = "Buy eggs";
dat.notes = "Testing";
string json = JsonConvert.SerializeObject(dat);
string data ="\"data\": " + json;
byte[] bytes = Encoding.UTF8.GetBytes(data);
var req = (HttpWebRequest)WebRequest.Create(url);
Console.WriteLine(bytes.ToString());
req.Method = WebRequestMethods.Http.Post;
req.ContentLength = bytes.Length;
req.ContentType = "application/json";
var authInfo = apiKey + ":";
var encodedAuthInfo = Convert.ToBase64String(
Encoding.Default.GetBytes(authInfo));
req.Headers.Add("Authorization", "Basic " + encodedAuthInfo);
req.ContentLength = bytes.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
try
{
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string res = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(res);
Console.ReadLine();
}
catch (WebException ex)
{
HttpWebResponse response = ((HttpWebResponse)ex.Response);
string e = url + " caused a " + (int)response.StatusCode + " error.\n" + response.StatusDescription;
Console.WriteLine(e);
Console.ReadLine();
}
I put the serial converter, did i do it wrong?
As the first comment points out, you need to serialize the data properly. The final body posted should look something like:
{ "data": { "name": "My Example Task", ... }}
(Except of course with the ... replaced with more fields.)
I have researched a long and found below code useful and working. I can successfully post Task to Asana through my application. I have used Json serializer for dot net. Thanks to Newtonsoft.Json.
string json = null;
byte[] bytes = null;
string url = "https://app.asana.com/api/1.0/tasks";
HttpWebRequest req = default(HttpWebRequest);
Stream reqStream = default(Stream);
string authInfo = null;
Task TaskData = new Task();
try
{
authInfo = apiKey + Convert.ToString(":");
TaskData.workspace = WorkspaceId;
TaskData.name = TaskName;
TaskData.notes = TaskNotes;
json = JsonConvert.SerializeObject(TaskData);
json = json.Insert((json.Length - 1), ",\"projects\":[" + ProjectId + "]");
json = Convert.ToString("{ \"data\":") + json + "}";
bytes = Encoding.UTF8.GetBytes(json);
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = WebRequestMethods.Http.Post;
req.ContentType = "application/json";
req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)));
req.ContentLength = bytes.Length;
reqStream = req.GetRequestStream();
reqStream.Write(bytes, 0, bytes.Length);
reqStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
string res = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.WriteLine(res);
Console.ReadLine();
string finalString = res.Remove(0, 8);
finalString = finalString.Remove((finalString.Length - 1));
AsanaObjectId newtask = JsonConvert.DeserializeObject<AsanaObjectId>(finalString);
return newtask;
}
catch (WebException ex)
{
HttpWebResponse response = (HttpWebResponse)ex.Response;
string resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
MessageBox.Show(resp);
System.Environment.Exit(0);
}
Can anybody explain how to integrate third party payment migs (MasterCard Virtual Payment Client) in C#?
Anyone who has done a similar project or has any clue as to what am missing here, can be of great help to me. In case of any question, I shall clarify in details. Thank you.
try
{
//Define Variables
string MerchantId = "00000047";
string Amount = txtAmountUSD.Text.Trim();
long PhoneNumber=long.Parse( txtPhoneNumber.Text.Trim().ToString());
string AccessCode = "4EC13697";
string SECURE_SECRET = "A1A3999770F5893719AE0076C7F18834";
string ReturnUrl = "http://localhost:2035/Core/frmMoneyTransfer.aspx";
string DestinationUrl = "https://migs.mastercard.com.au/vpcpay?";
string MerchantTransactionRef = Amount + DateTime.Now;
string Command = "Pay";
var HashData = SECURE_SECRET;
string postData = "vpc_Merchant=" + MerchantId;
postData += ("&vpc_Amount=" + Amount);
postData += ("&vpc_AccessCode=" + AccessCode);
postData += ("&vpc_Command=" + Command);
postData += ("&vpc_MerchTxnRef=" + MerchantTransactionRef);
postData += ("&vpc_ReturnURL=" + ReturnUrl);
postData += ("&vpc_SecureHashType=" + "SHA256");
postData += ("&vpc_OrderInfo=" + PhoneNumber );
postData += ("&vpc_Version=" + "1.0");
postData+=("&vpc_SecureHash="+SECURE_SECRET );
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(DestinationUrl);
request1.Method = "POST";
request1.ContentType = "application/x-www-form-urlencoded";
request1.AllowAutoRedirect = true;
request1.ProtocolVersion = HttpVersion.Version11;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(postData);
request1.ContentLength = bytes.Length;
Stream requestStream = request1.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
WebResponse response = request1.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
var result = reader.ReadToEnd();
Response.Redirect(request1.Address.ToString(), false );
stream.Dispose();
reader.Dispose();
}
catch (Exception Ex)
{
lblInfo.Text= Ex.Message.ToString();
}
Im trying to convert Java program to C#. This programe sent JSON object to server using a HTTP POST. Java program works fine. return 200. But C# program return 400 (bad request). What can be the cause
Java Code
String base_url = "https://test-url.com";
String username = "test-user";
String password = "test-pass";
String client_id = "test-client";
String client_secret = "test-key";
String loginUrl = base_url + "session/login";
Charset utf8 = Charset.forName("UTF-8");
ContentType jason_content_type = ContentType.create("application/json", utf8);
try {
HttpClient c = HttpClients.custom().setUserAgent(client_id + "/1.0").build();
HttpPost p = new HttpPost(loginUrl);
String json_str = "{" + "\"userId\":\"" + username + "\"," + "\"password\":\"" + password + "\"," + "\"clientId\":\"" + client_id + "\"," + "\"clientSecret\":\"" + client_secret + "\"" + "}";
p.setEntity(new StringEntity(json_str, jason_content_type));
HttpResponse r = c.execute(p);
int status = r.getStatusLine().getStatusCode();
} catch (IOException e) {
System.out.println(e);
}
C# Code
string base_url = "https://test-url.com";
string username = "test-user";
string password = "test-pass";
string client_id = "test-client";
string client_secret = "test-key";
string login_url = base_url + "session/login";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(login_url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = WebRequestMethods.Http.Post;
httpWebRequest.UserAgent = client_id + "/1.0";
httpWebRequest.ProtocolVersion=HttpVersion.Version11;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream(), Encoding.UTF8))
{
string json_str = "{" + "\"userId\":\"" + username + "\"," + "\"password\":\"" + password + "\"," + "\"clientId\":\"" + client_id + "\"," + "\"clientSecret\":\"" + client_secret + "\"" + "}";
streamWriter.Write(json_str);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
Try out adding in C# :
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
i tried this:
public static void CreateNewThread(string url,string fId, string title, string message, string tag)
{
url += "newthread.php?do=postthread";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//string result = "";
string values = "subject=" + title
+ "&message=" + message
+ "&tag=" + tag
+ "&do=postthread"
+ "&f=" + fId
+ "&s="
+ ""
;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = values.Length;
ServicePointManager.Expect100Continue = false; // prevents 417 error
using (StreamWriter writer = new StreamWriter(req.GetRequestStream(), Encoding.UTF8))
{
writer.Write(values);
}
HttpWebResponse c = (HttpWebResponse)req.GetResponse();
}
But this is doesnt work!
Try encoding the subject and message paramaters:
HttpUtility.UrlEncode(
string values = "subject=" + HttpUtility.UrlEncode(title)
+ "&message=" + HttpUtility.UrlEncode(message)
+ "&tag=" + HttpUtility.UrlEncode(tag)
+ "&do=postthread"
+ "&f=" + fId
+ "&s="
+ ""
;