Example #1
0
        internal void MoveNode([NotNull] ResourceTableEntry resourceTableEntry, [NotNull] IEnumerable <ResourceTableEntry> previousEntries)
        {
            Contract.Requires(resourceTableEntry != null);
            Contract.Requires(previousEntries != null);

            if (!CanEdit())
            {
                return;
            }

            var node = _nodes.GetValueOrDefault(resourceTableEntry.Key);

            if (node == null)
            {
                return;
            }

            var prevousNode = previousEntries
                              .Select(entry => _nodes.GetValueOrDefault(entry.Key))
                              .FirstOrDefault(item => item != null);

            if (prevousNode == null)
            {
                return;
            }

            var element = node.Element;

            element.Remove();
            prevousNode.Element.AddAfterSelf(element);

            OnChanged();
        }
Example #2
0
        private static string MakeUriString(IDictionary <string, object> env, IDictionary <string, string[]> requestHeaders)
        {
            string[] hostHeaders;
            string   host = "localhost";

            if (requestHeaders.TryGetValue("Host", out hostHeaders) && hostHeaders.Length > 0)
            {
                host = hostHeaders[0];
            }
            if (string.IsNullOrWhiteSpace(host))
            {
                host = "localhost";
            }
            var    scheme   = env.GetValueOrDefault(OwinKeys.Scheme, "http");
            var    pathBase = env.GetValueOrDefault(OwinKeys.PathBase, string.Empty);
            var    path     = env.GetValueOrDefault(OwinKeys.Path, "/");
            var    uri      = string.Format("{0}://{1}{2}{3}", scheme, host, pathBase, path);
            object queryString;

            if (env.TryGetValue(OwinKeys.QueryString, out queryString))
            {
                if (queryString != null && !string.IsNullOrWhiteSpace((string)queryString))
                {
                    uri = uri + "?" + queryString;
                }
            }
            return(uri);
        }
Example #3
0
        private IEnumerable <string> GetTargetsArray(HttpRequest request)
        {
            IEnumerable <string> targets = null;
            // At the moment, request.Form is throwing an InvalidOperationException...
            //if (request.Form.ContainsKey("targets"))
            //{
            //    targets = request.Form["targets"];
            //}

            IDictionary <string, string> parameters = request.Query.Count > 0
                ? request.Query.ToDictionary(k => k.Key, v => string.Join(";", v.Value))
                : request.Form.ToDictionary(k => k.Key, v => string.Join(";", v.Value));

            if (targets == null)
            {
                string t = parameters.GetValueOrDefault("targets[]");
                if (string.IsNullOrEmpty(t))
                {
                    t = parameters.GetValueOrDefault("targets");
                }
                if (string.IsNullOrEmpty(t))
                {
                    return(null);
                }
                targets = t.Split(',');
            }
            return(targets);
        }
        public RookieDriveFddPlugin(PluginContext context, IDictionary <string, object> pluginConfig)
        {
            kernelRoutines = new Dictionary <ushort, Action>
            {
                { 0x4010, DSKIO },
                { 0x4013, () => DSKCHG_GETDPB(true) },
                { 0x4016, () => DSKCHG_GETDPB(false) },
                { 0x4019, CHOICE },
                { 0x401C, DSKFMT },
                { 0x401F, MTOFF }
            };

            addressOfCallInihrd = pluginConfig.GetValueOrDefault <ushort>("addressOfCallInihrd", 0x176F);
            addressOfCallDrives = pluginConfig.GetValueOrDefault <ushort>("addressOfCallDrives", 0x1850);

            this.slotNumber     = new SlotNumber(pluginConfig.GetValue <byte>("NestorMSX.slotNumber"));
            this.kernelFilePath = pluginConfig.GetMachineFilePath(pluginConfig.GetValueOrDefault("kernelFile", "MsxDosKernel.rom"));

            this.z80    = context.Cpu;
            this.memory = context.SlotsSystem;

            z80.BeforeInstructionFetch += (sender, args) => BeforeZ80InstructionFetch(z80.Registers.PC);

            this.kernelContents = File.ReadAllBytes(kernelFilePath);
            ValidateKernelFileContents(kernelContents);

            host = new UsbHost(new CH376UsbHostHardware(UsbServiceProvider.GetCH376Ports()));
            UpdateCbiInstance();
        }
Example #5
0
 public LanguageServiceMetadata(IDictionary <string, object> data)
     : base(data)
 {
     this.ServiceType = (string)data.GetValueOrDefault("ServiceType");
     this.Layer       = (string)data.GetValueOrDefault("Layer");
     this.Data        = (IReadOnlyDictionary <string, object>)data;
 }
Example #6
0
        private static DateTime ParseExpirationDateFromResult(IDictionary <string, object> resultDictionary)
        {
            DateTime expiration;

            if (Constants.IsWeb)
            {
                // For canvas we get back the time as seconds since now instead of in epoch time.
                long timeTillExpiration = resultDictionary.GetValueOrDefault <long>(LoginResult.ExpirationTimestampKey);
                expiration = DateTime.UtcNow.AddSeconds(timeTillExpiration);
            }
            else
            {
                string expirationStr = resultDictionary.GetValueOrDefault <string>(LoginResult.ExpirationTimestampKey);
                int    expiredTimeSeconds;
                if (int.TryParse(expirationStr, out expiredTimeSeconds) && expiredTimeSeconds > 0)
                {
                    if (Constants.IsGameroom)
                    {
                        expiration = DateTime.UtcNow.AddSeconds(expiredTimeSeconds);
                    }
                    else
                    {
                        expiration = Utilities.FromTimestamp(expiredTimeSeconds);
                    }
                }
                else
                {
                    expiration = DateTime.MaxValue;
                }
            }

            return(expiration);
        }
Example #7
0
        private static void StartTelemetryIfFunctionInvocation(IDictionary <string, object> stateValues)
        {
            if (stateValues == null)
            {
                return;
            }

            string functionName         = stateValues.GetValueOrDefault <string>(ScopeKeys.FunctionName);
            string functionInvocationId = stateValues.GetValueOrDefault <string>(ScopeKeys.FunctionInvocationId);
            string eventName            = stateValues.GetValueOrDefault <string>(ScopeKeys.Event);

            // If we have the invocation id, function name, and event, we know it's a new function. That means
            // that we want to start a new operation and let App Insights track it for us.
            if (!string.IsNullOrEmpty(functionName) &&
                !string.IsNullOrEmpty(functionInvocationId) &&
                eventName == LogConstants.FunctionStartEvent)
            {
                RequestTelemetry request = new RequestTelemetry()
                {
                    Id   = functionInvocationId,
                    Name = functionName
                };

                // We'll need to store this operation context so we can stop it when the function completes
                request.Start();
                stateValues[OperationContext] = request;
            }
        }
Example #8
0
        public void GetValueOrDefault_Self()
        {
            IDictionary <string, int> s = null;

            Assert.Throws <ArgumentNullException>(() => s.GetValueOrDefault("foo"));
            Assert.Throws <ArgumentNullException>(() => s.GetValueOrDefault("foo", 42));
        }
 public IncrementalAnalyzerProviderMetadata(IDictionary <string, object> data) : base(data)
 {
     this.HighPriorityForActiveFile = (bool)data.GetValueOrDefault(
         "HighPriorityForActiveFile"
         );
     this.Name = (string)data.GetValueOrDefault("Name");
 }
 public LanguageServiceMetadata(IDictionary<string, object> data)
     : base(data)
 {
     this.ServiceType = (string)data.GetValueOrDefault("ServiceType");
     this.Layer = (string)data.GetValueOrDefault("Layer");
     this.Data = (IReadOnlyDictionary<string, object>)data;
 }
        public IDeliverableCategory BuildNonRegulatedActivity(string[] headers, IDictionary <string, IEnumerable <PeriodisedValue> > esfValues, IDictionary <string, IEnumerable <PeriodisedValue> > ilrValues)
        {
            var ilrNR01Start = ilrValues.GetValueOrDefault(DeliverableCodeConstants.DeliverableCode_NR01)?.Where(x => x.AttributeName.CaseInsensitiveEquals(FundingSummaryReportConstants.IlrStartEarningsAttribute));
            var ilrNR01Ach   = ilrValues.GetValueOrDefault(DeliverableCodeConstants.DeliverableCode_NR01)?.Where(x => x.AttributeName.CaseInsensitiveEquals(FundingSummaryReportConstants.IlrAchievementEarningsAttribute));
            var esfNR01      = esfValues.GetValueOrDefault(DeliverableCodeConstants.DeliverableCode_NR01)?.Where(x => x.AttributeName.CaseInsensitiveEquals(FundingSummaryReportConstants.EsfReferenceTypeAuthorisedClaims));

            return(new DeliverableCategory(FundingSummaryReportConstants.Total_NonRegulatedActivity)
            {
                GroupHeader = BuildFundingHeader(FundingSummaryReportConstants.Header_NonRegulatedActivity, headers),
                DeliverableSubCategories = new List <IDeliverableSubCategory>
                {
                    new DeliverableSubCategory(FundingSummaryReportConstants.SubCategoryHeader_IlrNonRegulatedActivity, true)
                    {
                        ReportValues = new List <IPeriodisedReportValue>
                        {
                            BuildPeriodisedReportValue(FundingSummaryReportConstants.Deliverable_ILR_NR01_Start, ilrNR01Start),
                            BuildPeriodisedReportValue(FundingSummaryReportConstants.Deliverable_ILR_NR01_Ach, ilrNR01Ach),
                        }
                    },
                    new DeliverableSubCategory(FundingSummaryReportConstants.Default_SubCateogryTitle, false)
                    {
                        ReportValues = new List <IPeriodisedReportValue>
                        {
                            BuildPeriodisedReportValue(FundingSummaryReportConstants.Deliverable_ESF_NR01, esfNR01),
                        }
                    }
                }
            });
        }
Example #12
0
 /// <summary>
 /// Gets a unique key representing a composite value of the four stable metadata token types 
 /// (MetricInstanceSetType, MetricType, RenderingMode and Open) which are used to sub-group 
 /// the metric templates to reduce the amount of iteration required while searching for matches.
 /// </summary>
 /// <param name="tokens">The tokens to be used to create the metric template groupings.</param>
 /// <returns>A metric template grouping key.</returns>
 public static string GetTemplateGroupingId(IDictionary<string, string> tokens)
 {
     return DescriptorHelper.CreateUniqueId(tokens.GetValueOrDefault("MetricInstanceSetType"),
                                     tokens.GetValueOrDefault("MetricType"),
                                     tokens.GetValueOrDefault("RenderingMode"),
                                     tokens.GetValueOrDefault("Open"));
 }
        private void StartTelemetryIfFunctionInvocation(IDictionary <string, object> stateValues)
        {
            if (stateValues == null)
            {
                return;
            }

            // Http and ServiceBus triggers are tracked automatically by the ApplicationInsights SDK
            // In such case a current Activity is present.
            // We won't track and only stamp function specific details on the RequestTelemtery
            // created by SDK via Activity when function ends
            if (Activity.Current == null)
            {
                string functionName         = stateValues.GetValueOrDefault <string>(ScopeKeys.FunctionName);
                string functionInvocationId = stateValues.GetValueOrDefault <string>(ScopeKeys.FunctionInvocationId);
                string eventName            = stateValues.GetValueOrDefault <string>(ScopeKeys.Event);

                // If we have the invocation id, function name, and event, we know it's a new function. That means
                // that we want to start a new operation and let App Insights track it for us.
                if (!string.IsNullOrEmpty(functionName) &&
                    !string.IsNullOrEmpty(functionInvocationId) &&
                    eventName == LogConstants.FunctionStartEvent)
                {
                    RequestTelemetry request = new RequestTelemetry()
                    {
                        Name = functionName
                    };

                    // We'll need to store this operation context so we can stop it when the function completes
                    IOperationHolder <RequestTelemetry> operation = _telemetryClient.StartOperation(request);
                    stateValues[OperationContext] = operation;
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ResourceTableEntry" /> class.
        /// </summary>
        /// <param name="container">The owner.</param>
        /// <param name="key">The resource key.</param>
        /// <param name="index">The original index of the resource in the file.</param>
        /// <param name="languages">The localized values.</param>
        internal ResourceTableEntry([NotNull] ResourceEntity container, [NotNull] string key, double index, [NotNull] IDictionary <CultureKey, ResourceLanguage> languages)
        {
            Contract.Requires(container != null);
            Contract.Requires(!string.IsNullOrEmpty(key));
            Contract.Requires(languages != null);
            Contract.Requires(languages.Any());

            _container = container;
            _key       = key;
            _index     = index;
            _languages = languages;

            _deferredValuesChangedThrottle  = new DispatcherThrottle(() => OnPropertyChanged(nameof(Values)));
            _deferredCommentChangedThrottle = new DispatcherThrottle(() => OnPropertyChanged(nameof(Comment)));

            _values = new ResourceTableValues <string>(_languages, lang => lang.GetValue(_key), (lang, value) => lang.SetValue(_key, value));
            _values.ValueChanged += Values_ValueChanged;

            _comments = new ResourceTableValues <string>(_languages, lang => lang.GetComment(_key), (lang, value) => lang.SetComment(_key, value));
            _comments.ValueChanged += Comments_ValueChanged;

            _fileExists = new ResourceTableValues <bool>(_languages, lang => true, (lang, value) => false);

            _snapshotValues   = new ResourceTableValues <string>(_languages, lang => _snapshot?.GetValueOrDefault(lang.CultureKey)?.Text, (lang, value) => false);
            _snapshotComments = new ResourceTableValues <string>(_languages, lang => _snapshot?.GetValueOrDefault(lang.CultureKey)?.Comment, (lang, value) => false);

            _valueAnnotations   = new ResourceTableValues <ICollection <string> >(_languages, GetValueAnnotations, (lang, value) => false);
            _commentAnnotations = new ResourceTableValues <ICollection <string> >(_languages, GetCommentAnnotations, (lang, value) => false);

            Contract.Assume(languages.Any());
            _neutralLanguage = languages.First().Value;
            Contract.Assume(_neutralLanguage != null);
        }
Example #15
0
        public static InlineCodeExtractionResult ConvertHtmlTagsInInLineCodes(this string htmlText)
        {
            var doc = new HtmlDocument();

            doc.LoadHtml(htmlText);
            var text                = new List <ResourceStringContent>();
            var originalData        = new Dictionary <String, String>();
            int tagCounter          = 0;
            int originalDataCounter = 1;

            foreach (var node in doc.DocumentNode.ChildNodes)
            {
                if (node.NodeType == HtmlNodeType.Text)
                {
                    text.Add(new PlainText(node.InnerText));
                }
                if (node.NodeType == HtmlNodeType.Element && node.HasChildNodes)
                {
                    var inlineCodeType = Map.GetValueOrDefault(node.Name);
                    if (inlineCodeType.Type == null)
                    {
                        text.Add(new PlainText(node.InnerText));
                    }
                    else
                    {
                        tagCounter++;
                        var startTagId = AddOriginalData(originalData, "<" + node.Name + ">", ref originalDataCounter);
                        var endTagId   = AddOriginalData(originalData, "</" + node.Name + ">", ref originalDataCounter);
                        var pc         = new SpanningCode(tagCounter.ToString());
                        pc.DataReferenceStart = startTagId;
                        pc.DataReferenceEnd   = endTagId;
                        pc.Text.Add(new PlainText(node.InnerText));
                        pc.Type    = inlineCodeType.Type;
                        pc.SubType = inlineCodeType.Subtype;
                        text.Add(pc);
                    }
                }
                if (node.NodeType == HtmlNodeType.Element && !node.HasChildNodes)
                {
                    var inlineCodeType = Map.GetValueOrDefault(node.Name);
                    if (inlineCodeType.Type == null)
                    {
                        continue;
                    }
                    tagCounter++;
                    var tagId = AddOriginalData(originalData, "<" + node.Name + "/>", ref originalDataCounter);
                    var ph    = new StandaloneCode(tagCounter.ToString());
                    ph.DataReference = tagId;
                    ph.Type          = inlineCodeType.Type;
                    ph.SubType       = inlineCodeType.Subtype;
                    text.Add(ph);
                }
            }
            return(new InlineCodeExtractionResult()
            {
                OriginalData = originalData,
                Text = text
            });
        }
Example #16
0
 private PollenNumbers GetPollenNumbers(IDictionary <string, int> pollenDictionary)
 {
     return(new PollenNumbers
     {
         Birch = pollenDictionary.GetValueOrDefault(BirchName),
         Grass = pollenDictionary.GetValueOrDefault(GrassName),
     });
 }
Example #17
0
        private static Size ParseSize(IDictionary <string, string> commands, CommandParser parser)
        {
            // The command parser will reject negative numbers as it clamps values to ranges.
            uint width  = parser.ParseValue <uint>(commands.GetValueOrDefault(Width));
            uint height = parser.ParseValue <uint>(commands.GetValueOrDefault(Height));

            return(new Size((int)width, (int)height));
        }
Example #18
0
 /// <summary>
 ///  Initializes a new instance of the <see cref="SerialTransport" /> class.
 /// </summary>
 /// <param name="config">Case insensitive configuration parameters.</param>
 public SerialTransport(IDictionary <string, string> config)
 {
     this.portName = config.GetValueOrDefault(PortNameKey, DefaultPortName);
     this.baudRate = config.GetValueOrDefault(BaudRateKey, DefaultBaudRate, int.TryParse);
     this.parity   = config.GetValueOrDefault(ParityKey, DefaultParity, Enum.TryParse);
     this.dataBits = config.GetValueOrDefault(DataBitsKey, DefaultDataBits, int.TryParse);
     this.stopBits = config.GetValueOrDefault(StopBitsKey, DefaultStopBits, Enum.TryParse);
 }
Example #19
0
 /// <inheritdoc />
 public IDocumentation?TryGetDocumentation(MemberId member)
 {
     return(member switch
     {
         TypeId typeId => m_Types.GetValueOrDefault(typeId)?.TryGetDocumentation(member),
         TypeMemberId typeMemberId => m_Types.GetValueOrDefault(typeMemberId.DefiningType)?.TryGetDocumentation(member),
         NamespaceId namespaceId => m_Namespaces.GetValueOrDefault(namespaceId),
         _ => null
     });
        public SpecialDiskBasicPlugin(PluginContext context, IDictionary <string, object> pluginConfig)
        {
            fileName = pluginConfig.GetMachineFilePath(pluginConfig.GetValueOrDefault <string>("file", "SpecialDiskBasic.rom"));

            context.Cpu.BeforeInstructionFetch += Z80OnBeforeInstructionFetch;
            var filesystemBasePath = pluginConfig.GetValueOrDefault <string>("filesystemBasePath", "$MyDocuments$/NestorMSX/FileSystem").AsAbsolutePath();

            dosFunctionsExecutor = new DosFunctionCallExecutor(context.Cpu.Registers, context.SlotsSystem, filesystemBasePath);
        }
        /// <summary>
        /// Method mostly copied from Microsoft.AspNet.SignalR OwinExtensions class, but without external dependency on Katana.
        /// </summary>
        /// <param name="configuration">The <see cref="HubConfiguration"/> to use.</param>
        /// <param name="startupEnv">Startup parameters.</param>
        /// <param name="next">Next <see cref="AppFunc"/> in pipeline.</param>
        /// <returns><see cref="AppFunc"/> ready for use.</returns>
        public static Func <IDictionary <string, object>, Task> BuildHubFunc(HubConfiguration configuration, IDictionary <string, object> startupEnv, AppFunc next)
        {
            if (configuration == null)
            {
                throw new ArgumentException("No configuration provided");
            }

            var resolver = configuration.Resolver;

            if (resolver == null)
            {
                throw new ArgumentException("No dependency resolver provider");
            }

            var token = startupEnv.GetValueOrDefault("owin.CallCancelled", CancellationToken.None);

            string instanceName = startupEnv.GetValueOrDefault("host.AppName", Guid.NewGuid().ToString());

            var protectedData = new DefaultProtectedData();

            resolver.Register(typeof(IProtectedData), () => protectedData);

            // If the host provides trace output then add a default trace listener
            var traceOutput = startupEnv.GetValueOrDefault("host.TraceOutput", (TextWriter)null);

            if (traceOutput != null)
            {
                var hostTraceListener = new TextWriterTraceListener(traceOutput);
                var traceManager      = new TraceManager(hostTraceListener);
                resolver.Register(typeof(ITraceManager), () => traceManager);
            }

            // Try to get the list of reference assemblies from the host
            IEnumerable <Assembly> referenceAssemblies = startupEnv.GetValueOrDefault("host.ReferencedAssemblies",
                                                                                      (IEnumerable <Assembly>)null);

            if (referenceAssemblies != null)
            {
                // Use this list as the assembly locator
                var assemblyLocator = new EnumerableOfAssemblyLocator(referenceAssemblies);
                resolver.Register(typeof(IAssemblyLocator), () => assemblyLocator);
            }

            resolver.InitializeHost(instanceName, token);

            var hub = new HubDispatcherMiddleware(new KatanaShim(next), configuration);

            return(async env =>
            {
                await hub.Invoke(new OwinContext(env));

                if (!env.ContainsKey("owin.ResponseStatusCode"))
                {
                    env["owin.ResponseStatusCode"] = 200;
                }
            });
        }
        internal void Parsing(string connectionString, string dbId, string collectionId)
        {
            IDictionary <string, string> dict = connectionString.AzureConnectionStringToDictionary(':', '=');

            ConnectionString = connectionString;
            Uri          = dict.GetValueOrDefault(nameof(Uri));
            Key          = dict.GetValueOrDefault(nameof(Key));
            DbId         = dict.GetValueOrDefault(nameof(DbId));
            CollectionId = dict.GetValueOrDefault(nameof(CollectionId));
        }
        internal void Parsing(string connectionString)
        {
            IDictionary <string, string> dictionary = connectionString.AzureConnectionStringToDictionary(';', '=');

            this.ConnectionString         = connectionString;
            this.DefaultEndPointsProtocol = dictionary.GetValueOrDefault(nameof(DefaultEndPointsProtocol));
            this.AccountName    = dictionary.GetValueOrDefault(nameof(AccountName));
            this.AccountKey     = dictionary.GetValueOrDefault(nameof(AccountKey));
            this.EndPointSuffix = dictionary.GetValueOrDefault(nameof(EndPointSuffix));
        }
Example #24
0
            private ArtistDetails(IDictionary <string, object> data)
            {
                const string ID           = "id";
                const string RESOURCE_URL = "resource_url";
                const string NAME         = "name";

                this.Id          = Convert.ToString(data.GetValueOrDefault(ID));
                this.ResourceUrl = Convert.ToString(data.GetValueOrDefault(RESOURCE_URL));
                this.Name        = Convert.ToString(data.GetValueOrDefault(NAME));
            }
        public void GetValueOrDefault()
        {
            var foundValue = _dictionary.GetValueOrDefault("a");

            Assert.That(foundValue, Is.EqualTo("Alpha"));

            var notFoundValue = _dictionary.GetValueOrDefault("z");

            Assert.That(notFoundValue, Is.Null);
        }
Example #26
0
        public static AccessToken ParseAccessTokenFromResult(IDictionary <string, object> resultDictionary)
        {
            string               valueOrDefault  = resultDictionary.GetValueOrDefault(LoginResult.UserIdKey, true);
            string               valueOrDefault2 = resultDictionary.GetValueOrDefault(LoginResult.AccessTokenKey, true);
            DateTime             expirationTime  = Utilities.ParseExpirationDateFromResult(resultDictionary);
            ICollection <string> permissions     = Utilities.ParsePermissionFromResult(resultDictionary);
            DateTime?            lastRefresh     = Utilities.ParseLastRefreshFromResult(resultDictionary);

            return(new AccessToken(valueOrDefault2, valueOrDefault, expirationTime, permissions, lastRefresh));
        }
Example #27
0
 public LearningDeliveryPeriodisedValuesAttributesModel BuildFm35PeriodisedValuesAttributes(IDictionary <string, decimal[]> periodisedValues, int period)
 {
     return(new LearningDeliveryPeriodisedValuesAttributesModel()
     {
         OnProgPayment = periodisedValues.GetValueOrDefault(AttributeConstants.Fm35OnProgPayment)?[period] ?? _defaultDecimal,
         BalancePayment = periodisedValues.GetValueOrDefault(AttributeConstants.Fm35BalancePayment)?[period] ?? _defaultDecimal,
         AchievePayment = periodisedValues.GetValueOrDefault(AttributeConstants.Fm35AchievePayment)?[period] ?? _defaultDecimal,
         EmpOutcomePay = periodisedValues.GetValueOrDefault(AttributeConstants.Fm35EmpOutcomePay)?[period] ?? _defaultDecimal,
         LearnSuppFundCash = periodisedValues.GetValueOrDefault(AttributeConstants.Fm35LearnSuppFundCash)?[period] ?? _defaultDecimal,
     });
 }
Example #28
0
 public static GeographyPoint CreateGeographyPoint(IDictionary <string, object> source)
 {
     return(GeographyPoint.Create(
                CoordinateSystem.Geography(source.ContainsKey("CoordinateSystem")
             ? source.GetValueOrDefault <CoordinateSystem>("CoordinateSystem").EpsgId
             : null),
                source.GetValueOrDefault <double>("Latitude"),
                source.GetValueOrDefault <double>("Longitude"),
                source.GetValueOrDefault <double?>("Z"),
                source.GetValueOrDefault <double?>("M")));
 }
Example #29
0
        protected override void ApplyConfiguration(IDictionary <string, object> pluginConfig)
        {
            maxNumberOfDevices = pluginConfig.GetValueOrDefault("numberOfDrives", 2);
            if (maxNumberOfDevices < 1 || maxNumberOfDevices > 8)
            {
                throw new ConfigurationException("numberOfDrives must be a number between 1 and 8");
            }

            addressOfCallInihrd = pluginConfig.GetValueOrDefault <ushort>("addressOfCallInihrd", 0x176F);
            addressOfCallDrives = pluginConfig.GetValueOrDefault <ushort>("addressOfCallDrives", 0x1850);
        }
Example #30
0
        private void StartTelemetryIfFunctionInvocation(IDictionary <string, object> stateValues)
        {
            if (stateValues == null)
            {
                return;
            }

            // HTTP and ServiceBus triggers are tracked automatically by the ApplicationInsights SDK
            // In such case a current Activity is present.
            // We won't track and only stamp function specific details on the RequestTelemetry
            // created by SDK via Activity when function ends

            var currentActivity = Activity.Current;

            if (currentActivity == null ||
                // Activity is tracked, but Functions wants to ignore it:
                DictionaryLoggerScope.GetMergedStateDictionary().ContainsKey("MS_IgnoreActivity") ||
                // Functions create another RequestTrackingTelemetryModule to make sure first request is tracked (as ASP.NET Core starts before web jobs)
                // however at this point we may discover that RequestTrackingTelemetryModule is disabled by customer and even though Activity exists, request won't be tracked
                // So, if we've got AspNetCore Activity and EnableHttpTriggerExtendedInfoCollection is false - track request here.
                (!_loggerOptions.HttpAutoCollectionOptions.EnableHttpTriggerExtendedInfoCollection && IsHttpRequestActivity(currentActivity)))
            {
                string functionName         = stateValues.GetValueOrDefault <string>(ScopeKeys.FunctionName);
                string functionInvocationId = stateValues.GetValueOrDefault <string>(ScopeKeys.FunctionInvocationId);
                string eventName            = stateValues.GetValueOrDefault <string>(ScopeKeys.Event);

                // If we have the invocation id, function name, and event, we know it's a new function. That means
                // that we want to start a new operation and let App Insights track it for us.
                if (!string.IsNullOrEmpty(functionName) &&
                    !string.IsNullOrEmpty(functionInvocationId) &&
                    eventName == LogConstants.FunctionStartEvent)
                {
                    RequestTelemetry request = new RequestTelemetry
                    {
                        Name = functionName
                    };

                    // We'll need to store this operation context so we can stop it when the function completes
                    IOperationHolder <RequestTelemetry> operation = _telemetryClient.StartOperation(request);

                    if (_loggerOptions.HttpAutoCollectionOptions.EnableW3CDistributedTracing)
                    {
                        // currently ApplicationInsights supports 2 parallel correlation schemes:
                        // legacy and W3C, they both appear in telemetry. UX handles all differences in operation Ids.
                        // This will be resolved in next .NET SDK on Activity level.
                        // This ensures W3C context is set on the Activity.
                        Activity.Current?.GenerateW3CContext();
                    }

                    stateValues[OperationContext] = operation;
                }
            }
        }
Example #31
0
            /// <summary>
            ///  Initializes a new instance of the <see cref="TcpTransport" /> class.
            /// </summary>
            /// <param name="config">Case insensitive configuration parameters.</param>
            public TcpTransport(IDictionary <string, string> config)
            {
                IPAddress endpointAddress = config.GetValueOrDefault(PeripheralConfigKey.IpAddress, IPAddress.None, IPAddress.TryParse);
                int       port            = config.GetValueOrDefault(PeripheralConfigKey.Port, 0, int.TryParse);

                if (endpointAddress.Equals(IPAddress.None) || port <= 0)
                {
                    throw new InvalidOperationException("Invalid internet protocol address or port specified for tcp transport");
                }

                this.Endpoint = new IPEndPoint(endpointAddress, port);
            }
Example #32
0
            private TrackDetails(IDictionary <string, object> data)
            {
                const string POSITION     = "position";
                const string TITLE        = "title";
                const string EXTRAARTISTS = "extraartists";
                const string TYPE         = "type_";

                this.Position = Convert.ToString(data.GetValueOrDefault(POSITION));
                this.Artists  = ArtistDetails.FromResults(data.GetValueOrDefault(EXTRAARTISTS) as IList <object>).ToArray();
                this.Title    = Convert.ToString(data.GetValueOrDefault(TITLE));
                this.Type     = Convert.ToString(data.GetValueOrDefault(TYPE));
            }
        private static AccessToken ParseAccessTokenFromResult(IDictionary<string, object> resultDictionary)
        {
            string userID = resultDictionary.GetValueOrDefault<string>(LoginResult.UserIdKey);
            string accessToken = resultDictionary.GetValueOrDefault<string>(LoginResult.AccessTokenKey);
            DateTime expiration = LoginResult.ParseExpirationDateFromResult(resultDictionary);
            ICollection<string> permissions = LoginResult.ParsePermissionFromResult(resultDictionary);

            return new AccessToken(
                accessToken,
                userID,
                expiration,
                permissions);
        }
Example #34
0
        private void Configure(IDictionary<string, string> props) {
            if(props == null) {
                if(IsDebugEnabled)
                    log.Debug("캐시의 환경 설정 값을 기본값으로 설정합니다...");

                _expiration = DefaultExpiration;
                _priority = CacheItemPriority.Default;
                _regionPrefix = DefaultRegionPrefix;
            }
            else {
                _priority = props.GetValueOrDefault("priority", "4").AsEnum(CacheItemPriority.Default);
                _expiration = TimeSpan.FromSeconds(Math.Max(60, props.GetValueOrDefault("expiration", "300").AsInt(300)));
                _regionPrefix = props.GetValueOrDefault("regionPrefix", string.Empty).AsText(DefaultRegionPrefix);
            }
        }
Example #35
0
        private IAstTypeReference RecursionSafeReflect(Type type, IDictionary<Type, IAstTypeReference> alreadyReflected)
        {
            var reflected = alreadyReflected.GetValueOrDefault(type);
            if (reflected != null)
                return reflected;

            if (type == typeof(object))
                return AstAnyType.Instance;

            if (type.IsGenericParameter) {
                var constraints = type.GetGenericParameterConstraints();
                return new AstGenericPlaceholderType(
                    type.Name,
                    p => {
                        alreadyReflected.Add(type, p);
                        return constraints.Select(c => this.RecursionSafeReflect(c, alreadyReflected));
                    },
                    target: type
                );
            }

            if (IsFunctionType(type))
                return ReflectFunctionType(type, alreadyReflected);

            if (type.IsGenericType && !type.IsGenericTypeDefinition)
                return ReflectGenericType(type, alreadyReflected);

            return new AstReflectedType(type, this);
        }
Example #36
0
 public OrderableMetadata(IDictionary<string, object> data)
 {
     var readOnlyData = (IReadOnlyDictionary<string, object>)data;
     this.AfterTyped = readOnlyData.GetEnumerableMetadata<string>("After").WhereNotNull();
     this.BeforeTyped = readOnlyData.GetEnumerableMetadata<string>("Before").WhereNotNull();
     this.Name = (string)data.GetValueOrDefault("Name");
 }
 private Mock<IVsSettingsReader> MockDictionarySettingsReader(IDictionary<string, string> settings)
 {
     var reader = new Mock<IVsSettingsReader>();
     string _;
     reader.Setup(x => x.ReadSettingString(It.IsAny<string>(), out _))
           .Callback((string key, out string value) => { value = settings.GetValueOrDefault(key); });
     return reader;
 }
Example #38
0
        private void AddGenericTheory(IDictionary<Type, ISet<Type>> genericTheories, Type genericType, Type actualType)
        {
            var set = genericTheories.GetValueOrDefault(genericType);
            if (set == null) {
                genericTheories.Add(genericType, new HashSet<Type> {actualType});
                return;
            }

            set.Add(actualType);
        }
Example #39
0
 internal Lexer(string str, IDictionary<string, object> options)
 {
     _input = InputRegex.Replace(str, "\n");
     _colons = (bool) options.GetValueOrDefault("colons", false);
     _deferredTokens = new List<Token>();
     _lastIndents = 0;
     LineNumber = 1;
     _stash = new List<Token>();
     _indentStack = new List<int>();
     _indentRe = null;
     Pipeless = false;
 }
Example #40
0
 internal Compiler(Node node, IDictionary<string, object> options = null)
 {
     _options = options ?? new Dictionary<string, object>();
     _node = node;
     _hasCompiledDoctype = false;
     _hasCompiledTag = false;
     _pp = (bool) _options.GetValueOrDefault("pretty", false);
     _debug = _options.ContainsKey("compileDebug") && (bool) _options["compileDebug"];
     _indents = 0;
     _parentIndents = 0;
     if (_options.ContainsKey("doctype")) SetDoctype((string) _options["doctype"]);
         
 }
Example #41
0
        public override void Render(IParrotWriter writer, IRendererFactory rendererFactory, Statement statement, IDictionary<string, object> documentHost, object model)
        {
            var childrenQueue = documentHost.GetValueOrDefault(LayoutRenderer.LayoutChildren) as Queue<StatementList>;
            if (childrenQueue == null)
            {
                //TODO: replace this with a real exception
                throw new Exception("Children elements empty");
            }

            var children = childrenQueue.Dequeue();

            RenderChildren(writer, children, rendererFactory, documentHost, DefaultChildTag, model);
        }
        private static DateTime ParseExpirationDateFromResult(IDictionary<string, object> resultDictionary)
        {
            DateTime expiration;
            if (Constants.IsWeb)
            {
                // For canvas we get back the time as seconds since now instead of in epoch time.
                expiration = DateTime.Now.AddSeconds(resultDictionary.GetValueOrDefault<long>(LoginResult.ExpirationTimestampKey));
            }
            else
            {
                string expirationStr = resultDictionary.GetValueOrDefault<string>(LoginResult.ExpirationTimestampKey);
                int expiredTimeSeconds;
                if (int.TryParse(expirationStr, out expiredTimeSeconds) && expiredTimeSeconds > 0)
                {
                    expiration = LoginResult.FromTimestamp(expiredTimeSeconds);
                }
                else
                {
                    expiration = DateTime.MaxValue;
                }
            }

            return expiration;
        }
 public ContentTypeLanguageMetadata(IDictionary<string, object> data)
     : base(data)
 {
     this.DefaultContentType = (string)data.GetValueOrDefault("DefaultContentType");
 }
Example #44
0
 public ContentTypeMetadata(IDictionary<string, object> data)
 {
     this.ContentTypes = (IEnumerable<string>)data.GetValueOrDefault("ContentTypes");
 }
Example #45
0
 public IEnumerable<Annotation> GetAnnotations(StorageModule storage, String param, IDictionary<String, String> args)
 {
     IQueryable annotations = storage.GetAnnotations(
         args.GetValueOrDefault("accountId"),
         args.GetValueOrDefault("name"),
         args.GetValueOrDefault("value")
     ).OrderByDescending(a => a).AsQueryable();
     if (args.ContainsKey("query"))
     {
         annotations = annotations.Execute(args["query"]);
     }
     return annotations.Cast<Annotation>();
 }
 public VisualStudioVersionMetadata(IDictionary<string, object> data)
 {
     Version = (VisualStudioVersion)data.GetValueOrDefault("Version");
 }
Example #47
0
 public WorkspaceServiceMetadata(IDictionary<string, object> data)
 {
     this.ServiceType = (string)data.GetValueOrDefault("ServiceType");
     this.Layer = (string)data.GetValueOrDefault("Layer");
 }
Example #48
0
 public FeatureMetadata(IDictionary<string, object> data)
 {
     this.FeatureName = (string)data.GetValueOrDefault("FeatureName");
 }
 public DiagnosticProviderMetadata(IDictionary<string, object> data)
 {
     this.Name = (string)data.GetValueOrDefault("Name");
     this.Languages = (string[])data.GetValueOrDefault("Languages");
 }
Example #50
0
 public IEnumerable<Mark> GetMarks(StorageModule storage, String param, IDictionary<String, String> args)
 {
     IQueryable marks = storage.GetMarks(
         args.GetValueOrDefault("accountId"),
         args.GetValueOrDefault("name"),
         args.GetValueOrDefault("markingAccountId"),
         args.ContainsKey("markingTimestamp") ? DateTime.Parse(args["markingTimestamp"]) : default(Nullable<DateTime>),
         args.GetValueOrDefault("markingCategory"),
         args.GetValueOrDefault("markingSubId")
     ).OrderByDescending(m => m).AsQueryable();
     if (args.ContainsKey("query"))
     {
         marks = marks.Execute(args["query"]);
     }
     return marks.Cast<Mark>();
 }
 public OrderableLanguageMetadata(IDictionary<string, object> data)
     : base(data)
 {
     this.Language = (string)data.GetValueOrDefault("Language");
 }
Example #52
0
 public IEnumerable<Account> GetAccounts(StorageModule storage, String param, IDictionary<String, String> args)
 {
     IQueryable activities = storage.GetAccounts(
         args.GetValueOrDefault("accountId"),
         args.GetValueOrDefault("realm"),
         args.GetValueOrDefault("seedString")
     ).OrderByDescending(a => a).AsQueryable();
     if (args.ContainsKey("query"))
     {
         activities = activities.Execute(args["query"]);
     }
     return activities.Cast<Account>();
 }
Example #53
0
 public IEnumerable<Tag> GetTags(StorageModule storage, String param, IDictionary<String, String> args)
 {
     IQueryable tags = storage.GetTags(
         args.GetValueOrDefault("accountId"),
         args.ContainsKey("timestamp") ? DateTime.Parse(args["timestamp"]) : default(Nullable<DateTime>),
         args.GetValueOrDefault("category"),
         args.GetValueOrDefault("subId"),
         args.GetValueOrDefault("name"),
         args.GetValueOrDefault("value")
     ).OrderByDescending(t => t).AsQueryable();
     if (args.ContainsKey("query"))
     {
         tags = tags.Execute(args["query"]);
     }
     return tags.Cast<Tag>();
 }
Example #54
0
 public IEnumerable<Relation> GetRelations(StorageModule storage, String param, IDictionary<String, String> args)
 {
     IQueryable relations = storage.GetRelations(
         args.GetValueOrDefault("accountId"),
         args.GetValueOrDefault("name"),
         args.GetValueOrDefault("relatingAccountId")
     ).OrderByDescending(r => r).AsQueryable();
     if (args.ContainsKey("query"))
     {
         relations = relations.Execute(args["query"]);
     }
     return relations.Cast<Relation>();
 }
Example #55
0
 public IEnumerable<Reference> GetReferences(StorageModule storage, String param, IDictionary<String, String> args)
 {
     IQueryable references = storage.GetReferences(
         args.GetValueOrDefault("accountId"),
         args.ContainsKey("timestamp") ? DateTime.Parse(args["timestamp"]) : default(Nullable<DateTime>),
         args.GetValueOrDefault("category"),
         args.GetValueOrDefault("subId"),
         args.GetValueOrDefault("name"),
         args.GetValueOrDefault("referringAccountId"),
         args.ContainsKey("referringTimestamp") ? DateTime.Parse(args["referringTimestamp"]) : default(Nullable<DateTime>),
         args.GetValueOrDefault("referringCategory"),
         args.GetValueOrDefault("referringSubId")
     ).OrderByDescending(r => r).AsQueryable();
     if (args.ContainsKey("query"))
     {
         references = references.Execute(args["query"]);
     }
     return references.Cast<Reference>();
 }
Example #56
0
 public IEnumerable<Activity> GetPosts(StorageModule storage, String param, IDictionary<String, String> args)
 {
     IQueryable posts = storage.GetActivities(
         args.GetValueOrDefault("accountId"),
         args.ContainsKey("timestamp") ? DateTime.Parse(args["timestamp"]) : default(Nullable<DateTime>),
         "Post",
         args.GetValueOrDefault("subId"),
         args.GetValueOrDefault("userAgent"),
         args.ContainsKey("value")
             ? args["value"].If(String.IsNullOrEmpty, s => DBNull.Value, s => (Object) s)
             : null,
         args.ContainsKey("data")
             ? args["data"].If(String.IsNullOrEmpty, s => DBNull.Value, s => (Object) s.Base64Decode().ToArray())
             : null
     ).OrderByDescending(p => p).AsQueryable();
     if (args.ContainsKey("query"))
     {
         posts = posts.Execute(args["query"]);
     }
     return posts.Cast<Activity>();
 }
 public OptionSerializerMetadata(IDictionary<string, object> data) : base(data)
 {
     this.Features = (IEnumerable<string>)data.GetValueOrDefault("Features");
 }
Example #58
0
 private void UpdateVector2GroupPath(
         IDictionary<BigInteger, string> vector2GroupPath, BigInteger vector, CstNode node) {
     var groupPath = GetGroupPathFromNode(node);
     var existingGroupPath = vector2GroupPath.GetValueOrDefault(vector);
     if (existingGroupPath == null) {
         vector2GroupPath.Add(vector, groupPath);
     } else {
         vector2GroupPath[vector] = LearningExperimentUtil.GetCommonSuffix(
                 existingGroupPath, groupPath);
     }
 }
Example #59
0
        private void Result(Task task, IDictionary<string,object> env)
        {
            if (task.IsFaulted)
            {
                _networkStream.WriteAsync(Status500InternalServerError, 0, Status500InternalServerError.Length)
                    .ContinueWith(_ => Dispose());
            }

            int status = env.GetValueOrDefault(OwinKeys.ResponseStatusCode, 0);
            if (status == 0 || status == 404)
            {
                _networkStream.WriteAsync(Status404NotFound, 0, Status404NotFound.Length)
                    .ContinueWith(_ => Dispose());
            }

            WriteResult(status, env)
                .ContinueWith(ListenAgain);
        }
 public PerLanguageIncrementalAnalyzerProviderMetadata(IDictionary<string, object> data)
     : base(data)
 {
     this.Name = (string)data.GetValueOrDefault("Name");
 }