/// <summary> /// Create a topic and subscription if they don't already exist. /// </summary> static void CreateTopicAndSubscription(PubsubOptions options, ILogger logger) { var topicName = new TopicName(options.ProjectId, options.TopicId); var publisher = PublisherServiceApiClient.Create(); try { publisher.CreateTopic(topicName); } catch (Grpc.Core.RpcException e) when(e.Status.StatusCode == Grpc.Core.StatusCode.AlreadyExists || e.Status.StatusCode == Grpc.Core.StatusCode.PermissionDenied) { logger.LogWarning(0, e, "Could not create topic {0}", topicName); } var subscriptionName = new SubscriptionName( options.ProjectId, options.SubscriptionId); var pushConfig = new PushConfig() { PushEndpoint = $"https://{options.ProjectId}.appspot.com/Push" }; var subscriber = SubscriberServiceApiClient.Create(); try { subscriber.CreateSubscription(subscriptionName, topicName, pushConfig, 20); return; } catch (Grpc.Core.RpcException e) when(e.Status.StatusCode == Grpc.Core.StatusCode.AlreadyExists || e.Status.StatusCode == Grpc.Core.StatusCode.PermissionDenied) { logger.LogWarning(1, e, "Could not create subscription {0}", subscriptionName); } try { subscriber.ModifyPushConfig(subscriptionName, pushConfig); } catch (Grpc.Core.RpcException e) when(e.Status.StatusCode == Grpc.Core.StatusCode.PermissionDenied) { logger.LogWarning(2, e, "Could not modify subscription {0}", subscriptionName); } }
public async Task CreateSubscriptionAsync() { // Snippet: CreateSubscriptionAsync(string,string,PushConfig,int,CallSettings) // Additional: CreateSubscriptionAsync(string,string,PushConfig,int,CancellationToken) // Create client SubscriberClient subscriberClient = SubscriberClient.Create(); // Initialize request argument(s) string formattedName = SubscriberClient.FormatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); string formattedTopic = SubscriberClient.FormatTopicName("[PROJECT]", "[TOPIC]"); PushConfig pushConfig = new PushConfig(); int ackDeadlineSeconds = 0; // Make the request Subscription response = await subscriberClient.CreateSubscriptionAsync(formattedName, formattedTopic, pushConfig, ackDeadlineSeconds); // End snippet }
public string CreateBIMFile(IEnumerable <IObject> iObjs, PushConfig pushConfig) { // Write .BIM file and commit it. List <IObject> objList = iObjs.ToList(); string BIMFilePath = WriteBIMFile(objList, pushConfig.Directory, pushConfig.FileName, pushConfig.RenderMeshOptions); iObjs = objList; // Commit the objects as serialised in the created BIM file. if (!string.IsNullOrWhiteSpace(BIMFilePath)) { CommitNewRevision(BIMFilePath); } return(BIMFilePath); }
public async Task CreateSubscriptionAsync() { // Snippet: CreateSubscriptionAsync(SubscriptionName,TopicName,PushConfig,int,CallSettings) // Additional: CreateSubscriptionAsync(SubscriptionName,TopicName,PushConfig,int,CancellationToken) // Create client SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(); // Initialize request argument(s) SubscriptionName name = new SubscriptionName("[PROJECT]", "[SUBSCRIPTION]"); TopicName topic = new TopicName("[PROJECT]", "[TOPIC]"); PushConfig pushConfig = new PushConfig(); int ackDeadlineSeconds = 0; // Make the request Subscription response = await subscriberClient.CreateSubscriptionAsync(name, topic, pushConfig, ackDeadlineSeconds); // End snippet }
public Subscription CreatePushSubscription(string projectId, string topicId, string subscriptionId, string pushEndpoint) { SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create(); TopicName topicName = TopicName.FromProjectTopic(projectId, topicId); SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId); PushConfig pushConfig = new PushConfig { PushEndpoint = pushEndpoint }; // The approximate amount of time in seconds (on a best-effort basis) Pub/Sub waits for the // subscriber to acknowledge receipt before resending the message. var ackDeadlineSeconds = 60; var subscription = subscriber.CreateSubscription(subscriptionName, topicName, pushConfig, ackDeadlineSeconds); return(subscription); }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected async override void OnNavigatedTo(NavigationEventArgs e) { // TODO: Prepare page for display here. // TODO: If your application contains multiple pages, ensure that you are // handling the hardware Back button by registering for the // Windows.Phone.UI.Input.HardwareButtons.BackPressed event. // If you are using the NavigationHelper provided by some templates, // this event is handled for you. await StatusBar.GetForCurrentView().HideAsync(); PushConfig pushConfig = new PushConfig() { UnifiedPushUri = new Uri("<pushServerURL e.g http(s)//host:port/context >"), VariantId = "<variantID e.g. 1234456-234320>", VariantSecret = "<variantSecret e.g. 1234456-234320>" }; Registration registration = new WnsRegistration(); registration.PushReceivedEvent += HandleNotification; try { await registration.Register(pushConfig); var param = e.Parameter as string; if (!string.IsNullOrEmpty(param)) { await registration.SendMetricWhenAppLaunched(pushConfig, param); } else { onRegistrationComplete(); } } catch (Exception ex) { new MessageDialog("Error", ex.Message).ShowAsync(); } this.InitializeComponent(); }
public void ExecuteTrans(PushConfig config, string dataJson, string dicTypeCode, string dictTypeName) { var _responses = JsonConvert.DeserializeObject <ReturnBasicResponse <BasicResponse> >(dataJson); foreach (var response in _responses.Data) { var _result = repository.GetInfoByGuid(config.FromSystem, response.id.ToString()); if (_result == null) { _result = new T_EXT_BasicData(); _result.BasicDataGuid = Guid.NewGuid(); } _result.FromSystem = config.FromSystem; _result.OneOrgId = config.ChargeLevelOneOrgId; _result.OneOrgName = config.ChargeLevelOneOrgName; _result.DictTypeCode = dicTypeCode; _result.DictTypeName = dictTypeName; _result.DictSort = 0; _result.DictId = response.id.ToString(); _result.DictValue = response.value; _result.DictCreatetime = DateTime.Parse(DateTimeFormat(response.createtime)); _result.DictUpdatetime = DateTime.Parse(DateTimeFormat(response.updatetime)); _result.DictStatus = response.status; _result.DictDescribe = response.describe; _result.UpdaterUserId = "系统同步"; _result.UpdaterUserName = "******"; _result.CreatedDate = DateTime.Now; _result.UpdateDate = DateTime.Now; _result.POCSource = config.POCSource; if (_result.Id == 0) { Add(_result); } else { Save(_result); } } }
/***************************************************/ public IFSContainer Create(IFSContainer fileOrDir, PushType pushType, PushConfig pushConfig) { pushConfig = pushConfig ?? new PushConfig(); if (fileOrDir == null) { return(null); } if (fileOrDir is IFile) { return(CreateJson((FSFile)fileOrDir, pushType, pushConfig) as IFSContainer); } if (fileOrDir is IDirectory) { return(CreateDirectory((FSDirectory)fileOrDir, pushType, pushConfig) as IFSContainer); } BH.Engine.Base.Compute.RecordError($"Could not create {fileOrDir.ToString()}."); return(null); }
protected override void ProcessRecord() { if (InputObject != null) { Subscription = InputObject.Name; } Subscription = GetProjectPrefixForSubscription(Subscription, Project); ModifyPushConfigRequest requestBody = new ModifyPushConfigRequest(); if (!PullConfig.IsPresent) { PushConfig pushConfig = new PushConfig() { PushEndpoint = PushEndpoint }; requestBody.PushConfig = pushConfig; } else { // Setting this to null will change a push config to a pull config. requestBody.PushConfig = null; } try { ProjectsResource.SubscriptionsResource.ModifyPushConfigRequest request = Service.Projects.Subscriptions.ModifyPushConfig(requestBody, Subscription); request.Execute(); } catch (GoogleApiException ex) when(ex.HttpStatusCode == HttpStatusCode.NotFound) { WriteResourceMissingError( exceptionMessage: $"Subscription '{Subscription}' does not exist in project '{Project}'.", errorId: "SubscriptionNotFound", targetObject: Subscription); } }
/***************************************************/ /**** Private Methods ****/ /***************************************************/ private string GetTableName(Type objectType, PushConfig config) { // Get possible table from push config string table = null; if (config != null && !string.IsNullOrWhiteSpace(config.Table)) { table = config.Table; } // If table is already registered, make sure that the type matches. Return error otherwise if (table != null) { if (m_TableTypes.ContainsKey(table)) { if (m_TableTypes[table].Contains(objectType)) { return(table); } else { string message = $"Table {table} expects objects of type {m_TableTypes[table].Select(x => x.ToString()).Aggregate((a,b) => a + " or " + b)}." + "\nThis doesn't match the type of the objects to push ({objectType.ToString()})."; Engine.Base.Compute.RecordError(message); return(null); } } else { return(table); } } else { return(GetMatchingTable(objectType)); } }
public PushConfig ReadPushConfig() { var configName = FHConfig.GetInstance().IsLocalDevelopment ? Constants.LocalConfigFileName : Constants.ConfigFileName; var appProps = ReadAppProps(); var configLocation = Path.Combine(GetPackageDir(), configName); var json = ServiceFinder.Resolve <IIOService>().ReadFile(configLocation); var config = (JObject)JsonConvert.DeserializeObject(json); var configWindows = config["windows"]; var pushConfig = new PushConfig { Alias = (string)config["Alias"], Categories = config["Categories"]?.ToObject <List <string> >(), UnifiedPushUri = new Uri(appProps.host + "/api/v2/ag-push"), VariantId = (string)(configWindows != null ? configWindows["variantID"] : config["variantID"]), VariantSecret = (string)(configWindows != null ? configWindows["variantSecret"] : config["variantSecret"]) }; return(pushConfig); }
public override List <object> Push(IEnumerable <object> objects, string tag = "", PushType pushType = PushType.AdapterDefault, ActionConfig actionConfig = null) { PushConfig pushConfig = actionConfig as PushConfig == null ? new PushConfig() : actionConfig as PushConfig; if (string.IsNullOrWhiteSpace(m_defaultFilePath)) // = if we are about to push multiple files/directories { if (pushType == PushType.DeleteThenCreate && m_Push_enableDeleteWarning && !pushConfig.DisableWarnings) { BH.Engine.Base.Compute.RecordWarning($"You have selected the {nameof(PushType)} {nameof(PushType.DeleteThenCreate)}." + $"\nThis has the potential of deleting files and folders with their contents." + $"\nMake sure that you know what you are doing. This warning will not be repeated." + $"\nRe-enable the component to continue."); m_Push_enableDeleteWarning = false; return(new List <object>()); } } List <IResource> createdFiles = new List <IResource>(); List <IResource> filesOrDirs = objects.OfType <IResource>().Select(fd => fd.ShallowClone()).ToList(); List <object> remainder = objects.Where(o => !(o is IResource)).ToList(); if (remainder.Any()) { if (filesOrDirs.Any()) { BH.Engine.Base.Compute.RecordError($"Input objects are both of type `{nameof(BH.oM.Adapters.File.File)}`/`{nameof(BH.oM.Adapters.File.Directory)}` and generic objects." + $"\nIn order to push them:" + $"\n\t- for the `{nameof(BH.oM.Adapters.File.File)}`/`{nameof(BH.oM.Adapters.File.Directory)}` objects, use a Push using a {nameof(FileAdapter)} with no targetLocation input;" + $"\n\t- for the generic objects, use a Push using a {nameof(FileAdapter)} that specifies a targetLocation."); return(null); } else if (string.IsNullOrWhiteSpace(m_defaultFilePath)) { BH.Engine.Base.Compute.RecordError($"To Push objects that are not of type `{nameof(BH.oM.Adapters.File.File)}` or `{nameof(BH.oM.Adapters.File.Directory)}`," + $"\nyou need to specify a target Location by creating the {nameof(FileAdapter)} through the constructor with inputs."); return(null); } } if (m_defaultFilePath != null) { if (filesOrDirs.Any()) { BH.Engine.Base.Compute.RecordWarning($"A `targetLocation` has been specified in the File_Adapter constructor." + $"\nObjects of type `{nameof(BH.oM.Adapters.File.File)}` or `{nameof(BH.oM.Adapters.File.Directory)}` will be appended to the file at `targetLocation`." + $"\nIf you want to target multiple files, you need create the {nameof(FileAdapter)} through the constructor without inputs."); } } foreach (IResource fileOrDir in filesOrDirs) { if (fileOrDir == null) { continue; } if (fileOrDir is IFile) { string extension = Path.GetExtension(fileOrDir.IFullPath()); if (string.IsNullOrWhiteSpace(extension)) { BH.Engine.Base.Compute.RecordNote($"File {fileOrDir.IFullPath()} has no extension specified. Defaults to JSON."); extension = ".json"; fileOrDir.Name += extension; } if (extension != ".json") { BH.Engine.Base.Compute.RecordWarning($"Cannot create File {fileOrDir.IFullPath()}. Currently only JSON extension is supported."); continue; } } IResource created = Create(fileOrDir as dynamic, pushType, pushConfig); createdFiles.Add(created); } if (remainder.Any()) { string defaultDirectory = Path.GetDirectoryName(m_defaultFilePath); string defaultFileName = Path.GetFileName(m_defaultFilePath); FSFile file = CreateFSFile(defaultDirectory, defaultFileName, remainder); if (remainder.All(o => o is Dataset)) { // Automatically set UseDatasetSerialization to true. pushConfig.UseDatasetSerialization = true; pushConfig.BeautifyJson = false; } IResource created = Create(file, pushType, pushConfig); if (created != null) { createdFiles.Add(created); } } return(createdFiles.OfType <object>().ToList()); }
public bool CommentIssue(oM.Inspection.Issue bhomIssue, string tdrepoIssueId, PushConfig pushConfig = null) { bool success = true; CheckMediaPath(pushConfig); foreach (var mediaPath in bhomIssue.Media) { string mediaFullPath = pushConfig.MediaDirectory + "/" + mediaPath; success &= CommentIssue(bhomIssue.Name, tdrepoIssueId, mediaPath, mediaFullPath); } return(success); }
/***************************************************/ /**** Public Methods ****/ /***************************************************/ public FSFile CreateJson(FSFile file, PushType pushType, PushConfig pushConfig) { string fullPath = file.IFullPath(); bool fileExisted = System.IO.File.Exists(fullPath); // Put together all of the file content. List <string> allLines = new List <string>(); string json = ""; // Process file content, only if there is any. if (file.Content != null && file.Content.Count != 0) { if (file.Content.All(o => o is Dataset)) { pushConfig.UseDatasetSerialization = true; } if (!pushConfig.UseDatasetSerialization) { allLines.AddRange(file.Content.Where(c => c != null).Select(obj => obj.ToJson() + ",")); // Remove the trailing comma if there is only one element. allLines[allLines.Count - 1] = allLines[allLines.Count - 1].Remove(allLines[allLines.Count - 1].Length - 1); // Join all between square brackets to make a valid JSON array. json = String.Join(Environment.NewLine, allLines); json = "[" + json + "]"; } else { // Use the non-JSON compliant "Dataset" serialization style. // This is a newline-separated concatenation of individual JSON-serialized objects. allLines.AddRange(file.Content.Where(c => c != null).Select(obj => obj.ToJson())); json = String.Join(Environment.NewLine, allLines); } if (pushConfig.BeautifyJson) { try { json = BeautifyJson(json); } catch (Exception e) { BH.Engine.Base.Compute.RecordWarning($"Beautify json failed. File will be created with non-beautified json. Error:\n{e.Message}"); } } } bool filecreated = true; try { // Clarify if we are considering the Push in terms of content or of Files. if (string.IsNullOrWhiteSpace(m_defaultFilePath)) // We are talking about Files/Directories. { if (pushType == PushType.DeleteThenCreate) { if (fileExisted) { System.IO.File.Delete(fullPath); } WriteJsonFile(fullPath, json, true); } else if (pushType == PushType.UpdateOnly) { // Overwrite existing file. if (fileExisted) { WriteJsonFile(fullPath, json, true); } else { BH.Engine.Base.Compute.RecordNote($"File {fullPath} was not updated as no file existed at that location."); } } else if (pushType == PushType.UpdateOrCreateOnly) { // Overwrite existing file. If it doesn't exist, create it. WriteJsonFile(fullPath, json, true); } else if (pushType == PushType.CreateOnly || pushType == PushType.CreateNonExisting) { // Create only if file didn't exist. Do not touch existing ones. if (!fileExisted) { WriteJsonFile(fullPath, json, true); } else { BH.Engine.Base.Compute.RecordNote($"File {fullPath} was not created as it existed already (Pushtype {pushType.ToString()} was specified)."); } } else { BH.Engine.Base.Compute.RecordWarning($"The specified Pushtype of {pushType.ToString()} is not supported for .json files."); filecreated = false; } } else // We are talking about File content. { if (pushType == PushType.DeleteThenCreate) { BH.Engine.Base.Compute.RecordNote($"Replacing entire content of file `{fullPath}`."); // Replace all content. WriteJsonFile(fullPath, json, true); } else if (pushType == PushType.CreateOnly || pushType == PushType.CreateNonExisting || pushType == PushType.UpdateOnly || pushType == PushType.UpdateOrCreateOnly) { // Should be refactored to cover distinct use cases for CreateNonExisting, UpdateOnly, UpdateOrCreateOnly if (fileExisted) { BH.Engine.Base.Compute.RecordNote($"Appending content to file `{fullPath}`."); } WriteJsonFile(fullPath, json, false); } else if (pushType == PushType.CreateNonExisting) { // Currently captured by CreateOnly. // The following ideally should be the default behaviour of the IDiffing method. //IEnumerable<object> allReadContent = ReadContent(fullPath); //IEnumerable<IBHoMObject> bHoMObjects_read = allReadContent.OfType<IBHoMObject>(); //IEnumerable<object> genericObjs_read = allReadContent.Except(bHoMObjects_read); //IEnumerable<IBHoMObject> readBhomObjects_hashAssigned = BH.Engine.Diffing.Modify.SetHashFragment(bHoMObjects_read); //IEnumerable<IBHoMObject> bHoMObjects_create = file.Content.OfType<IBHoMObject>(); //IEnumerable<object> genericObjs_create = file.Content.Except(bHoMObjects_create); //Diff diffGeneric = BH.Engine.Diffing.Compute.DiffGenericObjects(genericObjs_read, genericObjs_create, null, true); // Then combine the two diffs in one. // For old objects (= already in file) do not create. // Create only those that are "new". } else if (pushType == PushType.UpdateOnly || pushType == PushType.UpdateOrCreateOnly) { // Currently captured by CreateOnly. See above. // For old objects (= already in file) Update Them. // For those who are "new": create them only if `UpdateOrCreateOnly` is used. } else { BH.Engine.Base.Compute.RecordWarning($"The specified Pushtype of {pushType.ToString()} is not supported for .json files."); filecreated = false; } } } catch (Exception e) { BH.Engine.Base.Compute.RecordError(e.Message); } if (filecreated) { System.IO.FileInfo fileinfo = new System.IO.FileInfo(fullPath); oM.Adapters.File.FSFile createdFile = fileinfo.ToFiling(); createdFile.Content = file.Content; return(createdFile); } BH.Engine.Base.Compute.RecordError($"Could not create {file.ToString()}"); return(null); }
/***************************************************/ /**** Public Methods ****/ /***************************************************/ public IFSContainer CreateDirectory(FSDirectory dir, PushType pushType, PushConfig pushConfig) { List <BH.oM.Adapters.File.IFSContainer> createdDirs = new List <oM.Adapters.File.IFSContainer>(); bool clearfile = pushType == PushType.DeleteThenCreate ? true : false; string dirFullPath = dir.IFullPath(); bool existed = System.IO.Directory.Exists(dirFullPath); bool directoryCreated = true; try { if (pushType == PushType.DeleteThenCreate) // Deletes and recreates the directory. { if (existed) { System.IO.Directory.Delete(dirFullPath, true); // Deletes the directory and all contents. To make things safer, a Warning is exposed in the Push before proceeding. } System.IO.Directory.CreateDirectory(dirFullPath); } else if (pushType == PushType.CreateOnly || pushType == PushType.CreateNonExisting || pushType == PushType.UpdateOrCreateOnly || pushType == PushType.UpdateOnly) { // Create only directories that didn't exist. if (pushType != PushType.UpdateOnly) { if (!existed) { System.IO.Directory.CreateDirectory(dirFullPath); } else { BH.Engine.Base.Compute.RecordNote($"Directory {dirFullPath} was not created as it existed already (Pushtype {pushType.ToString()} was specified)."); directoryCreated = false; } } if (dir.Content != null && dir.Content.Any()) { for (int i = 0; i < dir.Content.Count; i++) { ILocatableResource item = (dir.Content[i] as ILocatableResource).DeepClone(); if (item == null) { BH.Engine.Base.Compute.RecordWarning($"Cannot push Directory content {dir.Content[i].GetType().Name}."); } string itemFullPath = item.IFullPath(); if (string.IsNullOrWhiteSpace(itemFullPath) && !string.IsNullOrWhiteSpace(item.Name)) { itemFullPath = Path.Combine(dirFullPath, item.Name); // Default to Container Directory path. item.Location = Path.GetDirectoryName(itemFullPath); } if (item.Location == dirFullPath) { Create(item, pushType, pushConfig); } else { BH.Engine.Base.Compute.RecordWarning($"The content of the Directory {dirFullPath} can't be Pushed because the content Path {itemFullPath} does not match the container Directory path."); } } } } else { BH.Engine.Base.Compute.RecordWarning($"The specified Pushtype of {pushType.ToString()} is not supported for {nameof(BH.oM.Adapters.File.FSDirectory)} objects."); directoryCreated = false; } } catch (Exception e) { BH.Engine.Base.Compute.RecordError(e.Message); } if (directoryCreated || existed) { System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(dirFullPath); oM.Adapters.File.FSDirectory createdDir = dirInfo.ToFiling(); return(createdDir); } BH.Engine.Base.Compute.RecordError($"Could not create the Directory {dir.ToString()}."); return(null); }
public void LoadConfig() { AnnouncementConfigData = new AnnouncementConfig(); BadgeAttrConfigData = new BadgeAttrConfig(); ConstStringConfigData = new ConstStringConfig(); CommonConfig = new CommonConfig(); AttrNameConfigData = new AttrNameConfig(); RoleBaseConfigData2 = new BaseDataConfig2(); AttrDataConfigData = new AttrDataConfig(); TeamLevelConfigData = new TeamLevelConfig(); RoleLevelConfigData = new RoleLevelConfig(); NPCConfigData = new NPCDataConfig(); SkillConfig = new SkillConfig(); GoodsConfigData = new GoodsConfig(); StoreGoodsConfigData = new StoreGoodsConfig(); BaseDataBuyConfigData = new BaseDataBuyConfig(); TaskConfigData = new TaskDataConfig(); AwardPackConfigData = new AwardPackDataConfig(); PractiseConfig = new PractiseConfig(); PracticePveConfig = new PracticePveConfig(); PractiseStepConfig = new PractiseStepConfig(); GameModeConfig = new GameModeConfig(); TrainingConfig = new TrainingConfig(); TattooConfig = new TattooConfig(); EquipmentConfigData = new EquipmentConfig(); TourConfig = new TourConfig(); GuideConfig = new GuideConfig(); FunctionConditionConfig = new FunctionConditionConfig(); RoleShapeConfig = new RoleShapeConfig(); FashionConfig = new FashionConfig(); FashionShopConfig = new FashionShopConfig(); VipPrivilegeConfig = new VipPrivilegeConfig(); pushConfig = new PushConfig(); presentHpConfigData = new PresentHpConfig(); LotteryConfig = new LotteryConfig(); starAttrConfig = new StarAttrConfig(); qualityAttrCorConfig = new QualityAttrCorConfig(); skillUpConfig = new SkillUpConfig(); RankConfig = new RankConfig(); signConfig = new SignConfig(); NewComerSignConfig = new NewComerSignConfig(); FightingCapacityConfig = new FightingCapacityConfig(); BodyInfoListConfig = new BodyInfoListConfig(); BadgeSlotsConfig = new BadgeSlotConfig(); GoodsComposeNewConfigData = new GoodsComposeNewConfig(); SceneConfig = new SceneConfig(); ReboundAttrConfigData = new ReboundAttrConfig(); CareerConfigData = new CareerConfig(); PotientialEffectConfig = new PotientialEffectConfig(); PVPPointConfig = new PVPPointConfig(); WinningStreakAwardConfig = new WinningStreakAwardConfig(); ArticleStrengthConfig = new ArticleStrengthConfig(); PhRegainConfig = new PhRegainConfig(); MatchAchievementConfig = new MatchAchievementConfig(); SpecialActionConfig = new SpecialActionConfig(); StealConfig = new StealConfig(); CurveRateConfig = new CurveRateConfig(); DunkRateConfig = new DunkRateConfig(); AIConfig = new AIConfig(); AttrReduceConfig = new AttrReduceConfig(); qualifyingConfig = new QualifyingConfig(); qualifyingNewConfig = new QualifyingNewConfig(); qualifyingNewerConfig = new QualifyingNewerConfig(); bullFightConfig = new BullFightConfig(); HedgingConfig = new HedgingConfig(); roleGiftConfig = new RoleGiftConfig(); DebugConfig = new DebugConfig(); shootGameConfig = new ShootGameConfig(); MapConfig = new MapConfig(); activityConfig = new ActivityConfig(); trialConfig = new TrialConfig(); gameMatchConfig = new GameMatchConfig(); shootSolutionManager = new ShootSolutionManager(); talentConfig = new TalentConfig(); ladderConfig = new LadderConfig(); matchSoundConfig = new MatchSoundConfig(); matchMsgConfig = new MatchMsgConfig(); MatchPointsConfig = new MatchPointsConfig(); AnimationSampleManager.Instance.LoadXml(); }
public bool Create(IEnumerable <oM.Inspection.Issue> bhomIssues, PushConfig pushConfig) { bool success = true; string mediaDirectory = pushConfig.MediaDirectory; CheckMediaPath(pushConfig); foreach (oM.Inspection.Issue bhomIssue in bhomIssues) { // Convert BHoM Audits to 3DRepo issues. BH.oM.Adapters.TDRepo.Issue issue = bhomIssue.ToTDRepo(mediaDirectory); // Serialise the object. All property names must have the first letter lowercase for 3DRepo API, hence the need for serialiserSettings. var serializerSettings = new Newtonsoft.Json.JsonSerializerSettings(); serializerSettings.ContractResolver = new IssueContractResolver();; string issue_serialised = Newtonsoft.Json.JsonConvert.SerializeObject(issue, serializerSettings); // Endpoint for creating a new issue string issueEndpoint = $"{m_host}/{m_teamspace}/{m_modelId}/issues?key={m_userAPIKey}"; // POST request HttpResponseMessage respMessage; string fullResponse = ""; var httpContent = new StringContent(issue_serialised, Encoding.UTF8, "application/json"); using (HttpClient httpClient = new HttpClient()) { respMessage = httpClient.PostAsync(issueEndpoint, httpContent).Result; // Process response fullResponse = respMessage.Content.ReadAsStringAsync().Result; } // Deserialise the response. serializerSettings.ContractResolver = new IssueContractResolver(); BH.oM.Adapters.TDRepo.Issue issue_deserial = Newtonsoft.Json.JsonConvert.DeserializeObject <BH.oM.Adapters.TDRepo.Issue>(fullResponse, serializerSettings); if (!respMessage.IsSuccessStatusCode) { fullResponse = fullResponse.GetResponseBody(); BH.Engine.Reflection.Compute.RecordError($"The server returned a {respMessage.StatusCode} Error:\n" + fullResponse); success = false; } // Assign the CreatedIssue Id to the Audit. string issueId = issue_deserial.Id; SetAdapterId(bhomIssue, issueId); // Try attaching the media (resources) with its dedicated endpoint. if (!AttachResources(bhomIssue, issueId, pushConfig, false)) { // (As this seems to systematically fail) // In case of failure, use 3DRepo's workaround to post Resources in the Comments to the issue. BH.Engine.Reflection.Compute.RecordWarning("Failed attaching Media to the 3DRepo Issue's Resources.\nTrying adding Media as Comments to the Issue on 3DRepo."); CommentIssue(bhomIssue, issueId, pushConfig); } } return(success); }
public bool AttachResources(oM.Inspection.Issue bhomIssue, string tdrepoIssueId, PushConfig pushConfig, bool raiseErrors = true) { bool success = true; if (!bhomIssue.Media?.Any() ?? true) { return(true); } CheckMediaPath(pushConfig); // // - The media needs to be attached as a "Resource" of the issue. // // - This requires a MultipartFormData request. See https://3drepo.github.io/3drepo.io/#api-Issues-attachResource using (HttpClient httpClient = new HttpClient()) { string issueResourceEndpoint = $"{m_host}/{m_teamspace}/{m_modelId}/issues/{tdrepoIssueId}/resources?key={m_userAPIKey}"; foreach (string mediaPath in bhomIssue.Media) { // Remember that BHoMIssues have media attached as a partial file path. string fullMediaPath = System.IO.Path.Combine(pushConfig.MediaDirectory ?? "C:\\temp\\", mediaPath); var f = System.IO.File.OpenRead(fullMediaPath); StreamContent imageContent = new StreamContent(f); MultipartFormDataContent mpcontent = new MultipartFormDataContent(); mpcontent.Add(imageContent, "file", mediaPath); StringContent nameContent = new StringContent(Path.GetFileNameWithoutExtension(mediaPath)); mpcontent.Add(nameContent, "names"); // POST request HttpResponseMessage respMessage = null; try { respMessage = httpClient.PostAsync(issueResourceEndpoint, mpcontent).Result; } catch (AggregateException e) { string errors = $"Error(s) attaching multiple resources (media) for issue `{tdrepoIssueId}` named `{bhomIssue.Name}`:"; foreach (var innerException in e.Flatten().InnerExceptions) { errors += $"\n\t{innerException.Message}\n{innerException.InnerException}"; } if (raiseErrors) { BH.Engine.Reflection.Compute.RecordError(errors); } return(false); } finally { f.Close(); } // Process response string fullResponse = respMessage?.Content.ReadAsStringAsync().Result; if (respMessage != null && !respMessage.IsSuccessStatusCode) { fullResponse = fullResponse.GetResponseBody(); BH.Engine.Reflection.Compute.RecordWarning($"While attaching multiple resources (media) for issue `{tdrepoIssueId}` named `{bhomIssue.Name}`," + $"\nthe server returned a '{respMessage.StatusCode}' error for media `{mediaPath}`:\n ==>" + fullResponse); success = false; } } } return(success); }
protected override void ProcessRecord() { if (InputObject != null) { Subscription = InputObject.Name; } Subscription = GetProjectPrefixForSubscription(Subscription, Project); ModifyPushConfigRequest requestBody = new ModifyPushConfigRequest(); if (!PullConfig.IsPresent) { PushConfig pushConfig = new PushConfig() { PushEndpoint = PushEndpoint }; requestBody.PushConfig = pushConfig; } else { // Setting this to null will change a push config to a pull config. requestBody.PushConfig = null; } try { ProjectsResource.SubscriptionsResource.ModifyPushConfigRequest request = Service.Projects.Subscriptions.ModifyPushConfig(requestBody, Subscription); request.Execute(); } catch (GoogleApiException ex) when (ex.HttpStatusCode == HttpStatusCode.NotFound) { WriteResourceMissingError( exceptionMessage: $"Subscription '{Subscription}' does not exist in project '{Project}'.", errorId: "SubscriptionNotFound", targetObject: Subscription); } }