public void Validate_Calls_Source_Get_Transformer_Transform_Validator_Validate_And_Coercer_Coerce() { const string name = ConfigWrapper<int>.ThePropertyName; var expectedRaw = "1"; var expectedValue = 1; var cache = new TestingCache(); var sourceMock = new Mock<IValueSource>(); sourceMock.Setup(s => s.Get(name, It.IsAny<PropertyInfo>(), out expectedRaw)) .Returns(true); var transformerMock = new Mock<IValueTransformer>(); transformerMock.Setup(x => x.Transform(expectedRaw, name, It.IsAny<PropertyInfo>())) .Returns(expectedRaw); var validatorMock = new Mock<IValueValidator>(); validatorMock.Setup(s => s.Validate(expectedRaw, name, It.IsAny<PropertyInfo>(), out expectedValue)) .Returns(false); var coercerMock = new Mock<IValueCoercer>(); coercerMock.Setup(c => c.Coerce(expectedRaw, name, It.IsAny<PropertyInfo>(), out expectedValue)) .Returns(true); var config = new ConfigWrapper<int>(cache, sourceMock.Object, transformerMock.Object, validatorMock.Object, coercerMock.Object); config.Validate(); sourceMock.Verify(s => s.Get(name, It.IsAny<PropertyInfo>(), out expectedRaw), Times.Once); transformerMock.Verify(x => x.Transform(expectedRaw, name, It.IsAny<PropertyInfo>()), Times.Once); validatorMock.Verify(v => v.Validate(expectedRaw, name, It.IsAny<PropertyInfo>(), out expectedValue), Times.Once); coercerMock.Verify(c => c.Coerce(expectedRaw, name, It.IsAny<PropertyInfo>(), out expectedValue), Times.Once); }
public void Constructor_With_String_Array_Works() { var args = new[] { "argument1", "argument2" }; var config = new ConfigWrapper<object>(args); Assert.IsNotNull(config); }
public void ClearCache_Calls_Cache_Clear() { var cacheMock = new Mock<IValueCache>(); var config = new ConfigWrapper<object>(cacheMock.Object, null, null, null, null); config.ClearCache(); cacheMock.Verify(c => c.Clear(), Times.Once); }
public void Get_Calls_Cache_Get() { const string name = "__value__"; var expected = new object(); var cacheMock = new Mock<IValueCache>(); cacheMock.Setup(c => c.Get(name, It.IsAny<Func<string, object>>())) .Returns(expected); var config = new ConfigWrapper<object>(cacheMock.Object, null, null, null, null); var result = config.Get_Wrapper(name); cacheMock.Verify(c => c.Get(name, It.IsAny<Func<string, object>>()), Times.Once); Assert.AreSame(expected, result); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { MediaServicesHelpers.LogInformation(log, "C# HTTP trigger function processed a request."); dynamic data; try { data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } var generalOutputInfos = new List <GeneralOutputInfo>(); var liveEventName = (string)data.liveEventName; if (liveEventName == null) { return(IrdetoHelpers.ReturnErrorException(log, "Error - please pass liveEventName in the JSON")); } // default settings var eventInfoFromCosmos = new LiveEventSettingsInfo { LiveEventName = liveEventName }; // Load config from Cosmos try { var setting = await CosmosHelpers.ReadSettingsDocument(liveEventName); eventInfoFromCosmos = setting ?? eventInfoFromCosmos; if (setting == null) { log.LogWarning("Settings not read from Cosmos."); } } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } // Azure region management var azureRegions = new List <string>(); if ((string)data.azureRegion != null) { azureRegions = ((string)data.azureRegion).Split(',').ToList(); } else { azureRegions.Add((string)null); } // init default var deleteAsset = (data.deleteAsset != null) ? (bool)data.deleteAsset : true; var uniquenessAssets = Guid.NewGuid().ToString().Substring(0, 13); string uniquenessPolicyName = Guid.NewGuid().ToString().Substring(0, 13); var manifestName = liveEventName.ToLower(); if (data.archiveWindowLength != null) { eventInfoFromCosmos.ArchiveWindowLength = (int)data.archiveWindowLength; } var cencKey = new StreamingLocatorContentKey(); var cbcsKey = new StreamingLocatorContentKey(); if (!deleteAsset) // we need to regenerate the keys if the user wants to keep the asset as keys cannot be reused for more than one asset { try { ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), null); MediaServicesHelpers.LogInformation(log, "Irdeto call..."); cencKey = await IrdetoHelpers.GenerateAndRegisterCENCKeyToIrdeto(liveEventName, config); cbcsKey = await IrdetoHelpers.GenerateAndRegisterCBCSKeyToIrdeto(liveEventName, config); MediaServicesHelpers.LogInformation(log, "Irdeto call done."); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex, "Irdeto response error")); } } var clientTasks = new List <Task <LiveEventEntry> >(); // list of locators guid for the new locators var locatorGuids = new List <Guid>(); for (int i = 0; i < 10; i++) { locatorGuids.Add(Guid.NewGuid()); } foreach (var region in azureRegions) { var task = Task <LiveEventEntry> .Run(async() => { Asset asset = null; LiveEvent liveEvent = null; LiveOutput liveOutput = null; bool reuseKeys = false; string storageAccountName = null; var streamingLocatorsPolicies = new Dictionary <string, string>(); // locator name, policy name ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), region ); MediaServicesHelpers.LogInformation(log, "config loaded.", region); MediaServicesHelpers.LogInformation(log, "connecting to AMS account : " + config.AccountName, region); var client = await MediaServicesHelpers.CreateMediaServicesClientAsync(config); // Set the polling interval for long running operations to 2 seconds. // The default value is 30 seconds for the .NET client SDK client.LongRunningOperationRetryTimeout = 2; // let's check that the channel exists liveEvent = await client.LiveEvents.GetAsync(config.ResourceGroup, config.AccountName, liveEventName); if (liveEvent == null) { throw new Exception("Error : live event does not exist !"); } if (liveEvent.ResourceState != LiveEventResourceState.Running && liveEvent.ResourceState != LiveEventResourceState.Stopped) { throw new Exception("Error : live event should be in Running or Stopped state !"); } // get live output(s) - it should be one var myLiveOutputs = client.LiveOutputs.List(config.ResourceGroup, config.AccountName, liveEventName); // get the names of the streaming policies. If not possible, recreate it if (myLiveOutputs.FirstOrDefault() != null) { asset = client.Assets.Get(config.ResourceGroup, config.AccountName, myLiveOutputs.First().AssetName); var streamingLocatorsNames = client.Assets.ListStreamingLocators(config.ResourceGroup, config.AccountName, asset.Name).StreamingLocators.Select(l => l.Name); foreach (var locatorName in streamingLocatorsNames) { var locator = client.StreamingLocators.Get(config.ResourceGroup, config.AccountName, locatorName); if (locator != null) { streamingLocatorsPolicies.Add(locatorName, locator.StreamingPolicyName); if (locator.StreamingPolicyName != PredefinedStreamingPolicy.ClearStreamingOnly) // let's backup the keys to reuse them { if (deleteAsset) // we reuse the keys. Only possible if the previous asset is deleted { reuseKeys = true; var keys = client.StreamingLocators.ListContentKeys(config.ResourceGroup, config.AccountName, locatorName).ContentKeys; cencKey = keys.Where(k => k.LabelReferenceInStreamingPolicy == IrdetoHelpers.labelCenc).FirstOrDefault(); cbcsKey = keys.Where(k => k.LabelReferenceInStreamingPolicy == IrdetoHelpers.labelCbcs).FirstOrDefault(); } } } } if (streamingLocatorsPolicies.Count == 0) // no way to get the streaming policy, let's create a new one { MediaServicesHelpers.LogInformation(log, "Creating streaming policy.", region); var streamingPolicy = await IrdetoHelpers.CreateStreamingPolicyIrdeto(config, client); streamingLocatorsPolicies.Add("", streamingPolicy.Name); } } // let's purge all live output for now foreach (var p in myLiveOutputs) { var assetName = p.AssetName; var thisAsset = client.Assets.Get(config.ResourceGroup, config.AccountName, p.AssetName); if (thisAsset != null) { storageAccountName = thisAsset.StorageAccountName; // let's backup storage account name to create the new asset here } MediaServicesHelpers.LogInformation(log, "deleting live output : " + p.Name, region); await client.LiveOutputs.DeleteAsync(config.ResourceGroup, config.AccountName, liveEvent.Name, p.Name); if (deleteAsset) { MediaServicesHelpers.LogInformation(log, "deleting asset : " + assetName, region); await client.Assets.DeleteAsync(config.ResourceGroup, config.AccountName, assetName); } } if (liveEvent.ResourceState == LiveEventResourceState.Running) { MediaServicesHelpers.LogInformation(log, "reseting live event : " + liveEvent.Name, region); await client.LiveEvents.ResetAsync(config.ResourceGroup, config.AccountName, liveEvent.Name); } else { MediaServicesHelpers.LogInformation(log, "Skipping the reset of live event " + liveEvent.Name + " as it is stopped.", region); } // LIVE OUTPUT CREATION MediaServicesHelpers.LogInformation(log, "Live output creation...", region); try { MediaServicesHelpers.LogInformation(log, "Asset creation...", region); asset = await client.Assets.CreateOrUpdateAsync(config.ResourceGroup, config.AccountName, "asset-" + uniquenessAssets, new Asset(storageAccountName: storageAccountName)); Hls hlsParam = null; liveOutput = new LiveOutput(asset.Name, TimeSpan.FromMinutes(eventInfoFromCosmos.ArchiveWindowLength), null, "output-" + uniquenessAssets, null, null, manifestName, hlsParam); MediaServicesHelpers.LogInformation(log, "create live output...", region); await client.LiveOutputs.CreateAsync(config.ResourceGroup, config.AccountName, liveEventName, liveOutput.Name, liveOutput); } catch (Exception ex) { throw new Exception("live output creation error", ex); } try { // streaming locator(s) creation MediaServicesHelpers.LogInformation(log, "Locator creation...", region); int i = 0; foreach (var entryLocPol in streamingLocatorsPolicies) { StreamingLocator locator = null; var streamingLocatorGuid = locatorGuids[i]; // same locator for the two ouputs if 2 live event namle created var uniquenessLocator = streamingLocatorGuid.ToString().Substring(0, 13); var streamingLocatorName = "locator-" + uniquenessLocator; if (entryLocPol.Value == PredefinedStreamingPolicy.ClearStreamingOnly) { locator = await IrdetoHelpers.CreateClearLocator(config, streamingLocatorName, client, asset, streamingLocatorGuid); } else // DRM content { MediaServicesHelpers.LogInformation(log, "creating DRM locator : " + streamingLocatorName, region); if (!reuseKeys) { MediaServicesHelpers.LogInformation(log, "using new keys.", region); locator = await IrdetoHelpers.SetupDRMAndCreateLocatorWithNewKeys( config, entryLocPol.Value, streamingLocatorName, client, asset, cencKey, cbcsKey, streamingLocatorGuid); } else // no need to create new keys, let's use the exiting one { MediaServicesHelpers.LogInformation(log, "using existing keys.", region); locator = await IrdetoHelpers.SetupDRMAndCreateLocatorWithExistingKeys( config, entryLocPol.Value, streamingLocatorName, client, asset, cencKey, cbcsKey, streamingLocatorGuid); } } MediaServicesHelpers.LogInformation(log, "locator : " + streamingLocatorName, region); i++; } await client.Assets.UpdateAsync(config.ResourceGroup, config.AccountName, asset.Name, asset); } catch (Exception ex) { throw new Exception("locator creation error", ex); } var generalOutputInfo = GenerateInfoHelpers.GenerateOutputInformation(config, client, new List <LiveEvent> { liveEvent }); if (!await CosmosHelpers.CreateOrUpdateGeneralInfoDocument(generalOutputInfo.LiveEvents[0])) { MediaServicesHelpers.LogWarning(log, "Cosmos access not configured.", region); } return(generalOutputInfo.LiveEvents[0]); }); clientTasks.Add(task); } try { Task.WaitAll(clientTasks.ToArray()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } return(new OkObjectResult( JsonConvert.SerializeObject(new GeneralOutputInfo { Success = true, LiveEvents = clientTasks.Select(i => i.Result).ToList() }, Formatting.Indented) )); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); dynamic data; try { data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } var assetName = (string)data.assetName; if (assetName == null) { return(IrdetoHelpers.ReturnErrorException(log, "Error - please pass assetName in the JSON")); } // Azure region management var azureRegions = new List <string>(); if ((string)data.azureRegion != null) { azureRegions = ((string)data.azureRegion).Split(',').ToList(); } else { azureRegions.Add((string)null); } // semaphore file (json structure) VodSemaphore semaphore = null; if (data.semaphore != null) { semaphore = VodSemaphore.FromJson((string)data.semaphore); } // init default var streamingLocatorGuid = Guid.NewGuid(); // same locator for the two ouputs if 2 live event namle created var uniquenessLocator = streamingLocatorGuid.ToString().Substring(0, 13); var streamingLocatorName = "locator-" + uniquenessLocator; string locatorPath = string.Empty; string uniquenessPolicyName = Guid.NewGuid().ToString().Substring(0, 13); // Default content id and semaphare value string irdetoContentId = null; if (semaphore != null && semaphore.DrmContentId != null) // semaphore data has higher priority { irdetoContentId = semaphore.DrmContentId; } else if (data.defaultIrdetoContentId != null) { irdetoContentId = (string)data.defaultIrdetoContentId; } var clientTasks = new List <Task <AssetEntry> >(); foreach (var region in azureRegions) { var task = Task <AssetEntry> .Run(async() => { Asset asset = null; ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), region ); MediaServicesHelpers.LogInformation(log, "config loaded.", region); MediaServicesHelpers.LogInformation(log, "connecting to AMS account : " + config.AccountName, region); var client = await MediaServicesHelpers.CreateMediaServicesClientAsync(config); // Set the polling interval for long running operations to 2 seconds. // The default value is 30 seconds for the .NET client SDK client.LongRunningOperationRetryTimeout = 2; // let's get the asset try { MediaServicesHelpers.LogInformation(log, "Getting asset.", region); asset = await client.Assets.GetAsync(config.ResourceGroup, config.AccountName, assetName); } catch (Exception ex) { throw new Exception("Error when retreving asset by name", ex); } // Locator creation try { StreamingLocator locator = null; locator = await IrdetoHelpers.CreateClearLocator(config, streamingLocatorName, client, asset, streamingLocatorGuid); MediaServicesHelpers.LogInformation(log, "locator : " + locator.Name, region); } catch (Exception ex) { throw new Exception("Error when creating the locator", ex); } // let's build info for the live event and output AssetEntry assetEntry = await GenerateInfoHelpers.GenerateAssetInformation(config, client, asset, semaphore, irdetoContentId, region); var locatorPath2 = assetEntry.StreamingLocators.Where(l => l.StreamingLocatorName == streamingLocatorName).First().Urls.Where(u => u.Protocol == OutputProtocol.SmoothStreaming.ToString()).First().Url; var uriloc = new Uri(locatorPath2); locatorPath = uriloc.Scheme + "://" + uriloc.Host + "/" + uriloc.Segments[1]; if (!await CosmosHelpers.CreateOrUpdateAssetDocument(assetEntry)) { log.LogWarning("Cosmos access not configured."); } return(assetEntry); }); clientTasks.Add(task); } try { Task.WaitAll(clientTasks.ToArray()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } return(new OkObjectResult( JsonConvert.SerializeObject(new VodAssetInfoSimple { CreatedLocatorName = streamingLocatorName, CreatedLocatorPath = locatorPath, Success = true, Asset = clientTasks.Select(i => i.Result).First() }, Formatting.Indented) )); }
public MessageCenter() { Enabled = new ConfigWrapper <bool>("enabled", this, true); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); dynamic data; try { data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } var assetName = (string)data.assetName; if (assetName == null) { return(IrdetoHelpers.ReturnErrorException(log, "Error - please pass assetName in the JSON")); } // Azure region management var azureRegions = new List <string>(); if ((string)data.azureRegion != null) { azureRegions = ((string)data.azureRegion).Split(',').ToList(); } else { azureRegions.Add((string)null); } // semaphore file (json structure) VodSemaphore semaphore = null; if (data.semaphore != null) { semaphore = VodSemaphore.FromJson((string)data.semaphore); } // init default var streamingLocatorGuid = Guid.NewGuid(); // same locator for the two ouputs if 2 live event namle created var uniquenessLocator = streamingLocatorGuid.ToString().Substring(0, 13); var streamingLocatorName = "locator-" + uniquenessLocator; string uniquenessPolicyName = Guid.NewGuid().ToString().Substring(0, 13); // useDRM init var useDRM = true; if (data.useDRM != null) { useDRM = (bool)data.useDRM; } else if (semaphore != null & semaphore.ClearStream != null) { useDRM = !(bool)semaphore.ClearStream; } // Default content id and semaphare value string irdetoContentId = null; if (semaphore != null && semaphore.DrmContentId != null) // semaphore data has higher priority { irdetoContentId = semaphore.DrmContentId; } else if (data.defaultIrdetoContentId != null) { irdetoContentId = (string)data.defaultIrdetoContentId; } DateTime?startTime = null; DateTime?endTime = null; try { if (semaphore != null && semaphore.StartTime != null) { startTime = DateTime.ParseExact(semaphore.StartTime, AssetEntry.DateFormat, System.Globalization.CultureInfo.InvariantCulture); } if (semaphore != null && semaphore.EndTime != null) { endTime = DateTime.ParseExact(semaphore.EndTime, AssetEntry.DateFormat, System.Globalization.CultureInfo.InvariantCulture); } } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } var cencKey = new StreamingLocatorContentKey(); var cbcsKey = new StreamingLocatorContentKey(); if (useDRM) { try { ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), null); MediaServicesHelpers.LogInformation(log, "Irdeto call..."); cencKey = await IrdetoHelpers.GenerateAndRegisterCENCKeyToIrdeto(irdetoContentId, config); cbcsKey = await IrdetoHelpers.GenerateAndRegisterCBCSKeyToIrdeto(irdetoContentId, config); MediaServicesHelpers.LogInformation(log, "Irdeto call done."); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex, "Irdeto response error")); } } var clientTasks = new List <Task <AssetEntry> >(); foreach (var region in azureRegions) { var task = Task <AssetEntry> .Run(async() => { Asset asset = null; StreamingPolicy streamingPolicy = null; ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), region ); MediaServicesHelpers.LogInformation(log, "config loaded.", region); MediaServicesHelpers.LogInformation(log, "connecting to AMS account : " + config.AccountName, region); var client = await MediaServicesHelpers.CreateMediaServicesClientAsync(config); // Set the polling interval for long running operations to 2 seconds. // The default value is 30 seconds for the .NET client SDK client.LongRunningOperationRetryTimeout = 2; if (useDRM) { MediaServicesHelpers.LogInformation(log, "Trying to read streaming policy from Cosmos.", region); string streamingPolicyName = null; // Load streaming policy info from Cosmos try { var info = await CosmosHelpers.ReadStreamingPolicyDocument(new StreamingPolicyInfo() { Project = policyProject, AMSAccountName = config.AccountName }); if (info == null) { log.LogWarning("Streaming policy not read from Cosmos."); } else { streamingPolicyName = info.StreamingPolicyName; } } catch (Exception ex) { throw new Exception("Error reading Cosmos DB", ex); } // STREAMING POLICY CREATION if (streamingPolicyName == null) // not found in Cosmos let's create a new one { MediaServicesHelpers.LogInformation(log, "Creating streaming policy.", region); try { streamingPolicy = await IrdetoHelpers.CreateStreamingPolicyIrdeto(config, client, uniquenessPolicyName); } catch (Exception ex) { throw new Exception("Streaming policy creation error", ex); } try { if (!await CosmosHelpers.CreateOrUpdatePolicyDocument(new StreamingPolicyInfo() { Project = policyProject, AMSAccountName = config.AccountName, StreamingPolicyName = streamingPolicy.Name })) { log.LogWarning("Cosmos access not configured or error."); } } catch (Exception ex) { throw new Exception("Streaming policy write error to Cosmos", ex); } } else { MediaServicesHelpers.LogInformation(log, "Getting streaming policy in AMS.", region); try { streamingPolicy = await client.StreamingPolicies.GetAsync(config.ResourceGroup, config.AccountName, streamingPolicyName); } catch (Exception ex) { throw new Exception("Error when getting streaming policy " + streamingPolicy, ex); } } } // let's get the asset try { MediaServicesHelpers.LogInformation(log, "Getting asset.", region); asset = await client.Assets.GetAsync(config.ResourceGroup, config.AccountName, assetName); } catch (Exception ex) { throw new Exception("Error when retreving asset by name", ex); } // Locator creation try { StreamingLocator locator = null; if (useDRM) { locator = await IrdetoHelpers.SetupDRMAndCreateLocatorWithNewKeys(config, streamingPolicy.Name, streamingLocatorName, client, asset, cencKey, cbcsKey, streamingLocatorGuid, irdetoContentId, startTime, endTime); } else // no DRM { locator = await IrdetoHelpers.CreateClearLocator(config, streamingLocatorName, client, asset, streamingLocatorGuid, startTime, endTime); } MediaServicesHelpers.LogInformation(log, "locator : " + locator.Name, region); } catch (Exception ex) { throw new Exception("Error when creating the locator", ex); } // let's build info for the live event and output AssetEntry assetEntry = await GenerateInfoHelpers.GenerateAssetInformation(config, client, asset, semaphore, irdetoContentId, region); if (!await CosmosHelpers.CreateOrUpdateAssetDocument(assetEntry)) { log.LogWarning("Cosmos access not configured."); } return(assetEntry); }); clientTasks.Add(task); } try { Task.WaitAll(clientTasks.ToArray()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } return(new OkObjectResult( JsonConvert.SerializeObject(new AssetInfo { Success = true, Assets = clientTasks.Select(i => i.Result).ToList() }, Formatting.Indented) )); }
protected void Start() { UseMakerLoadPreferences = new ConfigWrapper <bool>("useMakerPrefs", this, true); }
public LIFXOAuthHelper(Microsoft.Extensions.Options.IOptionsMonitor <ConfigWrapper> optionsAccessor) { _options = optionsAccessor.CurrentValue; }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { MediaServicesHelpers.LogInformation(log, "C# HTTP trigger function processed a request."); dynamic data; try { data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } ConfigWrapper config = null; var generalOutputInfos = new List <GeneralOutputInfo>(); // Azure region management var azureRegions = new List <string>(); if ((string)data.azureRegion != null) { azureRegions = ((string)data.azureRegion).Split(',').ToList(); } else { azureRegions.Add((string)null); } foreach (var region in azureRegions) { try { config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), region ); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } MediaServicesHelpers.LogInformation(log, "config loaded.", region); MediaServicesHelpers.LogInformation(log, "connecting to AMS account : " + config.AccountName, region); var client = await MediaServicesHelpers.CreateMediaServicesClientAsync(config); // Set the polling interval for long running operations to 2 seconds. // The default value is 30 seconds for the .NET client SDK client.LongRunningOperationRetryTimeout = 2; var liveEvents = client.LiveEvents.List(config.ResourceGroup, config.AccountName); // object to store the output of the function var generalOutputInfo = new GeneralOutputInfo(); // let's list live events try { generalOutputInfo = GenerateInfoHelpers.GenerateOutputInformation(config, client, liveEvents.ToList()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } try { var success = new List <bool>(); foreach (var le in generalOutputInfo.LiveEvents) { success.Add(await CosmosHelpers.CreateOrUpdateGeneralInfoDocument(le)); } if (success.Any(b => b == false)) { log.LogWarning("Cosmos access not configured."); } } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } generalOutputInfos.Add(generalOutputInfo); } return(new OkObjectResult( JsonConvert.SerializeObject(new GeneralOutputInfo { Success = true, LiveEvents = generalOutputInfos.SelectMany(i => i.LiveEvents).ToList() }, Formatting.Indented) )); }
public void Awake() { UseLongDescription = Config.Wrap("InfoOnPing", "UseLongDescription", "Whether to show the long description in chat when a pickup is pinged.", false); AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; On.RoR2.UI.PingIndicator.RebuildPing += (orig, self) => { orig(self); try { if (self.GetFieldValue <RoR2.UI.PingIndicator.PingType>("pingType") == RoR2.UI.PingIndicator.PingType.Interactable) // If object is an interactable { GameObject target = self.pingTarget; BarrelInteraction BI = target.GetComponent <BarrelInteraction>(); // Barrel Interactable info PurchaseInteraction PI = target.GetComponent <PurchaseInteraction>(); // Purchase Interactable info GenericPickupController GPC = target.GetComponent <GenericPickupController>(); // Generic item pickup if (BI) { Chat.AddMessage(ExtPingMessages.BarrelMessage(BI)); // Send chat message with name and rewards (gold, exp). Also shows exp needed for next level. Chat.AddMessage(ExtPingMessages.ExpMessage()); } else if (PI && PI.costType != CostTypeIndex.None) // If object is purchasable and has a valid cost type { if (PI.GetComponent <ShopTerminalBehavior>()) // If object is a shop terminal, don't use normal purchasable behavior. { Chat.AddMessage(ExtPingMessages.ShopTerminalMessage(PI.GetComponent <ShopTerminalBehavior>())); // Send chat message with shown pickup name, cost and description } else { Chat.AddMessage(ExtPingMessages.PurchasableMessage(PI)); // Send chat message with name and price info (ex: Chest: $22, Shrine of Blood: 50% HP, etc). } } else if (GPC) // If object is a pickup { PickupIndex pickupIdx = GPC.pickupIndex; if (pickupIdx.itemIndex != ItemIndex.None) { Chat.AddMessage(ExtPingMessages.ItemMessage(pickupIdx)); // Send chat message with item name and description. } else if (pickupIdx.equipmentIndex != EquipmentIndex.None) { Chat.AddMessage(ExtPingMessages.EquipmentMessage(pickupIdx)); // Send chat message with equipment name and description. } } } else if (self.GetFieldValue <RoR2.UI.PingIndicator.PingType>("pingType") == RoR2.UI.PingIndicator.PingType.Enemy) // If object is an enemy/character { GameObject target = self.pingTarget; CharacterBody CB = target.GetComponent <CharacterBody>(); if (CB) { Chat.AddMessage(ExtPingMessages.CharacterHeaderMessage(CB)); Chat.AddMessage(ExtPingMessages.CharacterHealthStatsMessage(CB)); Chat.AddMessage(ExtPingMessages.CharacterDamageStatsMessage(CB)); } } } catch (Exception e) { Debug.LogError(e); } }; }
public void Awake() { //Singleton used for hacky crap :) if (instance == null) { instance = this; } else { Destroy(this); } loadKey = Config.Wrap <int>( "Keybinds", "LoadKey", null, (int)KeyCode.F5); saveKey = Config.Wrap <int>( "Keybinds", "SaveKey", null, (int)KeyCode.F8); //Register our Commands On.RoR2.Console.Awake += (orig, self) => { Generic.CommandHelper.RegisterCommands(self); orig(self); }; //Stop the scene loading objects so we can load our own On.RoR2.SceneDirector.PopulateScene += (orig, self) => { if (!loadingScene) { orig(self); } loadingScene = false; }; //Removing targetGraphic null error On.RoR2.UI.CustomButtonTransition.DoStateTransition += (orig, self, state, instant) => { if (self.targetGraphic != null) { orig(self, state, instant); } }; //Removing targetGraphic null error On.RoR2.UI.CustomScrollbar.DoStateTransition += (orig, self, state, instant) => { if (self.targetGraphic != null) { orig(self, state, instant); } }; //Setup "Load Game" Main Menu button and loading menu On.RoR2.UI.MainMenu.MainMenuController.Start += (orig, self) => { ModButton button = new ModButton("Load Game"); Transform buttonTransform = button.gameObject.transform; buttonTransform.SetParent(self.titleMenuScreen.transform.GetChild(2).transform); buttonTransform.SetSiblingIndex(1); Color32 c = button.baseImage.color; c.a = 73; button.baseImage.color = c; button.rectTransform.localScale = Vector3.one; button.rectTransform.sizeDelta = new Vector2(320, 48); button.buttonSkinController.useRecommendedAlignment = false; button.tmpText.alignment = TextAlignmentOptions.Left; button.tmpText.rectTransform.sizeDelta = new Vector2(-24, -8); GameObject submenuPrefab = new GameObject("Load Game"); GameObject scaledSpace = new GameObject("Scaled Space"); RectTransform scaledRect = scaledSpace.AddComponent <RectTransform>(); scaledRect.anchorMin = new Vector2(0.05f, 0.05f); scaledRect.anchorMax = new Vector2(0.95f, 0.95f); scaledRect.offsetMax = new Vector2(0, 0); scaledRect.offsetMin = new Vector2(0, 0); scaledSpace.transform.SetParent(submenuPrefab.transform); ModPanel topPanel = new ModPanel(); topPanel.gameObject.transform.SetParent(scaledSpace.transform); topPanel.rectTransform.anchorMin = new Vector2(0, 1); topPanel.rectTransform.anchorMax = new Vector2(1, 1); topPanel.rectTransform.sizeDelta = new Vector2(0, 96); topPanel.rectTransform.pivot = new Vector2(0.5f, 1); ModButton backButton = new ModButton("Back"); backButton.gameObject.transform.SetParent(scaledSpace.transform); backButton.customButtonTransition.onClick.AddListener(delegate() { self.SetDesiredMenuScreen(self.titleMenuScreen); }); //ModButton loadButton = new ModButton("Load"); //loadButton.gameObject.transform.SetParent(scaledSpace.transform); //loadButton.customButtonTransition.onClick.AddListener(delegate () { }); ModSubMenu saveMenu = new ModSubMenu("Load Menu", self, submenuPrefab); submenuPrefab.transform.SetParent(saveMenu.subMenuObject.transform); ModScrollBar sb = new ModScrollBar(); sb.gameObject.transform.SetParent(scaledSpace.transform); submenuPrefab.SetActive(false); GameObject contentObject = new GameObject("Content"); contentObject.transform.SetParent(sb.viewportObject.transform); contentObject.AddComponent <CanvasRenderer>(); instance.StartCoroutine(SetupUI(delegate() { backButton.rectTransform.anchoredPosition = new Vector2(0, 0); backButton.rectTransform.anchorMin = new Vector2(0, 0); backButton.rectTransform.anchorMax = new Vector2(0, 0); backButton.rectTransform.sizeDelta = new Vector2(200, 50); backButton.rectTransform.pivot = new Vector2(0, 0); //loadButton.rectTransform.anchorMin = new Vector2(1, 0); //loadButton.rectTransform.anchorMax = new Vector2(1, 0); //loadButton.rectTransform.sizeDelta = new Vector2(200, 50); //loadButton.rectTransform.pivot = new Vector2(1, 0); RectTransform contentRect = contentObject.AddComponent <RectTransform>(); contentRect.sizeDelta = new Vector2(100, 300); sb.scrollRect.content = contentRect; sb.customScrollbar.direction = Scrollbar.Direction.BottomToTop; sb.scrollRect.movementType = ScrollRect.MovementType.Clamped; sb.rectTransform.anchorMin = new Vector2(0, 0); sb.rectTransform.anchorMax = new Vector2(1, 1); sb.rectTransform.sizeDelta = new Vector2(-60, -200); sb.rectTransform.anchoredPosition = new Vector2(0, 0); sb.gameObject.GetComponent <Image>().color = new Color32(16, 16, 16, 150); sb.gameObject.GetComponent <Image>().sprite = Generic.FindResource <Sprite>("texUIHighlightHeader"); sb.gameObject.GetComponent <Image>().color = new Color32(14, 14, 14, 150); sb.gameObject.GetComponent <Image>().type = Image.Type.Sliced; sb.customScrollbar.GetComponent <RectTransform>().anchorMin = new Vector2(0, 0); sb.customScrollbar.GetComponent <RectTransform>().anchorMax = new Vector2(1, 1); sb.customScrollbar.GetComponent <RectTransform>().sizeDelta = new Vector2(20, 0); sb.handleAreaObject.GetComponent <RectTransform>().anchorMin = new Vector2(1, 0); sb.handleAreaObject.GetComponent <RectTransform>().anchorMax = new Vector2(1, 1); sb.handleAreaObject.GetComponent <RectTransform>().sizeDelta = new Vector2(10, 0); sb.handleAreaObject.GetComponent <RectTransform>().pivot = new Vector2(0, 1); sb.handleAreaObject.GetComponent <Image>().sprite = Generic.FindResource <Sprite>("texUICleanButton"); sb.handleAreaObject.GetComponent <Image>().color = new Color32(44, 44, 44, 150); sb.handleAreaObject.GetComponent <Image>().type = Image.Type.Sliced; sb.handleObject.GetComponent <RectTransform>().sizeDelta = new Vector2(20, 0); sb.handleObject.GetComponent <Image>().sprite = Generic.FindResource <Sprite>("texUICleanButton"); sb.handleObject.GetComponent <Image>().type = Image.Type.Sliced; sb.handleOutlineObject.GetComponent <Image>().enabled = false; sb.viewportObject.GetComponent <RectTransform>().anchorMin = new Vector2(0, 0); sb.viewportObject.GetComponent <RectTransform>().anchorMax = new Vector2(1, 1); sb.viewportObject.GetComponent <RectTransform>().sizeDelta = new Vector2(0, 0); contentObject.GetComponent <RectTransform>().anchorMin = new Vector2(0, 0); contentObject.GetComponent <RectTransform>().anchorMax = new Vector2(1, 1); contentObject.GetComponent <RectTransform>().pivot = new Vector2(1, 1); contentObject.GetComponent <RectTransform>().sizeDelta = new Vector2(0, 0); VerticalLayoutGroup contentLayoutGroup = contentObject.AddComponent <VerticalLayoutGroup>(); ContentSizeFitter contentSizeFitter = contentObject.AddComponent <ContentSizeFitter>(); contentSizeFitter.verticalFit = ContentSizeFitter.FitMode.MinSize; foreach (var file in Directory.GetFiles(directory)) { FileStream saveFile = File.Open(file, FileMode.Open); string fileName = saveFile.Name.Replace(directory, "") .Replace(".json", ""); ModButton fileSelectButton = new ModButton(fileName); fileSelectButton.customButtonTransition.onClick.AddListener(delegate() { RoR2.Console.instance.SubmitCmd(null, $"load {fileName}"); }); fileSelectButton.gameObject.GetComponent <LayoutElement>().minHeight = 200; fileSelectButton.gameObject.transform.SetParent(contentObject.transform); saveFile.Close(); } })); button.customButtonTransition.onClick.AddListener(delegate() { self.SetDesiredMenuScreen(saveMenu.submenuMainMenuScreen); submenuPrefab.SetActive(true); }); orig(self); }; //Add save button to pause screen On.RoR2.UI.PauseScreenController.Awake += (orig, self) => { ModButton button = new ModButton("Save"); GameObject buttonObject = button.gameObject; buttonObject.transform.SetParent(self.mainPanel.GetChild(0)); buttonObject.transform.SetSiblingIndex(1); buttonObject.GetComponent <RectTransform>().localScale = Vector3.one; buttonObject.GetComponent <RectTransform>().sizeDelta = new Vector2(320, 48); ModInputField inputField = new ModInputField(); GameObject inputObject = inputField.gameObject; inputObject.transform.SetParent(self.mainPanel.GetChild(0)); inputObject.transform.SetSiblingIndex(1); RectTransform inputRect = inputField.rectTransform; inputRect.sizeDelta = new Vector2(320, 48); inputRect.localScale = new Vector3(1, 1, 1); CustomButtonTransition buttonEvents = buttonObject.GetComponent <CustomButtonTransition>(); buttonEvents.onClick.AddListener(() => { RoR2.Console.instance.SubmitCmd(null, $"save {inputField.tmpInputField.text}"); }); orig(self); }; }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, Microsoft.Azure.WebJobs.ExecutionContext execContext) { MediaServicesHelpers.LogInformation(log, "C# HTTP trigger function processed a request."); dynamic data; try { data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } var assetName = (string)data.assetName; if (assetName == null) { return(IrdetoHelpers.ReturnErrorException(log, "Error - please pass assetName in the JSON")); } List <string> fileNames = new List <string>(); ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), null ); MediaServicesHelpers.LogInformation(log, "connecting to AMS account : " + config.AccountName, null); var client = await MediaServicesHelpers.CreateMediaServicesClientAsync(config); // Set the polling interval for long running operations to 2 seconds. // The default value is 30 seconds for the .NET client SDK client.LongRunningOperationRetryTimeout = 2; MediaServicesHelpers.LogInformation(log, "asset name : " + assetName, null); Asset asset = new Asset(); try { asset = await client.Assets.GetAsync(config.ResourceGroup, config.AccountName, assetName); ListContainerSasInput input = new ListContainerSasInput() { Permissions = AssetContainerPermission.Read, ExpiryTime = DateTime.Now.AddHours(2).ToUniversalTime() }; var responseAssetContSas = await client.Assets.ListContainerSasAsync(config.ResourceGroup, config.AccountName, assetName, input.Permissions, input.ExpiryTime); string uploadSasUrl = responseAssetContSas.AssetContainerSasUrls.First(); Uri sasUri = new Uri(uploadSasUrl); var container = new CloudBlobContainer(sasUri); BlobContinuationToken continuationToken = null; var blobs = new List <IListBlobItem>(); do { BlobResultSegment segment = await container.ListBlobsSegmentedAsync(null, false, BlobListingDetails.Metadata, null, continuationToken, null, null); blobs.AddRange(segment.Results); foreach (IListBlobItem blob in segment.Results) { if (blob.GetType() == typeof(CloudBlockBlob)) { CloudBlockBlob bl = (CloudBlockBlob)blob; fileNames.Add(bl.Name); } } continuationToken = segment.ContinuationToken; }while (continuationToken != null); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } var response = new JObject { { "success", true }, { "assetName", assetName }, { "assetId", asset.AssetId }, { "fileNames", new JArray(fileNames) }, { "container", asset.Container }, { "storageAccountName", asset.StorageAccountName }, { "operationsVersion", AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().Location).Version.ToString() } }; return(new OkObjectResult( response )); }
private void OnSetItemDefs(ItemCatalog.orig_SetItemDefs orig, ItemDef[] itemDefs) { ItemDef[] newItemDefs = new ItemDef[itemDefs.Length]; int i = 0; foreach (ItemDef itemDef in itemDefs) { if (itemDef == null) { i++; continue; } ItemTier currTier = itemDef.tier; int defTier; switch (currTier) { case ItemTier.Tier1: { defTier = 1; break; } case ItemTier.Tier2: { defTier = 2; break; } case ItemTier.Tier3: { defTier = 3; break; } case ItemTier.Lunar: { defTier = 4; break; } case ItemTier.Boss: { defTier = 5; break; } default: { defTier = 0; break; } } string itemName = itemDef.nameToken; if (itemName == null) { itemName = itemDef.itemIndex.ToString(); } itemName = itemName.ToUpper(CultureInfo.InvariantCulture); foreach (string ch in _invalidConfigChars) { itemName = itemName.Replace(ch, string.Empty); } ConfigWrapper <int> c = Config.Wrap("Item Tiers", itemName + " tier", "Tier of this item. 0 is no tier, 1 is white, 2 is green, 3 is red, 4 is lunar", defTier); int newTierNum = c.Value; if (newTierNum == defTier) { newItemDefs[i] = itemDef; i++; continue; } switch (newTierNum) { case 1: { itemDef.tier = ItemTier.Tier1; break; } case 2: { itemDef.tier = ItemTier.Tier2; break; } case 3: { itemDef.tier = ItemTier.Tier3; break; } case 4: { itemDef.tier = ItemTier.Lunar; break; } default: { if (newTierNum == 5 && currTier == ItemTier.Boss) { break; } itemDef.tier = ItemTier.NoTier; break; } } Logger.LogInfo("Changing tier of " + itemName + "."); newItemDefs[i] = itemDef; i++; } orig.Invoke(newItemDefs); }
public void Get_Throws_CoercionException_When_Coercer_Coerce_Returns_False() { const string name = "__value__"; var expectedRaw = "1"; var expectedValue = 1; var cache = new TestingCache(); var sourceMock = new Mock<IValueSource>(); sourceMock.Setup(s => s.Get(name, It.IsAny<PropertyInfo>(), out expectedRaw)) .Returns(true); var transformerMock = new Mock<IValueTransformer>(); transformerMock.Setup(x => x.Transform(expectedRaw, name, It.IsAny<PropertyInfo>())) .Returns(expectedRaw); var validatorMock = new Mock<IValueValidator>(); validatorMock.Setup(s => s.Validate(expectedRaw, name, It.IsAny<PropertyInfo>(), out expectedValue)) .Returns(false); var coercerMock = new Mock<IValueCoercer>(); coercerMock.Setup(c => c.Coerce(expectedRaw, name, It.IsAny<PropertyInfo>(), out expectedValue)) .Returns(false); var config = new ConfigWrapper<int>(cache, sourceMock.Object, transformerMock.Object, validatorMock.Object, coercerMock.Object); config.Get_Wrapper(name); }
public ConfigurationManager() { _showAdvanced = new ConfigWrapper <bool>("showAdvanced", this, false); _showKeybinds = new ConfigWrapper <bool>("showKeybinds", this, true); _showSettings = new ConfigWrapper <bool>("showSettings", this, true); }
public override void InitConfigValues() { // Pistol PistolDamageCoefficient = new FieldConfigWrapper <string>(WrapConfigFloat("PistolDamageCoefficient", "Damage coefficient for the pistol, in percent."), "damageCoefficient", true); PistolBaseDuration = new FieldConfigWrapper <string>(WrapConfigFloat("PistolBaseDuration", "Base duration for the pistol shot, in percent. (Attack Speed)"), "baseDuration", true); PistolFields = new List <IFieldChanger> { PistolBaseDuration, PistolDamageCoefficient }; PistolHitLowerBarrageCooldownPercent = WrapConfigFloat("PistolHitLowerBarrageCooldownPercent", "The amount in percent that the current cooldown of the Barrage Skill should be lowered by. Needs to have PistolHitLowerBarrageCooldownPercent set."); PistolHitLowerBarrageCooldown = WrapConfigStandardBool("PistolHitLowerBarrageCooldown", "If the pistol hit should lower the Barrage Skill cooldown. Needs to have PistolHitLowerBarrageCooldownPercent set to work"); // Laser LaserDamageCoefficient = new FieldConfigWrapper <string>(WrapConfigFloat("LaserDamageCoefficient", "Damage coefficient for the secondary laser, in percent."), "damageCoefficient", true); LaserFields = new List <IFieldChanger> { LaserDamageCoefficient }; // Dash DashResetsSecondCooldown = WrapConfigStandardBool("DashResetsSecondCooldown", "If the dash should reset the cooldown of the second ability."); DashInvulnerability = WrapConfigStandardBool("DashInvulnerability", "If Commando should be invulnerable while dashing."); DashInvulnerabilityTimer = WrapConfigFloat("DashInvulnerabilityTimer", "How long Commando should be invincible for when dashing. Only active when DashInvulnerability is on. 0 = For the whole dash."); // Barrage BarrageScalesWithAttackSpeed = WrapConfigStandardBool("BarrageScalesWithAttackSpeed", "If the barrage bullet count should scale with attack speed. Idea by @Twyla. Needs BarrageScaleModifier to be set."); BarrageScaleModifier = WrapConfigFloat("BarrageScaleCoefficient", "Coefficient for the AttackSpeed scale of Barrage bullet count, in percent. Formula: BCount + BCount * (ATKSP - 1) * Coeff"); BarrageBaseShotAmount = new FieldConfigWrapper <int>( WrapConfigInt("BarrageBaseShotAmount", "How many shots the Barrage skill should fire"), "bulletCount", true); BarrageBaseDurationBetweenShots = new FieldConfigWrapper <string>(WrapConfigFloat("BarrageBaseDurationBetweenShots", "Base duration between shots in the Barrage skill."), "baseDurationBetweenShots", true); BarrageFields = new List <IFieldChanger> { BarrageBaseShotAmount, BarrageBaseDurationBetweenShots }; }
private void Main() { RandomMale = new ConfigWrapper <bool>("RandomMale", PluginNameInternal, true); RandomHotkey = new SavedKeyboardShortcut("RandomHotkey", PluginNameInternal, new KeyboardShortcut(KeyCode.F5)); }
private void OnRegisterEquipment(EquipmentCatalog.orig_RegisterEquipment orig, EquipmentIndex equipmentIndex, EquipmentDef equipmentDef) { if (equipmentDef == null || !equipmentDef.canDrop) { orig.Invoke(equipmentIndex, equipmentDef); return; } int defTier = equipmentDef.isLunar ? 2 : 1; string equipmentNameToken = equipmentDef.nameToken; if (equipmentNameToken == null) { equipmentNameToken = equipmentIndex.ToString(); } string upper = equipmentNameToken.ToUpper(CultureInfo.InvariantCulture); foreach (string ch in _invalidConfigChars) { upper = upper.Replace(ch, string.Empty); } ConfigWrapper <int> c = Config.Wrap("Equipment Tiers", upper + " tier", "Tier of this equipment. 0 is no tier, 1 is standard, 2 is lunar", defTier); int newTier = c.Value; if (newTier == defTier) { orig.Invoke(equipmentIndex, equipmentDef); return; } switch (newTier) { case 1: { equipmentDef.isLunar = false; equipmentDef.colorIndex = ColorCatalog.ColorIndex.Equipment; break; } case 2: { equipmentDef.isLunar = true; equipmentDef.colorIndex = ColorCatalog.ColorIndex.LunarItem; break; } default: { equipmentDef.canDrop = false; equipmentDef.isLunar = false; // Don't know if this is needed, but better safe than sorry! break; } } Logger.LogInfo("Changing tier of " + upper + "."); orig.Invoke(equipmentIndex, equipmentDef); }
public static object LoadConfig(ConfigWrapper config) { return(new IdleTimeout(config)); }
public void InitWrap() { WrapModIsEnabled = Config.Wrap( "Settings", "ModEnabled", "Toggles mod.", true); // Add config options for all settings WrapMoneyIsShared = Config.Wrap( "Settings", "MoneyShared", "Toggles money sharing.", false); WrapMoneyScalar = Config.Wrap( "Settings", "MoneyScalar", "Modifies player count used in calculations of gold earned when money sharing is on.", 1); WrapWhiteItemsShared = Config.Wrap( "Settings", "WhiteItemsShared", "Toggles item sharing for common items.", true); WrapGreenItemsShared = Config.Wrap( "Settings", "GreenItemsShared", "Toggles item sharing for rare items.", true); WrapRedItemsShared = Config.Wrap( "Settings", "RedItemsShared", "Toggles item sharing for legendary items.", true); WrapLunarItemsShared = Config.Wrap( "Settings", "LunarItemsShared", "Toggles item sharing for Lunar items.", false); WrapBossItemsShared = Config.Wrap( "Settings", "BossItemsShared", "Toggles item sharing for boss items.", true); WrapQueensGlandsShared = Config.Wrap( "Balance", "QueensGlandsShared", "Toggles item sharing for specifically the Queen's Gland (reduces possible lag).", false); WrapPrinterCauldronFixEnabled = Config.Wrap( "Balance", "PrinterCauldronFix", "Toggles 3D printer and Cauldron item dupe fix by giving the item directly instead of" + " dropping it on the ground.", true); WrapOverridePlayerScalingEnabled = Config.Wrap( "Balance", "DisablePlayerScaling", "Toggles override of the scalar of interactables (chests, shrines, etc) that spawn in the world to your configured credit.", true); WrapInteractablesCredit = Config.Wrap( "Balance", "InteractablesCredit", "If player scaling via this mod is enabled, the amount of players the game should think are playing in terms of chest spawns.", 1); WrapOverrideBossLootScalingEnabled = Config.Wrap( "Balance", "DisableBossLootScaling", "Toggles override of the scalar of boss loot drops to your configured balance.", true); WrapBossLootCredit = Config.Wrap( "Settings", "BossLootCredit", "Specifies the amount of boss items dropped when boss drop override is true.", 1); WrapDeadPlayersGetItems = Config.Wrap( "Balance", "DeadPlayersGetItems", "Toggles item sharing for dead players.", false); WrapItemBlacklist = Config.Wrap( "Settings", "ItemBlacklist", "Items (by index) that you do not want to share, comma seperated. Please find the item indices at: https://github.com/risk-of-thunder/R2Wiki/wiki/Item-Equipment-names", ""); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { MediaServicesHelpers.LogInformation(log, "C# HTTP trigger function processed a request."); string requestBody = new StreamReader(req.Body).ReadToEnd(); dynamic data = JsonConvert.DeserializeObject(requestBody); // Validate input objects if (data.inputAssetName == null) { return(new BadRequestObjectResult("Please pass inputAssetName in the input object")); } if (data.transformName == null) { return(new BadRequestObjectResult("Please pass transformName in the input object")); } if (data.outputAssetNamePrefix == null) { return(new BadRequestObjectResult("Please pass outputAssetNamePrefix in the input object")); } string inputAssetName = data.inputAssetName; string transformName = data.transformName; string outputAssetNamePrefix = data.outputAssetNamePrefix; string assetStorageAccount = null; if (data.assetStorageAccount != null) { assetStorageAccount = data.assetStorageAccount; } // Azure region management var azureRegions = new List <string>(); if ((string)data.azureRegion != null) { azureRegions = ((string)data.azureRegion).Split(',').ToList(); } else { azureRegions.Add((string)null); } Asset inputAsset = null; string guid = Guid.NewGuid().ToString(); string jobName = "amsv3function-job-" + guid; string encoderOutputAssetName = null; string audioAnalyzerOutputAssetName = null; string videoAnalyzerOutputAssetName = null; JArray outputs = new JArray(); foreach (var region in azureRegions) { ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), region ); MediaServicesHelpers.LogInformation(log, "config loaded.", region); MediaServicesHelpers.LogInformation(log, "connecting to AMS account : " + config.AccountName, region); var client = await MediaServicesHelpers.CreateMediaServicesClientAsync(config); // Set the polling interval for long running operations to 2 seconds. // The default value is 30 seconds for the .NET client SDK client.LongRunningOperationRetryTimeout = 2; try { inputAsset = client.Assets.Get(config.ResourceGroup, config.AccountName, inputAssetName); if (inputAsset == null) { return(new BadRequestObjectResult("Asset for input not found")); } Transform transform = client.Transforms.Get(config.ResourceGroup, config.AccountName, transformName); if (transform == null) { return(new BadRequestObjectResult("Transform not found")); } var jobOutputList = new List <JobOutput>(); for (int i = 0; i < transform.Outputs.Count; i++) { Guid assetGuid = Guid.NewGuid(); string outputAssetName = outputAssetNamePrefix + "-" + assetGuid.ToString(); Asset assetParams = new Asset(null, outputAssetName, null, assetGuid, DateTime.Now, DateTime.Now, null, outputAssetName, null, assetStorageAccount, AssetStorageEncryptionFormat.None); Asset outputAsset = client.Assets.CreateOrUpdate(config.ResourceGroup, config.AccountName, outputAssetName, assetParams); jobOutputList.Add(new JobOutputAsset(outputAssetName)); Preset preset = transform.Outputs[i].Preset; if (encoderOutputAssetName == null && (preset is BuiltInStandardEncoderPreset || preset is StandardEncoderPreset)) { encoderOutputAssetName = outputAssetName; } if (audioAnalyzerOutputAssetName == null && preset is AudioAnalyzerPreset) { audioAnalyzerOutputAssetName = outputAssetName; } if (videoAnalyzerOutputAssetName == null && preset is VideoAnalyzerPreset) { videoAnalyzerOutputAssetName = outputAssetName; } // set up jobOutputs JObject outObject = new JObject(); outObject["Preset"] = preset.ToString().Split('.').Last <string>(); outObject["OutputAssetName"] = outputAssetName; if (preset is BuiltInStandardEncoderPreset || preset is StandardEncoderPreset) { outObject["Category"] = "Encoder"; } else if (preset is AudioAnalyzerPreset || preset is VideoAnalyzerPreset) { outObject["Category"] = "Analyzer"; } else { outObject["Category"] = "Unknown"; } outputs.Add(outObject); } // Use the name of the created input asset to create the job input. JobInput jobInput = new JobInputAsset(assetName: inputAssetName); JobOutput[] jobOutputs = jobOutputList.ToArray(); Job job = client.Jobs.Create( config.ResourceGroup, config.AccountName, transformName, jobName, new Job { Input = jobInput, Outputs = jobOutputs, } ); } catch (ApiErrorException e) { log.LogError($"ERROR: AMS API call failed with error code: {e.Body.Error.Code} and message: {e.Body.Error.Message}"); return(new BadRequestObjectResult("AMS API call error: " + e.Message + "\nError Code: " + e.Body.Error.Code + "\nMessage: " + e.Body.Error.Message)); } catch (Exception e) { log.LogError($"ERROR: Exception with message: {e.Message}"); return(new BadRequestObjectResult("Error: " + e.Message)); } } JObject result = new JObject(); result["jobName"] = jobName; result["jobOutputs"] = outputs; result["encoderOutputAssetName"] = encoderOutputAssetName; result["videoAnalyzerOutputAssetName"] = videoAnalyzerOutputAssetName; result["audioAnalyzerOutputAssetName"] = audioAnalyzerOutputAssetName; return((ActionResult) new OkObjectResult(result)); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); bool success = true; var requestBody = new StreamReader(req.Body).ReadToEnd(); LiveEventSettingsInfo settings = null; try { settings = (LiveEventSettingsInfo)JsonConvert.DeserializeObject(requestBody, typeof(LiveEventSettingsInfo)); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } ConfigWrapper config = null; try { config = new ConfigWrapper( new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build() ); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } log.LogInformation("config loaded."); try { if (!await CosmosHelpers.CreateOrUpdateSettingsDocument(settings)) { log.LogWarning("Cosmos access not configured or error."); success = false; } } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } var response = new JObject { { "Success", success }, { "OperationsVersion", AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().Location).Version.ToString() } }; return(new OkObjectResult( response.ToString() )); }
public frmContacts(string userName, string password) { InitializeComponent(); Dictionary <string, string> ServerInfo = ConfigWrapper.GetSetting("server")[0]; //CHANGE THE TITLE TO MATCH WHOS CONTACT WINDOW THIS IS this.Text = string.Format("{0}'s - Contact List", userName); //CREATE A CONNECTION AND OPEN IT TO THE SERVER ThisConnection.TcpConnection = new TcpClient(); try { ThisConnection.TcpConnection.Connect(ServerInfo["host"], int.Parse(ServerInfo["port"])); } catch { //THIS WILL CATCH THE SERVER REFUSING CONNECTION BECAUSE THE SERVER IS NOT RUNNING OR THE SERVER IP IS INCORRECT //TODO: NEED TO TELL THE USER THIS HAS HAPPENED } //WAIT FOR THE CONNECTION TO CONNECT long StartTicks = DateTime.Now.Ticks; while (ThisConnection.TcpConnection.Connected == false && new TimeSpan(DateTime.Now.Ticks - StartTicks).Seconds <= 5) { System.Threading.Thread.Sleep(10); } if (ThisConnection.TcpConnection.Connected) { //IF THE CONNECTION WORKED THEN SHOW THIS FORM tmrKeepAlive.Enabled = true; //COPY THE STREAM VARIABLE TO THE CONNECTION FOR PASSING AROUND ThisConnection.TcpConnection.SendBufferSize = 1024 * 1024 * 20; ThisConnection.TcpConnection.ReceiveBufferSize = 1024 * 1024 * 20; ThisConnection.NetStream = ThisConnection.TcpConnection.GetStream(); //SETUP THE READING THREAD TO RUN IN THE BACKGROUND WAITING ON DATA TO COME IN mThread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ReadThread)); mThread.SetApartmentState(System.Threading.ApartmentState.STA); mThread.IsBackground = true; mThread.Start(ThisConnection); //HAND SHAKE new Message_HandShake().Send(ThisConnection); //NEED TO AUTHENTICATE AND WAIT FOR A RESPONSE new Message_Authenticate() { UserName = userName, Password = password }.Send(ThisConnection); while (ThisConnection.Authenticated == false && ThisConnection.TcpConnection.Connected) { Application.DoEvents(); } //GET THE USERS CONTACTS ONCE WE ARE CONNECTED new Message_GetContacts().Send(ThisConnection); //GET A LIST OF MISSED CONVERSATIONS if (ConfigWrapper.GetSetting("ConversationSettings").FirstOrDefault() == null || bool.Parse(ConfigWrapper.GetSetting("ConversationSettings").FirstOrDefault()["CheckMissedConversations"]) == true) { new Message_GetMissedConversations() { IsLoginCall = true } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, Microsoft.Azure.WebJobs.ExecutionContext execContext) { MediaServicesHelpers.LogInformation(log, "C# HTTP trigger function processed a request."); dynamic data; try { data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } var generalOutputInfos = new List <GeneralOutputInfo>(); var assetName = (string)data.assetName; if (assetName == null) { return(IrdetoHelpers.ReturnErrorException(log, "Error - please pass assetName in the JSON")); } var fileName = (string)data.fileName; ManifestGenerated smildata = null; VodSemaphore semaphore = null; if (data.semaphore != null) { semaphore = VodSemaphore.FromJson((string)data.semaphore); } // Azure region management var azureRegions = new List <string>(); if ((string)data.azureRegion != null) { azureRegions = ((string)data.azureRegion).Split(',').ToList(); } else { azureRegions.Add((string)null); } foreach (var region in azureRegions) { ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), region ); MediaServicesHelpers.LogInformation(log, "config loaded.", region); MediaServicesHelpers.LogInformation(log, "connecting to AMS account : " + config.AccountName, region); var client = await MediaServicesHelpers.CreateMediaServicesClientAsync(config); // Set the polling interval for long running operations to 2 seconds. // The default value is 30 seconds for the .NET client SDK client.LongRunningOperationRetryTimeout = 2; MediaServicesHelpers.LogInformation(log, "asset name : " + assetName, region); var asset = client.Assets.Get(config.ResourceGroup, config.AccountName, assetName); if (asset == null) { throw new Exception($"Asset {asset} does not exist."); } // Access to container ListContainerSasInput input = new ListContainerSasInput() { Permissions = AssetContainerPermission.ReadWriteDelete, ExpiryTime = DateTime.Now.AddHours(2).ToUniversalTime() }; var responseListSas = await client.Assets.ListContainerSasAsync(config.ResourceGroup, config.AccountName, asset.Name, input.Permissions, input.ExpiryTime); string uploadSasUrl = responseListSas.AssetContainerSasUrls.First(); var sasUri = new Uri(uploadSasUrl); var container = new CloudBlobContainer(sasUri); // Manifest generate smildata = (semaphore == null) ? await ManifestHelpers.LoadAndUpdateManifestTemplate(asset, container, execContext, fileName) : await ManifestHelpers.LoadAndUpdateManifestTemplateUsingSemaphore(semaphore, execContext, fileName); // if not file name passed, then we use the one generated based on mp4 files names if (fileName == null) { fileName = smildata.FileName; } var blob = container.GetBlockBlobReference(fileName); using (Stream s = ManifestHelpers.GenerateStreamFromString(smildata.Content)) { await blob.UploadFromStreamAsync(s); } } var response = new JObject { { "success", true }, { "fileName", fileName }, { "manifestContent", smildata.Content }, { "operationsVersion", AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().Location).Version.ToString() } }; return(new OkObjectResult( response )); }
public SavedKeyboardShortcut(ConfigFile file, string key, string description, KeyboardShortcut defaultShortcut) { Wrapper = file.Wrap(new ConfigDefinition(KeybindCategoryName, key, description), defaultShortcut.Serialize()); Wrapper.SettingChanged += ShortcutChanged; ShortcutChanged(null, null); }
public void Awake() { PercentageConfig = Config.Wrap( "Chance Shrine", "Percentage", "The percentage to modify the chance to fail. 100 = off 50 = half", 93); MessageConfig = Config.Wrap( "Chance Shrine", "Chat Display", "Display the chance to fail in chat.", true); RemoveDefaultMessage = Config.Wrap( "Chance Shrine", "Remove Default Message", "Removes the normal shrine message (Option disabled if Percentage is higher than 100. Affects all players)", false); CooldownConfig = Config.Wrap( "Chance Shrine", "Cooldown", "Remove the cooldown on chance shrines.", true); On.RoR2.Console.Awake += (orig, self) => { CommandHelper.RegisterCommands(self); orig(self); }; On.RoR2.ShrineChanceBehavior.AddShrineStack += (orig, self, interactor) => { orig(self, interactor); CalculateSuccess(self); if (CooldownConfig.Value) { self.SetFieldValue("refreshTimer", 0f); } }; // Reset counter on stage load On.RoR2.Stage.Start += (orig, self) => { count = 0; orig(self); }; if (RemoveDefaultMessage.Value & PercentageConfig.Value < 101) { IL.RoR2.ShrineChanceBehavior.AddShrineStack += il => { var c = new ILCursor(il); var sendBroadcastChat = typeof(Chat).GetMethod("SendBroadcastChat", new[] { typeof(Chat.ChatMessageBase) }); while (c.TryGotoNext(x => x.MatchCall(sendBroadcastChat))) { c.Emit(OpCodes.Pop); c.Remove(); } }; } }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, Microsoft.Azure.WebJobs.ExecutionContext execContext) { MediaServicesHelpers.LogInformation(log, "C# HTTP trigger function processed a request."); dynamic data; try { data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd()); } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } var assetName = (string)data.assetName; if (assetName == null) { return(IrdetoHelpers.ReturnErrorException(log, "Error - please pass assetName in the JSON")); } // Azure region management var azureRegions = new List <string>(); if ((string)data.azureRegion != null) { azureRegions = ((string)data.azureRegion).Split(',').ToList(); } else { azureRegions.Add((string)null); } CopyStatus copyStatus = CopyStatus.Success; foreach (var region in azureRegions) { ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), region ); MediaServicesHelpers.LogInformation(log, "config loaded.", region); MediaServicesHelpers.LogInformation(log, "connecting to AMS account : " + config.AccountName, region); var client = await MediaServicesHelpers.CreateMediaServicesClientAsync(config); // Set the polling interval for long running operations to 2 seconds. // The default value is 30 seconds for the .NET client SDK client.LongRunningOperationRetryTimeout = 2; MediaServicesHelpers.LogInformation(log, "asset name : " + assetName, region); try { var asset = client.Assets.Get(config.ResourceGroup, config.AccountName, assetName); // Access to container ListContainerSasInput input = new ListContainerSasInput() { Permissions = AssetContainerPermission.ReadWrite, ExpiryTime = DateTime.Now.AddHours(6).ToUniversalTime() }; var responseListSas = await client.Assets.ListContainerSasAsync(config.ResourceGroup, config.AccountName, asset.Name, input.Permissions, input.ExpiryTime); string uploadSasUrl = responseListSas.AssetContainerSasUrls.First(); var sasUri = new Uri(uploadSasUrl); var destinationBlobContainer = new CloudBlobContainer(sasUri); BlobResultSegment segment = await destinationBlobContainer.ListBlobsSegmentedAsync(null, true, BlobListingDetails.None, null, null, null, null); foreach (var dest in segment.Results) { var destBlob = dest as CloudBlob; await destBlob.FetchAttributesAsync(); if (destBlob.CopyState.Status == CopyStatus.Aborted || destBlob.CopyState.Status == CopyStatus.Failed) { // Log the copy status description for diagnostics and restart copy await destBlob.StartCopyAsync(destBlob.CopyState.Source); copyStatus = CopyStatus.Pending; } else if (destBlob.CopyState.Status == CopyStatus.Pending) { // We need to continue waiting for this pending copy // However, let us log copy state for diagnostics copyStatus = CopyStatus.Pending; } // else we completed this pending copy } } catch (Exception ex) { return(IrdetoHelpers.ReturnErrorException(log, ex)); } } var response = new JObject { { "success", true }, { "copyStatus", copyStatus.ToString() }, { "isRunning", (copyStatus == CopyStatus.Pending) }, { "isSuccessful", (copyStatus == CopyStatus.Success) }, { "operationsVersion", AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().Location).Version.ToString() } }; return(new OkObjectResult( response )); }
public void Get_Calls_Source_Get_Transformer_Transform_Validator_Validate_And_Coercer_Coerce_Twice_Each_When_Callback_Invoked_Via_Property_Twice_When_Using_A_Real_Cache_Implementation_And_The_Property_Is_Removed_From_The_Cache_In_Between() { const string name = ConfigWrapper<object>.ThePropertyName; var expectedRaw = "{}"; var expectedValue = new object(); var cache = new DictionaryCache(); var sourceMock = new Mock<IValueSource>(); sourceMock.Setup(s => s.Get(name, It.IsAny<PropertyInfo>(), out expectedRaw)) .Returns(true); var transformerMock = new Mock<IValueTransformer>(); transformerMock.Setup(x => x.Transform(expectedRaw, name, It.IsAny<PropertyInfo>())) .Returns(expectedRaw); var validatorMock = new Mock<IValueValidator>(); validatorMock.Setup(s => s.Validate(expectedRaw, name, It.IsAny<PropertyInfo>(), out expectedValue)) .Returns(false); var coercerMock = new Mock<IValueCoercer>(); coercerMock.Setup(c => c.Coerce(expectedRaw, name, It.IsAny<PropertyInfo>(), out expectedValue)) .Returns(true); var config = new ConfigWrapper<object>(cache, sourceMock.Object, transformerMock.Object, validatorMock.Object, coercerMock.Object); var result1 = config.TheProperty; cache.Remove(name); var result2 = config.TheProperty; sourceMock.Verify(s => s.Get(name, It.IsAny<PropertyInfo>(), out expectedRaw), Times.Exactly(2)); transformerMock.Verify(x => x.Transform(expectedRaw, name, It.IsAny<PropertyInfo>()), Times.Exactly(2)); validatorMock.Verify(v => v.Validate(expectedRaw, name, It.IsAny<PropertyInfo>(), out expectedValue), Times.Exactly(2)); coercerMock.Verify(c => c.Coerce(expectedRaw, name, It.IsAny<PropertyInfo>(), out expectedValue), Times.Exactly(2)); Assert.AreEqual(expectedValue, result1); Assert.AreSame(result1, result2); }
public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log, Microsoft.Azure.WebJobs.ExecutionContext execContext) { MediaServicesHelpers.LogInformation(log, "C# HTTP trigger function processed a request."); dynamic data; try { data = JsonConvert.DeserializeObject(new StreamReader(req.Body).ReadToEnd()); } catch (Exception ex) { return IrdetoHelpers.ReturnErrorException(log, ex); } var assetNameStartsWith = (string)data.assetNameStartsWith; if (assetNameStartsWith == null) return IrdetoHelpers.ReturnErrorException(log, "Error - please pass assetNameStartsWith in the JSON"); List<string> assets = new List<string>(); // Azure region management var azureRegions = new List<string>(); if ((string)data.azureRegion != null) { azureRegions = ((string)data.azureRegion).Split(',').ToList(); } else { azureRegions.Add((string)null); } foreach (var region in azureRegions) { ConfigWrapper config = new ConfigWrapper(new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .Build(), region ); MediaServicesHelpers.LogInformation(log, "config loaded.", region); MediaServicesHelpers.LogInformation(log, "connecting to AMS account : " + config.AccountName, region); var client = await MediaServicesHelpers.CreateMediaServicesClientAsync(config); // Set the polling interval for long running operations to 2 seconds. // The default value is 30 seconds for the .NET client SDK client.LongRunningOperationRetryTimeout = 2; MediaServicesHelpers.LogInformation(log, "asset name starts : " + assetNameStartsWith, region); try { ODataQuery<Asset> query = new ODataQuery<Asset>(); string search = "'" + assetNameStartsWith + "'"; query.Filter = "name gt " + search.Substring(0, search.Length - 2) + char.ConvertFromUtf32(char.ConvertToUtf32(search, search.Length - 2) - 1) + new string('z', 262 - search.Length) + "'" + " and name lt " + search.Substring(0, search.Length - 1) + new string('z', 262 - search.Length) + "'"; query.OrderBy = "Properties/Created"; var assetsResult = client.Assets.List(config.ResourceGroup, config.AccountName, query); assets = assetsResult.Select(a => a.Name).ToList(); } catch (Exception ex) { return IrdetoHelpers.ReturnErrorException(log, ex); } } var response = new JObject { {"success", true}, {"assetNames", new JArray(assets)}, { "operationsVersion", AssemblyName.GetAssemblyName(Assembly.GetExecutingAssembly().Location).Version.ToString() } }; return new OkObjectResult( response ); }
public void Get_Calls_Source_Get_Transformer_Transform_Validator_Validate_But_Skips_Coercer_Coerce_When_Callback_Invoked_For_String() { const string name = "__value__"; var expected = "bananas"; var cache = new TestingCache(); var sourceMock = new Mock<IValueSource>(); sourceMock.Setup(s => s.Get(name, null, out expected)) .Returns(true); var transformerMock = new Mock<IValueTransformer>(); transformerMock.Setup(x => x.Transform(expected, name, It.IsAny<PropertyInfo>())) .Returns(expected); var validatorMock = new Mock<IValueValidator>(); validatorMock.Setup(s => s.Validate(expected, name, null, out expected)) .Returns(false); var coercerMock = new Mock<IValueCoercer>(); var config = new ConfigWrapper<string>(cache, sourceMock.Object, transformerMock.Object, validatorMock.Object, coercerMock.Object); var result = config.Get_Wrapper(name); sourceMock.Verify(s => s.Get(name, null, out expected), Times.Once); transformerMock.Verify(x => x.Transform(expected, name, null), Times.Once); validatorMock.Verify(v => v.Validate(expected, name, null, out expected), Times.Once); coercerMock.Verify(c => c.Coerce(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<PropertyInfo>(), out expected), Times.Never); Assert.AreEqual(expected, result); }
private static void SetupSetting(HarmonyInstance harmony, MethodInfo targetMethod, MethodInfo patchMethod, ConfigWrapper <bool> targetSetting) { if (targetSetting.Value) { harmony.Patch(targetMethod, new HarmonyMethod(patchMethod), null); } targetSetting.SettingChanged += (sender, args) => { if (targetSetting.Value) { harmony.Patch(targetMethod, new HarmonyMethod(patchMethod), null); } else { harmony.RemovePatch(targetMethod, patchMethod); } }; }
public void Get_Throws_MissingValueException_When_Source_Get_Returns_Null() { const string name = "__value__"; string expectedRaw; var cache = new TestingCache(); var sourceMock = new Mock<IValueSource>(); sourceMock.Setup(s => s.Get(name, null, out expectedRaw)) .Returns(false); var config = new ConfigWrapper<int>(cache, sourceMock.Object, null, null, null); config.Get_Wrapper(name); }
public override void InitConfigValues() { // Firebolt FireboltAttackSpeedStockScaling = WrapConfigStandardBool("FireboltAttackSpeedStockScaling", "If the charge count of the FireBolt Skill should scale with AttackSpeed. Needs to have FireboltAttackSpeedStockScalingCoefficent set to work."); FireboltAttackSpeedStockScalingCoefficient = WrapConfigFloat("FireboltAttackSpeedStockScalingCoefficient", "Coefficient for charge AttackSpeed scaling, in percent. Formula: Stock + Stock * (ATKSP - 1) * Coeff."); FireboltAttackSpeedCooldownScaling = WrapConfigStandardBool("FireboltAttackSpeedCooldownScaling", "If the cooldown of the Firebolt Skill should scale with AttackSpeed. Needs to have FireboltAttackSpeedCooldownScalingCoefficent set to work."); FireboltAttackSpeedCooldownScalingCoefficient = WrapConfigFloat( "FireboltAttackSpeedCooldownScalingCoefficient", "Coefficient for cooldown AttackSpeed scaling, in percent. Formula: BaseCooldown * (1 / (1 + (ATKSP-1) * Coeff)) ."); // NovaBomb NovaBombMaxChargeDuration = new FieldConfigWrapper <string>(WrapConfigFloat("NovaBombBaseChargeDuration", "Base max charging duration of the NovaBomb"), "baseChargeDuration", true); NovaBombMaxDamageCoefficient = new FieldConfigWrapper <string>(WrapConfigFloat( "NovaBombMaxDamageCoefficient", "Max damage coefficient of the NovaBomb"), "maxDamageCoefficient", true); ChargeNovaBombFields = new List <IFieldChanger> { NovaBombMaxChargeDuration, NovaBombMaxDamageCoefficient }; // Flamethrower FlamethrowerProcCoefficientPerTick = new FieldConfigWrapper <string>(WrapConfigFloat( "FlamethrowerProcCoefficientPerTick", "The coefficient for items per proc of the flamethrower."), "procCoefficientPerTick", true); FlamethrowerMaxDistance = new FieldConfigWrapper <string>(WrapConfigFloat("FlamethrowerMaxDistance", "The max distance of the Flamethrower"), "maxDistance", true); FlamethrowerRadius = new FieldConfigWrapper <string>(WrapConfigFloat("FlamethrowerRadius", "The radius of the Flamethrower"), "radius", true); FlamethrowerTotalDamageCoefficient = new FieldConfigWrapper <string>(WrapConfigFloat( "FlamethrowerTotalDamageCoefficient", "The total damage coefficient for the flamethrower"), "totalDamageCoefficient", true); FlamethrowerIgnitePercentChance = new FieldConfigWrapper <string>(WrapConfigFloat( "FlamethrowerIgnitePercentChance", "The change to ignite per proc in percent."), "ignitePercentChance", true); FlamethrowerFields = new List <IFieldChanger> { FlamethrowerProcCoefficientPerTick, FlamethrowerMaxDistance, FlamethrowerRadius, FlamethrowerTotalDamageCoefficient, FlamethrowerIgnitePercentChance }; FlamethrowerDuration = new FieldConfigWrapper <string>(WrapConfigFloat("FlamethrowerDuration", "The duration of the flamethrower"), "baseFlamethrowerDuration", true); FlamethrowerTickFrequency = new FieldConfigWrapper <string>(WrapConfigFloat("FlamethrowerTickFrequency", "The tick frequency of the flamethrower"), "tickFrequency", true); FlamethrowerTickFrequencyScaleWithAttackSpeed = WrapConfigStandardBool( "FlamethrowerTickFrequencyScaleWithAttackSpeed", "If the tick frequency should scale with AttackSpeed. Needs FlamethrowerTickFrequencyScaleCoefficient to be set to work."); FlamethrowerTickFrequencyScaleCoefficient = WrapConfigFloat("FlamethrowerTickFrequencyScaleCoefficient", "The coefficient for the AttackSpeed scaling of the Flamethrower. Formula: TickFreq + Coeff * (ATKSP - 1) * TickFreq"); FlamethrowerDurationScaleDownWithAttackSpeed = WrapConfigStandardBool("FlamethrowerDurationScaleDownWithAttackSpeed", "If the flame thrower duration should get shorter with more attack speed. Needs FlamethrowerDurationScaleCoefficient to be set."); FlamethrowerDurationScaleCoefficient = WrapConfigFloat("FlamethrowerDurationScaleCoefficient", "The coefficient for flame thrower scaling. Formula: Duration - Coeff * (ATKSP - 1) * Duration. Minimum of FlamethrowerMinimalDuration seconds."); FlamethrowerMinimalDuration = WrapConfigFloat("FlamethrowerMinimalDuration", "The minimal duration of the flamethrower", 1f); }
public void Default_Constructor_Works() { var config = new ConfigWrapper<object>(); Assert.IsNotNull(config); }
public void Awake() { Debug.Log("SavedGames - Original by morris1927"); //Singleton used for hacky crap :) if (instance == null) { instance = this; } else { Destroy(this); } loadKey = Config.Wrap <int>( "Keybinds", "LoadKey", null, (int)KeyCode.F5); saveKey = Config.Wrap <int>( "Keybinds", "SaveKey", null, (int)KeyCode.F8); //Register our Commands On.RoR2.Console.Awake += (orig, self) => { Generic.CommandHelper.RegisterCommands(self); orig(self); }; //Stop the scene loading objects so we can load our own On.RoR2.SceneDirector.PopulateScene += (orig, self) => { if (!loadingScene) { orig(self); } loadingScene = false; }; //Removing targetGraphic null error On.RoR2.UI.CustomButtonTransition.DoStateTransition += (orig, self, state, instant) => { if (self.targetGraphic != null) { orig(self, state, instant); } }; //Removing targetGraphic null error On.RoR2.UI.CustomScrollbar.DoStateTransition += (orig, self, state, instant) => { if (self.targetGraphic != null) { orig(self, state, instant); } }; //Setup "Load Game" Main Menu button and loading menu On.RoR2.UI.MainMenu.MainMenuController.Start += (orig, self) => { ModButton button = new ModButton("Load Game"); Transform buttonTransform = button.gameObject.transform; buttonTransform.SetParent(self.titleMenuScreen.transform.GetChild(2).transform); buttonTransform.SetSiblingIndex(1); Color32 c = button.baseImage.color; c.a = 73; button.baseImage.color = c; button.rectTransform.localScale = Vector3.one; button.rectTransform.sizeDelta = new Vector2(320, 48); button.buttonSkinController.useRecommendedAlignment = false; button.tmpText.alignment = TextAlignmentOptions.Left; button.tmpText.rectTransform.sizeDelta = new Vector2(-24, -8); GameObject submenuPrefab = new GameObject("Load Game"); GameObject scaledSpace = new GameObject("Scaled Space"); RectTransform scaledRect = scaledSpace.AddComponent <RectTransform>(); scaledRect.anchorMin = new Vector2(0.05f, 0.05f); scaledRect.anchorMax = new Vector2(0.95f, 0.95f); scaledRect.offsetMax = new Vector2(0, 0); scaledRect.offsetMin = new Vector2(0, 0); scaledSpace.transform.SetParent(submenuPrefab.transform); ModPanel topPanel = new ModPanel(); topPanel.gameObject.AddComponent <HorizontalLayoutGroup>(); topPanel.gameObject.transform.SetParent(scaledSpace.transform); topPanel.rectTransform.anchorMin = new Vector2(0, 1); topPanel.rectTransform.anchorMax = new Vector2(1, 1); topPanel.rectTransform.sizeDelta = new Vector2(0, 96); topPanel.rectTransform.pivot = new Vector2(0.5f, 1); ModButton backButton = new ModButton("Back"); backButton.gameObject.transform.SetParent(scaledSpace.transform); backButton.customButtonTransition.onClick.AddListener(delegate() { self.SetDesiredMenuScreen(self.titleMenuScreen); }); //ModButton loadButton = new ModButton("Load"); //loadButton.gameObject.transform.SetParent(scaledSpace.transform); //loadButton.customButtonTransition.onClick.AddListener(delegate () { }); ModSubMenu saveMenu = new ModSubMenu("Load Menu", self, submenuPrefab); submenuPrefab.transform.SetParent(saveMenu.subMenuObject.transform); ModScrollBar sb = new ModScrollBar(); sb.gameObject.transform.SetParent(scaledSpace.transform); submenuPrefab.SetActive(false); GameObject contentObject = new GameObject("Content"); contentObject.transform.SetParent(sb.viewportObject.transform); contentObject.AddComponent <CanvasRenderer>(); ModButton sortButton1 = new ModButton("Sort by date"); sortButton1.gameObject.transform.SetParent(topPanel.gameObject.transform); sortButton1.customButtonTransition.onClick.AddListener(delegate() { sortDir = sort == 0 ? !sortDir : true; sort = 0; SortSaves(); }); sortButton1.rectTransform.anchorMin = new Vector2(0, 0.5f); sortButton1.rectTransform.anchorMax = new Vector2(0, 0.5f); sortButton1.rectTransform.pivot = new Vector2(0, 0.5f); sortButton1.rectTransform.anchoredPosition = new Vector2(20, 0); ModButton sortButton2 = new ModButton("Sort by name"); sortButton2.gameObject.transform.SetParent(topPanel.gameObject.transform); sortButton2.customButtonTransition.onClick.AddListener(delegate() { sortDir = sort == 1 ? !sortDir : true; sort = 1; SortSaves(); }); sortButton2.rectTransform.anchorMin = new Vector2(0, 0.5f); sortButton2.rectTransform.anchorMax = new Vector2(0, 0.5f); sortButton2.rectTransform.pivot = new Vector2(0, 0.5f); sortButton2.rectTransform.anchoredPosition = new Vector2(20, 0); instance.StartCoroutine(SetupUI(delegate() { backButton.rectTransform.anchoredPosition = new Vector2(0, 0); backButton.rectTransform.anchorMin = new Vector2(0, 0); backButton.rectTransform.anchorMax = new Vector2(0, 0); backButton.rectTransform.sizeDelta = new Vector2(200, 50); backButton.rectTransform.pivot = new Vector2(0, 0); //loadButton.rectTransform.anchorMin = new Vector2(1, 0); //loadButton.rectTransform.anchorMax = new Vector2(1, 0); //loadButton.rectTransform.sizeDelta = new Vector2(200, 50); //loadButton.rectTransform.pivot = new Vector2(1, 0); RectTransform contentRect = contentObject.AddComponent <RectTransform>(); contentRect.sizeDelta = new Vector2(100, 300); sb.scrollRect.content = contentRect; sb.customScrollbar.direction = Scrollbar.Direction.BottomToTop; sb.scrollRect.movementType = ScrollRect.MovementType.Clamped; sb.rectTransform.anchorMin = new Vector2(0, 0); sb.rectTransform.anchorMax = new Vector2(1, 1); sb.rectTransform.sizeDelta = new Vector2(-60, -200); sb.rectTransform.anchoredPosition = new Vector2(0, 0); sb.gameObject.GetComponent <Image>().color = new Color32(16, 16, 16, 150); sb.gameObject.GetComponent <Image>().sprite = Generic.FindResource <Sprite>("texUIHighlightHeader"); sb.gameObject.GetComponent <Image>().color = new Color32(14, 14, 14, 150); sb.gameObject.GetComponent <Image>().type = Image.Type.Sliced; sb.customScrollbar.GetComponent <RectTransform>().anchorMin = new Vector2(0, 0); sb.customScrollbar.GetComponent <RectTransform>().anchorMax = new Vector2(1, 1); sb.customScrollbar.GetComponent <RectTransform>().sizeDelta = new Vector2(20, 0); sb.handleAreaObject.GetComponent <RectTransform>().anchorMin = new Vector2(1, 0); sb.handleAreaObject.GetComponent <RectTransform>().anchorMax = new Vector2(1, 1); sb.handleAreaObject.GetComponent <RectTransform>().sizeDelta = new Vector2(10, 0); sb.handleAreaObject.GetComponent <RectTransform>().pivot = new Vector2(0, 1); sb.handleAreaObject.GetComponent <Image>().sprite = Generic.FindResource <Sprite>("texUICleanButton"); sb.handleAreaObject.GetComponent <Image>().color = new Color32(44, 44, 44, 150); sb.handleAreaObject.GetComponent <Image>().type = Image.Type.Sliced; sb.handleObject.GetComponent <RectTransform>().sizeDelta = new Vector2(20, 0); sb.handleObject.GetComponent <Image>().sprite = Generic.FindResource <Sprite>("texUICleanButton"); sb.handleObject.GetComponent <Image>().type = Image.Type.Sliced; sb.handleOutlineObject.GetComponent <Image>().enabled = false; sb.viewportObject.GetComponent <RectTransform>().anchorMin = new Vector2(0, 0); sb.viewportObject.GetComponent <RectTransform>().anchorMax = new Vector2(1, 1); sb.viewportObject.GetComponent <RectTransform>().sizeDelta = new Vector2(0, 0); contentObject.GetComponent <RectTransform>().anchorMin = new Vector2(0, 0); contentObject.GetComponent <RectTransform>().anchorMax = new Vector2(1, 1); contentObject.GetComponent <RectTransform>().pivot = new Vector2(1, 1); contentObject.GetComponent <RectTransform>().sizeDelta = new Vector2(0, 0); VerticalLayoutGroup contentLayoutGroup = contentObject.AddComponent <VerticalLayoutGroup>(); ContentSizeFitter contentSizeFitter = contentObject.AddComponent <ContentSizeFitter>(); contentSizeFitter.verticalFit = ContentSizeFitter.FitMode.MinSize; if (Directory.Exists(directory)) { saveButtons.Clear(); foreach (var file in Directory.GetFiles(directory, "*.json")) { FileStream saveFile = File.Open(file, FileMode.Open, FileAccess.ReadWrite); string fileName = saveFile.Name.Replace(directory, "") .Replace(".json", ""); SaveData data; using (var sr = new StreamReader(saveFile)) { data = TinyJson.JSONParser.FromJson <SaveData>(sr.ReadToEnd()); } SaveButton fileSelectButton = new SaveButton(fileName, data); fileSelectButton.customButtonTransition.onClick.AddListener(delegate() { RoR2.Console.instance.SubmitCmd(null, $"load {fileName}"); }); fileSelectButton.container.GetComponent <LayoutElement>().minHeight = 200; fileSelectButton.container.transform.SetParent(contentObject.transform); saveButtons.Add(fileSelectButton); saveFile.Close(); } SortSaves(); } })); button.customButtonTransition.onClick.AddListener(delegate() { self.SetDesiredMenuScreen(saveMenu.submenuMainMenuScreen); submenuPrefab.SetActive(true); }); orig(self); }; //Add save button to pause screen On.RoR2.UI.PauseScreenController.Awake += (orig, self) => { StartCoroutine(CaptureScreen(self)); ModButton button = new ModButton("Save"); GameObject buttonObject = button.gameObject; buttonObject.transform.SetParent(self.mainPanel.GetChild(0)); buttonObject.transform.SetSiblingIndex(1); buttonObject.GetComponent <RectTransform>().localScale = Vector3.one; buttonObject.GetComponent <RectTransform>().sizeDelta = new Vector2(320, 48); ModInputField inputField = new ModInputField(); GameObject inputObject = inputField.gameObject; inputObject.transform.SetParent(self.mainPanel.GetChild(0)); inputObject.transform.SetSiblingIndex(1); inputField.tmpInputField.text = lastSelected; RectTransform inputRect = inputField.rectTransform; inputRect.sizeDelta = new Vector2(320, 48); inputRect.localScale = new Vector3(1, 1, 1); CustomButtonTransition buttonEvents = buttonObject.GetComponent <CustomButtonTransition>(); buttonEvents.onClick.AddListener(delegate { string saveName = inputField.tmpInputField.text; if (File.Exists($"{directory}{saveName}.json")) { SimpleDialogBox box = SimpleDialogBox.Create(); box.headerLabel.text = "Overwrite save?"; box.descriptionLabel.text = "There's already save with that name, are you sure you wish to overwrite it?"; box.AddActionButton(() => { RoR2.Console.instance.SubmitCmd(null, $"save {saveName}"); }, "Overwrite"); box.AddCancelButton("Cancel"); } else { RoR2.Console.instance.SubmitCmd(null, $"save {saveName}"); } }); orig(self); }; }
public void Get_Calls_Source_Get_Transformer_TranmsformValue_Validator_Validate_And_Coercer_Coerce_When_Callback_Invoked() { const string name = "__value__"; var expectedRaw = "1"; var expectedValue = 1; var cache = new TestingCache(); var sourceMock = new Mock<IValueSource>(); sourceMock.Setup(s => s.Get(name, null, out expectedRaw)) .Returns(true); var transformerMock = new Mock<IValueTransformer>(); transformerMock.Setup(x => x.Transform(expectedRaw, name, It.IsAny<PropertyInfo>())) .Returns(expectedRaw); var validatorMock = new Mock<IValueValidator>(); validatorMock.Setup(s => s.Validate(expectedRaw, name, null, out expectedValue)) .Returns(false); var coercerMock = new Mock<IValueCoercer>(); coercerMock.Setup(c => c.Coerce(expectedRaw, name, null, out expectedValue)) .Returns(true); var config = new ConfigWrapper<int>(cache, sourceMock.Object, transformerMock.Object, validatorMock.Object, coercerMock.Object); var result = config.Get_Wrapper(name); sourceMock.Verify(s => s.Get(name, null, out expectedRaw), Times.Once); transformerMock.Verify(x => x.Transform(expectedRaw, name, null), Times.Once); validatorMock.Verify(v => v.Validate(expectedRaw, name, null, out expectedValue), Times.Once); coercerMock.Verify(c => c.Coerce(expectedRaw, name, null, out expectedValue), Times.Once); Assert.AreEqual(expectedValue, result); }
public MessageCenter() { Enabled = Config.Wrap("General", "Show messages in UI", "Allow plugins to show pop-up messages", true); BepInEx.Logging.Logger.Listeners.Add(new MessageLogListener()); }
public void Validate_Throws_ConfigValidationException_When_A_Property_Is_Invalid() { const string name = ConfigWrapper<int>.ThePropertyName; var expectedRaw = "blorb"; int expectedValue; var cache = new TestingCache(); var sourceMock = new Mock<IValueSource>(); sourceMock.Setup(s => s.Get(name, It.IsAny<PropertyInfo>(), out expectedRaw)) .Returns(true); var transformerMock = new Mock<IValueTransformer>(); transformerMock.Setup(x => x.Transform(expectedRaw, name, It.IsAny<PropertyInfo>())) .Returns(expectedRaw); var validatorMock = new Mock<IValueValidator>(); validatorMock.Setup(s => s.Validate(expectedRaw, name, It.IsAny<PropertyInfo>(), out expectedValue)) .Callback(() => { throw new Exception(); }); var config = new ConfigWrapper<int>(cache, sourceMock.Object, transformerMock.Object, validatorMock.Object, null); config.Validate(); }
public SliderUnlocker() { Minimum = new ConfigWrapper <int>("wideslider-minimum", this, -100); Maximum = new ConfigWrapper <int>("wideslider-maximum", this, 200); }