private void loadUI() { MapApplication.SetApplication(BuilderApplication.Instance); AppCoreHelper.SetService(new ApplicationServices()); this.RootVisual = mainPage = new MainPage() { DataContext = BuilderApplication.Instance, }; ESRI.ArcGIS.Mapping.Core.Utility.SetRTL(mainPage); ImageUrlResolver.RegisterImageUrlResolver(new BuilderImageUrlResolver()); WebClientFactory.Initialize(); NotificationPanel.Instance.Initialize(); if (!NotificationPanel.Instance.OptedOutOfNotification) { EventHandler handler = null; handler = (o, e) => { if (NotificationPanel.Instance.OptedOutOfNotification) { NotificationPanel.Instance.NotificationsUpdated -= handler; return; } showExtensionLoadFailedMessageOnStartup(); }; NotificationPanel.Instance.NotificationsUpdated += handler; if (hasStartupExtensionLoadFailedEvent) { showExtensionLoadFailedMessageOnStartup(); } } }
public TimeZone Query(decimal latitude, decimal longitude) { var client = WebClientFactory.GetClient(); var data = client.DownloadString(string.Format (BaseUrlTimeZone, latitude, longitude)); XDocument doc = XDocument.Parse(data); var timeZoneElement = doc.Descendants("timezone").First(); var ret = new TimeZone() { Version = Decimal.Parse(timeZoneElement.Elements("version").First().Value), DST = timeZoneElement.Elements("dst").First().Value, IsoTime = DateTimeOffset.Parse(timeZoneElement.Elements("isotime").First().Value), LocalTime = DateTime.Parse(timeZoneElement.Elements("localtime").First().Value), Location = new Location() { Longitude = Decimal.Parse(timeZoneElement.Elements("location").First().Elements("longitude").First().Value), Latitude = Decimal.Parse(timeZoneElement.Elements("location").First().Elements("latitude").First().Value), }, Offset = Decimal.Parse(timeZoneElement.Elements("offset").First().Value), Suffix = timeZoneElement.Elements("suffix").First().Value, UtcTime = DateTime.Parse(timeZoneElement.Elements("utctime").First().Value) }; return(ret); }
public ContentResult Dictionary(TranslatorCriteria criteria) { var html = "<div>Implementing</div>"; if (criteria.From == "zh") { var url = string.Format(@"http://www.mdbg.net/chindict/chindict_ajax.php?c=wordvocab&i={0}&st=0", HttpUtility.UrlEncode(criteria.Text)); using (var webClient = WebClientFactory.ChromeClient()) { webClient.Encoding = Encoding.UTF8; html = webClient.DownloadString(url); } var startIndex = html.IndexOf("<table", StringComparison.OrdinalIgnoreCase); var endIndex = html.IndexOf("</body>", StringComparison.OrdinalIgnoreCase); if (endIndex > startIndex) { return new ContentResult { Content = html.Substring(startIndex, endIndex - startIndex), ContentEncoding = new UTF8Encoding(), ContentType = "text/html" } } ; } return(new ContentResult { Content = html }); }
public void GeneratesStartsNewClient() { var factory = new WebClientFactory <DefaultWebClient>(); var client = factory.Generate(); Assert.IsInstanceOf <DefaultWebClient>(client); }
public void GetCatalog(object userState) { if (string.IsNullOrEmpty(Uri)) { throw new InvalidOperationException(Resources.Strings.ExceptionUriMustNotBeNull); } // ensure that catalog requests always end with /databases if (!Uri.EndsWith("/databases", StringComparison.OrdinalIgnoreCase) && !Uri.EndsWith("/databases/", StringComparison.OrdinalIgnoreCase)) { if (!Uri.EndsWith("/", StringComparison.Ordinal)) { Uri += "/"; } Uri += "databases"; } UriBuilder builder = new UriBuilder(Uri); builder.Query = Utils.GetQueryParameters(Uri); finalUrl = builder.Uri; webClient = WebClientFactory.CreateWebClient(); webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(this.DownloadStringCompleted); webClient.DownloadStringAsync(finalUrl, userState); }
private async Task <T> DownloadJsonAsync <T>(string url) where T : class { using (var wc = WebClientFactory.GetClient()) { return(await wc.DownloadJsonAsync <T>(url)); } }
protected async Task WebClient(PhotonServerDefinition server, Func <WebClient, Task> clientTask) { var client = WebClientFactory.Create(server, Username, Password); try { await clientTask(client); } catch (WebException error) { if (error.Response is HttpWebResponse httpResponse) { if (httpResponse.StatusCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } if (httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new HttpUnauthorizedException(); } } throw; } finally { client.Dispose(); } }
private void StartupAfterGettingResources(object sender, StartupEventArgs e) { string baseUrl = getBaseUri(e); MainPage mainPage = null; ViewerApplicationControl viewerControl = new ViewerApplicationControl() { BaseUri = new Uri(baseUrl, UriKind.Absolute) }; this.RootVisual = mainPage = new MainPage() { Content = viewerControl }; viewerControl.ViewInitialized += (o, args) => { viewerControl.View.ApplicationColorSet.SyncDesignHostBrushes = true; }; RTLHelper helper = Application.Current.Resources["RTLHelper"] as RTLHelper; Debug.Assert(helper != null); if (helper != null) { mainPage.FlowDirection = helper.FlowDirection; } WebClientFactory.Initialize(); ImageUrlResolver.RegisterImageUrlResolver(new UrlResolver(baseUrl)); }
public LauncherLogic(AddressSet addressSet, IpPortConfig mySqlConfig, IpPortConfig worldConfig) { _syncContext = SynchronizationContext.Current; _addressSet = addressSet; _mySqlConfig = mySqlConfig; _worldConfig = worldConfig; _webClientFactory = new WebClientFactory(); }
public static PurchaseOrderLineCollection GetCollectionByProductId(int productId) { GenieLamp.Examples.QuickStart.Services.Interfaces.QuickStart.PurchaseOrderLineRequest request = new GenieLamp.Examples.QuickStart.Services.Interfaces.QuickStart.PurchaseOrderLineRequest(); GenieLamp.Examples.QuickStart.Services.Interfaces.QuickStart.PurchaseOrderLineListResponse response = WebClientFactory.GetJsonClient() .Get <GenieLamp.Examples.QuickStart.Services.Interfaces.QuickStart.PurchaseOrderLineListResponse>(String.Format("/PurchaseOrderLineService/ProductId/{0}", productId)); WebClientFactory.CheckResponseStatus(response.ResponseStatus); return(new PurchaseOrderLineCollection(response.PurchaseOrderLineDTOList)); }
public override Task <WebClientResponseMessage> GetAsync(WebClientRequestMessage request, ClientSetting clientSetting, CancellationToken cancellationToken) { var client = WebClientFactory.Create(new Settings() { TimeOut = (int)clientSetting.TimeOut.TotalMilliseconds }); return(client.GetAsync(request, cancellationToken)); }
/// <summary> /// Reads the list of clouds and returns the first one. /// This is a helper function for other operations classes which sometimes need cloudId and/or stampId to do their jos. /// It is okay to blindly take the first cloud because WAP subscriptions are currently limited to one cloud and one stamp. /// i.e., there should only be one cloud available anyway. /// </summary> /// <returns></returns> public static Cloud ReadFirstCloud(WebClientFactory webClientFactory) { var ops = new CloudOperations(webClientFactory); var cloudList = ops.Read(); if (cloudList.Count <= 0) { throw new WAPackOperationException(Resources.NoCloudsAvailable); } return(cloudList[0]); }
public static PurchaseOrderCollection GetByQuery(string query, GenieLamp.Examples.QuickStart.Services.Interfaces.ServicesQueryParams queryParams, int pageNum = 0, int pageSize = 300) { GenieLamp.Examples.QuickStart.Services.Interfaces.QuickStart.PurchaseOrderRequest request = new GenieLamp.Examples.QuickStart.Services.Interfaces.QuickStart.PurchaseOrderRequest(); request.Gl_Query = query; request.Gl_QueryParams = queryParams; request.Gl_PageNum = pageNum; request.Gl_PageSize = pageSize; GenieLamp.Examples.QuickStart.Services.Interfaces.QuickStart.PurchaseOrderListResponse response = WebClientFactory.GetJsonClient() .Post <GenieLamp.Examples.QuickStart.Services.Interfaces.QuickStart.PurchaseOrderListResponse>("/PurchaseOrderService", request); WebClientFactory.CheckResponseStatus(response.ResponseStatus); return(new PurchaseOrderCollection(response.PurchaseOrderDTOList)); }
protected override IEnumerable <ServiceInstanceListener> CreateServiceInstanceListeners() { return(new[] { OrleansServiceInstanceListenerFactory.Get(), WebClientFactory.Get(new WebClientFactoryOptions { ContentDirectory = (new DirectoryInfo(Directory.GetCurrentDirectory()).Parent?.FullName ?? string.Empty) + "\\Fabric.Web", EndpointName = "Web", LogAction = (ctx, log) => ServiceEventSource.Current.ServiceMessage(ctx, log) }) }); }
public void Should_create_webClient_with_correct_userAgent_header() { const string expected = "test user agent"; var settingsMock = new Mock <ICrawlerSettingsRepository>(); settingsMock.Setup(m => m.GetUserAgent()).Returns(expected); var factory = new WebClientFactory(settingsMock.Object); using (var wc = factory.CreateWebClient()) { Assert.Equal(expected, wc.GetHeader(HttpRequestHeader.UserAgent)); } }
public void GetTables(object userState) { if (string.IsNullOrEmpty(Uri)) { throw new InvalidOperationException("Uri must not be null"); } UriBuilder builder = new UriBuilder(Uri); builder.Query = Utils.GetQueryParameters(Uri); finalUrl = builder.Uri; webClient = WebClientFactory.CreateWebClient(); webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(this.DownloadStringCompleted); webClient.DownloadStringAsync(finalUrl, userState); }
public void GetFeatureServiceDetails(object userState) { if (string.IsNullOrEmpty(Uri)) { throw new InvalidOperationException(Resources.Strings.ExceptionUriMustNotBeNull); } UriBuilder builder = new UriBuilder(Uri); builder.Query = Utils.GetQueryParameters(Uri); finalUrl = builder.Uri; webClient = WebClientFactory.CreateWebClient(); webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCompleted); webClient.DownloadStringAsync(finalUrl, userState); }
internal void SaveTrainerDocuments(List<TrainerDocument> trainerDocuments) { try { using (var usersFactory = new WebClientFactory<ITrainerDocument>()) { var client = usersFactory.CreateClient(); client.SaveTrainerDocuments(trainerDocuments); } } catch (Exception ex) { ErrorMessage = ex.Message; } }
public IEnumerable <Place> Query(string Location) { var client = WebClientFactory.GetClient(); var data = client.DownloadString(string.Format (BaseUrlPlaces, Location)); XDocument doc = XDocument.Parse(data); var d = from p in doc.Descendants("place") select new Place() { Name = p.Elements("name").First().Value, Admin1 = p.Elements("admin1").First().Value, Admin2 = p.Elements("admin2").First().Value, Country = p.Elements("country").First().Value, Detail = new Detail() { FeatureClass = new FeatureClass() { Code = p.Elements("detail") .First() .Elements("featureclass") .First() .Elements("code") .First() .Value, Description = p.Elements("detail") .First() .Elements("featureclass") .First() .Elements("description").First().Value, Type = p.Elements("detail") .First() .Elements("featureclass") .First() .Elements("type") .First() .Value, }, Importance = Int32.Parse(p.Elements("detail").First().Elements("importance").First().Value), }, Latitude = Decimal.Parse(p.Elements("latitude").First().Value), Longitude = Decimal.Parse(p.Elements("longitude").First().Value) }; return(d.OrderBy(p => p.Detail.Importance)); }
private Result <IEnumerable <S> > GetResponse <TResponse, S>(string url) where TResponse : IWebResponse <S> { WebClient client; string rawResponse; try { client = WebClientFactory.Create(); rawResponse = client.DownloadString(url); } catch (WebException) { return(Result <IEnumerable <S> > .Fail("Network Failure")); } TResponse response = JsonConvert.DeserializeObject <TResponse>(rawResponse); return(Result <IEnumerable <S> > .Ok(response.Data.ToList())); }
protected async Task <T> WebClient <T>(PhotonServerDefinition server, Func <WebClient, Task <T> > clientTask) { var client = WebClientFactory.Create(server, Username, Password); try { return(await clientTask(client)); } catch (WebException error) { if (error.Response is HttpWebResponse httpResponse) { if (httpResponse.StatusCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } if (httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new HttpUnauthorizedException(); } if (httpResponse.StatusCode == HttpStatusCode.BadRequest) { string text = null; try { using (var stream = httpResponse.GetResponseStream()) using (var reader = new StreamReader(stream)) { text = await reader.ReadToEndAsync(); } } catch {} throw new ApplicationException($"Bad Request! {text}"); } } throw; } finally { client.Dispose(); } }
protected override IEnumerable <ServiceInstanceListener> CreateServiceInstanceListeners() { var myConfigPackage = Context.CodePackageActivationContext.GetConfigurationPackageObject("Config"); var fabricSettings = new FabricSettings(myConfigPackage); var webFactoryOptions = new WebClientFactoryOptions { FabricSettings = fabricSettings, EndpointName = "Web", LogAction = (ctx, log) => ServiceEventSource.Current.ServiceMessage(ctx, log), ContentRoot = (new DirectoryInfo(Directory.GetCurrentDirectory()).Parent?.FullName ?? string.Empty) + "\\Fabric.Web" }; return(new[] { OrleansServiceInstanceListenerFactory.Get(fabricSettings), WebClientFactory.Get(webFactoryOptions) }); }
/// <summary> /// Инициализирует экземпляр класса. /// </summary> /// <param name="rootDirectory">Корневая папка, в которой происходят обновления</param> /// <param name="serverPidFile">Адрес pid файла на сервере</param> /// <param name="localPidFile">Путь к локальному Pid файлу</param> /// <param name="serverPatchListFile">Адрес файла c описанием файлов для обновления на сервере</param> /// <param name="serverFilesRoot">Корневая папка на сервере, в которой лежат файлы для обновления</param> public WowUpdater(string rootDirectory, string serverPidFile, string localPidFile, string serverPatchListFile, string serverFilesRoot) { if (!Directory.Exists(rootDirectory)) { throw new DirectoryNotFoundException("rootDirectory"); } _rootDirectory = rootDirectory; _serverPidFile = serverPidFile; _localPidFile = localPidFile; _serverPatchListFile = serverPatchListFile; _serverFilesRoot = serverFilesRoot; _syncContext = SynchronizationContext.Current ?? new SynchronizationContext(); _webClientFactory = new WebClientFactory(); _webClient = _webClientFactory.Create(); _currentState = UpdateState.None; TempFolder = Path.Combine(Path.GetTempPath(), Wow.FolderName.TEMP_FOLDER_NAME); }
public IEnumerable <ReleaseForm> CheckUsingWebClient(string url) { using (var webClient = WebClientFactory.ChromeClient()) { try { var xmlString = webClient.DownloadString(url); var reader = new FeedReader(); var items = reader.RetrieveFeed(XmlReader.Create(new StringReader(xmlString))); return(items.Select(i => new ReleaseForm { Date = i.PublishDate.LocalDateTime, Title = i.Title, Summary = Html2Text(i.Summary), Url = i.Uri.ToString(), UrlHash = i.Uri.ToString().GetIntHash() })); } catch (Exception ex) {} } return(new List <ReleaseForm>()); }
private async Task Reconnect(PhotonServerDefinition server, string latestVersion, TimeSpan timeout) { using (var tokenSource = new CancellationTokenSource(timeout)) using (var webClient = WebClientFactory.Create(server, Username, Password)) { var token = tokenSource.Token; while (true) { token.ThrowIfCancellationRequested(); try { var version = await webClient.DownloadStringTaskAsync("api/version"); if (!VersionTools.HasUpdates(version, latestVersion)) { break; } } catch (Exception error) when(error is SocketException || error is WebException) { await Task.Delay(1000, tokenSource.Token); } } } }
private static VirtualMachine InitVirtualMachineOperation(MockRequestChannel mockChannel, out VirtualMachineOperations vmOperations) { //Cloud for return value of first request (client gets cloud to get stampId) var testCloud = new Cloud { ID = Guid.NewGuid(), StampId = Guid.NewGuid() }; mockChannel.AddReturnObject(testCloud); //VM for return value of second request (client updates VM with operation) var testVM = new VirtualMachine { ID = Guid.NewGuid(), StampId = testCloud.StampId }; mockChannel.AddReturnObject(testVM, new WebHeaderCollection { "x-ms-request-id:" + Guid.NewGuid() }); var factory = new WebClientFactory(new Subscription(), mockChannel); vmOperations = new VirtualMachineOperations(factory); return(testVM); }
public void GeneratesStartsNewClient() { var factory = new WebClientFactory<DefaultWebClient>(); var client = factory.Generate(); Assert.IsInstanceOf<DefaultWebClient>(client); }
public StaticIPAddressPoolOperations(WebClientFactory webClientFactory) : base(webClientFactory, "/StaticIPAddressPools") { }
public VMRoleOperations(WebClientFactory webClientFactory) : base(webClientFactory, genericBaseUri) { }
public void Setup() { _client = WebClientFactory.CreateWebClient(); }
private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Cancelled) { return; } if (e.Error != null) { bool redownloadAttempted = WebClientFactory.RedownloadAttempted.Contains(webClient); if (Utils.IsMessageLimitExceededException(e.Error) && !redownloadAttempted) { // Re-issue the request which should serve it out of cache // and helps us avoid the error which is caused by setting AllowReadStreamBuffering=false // which was used to workaround the problem of SL4 and gzipped content WebClientFactory.RedownloadStringAsync(webClient, finalUrl, e.UserState); } else { if (redownloadAttempted) { WebClientFactory.RedownloadAttempted.Remove(webClient); } OnGetTablesInDatabaseFailed(new ExceptionEventArgs(e.Error, e.UserState)); } return; } if (string.IsNullOrEmpty(e.Result)) { OnGetTablesInDatabaseFailed(new ExceptionEventArgs(new Exception("Empty response"), e.UserState)); return; } DatabaseTables databaseTables = null; try { string json = e.Result; if (Utils.IsSDSCatalogResponse(json)) { // We were expecting a response consisting of tables, instead we got a response of the catalog // this must be because we formed/guessed our URL wrong OnGetTablesInDatabaseFailed(new ExceptionEventArgs(new Exception("Invalid response recieved. Catalog response recieved when expecting database tables"), e.UserState)); return; } Exception exception = Utils.CheckJsonForException(json); if (exception != null) { OnGetTablesInDatabaseFailed(new ExceptionEventArgs(exception, e.UserState)); return; } byte[] bytes = Encoding.Unicode.GetBytes(json); using (MemoryStream memoryStream = new MemoryStream(bytes)) { DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(DatabaseTables)); databaseTables = dataContractJsonSerializer.ReadObject(memoryStream) as DatabaseTables; memoryStream.Close(); } if (databaseTables == null) { OnGetTablesInDatabaseFailed(new ExceptionEventArgs(new Exception("Unable to deserialize response"), e.UserState)); return; } List <Resource> childResources = new List <Resource>(); int totalTableCount = databaseTables.Tables != null ? databaseTables.Tables.Count : 0; if (databaseTables.Tables != null) { int tableCount = 0; foreach (string table in databaseTables.Tables) { Resource databaseTable = new Resource() { ResourceType = ResourceType.DatabaseTable, DisplayName = table, Url = string.Format("{0}/{1}", Uri, table), }; if (FilterForSpatialContent) { FeatureService featureService = new FeatureService(databaseTable.Url); featureService.GetFeatureServiceDetailsFailed += (o, args) => { // Remove the table childResources.Remove(args.UserState as Resource); tableCount++; if (tableCount >= totalTableCount) { // all done raise the event OnGetTablesInDatabaseFailed(args); } }; featureService.GetFeatureServiceDetailsCompleted += (o, args) => { tableCount++; if (args.FeatureServiceInfo == null || !args.FeatureServiceInfo.DoesTableHasGeometryColumn()) { // Remove the table childResources.Remove(args.UserState as Resource); } if (tableCount >= totalTableCount) { // all done raise the event OnGetTablesInDatabaseCompleted(new GetTablesInDatabaseCompletedEventArgs() { ChildResources = childResources, UserState = e.UserState }); } }; // Add table before validation to preserve catalog order. Table will be removed if // validation fails. Resource child = new Resource() { ResourceType = ResourceType.DatabaseTable, DisplayName = databaseTable.DisplayName, Url = databaseTable.Url, }; childResources.Add(child); featureService.GetFeatureServiceDetails(child); } else { childResources.Add(databaseTable); } } } if (!FilterForSpatialContent || totalTableCount == 0) { OnGetTablesInDatabaseCompleted(new GetTablesInDatabaseCompletedEventArgs() { ChildResources = childResources, UserState = e.UserState }); } } catch (Exception ex) { OnGetTablesInDatabaseFailed(new ExceptionEventArgs(ex, e.UserState)); } }