public ComputeApiClient(string targetRegionName) { if (string.IsNullOrWhiteSpace(targetRegionName)) throw new ArgumentException( "Argument cannot be null, empty, or composed entirely of whitespace: 'targetRegionName'.", "targetRegionName"); WebApi = new WebApi(targetRegionName); }
public void ShowProgress(WebApi webApi) { this.webApi = webApi; var dialog = new UploadDialog() { DataContext = this, Owner = Application.Current.MainWindow }; dialog.Closing += async (_, __) => await this.Cancel(); dialog.ShowDialog(); this.cancellationTokenSource = new CancellationTokenSource(); }
/// <summary> /// Initialises a new instance of the <see cref="ComputeApiClient"/> class. /// Creates a new CaaS API client using a base URI. /// </summary> /// <param name="baseUri"> /// The base URI to use for the CaaS API. /// </param> public ComputeApiClient(Uri baseUri) { if (baseUri == null) throw new ArgumentNullException("baseUri", "Argument cannot be null"); if (!baseUri.IsAbsoluteUri) throw new ArgumentException("Base URI supplied is not an absolute URI", "baseUri"); WebApi = new WebApi(baseUri); }
public static async void ShowMatches(string start, string end) { WebApi wa = new WebApi(start, end); Dictionary <string, string> returnedResult = await wa.GetMatchesAsync(uri); if (returnedResult.Count == 0) { Console.WriteLine("Нет совпадений"); } foreach (var i in returnedResult) { Console.WriteLine($"{i.Key} / {i.Value}"); } }
public async Task <LikeResponseMessage> UnLike(string mediaId, CancellationToken token) { dynamic syncMessage = new JObject(); syncMessage._uuid = _authSettings.Guid; syncMessage._uid = _authSettings.UserId; syncMessage._csrftoken = _authSettings.Token; syncMessage.media_id = mediaId; var content = SignedContent(syncMessage.ToString()); var likeResponse = await Retry.Do(WebApi.PostEntityAsync <LikeResponseMessage>(string.Format(PostUnLike, mediaId), content, token), token); return(likeResponse); }
public async Task <FollowResponseMessage> UnFollow(string userId, CancellationToken token) { dynamic syncMessage = new JObject(); syncMessage._uuid = _authSettings.Guid; syncMessage._uid = _authSettings.UserId; syncMessage._csrftoken = _authSettings.Token; syncMessage.user_id = userId; var content = SignedContent(syncMessage.ToString()); var followReponse = await Retry.Do(WebApi.PostEntityAsync <FollowResponseMessage>(string.Format(PostUnFollow, userId), content, token), token); return(followReponse); }
internal override string GetBatchString(BatchRequest batchRequest, WebApi webApi, int?lastContentId) { var entityUrl = lastContentId != null ? "$" + lastContentId.ToString() : webApi.ApiUrl + RequestEntityParser.GetEntityApiUrl(EntityToDelete, webApi.WebApiMetadata); var jObject = "{}"; var entityString = JsonConvert.SerializeObject(jObject); var batchString = $"--changeset_{batchRequest.ChangeSetId.ToString("N")}" + NewLine; batchString += $"Content-Type: application/http" + NewLine; batchString += $"Content-Transfer-Encoding:binary" + NewLine; batchString += $"Content-ID: {batchRequest.ContentId}" + NewLine + NewLine; batchString += $"DELETE {entityUrl} HTTP/1.1" + NewLine; batchString += $"Content-Type: application/json;type=entry" + NewLine + NewLine; batchString += entityString + NewLine + NewLine; return(batchString); }
/// <summary> /// 获取到款记录 /// </summary> /// <param name="id">合同id</param> /// <returns></returns> public static ResultDTO GetReceiptRecords(string id) { var sql = @"SELECT CONVERT(varchar(100), a.ArrivedDate, 20) as ArrivedDate ,Convert(decimal(18,2),isnull(a.Amount,0)/10000) as ArrivedMoney ,c.Name,a.ID FROM S_C_Receipt AS a Left JOIN S_C_ReceiptPlanRelation AS b ON a.ID=b.ReceiptID Left JOIN S_C_PlanReceipt AS c ON b.PlanID=c.ID left join (select ID,PartyA from S_C_ManageContract where IsSigned='Signed')con on a.CustomerID = con.PartyA and con.ID=a.ContractInfoID WHERE con.ID='{0}' ORDER BY ArrivedDate DESC"; var db = new MarketContext(); var list = db.Database.SqlQuery <ReceiptRecordDTO>(string.Format(sql, id)); var results = new List <ReceiptRecordDTO>(); foreach (var item in list.GroupBy(p => p.ID)) { string names = ""; string arrivedDate = ""; decimal arrivedMoney = 0; var t = item.GetEnumerator(); while (t.MoveNext()) { names += t.Current.Name + ","; arrivedDate = t.Current.ArrivedDate; arrivedMoney = t.Current.ArrivedMoney; } if (names.IndexOf(',') >= 0) { names = names.Substring(0, names.Length - 1); } if (string.IsNullOrEmpty(names)) { names = ""; } results.Add(new ReceiptRecordDTO { ArrivedMoney = arrivedMoney, ArrivedDate = arrivedDate, Name = names }); } return(WebApi.Success(results)); }
public WebRet(WebApi api, string url, string contentType, byte[] data, HttpResponseHeaders headers, bool isSuccessStatusCode, HttpStatusCode statusCode, string statusReason) { this.Api = api; this.Url = url._NonNull(); this.ContentType = contentType._NonNull(); this.Headers = headers; this.StatusCode = statusCode; this.IsSuccessStatusCode = isSuccessStatusCode; this.StatusReason = statusReason._NonNull(); this.StatusCodeAndReasonString = string.Format("Response status code does not indicate success: {0} ({1}).", (int)statusCode, statusReason); try { var ct = new System.Net.Mime.ContentType(this.ContentType); this.MediaType = ct.MediaType._NonNull(); this.CharSet = ct.CharSet._NonNull(); } catch { this.MediaType = this.ContentType; this.CharSet = ""; } try { if (this.CharSet._IsFilled()) { this.DefaultEncoding = Encoding.GetEncoding(this.CharSet); } } catch { } if (this.DefaultEncoding == null) { this.DefaultEncoding = api.RequestEncoding; } this.Data = data._NonNull(); if (this.Api.DebugPrintResponse) { this._DebugObject(); } }
public AuthenticodeSignClient(string url, string sslSha, TcpIpSystem?tcpIp = null) { try { this.Url = url; this.Web = new WebApi(new WebApiOptions(new WebApiSettings { MaxRecvSize = Consts.Numbers.SignCodeServerMaxFileSize, SslAcceptCertSHAHashList = sslSha._SingleList() }, tcpIp)); } catch (Exception ex) { this._DisposeSafe(ex); throw; } }
/// <summary> /// Initializes a new instance of the <see cref="GoogleMapsApiClient"/> class. /// </summary> /// <param name="apiKey"> /// The api key. /// </param> public GoogleMapsApiClient(string apiKey) { var url = EndPointUris.GetBaseUri(); var httpClientHandler = new HttpClientHandler(); var httpClient = new HttpClientAdapter( new HttpClient(httpClientHandler, true) { BaseAddress = url }); var webApi = new WebApi(httpClient, apiKey); PlaceSearch = new PlaceSearch(webApi); GeocodingService = new GeocodingService(webApi); DirectionsService = new DirectionsService(webApi); }
public static IList <BitfinexTradesGet> GetPairTrades(BtcInfo.PairTypeEnum pairType, BtcInfo.BitfinexUnauthenicatedCallsEnum callType) { var call = Enum.GetName(typeof(BtcInfo.BitfinexUnauthenicatedCallsEnum), callType); var symbol = Enum.GetName(typeof(BtcInfo.PairTypeEnum), pairType); var url = @"/v1/" + call.ToLower(CultureInfo.InvariantCulture) + "/" + symbol.ToLower(CultureInfo.InvariantCulture); var response = WebApi.GetBaseResponse(url); var pairTradesResponseObj = JsonConvert.DeserializeObject <IList <BitfinexTradesGet> >(response); foreach (var pairTrade in pairTradesResponseObj) { Log.Info("Pair Trade: {0}", pairTrade); } return(pairTradesResponseObj); }
/// <summary> /// SimulatorLaneSendMes /// </summary> public void AddMessage(MessageCUR messagecreate) { try { socket.Emit("createMessage", (data) => { reciveStatus?.Invoke(convertData(data)); }, JsonConvert.SerializeObject(messagecreate)); } catch (Exception ex)//尝试用API的方式发送 { string url = apiAddress + "/addMessage"; dynamic str = WebApi.Post(url, JsonConvert.SerializeObject(messagecreate)); reciveStatus?.Invoke(convertData(str)); } }
public override Task <ILazyTreeNode <INetDiskFile> > GetFileRootAsync() { var tree = new LazyTreeNode <INetDiskFile>(new SixCloudFile()) { ChildrenProvider = async parent => { var json = await WebApi.GetFilesByPathAsync(new GetFilesByPathArgs { Path = parent.Path, PageSize = 999 }); return(json.Success ? json.Result["list"].Select(item => item.ToObject <SixCloudFile>()).ToList() : Enumerable.Empty <SixCloudFile>()); } }; return(Task.FromResult <ILazyTreeNode <INetDiskFile> >(tree)); }
public static List <Booking> GetByParameter(DateTime startDate, DateTime endDate, int?costAccountCreditorId = null, int?costAccountDebitorId = null, bool OnlyCanceledBookings = false) { Dictionary <string, object> parameters = new Dictionary <string, object> { { "startDate", startDate }, { "endDate", endDate }, { "costAccountCreditorId", costAccountCreditorId }, { "costAccountDebitorId", costAccountDebitorId } }; if (OnlyCanceledBookings) { parameters.Add("OnlyCanceledBookings", OnlyCanceledBookings); } return(WebApi <List <Booking> > .GetData(controllerName, "GetByParameter", parameters)); }
public async Task SignUpAsync(string username, string password, string passCode, string phoneInfo) { if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password) && !string.IsNullOrWhiteSpace(passCode) && !string.IsNullOrWhiteSpace(phoneInfo)) { await WebApi.RegisterAsync(new RegisterArgs { NickName = username, PhoneCode = passCode, PasswordMd5 = password.ToMd5(), PhoneInfo = phoneInfo }); } }
/// <summary> /// 获取合同详情 /// </summary> /// <param name="id">合同id</param> /// <returns></returns> public static ResultDTO GetDetail(string id) { var sql = @"SELECT Name,SerialNumber ,Convert(decimal(18,2),isnull(ContractRMBAmount,0)/10000) as ContractRMBAmount ,Convert(decimal(18,2),isnull(SumInvoiceValue,0)/10000) as SummaryInvoiceValue ,Convert(decimal(18,2),isnull(SumReceiptValue,0)/10000) as SummaryReceiptValue ,case when isNull(CONVERT(varchar(100), SignDate, 23),'')='' then '--' else isNull(CONVERT(varchar(100), SignDate, 23),'') end as StartDate ,case when isNull(CONVERT(varchar(100), EndDate, 23),'')='' then '--' else isNull(CONVERT(varchar(100), EndDate, 23),'') end as EndDate ,case when isNull(BusinessManagerName,'')='' then '未安排' else isNull(BusinessManagerName,'') end as HeadOfSalesName ,case when isNull(ProductionManagerName,'')='' then '未安排' else isNull(ProductionManagerName,'') end as ProduceMasterName ,'' as SignDept FROM S_C_ManageContract where ID='{0}'"; var db = new MarketContext(); return(WebApi.Success(db.Database.SqlQuery <ContractDTO>(string.Format(sql, id)).FirstOrDefault())); }
public async Task <TagFeedResponseMessage> TagFeed(string tag, CancellationToken token, int?maxId = null) { var endpoint = string.Format(GetTag, tag); if (maxId != null && maxId > 0) { endpoint = $"{endpoint}?max_id={maxId}"; } if (string.IsNullOrWhiteSpace(tag)) { throw new ArgumentException(nameof(tag)); } var feed = await Retry.Do(WebApi.GetEntityAsync <TagFeedResponseMessage>(endpoint, token), token); return(feed); }
public override async Task InitializeAsync(object _) { LoadingQueue = true; ErrorMessage = ""; try { var queue = await WebApi.GetQueueAsync(_appState.Session.Id); Queue = queue.Select(item => new MediaViewModel(item)).ToList(); } catch (Exception e) { ErrorMessage = e.Message; } LoadingQueue = false; }
/// <summary> /// Obtem o relatório completo do estacionamento /// </summary> /// <returns></returns> public List <ListaEstacionamentoCompletoRelatorio> RelatorioCompletoLista(DateTime datainicial, DateTime datafinal) { DadosFormularioPesquisa dados = new DadosFormularioPesquisa() { DtInicio = Convert.ToDateTime(datainicial.ToString("yyyy-MM-dd HH:mm:ss")), DtFim = Convert.ToDateTime(datafinal.ToString("yyyy-MM-dd HH:mm:ss")) }; string jsonData = JsonConvert.SerializeObject(dados, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-dd" }); string json = WebApi.RequestPOST("estacionamento/estacionamentos/gerencial", jsonData); List <ListaEstacionamentoCompletoRelatorio> lista = JsonConvert.DeserializeObject <List <ListaEstacionamentoCompletoRelatorio> >(json); return(lista); }
public async Task <bool> SyncFeatures() { dynamic syncMessage = new JObject(); syncMessage._uuid = _authSettings.Guid; syncMessage._uid = _authSettings.UserId; syncMessage._csrftoken = _authSettings.Token; syncMessage.id = _authSettings.UserId; syncMessage.experiments = _apiSettings.Experiments; var content = SignedContent(syncMessage.ToString()); var syncEntity = await WebApi.PostEntityAsync <SyncResponseMessage>(GetSync, content); return(true); }
/// <summary> /// 获取项目下用户信息 /// </summary> /// <param name="id">项目ID</param> /// <param name="condition">查询条件</param> /// <returns></returns> public static ResultDTO GetPrjUsers(string id, string condition) { var basedbname = Base.GetDbName("Base"); var prjdbname = Base.GetDbName("Project"); var sql = @"SELECT case when m.MajorName is null then m.RoleName else m.MajorName+'·'+ m.RoleName end MajorRole ,m.UserName,u.MobilePhone,u.Email FROM [{3}].[dbo].[S_W_OBSUser] m LEFT JOIN [{2}].[dbo].[S_A_User] u ON m.UserID = u.ID WHERE ProjectInfoID = '{0}' and m.UserName like '%{1}%' order by MajorName+RoleName"; var db = new ProjectContext(); return(WebApi.Success(db.Database.SqlQuery <ProjectUser>(string.Format(sql, id, condition, basedbname, prjdbname)))); }
public void deleteMessage(MessageD messageDel) { try { socket.Emit("deleteMessage", (data) => { reciveStatus?.Invoke(JsonConvert.SerializeObject(data)); }, JsonConvert.SerializeObject(messageDel)); } catch (Exception ex) { string url = apiAddress + "/deleteMessage"; dynamic str = WebApi.Post(url, JsonConvert.SerializeObject(messageDel)); reciveStatus?.Invoke(convertData(str)); } }
async Task ExecuteGetPromotionsCommand(object obj) { try { if (IsBusy) { return; } IsBusy = true; //Firebase var localPromotionList = new List <Promotion>(); localPromotionList = await WebApi.GetPromotions().ConfigureAwait(false); if (!localPromotionList.Any()) { IsBusy = true; return; } /* * //Todo : Web Services * * await Task.Delay(3000); * var LocalPromotionList = new System.Collections.Generic.List<Promotion> * { * new Promotion(){Title = "Cerveza",Detail = "1223"}, * new Promotion(){Title = "Refresco",Detail = "5555"} * * };*/ ObjectList = new ObservableCollection <Promotion>(localPromotionList); OnPropertyChanged(nameof(ObjectList)); IsBusy = false; } catch (Exception ex) { IsBusy = false; Console.WriteLine(ex.Message); } }
public async Task <FollowResponseMessage> Follow(string userId) { MessageHub.PublishAsync(new BeforeFollowEvent(this, userId)); dynamic syncMessage = new JObject(); syncMessage._uuid = _authSettings.Guid; syncMessage._uid = _authSettings.UserId; syncMessage._csrftoken = _authSettings.Token; syncMessage.user_id = userId; var content = SignedContent(syncMessage.ToString()); var followReponse = await WebApi.PostEntityAsync <FollowResponseMessage>(string.Format(PostFollow, userId), content); MessageHub.PublishAsync(new AfterFollowEvent(this, userId)); return(followReponse); }
public async Task <IActionResult> ViewCustomers() { var response = await WebApi.InitializeClient().GetAsync("api/customers"); if (!response.IsSuccessStatusCode) { return(NotFound()); } // Storing the response details recieved from web api. var result = response.Content.ReadAsStringAsync().Result; // Deserializing the response recieved from web api and storing into a list. var customers = JsonConvert.DeserializeObject <List <Customer> >(result); return(View(customers)); }
public async Task <LikeResponseMessage> Like(Media media, CancellationToken token) { MessageHub.PublishAsync(new BeforeLikeEvent(this, media)); dynamic syncMessage = new JObject(); syncMessage._uuid = _authSettings.Guid; syncMessage._uid = _authSettings.UserId; syncMessage._csrftoken = _authSettings.Token; syncMessage.media_id = media.Id; var content = SignedContent(syncMessage.ToString()); var likeResponse = await Retry.Do(WebApi.PostEntityAsync <LikeResponseMessage>(string.Format(PostLike, media.Id), content, token), token); MessageHub.PublishAsync(new AfterLikeEvent(this, media)); return(likeResponse); }
public IActionResult EditCustomer(int id, Customer customer) { if (ModelState.IsValid) { var content = new StringContent(JsonConvert.SerializeObject(customer), Encoding.UTF8, "application/json"); var response = WebApi.InitializeClient().PutAsync($"api/Customers/{id}", content).Result; //Console.WriteLine(JsonConvert.SerializeObject(customer)); if (response.IsSuccessStatusCode) { return(RedirectToAction("ViewCustomers")); } } return(View(customer)); }
private void CompleteNewStatesRegistration(HttpClient client, Guid folderSessionId, Guid processId, string errorMessage) { Entities.CommandKey.ValidationActionType currentActionType = this.ActionTypeName; OpenAPIService.StatusClient status = new OpenAPIService.StatusClient(WebApi.ToString(), client); //add 2 records (started/failed) for state var startStateResponse = status.StartAsync(processId).GetAwaiter().GetResult(); if (startStateResponse.StatusCode != 200) { throw new ApplicationException(String.Format("Start state registration returned a bad response (not 200 code)! Action ID {0}, Folder / Session ID {1}.", processId, folderSessionId)); } OnNotify(new NotificationEvent { Client = client, Id = folderSessionId, Result = NotificationEvent.State.Started }); var failedStateResponse = status.FailedAsync(processId, new BodyMessage { Message = errorMessage }).GetAwaiter().GetResult(); if (failedStateResponse.StatusCode != 200) { throw new ApplicationException(String.Format("Failed state registration returned a bad response (not 200 code)! Action ID {0}, Folder / Session ID {1}.", processId, folderSessionId)); } SummaryItem summaryObj = new SummaryItem { Accepted = 0, Processed = 0, Rejected = 1, Start = DateTimeOffset.Now, End = DateTimeOffset.Now }; string summaryStr = JsonConvert.SerializeObject(summaryObj); //final update var finalUpdateResponse = status.UpdateAsync(processId, new BodyUpdate { Result = "Failed", Summary = summaryStr }).GetAwaiter().GetResult(); if (finalUpdateResponse.StatusCode != 200) { throw new ApplicationException(String.Format("Final update status returned a bad response (not 200 code)! Action ID {0}, Folder / Session ID {1}.", processId, folderSessionId)); } OnNotify(new NotificationEvent { Client = client, Id = folderSessionId, Result = NotificationEvent.State.CompletedOrFailed }); }
public Task <PostMessageResponse> PostMessageAsync( PostMessageRequest request, CancellationToken cancellationToken = default ) { // Validate parameters. if (request == null) { throw new ArgumentNullException(nameof(request)); } // Post the request. return(WebApi.PostToWebApiAsync <PostMessageRequest, PostMessageResponse>( "chat.postMessage", request, cancellationToken )); }
// this is a necessary ShellBoost override for better performance (direct access instead of implicit call to EnumItems) // https://www.shellboost.com/Doc/Developer-s-Guide/Items-enumeration public override ShellItem GetItem(ShellItemId id) { var guidPidl = KeyShellItemId.From(id.Data, false) as GuidKeyShellItemId; if (guidPidl == null) { return(null); } if (guidPidl.Value == Guid.Empty) { return(Root); } var apiItem = WebApi.GetAsync(guidPidl.Value).Result; return(ShellItemFromApi(apiItem)); }
public override async Task <bool> RefreshAsync() { var result = await WebApi.GetUserInfoAsync().RunApi(); if (!result.Success) { return(false); } Id = result.Result["uuid"].ToObject <long>().ToString(); Username = result.Result["name"].ToObject <string>(); Email = result.Result["email"].ToObject <string>(); Phone = result.Result["phone"].ToObject <string>(); UsedCapacity = result.Result["spaceUsed"].ToObject <long>(); TotalCapacity = result.Result["spaceCapacity"].ToObject <long>(); return(true); }
private async void Login(object _) { LoggingIn = true; LoginMessage = ""; try { var login = await WebApi.LoginAsync(Account, Password, _appState.Session.Id); _settings.Save(SettingsKey.AUTH_TOKEN, login.AuthorizationToken); _appState.Session.User = login.User; await _navigation.Navigate <QueuePageViewModel>(null); } catch (Exception e) { LoginMessage = e.Message; } LoggingIn = false; }
/// <summary> /// Asynchronously resumes uploading a synth packet to the Photosynth upload service for processing in the cloud. /// </summary> /// <param name="webApi">A WebApi object for handling HTTP communication with the Photosynth web service</param> /// <param name="fileStorage">An IFileStorage implementation for handling file I/O</param> /// <param name="cancellationToken">A cancellation token.</param> /// <param name="parallelism">The maximum number of chunks that can be uploaded in parallel.</param> /// <returns>The task object representing the asynchronous operation</returns> public async Task ResumeUploadAsync(WebApi webApi, IFileStorage fileStorage, CancellationToken cancellationToken, int parallelism = 2) { if (this.IsUploading) { throw new InvalidOperationException("Only 1 upload per Uploader instance is allowed."); } if (!this.FailedChunks.Any()) { return; } try { this.IsUploading = true; this.ProgressPercentage = 0; this.EstimatedTimeRemaining = string.Empty; var failedChunks = await this.UploadChunksAsync(webApi, fileStorage, this.FailedChunks.ToList(), 0, cancellationToken, parallelism); this.FailedChunks.Clear(); foreach (var failedChunk in failedChunks) { this.FailedChunks.Add(failedChunk); } this.ProgressPercentage = 100; } finally { this.IsUploading = false; } }
static void Main(string[] args) { //Console.WriteLine("Processing..."); const string apiBaseUrl = @"https://bamboo.bistudio.com/rest/api/latest/"; #region MyRegion const string userName = ""; const string password = ""; #endregion BambooApi api = new BambooApi(apiBaseUrl, userName, password); new PlanSample(api, "JHT", "AIRI"); wa = new WebApi(userName, password); wa.SimpleHttp.Verbose = true; var projectsService = api.GetService<ProjectService>(); planService = api.GetService<PlanService>(); queueService = api.GetService<QueueService>(); //projectsService.Clone("JHT", "AH", "JHT", "AIR11"); ////projectsService.TestChangeConfig(); var templateProjKey = "JHT"; var projKey = "AIIIDATA"; var templatebuildKey = "TEM"; //var tetest = projectsService.GetProjectWithAllPlans(templateProjKey); //foreach (var plan in tetest.Plans.All) //{ // if (plan.ShortKey == "RRRDEN") // { // //wa.ShareAllArtifactsToAnotherJob(plan.ProjectKey, plan.ShortKey, "JOB1", "RRRR"); // //wa.DeleteStage(plan.ProjectKey, plan.ShortKey, "GetSvnConfiguration"); // wa.AddPlanVariable(plan.ProjectKey, plan.ShortKey, "aaaa", "cc"); // } //} //var arma3DataPlansWitVars = projectsService.GetProjectWithAllPlansAndVariables(templateProjKey); //foreach (var plan in arma3DataPlansWitVars.Plans.All) //{ // if (plan.ShortName.ToLower().Contains("exp")) // { // var currentPlan = planService.GetPlan(projKey, plan.ShortKey); // foreach (var variable in currentPlan.VariableContext.All) // { // if (variable.Key == "a3_useOldBuildingPipeline" && variable.Value == "true") // { // Console.WriteLine(plan.ShortName + Environment.NewLine); // } // } // } //} wa.ClonePlan("JHT", templatebuildKey, "JHT", "LALALA"); var arma3DataPlans = projectsService.GetProjectWithAllPlans(templateProjKey); var buildingPlans = new List<Bamboo.Sharp.Api.Model.Plan>(); var processed = true; foreach (var plan in arma3DataPlans.Plans.All) { var buildKey = plan.ShortKey; Console.WriteLine(plan.ProjectKey + " " + plan.ShortKey + " " + plan.ShortName); if (plan.ShortKey == "RNDROOT") { } //else if (plan.ShortKey == "MAPSDT") //{ // processed = false; //} else if (plan.IsBuilding) { //buildingPlans.Add(plan); } //STRUCTURES_F_EXP || MAP_TANOABUKA else if (plan.ShortKey == "STRUCEX")// if (plan.BuildName.ToLower().Contains("exp")) { //wa.DeletePlan(plan.ProjectKey, plan.ShortKey); wa.ClonePlan("JHT", templatebuildKey, plan.ProjectKey, plan.ShortKey); //DeleteStage(plan.ProjectKey, buildKey, "Build package"); //CreateStage(plan.ProjectKey, plan.ShortKey, "Build+package"); //CreateStage(plan.ProjectKey, plan.ShortKey, "Synchronize+data"); //wa.JobCleanWorkingDirectory(plan.ProjectKey, buildKey, "JOB1"); //wa.DeleteJob(plan.ProjectKey, buildKey, "DTF"); //CloneJob(templateProjKey, templatebuildKey, "JOB1", "Build+Package", plan.ProjectKey, buildKey, "Build+package"); //CloneJob(templateProjKey, templatebuildKey, "RRRR", "Copy+data+and+packlogs", plan.ProjectKey, buildKey, "Synchronize+data"); //CloneJob(templateProjKey, templatebuildKey, "DTF", "Delete+temp+files", plan.ProjectKey, buildKey, "Synchronize+data"); //ShareAllArtifactsToAnotherJob(plan.ProjectKey, buildKey, "JOB1", "RRRR"); //AddPlanVariable(plan.ProjectKey, buildKey, "a3_useOldBuildingPipeline", "false"); //AddPlanVariable(plan.ProjectKey, buildKey, "svnSubdirectory"); } } /* for plan cloning, load all plans for arma3data project to array and than foreach it, */ //api.GetService<QueueService>().Show(); //var projectsService = api.GetService<ProjectService>(); //var projects = projectsService.GetProjects(); //Console.WriteLine("Alive!"); //var project = projectsService.GetProject("JHT"); //var queue = api.GetService<QueueService>(); // var user = api.GetService<CurrentUserService>(); }
/// <summary> /// Initialises a new instance of the <see cref="ComputeApiClient"/> class. /// Creates a new CaaS API client using a known vendor and region. /// </summary> /// <param name="vendor"> /// The vendor /// </param> /// <param name="region"> /// The region /// </param> public ComputeApiClient(KnownApiVendor vendor, KnownApiRegion region) { Uri baseUri = KnownApiUri.Instance.GetBaseUri(vendor, region); _ftpHost = KnownApiUri.Instance.GetFtpHost(vendor, region); if (!baseUri.IsAbsoluteUri) throw new ArgumentException("Base URI supplied is not an absolute URI", "vendor"); WebApi = new WebApi(baseUri); }
public ComputeApiClient(IHttpClient client) { if (client == null) throw new ArgumentNullException("client", "Argument cannot be null"); WebApi = new WebApi(client); }
/// <summary> /// Asynchronously uploads a synth packet to the Photosynth upload service for processing in the cloud. /// </summary> /// <param name="webApi">A WebApi object for handling HTTP communication with the Photosynth web service</param> /// <param name="fileStorage">An IFileStorage implementation for handling file I/O</param> /// <param name="synthPacketUpload">Metadata for the synth packet to be uploaded.</param> /// <param name="cancellationToken">A cancellation token.</param> /// <param name="parallelism">The maximum number of chunks that can be uploaded in parallel.</param> /// <returns>The task object representing the asynchronous operation</returns> public async Task UploadSynthPacketAsync( WebApi webApi, IFileStorage fileStorage, SynthPacketUpload synthPacketUpload, CancellationToken cancellationToken, int parallelism = 2) { if (this.IsUploading) { throw new InvalidOperationException("Only one upload at a time per Uploader instance is allowed."); } if (string.IsNullOrWhiteSpace(synthPacketUpload.Title)) { throw new ArgumentException("Must provide a Title for the SynthPacketUpload."); } try { this.IsUploading = true; this.Id = Guid.Empty; this.ProgressPercentage = 0; this.EstimatedTimeRemaining = string.Empty; this.FailedChunks.Clear(); // Create a new Photosynth collection this.Status = "Creating collection..."; var createCollectionRequest = new CreateMediaRequest() { UploadType = UploadType.SynthPacketFromRawImages }; var createCollectionResponse = await webApi.CreateMediaAsync(createCollectionRequest); this.ProgressPercentage = 1; this.Id = createCollectionResponse.Id; // Add images to the collection and get upload URLs for each file this.Status = "Adding images to collection..."; var addFilesRequest = new AddFilesRequest(); for (int i = 0; i < synthPacketUpload.PhotoPaths.Count; i++) { addFilesRequest.Files.Add(new AddFileRequest() { Id = i.ToString(), Extension = "jpg", Order = i.ToString("000"), ChunkCount = 1, }); } var addFilesResponse = await webApi.AddFilesAsync(this.Id, addFilesRequest); this.ProgressPercentage = 2; // Get info about all the files that need uploading List<ChunkInfo> chunks = addFilesRequest.Files.Join( addFilesResponse.Files, req => req.Id, resp => resp.ClientId, (req, resp) => { string photoPath = synthPacketUpload.PhotoPaths[Int32.Parse(resp.ClientId)]; FileChunk chunk = resp.Chunks.First(); return new ChunkInfo(chunk.UploadUri, photoPath, fileStorage.GetFileSize(photoPath)); }).ToList(); // Commit the collection, no more files can be added this.Status = "Setting properties for the collection..."; var editMediaRequest = new EditMediaRequest() { Name = synthPacketUpload.Title, Description = synthPacketUpload.Description, ImageCount = synthPacketUpload.PhotoPaths.Count, PrivacyLevel = synthPacketUpload.PrivacyLevel, CapturedDate = synthPacketUpload.CapturedDate, Committed = true, SynthPacket = new SynthPacket() { License = synthPacketUpload.License, }, UploadHints = synthPacketUpload.Topology.ToString() // TODO geotag }; if (synthPacketUpload.Tags.Any()) { editMediaRequest.Tags = string.Join(",", synthPacketUpload.Tags); } await webApi.EditMediaAsync(this.Id, editMediaRequest); this.ProgressPercentage = 3; var failedChunks = await this.UploadChunksAsync(webApi, fileStorage, chunks, 3, cancellationToken, parallelism); foreach (var failedChunk in failedChunks) { this.FailedChunks.Add(failedChunk); } this.ProgressPercentage = 100; if (this.FailedChunks.Any()) { this.Status = string.Format(CultureInfo.CurrentUICulture, "{0} files failed to upload.", this.FailedChunks.Count); } else { this.Status = string.Format(CultureInfo.CurrentUICulture, "{0} files successfully uploaded.", chunks.Count); } } catch (Exception e) { this.Status = string.Format(CultureInfo.CurrentUICulture, "Error: {0}", e.Message); } finally { this.IsUploading = false; } }
private async Task<IEnumerable<ChunkInfo>> UploadChunksAsync( WebApi webApi, IFileStorage fileStorage, List<ChunkInfo> chunks, int progressBaseline, CancellationToken cancellationToken, int parallelism) { // Assume all chunks failed until successfully uploaded var failedChunks = new List<ChunkInfo>(chunks.ToArray()); long totalBytes = chunks.Sum(chunk => chunk.TotalBytes); if (totalBytes > MinimumByteCount) { this.EstimatedTimeRemaining = "Estimating remaining time"; } Stopwatch stopwatch = Stopwatch.StartNew(); // Create a callback that updates the progress and remaining time estimate Action updateProgress = () => { long totalBytesSent = chunks.Sum(c => c.BytesSent); if (totalBytesSent >= MinimumByteCount) { long totalBytesRemaining = totalBytes - totalBytesSent; TimeSpan remainingTime = TimeSpan.FromSeconds( Math.Max(1, Math.Round((double)totalBytesRemaining * stopwatch.Elapsed.TotalSeconds / (double)totalBytesSent))); double mbps = (double)totalBytesSent / stopwatch.Elapsed.TotalSeconds * 8e-6; this.EstimatedTimeRemaining = string.Format( CultureInfo.CurrentCulture, "About {0} remaining ({1:#,##0.##} Mbps)", remainingTime.FormatTimeSpan(), mbps); } double progressFraction = totalBytesSent / (double)totalBytes; this.ProgressPercentage = progressBaseline + 90 * progressFraction; }; this.Status = "Uploading files..."; Action<IEnumerable<ChunkInfo>> uploadChunks = chunkSlice => { foreach (var chunk in chunkSlice) { using (var stream = fileStorage.GetFileStream(chunk.FilePath, FileMode.Open)) { bool uploaded = webApi.UploadFileAsync(chunk.UploadUri, stream, cancellationToken, bytesSent => { chunk.BytesSent = bytesSent; updateProgress(); }).Result; if (uploaded) { chunk.BytesSent = chunk.TotalBytes; lock (failedChunks) { failedChunks.Remove(chunk); } } updateProgress(); } if (cancellationToken.IsCancellationRequested) { break; } } }; // Split into n segments and assign a task to each int sliceCount = Math.Min(chunks.Count, parallelism); int sliceLength = chunks.Count / sliceCount; await Task.WhenAll(Enumerable.Range(0, sliceCount).Select(i => Task.Run(() => { if (i == sliceCount - 1) { // The last slice may be larger than the rest uploadChunks(chunks.Skip(i * sliceLength)); } else { uploadChunks(chunks.Skip(i * sliceLength).Take(sliceLength)); } })).ToArray()); // Measure the upload rate in megabits per second. (There are 8 bits per byte and 10^6 bits per megabit, so we scale bytes-per-second by 8*10^-6.) stopwatch.Stop(); double averageMbps = (double)totalBytes / stopwatch.Elapsed.TotalSeconds * 8e-6; this.EstimatedTimeRemaining = string.Format("Average upload speed: {0:#,##0.##} Mbps", averageMbps); return failedChunks; }