Server Hosting Error in C# - c#

I developed a eCommerce Website using ASP.Net 3.5 and C#. It is working good with Visual Stdio 2010. I uploaded my website to my domain under the public folder.
It show the error like below:
Click for full-size, or here's the stack trace fragment from the local error page.
NullReferenceException: Object reference not set to an instance of an object
SageFrame.Framework.PageBase.OptimizeJs(List`1 lstJsColl, Int32 Mode) +7940
SageFrame.Framework.PageBase.LoadModuleJs() +944
SageFrame.Framework.PageBase.OnPreRender(EventArgs e) +233
System.Web.UI.PreRenderRecursiveInternal() +107
It was working fine before!
The code of the page_Load() is:
protected void Page_Load(object sender, EventArgs e)
{
string selectedCurrency = string.Empty;
string MainCurrency = string.Empty;
try
{
StoreSettingConfig ssc = new StoreSettingConfig();
MainCurrency = ssc.GetStoreSettingsByKey(StoreSetting.MainCurrency, GetStoreID, GetPortalID, GetCurrentCultureName);
if (Session["SelectedCurrency"] != null && Session["SelectedCurrency"] != "")
{
selectedCurrency = Session["SelectedCurrency"].ToString();
}
else
{
selectedCurrency = MainCurrency;
}
string islive = Request.Form["custom"];
string test = string.Empty;
const string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
const string strLive = "https://www.paypal.com/cgi-bin/webscr";
test = bool.Parse(islive.Split('#')[6]) ? strSandbox : strLive;
var req = (HttpWebRequest)WebRequest.Create(test);
//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;
var streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
var streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
if (strResponse == "VERIFIED")
{
string payerEmail = Request.Form["payer_email"];
string paymentStatus = Request.Form["payment_status"];
string receiverEmail = Request.Form["receiver_email"];
string amount = Request.Form["mc_gross"];
string invoice = Request.Form["invoice"];
string addressName = Request.Form["address_name"];
string addressStreet = Request.Form["address_street"];
string addressCity = Request.Form["address_city"];
string addressZip = Request.Form["address_zip"];
string addressCountry = Request.Form["address_country"];
string transID = Request.Form["txn_id"];
string custom = Request.Form["custom"];
string[] ids = custom.Split('#');
int orderID = int.Parse(ids[0]);
int storeID = int.Parse(ids[1]);
int portalID = int.Parse(ids[2]);
string userName = ids[3];
int customerID = int.Parse(ids[4]);
string sessionCode = ids[5];
string pgid = ids[7];
var tinfo = new TransactionLogInfo();
var tlog = new TransactionLog();
tinfo.TransactionID = transID;
tinfo.AuthCode = "";
tinfo.TotalAmount = decimal.Parse(amount);
tinfo.ResponseCode = "1";
tinfo.ResponseReasonText = "";
tinfo.OrderID = orderID;
tinfo.StoreID = storeID;
tinfo.PortalID = portalID;
tinfo.AddedBy = userName;
tinfo.CustomerID = customerID;
tinfo.SessionCode = sessionCode;
tinfo.PaymentGatewayID = int.Parse(pgid);
tinfo.PaymentStatus = paymentStatus;
tinfo.PayerEmail = payerEmail;
tinfo.CreditCard = "";
tinfo.RecieverEmail = receiverEmail;
tinfo.CurrencyCode = selectedCurrency;
tlog.SaveTransactionLog(tinfo);
if (paymentStatus.Equals("Completed"))
{
var paypalobj = new PayPalHandler();
paypalobj.ParseIPN(orderID, transID, paymentStatus, storeID, portalID, userName, customerID, sessionCode);
}
}
else if (strResponse == "INVALID")
{
//log for manual investigation
}
else
{
//log response/ipn data for manual investigation
}
// }
}
catch (Exception ex)
{
ProcessException(ex);
// throw new Exception("This Page is not accessible!");
}
}

From the error message, it appears that your store library cannot be loaded. This could be because it isn't installed on the server or the trust level is too low.
Either way, your hosting provider could assist with the setup.

Related

Umbraco Decrypting using MachineKey Encoding in C#

I want to first encrypt some nodes in Umbraco's content editor. The code below is the one I use for encryption. I use MachineKey.Protect for this.
try
{
MailMessage message1 = new MailMessage();
MailMessage message2 = new MailMessage();
SmtpClient client = new SmtpClient();
string AfsenderEmail = model.Email;
string AfsenderNavn = model.Name;
string toAddress = Umbraco.Content(rootNode.Id).mailDerSendesTil;
message1.From = new MailAddress(toAddress);
message2.From = new MailAddress(toAddress);
message1.Subject = $"{Umbraco.Content(rootNode.Id).overskriftPaaDenMailViFaar}";
message1.Subject = message1.Subject.Replace("AfsenderEmail", AfsenderEmail);
message1.Subject = message1.Subject.Replace("AfsenderNavn", AfsenderNavn);
message1.Body = $"{Umbraco.Content(rootNode.Id).beskedViFaarNaarBeskedenSendes}";
message1.Body = message1.Body.Replace("AfsenderEmail", AfsenderEmail);
message1.Body = message1.Body.Replace("AfsenderNavn", AfsenderNavn);
message1.To.Add(new MailAddress(toAddress));
client.Send(message1);
message2.Subject = $"{Umbraco.Content(rootNode.Id).overskriftPaaMeddelelsenAfsenderenFaar}";
message2.Subject = message2.Subject.Replace("AfsenderEmail", AfsenderEmail);
message2.Subject = message2.Subject.Replace("AfsenderNavn", AfsenderNavn);
message2.Body = $"{Umbraco.Content(rootNode.Id).beskedAfsenderenFaarNaarBeskedenSendes}";
message2.Body = message2.Body.Replace("AfsenderEmail", AfsenderEmail);
message2.Body = message2.Body.Replace("AfsenderNavn", AfsenderNavn);
message2.To.Add(new MailAddress(AfsenderEmail));
client.Send(message2);
var beskederNode = Umbraco.TypedContentAtRoot().FirstOrDefault(x => x.ContentType.Alias.Equals("Besked"));
var encryptName = MachineKey.Protect(Encoding.ASCII.GetBytes(model.Name));
var encryptEmail = MachineKey.Protect(Encoding.ASCII.GetBytes(model.Email));
var encryptMessage = MachineKey.Protect(Encoding.ASCII.GetBytes(model.Message));
string nameEncrypted = Encoding.ASCII.GetString(encryptName);
string emailEncrypted = Encoding.ASCII.GetString(encryptEmail);
string messageEncrypted = Encoding.ASCII.GetString(encryptMessage);
var newContent = contentService.CreateContent(nameEncrypted, beskederNode.Id, "mails");
newContent.SetValue("fra", nameEncrypted);
newContent.SetValue("eMail", emailEncrypted);
newContent.SetValue("besked", messageEncrypted);
var result = contentService.SaveAndPublishWithStatus(newContent);
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
catch (System.Exception ex)
{
Log.Error("Contact Form Error", ex);
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
}
This is where I Try to decrypt my code again. It throws an exception (System.Security.Cryptography.CryptographicException: 'Error occurred during a cryptographic operation.') when I call MachineKey.Unprotect(nameDecrypted) and I cannnot find my mistake. I think it maybe has somethimg to do with my Encoding and Decoding?
private void EditorModelEventManager_SendingContentModel(System.Web.Http.Filters.HttpActionExecutedContext sender, EditorModelEventArgs<Umbraco.Web.Models.ContentEditing.ContentItemDisplay> e)
{
var node = e.Model.Properties.ToList();
if (e.Model.IsChildOfListView && e.Model.ContentTypeAlias == "mails")
{
string nameDecrypt = node.Where(x => x.Alias.ToLower() == "fra").Select(x => x.Value).First().ToString();
Byte[] nameDecrypted = Encoding.ASCII.GetBytes(nameDecrypt);
var name = e.Model.Properties.FirstOrDefault(x => x.Alias.ToLower() == "fra");
Byte[] decryptName = MachineKey.Unprotect(nameDecrypted);
string nameReady = Encoding.ASCII.GetString(decryptName);
name.Value = $"{nameReady}";
}
}
}
}
I found a solution. Instead of using Encoding.ASCII.GetString(), I used Convert.FromBase64String().

URL not opening correctly on another browser asp.net mvc

I have an asp.net mvc application were i send sms messages with URL to clients. message and URL is sent correctly but when i click on the link it does not open correctly, example there is no data passed from database, example if you click the following url, there is no data passed to view: http://binvoicing.com/InvoiceAddlines/PaymentPreview?originalId=11&total=585.00
Here code:
public ActionResult SendSms(string cellnumber, int? id, string rt, string tenant, decimal? total, string userloggedin)
{
StreamReader objReader;
WebClient client = new WebClient();
int payid = 0;
int paypalaid = 0;
string UrL = "";
string pass = "mypassword";
//string cell = cellnumber;
string user = "username";
var pay = from e in db.PayfastGateways
where e.userId == userloggedin
select e;
var paya = pay.ToList();
foreach (var y in paya)
{
payid = y.ID;
}
var pal = from e in db.PaypalGateways
where e.userId == userloggedin
select e;
var payla = pal.ToList();
foreach (var y in payla)
{
paypalaid = y.ID;
}
string url = Url.Action("PaymentPreview", "InvoiceAddlines", new System.Web.Routing.RouteValueDictionary(new { originalId = id, total = total }), "http", Request.Url.Host);
if (payid == 0 && paypalaid == 0)
{
UrL = "";
}
else
{
UrL = url;
}
string mess = " Dear Customer, please click on the following link to view generated invoice, you can also pay your invoice online." + UrL;
string message = HttpUtility.UrlEncode(mess, System.Text.Encoding.GetEncoding("ISO-8859-1"));
string baseurl =
"http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0?" +
"username=" + user + "&" +
"password=" + pass + "&" +
"message=" + message + "&" +
"msisdn=" + cellnumber;
WebRequest wrGETURL;
wrGETURL = WebRequest.Create(baseurl);
HttpUtility.UrlEncode("http://www.vcskicks.com/c#");
try
{
Stream objStream;
objStream = wrGETURL.GetResponse().GetResponseStream();
objReader = new StreamReader(objStream);
objReader.Close();
}
catch (Exception ex)
{
ex.ToString();
}
ViewBag.cellnumber = cellnumber;
ViewBag.id = id;
ViewBag.rt = rt;
ViewBag.tenant = tenant;
ViewBag.total = total;
ViewBag.UrL = UrL;
return View();
}
SMS send url like http://binvoicing.com/InvoiceAddlines/PaymentPreview?originalId=11&total=585.00
Here Is my PaymentPreview method:
public ActionResult PaymentPreview(int? originalId, decimal? total)
{
TempData["keyEditId"] = originalId;
ViewBag.ind = originalId;
decimal totals = 0;
totals = (decimal)total;
var line = from e in db.InvoiceAddlines
where e.AddlineID == originalId
select e;
var addlines = line.ToList();
foreach (var y in addlines)
{
decimal? de = Math.Round(totals);
string tots = de.ToString();
y.Total = tots;
db.SaveChanges();
}
return View(db.InvoiceAddlines.ToList());
}
Hope someone can assist, thanks.
I think there is something wrong with the way URL is being built. See if this works -
Change this part of your code
string url = Url.Action("PaymentPreview", "InvoiceAddlines", new System.Web.Routing.RouteValueDictionary(new { originalId = id, total = total }), "http", Request.Url.Host);
To
string url = Url.Action("PaymentPreview", "InvoiceAddlines", new { originalId = id, total = total })

OVER_QUERY_LIMIT status found from Geocode

I have to update my database from geocode to get longitude and latitude of address stored in database.
For that I created one console application. Daily I can update 25000 records from google per user, And I am executing my console from different 3 machines everyday since last 4 to 5 days.
But I am getting OVER_QUERY_LIMIT status from today and I am not able to update database.
What should i do for this?
Here is my code to get Longitude-latitude of console:
protected static void FindLocation(string strLocation, out string lat, out string lng, out string Output)
{
StreamWriter myWriter;
System.Net.HttpWebRequest geoRequest;
string googResponse;
googResponse = "";
lat = "";
lng = "";
Output = "";
string abc = "";
string strRequestURL;
strRequestURL = "https://maps.googleapis.com/maps/api/geocode/xml?address=" + strLocation + "&sensor=false";
try
{
geoRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strRequestURL);
geoRequest.Method = "POST";
geoRequest.KeepAlive = true;
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(strRequestURL);
geoRequest.ContentLength = bytes.Length;
using (Stream writeStream = geoRequest.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
writeStream.Close();
}
System.Net.HttpWebResponse geoResponse;
geoResponse = (System.Net.HttpWebResponse)geoRequest.GetResponse();
if (geoResponse != null)
{
XPathDocument document = new XPathDocument(geoResponse.GetResponseStream());
XPathNavigator navigator = document.CreateNavigator();
// get response status
XPathNodeIterator statusIterator = navigator.Select("/GeocodeResponse/status");
while (statusIterator.MoveNext())
{
if (statusIterator.Current.Value != "OK")
{
if (statusIterator.Current.Value == "OVER_QUERY_LIMIT")
{
}
Output = "Failed";
}
else
{
Output = statusIterator.Current.Value;
}
}
// get results
XPathNodeIterator resultIterator = navigator.Select("/GeocodeResponse/result");
while (resultIterator.MoveNext())
{
XPathNodeIterator geometryIterator = resultIterator.Current.Select("geometry");
while (geometryIterator.MoveNext())
{
XPathNodeIterator locationIterator = geometryIterator.Current.Select("location");
while (locationIterator.MoveNext())
{
XPathNodeIterator latIterator = locationIterator.Current.Select("lat");
while (latIterator.MoveNext())
{
lat = latIterator.Current.Value;
}
XPathNodeIterator lngIterator = locationIterator.Current.Select("lng");
while (lngIterator.MoveNext())
{
lng = lngIterator.Current.Value;
}
}
}
}
}
else
{
Output = "Failed";
}
}
catch (Exception ex)
{
Output = "Failed";
}
}

How to use cursors to iterate through the result set of GET followers/list in Twitter API using c#?

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.

How to click a button in an webpage

I'm using these code to download a file from the server.
The link of the server from where I need to download the file is:
http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx
var forms = new NameValueCollection();
forms["__EVENTARGUMENT"] = "";
forms["__VIEWSTATE"] = ExtractVariable(s, "__VIEWSTATE");
forms["mTbdate"] = "12/22/2011";
forms["__EVENTVALIDATION"] = __EVENTVALIDATION;
forms["mImgBtnGo"] = "?";
forms["__EVENTTARGET"] = "btnLink_Excel";
webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
var responseData = webClient.UploadValues(#"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms);
System.IO.File.WriteAllBytes(#"c:\11152011.csv", responseData);
Its downloading the file of the given date in the textbox which is default in the website now.
I need to click a button called mImgBtnGo before, to download the file of the given date
in the mTbdate.
I don't know what I should do to click the button called mImgBtnGo .
What I should write here
forms["mImgBtnGo"] = "?";
using fiddler I think this is what you want:
class Program
{
static string Extract(string s, string tag)
{
var startTag = String.Format("id=\"{0}\" value=\"", tag);
var eaPos = s.IndexOf(startTag) + startTag.Length ;
var eaPosLast = s.IndexOf('"', eaPos);
return s.Substring(eaPos, eaPosLast-eaPos);
}
static void Main(string[] args)
{
WebClient webClient = new WebClient();
var firstResponse = webClient.DownloadString(#"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx");
var forms = new NameValueCollection();
forms["__EVENTARGUMENT"] = "";
forms["__VIEWSTATE"] = Extract(firstResponse, "__VIEWSTATE");
forms["mTbdate"] = "12/22/2011";
forms["__EVENTVALIDATION"] = Extract(firstResponse, "__EVENTVALIDATION");
forms["mImgBtnGo.x"] = "10";
forms["mImgBtnGo.y"] = "10";
forms["ScriptManager1"] = "MupdPnl|mImgBtnGo";
// forms["__EVENTTARGET"] = "btnLink_Excel";
webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
String secondResponse = UTF8Encoding.UTF8.GetString(
webClient.UploadValues(#"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms)
);
forms = new NameValueCollection();
forms["__EVENTARGUMENT"] = "";
forms["__VIEWSTATE"] = Extract(secondResponse, "__VIEWSTATE");
forms["mTbdate"] = "12/22/2011";
forms["__EVENTVALIDATION"] = Extract(secondResponse, "__EVENTVALIDATION");
// forms["mImgBtnGo"] = "?";
forms["__EVENTTARGET"] = "btnLink_Excel";
webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
var responseData = webClient.UploadValues(#"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms);
System.IO.File.WriteAllBytes(#"c:\prj\11152011.csv", responseData);
}
}

Categories