Telegram SendPhoto() Methode in ASP.NET by Telegram Bot - asp.net

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();

Related

How to save textfile data in column format in ASP.NET MVC

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.

How to get internal shared storage and sd card file paths of document files?

I am trying to get file paths of videos from internal shared storage and sd card.
I have randomly saved videos in random folders in internal shared storage and external storage.
public ArrayList<String> getVideosPath(Activity activity,Context context)
{
listOfAllImages = new ArrayList<String>();
Cursor cursor;
final String[] columns = {MediaStore.Video.Media.DATA, MediaStore.Video.Media._ID};
final String orderBy = MediaStore.Video.Media._ID;
//Stores all the images from the gallery in Cursor
cursor = getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
//Total number of images
int count = cursor.getCount();
//Create an array to store path to all the images
String[] arrPath = new String[count];
for (int i = 0; i < count; i++) {
cursor.moveToPosition(i);
int dataColumnIndex = cursor.getColumnIndex(MediaStore.Video.Media.DATA);
//Store the path of the image
arrPath[i] = cursor.getString(dataColumnIndex);
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(arrPath[i],
MediaStore.Images.Thumbnails.MINI_KIND);
// BitmapFactory.Options options = new BitmapFactory.Options();
// options.inSampleSize = 4;
// Bitmap b = BitmapFactory.decodeFile(arrPath[i], options);
bitmap.add(thumb);
// drawimages_onvideo.add(thumb);
Log.i("PATH", arrPath[i]);
listOfAllImages.add(arrPath[i]);
}
Although it gets the files from sd card and phone storage, the paths are different.
for e.g there are 2 video files one in android storage and one in sd-card and there path are
android storage : /storage/emulated/0/Movies/videoplay.mp4
and
sd-card : /storage/BBF7-A8D2/videos/videoplay.mp4
and i am getting these 2 files but the paths which are displayed to me are these:
/storage/emulated/0/Movies/videoplay.mp4
/storage/emulated/0/Movies/videoplay.mp4
What is wrong ?
this gives me the document files that i required, got help from one of stack over flow links.
public void getDocumentspath(){
listOfAllDocuments = new ArrayList<String>();
Cursor cursor;
String root_sd = Environment.getExternalStorageDirectory().toString();
String pdf = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
String doc = MimeTypeMap.getSingleton().getMimeTypeFromExtension("doc");
String docx = MimeTypeMap.getSingleton().getMimeTypeFromExtension("docx");
String xls = MimeTypeMap.getSingleton().getMimeTypeFromExtension("xls");
String xlsx = MimeTypeMap.getSingleton().getMimeTypeFromExtension("xlsx");
String ppt = MimeTypeMap.getSingleton().getMimeTypeFromExtension("ppt");
String pptx = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pptx");
String txt = MimeTypeMap.getSingleton().getMimeTypeFromExtension("txt");
String rtx = MimeTypeMap.getSingleton().getMimeTypeFromExtension("rtx");
String rtf = MimeTypeMap.getSingleton().getMimeTypeFromExtension("rtf");
String html = MimeTypeMap.getSingleton().getMimeTypeFromExtension("html");
String css = MimeTypeMap.getSingleton().getMimeTypeFromExtension("css");
// String js = MimeTypeMap.getSingleton().getMimeTypeFromExtension("js");
//Table
Uri table = MediaStore.Files.getContentUri("external");
//Column
String[] column = {MediaStore.Files.FileColumns.DATA};
//Where
String where = MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?"
+" OR " +MediaStore.Files.FileColumns.MIME_TYPE + "=?";
//args
String[] args = new String[]{pdf,doc,docx,xls,xlsx,ppt,pptx,txt,rtx,rtf,html,css};
Cursor fileCursor = getContentResolver().query(table, column, where, args, null);
int count = fileCursor.getCount();
//Create an array to store path to all the documents
String[] arrPath = new String[count];
for (int i = 0; i < count; i++) {
fileCursor.moveToPosition(i);
int dataColumnIndex = fileCursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
//Store the path of the document
arrPath[i] = fileCursor.getString(dataColumnIndex);
Bitmap b = ((BitmapDrawable) ResourcesCompat.getDrawable(this.getResources(), R.drawable.documentfile, null)).getBitmap();
bitmap.add(b);
Log.i("PATH", arrPath[i]);
listOfAllDocuments.add(arrPath[i]);
}
}

How to send unicode character sms into mobile using asp.net c#

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.

Http error 406 when I try to access yahoo API

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

How to get a variable replaced with a field name in a LINQ?

string companyName="ABC";
var query = from q in context.Company where q.CompanyName == companyName select q;
Is there any way to replace the q.CompanyName part of the query with a string variable
so that the field used for filtering be a parametric?
I tried
string str1 = "companySize";
string str2 = "q." + str1;
string companySize = "Mid";
var query = from q in context.Company where str2 == companySize select q;
Didn't work.
Been trying to let the user choose the columns for the query.
Read more about both below option at : Dynamic query with Linq
you can use one of this
Use Dynamic LINQ library
Example for the the blog below
string strWhere = string.Empty;
string strOrderBy = string.Empty;
if (!string.IsNullOrEmpty(txtAddress.Text))
strWhere = "Address.StartsWith(\"" + txtAddress.Text + "\")";
if (!string.IsNullOrEmpty(txtEmpId.Text))
{
if(!string.IsNullOrEmpty(strWhere ))
strWhere = " And ";
strWhere = "Id = " + txtEmpId.Text;
}
if (!string.IsNullOrEmpty(txtDesc.Text))
{
if (!string.IsNullOrEmpty(strWhere))
strWhere = " And ";
strWhere = "Desc.StartsWith(\"" + txtDesc.Text + "\")";
}
if (!string.IsNullOrEmpty(txtName.Text))
{
if (!string.IsNullOrEmpty(strWhere))
strWhere = " And ";
strWhere = "Name.StartsWith(\"" + txtName.Text + "\")";
}
EmployeeDataContext edb = new EmployeeDataContext();
var emp = edb.Employees.Where(strWhere);
Predicate Builder
EXample
var predicate = PredicateBuilder.True<employee>();
if(!string.IsNullOrEmpty(txtAddress.Text))
predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text));
if (!string.IsNullOrEmpty(txtEmpId.Text))
predicate = predicate.And(e1 => e1.Id == Convert.ToInt32(txtEmpId.Text));
if (!string.IsNullOrEmpty(txtDesc.Text))
predicate = predicate.And(e1 => e1.Desc.Contains(txtDesc.Text));
if (!string.IsNullOrEmpty(txtName.Text))
predicate = predicate.And(e1 => e1.Name.Contains(txtName.Text));
EmployeeDataContext edb= new EmployeeDataContext();
var emp = edb.Employees.Where(predicate);
If you don't want to use libraries like dynamicLINQ, you can just create the Expression Tree by yourself:
string str1 = "companySize";
string str2 = "q." + str1;
string companySize = "Mid";
var param = Expression.Parameter(typeof(string));
var exp = Expression.Lambda<Func<Company, bool>>(
Expression.Equal(
Expression.Property(param, str1),
Expression.Constant(companySize)),
param);
var query = context.Company.Where(exp);
I think the best way to do this is with built in libraries (and PropertyDescriptor type).
using System.ComponentModel;
void Main()
{
Test test = new Test();
test.CompanyName = "ABC";
object z = TypeDescriptor.GetProperties(test).OfType<PropertyDescriptor>()
.Where(x => x.Name == "CompanyName").Select(x => x.GetValue(test)).FirstOrDefault();
Console.WriteLine(z.ToString());
}
public class Test
{
public string CompanyName { get; set; }
}

Resources