Search code in azure devops projects with REST api - asp.net
i am trying to search code through some project, i didnt succeed to recieve a proper response.
that what i did:
public async void GetProjects()
{
try
{
var personalaccesstoken = "mypersonalPat";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
var httpClient = new HttpClient();
var list = new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, string>("searchText", "a"));
list.Add(new KeyValuePair<string, string>("$top", "10"));
var content = new FormUrlEncodedContent(list);
var response = await httpClient.PostAsync("https://almsearch.dev.azure.com/myorganization/myproject/_apis/search/codesearchresults?api-version=5.1-preview.1", content);
var res = await response.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
in the response i got 203 status message, in the res i got this (formatted as XML):
Azure DevOps Services | Sign In var __vssPageContext = {"webContext":{"user":{"id":"aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa","name":"Anonymous","email":"","uniqueName":"TEAM FOUNDATION\\Anonymous"},"host":{"id":"7d0cc8e9-39e8-4313-9ff3-23ace0f8f4cf","name":"TEAM FOUNDATION","uri":"https://spsprodweu4.vssps.visualstudio.com/","relativeUri":"/","hostType":"deployment","scheme":"https","authority":"spsprodweu4.vssps.visualstudio.com"}},"moduleLoaderConfig":{"baseUrl":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/","paths":{"Profile/Scripts/Resources":"en-US","VSS/Resources":"en-US","Account/Scripts/Resources":"en-US","UserManagement/Scripts/Resources":"en-US","Authentication/Scripts/Resources":"en-US"},"map":{},"contributionPaths":{"VSS":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/VSS","pathType":"default"},"VSS/Resources":{"value":"en-US","pathType":"resource"},"q":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/q","pathType":"default"},"knockout":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/knockout","pathType":"default"},"mousetrap":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/mousetrap","pathType":"default"},"mustache":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/mustache","pathType":"default"},"react":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/react.15.3","pathType":"default"},"react-dom":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/react-dom.15.3","pathType":"default"},"react-transition-group":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/react-transition-group.15.3","pathType":"default"},"jQueryUI":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/jQueryUI","pathType":"default"},"jquery":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/jquery","pathType":"default"},"OfficeFabric":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/OfficeFabric","pathType":"default"},"tslib":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/tslib","pathType":"default"},"#uifabric":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/#uifabric","pathType":"default"},"VSSUI":{"value":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/VSSUI","pathType":"default"}},"shim":{"jquery":{"deps":[],"exports":"jQuery"}},"waitSeconds":30},"coreReferences":{"stylesheets":[{"url":"/_static/tfs/M166_20200303.4/_cssbundles/Default/vss-bundle-ext-core-css-vgEHbWqZ4eb0vmOdl2cWjkpPtqcsX1GJCq4DnY78oN3s=","highContrastUrl":null,"isCoreStylesheet":true}],"scripts":[{"identifier":"JQuery","url":"/_static/3rdParty/_scripts/jquery-2.2.4.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"JQueryXDomain","url":"/_static/3rdParty/_scripts/jquery.xdomainrequest.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"Promise","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/promise.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"GlobalScripts","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/min/global-scripts.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"LoaderFixes","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/pre-loader-shim.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":false},{"identifier":"AMDLoader","url":"/_static/3rdParty/_scripts/require.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},{"identifier":"LoaderFixes","url":"/_static/tfs/M166_20200303.4/_scripts/TFS/post-loader-shim.min.js","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":false}],"coreScriptsBundle":{"identifier":"CoreBundle","url":"/_public/_Bundling/Content?bundle=vss-bundle-basejs-v9GpWWBnsWqhM23ijhK2HfAqLowTXGUqZLDRsBCZbkfY=","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true},"extensionCoreReferences":{"identifier":"CoreBundle","url":"/_public/_Bundling/Content?bundle=vss-bundle-ext-core-vjMBLvR7Lq0Z_oS-OpRMsP9FOHhkdmDXf0mCbsK5c0RI=","fallbackUrl":null,"fallbackCondition":null,"isCoreModule":true}},"webAccessConfiguration":{"isHosted":true,"paths":{"rootPath":"/","staticContentRootPath":"/","staticContentVersion":"M166_20200303.4","resourcesPath":"/_static/tfs/M166_20200303.4/_content/","staticRootTfs":"/_static/tfs/M166_20200303.4/","cdnFallbackStaticRootTfs":"/_static/tfs/M166_20200303.4/","staticRoot3rdParty":"/_static/3rdParty/"},"api":{"webApiVersion":"1","areaPrefix":"_","controllerPrefix":""},"mailSettings":{"enabled":false},"registryItems":{}},"microsoftAjaxConfig":{"cultureInfo":{"name":"en-US","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":".","IsReadOnly":true,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":",","CurrencySymbol":"$","NaNSymbol":"NaN","CurrencyNegativePattern":0,"NumberNegativePattern":1,"PercentPositivePattern":1,"PercentNegativePattern":1,"NegativeInfinitySymbol":"-∞","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":".","NumberGroupSeparator":",","CurrencyPositivePattern":0,"PositiveInfinitySymbol":"∞","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":".","PercentGroupSeparator":",","PercentSymbol":"%","PerMilleSymbol":"‰","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"AM","Calendar":{"MinSupportedDateTime":"0001-01-01T00:00:00","MaxSupportedDateTime":"9999-12-31T23:59:59.9999999","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, MMMM d, yyyy h:mm:ss tt","LongDatePattern":"dddd, MMMM d, yyyy","LongTimePattern":"h:mm:ss tt","MonthDayPattern":"MMMM d","PMDesignator":"PM","RFC1123Pattern":"ddd, dd MMM yyyy HH':'mm':'ss 'GMT'","ShortDatePattern":"M/d/yyyy","ShortTimePattern":"h:mm tt","SortableDateTimePattern":"yyyy'-'MM'-'dd'T'HH':'mm':'ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy'-'MM'-'dd HH':'mm':'ss'Z'","YearMonthPattern":"MMMM yyyy","AbbreviatedDayNames":["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],"ShortestDayNames":["Su","Mo","Tu","We","Th","Fr","Sa"],"DayNames":["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],"AbbreviatedMonthNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthNames":["January","February","March","April","May","June","July","August","September","October","November","December",""],"IsReadOnly":true,"NativeCalendarName":"Gregorian Calendar","AbbreviatedMonthGenitiveNames":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec",""],"MonthGenitiveNames":["January","February","March","April","May","June","July","August","September","October","November","December",""]},"numberShortForm":{"QuantitySymbols":["K","M","B"],"NumberGroupSize":1000,"ThousandSymbol":"K"},"eras":null}},"timeZonesConfiguration":{},"featureAvailability":{"featureStates":{"VisualStudio.Services.Contribution.EnableOnPremUnsecureBrowsers":false,"VisualStudio.Service.WebPlatform.ClientErrorReporting":false,"Microsoft.VisualStudio.Services.Gallery.Client.UseCdnAssetUri":false,"VisualStudio.Services.WebAccess.SubresourceIntegrity":false,"VisualStudio.Services.IdentityPicker.ReactProfileCard":true}},"appInsightsConfiguration":{"enabled":false,"instrumentationKey":"00000000-0000-0000-0000-000000000000","insightsScriptUrl":null},"diagnostics":{"sessionId":"24ec3e5b-2a51-44d0-8738-32e2f2c48c12","activityId":"24ec3e5b-2a51-44d0-8738-32e2f2c48c12","bundlingEnabled":true,"webPlatformVersion":"M166","serviceVersion":"Dev18.M166.1 (build: AzureDevOps_M166_20200320.5)"},"navigation":{"topMostLevel":"deployment","area":"","currentController":"Signin","currentAction":"Index","routeId":"LegacyWebAccessRoute","routeValues":{"controller":"Signin","action":"Index"}},"globalization":{"explicitTheme":"","theme":"Default","culture":"en-US","timezoneOffset":0,"timeZoneId":"UTC"},"serviceInstanceId":"951917ac-a960-4999-8464-e3f0aa25b381","hubsContext":{},"serviceLocations":{"locations":{"951917ac-a960-4999-8464-e3f0aa25b381":{"Application":"https://spsprodweu4.vssps.visualstudio.com/","Deployment":"https://spsprodweu4.vssps.visualstudio.com/"}}}}; var __cultureInfo = __vssPageContext.microsoftAjaxConfig.cultureInfo;
hope someone can tell me the proper way to send the post request.
Try with below script:
try
{
var personalaccesstoken = "{token}";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", "", personalaccesstoken))));
var httpClient = new HttpClient();
var newcontent = new StringContent("{\"searchText\":\"gradle\",\"$top\":33}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = await client.PostAsync("https://almsearch.dev.azure.com/{org}/{project}/_apis/search/codesearchresults?api-version=5.1-preview.1", newcontent))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Result:
Related
How can I pass header and parameter with HttpClient in .NET Core
This is my code using the RestSharp library: var client = new RestClient("https://example.com/api"); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("Authorization", "Bearer token..."); request.AddHeader("Content-Type", "text/plain"); request.AddParameter("text/plain", "{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}", ParameterType.RequestBody); IRestResponse response = await client.ExecuteAsync(request); // Console.WriteLine(response.Content); // var res = response.Content; How can I convert it to HttpClient using best practices?
You can use this: var client = new HttpClient() { BaseAddress = new Uri("https://example.com"), Timeout = TimeSpan.FromMinutes(5) //default is 90 seconds }; client.DefaultRequestHeaders.Add("Authorization", "Bearer token..."); var body = new StringContent("{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}",Encoding.UTF8, "text/plain"); var response = await client.PostAsync("api", body); var responseString = await response.Content.ReadAsStringAsync(); And for using the HttpClient in the right way I highly recommend to see this link.
Call simple POST API from console App in VS2019 with XML
I have referred the Trying to call simple POST API from console App in VS2019. But, need to pass XML method in post instead of JSON . Any suggestions ? static async Task Main(string[] args) { var TicketTask = await createTicket(); } async static Task<string> createTicket() { var content = "unknown error"; using (var httpClient = new System.Net.Http.HttpClient()) { using (var request = new System.Net.Http.HttpRequestMessage(new HttpMethod("POST"), "http://1.0.01.1/slive/")) { try { var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password")); request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); request.Content = new StringContent("<soapenv:Envelope xmlns:xsi...", Encoding.UTF8, "application/xml"); ????? need to post a xml method here request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false); content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); Console.WriteLine(response); } catch (Exception ex) { content = ex.Message; } } } return content;
Found the solution, please correct me if there is a better way: async static Task<string> createTicket2() { var content = "unknown error"; using (var httpClient = new System.Net.Http.HttpClient()) { using (var request = new System.Net.Http.HttpRequestMessage(new HttpMethod("POST"), "http://10/sap-lve/")) { try { var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("an:s")); request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); String str1 = #"<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><Get_api_version xmlns='http://e.s.a.com'/></s:Body></s:Envelope>"; **request.Content = new StringContent(str1, Encoding.UTF8, "text/xml");** ; request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml"); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; HttpResponseMessage response = await httpClient.SendAsync(request).ConfigureAwait(false); content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); //Console.WriteLine(response); var result = response.Content.ReadAsStringAsync(); Console.WriteLine(result.Result); } catch (Exception ex) { content = ex.Message; } } } return content; }
What can i do if SSL certificate don`t working in IIS, but working in Local
I have two projects: Web Api(back) and MVC(front). Web Api(back) has a method that uses the SSL certificate. If running the Web Api(back) in local, then the method works, but if running Web Api(back) in IIS and send post in MVC(front) to the method, then it catches an error "One or more errors occurred". (The SSL connection could not be established, see inner exception.). Web Api(back) code public decimal GetIdentification(IdentificationModel identification, int key) { try { var handler = new HttpClientHandler(); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"cert\\hgg.p12"); handler.ClientCertificates.Add(new X509Certificate2(path, _certPassword)); using (var httpClient = new HttpClient(handler)) { using (var request = new HttpRequestMessage(new HttpMethod("POST"), _identityUrl + "iin=" + identification.IIN + "&vendor=" + _vendor)) { string token = GetToken(); request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token); request.Headers.TryAddWithoutValidation("x-idempotency-key", "key:" + "hggKey-" + key); request.Method = new HttpMethod("POST"); //request.Content = new StringContent(identification.Photo); request.Content = new StreamContent(new MemoryStream(Convert.FromBase64String(identification.Photo))); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png"); var response = httpClient.SendAsync(request); string data = response.Result.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject<dynamic>(data).result; } } } catch (Exception e) { throw new Exception("GetIdentification" + e.Message); } } public string GetToken() { var handler = new HttpClientHandler(); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cert\\hgg.p12"); handler.ClientCertificates.Add(new X509Certificate2(path, _certPassword)); try { using (var httpClient = new HttpClient(handler)) { using (var request = new HttpRequestMessage(new HttpMethod("POST"), _tokenUrl)) { request.Headers.TryAddWithoutValidation("Authorization", "Basic " + _token); request.Method = new HttpMethod("POST"); request.Content = new StringContent("grant_type=password&username=" + _username + "&password=" + _password + "&scope=identkey"); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); var response = httpClient.SendAsync(request); return JsonConvert.DeserializeObject<dynamic>(response.Result.Content.ReadAsStringAsync().Result).access_token; } } } catch(Exception e) { throw new Exception("GetToken" + e.Message + path + " " +_certPassword); } } } MVC(front) public string Identity(RequestClass<IdentificationModel> request) { ResponseClass<decimal> response = new ResponseClass<decimal>(); using (var httpClient = new HttpClient()) { var json = JsonConvert.SerializeObject(request); var data = new StringContent(json, Encoding.UTF8, "application/json"); var httpResponse = httpClient.PostAsync(_apiUrl + $"Identification", data).Result; string responseContent = httpResponse.Content.ReadAsStringAsync().Result; return responseContent; } }
ApplicationPoolIdentity don't have permission for certmgr.msc
uri is too long when I try to send a base64 using xamarin forms
I am working with xamarin.forms and System.Net.Http; I am sending a photo using a post function which is this: public static async Task<String> PostImagemAsync(User user) { using (var client = new HttpClient()) { try { var values = new List<KeyValuePair<string, string>>(0); values.Add(new KeyValuePair<string, string>("email", user.usua_login)); values.Add(new KeyValuePair<string, string>("senha", user.usua_senha)); values.Add(new KeyValuePair<string, string>("foto", user.cont_imagem)); values.Add(new KeyValuePair<string, string>("json", "1")); var content = new FormUrlEncodedContent(values); HttpResponseMessage response = await client.PostAsync("http://ws.neosuite.com.br/login.asmx/foto", content); var json = response.Content.ReadAsStringAsync().Result; json = json.Substring(json.IndexOf('[')); json = json.Substring(0, json.LastIndexOf(']') + 1); var userImage = JsonConvert.DeserializeObject<List<User>>(json); return userImage[0].cont_imagem; } catch (Exception ex) { Debug.WriteLine(ex.Message); return null; } } } My image (foto) is a base64 And it does I get this error when I try to send it: Invalid URI: The Uri string is too long. How to solve that?
Without adding your POST content into url, add that to body using following code var uri = new Uri (string.Format ("http://ws.neosuite.com.br/login.asmx/foto", string.Empty)); var json = JsonConvert.SerializeObject (user);//user object or you can create your own jason here var content = new StringContent (json, Encoding.UTF8, "application/json"); var response = await client.PostAsync (uri, content);
Asp.net Web Api Authentication and password encryption
I have a autentication with the web api working, but is using the email and password to autenticate, how can i change so that web api uses a username field and password for the autentication? Another thing, how can i change the encrytion method for the password? The Autentication is made this away: public async Task<string> LoginAsync(string username, string password) { try { var keyValues = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("username", username), new KeyValuePair<string, string>("password", password), new KeyValuePair<string, string>("grant_type", "password") }; Settings.Serverdown = false; var request = new HttpRequestMessage(HttpMethod.Post, "http://192.168.44.22:56479/Token"); request.Content = new FormUrlEncodedContent(keyValues); var client = new HttpClient(); client.Timeout = TimeSpan.FromMilliseconds(6000); var response = await client.SendAsync(request); var jwt = await response.Content.ReadAsStringAsync(); Settings.LoginSucess = response.IsSuccessStatusCode; Settings.Username = username; JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(jwt); var accessToken = jwtDynamic.Value<string>("access_token"); Settings.AccessToken = accessToken; } catch (Exception e) { XFToast.LongMessage("Cant reach the server"); Settings.Serverdown = true; } var accessToken2=Settings.AccessToken; return accessToken2; } Thanks