How to send Notification to multiple android devices in same request? - c#

i am using the following code to send notification but it is for only one device but i want to send notification to multiple devices in same request.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class AndroidPush : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string deviceId = "DEVICE_REGISTRATION_ID";
string message = "Lead Generated Please check Lead section";
string tickerText = "Lead Generated Please check Lead section";
string contentTitle = "Lead Generated Please check Lead section";
string postData =
"{ \"registration_ids\": [ \"" + deviceId + "\" ], " +
"\"data\": {\"tickerText\":\"" + tickerText + "\", " +
"\"contentTitle\":\"" + contentTitle + "\", " +
"\"message\": \"" + message + "\"}}";
string response = SendGCMNotification("my api key", postData, "application/json");
}
/// <summary>
/// Send a Google Cloud Message. Uses the GCM service and your provided api key.
/// </summary>
/// <param name="apiKey"></param>
/// <param name="postData"></param>
/// <param name="postDataContentType"></param>
/// <returns>The response string from the google servers</returns>
private string SendGCMNotification(string apiKey, string postData, string postDataContentType)
{
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
//
// MESSAGE CONTENT
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//
// CREATE REQUEST
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = postDataContentType;
Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//
// SEND MESSAGE
try
{
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
var text = "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadToEnd();
Reader.Close();
return responseLine;
}
catch (Exception e)
{
}
return "error";
}
public static bool ValidateServerCertificate(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
so i want to know how can i use this code so that it can send notification to multiple devices.
If anyone knows about this then please provide answer or suggestion for the same.
Thanks in advance

Related

500: internal server error while trying to call a REST api from C# console

I m trying to generate a token from salesforce api with oauth. I m using this token to retreive data and then perform put request for each object. However, the web response is showing an unhandled exception saying "500:Internal server error" while i m trying to generate a token. I need to pass content type and accept in header params and other params in body.
namespace Test
{
class Program
{
static void Main(string[] args)
{
string response = Post("https://xx-dev.cs15.my.salesforce.com/services/oauth2/token");
dynamic data = JObject.Parse(response);
string accessToken = data.access_token;
}
//POST to generate token.
private static string Post(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.Accept = "application/json";
request.ContentType = "application/x-www-form-urlencoded";
string body = "client_id=43nmbmn43534y98jh_3yQty7vm3CqYMvrSdfdsfFDSGFW7kNYk_bWxmhTaY5KT&client_secret=123456789&grant_type=password&username=user#username.com.test&password=TestPassword";
byte[] byteArray = Encoding.UTF8.GetBytes(body);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();//**I'm getting the error here**
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
Headers:
Postman;
Application
I believe the content your are passing in the body should be in the URL. The Developer Documentation suggests building your HttpWebRequest like this:
string strContent = "grant_type=password" +
"&client_id=" + consumerKey +
"&client_secret=" + consumerSecret +
"&username=" + acctName +
"&password=" + acctPw;
string urlStr = "https://login.salesforce.com/services/oauth2/token?" + strContent;
HttpWebRequest request = WebRequest.Create(urlStr) as HttpWebRequest;
request.Method = "POST";
EDIT
Sorry, I spent a lot of time trying to get it working with the content in the body like you have it, but I kept getting "(400) Bad Request" as the response. I'm not sure why you were originally getting "500:Internal server error" back; I kept getting the "(400) Bad Request" response back using the exact same code you were using.
The code example in the Developer Documentation is working for me. There are some REST wrappers available if you would like to try that; most are available as NuGet packages. See SalesforceSharp. It may be worth considering as it would likely reduce the amount of code you have to write and be less tedious.
Here is my source code which I copied from the Developer Documentation if you would like to replace it with your credentials and see if it works for you:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace VerifyRESTTest
{
class Program
{
// Class used for serializing the OAuth JSON response
[DataContract]
public class OAuthUsernamePasswordResponse
{
[DataMember]
public string access_token { get; set; }
[DataMember]
public string id { get; set; }
[DataMember]
public string instance_url { get; set; }
[DataMember]
public string issued_at { get; set; }
[DataMember]
public string signature { get; set; }
}
private static string accessToken = "";
private static string instanceUrl = "";
private static void login()
{
string acctName = "#########gmail.com";
string acctPw = "##############";
string consumerKey = "###############################################";
string consumerSecret = "#################";
// Just for testing the developer environment, we use the simple username-password OAuth flow.
// In production environments, make sure to use a stronger OAuth flow, such as User-Agent
string strContent = "grant_type=password" +
"&client_id=" + consumerKey +
"&client_secret=" + consumerSecret +
"&username=" + acctName +
"&password=" + acctPw;
string urlStr = "https://############-dev-ed.my.salesforce.com/services/oauth2/token?" + strContent;
HttpWebRequest request = WebRequest.Create(urlStr) as HttpWebRequest;
request.Method = "POST";
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
// Parse the JSON response and extract the access token and instance URL
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(OAuthUsernamePasswordResponse));
OAuthUsernamePasswordResponse objResponse = jsonSerializer.ReadObject(response.GetResponseStream()) as OAuthUsernamePasswordResponse;
accessToken = objResponse.access_token;
instanceUrl = objResponse.instance_url;
}
}
catch (Exception e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
static void Main(string[] args)
{
login();
if (accessToken != "")
{
// display some current login settings
Console.Write("Instance URL: " + instanceUrl + "\n");
Console.Write("Access Token: " + accessToken + "\n");
Console.Write("Press any key to continue:\n");
Console.ReadKey();
}
}
}
}
Some things to consider: Since you ended up getting a "(400) Bad Request" when you initially tried the example code as opposed to the "500:Internal server error", the "HTTP 400" is more specific and usually indicates a syntax error, so it might be worth trying the example method again and making sure something wasn't mistyped, and your security token, site key, client secret, username, and password are correct, and that you appended your security token to the end of your password.
Edit 2
See how SalesforceSharp authenticates with Salesforce in Line 93. They are using RestSharp, which is available as a NuGet package.

Python Requests Post Failing With 500 Error

I am using this excellent project on GitHub (https://github.com/cjyoung/MouseBitesWPF). However, that is written in C# and I really need something written in Python. I have boiled that code down to the absolute bare bones of what it needs to work and came up with this:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace DisneyFinderSmaller
{
class Program
{
static CookieContainer cookieJar = new CookieContainer();
static internal string rootUrl = "https://disneyworld.disney.go.com";
static internal string siteUrl = "/dining/";
static internal string diningSearchUrl = "/finder/dining-availability";
static void Main(string[] args)
{
LaunchSearchInstance();
string test = Console.ReadLine();
}
private static void LaunchSearchInstance()
{
string result = getCookiesFromRequest(rootUrl + siteUrl, "", "GET");
string pep_csrf = "";
Match match = Regex.Match(result, "<input[^>]*name=['\"]pep_csrf['\"][^>]*value=['\"]([^'\"]*)['\"]*[^>]>", RegexOptions.Singleline & RegexOptions.IgnoreCase);
pep_csrf = match.Groups[1].ToString();
ConductSearch(pep_csrf);
}
private static void ConductSearch(string pep_csrf)
{
string postString = string.Format("&searchDate={1}" +
"&skipPricing=true" +
"&searchTime={2}" +
"&partySize={3}" +
"&id={0}%3BentityType%3Drestaurant" +
"&type=dining" +
"&pep_csrf={4}",
"293704",
"2015-11-18",
"80000714",
"2",
pep_csrf);
string result = getCookiesFromRequest(rootUrl + diningSearchUrl, postString, "POST");
System.Console.WriteLine(result);
}
private static String getCookiesFromRequest(string url, string postString, string method = "POST")
{
String result = "";
byte[] postBytes = Encoding.ASCII.GetBytes(postString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.Referer = rootUrl + siteUrl;
request.CookieContainer = cookieJar;
if (method == "POST")
{
request.ContentType = "application/x-www-form-urlencoded";
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
}
try
{
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
result = responseStreamReader.ReadToEnd();
responseStream.Close();
webResponse.Close();
}
catch (Exception ex)
{
Console.WriteLine("IOException source: {0}", ex.Source);
}
return result;
}
}
}
In my efforts to translate this to Python using Requests, I have come up with this:
#!/usr/bin/env python
import requests
url = "https://disneyworld.disney.go.com/dining/"
url2 = "https://disneyworld.disney.go.com/dining/finder/dining-availability"
session = requests.Session()
tokenRequest = session.get(url, headers=header)
start = tokenRequest.content.find('''id="pep_csrf"''')
pep = tokenRequest.content[start+21:tokenRequest.content.find('>',start+22)-1]
raw = "&searchDate=2015-11-18&skipPricing=true&searchTime=80000714&partySize=2&id=293704%3BentityType%3Drestaurant&type=dining&pep_csrf=" + pep
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'referer': 'https://disneyworld.disney.go.com/dining/',
'method' : 'POST'
}
result = session.post(url2, data=raw, headers=headers)
print result.status_code
But this doesn't work and returns a status code of 500.
Any thoughts on where things are going wrong? I have been hanging my head against the wall for a few days and any insight at all would be so appreciated.

PayPal IPN Error

When I ran the following code through the IPN simulator the simulator said it worked however my page received a INVALID response.
I did some reading and paypal said it uses charset UTF-8 but when I changed to that the simulator failed and I received no response.
The code runs on pageload
string postUrl = ConfigurationManager.AppSettings["PayPalSubmitUrlSandBox"];
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(postUrl);
//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);
string ipnPost = strRequest;
strRequest = "cmd=_notify-validate&" + strRequest;
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")
{
//removed this because I don't think it is what is causing the trouble }
}
else if (strResponse == "INVALID")
{
//removed this because I don't think it is what is causing the trouble
}
else
{
//removed this because I don't think it is what is causing the trouble
}
Try changing your code to the following:
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;
Also, make sure you're logged into the sandbox BEFORE you do the test...
Figured it out... not really sure what changed from the previous code. I just found code on a tutorial and did some minor modifications.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Globalization;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Web.Configuration;
using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
using System.Drawing;
public partial class paypal_IPNHandler : System.Web.UI.Page
{
string payerEmail;
string paymentStatus;
string receiverEmail;
string amount;
/// <summary>
/// Process an incoming Instant Payment Notification (IPN)
/// from PayPal, at conclusion of a received payment from a
/// customer
/// </summary>
///
protected void Page_Load(object sender, EventArgs e)
{
// receive PayPal ipn data
// extract ipn data into a string
byte[] param = Request.BinaryRead(Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
// append PayPal verification code to end of string
strRequest = "cmd=_notify-validate&" + strRequest;
// create an HttpRequest channel to perform handshake with PayPal
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(#"https://www.paypal.com/cgi-bin/webscr");
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = strRequest.Length;
// send data back to PayPal to request verification
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
// receive response from PayPal
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
// if PayPal response is successful / verified
if (strResponse.Equals("VERIFIED"))
{
// paypal has verified the data, it is safe for us to perform processing now
// extract the form fields expected: buyer and seller email, payment status, amount
payerEmail = Request.Form["payer_email"];
paymentStatus = Request.Form["payment_status"];
receiverEmail = Request.Form["receiver_email"];
amount = Request.Form["mc_gross"];
}
// else
else
{
// payment not complete yet, may be undergoing additional verification or processing
// do nothing - wait for paypal to send another IPN when payment is complete
}
String insertConnString = System.Configuration.ConfigurationManager.ConnectionStrings["BeachConnectionString"].ConnectionString;
using (SqlConnection insertcon = new SqlConnection(insertConnString))
using (SqlCommand cmdinsert = insertcon.CreateCommand())
{
string insertprofile = "INSERT INTO Test (Status, Text) VALUES (#Status, #Text)";
cmdinsert.CommandText = insertprofile;
cmdinsert.Parameters.Add("#Status", SqlDbType.VarChar).Value = strResponse.ToString();
cmdinsert.Parameters.Add("#Text", SqlDbType.VarChar).Value = strRequest.ToString();
cmdinsert.Connection.Open();
cmdinsert.ExecuteNonQuery();
}
}
}

Automatic add text on textbox when I open one site

So, i'm tring to put one information on one textbox, in more special textbox, CNPJ of one site:
http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp
but I'm not getting... so, what I have tried... I have tried to put the cnpj value on the final of link, like this:
http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp?cnpj=00495835000160
but, the site no put the value on the text box...
How I can make to enter with with the cnpj value on the site ( whiout digit on the site, just in the link... )
And, In C# I have tried this:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace ReceitaFederal
{
class Program
{
static void Main(string[] args)
{
try
{
WebRequest request = WebRequest.Create("http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp");
string strPost = "cnpj=00495835000160";
request.Method = "POST";
request.ContentLength = strPost.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(strPost);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
Console.WriteLine(responseFromServer);
}
catch (Exception exec)
{
Console.WriteLine(exec.GetType() + "" + exec.Message);
}
}
}
}
Solved!!! First add this cookie container:
using System;
using System.Net;
namespace ConsultaCNPJ
{
public class CookieAwareWebClient : WebClient
{
private CookieContainer _mContainer;
public void SetCookieContainer(CookieContainer container)
{
_mContainer = container;
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
var webRequest = request as HttpWebRequest;
if (webRequest != null)
{
webRequest.CookieContainer = _mContainer;
webRequest.KeepAlive = true;
webRequest.ProtocolVersion = HttpVersion.Version10;
}
return request;
}
}
}
Then edit you code to this:
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsultaCNPJ
{
public class ConsultaCNPJBroker
{
private readonly CookieContainer _cookies = new CookieContainer();
public String DominioReceitaFederal = "http://www.receita.fazenda.gov.br";
public String GetDataReceitaFederal = "/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao2.asp";
public String PostDataReceitaFederal = "/pessoajuridica/cnpj/cnpjreva/valida.asp";
private String _viewState;
public Bitmap GetCaptcha()
{
const string strViewState = "<input type=hidden id=viewstate name=viewstate value='";
const string strImagemCaptcha = "<img border='0' id='imgcaptcha' alt='Imagem com os caracteres anti robô' src='";
String htmlResult;
using (var wc = new CookieAwareWebClient())
{
wc.SetCookieContainer(_cookies);
wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)";
wc.Headers[HttpRequestHeader.KeepAlive] = "300";
htmlResult = wc.DownloadString(DominioReceitaFederal + GetDataReceitaFederal);
}
if (htmlResult.Length > 0)
{
_viewState = htmlResult;
int posString = _viewState.IndexOf(strViewState, StringComparison.Ordinal);
_viewState = _viewState.Substring(posString + strViewState.Length);
posString = _viewState.IndexOf("'>", StringComparison.Ordinal);
_viewState = _viewState.Substring(0, posString);
String urlImagemCaptcha = htmlResult;
posString = urlImagemCaptcha.IndexOf(strImagemCaptcha, StringComparison.Ordinal);
urlImagemCaptcha = urlImagemCaptcha.Substring(posString + strImagemCaptcha.Length);
posString = urlImagemCaptcha.IndexOf("'>", StringComparison.Ordinal);
urlImagemCaptcha = urlImagemCaptcha.Substring(0, posString);
urlImagemCaptcha = urlImagemCaptcha.Replace("amp;", "");
if (urlImagemCaptcha.Length > 0)
{
var wc2 = new CookieAwareWebClient();
wc2.SetCookieContainer(_cookies);
wc2.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)";
wc2.Headers[HttpRequestHeader.KeepAlive] = "300";
byte[] data = wc2.DownloadData(DominioReceitaFederal + urlImagemCaptcha);
return new Bitmap(
new MemoryStream(data));
}
return null;
}
_viewState = "";
return null;
}
public Stream Consulta(string aCNPJ, string aCaptcha, bool removerEspacosDuplos)
{
var request = (HttpWebRequest) WebRequest.Create(DominioReceitaFederal + PostDataReceitaFederal);
request.ProtocolVersion = HttpVersion.Version10;
request.CookieContainer = _cookies;
request.Method = "POST";
string fviewstate = _viewState;
fviewstate = Uri.EscapeDataString((fviewstate));
string postData = "";
postData = postData + "origem=comprovante&";
postData = postData + "viewstate=" + fviewstate + "&";
postData = postData + "cnpj=" + new Regex(#"[^\d]").Replace(aCNPJ, string.Empty) + "&";
postData = postData + "captcha=" + aCaptcha + "&";
postData = postData + "captchaAudio=&";
postData = postData + "submit1=Consultar&";
postData = postData + "search_type=cnpj";
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();
return response.GetResponseStream();
}
}
}
That's it!
Special thanks to my great friend CunhaW!
Usage:
First create a form with a PictureBox and a TextBox and the broker for captcha like this
private readonly ConsultaCNPJBroker _broker = new ConsultaCNPJBroker();
this.ImgCaptcha = new System.Windows.Forms.PictureBox();
this.TbxCaptcha = new System.Windows.Forms.TextBox();
Then use like 2-Steps query, first get the Captcha then do the Query with the captcha
private void UpdateCaptcha()
{
ImgCaptcha.Image = _broker.GetCaptcha();
TbxCaptcha.Text = string.Empty;
}
A user interaction is need here to solve the captcha and fill the textbox and finally
private void BtnExecute_OnClick(object sender, EventArgs e)
{
var pessoaJuridica = _broker.Consulta(TbxCNPJ.Text, TbxCaptcha.Text, true);
// here you can see props like pessoaJuridica.CNPJ
}
Maybe this help you, it's not working yet... but almost there...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Windows.Forms;
namespace LeituraWeb
{
public partial class Form1 : Form
{
String viewState;
public String Dominio_ReceitaFederal = "http://www.receita.fazenda.gov.br/";
public String GetData_ReceitaFederal = "pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao2.asp";
public String PostData_ReceitaFederal = "pessoajuridica/cnpj/cnpjreva/valida.asp";
public Form1()
{
InitializeComponent();
}
private void btnGo_Click(object sender, EventArgs e)
{
int PosString;
String StrViewState = "<input type=hidden id=viewstate name=viewstate value='";
String StrImagemCaptcha = "<img border='0' id='imgcaptcha' alt='Imagem com os caracteres anti robô' src='";
String UrlImagemCaptcha = "";
String HtmlResult = "";
using (WebClient wc = new WebClient()){
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
HtmlResult = wc.DownloadString(Dominio_ReceitaFederal + GetData_ReceitaFederal);
}
if (HtmlResult.Length > 0)
{
viewState = HtmlResult;
// executando um crop do viewstate para utilizar no post
PosString = viewState.IndexOf(StrViewState);
viewState = viewState.Substring(PosString + StrViewState.Length);
PosString = viewState.IndexOf("'>");
viewState = viewState.Substring(0, PosString);
//executando um crop na url da imagem
UrlImagemCaptcha = HtmlResult;
PosString = UrlImagemCaptcha.IndexOf(StrImagemCaptcha);
UrlImagemCaptcha = UrlImagemCaptcha.Substring(PosString + StrImagemCaptcha.Length);
PosString = UrlImagemCaptcha.IndexOf("'>");
UrlImagemCaptcha = UrlImagemCaptcha.Substring(0, PosString);
UrlImagemCaptcha = UrlImagemCaptcha.Replace("amp;", "");
// populando a imagem do captcha dentro de um picturebox
if (UrlImagemCaptcha.Length > 0)
pictureBox1.Image = new System.Drawing.Bitmap(new System.IO.MemoryStream(new System.Net.WebClient().DownloadData(Dominio_ReceitaFederal + UrlImagemCaptcha)));
}
else
{
viewState = "";
}
}
private void button1_Click(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create(Dominio_ReceitaFederal + PostData_ReceitaFederal);
// Formatando o ViewState Recebido
string fviewstate = viewState;
fviewstate = System.Uri.EscapeDataString(System.Uri.UnescapeDataString(fviewstate));
// inserindo os campos a serem postados
string postData = "";
postData = postData + "origem=comprovante&";
postData = postData + "viewstate=" + fviewstate + "&";
postData = postData + "cnpj=00000000000000&";
postData = postData + "captcha=000000&";
postData = postData + "captchaAudio=&";
postData = postData + "submit1=Consultar&";
postData = postData + "search_type=cnpj";
// montando a requisicao
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();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
// ---------- erro aqui !!!
// retorno da sefaz ---- sempre retorna -- Parametros Inválidos
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
}
}
}
You have to make sure the target site supports the kind of request you are trying to do.
If not, you are out of luck. Keep in mind that the web app implementation is the one who dictates the rules, not you.
Additionally, it looks like you are trying to obtain information from a Brazilian government site. Usually, this type of sites have mechanisms to prevent what you are trying to achieve, such as captchas and domain validation.
The good news is that, also usually, government sites publish rules and manuals on how to access public webservices. However, you also usually need permission for that.
The page uses frames:
<frame name="top" scrolling="no" frameborder="0" marginheight="0" noresize="true" target="contents" src="cabecalho.htm" marginwidth="0" marginheight="0">
<frame frameborder="0" name="main" SRC="cnpjreva_solicitacao2.asp" scrolling="auto" noresize="false" marginheight="0" marginwidth="0">
The main frame contains the page cnpjreva_solicitacao2.asp, so calling http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao2.asp?cnpj=00495835000160 (see the 2 in the page file name) will show you the content of the main frame with the CNPJ filled as passed by the parameter.
I say instead of crafting the resulting code,
you could inject javascript.
e.g.
open the page you posted
http://www.receita.fazenda.gov.br/pessoajuridica/cnpj/cnpjreva/cnpjreva_solicitacao.asp
open JS Console and type the following:
document.getElementsByName("main")[0].contentDocument.getElementsByName("cnpj")[0].value = "MyNewValue"
Notice, the form is within a frame element, so you need to get the frame element and then the input element.
You can do the same via the Web Browser API.
Good Luck with solving the CAPTCHA

GCM response coming is: Error=NotRegistered

This is my sample server created for GCM.
class Program2
{
public static string SenderId = "318115091714";
public static string RegistrationID = "APA91bF9hn6VeessobraNuauBcrFdlJ9eH1eVb44FAQ2oawerBeFWS48IEIFTPo8fdvWm93hwFY0tKszpPuSObPbTqgW-za1RLhCw-GDCn4JQZLQ-CmGwnnr6F5X8gYhNa2DNvFhCEM7HNgvdxtcnBqVX0dVnEynXQ";
public static string ApiKey = "AIzaSyAl2HdB4bbukkcmJwoxUmhof15IAiuJ16U";
public static string Message = "Testing GCM Server";
public static string ApplicationId = "com.google.android.gcm.demo.app";
/// <summary>
/// Main method
/// </summary>
public static void Main(string[] args)
{
try
{
Program2 objProgram2 = new Program2();
Console.WriteLine("\nPlease wait while GCM server is processing...");
string Text = objProgram2.SendMessage();
Console.WriteLine("\nSendMessage Response: " + Text);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("\n" + ex.Message);
Console.WriteLine("\n" + ex.StackTrace);
Console.ReadLine();
}
}
/// <summary>
/// Send Push Message to Device
/// </summary>
public string SendMessage()
{
//-- Create Query String --//
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.Message=" + Message + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + RegistrationID + "";
//Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//-- Create GCM Request Object --//
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.Headers.Add(string.Format("Authorization: key={0}", ApiKey));
Request.Headers.Add(string.Format("Sender: id={0}", SenderId));
Request.ContentLength = byteArray.Length;
//-- Delegate Modeling to Validate Server Certificate --//
ServicePointManager.ServerCertificateValidationCallback += delegate(
object
sender,
System.Security.Cryptography.X509Certificates.X509Certificate
pCertificate,
System.Security.Cryptography.X509Certificates.X509Chain pChain,
System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
{
return true;
};
//-- Create Stream to Write Byte Array --//
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//-- Post a Message --//
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
return "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
return "Response from web service isn't OK";
//Console.WriteLine("Response from web service is not OK :");
//Console.WriteLine(((HttpWebResponse)Response).StatusDescription);
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadLine();
Reader.Close();
return responseLine;
}
}
After running it with these valid values and keys I received this response.
Please wait while GCM server is processing...
SendMessage Response: Error=NotRegistered
I am getting Error=NotRegistered. This response is not even specified in android developer guide. What should be the reason I am getting this response? Can anyone help me out with this? Thanks in advance.
I have found out the reason why it was happening. There could be six type of responses. Following is the list of response and their meaning.
{ "message_id": "1:0408" } - success
{ "error": "Unavailable" } - should be resent
{ "error": "InvalidRegistration" } - had an unrecoverable error (maybe the value got corrupted in the database)
{ "message_id": "1:1516" } - success
{ "message_id": "1:2342", "registration_id": "32" } - success, but the registration ID should be updated in the server database
{ "error": "NotRegistered"} - registration ID should be removed from the server database because the application was uninstalled from the device
I was getting error message 6. With new Sender Id, Registration Id and API key my above code is working .
I am not the server guy but recently looked over the GCM server code to resolve the issue. So here what I found:
Your line of code to set API Key:
Request.Headers.Add(string.Format("Authorization: key={0}", ApiKey));
Does not look right to me. The key= word should be concatenated to the api key and then your line would look like this:
Request.Headers.Add("Authorization", "key=" + ApiKey));
That's what worked at my end.
and for sender Id we have a different approach, so check your this line of code too:
Request.Headers.Add(string.Format("Sender: id={0}", SenderId));

Categories