Attaching an Image to Work item in Visual Studio Team Services (was Visual Studio Online) - api

I'm sending an attachment through the Visual Studio Team Services API and it all look like its fine, until I look at the attachment on the work item.
The attachment should be a picture, but it a little black box with a white cross.
Has anyone had this issue and does anyone know what I've done wrong?
I get the image and convert it to a 64 Base string
FileInfo info = new FileInfo(attachment.Path);
byte[] bytes = File.ReadAllBytes(info.FullName);
String file = Convert.ToBase64String(bytes);
Then I send it to the API. This returns a message saying its been successful.
using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
{
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(getConnectionDetails())));
using (System.Net.Http.HttpResponseMessage response = client.PostAsync(SetURL(url),
new StringContent(binaryString,Encoding.UTF8,"application/json")).Result)
{
response.EnsureSuccessStatusCode();
responseString = await response.Content.ReadAsStringAsync();
}
}
I think its something small, that I'm missing!
This is the link to the document, I have used.
API document

Try it this way:
...
string uri = "https://xxxxxx.visualstudio.com/_apis/wit/attachments?fileName=test.jpg&api-version=1.0";
string filepath = "C:\\images\\test.jpg";
FileStream files = new FileStream(filepath,FileMode.Open);
StreamContent streamcontent = new StreamContent(files);
...
HttpResponseMessage response = hc.PostAsync(uri, streamcontent).Result;
...

Related

How to get microsoft account profile photo after login with application in mvc

With the help of claimprincipal, I'm able to get the details of signedin user as below but its not giving any pic related information as google does:
https://apis.live.net/v5.0/{USER_ID}/picture?type=large
which says The URL contains the path '{user_id}', which isn't supported.
Even tried
https://graph.microsoft.com/v1.0/me/photo/$value
which is asking for access token, but I am not sure what have to be passed
string userName = ClaimsPrincipal.Current.FindFirst("name").Value;
string userEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
Wanted an image which was added in any outlook account
For Image to show.. We have to use beared token and have to convert the image into memory stream and then have to used it.. I have done it in below ways. Hope this help ...
var client = new RestClient("https://login.microsoftonline.com/common/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"code={code}&client_id={OutClientId}&client_secret={SecretKey}&redirect_uri={OutRedirectUrl}&grant_type=authorization_code", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Token jsonContent = JsonConvert.DeserializeObject<Token>(response.Content);
var Token = jsonContent.AccessToken;
var TokenType = jsonContent.TokenType;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
HttpResponseMessage response1 = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photos/96x96/$value");
if (response1.StatusCode == HttpStatusCode.OK)
{
using (Stream responseStream = await response1.Content.ReadAsStreamAsync())
{
MemoryStream ms = new MemoryStream();
responseStream.CopyTo(ms);
byte[] buffer = ms.ToArray();
string result = Convert.ToBase64String(buffer);
HttpContext.Session[AppConstants.UserImage] = String.Format("data:image/gif;base64,{0}", result);
responseStream.Close();
}
}
Is there any reason you are using the live.net apis? Instead of the Microsoft Graph APIs? Microsoft Graph APIs are the future for all user data within Microsoft 365 consumer and commercial accounts.
You can get the Users photo very easily as described here https://learn.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0
GET /me/photo/$value
As you are using ASP.NET MVC, there is an SDK you can use that makes this very easy too.
https://learn.microsoft.com/en-us/graph/sdks/sdks-overview?context=graph%2Fapi%2F1.0&view=graph-rest-1.0

Marketo rest Api create lead

I have a question about this create/Update leads API, http://developers.marketo.com/documentation/rest/createupdate-leads/.
There is no sample code for C# or JAVA. Only ruby available. So I have to try it by myself. But I always get null return from the response.
Here is my code:
private async Task<CreateLeadResponseResult> CreateLead(string token)
{
string url = String.Format(marketoInstanceAddress+"/rest/v1/leads.json?access_token={0}", token);
var fullUri = new Uri(url, UriKind.Absolute);
CreateLeadResponseResult createLeadResponse = new CreateLeadResponseResult();
CreateLeadInput input = new CreateLeadInput { email = "123#123.com", lastName = "Lee", firstName = "testtesttest", postCode = "00000" };
CreateLeadInput input2 = new CreateLeadInput { email = "321#gagaga.com", lastName = "Lio", firstName = "ttttttt", postCode = "00000" };
List<CreateLeadInput> inputList = new List<CreateLeadInput>();
inputList.Add(input);
inputList.Add(input2);
CreateLeadRequest createLeadRequest = new CreateLeadRequest() { input = inputList };
JavaScriptSerializer createJsonString = new JavaScriptSerializer();
string inputJsonString = createJsonString.Serialize(createLeadRequest);
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.PostAsJsonAsync(fullUri.OriginalString, inputJsonString).ConfigureAwait(false);
// I can see the JSON string is in the message body in debugging mode.
if (response.IsSuccessStatusCode)
{
createLeadResponse = await response.Content.ReadAsAsync<CreateLeadResponseResult>();
}
else
{
if (response.StatusCode == HttpStatusCode.Forbidden)
throw new AuthenticationException("Invalid username/password combination.");
else
throw new ApplicationException("Not able to get token");
}
}
return createLeadResponse;}
//get null here.
Thank you.
-C.
The best way to debug this is to capture the exact URL, parameters and JSON that are submitted by your app and try submitting those manually via a tool like Postman (Chrome plug-in) or SOAP UI. Then you see the exact error message, which you can look up here: http://developers.marketo.com/documentation/rest/error-codes/. Based on that you can update your code. I don't know much about Java, but this is how I got my Python code to work.
Your example code was really helpful in getting my own implementation off the ground. Thanks!
After playing with it for a bit, I realized that the JavaScriptSerializer step is unnecessary since PostAsJsonAsync automatically serializes whatever object you pass to it. The double serialization prevents Marketo's API from processing the input.
Also, I agree with Jep that Postman is super helpful. But in the case of this error, Postman was working fine (using the contents of inputJsonString) but my C# code still didn't work properly. So I temporarily modified the code to return a dynamic object instead of a CreateLeadResponseResult. In debugging mode this allowed me to see fields that were discarded because they didn't fit the CreateLeadResponseResult type, which led me to the solution above.

PDF generation in mvc4 with itextsharp

I am working on pdf generation, it is successfully implemented using itextsharp.dll. It’s working fine on local environment after publish also. We have our own server at other site
But same code doesn't work on the server,pdf is not generated instead it gives an error: 'The document has no pages.'
Initially I thought it is due to no data in document but it works locally with or without data in the document.
I had code implemented as follows to make a web request Is any problem in that ??
try
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strPdfData + "?objpatId=" + patID);
var response = myHttpWebRequest.GetResponse();
myHttpWebRequest.Timeout = 900000;
var stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
content = sr.ReadToEnd();
}
create a method in the controller:
[HttpGet]
public JsonResult GetFile()
{
var json = new WebClient().DownloadFile(string address, string fileName);
//This code is just to convert the file to json you can keep it in file format and send to the view
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var oc = Newtonsoft.Json.JsonConvert.DeserializeObject<countdata[]>(Convert.ToString(result.countdata));
return Json(oc, JsonRequestBehavior.AllowGet);
}
In the view just call this function:
#Url.Action('genPDF','GetFile');

Windows Store 8.1: WebView.NavigateToStream does not work when altering stream

I am currently trying to use the WebView to display encrypted data (using DPP). The issue is that I am not able to get the WebView to show anything if the stream is manipulated in any way after reading the StorageFile into an IRandomAccessStream (ie. unencrypt the data).
This issue can easily be reproduced by using the source provided by Microsoft: http://code.msdn.microsoft.com/windowsapps/XAML-WebView-control-sample-58ad63f7
and altering the "StreamUriWinRTResolver" class to convert the IRandomAccessStream to a memory stream and then back again. Basically, in S4_NavToStream.xaml.cs at line 128, change this:
StorageFile f = item as StorageFile;
IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
return stream.GetInputStreamAt(0);
With this:
StorageFile f = item as StorageFile;
IRandomAccessStream randStream = await f.OpenAsync(FileAccessMode.Read);
var stream = randStream.AsStream();
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
return ms.AsInputStream();
This will show a blank page when run. I'm starting to think this is a bug, unless of course I'm using the stream conversions incorrectly. Has anybody tried anything similar?
Thomas Huber has very graciously answered my question over on social.msdn.microsoft.com. Full answer here:
http://social.msdn.microsoft.com/Forums/en-US/f51ab699-66c3-4961-8952-fbe341bf3e23/windows-81-webviewnavigatetostream-does-not-work-when-altering-the-stream
In summary, the issue is around the conversion of the memory stream to an input stream. This is the correct working code:
StorageFile f = item as StorageFile;
IRandomAccessStream randStream = await f.OpenAsync(FileAccessMode.Read);
var stream = randStream.AsStream();
var ms = new MemoryStream();
stream.CopyTo(ms);
InMemoryRandomAccessStream msras = new InMemoryRandomAccessStream();
DataWriter dw = new DataWriter(msras);
dw.WriteBytes(ms.ToArray());
await dw.StoreAsync();
var inputStream= msras.GetInputStreamAt(0);
return inputStream;

Windows Phone VB Web Request

does anybody has an idea how I can perform an asynchronus Post Request in VB.Net for Windows Phone 8?
I tried a lot but nothing worked... also this http://msdn.microsoft.com/de-de/library/system.net.httpwebrequest.begingetrequeststream.aspx didn't work.
Thanks a lot.
I had to figure this out for myself a while ago. Let me see what I can do to help.
Posting a web request is actually simpler than that link shows. Here's what I do.
First, I create a MultipartFormDataContent:
Dim form as New MultipartFormDataContent()
Next, I add each string I want to send like this:
form.Add(New StringContent("String to sent"), "name of the string you are sending")
Next, create a HttpClient:
Dim httpClient as HttpClient = new HttpClient()
Next, we'll create a HttpResponseMessage and post your information to the url of your choice:
Dim response as HttpResponseMessage = Await httpClient.PostAsync("www.yoururl.com/wherever", form)
Then, I usually need the response as a string, so I read the response to a string:
Dim responseString as String = Await response.Content.ReadAsStringAsync()
This will give you the response you wanted, if that's what you wanted.
Here's an example of a method I use:
Public Async Function GetItems() As Task
Dim getUrl As String = "https://myapiurl.com/v3/get"
Dim responseText As String = String.Empty
Dim detailType As String = "complete"
Try
Dim httpClient As HttpClient = New HttpClient()
Dim form As New MultipartFormDataContent()
form.Add(New StringContent(roamingSettings.Values("ConsumerKey").ToString()), "consumer_key")
form.Add(New StringContent(roamingSettings.Values("access_token").ToString()), "access_token")
form.Add(New StringContent(detailType.ToString()), "detailType")
Dim response As HttpResponseMessage = Await httpClient.PostAsync(getUrl, form)
responseText = Await response.Content.ReadAsStringAsync()
Catch ex As Exception
End Try
End Function
If you aren't using the Http client libraries, you need to install them like this:
What you need to do to use the HttpClient, is to navigate in Visual Studio, go to Tools->Library Package Manager->Manage Nuget Packages for this solution. When there, search the online section for HttpClient and make sure you have "Include Prerelease" selected in the listbox above the results. (Default is set to "Stable Only")
Then install the package with the ID of Microsoft.Net.Http
Then you'll need to add an Import statement at the beginning of the document you are using it in.
Let me know if this is what you were looking for.
Thanks,
SonofNun