upload serialized data using WebClient - asp.net-mvc

Simple requirement . I have a class - User - {userId, userName, age}.
How to serailize a object of the class and sent to a url (using post) using webclient.
Something Like below.
What is the best way to serialise user object into postdata format.
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
client.Credentials = CredentialCache.DefaultNetworkCredentials;
string postData = "orderId=5&status=processed2&advertId=ADV0001a";
byte[] postArray = Encoding.ASCII.GetBytes(postData);
client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
byte[] responseArray = client.UploadData(address, postArray);
var result = Encoding.ASCII.GetString(responseArray);
return result;

I would apply the following simplification to your code:
using (var client = new WebClient())
{
client.Credentials = CredentialCache.DefaultNetworkCredentials;
var data = new NameValueCollection
{
{ "userId", user.Id },
{ "userName", user.Name },
{ "age", user.Age }
};
var responseArray = client.UploadValues(address, data);
return Encoding.ASCII.GetString(responseArray);
}

Related

MS Graph SendMail with attachment

I have problem to send an email with attachment.
Without attachment it works.
If I use the same function and add an attachment to the message I get the following error message:
Code: ErrorRequiredPropertyMissing Message: Required property is missing. ClientRequestId: 2af....
I am using MS Graph v4.0.30319
What am I doing wrong
public static async Task<String> SendMyMailAsync()
{
try
{
var FromSender = new Microsoft.Graph.Recipient()
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "EarlyBird#mail.com"
}
};
byte[] contentBytes = System.IO.File.ReadAllBytes(#"C:\Users\me\Desktop\Test.pdf");
String bs64 = Convert.ToBase64String(contentBytes);
var attachment = new FileAttachment
{
AdditionalData = new Dictionary<string, object>()
{
{"#odata.type","#microsoft.graph.fileAttachment"}
},
//ODataType = "#microsoft.graph.fileAttachment",
ContentType = "application/pdf",
Name = "Test.pdf",
ContentBytes = Convert.FromBase64String(bs64),
IsInline = false,
Size = bs64.Length,
ContentId = "TestMail",
LastModifiedDateTime = DateTime.Now,
Id = "HSDJHEWuDSjfkkfGt",
};
Microsoft.Graph.Message message = new Microsoft.Graph.Message
{
Sender = FromSender,
From = FromSender,
Subject = "Mail no1",
Importance = Microsoft.Graph.Importance.Normal,
Body = new Microsoft.Graph.ItemBody
{
ContentType = Microsoft.Graph.BodyType.Html,
Content = "Hello World",
},
ToRecipients = new List<Microsoft.Graph.Recipient>()
{
new Microsoft.Graph.Recipient
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "EarlyBird#MailNo2.com"
}
}
},
Attachments = new MessageAttachmentsCollectionPage(),
};
// -- If I comment this out I can send the mail without error but without attachment----
message.Attachments.Add(attachment);
message.HasAttachments = true;
//-----------------------------------------------------------------
var request = graphClient.Me.SendMail(message, true);
// Messages[message.Id].Send();// SendMail(message, null);
await request.Request().PostAsync();
return "Mail send OK";
}
catch (ServiceException ex)
{
Console.WriteLine($"Error getting events: {ex.Message}");
return "Send mail error";
}
}
The below code works perfectly fine for me
public static async Task<String> SendMyMailAsync()
{
try
{
var FromSender = new Microsoft.Graph.Recipient()
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "Shiva#nishantsingh.live"
}
};
byte[] contentBytes = System.IO.File.ReadAllBytes(#"C:\Users\Shiva\Desktop\sample.pdf");
String bs64 = Convert.ToBase64String(contentBytes);
var attachment = new FileAttachment
{
AdditionalData = new Dictionary<string, object>()
{
{"#odata.type","#microsoft.graph.fileAttachment"}
},
ContentType = "application/pdf",
Name = "Test.pdf",
ContentBytes = Convert.FromBase64String(bs64),
IsInline = false,
Size = bs64.Length,
ContentId = "TestMail",
LastModifiedDateTime = DateTime.Now,
Id = "HSDJHEWuDSjfkkfGt",
};
Microsoft.Graph.Message message = new Microsoft.Graph.Message
{
Sender = FromSender,
From = FromSender,
Subject = "Mail no1",
Importance = Microsoft.Graph.Importance.Normal,
Body = new Microsoft.Graph.ItemBody
{
ContentType = Microsoft.Graph.BodyType.Html,
Content = "Hello World",
},
ToRecipients = new List<Microsoft.Graph.Recipient>()
{
new Microsoft.Graph.Recipient
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "Shiva#nishantsingh.live"
}
}
},
Attachments = new MessageAttachmentsCollectionPage(),
};
message.HasAttachments = true;
message.Attachments.Add(attachment);
var request = graphClient.Me.SendMail(message, true);
await request.Request().PostAsync();
return "Mail send OK";
}
catch (ServiceException ex)
{
Console.WriteLine($"Error getting events: {ex.Message}");
return "Send mail error";
}
}
You need to make sure that you have the PDF file path correctly specified and the fromSender variable will obviously be yours as you are calling me/sendMail. If you want to send mail from other user's mailbox then you need to have client credential flow setup so that it can give you an App-only token which should have required permissions and you need to change the call something like this var request = graphClient.Users["userid/UPN"].SendMail(message, true);.
I have just updated the MS Graph preview version from
4.0.0-preview.1
to
4.0.0-preview.2
Now everything works as expected
I think it was a bug in preview.1

Web api 2 - Async Post

I'm develop a web api2 where I post json data.
The code of this api is:
public HttpResponseMessage Post(an_lavanderie an_lavanderie)
{
var response = new HttpResponseMessage();
if (!ModelState.IsValid)
{
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception("modello non valido"));
}
bool creato = _repoLavanderie.CreaLavanderia(an_lavanderie);
if (creato == true)
{
response = Request.CreateResponse(HttpStatusCode.OK);
}
else
{
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception("Errore nella creazione"));
}
return response;
}
This code write into db correctly.
My code to POST DATA is this:
var risultato = PostDataAsync();
and the function is
var lav1 = new Lavanderia()
{
rag_soc = "Ragione Sociale",
rag_soc2 = "Ragione sociale2",
indirizzo = "Via Crispi 27",
citta = "Ovada",
provincia = "AL",
isAttiva = "N",
portalkey = "sample string 1",
isPortalVisibile = "S",
cap = "15057"
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:56040/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync("api/CreaLavanderia", lav1);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
MessageBox.Show("Crezione effettuata correttamente");
}
else
{
MessageBox.Show("Creazione non effettuata");
}
}
return "";
Post operation is ok, but when await don't fire.
Is possible that the return Message from webapi is not correct?
Where is the problem?
Thanks.
Since you are using await and you're saying that it's not firing make sure that your method is marked with the keyword async.

JIRA REST API how to add attachment using c#

I am using jira api to add attachment to the issue
According to documentation i have set few things.
submit a header of X-Atlassian-Token: nocheck with the request.
The name of the multipart/form-data parameter that contains attachments must be "file".
resource expects a multipart post.
& when i run my code i get internal server error.
my code is as follows
string postUrl = "http://localhost:8080/rest/api/latest/issue/TES-99/attachments";
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck");
client.BaseAddress = new System.Uri(postUrl);
byte[] cred = UTF8Encoding.UTF8.GetBytes(credentials);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
var content = new MultipartFormDataContent();
var values = new[]
{
new KeyValuePair<string, string>("file", "e:\\z.txt")
};
foreach (var keyValuePair in values)
{
content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
}
var result = client.PostAsync(postUrl, content).Result;
please suggest where i am making mistake
I solved this too. now i am able to add attachment using JIRA API with C#.
i was making mistake with this piece of code.
var values = new[]
{
new KeyValuePair<string, string>("file", "e:\\z.txt")
};
foreach (var keyValuePair in values)
{
content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
}
this is my code.
string postUrl = "http://localhost:8080/rest/api/latest/issue/" + projKey + "/attachments";
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.DefaultRequestHeaders.Add("X-Atlassian-Token", "nocheck");
client.BaseAddress = new System.Uri(postUrl);
byte[] cred = UTF8Encoding.UTF8.GetBytes(credentials);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
MultipartFormDataContent content = new MultipartFormDataContent();
**//The code which solved the problem**
HttpContent fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);
content.Add(fileContent, "file",fileName);
var result = client.PostAsync(postUrl, content).Result;
This is my working code.
[HttpPost]
public async Task<IActionResult> CreateTicketWithAttachent(IFormFile file, [FromQuery] string issuekey)
{
try
{
string url = $"http://jiraurl/rest/api/2/issue/{issuekey}/attachments";
var client = new HttpClient();
var header = new AuthenticationHeaderValue("Basic", "your-auth-key");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = header;
client.DefaultRequestHeaders.Add("X-Atlassian-Token", "no-check");
MultipartFormDataContent multiPartContent = new MultipartFormDataContent("-data-");
ByteArrayContent byteArrayContent;
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
//string fileString = Convert.ToBase64String(fileBytes);
byteArrayContent = new ByteArrayContent(fileBytes);
}
multiPartContent.Add(byteArrayContent, "file", file.FileName);
var response = await client.PostAsync(url, multiPartContent);
var result = response.Content.ReadAsStringAsync().Result;
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw new Exception(result);
return Ok();
}
catch (Exception e)
{
return BadRequest(e);
}
}

How do I to pass value my ViewBag for View in mvc

I have a method which convert my html in a string for export to PDF
only I need convert my html (View) to a string in order to export to PDF
Code:
public string RenderViewToString(Controller controller, string viewName, object viewData)
{
var renderedView = new StringBuilder();
using (var responseWriter = new StringWriter(renderedView))
{
var fakeResponse = new HttpResponse(responseWriter);
var fakeContext = new HttpContext(HttpContext.Current.Request, fakeResponse);
var fakeControllerContext = new ControllerContext(new HttpContextWrapper(fakeContext), controller.ControllerContext.RouteData, controller.ControllerContext.Controller);
var oldContext = HttpContext.Current;
HttpContext.Current = fakeContext;
using (var viewPage = new ViewPage())
{
var html = new HtmlHelper(CreateViewContext(responseWriter, fakeControllerContext), viewPage);
html.RenderPartial(viewName, viewData);
HttpContext.Current = oldContext;
}
}
return renderedView.ToString();
}
But the value is not going to view my ViewBag:
ViewBag.Email = usuario.strUsuarioEmail;
ViewBag.Nome = usuario.strUsuarioNome;
Code Export PDF:
public ActionResult EventoVisualizarPDF()
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["UrlAPI"]);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var id = Session["intCodigoGrupoUsuario"];
var intUsuarioId = Session["intUsuarioId"];
string url = "";
url = "api/usuario/GetBuscaUsuario/" + intUsuarioId;
HttpResponseMessage resposta = client.GetAsync(url).Result;
if (resposta.IsSuccessStatusCode)
{
var usuario = resposta.Content.ReadAsAsync<Usuario>().Result;
ViewBag.Email = usuario.strUsuarioEmail;
ViewBag.Nome = usuario.strUsuarioNome;
}
url = "api/evento/GetEventoByUsuario/" + id;
HttpResponseMessage response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
var eventos = response.Content.ReadAsAsync<IEnumerable<Evento>>().Result;
return this.ViewPdf("Customer report", "RelatorioEventoPDF", eventos.OrderBy(m => m.strEventoCodigo));
}
else
{
string msg = response.IsSuccessStatusCode.ToString();
throw new Exception(msg);
}
}
how do to retrieve the value from my ViewBag in view?
If you're familiar with blob storage in Azure, you can think of the ViewBag as the same abstract type of data store.
I'm assuming that you want to output these values so they can be consumed by your View -> PDF conversion method, so all you need on your view is :
<label id="vbEmail">#ViewBag.Email</label>
<label id="vbNome">#ViewBag.Nome</label>
That will output the values you've set in the controller as HTML.

How do I POST a httpclient to a WEB API? (simple as possible way for my highscore table)

My windows phone client sends a piece of JSON that represents the Name and Score... Should I be using the Class from the Web API instead ? What is the code to send the object to the server rather than the raw json?
private void btnCreateSampleScore_Click(object sender, RoutedEventArgs e)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://punkoutersoftware.azurewebsites.net");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("Bob", "2.65")
});
var result = client.PostAsync("/api/DrunkMeterScore", content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultContent);
//DrunkMeterScore dms = new DrunkMeterScore();
//dms.Name = "Bob";
//dms.Score = 2.42;
}
}
The server is using the plain Web API template
// POST api/DrunkMeterScore
public HttpResponseMessage PostDrunkMeterScore(DrunkMeterScore drunkmeterscore)
{
if (ModelState.IsValid)
{
db.DrunkMeterScores.Add(drunkmeterscore);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, drunkmeterscore);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = drunkmeterscore.DrunkMeterScoreId }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
edit1:
I tried both of these.. They both hang and never come back during the PostAsync calls :(
var client = new HttpClient();
client.BaseAddress = new Uri("http://punkoutersoftware.azurewebsites.net");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var score = new DrunkMeterScore() { Name = "Joe", Score = 2.67 };
//MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
//HttpContent content = new ObjectContent<DrunkMeterScore>(score, jsonFormatter);
//var resp = client.PostAsync("api/DrunkMeterScore", content).Result;
//Uri scoreUri = null;
//HttpResponseMessage response = client.PostAsJsonAsync("api/DrunkMeterScore", score).Result;
//if (response.IsSuccessStatusCode)
//{
// scoreUri = response.Headers.Location;
//}
//else
//{
// Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
//}
To serialize objects you need the ObjectContent class which for the wp8 is only available as an alpha release.
Use the package console to do,
Install-Package Microsoft.AspNet.WebApi.Client -Pre
Should be something like this. I did this from memory so YMMV.
DrunkMeterScore dms = new DrunkMeterScore();
dms.Name = "Bob";
dms.Score = 2.42;
var content = new ObjectContent(dms, new JsonMediaTypeFormatter());
var result = client.PostAsync("/api/DrunkMeterScore", content).Result;

Resources