Upload a post with description and title using facebook c# sdk - windows-phone

I used the following code. Picture is posted successfully with a name but its not able to post message/description with it. Please tell me where i am wrong. Also its not giving any exception.
private void SharePhoto(string _accessToken, string p)
{
var fb = new FacebookClient(_accessToken);
fb.PostCompleted += (o, args) =>
{
if (args.Error != null)
{
if (args.Error.Message.StartsWith("(OAuthException - #190)"))
{
Dispatcher.BeginInvoke(() =>
{ MessageBox.Show("Message Expired"); });
}
else
{
Dispatcher.BeginInvoke(() =>
{ MessageBox.Show(args.Error.Message, "Error", MessageBoxButton.OK); });
}
return;
}
else
{
Dispatcher.BeginInvoke(() =>
{ MessageBox.Show("Image Posted"); });
}
};
var fbupload = new FacebookMediaObject
{
FileName = "facebook.jpg",
ContentType = "image/jpeg"
};
StreamResourceInfo sri =Application.GetResourceStream(new Uri("facebook.jpg",UriKind.Relative));
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(sri.Stream);
var loadedImage = new WriteableBitmap(bitmap);
using (MemoryStream ms = new MemoryStream())
{
loadedImage.SaveJpeg(ms, loadedImage.PixelWidth, loadedImage.PixelHeight, 0, 95);
ms.Seek(0, 0);
byte[] data = new byte[ms.Length];
ms.Read(data, 0, data.Length);
ms.Close();
fbupload.SetValue(data);
}
var parameters = new Dictionary<string, object>();
parameters["message"] = txtMessage.Text;
parameters["description"] = "first ever one";
parameters["name"] = "My FB Pic";
parameters["picture"]=fbupload;
parameters["link"] = new Uri(#"http://www.anyxyz.com", UriKind.Absolute);
fb.PostAsync(#"me/photos", parameters);
}
I used extended permissions as:
private const string extendedPermissions = "user_about_me,read_stream,publish_stream";
Any Help would be greatly appreciated.

Related

Retreive the file name and size uploaded via postman in asp.net core

I have tried the following code ..
When I try out the following code I get 404 content not found. Also my controller doesn't get hit when I try to debug the code ..
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filename not present");
var path = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}
Upload file with size and filename as response:
public async Task<IActionResult> OnPostUploadAsync(IFormFile file)
{
long size = file.Length;//in bytes
if (file.Length > 0)
{
var name = Path.GetRandomFileName();
//var fileOriginName = file.FileName;
var path = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot", name);
using (var stream = System.IO.File.Create(path))
{
await file.CopyToAsync(stream);
}
return Ok(new { size = size, filename = name });
}
else {
return Ok(new { size = 0, filename = ""});
}
}
===============================================
I have an api like below and I had a file test.txt in wwwroot folder.
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filename not present");
var path = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
var contentType = "APPLICATION/octet-stream";
return File(memory, contentType, Path.GetFileName(path));
}
Then when I call localhost:port/home/download?filename=test then I'll get exception that file can't find. And when I call localhost:port/home/Download?filename=test.txt it succeeds.
My API is in an asp.net core MVC project and I think you need to check the contentType.

Azure Logic Apps internal server error 500

Am trying to create a an azure function that is triggered in a Logic Apps,
The functions purpose is to web crawl certain web sites, take the desired information, compare that with a a SQL Server database in Azure, compare if we already have that information if not add it.
My issue is that when ever i run it I get the Server 500 error, I assume its accessing the database that cause. Help?
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log
)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string RequestBody = await new StreamReader(req.Body).ReadToEndAsync();
{
return await CrawlBlog(0, RequestBody);
}
}
private static async Task<IActionResult> CrawlBlog(int Picker, string req)
{
int BlogPicker = Picker;
string TheResult = req;
//Get the url we want to test
var Url = "";
if (BlogPicker == 0)
{
Url = "*********";
}
else if (BlogPicker == 1)
{
Url = "*********";
}
/*
else if (BlogPicker == 2)
{
Url = "https://azure.microsoft.com/en-in/blog/?utm_source=devglan";
}
*/
else
{
TheResult = "False we got a wrong pick";
return (ActionResult)new OkObjectResult
( new {TheResult });
}
var httpClient = new HttpClient();
var html = await httpClient.GetStringAsync(Url);
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
//a list to add all availabel blogs we found
var Blog = new List<BlogStats>();
switch (BlogPicker)
{
case 0:
{
var divs =
htmlDocument.DocumentNode.Descendants("div")
.Where(node => node.GetAttributeValue("class", "").Equals("home_blog_sec_text")).ToList();
foreach (var divo in divs)
{
var Blogo = new BlogStats
{
Summary = divo.Descendants("p").FirstOrDefault().InnerText,
Link = divo.Descendants("a").FirstOrDefault().ChildAttributes("href").FirstOrDefault().Value,
Title = divo.Descendants("a").FirstOrDefault().InnerText
};
Blog.Add(Blogo);
}
break;
}
case 1:
{
var divs =
htmlDocument.DocumentNode.Descendants("div")
.Where(node => node.GetAttributeValue("class", "").Equals("post_header_title two_third last")).ToList();
foreach (var divo in divs)
{
//string TheSummary = "we goofed";
var ThePs = divo.Descendants("p").ToList();
var Blogo = new BlogStats
{
Summary = ThePs[1].GetDirectInnerText(),
Link = divo.Descendants("a").LastOrDefault().ChildAttributes("href").FirstOrDefault().Value,
Title = divo.Descendants("a").FirstOrDefault().InnerText
};
Blog.Add(Blogo);
}
break;
}
}
TheResult = await SqlCheck(Blog[0].Title, Blog[0].Summary, Blog[0].Link); //error 500
return (ActionResult)new OkObjectResult
(
new
{
TheResult
}
);
}
public static async Task<string> SqlCheck(string Tit, string Sumy, string Lin)
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "flygon.database.windows.net";
builder.UserID = "*****";
builder.Password = "********";
builder.InitialCatalog = "torkoal";
System.Data.DataSet ds = new System.Data.DataSet();
SqlConnection connection = new SqlConnection(builder.ConnectionString);
connection.Open();
SqlCommand CheckCommand = new SqlCommand("SELECT * FROM TableBoto WHERE Link = #id3 ", connection);
CheckCommand.Parameters.AddWithValue("#id3", Lin);
SqlDataAdapter dataAdapter = new SqlDataAdapter(CheckCommand);
dataAdapter.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if (i > 0)
{
return $" We got a Duplicates in title : {Tit}";
}
try
{
{
string query = $"insert into TableBoto(Title,Summary,Link) values('{Tit}','{Sumy}','{Lin}');";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = await command.ExecuteReaderAsync();
reader.Close();
}
}
catch (SqlException)
{
// Console.WriteLine(e.ToString());
}
connection.Close();
return $" Success Ign +{Tit} + Ign {Sumy}+ Ign {Lin} Ign Success SQL ";
}
}
500 HTTP status code is a generic code which means that the server was not able to process the request due to some issues, First step would be to add some exception handling to your function and see if the failure occurs and where it occurs.
On Side note, you should not use HTTP client in the way used in the code, you should not new it up every time your function executes, this client should be static in nature. Refer Manage connections in Azure Functions

Get Array of Bytes from ASP.NET WEB API to be rendered in PDF using React/Redux

I have this action on my WEBAPI´s controller using .NET that returns bytes from SSRS report link:
public IHttpActionResult GetReport(int? Id)
{
if (Id == null)
{
return NotFound();
}
var reportServer = ConfigurationManager.AppSettings["Report"];
var reportPath = $"{reportServer}/myReport&Id={Id}&rs:Format=PDF";
WebClient Client = new WebClient();
Client.UseDefaultCredentials = true;
byte[] reportBytes = Client.DownloadData(reportPath);
var reportBase64 = Convert.ToBase64String(reportBytes);
return Ok(reportBase64);
}
When i try to generate the PDF from this return, using this react/redux code ( i am using axios)....
//...code
const reportBlob = new Blob([myReportData], { type: "application/pdf" });
const reportBlobUrl = URL.createObjectURL(reportBlob);
window.open(reportBlobUrl);
.....it oppened a new browser´s tab with PDF template BUT showing PDF Error as: 'FAILED TO LOAD PDF document'.
No anwsers anywhere help me resolving this problem. :(
Note: the 'axios' call it´s returning the same array of bytes as the WEBAPI return, so as the 'myReportData' variable.
So i figured out by my self after 4 days. Anyone that needed this functionality (render the SSRS report in PDF within c# code returning PDF bytes from a ASP.NET WEB API, here is the what you have to do within your webapi controller to generate the PDF bytes from report viewer namespace to be sent to your React app using Redux.
WEB API ASP.NET (.NET Framework 4.6 using VS 2019):
note: first option i´ts commented and works the same way the option 2 that i´d prefer.
// return type is Bytes
[HttpGet]
[Route("api/YourReport/{testId}")]
public async Task<IHttpActionResult> GetYourReportAsync(int? testId)
{
if (testId == null)
{
return NotFound();
}
try
{
// 1. Works in this way without '?' on the end of the URL
// URL should be like this: "http://-yourServerName-/reportserver/ReportExecution2005.asmx"
//ReportExecutionService rs = new ReportExecutionService();
//rs.Credentials = CredentialCache.DefaultCredentials;
//rs.Url = "http://-yourServerNamein here-/reportserver/ReportExecution2005.asmx";
//// Render arguments
//byte[] result = null;
//string reportPath = "/-yourReportsFolderName-/-yourReportName-";
//string format = "PDF";
//string historyID = null;
//string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
//// parameters
//ParameterValue[] parameters = new ParameterValue[1];
//parameters[0] = new ParameterValue();
//parameters[0].Name = "yourId";
//parameters[0].Value = testId.ToString();
//string encoding;
//string mimeType;
//string extension;
//Warning[] warnings = null;
//string[] streamIDs = null;
//ExecutionInfo execInfo = new ExecutionInfo();
//ExecutionHeader execHeader = new ExecutionHeader();
//rs.ExecutionHeaderValue = execHeader;
//execInfo = rs.LoadReport(reportPath, historyID);
//rs.SetExecutionParameters(parameters, "en-us");
//string SessionId = rs.ExecutionHeaderValue.ExecutionID;
//try
//{
//// result type is bytes
// result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
//}
//catch (SoapException)
//{
// throw;
//}
//// below, just in case that you want to save it locally in PDF format.
//try
//{
// FileStream stream = File.Create(#"c:\report.pdf", result.Length);
//
// stream.Write(result, 0, result.Length);
// Console.WriteLine("Result written to the file.");
// stream.Close();
//}
//catch (Exception)
//{
// throw;
//}
//return await Task.Run(() => Ok(result));
// 2. Works this way also with '?' on the end of the URL
// URL should be like this: "http://-yourServerName-/reportserver/ReportExecution2005.asmx?"
using (ReportViewer yourReportViewer = new ReportViewer())
{
yourReportViewer.ProcessingMode = ProcessingMode.Remote;
// get the values from your web.config.
yourReportViewer.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings["youtReport"]);
yourReportViewer.ServerReport.ReportPath = $"/yourReportsFolder/yourReport";
;
ReportParameter testPlanIdParameter = new ReportParameter();
testPlanIdParameter.Name = "yourId";
testPlanIdParameter.Values.Add(testId.ToString());
yourReportViewer.ServerReport.SetParameters(new ReportParameter[] { testIdParameter });
byte[] yourReportBytes = yourReportViewer.ServerReport.Render("PDF");
return await Task.Run(() => Ok(yourReportBytes));
}
}
catch (SoapException)
{
throw;
}
catch (Exception)
{
throw ;
}
}
REACT/REDUX nstrong textote: you have to convert the stream of bytes returned from your WEB API Controller into BLOB format to render it in a new brownser tab in PDF format/type.
a. the button action/behavior
<div className="btn-group-vertical" role="group">
<button className="btn btn-sm btn-success ml-2 mb-2" style={{ width: '160px' }} onClick={(e) => openReport(e, testId)}>
<i className="fas fa-print"></i>
Report
</button>
</div>
b. the component ( i am omiting the redux part (reducers, actions, apiservice...)
openReport(event, item) {
event.preventDefault();
this.props.actions.loadReport(item);
this.setState({ Report: this.props.Report });
const ReportData = this.state.Report;
const b64toBlob = (b64Data, contentType = '', sliceSize = 512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
}
const ReportBlob = b64toBlob(ReportData, 'application/pdf');
const ReportBlobUrl = URL.createObjectURL(ReportBlob);
window.open(ReportBlobUrl);
}

How to convert MailAttachment to MimeKit Attachment

We have to rework how we're sending emails since we are using Amazon SES. In the past, we were using smtp but can't do that in this case. The class that needs updated has taken in a MailMessage object and used smtp to send it. So I'm trying to rework the method to be able to continue to accept the MailMessage object and convert it to a MimeKit MimeMessage. For the most part it's working fine except when it comes to attachments. In the code I have, the attachment gets added and sent, however, when trying to open it appears it's corrupted or something. In my test case I attached a csv file. I could not open it in excel after receiving the email.
public class EmailAbstraction
{
public virtual void Send(MailMessage mailMessage)
{
sendMessage(mailMessage);
}
private static void sendMessage(MailMessage mailMessage)
{
using (var client = new AmazonSimpleEmailServiceClient(AwsConstants.SESAWSKey, AwsConstants.SESAWSSecret, AwsConstants.RegionEndpoint))
{
foreach (var to in mailMessage.To)
{
using (var messageStream = new MemoryStream())
{
var newMessage = new MimeMessage();
var builder = new BodyBuilder
{
HtmlBody = mailMessage.Body
};
newMessage.From.Add(mailMessage.From == null
? new MailboxAddress(EmailConstants.DefaultFromEmailDisplayName, EmailConstants.DefaultFromEmailAddress)
: new MailboxAddress(mailMessage.From.Address));
newMessage.To.Add(new MailboxAddress(to.DisplayName, to.Address));
newMessage.Subject = mailMessage.Subject;
foreach (var attachment in mailMessage.Attachments)
{
builder.Attachments.Add(attachment.Name, attachment.ContentStream);
}
newMessage.Body = builder.ToMessageBody();
newMessage.WriteTo(messageStream);
var request = new SendRawEmailRequest
{
RawMessage = new RawMessage { Data = messageStream }
};
client.SendRawEmail(request);
}
}
}
}
}
And in my test app, I have this.
internal class Program
{
private static void Main(string[] args)
{
var s = GetFileStream();
var m = new MailMessage();
var sender = new MailAddress("info#ourwebsite.com", "info");
m.From = sender;
m.Sender = sender;
m.Body = "test email";
m.Subject = "test subject";
m.To.Add(myemail);
m.Attachments.Add(new Attachment(s, "test-file.csv"));
new EmailAbstraction().Send(m);
}
private static MemoryStream GetFileStream()
{
var stream = new MemoryStream();
var fileStream = File.Open(#"C:\Users\dev\Desktop\test-file.csv", FileMode.Open);
fileStream.CopyTo(stream);
fileStream.Close();
return stream;
}
}
This is just copied from the MimeKit source code:
static MimePart GetMimePart (System.Net.Mail.AttachmentBase item)
{
var mimeType = item.ContentType.ToString ();
var contentType = ContentType.Parse (mimeType);
var attachment = item as System.Net.Mail.Attachment;
MimePart part;
if (contentType.MediaType.Equals ("text", StringComparison.OrdinalIgnoreCase))
part = new TextPart (contentType);
else
part = new MimePart (contentType);
if (attachment != null) {
var disposition = attachment.ContentDisposition.ToString ();
part.ContentDisposition = ContentDisposition.Parse (disposition);
}
switch (item.TransferEncoding) {
case System.Net.Mime.TransferEncoding.QuotedPrintable:
part.ContentTransferEncoding = ContentEncoding.QuotedPrintable;
break;
case System.Net.Mime.TransferEncoding.Base64:
part.ContentTransferEncoding = ContentEncoding.Base64;
break;
case System.Net.Mime.TransferEncoding.SevenBit:
part.ContentTransferEncoding = ContentEncoding.SevenBit;
break;
//case System.Net.Mime.TransferEncoding.EightBit:
// part.ContentTransferEncoding = ContentEncoding.EightBit;
// break;
}
if (item.ContentId != null)
part.ContentId = item.ContentId;
var stream = new MemoryStream ();
item.ContentStream.CopyTo (stream);
stream.Position = 0;
part.Content = new MimeContent (stream);
return part;
}

Win Phone 8.1 : OutOfMemory Exception while downloading large files (30 MB)

I am creating a universal Windows Phone 8.1 App. I am trying to download the file and view it into launcher. I works for small file less than 15 MB files. But when file size is more than 15 MB, I got the out of memory exception.
async private Task<object> GetMailAttachments(string attachNotify)
{
try
{
cmdBarMailItem.IsEnabled = false;
if (await Device.IsNetworkAvailable())
{
cts = new CancellationTokenSource();
// Ignore SSL Certificate which is untrusted,expired and has invalid hostname.
var filter = new HttpBaseProtocolFilter() { AllowUI = false };
filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired);
filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.InvalidName);
// Start calling the soap service #userGetAttachmentByIndex
using (var client = new System.Net.Http.HttpClient(new WinRtHttpClientHandler(filter)))
{
//Prepare parameters which is to be post via soap envelope.
List<KeyValuePair<string, string>> parameter = new List<KeyValuePair<string, string>>();
parameter.Add(new KeyValuePair<string, string>("sessionId", GlobalInfo.SessionID));
parameter.Add(new KeyValuePair<string, string>("attachmentIndex", attachNotify.Split('|')[1].ToString()));
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
client.DefaultRequestHeaders.Add("SOAPAction", "userGetAttachmentByIndex");
var postContent = new StringContent(StringHelper.ConstructSoapRequest(parameter, "userGetAttachmentByIndex"), Encoding.UTF8, "text/xml");
// Getting response from soap service
var response = await client.PostAsync(new Uri(AppEnv.ServiceEndPoint), postContent, cts.Token);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string soapResponse = await response.Content.ReadAsStringAsync();
var soap = XDocument.Parse(soapResponse);
XNamespace ns = "http://service.webservice.cryoserver.ci";
var base64BinaryStr = soap.Descendants(ns + "userGetAttachmentByIndexResponse").First().Descendants(ns + "return").First().Descendants(ns + "attachmentType").First().Descendants(ns + "binaryData").First().Descendants(ns + "base64Binary").First().Value;
await saveStringToLocalFile(base64BinaryStr);
var file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("myTest.pdf");
bool x = await Windows.System.Launcher.LaunchFileAsync(file);
return x;
}
}
}
cmdBarMailItem.IsEnabled = true;
}
catch (TaskCanceledException)
{
PopupRetrieve.IsOpen = false;
ProgressBar.IsVisible = false;
cmdBarMailItem.IsEnabled = true;
}
catch(Exception ex)
{
cmdBarMailItem.IsEnabled = true;
ProgressBar.IsVisible = false;
MessageBox.Show(AlertType.Connectivity);
}
return null;
}
async Task saveStringToLocalFile(string content)
{
try
{
// saves the string 'content' to a file 'filename' in the app's local storage folder
// byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(content.ToCharArray());
byte[] byteArray = Convert.FromBase64String(content);
// create a file with the given filename in the local folder; replace any existing file with the same name
StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("myTest.pdf", CreationCollisionOption.ReplaceExisting);
// write the char array created from the content string into the file
using (var stream = await file.OpenStreamForWriteAsync())
{
stream.Write(byteArray, 0, byteArray.Length);
stream.Flush();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I got the exception on executing the line
string soapResponse = await response.Content.ReadAsStringAsync();
Anybody have an idea why the exception occurs ? What could be possible solution to fix it.
Any help would be appriciable. :)