I use yahoo oAuth1 and yahoo API to get contact list from yahoo server.
Here the code that I use to get contacts:
private void RetriveContacts()
{
OAuthBase oauth = new OAuthBase();
Uri uri = new Uri("https://social.yahooapis.com/v1/user/" + (string)Session["xoauth_yahoo_guid"] + "/contacts?format=XML");
string nonce = oauth.GenerateNonce();
string timeStamp = oauth.GenerateTimeStamp();
string normalizedUrl;
string normalizedRequestParameters;
string sig = oauth.GenerateSignature(uri, ConsumerKey, ConsumerSecret,
(string)Session["oauth_token"], (string)Session["oauth_token_secret"], "GET",
timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1,
out normalizedUrl, out normalizedRequestParameters);
StringBuilder sbGetContacts = new StringBuilder(uri.ToString());
try
{
string returnStr = string.Empty;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sbGetContacts.ToString());
req.Method = "GET";
string authHeader = "Authorization: OAuth " +
"realm=\"yahooapis.com\"" +
",oauth_consumer_key=\"" + ConsumerKey + "\"" +
",oauth_nonce=\"" + nonce + "\"" +
",oauth_signature_method=\"HMAC-SHA1\"" +
",oauth_timestamp=\"" + timeStamp + "\"" +
",oauth_token=\"" + (string)Session["oauth_token"] + "\"" +
",oauth_version=\"1.0\"" +
",oauth_signature=\"" + HttpUtility.UrlEncode(sig) + "\"";
req.Headers.Add(authHeader);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader streamReader = new StreamReader(res.GetResponseStream());
returnStr = streamReader.ReadToEnd();
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(returnStr);
XmlNodeList elemList = xmldoc.DocumentElement.GetElementsByTagName("fields");
List<string> emails = new List<string>();
for (int i = 0; i < elemList.Count; i++)
{
if (elemList[i].ChildNodes[1].InnerText == "email")
emails.Add(elemList[i].ChildNodes[2].InnerText);
//Response.Write(elemList[i].ChildNodes[2].InnerText + "<br/>");
}
}
catch (WebException ex)
{
//Response.Write(ex.Message);
Response.Write("<br/>" + ex.Message + "</br>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
Response.Write("<br/>length: " + ex.Source.Length.ToString());
Response.Write("<br/>stack trace: " + ex.StackTrace);
Response.Write("<br/>status: " + ex.Status.ToString());
HttpWebResponse res = (HttpWebResponse)ex.Response;
int code = Convert.ToInt32(res.StatusCode);
Response.Write("<br/>Status Code: (" + code.ToString() + ") " + res.StatusCode.ToString());
Response.Write("<br/>Status Description: " + res.StatusDescription);
if (ex.InnerException != null)
{
Response.Write("<br/>innerexception: " + ex.InnerException.Message);
}
if (ex.Source.Length > 0)
Response.Write("<br/>source: " + ex.Source.ToString());
if (res != null)
{
for (int i = 0; i < res.Headers.Count; i++)
{
Response.Write("<br/>headers: " + i.ToString() + ": " + res.Headers[i]);
}
}
}
}
But in this row:
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
I get this Error:
Any why I get this error and how to fix it?
Thank you in advance.
Try setting the Accept header in your HTTP request. Something like this:
Accept: text/html,*/*;q=0.9
HTTP 406 indicates that either this header is expected but missing, or that it was present but did not specify a Content-Type that is compatible with the resource (e.g. asking for Accept: text/html when requesting a JPEG image.)
See also the Accept-Charset, Accept-Encoding, and Accept-Language headers which can also trigger this status code.
My issue had to do with format=XML > changing it to format=json and changing both the accept and content type headers to appliocation/json, returns the emails which i was trying to GET
Get Yahoo Contact List in C# application
Related
I'm currently taking input from a registration form and download the input detail as a text file. the downloaded textfile result is : JimJone03/09/1998 00:00:00xxx#gmail.com 230436315
I want the result to be displayed in column format.
For example:
Jim Jone
03/09/98
xxx#gmail.com
+23057xxx556
This is what I have tried:
public ActionResult Create(Information information)
{
var byteArray = Encoding.ASCII.GetBytes(information.FirstName + ""
+ information.Surname + "" + information.DOB + ""
+ information.Email + " " + information.Tel);
var stream = new MemoryStream(byteArray);
return File(stream, "text/plain", "your_file_name.txt");
}
You can try to use regex to match them:
var input = "Jim Jone 03/09/98 xxx#gmail.com +23057897765";
var name = new Regex("^[a-zA-Z\\s]+").Match(input);
var birthday = new Regex("\\d{1,2}\\/\\d{1,2}\\/\\d{1,2}").Match(input);
var email = new Regex(#"([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)").Match(input);
var tel = new Regex("\\+\\d+").Match(input);
Console.WriteLine("Input: " + "\"" + input + "\"");
Console.WriteLine("Name: " + "\"" + name.Value.Substring(0, name.Value.Length - 1) + "\"");
Console.WriteLine("Birthday: " + "\"" + birthday.Value + "\"");
Console.WriteLine("Email: " + "\"" + email.Value + "\"");
Console.WriteLine("Tel: " + "\"" + tel.Value + "\"");
Output:
Then, you can write them all to your text file line-by-line.
Why don't you just use Environment.NewLine?
var byteArray = Encoding.ASCII.GetBytes($"{information.FirstName}{Environment.NewLine}{information.Surname}{Environment.NewLine}{information.DOB}{Environment.NewLine}{information.Email}{Environment.NewLine}{information.Tel}");
This should add a 'new line' after each value in your file.
I set the code for sending the photo to telegram, first is working on my localhost, after Update the telegram.bot package to ver 9.0.0 and publish to sever dosen't work at localhost and server.
i use the try/catch for sending Text instead of photo and now they not working, it is mean the Try block is working but it can't effect.
if (offerListDetail != null)
{
StringBuilder botTextA2 = new StringBuilder();
StringBuilder botTextB2 = new StringBuilder();
string remoteImgPath = offerListDetail.OFL_OfferImageUrl;
Uri remoteImgPathUri = new Uri(remoteImgPath);
string remoteImgPathWithoutQuery = remoteImgPathUri.GetLeftPart(UriPartial.Path);
string fileName = Path.GetFileName(remoteImgPathWithoutQuery);
string localPath = Server.MapPath("~/Images/telegram/"); //AppDomain.CurrentDomain.BaseDirectory + "Images/telegram/" + fileName;
WebClient webClient = new WebClient();
webClient.DownloadFile(remoteImgPath, localPath + fileName);
var botphoto = new FileToSend()
{
Content = OpenFile(localPath + fileName),
Filename = fileName
};
//var botClient = new Telegram.Bot.Api("157612108:AAFr4y7WWT32xX41EMOVkmEW19pIgcHImv4"); // استانبولیار
var botClient = new Telegram.Bot.Api("186221188:AAHrihjOH7__4vlF0DCNWLEzYQ3p3ORO0_k"); // ربات ری را
try
{
botTextA2.AppendLine("🔍 http://order.reera.ir/offers.aspx?offer=" + offerListDetail.OFL_ID);
botTextA2.AppendLine("📢 " + offerListDetail.OFL_OfferName);
botTextA2.AppendLine("📌 " + offerListDetail.brn_Name);
botTextA2.AppendLine("🕔 مهلت " + offerListDetail.remainday + " روز");
botTextA2.AppendLine("📦 سفارش در http://order.reera.ir");
botTextA2.AppendLine("📝 یا تلگرام #reerabrand");
string botTextA = botTextA2.ToString().Replace(Environment.NewLine, "\n");
botClient.SendPhoto("#istanbulyar", botphoto, "ddd");//botTextA);
botClient.SendPhoto("#reera", botphoto, "ddd");//botTextA);
}
catch
{
botTextB2.AppendLine(offerListDetail.OFL_OfferImageUrl);
botTextB2.AppendLine("*********************************");
botTextB2.AppendLine("📢<b> حراجی " + offerListDetail.OFL_OfferName + "</b> ");
botTextB2.AppendLine("📌<i> توسط وبسایت " + offerListDetail.brn_Name + "</i> ");
botTextB2.AppendLine("🕔 <b>مهلت خرید تا " + offerListDetail.remainday + " روز دیگر</b> ");
botTextB2.AppendLine("🔍 <a href='http://order.reera.ir/offers.aspx?offer=" + offerListDetail.OFL_ID + "'> مشاهده بوتیک </a> ");
botTextB2.AppendLine("");
botTextB2.AppendLine("📦 سفارش در http://order.reera.ir");
botTextB2.AppendLine("📝 یا تلگرام #reerabrand");
string botTextB = botTextB2.ToString().Replace(Environment.NewLine, "\n");
botClient.SendTextMessage("#istanbulyar", botTextB, parseMode: ParseMode.Html);
botClient.SendTextMessage("#reera", botTextB, disableNotification: true, parseMode: ParseMode.Html);
}
}
read picture with stream
example
string pic = "نام عکس مورد نظر";
string yourpath = Environment.CurrentDirectory + #"\Pic\"+pic;
FileStream stream = new FileStream(yourpath, FileMode.Open, FileAccess.Read);
FileToSend fs = new FileToSend("photo3.jpg",stream);
bot.MakeRequestAsync(new SendPhoto(update.Message.Chat.Id, fs)).Wait();
SenditemsTableAdapter sen = new SenditemsTableAdapter();
RegistrationTableAdapter reg = new RegistrationTableAdapter();
SendSMS sendsms = new SendSMS();
Here using tableAdapter
DS.RegistrationDataTable rtable = reg.GetDataByUsername(Session["username"].ToString());
if (rtable.Rows.Count > 0)
{
DS.RegistrationRow rrow = (DS.RegistrationRow)rtable.Rows[0];
int smscount = Convert.ToInt32(sen.Sumcredit(Session["username"].ToString()));
string username = rrow.Username;
// int smscount=0;
string MainString2 = txtmobileno.Text;
string[] Split2 = MainString2.Split(new Char[] { ',' });
string sendid = rrow.Senderid;
int CreditLmt = rrow.Creditlimit;
if (smscount <= CreditLmt)
{
if (rrow.Validitydate >= Convert.ToDateTime(DateTime.Now.ToString()))
{
for (int i = 0; i < Split2.Length; i++)
{
int credit = txtmessage.Text.Length / 160;
credit++;
DateTime date = DateTime.Now;
SqlConnection connection2 = new SqlConnection(con);
connection2.Open();
SqlCommand cmd1 = null;
string str = " insert into [Senditems] values('" + username + "','" + sendid + "', '" + Split2[i] + "',N'" + txtmessage.Text + "','Request.Url.AbsolutePath',' Request.UserHostAddress','Request.Browser.Platform + Request.Browser.Browser', '" + credit + "','" + date + "')";
cmd1 = new SqlCommand(str, connection2);
cmd1.ExecuteNonQuery();
string message = Convert.ToString(SqlHelper.ExecuteScalar(con, CommandType.Text, "SELECT message FROM senditems WHERE id = (SELECT MAX(id) FROM senditems)"));
sendsms.send(message, Split2[i], sendid);
connection2.Close();
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "<script>alert('Your message send successfully');</script>", false);
reset();
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "<script>alert('Cant send sms because your validity is expired');</script>", false);
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "<script>alert('Cant send sms because you dont have credit');</script>", false);
}
}
In the button click events i have using " sendsms.send(txtmobileno.Text, Split2[i], sendid);" this method for send sms to mobile.
strUrl = "http://onlinesms.in/api/sendValidSMSdataUrl.php?login=" + user + "&pword=" + pass +
"&msg=" + HttpUtility.UrlEncode(Message) +
"&senderid=" + sendId +
"&mobnum=" + mobNum;
WebRequest request = HttpWebRequest.Create(strUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = (Stream)response.GetResponseStream();
StreamReader readStream = new StreamReader(s);
string dataString = readStream.ReadToEnd();
response.Close();
s.Close();
readStream.Close();
And using this url to send sms.I have insert message into table is properly and i can get message to mobile ok but getting message ???????????? like this .
I want get sms properly pls any bady help.
I think it all depends of how the website API is converting back your URL string. In my opinion, I think it is safer to use the Uri.EscapeDataString() function instead of the HttpUtility.UrlEncode() because in a space you get the %20 instead of the + sign which may screw up your message.
I am downloading data from yahoo stocks using the Web.DownloadString(); the site will have multiply users so I need to have the client send the download request rather than the server to avoid getting blocked from sending too many request from the servers Ip address. I can't find a way to run it on the client side and am looking for assistance making it run from client rather than server.
below is a poorly formatted function that I plan to clean up that I am using right now
I plan only do use the part required to get the data run client side and the rest run server I have just yet to clean up my code.
Public void DownloadData()
{
string csvData = null;
string month1 = Convert.ToString(DropDownList1.SelectedIndex);
string month2 = Convert.ToString(DropDownList2.SelectedIndex);
string Temp = "http://ichart.finance.yahoo.com/table.csv?s=" + SymbolName.Text + "&d=" + month2 + "&e=" + TextBox3.Text + "&f=" + TextBox4.Text + "&g=d&a=" + month1 + "&b=" + TextBox1.Text + "&c=" + TextBox2.Text + "&ignore=.csv";
string FileRead;
List<string> Remove1 = new List<string>();
string path = System.AppDomain.CurrentDomain.BaseDirectory;
using (WebClient web = new WebClient())
{
try
{
csvData = web.DownloadString(Temp);
}
catch
{
}
}
if (csvData != null && csvData != "")
{
File.WriteAllText(path + "\\MyTest.txt", csvData);
}
System.IO.StreamReader file = new System.IO.StreamReader(path + "\\MyTest.txt");
while ((FileRead = file.ReadLine()) != null) //reads from file
{
Remove1.Add(FileRead);
}
file.Close();
csvData = csvData.Replace("Date,Open,High,Low,Close,Volume,Adj Close", "");
List<stock> prices = YahooFinance.Parse(csvData);
double Lowest = 0;
foreach (stock price in prices) // finds lowest value to addjust priceing
{
if (Lowest == 0)
{
Lowest = Convert.ToDouble(price.low);
}
if (Lowest > Convert.ToDouble(price.low))
{
Lowest = Convert.ToDouble(price.low);
}
}
// new double[] { Convert.ToDouble(price.low), Convert.ToDouble(price.high), Convert.ToDouble(price.Open), Convert.ToDouble(price.close) }
Chart1.ChartAreas[0].AxisX.Interval = 2;
Chart2.ChartAreas[0].AxisX.Interval = 2;
Chart1.ChartAreas[0].AxisX.Maximum = prices.Count + 20;
Chart1.ChartAreas[0].AxisY.Minimum = Lowest - 3;
foreach (stock price in prices)
{
Chart1.Series[0].Points.AddXY(price.date, Convert.ToDouble(price.low), Convert.ToDouble(price.high), Convert.ToDouble(price.Open), Convert.ToDouble(price.close));
Chart2.Series[0].Points.AddXY(price.date, Convert.ToDouble(price.Volume));
}
}
`
I'm having trouble with the log parser, punctually on the use of the function STRCAT parameter with CASE, using log parser the query works perfectly and using a simple STRCAT without CASE the query works even using c#, the problem starts when i use CASE. Am I missing something?
Here's the error:
CLogQueryClass: Error 8007064f: Execute: error parsing query: Syntax Error: : cannot find closing parenthesys for function STRCAT [ SQL query syntax invalid or unsupported. ]
string query = "SELECT " + " STRCAT('" + entry.Name +"'";
query += #", CASE INDEX_OF(SUBSTR(cs-uri-stem,1), '/')
WHEN 'NULL' THEN 'DEFAULTAPPPOOL'
ELSE EXTRACT_TOKEN(cs-uri-stem,1,'/')
END";
query += ") AS APPPOOL";
query += ", '" + Environment.MachineName + "' as server";
query += ", '" + entry.Name + "' as site";
query += ", cs-uri-stem as csUriStem";
query += ", c-ip as cIp, sc-status as scStatus";
query += ", sc-bytes as scBytes";
query += ", cs-bytes as csBytes";
query += ", time-taken as timeTaken";
query += " FROM " + logAddress + "\\" + yesterdayLogName;
// Initialize a LogQuery object
logQuery = new LogQueryClass();
logRecordSet = logQuery.Execute(query,new COMIISW3CInputContextClass());
//SHOWS RESULT
for (; !logRecordSet.atEnd(); logRecordSet.moveNext())
{
logrecord = logRecordSet.getRecord();
int i = 0;
while (i < 9)
{
Console.WriteLine(logrecord.getValue(i));
i++;
}
Thanks
First, it looks like you are mixing types. The CASE INDEX_OF(SUBSTR(cs-uri-stem,1), '/') WHEN 'NULL' compares an integer to string. This should be:
CASE INDEX_OF(SUBSTR(cs-uri-stem,1), '/')
WHEN NULL THEN 'DEFAULTAPPPOOL'
ELSE EXTRACT_TOKEN(cs-uri-stem,1,'/')
END
The error complains about finding the close parenthesis, but I've found that parsing errors can result in misleading error messages with LogParser.
Second, I've tested the following in C# targeted at .NET 3.5 (4.0 had an issue with embedded type. Similar to this...):
string logAddress = "C:\\Path\\to\\consolidatedFile";
string entryName = "blah";
string yesterdayLogName = "fileName.log";
string query = "SELECT " + " STRCAT('" + entryName + "'"
+ ", CASE INDEX_OF(SUBSTR(cs-uri-stem,1), '/') "
+ "WHEN NULL THEN 'DEFAULTAPPPOOL' "
+ "ELSE EXTRACT_TOKEN(cs-uri-stem,1,'/') "
+ "END"
+ ") AS APPPOOL"
+ ", '" + Environment.MachineName + "' as server"
+ ", '" + entryName + "' as site"
+ ", cs-uri-stem as csUriStem"
+ ", c-ip as cIp, sc-status as scStatus"
+ ", sc-bytes as scBytes"
+ ", cs-bytes as csBytes"
+ ", time-taken as timeTaken"
+ " FROM " + logAddress + "\\" + yesterdayLogName;
// Initialize a LogQuery object
COMW3CInputContextClassClass ctx = new COMW3CInputContextClassClass();
//LogQueryClass logQuery = new LogQueryClass();
LogQueryClass logQuery = new LogQueryClassClass();
//ILogRecordset logRecordSet = logQuery.Execute(query, new COMIISW3CInputContextClass());
ILogRecordset logRecordSet = logQuery.Execute(query, ctx);
//SHOWS RESULT
for (; !logRecordSet.atEnd(); logRecordSet.moveNext())
{
ILogRecord logrecord = logRecordSet.getRecord();
int i = 0;
while (i < 9)
{
Console.WriteLine(logrecord.getValue(i));
i++;
}
}
This ran successfully and return results. I commented out the lines initially presented since when I used them nothing returned on the console. That might be a difference of the code not presented. Finally, I substituted a string entryName for the entry.Name object assuming that it returns a string.
I hope this helps.