How to get Telegram channel Profile Photo with TelegramBotClient - telegram

I'm using C# TelegramBotClient library.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var bot = new TelegramBotClient("apiKey");
var chat = await bot.GetChatAsync("#channelName");
What should I do with BigFileId to get image?

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var bot = new TelegramBotClient("apiKey");
var chat = await bot.GetChatAsync("#channelName")
Telegram.Bot.Types.File p = await bot.GetFileAsync(chat.Photo.BigFileId);
string filePath = p.FilePath;
using (var outputStream = new MemoryStream())
{
var file = bot.GetInfoAndDownloadFileAsync(p.FileId, outputStream).GetAwaiter().GetResult();
var array = outputStream.ToArray();
using (var ms = new MemoryStream(array))
{
var image = Image.FromStream(ms);
image.Save("C:\\test\\image.jpg", ImageFormat.Jpeg);
}
}

Related

Query string encryption in angular and decrypt from asp.net

I want to encrypt my query string in Angular project and read it from asp.net page.
I have given my query string and AES encryption code below.
Angular Code:-
let lstrquerystring="username=visakah99$password=test";
let iv2 = CryptoJS.enc.Utf8.parse('Test123');
lstrcriptedtext = CryptoJS.AES.encrypt(lstrquerystring, 'Test123',
{
keySize: 128 / 8,
padding:CryptoJS.pad.ZeroPadding,
iv: iv2}
).toString();
window.location.href="http://localhost:2081/validate.aspx?am="+lstrcriptedtext;
.Net code
var sEncryptionKey="Test123";
var cipherText=this is the query string;
var keybytes = Encoding.UTF8.GetBytes(sEncryptionKey);
var iv = Encoding.UTF8.GetBytes(sEncryptionKey);
var encrypted = Convert.FromBase64String(cipherText);
using (var rijAlg = new RijndaelManaged())
{
//Settings
rijAlg.Mode = CipherMode.CBC;
rijAlg.Padding = PaddingMode.Zeros;
rijAlg.FeedbackSize = 128;
rijAlg.Key = key;
rijAlg.IV = iv;
// Create a decrytor to perform the stream transform.
var decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
try
{
// Create the streams used for decryption.
using (var msDecrypt = new MemoryStream(cipherText))
{
using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (var srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
plaintext = "keyError";
}
}
But the plaintext response is "�����H.Y���k4Ew"�K>>B�p&�z�\u0090����_�\u0002\u000f�\u001eW�\n4�\u000e��\g믑ȱ�\rn�ⅼ\u0005��\u0002��K�\u001b��\a����!k>\u00171Y����6������#bw�ô���ܓ\t
How do we get above text readable?
Thanks in advance.

Can i use putblock as append blob?

So I am trying to upload file chunk by chunk...
Can PutBlock be used to append to an existing BlockBlob in Azure from this example...
I am uploading a 20mb file but finally, when I see it on the container it is 7mb and when I download blob it is broken... What am I doing wrong?
public async Task AppendBlobOnAsset(Stream stream, MediaServiceRequest request)
{
var cloudBlobContainer = new CloudBlobContainer(request.InputAssetStorageUri);
var blockBlob = cloudBlobContainer.GetBlockBlobReference(request.BlobName);
var blockList = new List<ListBlockItem>();
var blockListItems = new List<string>();
if (true)
{
var blocks = await blockBlob.DownloadBlockListAsync();
blockList = blocks.ToList();
blockListItems = blockList.Select(x => x.Name).ToList();
}
//string blockId = Guid.NewGuid().ToString("m");
string blockId = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("0000005"));
blockBlob.PutBlock(blockId, stream, null);
blockListItems.Add(blockId);
blockBlob.PutBlockList(blockListItems);
}
using var file = File.OpenRead("C:\\Projects\\file.mp4");
int bytesRead;
var appendBlobMaxAppendBlockBytes = 4000000;
var buffer = new byte[appendBlobMaxAppendBlockBytes];
while ((bytesRead = await file.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
var newArray = new Span<byte>(buffer, 0, bytesRead).ToArray();
Stream stream = new MemoryStream(newArray);
stream.Position = 0;
await AppendBlobOnAsset(stream, request);
}
public async Task AppendBlobOnAssetAsync(int blockId, Stream stream, MediaServiceRequest request)
{
var cloudBlobContainer = new CloudBlobContainer(request.InputAssetStorageUri);
var blockBlob = cloudBlobContainer.GetBlockBlobReference(request.BlobName);
var blockItems = new List<ListBlockItem>();
var blockItemIds = new List<string>();
if (blockId > 0)
{
var blocks = await blockBlob.DownloadBlockListAsync();
blockItems = blocks.ToList();
blockItemIds = blockItems.Select(x => x.Name).ToList();
}
var Id = Convert.ToBase64String(Encoding.UTF8.GetBytes(blockId.ToString(CultureInfo.InvariantCulture).PadLeft(30, '0')));
blockBlob.PutBlock(Id, stream, null);
blockItemIds.Add(Id);
blockBlob.PutBlockList(blockItemIds);
}

How to set the Content Type of HttpClient

I'm uploading an image.
I want to set the value of Content-Type="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN"
using the code :
HttpRequestMessage request=new HttpRequestMessage();
request.Content.Headers.ContentType="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN";
or request.Header.ContentType="multipart/form-data; boundary=----WebKitFormBoundaryFoxUxCRayQhs5eNN";
it will cause an error:one of the identified items was in an invalid format.
if only set of "multipart/form-data" it will be ok but can not upload the file.
How to set it?
Here are some code snippets you can refer to:
using (var client = new HttpClient())
using (var fileStream = File.Open(fileName, FileMode.Open, FileAccess.Read)
using (var streamContent = new StreamContent(fileStream))
{
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
streamContent.Headers.ContentDisposition.Name = "\"file\"";
streamContent.Headers.ContentDisposition.FileName = "\"" + fileName + "\"";
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
string boundary = "WebKitFormBoundaryFoxUxCRayQhs5eNN";
var fContent = new MultipartFormDataContent(boundary);
fContent.Headers.Remove("Content-Type");
fContent.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);
fContent.Add(streamContent);
var response = await client.PostAsync(new Uri(url), fContent);
response.EnsureSuccessStatusCode();
}
if you use HttpWebRequest,you could refer to this:https://stackoverflow.com/a/20000831/10768653

Throwing an exception like "Operation time out"

I am trying to upload file on oracle cloud infrastructure iaas but found error like operation time out while writing stream using GetRequestStream().Please also check whether the file that I trying to post is in correct order or not.
FileInfo f = new FileInfo(FileUpload1.FileName);
byte[] filebyte =FileUpload1.FileBytes;
var postdata = Encoding.UTF8.GetBytes(filebyte.ToString());
var tenancyId = ConfigurationManager.AppSettings["BMCTenancyId"];
var userId = ConfigurationManager.AppSettings["BMCUserId"];
var fingerprint = ConfigurationManager.AppSettings["BMCFingerprint"];
var privateKeyPath = ConfigurationManager.AppSettings["BMCPrivateKeyPath"];
var privateKeyPassphrase = ConfigurationManager.AppSettings["BMCPrivateKeyPassphrase"];
var signer = new RequestSigner(tenancyId, userId, fingerprint, privateKeyPath, privateKeyPassphrase);
// ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var uri = new Uri($"https://objectstorage.us-phoenix-1.oraclecloud.com/");
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/json";
request.SendChunked = true;
request.ContentType = "text/plain";
request.KeepAlive = true;
request.AllowWriteStreamBuffering = false;
request.ContentLength =postdata.Length;
try
{
using (var stream = request.GetRequestStream())
{
stream.Write(postdata, 0, postdata.Length);
}
}
catch(Exception ex)
{
Response.Write("testing"+ex.Message+"Tedting");
}
request.Headers["x-content-sha256"] = Convert.ToBase64String(SHA256.Create().ComputeHash(postdata));
You'll need to update the URL to the following format:
var uri = new Uri($"https://objectstorage.us-phoenix-1.oraclecloud.com/n/{namespaceName}/b/{bucketName}/o/{objectName}");
Docs: https://docs.cloud.oracle.com/iaas/api/#/en/objectstorage/20160918/Object/PutObject
If you are still receiving an error after updating the URL please edit the question to include the full error you are getting.

ASP .Net Web API downloading images as binary

I want to try to use Web API make a rest call but I want the response to be the actual binary image stored in a database, not a JSON base64 encoded string. Anyone got some pointers on this?
Update-
This is what I ended up implementing:
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(new MemoryStream(profile.Avatar));
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "avatar.png";
return result;
You can set the response content to a StreamContent object:
var fileStream = new FileStream(path, FileMode.Open);
var resp = new HttpResponseMessage()
{
Content = new StreamContent(fileStream)
};
// Find the MIME type
string mimeType = _extensions[Path.GetExtension(path)];
resp.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
While this has been marked as answered, it wasn't quite what I wanted, so I kept looking. Now that I've figured it out, here's what I've got:
public FileContentResult GetFile(string id)
{
byte[] fileContents;
using (MemoryStream memoryStream = new MemoryStream())
{
using (Bitmap image = new Bitmap(WebRequest.Create(myURL).GetResponse().GetResponseStream()))
image.Save(memoryStream, ImageFormat.Jpeg);
fileContents = memoryStream.ToArray();
}
return new FileContentResult(fileContents, "image/jpg");
}
Granted, that's for getting an image through a URL. If you just want to grab an image off the file server, I'd imagine you replace this line:
using (Bitmap image = new Bitmap(WebRequest.Create(myURL).GetResponse().GetResponseStream()))
With this:
using (Bitmap image = new Bitmap(myFilePath))
EDIT: Never mind, this is for regular MVC. for Web API, I have this:
public HttpResponseMessage Get(string id)
{
string fileName = string.Format("{0}.jpg", id);
if (!FileProvider.Exists(fileName))
throw new HttpResponseException(HttpStatusCode.NotFound);
FileStream fileStream = FileProvider.Open(fileName);
HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(fileStream) };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
response.Content.Headers.ContentLength = FileProvider.GetLength(fileName);
return response;
}
Which is quite similar to what OP has.
I did this exact thing. Here is my code:
if (!String.IsNullOrWhiteSpace(imageName))
{
var savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine(uploadPath, imageName));
var image = System.Drawing.Image.FromFile(savedFileName);
if (ImageFormat.Jpeg.Equals(image.RawFormat))
{
// JPEG
using(var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Jpeg);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
else if (ImageFormat.Png.Equals(image.RawFormat))
{
// PNG
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Png);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
else if (ImageFormat.Gif.Equals(image.RawFormat))
{
// GIF
using (var memoryStream = new MemoryStream())
{
image.Save(memoryStream, ImageFormat.Gif);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memoryStream.ToArray())
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/gif");
result.Content.Headers.ContentLength = memoryStream.Length;
return result;
}
}
}
And then on the client:
var client = new HttpClient();
var imageName = product.ImageUrl.Replace("~/Uploads/", "");
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
Properties.Settings.Default.DeviceMediaPath + "\\" + imageName);
var response =
client.GetAsync(apiUrl + "/Image?apiLoginId=" + apiLoginId + "&authorizationToken=" + authToken +
"&imageName=" + product.ImageUrl.Replace("~/Uploads/","")).Result;
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsByteArrayAsync().Result;
using (var ms = new MemoryStream(data))
{
using (var fs = File.Create(path))
{
ms.CopyTo(fs);
}
}
result = true;
}
else
{
result = false;
break;
}
This task is much easily achieved without using WebAPI. I would implement a custom HTTP handler for a unique extension, and return the binary response there. The plus is that you can also modify the HTTP Response headers and content type, so you have absolute control over what is returned.
You can devise a URL pattern (defining how you know what image to return based on its URL), and keep those URLs in your API resources. Once the URL is returned in the API response, it can be directly requested by the browser, and will reach your HTTP handler, returning the correct image.
Images are static content and have their own role in HTTP and HTML - no need to mix them with the JSON that is used when working with an API.

Resources