Esempio n. 1
1
 private void Search(Dictionary<int, int> count, IList<int> temp, IList<IList<int>> results)
 {
     if (!count.Any() && temp.Any())
     {
         results.Add(new List<int>(temp));
         return;
     }
     var keys = count.Keys.ToList();
     foreach (var key in keys)
     {
         temp.Add(key);
         --count[key];
         if (count[key] == 0) count.Remove(key);
         Search(count, temp, results);
         temp.RemoveAt(temp.Count - 1);
         if (count.ContainsKey(key))
         {
             ++count[key];
         }
         else
         {
             count[key] = 1;
         }
     }
 }
        public override DbExpression Visit(DbScanExpression expression)
        {
            // a bit harder to get the metadata in CSpace
            var item = expression.Target.ElementType.MetadataProperties.First(p => p.Name == "Configuration");

            // using reflection to get the Annotations property as EntityTtypeConfiguration is an internal class in EF
            Dictionary<string, object> annotations = new Dictionary<string, object>();
            var value = item.Value;
            var propertyInfo = value.GetType().GetProperty("Annotations");
            if (propertyInfo != null)
            {
                annotations = (Dictionary<string, object>) propertyInfo.GetValue(value, null);
            }

            if (!annotations.Any())
            {
                return base.Visit(expression);
            }

            DbExpression current = expression;
            foreach (var globalFilter in annotations.Where(a => a.Key.StartsWith("globalFilter")))
            {
                var convention = (FilterDefinition)globalFilter.Value;

                Filter filterConfig;

                string filterName = globalFilter.Key.Split(new[] { "globalFilter_" }, StringSplitOptions.None)[1];

                if (!FilterExtensions.FilterConfigurations.TryGetValue(new Tuple<string, object>(filterName, _contextForInterception.GetInternalContext()), out filterConfig))
                    continue;

                if (!filterConfig.IsEnabled)
                    continue;

                var linqExpression = convention.Predicate(_contextForInterception, filterConfig.ParameterValues);

                var funcletizerType = typeof(DefaultExpressionVisitor).Assembly.GetType(
                    "System.Data.Entity.Core.Objects.ELinq.Funcletizer");
                var funcletizerFactoryMethod = funcletizerType.GetMethod("CreateQueryFuncletizer",
                    BindingFlags.Static | BindingFlags.NonPublic);
                var funcletizer = funcletizerFactoryMethod.Invoke(null, new[] { _objectContext });

                var converterType = typeof(DefaultExpressionVisitor).Assembly.GetType(
                    "System.Data.Entity.Core.Objects.ELinq.ExpressionConverter");
                var converter = Activator.CreateInstance(converterType,
                    BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { funcletizer, linqExpression }, null);
                var convertMethod = converterType.GetMethod("Convert",
                    BindingFlags.NonPublic | BindingFlags.Instance);
                var result = (DbFilterExpression)convertMethod.Invoke(converter, null);

                var binding = current.Bind();
                var normalizer = new BindingNormalizer(binding);
                var output = result.Predicate.Accept(normalizer);
                current = binding.Filter(output);
            }
            return current;
        }
        public static IDictionary<Version, ChangeLogVersionDetails> GetChangeLog(Version fromVersion, Version toVersion, XDocument changeLogContent)
        {
            var changeLog = new Dictionary<Version, ChangeLogVersionDetails>();

            foreach (var changeVersion in changeLogContent.Descendants("Version"))
            {
                var changeLogItem = BuildChangeLogItem(changeVersion);
                if (!changeLog.ContainsKey(changeLogItem.Key))
                {
                    changeLog.Add(changeLogItem.Key, changeLogItem.Value);
                }
            }

            if (fromVersion < toVersion && changeLog.Any(x => x.Key > fromVersion && x.Key <= toVersion))
            {
                return changeLog.Where(x => x.Key > fromVersion && x.Key <= toVersion).OrderByDescending(detail => detail.Key).ToDictionary(detail => detail.Key, detail => detail.Value);
            }

            if (fromVersion < toVersion && changeLog.Any() && toVersion > changeLog.Keys.Max())
            {
                return changeLog.Where(x => x.Key == changeLog.Keys.Max()).ToDictionary(detail => detail.Key, detail => detail.Value);
            }

            if (fromVersion < toVersion && toVersion.Revision > 0 && changeLog.Any() && toVersion < changeLog.Keys.Max())
            {
                var versionWithoutRevision = new Version(toVersion.Major, toVersion.Minor, toVersion.Build);
                return changeLog.Where(x => x.Key > versionWithoutRevision).ToDictionary(detail => detail.Key, detail => detail.Value);
            }

            return changeLog.OrderByDescending(detail => detail.Key).ToDictionary(detail => detail.Key, detail => detail.Value);
        }
Esempio n. 4
0
 /// <summary>метод который формирует данные для chart-а на основе колекции серий, 
 /// поинтов и их пересечений </summary>
 private SeriesCollection FillData(
     Dictionary<string, float> seriesDef, 
     Dictionary<string, float> pointDef,
     Dictionary<Intersection, float> intersections)
 {
     SeriesCollection result = new SeriesCollection();
     if (!subDiagramMode)
     {
         switch (this.DiagramType)
         {
             case DiagramTypeEnum.Graph:
                 result.Add(CreateDataForFullDiagram(seriesDef, pointDef, intersections, true));
                 break;
             case DiagramTypeEnum.ColumnDetail:
                 result.Add(CreateDataForFullDiagram(seriesDef, pointDef, intersections, false));
                 break;
             case DiagramTypeEnum.ColumnGeneral:
                 result.Add(CreateDataForColumnGeneral(seriesDef));
                 break;
             case DiagramTypeEnum.PieGeneral:
                 result.Add(CreateDataForPieGeneral(seriesDef));
                 break;
             case DiagramTypeEnum.Speedometer:
             case DiagramTypeEnum.TrafficLight:
                 if (seriesDef.Any( s => s.Key.Equals(defaultSeries)))
                     result.Add(FillSeriesData(seriesDef.First(s => s.Key.Equals(defaultSeries))));
                 break;
             case DiagramTypeEnum.PieDetail:
                 if (seriesDef.Any(s => s.Key.Equals(defaultSeries)))
                     result.Add(FillPointsData(seriesDef.First(s => s.Key.Equals(defaultSeries)),
                         pointDef, intersections, false));
                 break;
         }
     }
     else
     {
         if (string.IsNullOrEmpty(detalizedSeriesName)) detalizedSeriesName = this.defaultSeries;
         if (seriesDef.Any(s => s.Key.Equals(detalizedSeriesName)))
         {
             switch (this.SubDiagramType)
             {
                 case SubDiagramTypeEnum.Graph:
                 case SubDiagramTypeEnum.ColumnDetail:
                 case SubDiagramTypeEnum.PieDetail:
                     result.Add(FillPointsData(seriesDef.First(s => s.Key.Equals(detalizedSeriesName)),
                         pointDef, intersections, false));
                     break;
             }
         }
     }
     FillEmptyVisibleSeries(seriesDef.Keys.ToList());
     return result;
 }
        private void AssertAditionals(Dictionary<string, string> additionals)
        {
            if(additionals == null)
                return;

            if(additionals.Count > MaxAdditionalsCount)
                throw new ArgumentException();

            if(additionals.Any( a => a.Key.Length > MaxAdditionalKeyLenght))
                throw new ArgumentException();

            if(additionals.Any(( a => a.Value.Length > MaxAdditionalValueLenght)))
                throw new ArgumentException();
        }
 public void CreateLiveConnectFoldersSkyDrive(Dictionary<string, object> folderDictionary, EventHandler<LiveOperationCompletedEventArgs> callback)
 {
     if (folderDictionary.Any())
     {
         CreateLiveConnectFolders("me/skydrive", folderDictionary, callback);
     }
 }
Esempio n. 7
0
        public List<Dictionary<string, object>> Parse(IRestResponse<dynamic> responseToParse, ParserRules ruleset)
        {
            if (responseToParse.ResponseStatus != ResponseStatus.Completed)
                throw new ApplicationException("Response was not [Completed]");

            if (responseToParse.Data == null)
                throw new ApplicationException("Response data could not be parsed");

            var resultset = responseToParse.Data as IEnumerable<dynamic>;

            if (resultset == null)
                throw new ApplicationException("Response data could not be identified as collection");
            List<Dictionary<string, object>> l = new List<Dictionary<string, object>>();
            foreach (Dictionary<string, object> item in resultset)
            {
                var newItem = new Dictionary<string, object>();
                foreach (var field in ruleset.Fields)
                {
                    if (item.ContainsKey(field.Selector))
                    {
                        newItem.Add(field.Selector, item[field.Selector]);
                    }
                }

                if (newItem.Any())
                    l.Add(newItem);

            }

            return l;
        }
Esempio n. 8
0
        public override IEnumerable<string> Executar(Grafo grafo)
        {
            grafo.Direcionado = true;

            var retorno = new List<string>();
            Dictionary<string, Vertice> Q = new Dictionary<string, Vertice>();
            var primeiro = grafo.Vertices.First();
            Q.Add(primeiro.Key, primeiro.Value);
            while (Q.Any())
            {
                var U = Q.First();
                Q.Remove(Q.Keys.First());
                foreach (var vertice in grafo.GetAdj(U.Key))
                {
                    if (vertice.Value.Cor == CoresEnum.Branco)
                    {
                        vertice.Value.Descoberta = U.Value.Descoberta + 1;
                        vertice.Value.Pai = U.Value;
                        vertice.Value.Cor = CoresEnum.Cinza;
                        Q.Add(vertice.Key, vertice.Value);
                    }
                }
                retorno.Add(String.Format("{0} {1} {2}", grafo.Vertices.First().Key, U.Value.Id, U.Value.Descoberta));
                U.Value.Cor = CoresEnum.Preto;
            }

            return retorno;
        }
        public virtual Dictionary<string, object> GetRecognizeData(byte[] image, string condition = "")
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();

            try
            {
                DateTime timestamp = DateTime.Now;

                var templates = Directory.EnumerateFiles(_templatePath).Where(f => new[] { ".xml" }.Contains(Path.GetExtension(f)));
                foreach (string template in templates.Where(t => t.Contains(condition)))
                {
                    OnTry(template);

                    dic = GetRecognizeDataByTemplate(image, template);
                    if (dic.Any())
                    {
                        OnRecognizeData(DateTime.Now - timestamp, template);
                        return dic;
                    }
                }
            }
            catch(Exception ex)
            {
                OnError(ex);
            }

            return dic;
        }
Esempio n. 10
0
		internal static ClassDeclarationSyntax GetNonCollectible()
		{
			while(true)
			{
				var newNamingConflicts = new Dictionary<string, List<string>>();
				var classDecl = ClassDeclaration("NonCollectible").AddModifiers(Token(PublicKeyword));
				foreach(var c in ClassNames)
				{
					var className = c == "DREAM" ? "DreamCards" : CultureInfo.InvariantCulture.TextInfo.ToTitleCase(c.ToLower());
					var cCard = ClassDeclaration(className).AddModifiers(Token(PublicKeyword));
					var anyCards = false;
					foreach(var card in
						Cards.All.OrderBy(x => x.Value.Set)
							 .ThenBy(x => x.Key)
							 .Select(x => x.Value)
							 .Where(x => !x.Collectible && x.Class.ToString().Equals(c)))
					{
						var name = CultureInfo.InvariantCulture.TextInfo.ToTitleCase(card.Name.ToLower());
						name = Regex.Replace(name, @"[^\w\d]", "");
						name = ResolveNameFromId(card, name);
						name = ResolveNamingConflict(name, card, newNamingConflicts);
						cCard = cCard.AddMembers(GenerateConst(name, card.Id));
						anyCards = true;
					}
					if(anyCards)
						classDecl = classDecl.AddMembers(cCard);
				}
				if(!newNamingConflicts.Any(x => x.Value.Count > 1))
					return classDecl;
				foreach(var pair in newNamingConflicts.Where(x => x.Value.Count > 1).ToDictionary(pair => pair.Key, pair => pair.Value))
					_namingConflicts.Add(pair.Key, pair.Value);
			}
		}
Esempio n. 11
0
 internal List<Right> GetBexisRights(string dataBase,  Dictionary<int, int> dataSetsMapping)
 {
     List<Right> bexisRights = new List<Right>();
     string datasetQuery = "";
     foreach (var dataSetMapping in dataSetsMapping)
     {
         datasetQuery += "DATASETID = "+ dataSetMapping.Key;
         if (dataSetsMapping.Last().Key != dataSetMapping.Key)
             datasetQuery += " or ";
     }
     if (dataSetsMapping.Any())
     {
         datasetQuery = "where " + datasetQuery + "";
     }
     // DB query
     string mySelectQuery = "SELECT ROLENAME, DATASETID, FOREDIT, APPLICATIONNAME FROM \"PROVIDER\".\"RIGHTS\"   "+ datasetQuery;
     DB2Connection connect = new DB2Connection(dataBase);
     DB2Command myCommand = new DB2Command(mySelectQuery, connect);
     connect.Open();
     DB2DataReader myReader = myCommand.ExecuteReader();
     while (myReader.Read())
     {
         bexisRights.Add(new Right()
         {
             RoleName = myReader.GetString(0),
             DataSetId = (int)(myReader.GetValue(1)),
             CanEdit = myReader.GetString(2)=="N"?false:true
         });
     }
     myReader.Close();
     connect.Close();
     return bexisRights;
 }
        public async Task<IDictionary<string, Result>> GetBatchSentimentAsync(Dictionary<string, string> textBatch)
        {
            ValidateBatchRequest(textBatch);

            if (!textBatch.Any())
            {
                return new Dictionary<string, Result>();
            }

            string content;
            using (var response = await _requestor.PostAsync(Constants.SentimentBatchRequest, BuildInputString(textBatch)))
            {
                content = await response.Content.ReadAsStringAsync();
                if (!response.IsSuccessStatusCode)
                {
                    return textBatch.ToDictionary(r => r.Key, r => AzureMachineLearningResult.Build(_errorMessageGenerator.GenerateError(response.StatusCode, content)));
                }
            }

            var result = JsonConvert.DeserializeObject<SentimentBatchResult>(content);
            var parsedResults = result.SentimentBatch.ToDictionary(sr => sr.Id, sr => AzureMachineLearningResult.Build(sr.Score, ScoreToSentiment(sr.Score)));

            foreach (var error in result.Errors)
            {
                parsedResults.Add(error.Id, AzureMachineLearningResult.Build(error.Message));
            }

            return parsedResults;
        }
Esempio n. 13
0
        public HttpWorker(Uri uri, HttpMethod httpMethod = HttpMethod.Get, Dictionary<string, string> headers = null, byte[] data = null)
        {
            _buffer = new byte[8192];
            _bufferIndex = 0;
            _read = 0;
            _responseType = ResponseType.Unknown;
            _uri = uri;
            IPAddress ip;
            var headersString = string.Empty;
            var contentLength = data != null ? data.Length : 0;

            if (headers != null && headers.Any())
                headersString = string.Concat(headers.Select(h => "\r\n" + h.Key.Trim() + ": " + h.Value.Trim()));

            if (_uri.HostNameType == UriHostNameType.Dns)
            {
                var host = Dns.GetHostEntry(_uri.Host);
                ip = host.AddressList.First(i => i.AddressFamily == AddressFamily.InterNetwork);
            }
            else
            {
                ip = IPAddress.Parse(_uri.Host);
            }

            _endPoint = new IPEndPoint(ip, _uri.Port);
            _request = Encoding.UTF8.GetBytes($"{httpMethod.ToString().ToUpper()} {_uri.PathAndQuery} HTTP/1.1\r\nAccept-Encoding: gzip, deflate, sdch\r\nHost: {_uri.Host}\r\nContent-Length: {contentLength}{headersString}\r\n\r\n");

            if (data == null)
                return;

            var tmpRequest = new byte[_request.Length + data.Length];
            Buffer.BlockCopy(_request, 0, tmpRequest, 0, _request.Length);
            Buffer.BlockCopy(data, 0, tmpRequest, _request.Length, data.Length);
            _request = tmpRequest;
        }
Esempio n. 14
0
        /// <summary>
        /// To do. Create a clever search algorithm.
        /// </summary>
        /// <param name="Word"></param>
        /// <param name="Collection"></param>
        /// <returns></returns>
        public string GetSimilar(string Word, List<string> Collection)
        {
            if (Word.IsNullOrEmpty())
            {
                return Word;
            }

            Dictionary<string, int> keys = new Dictionary<string, int>();

            /*foreach (string s in words.Keys)
            {
                if (s.EndsWith(Word))
                {
                    keys.Add(s, s.Length);
                }
            }*/

            Collection.AsParallel().ForAll(s =>
            {
                if (s.EndsWith(Word))
                {
                    keys.Add(s, s.Length);
                }
            });

            if (!keys.Any() && Word.Length > 2)
            {
                return this.GetSimilar(Word.Substring(1), Collection);
            }

            string key = keys.OrderBy(val => val.Value).FirstOrDefault().Key;

            return key;
        }
        public void VisaData(IList<AktivPeriod> perioder)
        {
            panel1.Controls.Clear();

            var lista = new Dictionary<DateTime, double>();

            foreach (var dag in perioder.Select(o => o.Starttid.Date).Distinct())
            {
                var summeradDag = dag;
                lista.Add(dag,
                          perioder.Where(o => o.Starttid.Date.Equals(summeradDag)).Sum(o => o.Tidsmängd.TotalMinutes));
            }

            if (!lista.Any()) return;

            var max = lista.Max(o => o.Value);
            var xposition = 10;
            foreach (var d in lista)
            {
                var stapel = new Dagstapel
                                 {
                                     Height = panel1.Height - 20,
                                     Top = 10,
                                     Left = xposition
                                 };

                stapel.VisaUppgifter(d.Key, d.Value, max);
                xposition += stapel.Width;
                panel1.Controls.Add(stapel);
            }
        }
Esempio n. 16
0
		public override void Respond(Abstractions.IHttpContext context)
		{
			var prefetcherDocs = Database.IndexingExecuter.PrefetchingBehavior.DebugGetDocumentsInPrefetchingQueue().ToArray();
			var compareToCollection = new Dictionary<Etag, int>();

			for (int i = 1; i < prefetcherDocs.Length; i++)
				compareToCollection.Add(prefetcherDocs[i-1].Etag, prefetcherDocs[i].Etag.CompareTo(prefetcherDocs[i-1].Etag));

			if (compareToCollection.Any(x => x.Value < 0))
			{
				context.WriteJson(new
				{
					HasCorrectlyOrderedEtags = true,
					EtagsWithKeys = prefetcherDocs.ToDictionary(x => x.Etag, x => x.Key)
				});
			}
			else
			{
				context.WriteJson(new
				{
					HasCorrectlyOrderedEtags = false,
					IncorrectlyOrderedEtags = compareToCollection.Where(x => x.Value < 0),
					EtagsWithKeys = prefetcherDocs.ToDictionary(x => x.Etag, x => x.Key)
				});
			}
		}
Esempio n. 17
0
        protected virtual bool GetMatchedRecords(
            IOrderedEnumerable<IRecord> recordsFilteredByDate, 
            IModelInput modelInput,
            out IDictionary<string, IList<IRecord>> matchedRecords
        )
        {
            matchedRecords = new Dictionary<string, IList<IRecord>>();
            if (!recordsFilteredByDate.AnySave())
            {
                return false;
            }

            foreach (var record in recordsFilteredByDate)
            {
                foreach (var term in modelInput.FilterTerms)
                {
                    var distinctMatchedDescription = GetMatchedDistinctDescription(record.Description, term);
                    record.DistinctDescription = distinctMatchedDescription;
                    if (string.IsNullOrEmpty(distinctMatchedDescription))
                    {
                        continue;
                    }
                    if (matchedRecords.ContainsKey(distinctMatchedDescription))
                    {
                        matchedRecords[distinctMatchedDescription].Add(record);
                    }
                    else
                    {
                        matchedRecords.Add(distinctMatchedDescription, new List<IRecord>() { record });
                    }
                    break;
                }
            }
            return matchedRecords.Any();
        }
Esempio n. 18
0
        private static void AddLinkHeaders(NancyContext context, IEnumerable<Tuple<string, IEnumerable<Tuple<IResponseProcessor, ProcessorMatch>>>> compatibleHeaders, Response response)
        {
            var linkProcessors = new Dictionary<string, MediaRange>();

            var compatibleHeaderMappings =
                compatibleHeaders.SelectMany(m => m.Item2).SelectMany(p => p.Item1.ExtensionMappings);

            foreach (var compatibleHeaderMapping in compatibleHeaderMappings)
            {
                if (!compatibleHeaderMapping.Item2.Matches(response.ContentType))
                {
                    linkProcessors[compatibleHeaderMapping.Item1] = compatibleHeaderMapping.Item2;
                }
            }

            if (!linkProcessors.Any())
            {
                return;
            }

            var baseUrl =
                context.Request.Url.BasePath + "/" + Path.GetFileNameWithoutExtension(context.Request.Url.Path);

            var links = linkProcessors.Keys
                .Select(lp => string.Format("<{0}.{1}>; rel=\"{2}\"", baseUrl, lp, linkProcessors[lp]))
                .Aggregate((lp1, lp2) => lp1 + "," + lp2);

            response.Headers["Link"] = links;
        }
Esempio n. 19
0
        public void Progress(Dictionary<string, string> namedParameters, string[] parameters)
        {
            if (parameters.Length != 2 && parameters.Length != 1)
            {
                throw new ArgumentOutOfRangeException("parameters", "Parameter count must be at least one");
            }

            bool deleteParents =
                namedParameters.Any(
                    a => string.Compare("--delete-parents", a.Key, StringComparison.InvariantCultureIgnoreCase) == 0);

            string maxDepthResult = CommandHelper.GetProperty(namedParameters, "--max-depth", null);
            int maxDepth = maxDepthResult == null ? 0 : int.Parse(maxDepthResult);
            var issuer = CommandHelper.GetProperty (namedParameters, "--issuer", Environment.UserName);
            string comment = CommandHelper.GetProperty(namedParameters, "--comment", "Backup combination");

            string zip = parameters[0];
            string resultPath = parameters.Length == 2 ? parameters[1] : Path.GetTempFileName ();
            bool overrideZip = parameters.Length == 1;

            Backup.Combine(zip, resultPath, maxDepth, issuer, comment);

            if (overrideZip)
                File.Move(zip, resultPath);
        }
        public void CoursesCorrelation(List<string> callStack, Dictionary<string, decimal> coursesCatalog, List<string> coursesList)
        {
            while (coursesCatalog.Any(coursePointer => coursePointer.Value < 0))
            {
                callStack.Clear();
                var courseTarget = coursesCatalog.First(coursePointer => coursePointer.Value < 0).Key;
                while (courseTarget != "loop" && courseTarget != "base")
                {
                    courseTarget = recursiveInsight(courseTarget, callStack, coursesCatalog, coursesList);
                }

                if (courseTarget == "loop")
                {
                    foreach (var coursePointer in callStack)
                        coursesCatalog[coursePointer] = 0.1M;
                }
                if (courseTarget == "base")
                {
                    var courseLevelSetup = callStack.Count;

                    foreach (var coursePointer in callStack)
                    {
                        coursesCatalog[coursePointer] = courseLevelSetup;
                        courseLevelSetup--;
                    }
                }
            }
        }
Esempio n. 21
0
        internal static void Deserialize(CharacterFilterBase filter, Dictionary<string, object> fieldDict)
        {
            if (fieldDict == null || !fieldDict.Any())
                return;

            filter.Version = fieldDict.GetDoubleOrNull(_VERSION);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            MyProjects = RequestContext.CurrentUserProjects;

            InitControls();

            IsProjectAdmin = Page.Participant.IsAdmin;
            IsFullAdmin = Page.Participant.IsFullAdmin;
            IsOutsider = Page.Participant.UserInfo.IsOutsider();

            ParticipantSecurityInfo = new Dictionary<string, bool>
                                          {
                                              {"Project", IsProjectAdmin},
                                              {"Milestone", RequestContext.CanCreateMilestone()},
                                              {"Task", RequestContext.CanCreateTask()},
                                              {"Discussion", RequestContext.CanCreateDiscussion()},
                                              {"Time", RequestContext.CanCreateTime()},
                                              {"ProjectTemplate", IsProjectAdmin}
                                          };

            ShowCreateButton = (ParticipantSecurityInfo.Any(r => r.Value) || Page is TMDocs) && !Page.Participant.UserInfo.IsOutsider();


            var mobileAppRegistrator = new CachedMobileAppInstallRegistrator(new MobileAppInstallRegistrator());
            var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
            var isRegistered = mobileAppRegistrator.IsInstallRegistered(currentUser.Email, null);

            DisplayAppsBanner =
                SetupInfo.DisplayMobappBanner("projects")
                && !CoreContext.Configuration.Standalone
                && !isRegistered;
        }
Esempio n. 23
0
        /// <summary>
        /// Ensures the appropriate version of the specified packages are installed.  If an existing version of the package
        /// already exists the following will happen:
        /// If a semantically compatible version already exists, no change is made to the package.
        /// If an older major version exists, a warning is logged and the package is upgraded.
        /// If an older minor/build version exists, an information message is logged and the package is upgraded.
        /// If a newer major version exists, a warning is logged and no change is made to the package.
        /// </summary>
        public static async Task InstallPackagesAsync(
            Dictionary<string, string> packages,
            string extensionId,
            ConnectedServiceLogger logger,
            Project project,
            IVsPackageInstallerServices packageInstallerServices,
            IVsPackageInstaller packageInstaller)
        {
            Dictionary<string, string> packagesToInstall = new Dictionary<string, string>();

            await NuGetUtilities.InstallPackagesAsync(
                project,
                packages,
                (packageId, packageVersion) =>
                {
                    packagesToInstall.Add(packageId, packageVersion);
                    return Task.FromResult<object>(null);
                },
                logger,
                packageInstallerServices);

            if (packagesToInstall.Any())
            {
                packageInstaller.InstallPackagesFromVSExtensionRepository(extensionId, false, false, project, packagesToInstall);
            }
        }
Esempio n. 24
0
        //Returns the location of bracket mismatch
        //Rewrite this to make use of better suited container for brackets
        public int GetBracketMismatch(string code)
        {
            Dictionary<char, char> bracketMap = new Dictionary<char, char>()
            { {'{', '}'}, {'(', ')'}, {'[', ']'}, {'<', '>'} };//, {'\'', '\''} }; //{} () [] <> "" ''
            Stack<char> bracketStack = new Stack<char>();
            int counter = 0;

            foreach (char c in code)
            {
                if("(){}<>".Contains(c))
                {
                    if (!")}>".Contains(c))
                    {
                        bracketStack.Push(c);
                    }
                    else if (bracketMap.Any(q => q.Key == bracketMap[bracketStack.Last()]))
                    {
                        bracketStack.Pop();
                    }
                    else
                    {
                        return counter;
                    }
                }
                counter++;
            }

            return -1;
        }
Esempio n. 25
0
        public override IEnumerable<string> Executar(Grafo grafo)
        {
            var retorno = new List<string>();
            grafo.Direcionado = true;
            initialize(grafo);
            var s = grafo.Vertices.First();
            s.Value.Descoberta = 0;
            Dictionary<string, Vertice> q = new Dictionary<string, Vertice>();
            List<Vertice> w = new List<Vertice>();
            q = grafo.Vertices;
            while (q.Any())
            {
                q.OrderBy(e => e.Value.Descoberta).ToList();
                var u = q.First();
                q.Remove(q.Keys.First());

                foreach (var vertice in grafo.GetAdj(u.Value.Id))
                {
                    var aresta = grafo.Arestas
                        .Where(e => e.Origem.Equals(u.Key)
                                 && e.Destino.Equals(vertice.Key))
                        .FirstOrDefault();
                    relax(u.Value, vertice.Value, aresta.Peso);

                }

                if (u.Value.Descoberta != Int32.MaxValue)
                    retorno.Add(String.Format("{0} {1} {2}", s.Value.Id, u.Value.Id, u.Value.Descoberta));

            }
            return retorno;
        }
        public void DictionaryExtensions_Any_ReturnsFalseIfDictionaryDoesNotContainItems()
        {
            var dictionary = new Dictionary<Int32, String>();

            var result = dictionary.Any();

            TheResultingValue(result).ShouldBe(false);
        }
Esempio n. 27
0
		public static void HandleErrorDict(ModelStateDictionary stateDictionary, Dictionary<string, string> validationsDictionary) {
			if (validationsDictionary.Any()) {
				stateDictionary.AddModelError(String.Empty, "Please review and correct the noted errors.");
			}

			foreach (KeyValuePair<string, string> valuePair in validationsDictionary) {
				stateDictionary.AddModelError(valuePair.Key, valuePair.Value);
			}
		}
        /// <summary>
        /// Loads the current configuration setting the internal state of this configuration context.
        /// </summary>
        /// <param name="bucketConfig"></param>
        /// <param name="force">True to force a reconfiguration.</param>
        /// <exception cref="CouchbaseBootstrapException">Condition.</exception>
        public override void LoadConfig(IBucketConfig bucketConfig, bool force = false)
        {
            if (bucketConfig == null) throw new ArgumentNullException("bucketConfig");
            if (BucketConfig == null || !BucketConfig.Nodes.AreEqual<Node>(bucketConfig.Nodes) || force)
            {
                var clientBucketConfig = ClientConfig.BucketConfigs[bucketConfig.Name];
                var servers = new Dictionary<IPAddress, IServer>();
                var nodes = bucketConfig.GetNodes();
                foreach (var adapter in nodes)
                {
                    var endpoint = adapter.GetIPEndPoint(clientBucketConfig.UseSsl);
                    try
                    {
                        var connectionPool = ConnectionPoolFactory(clientBucketConfig.PoolConfiguration, endpoint);
                        var ioStrategy = IOStrategyFactory(connectionPool);
                        var server = new Core.Server(ioStrategy, adapter, ClientConfig, bucketConfig, Transcoder)
                        {
                            SaslFactory = SaslFactory
                        };
                        server.CreateSaslMechanismIfNotExists();

                        servers.Add(endpoint.Address, server);
                    }
                    catch (Exception e)
                    {
                        Log.ErrorFormat("Could not add server {0}. Exception: {1}", endpoint, e);
                    }
                }

                //If servers is empty that means we could not initialize _any_ nodes
                //We fail-fast here so that the problem can be indentified and handled.
                if (!servers.Any())
                {
                    throw new CouchbaseBootstrapException(ExceptionUtil.BootStrapFailedMsg);
                }

                var newDataNodes = servers
                         .Where(x => x.Value.IsDataNode)
                         .Select(x => x.Value)
                         .ToList();

                Interlocked.Exchange(ref DataNodes, newDataNodes);
                IsDataCapable = newDataNodes.Count > 0;

                var old = Interlocked.Exchange(ref Servers, servers);
                if (old != null)
                {
                    foreach (var server in old.Values)
                    {
                        server.Dispose();
                    }
                    old.Clear();
                }
            }
            Interlocked.Exchange(ref KeyMapper, new KetamaKeyMapper(Servers));
            Interlocked.Exchange(ref _bucketConfig, bucketConfig);
        }
Esempio n. 29
0
        /// <summary>
        /// transform a dictionary into the query string that is translated in byte array then
        /// </summary>
        /// <param name="items"></param>
        /// <returns></returns>
        public static byte[] PostBytes(Dictionary<string, string> items)
        {
            if (items == null || !items.Any())
                return null;

            var bytes = Encoding.UTF8.GetBytes(items.ToQueryString());

            return bytes.Any() ? bytes : null;
        }
Esempio n. 30
0
 public IBuildResponse Begin( HttpStatus status, Action<IDefineHeaders> headers ) 
 {
     var responseHeaders = new Dictionary<string,string>();
     var headerDefinition = new HeaderBuilder( responseHeaders );
     headers( headerDefinition );
     ChunkResponse = responseHeaders.Any( x => x.Key == HttpHeader.TRANSFER_ENCODING && x.Value.Equals( "chunked" ));
     Respond( status.ToString(), responseHeaders, Setup );
     return this;
 }
Esempio n. 31
0
        private void SetupFacets <T, TU>(EsRootObjectBase <T> results, SearchResultBase <TU> searchResult)
        {
            Dictionary <string, Aggregation> facets = results.Aggregations;

            if (facets?.Any() == true)
            {
                searchResult.Facets = facets.Select(f => new FacetEntry
                {
                    Key   = f.Key,
                    Count = f.Value.Facets.Length,
                    Hits  = f.Value.Facets.Select(i => new FacetHit
                    {
                        Key   = i.Key,
                        Count = i.Count
                    }).ToArray()
                }).ToArray();
            }
        }
Esempio n. 32
0
    private string GetParametersString(Dictionary <string, string> parameters)
    {
        if (parameters?.Any() != true)
        {
            return(string.Empty);
        }

        var parametersString = new StringBuilder("?");

        foreach (var parameter in parameters)
        {
            parametersString.Append($"{parameter.Key}={parameter.Value}&");
        }

        parametersString.Remove(parametersString.Length - 1, 1);

        return(parametersString.ToString());
    }
Esempio n. 33
0
        protected async Task <bool> Delete(string path, Dictionary <string, string> parameters = null)
        {
            if (parameters?.Any() ?? false)
            {
                path += "?" + string.Join("&",
                                          parameters.Select(kvp =>
                                                            $"{HttpUtility.UrlEncode(kvp.Key)}={HttpUtility.UrlEncode(kvp.Value)}"));
            }

            try
            {
                var response = await _client.DeleteAsync(path);

                return(response.IsSuccessStatusCode);
            }
            catch (HttpRequestException)
            {
                return(default);
            /// <summary>
            ///     Overrides INI file parameters.
            /// </summary>
            /// <param name="iniMap">
            ///     The INI map.
            /// </param>
            /// <param name="path">
            ///     The INI file path.
            /// </param>
            public static void Overrides(Dictionary <string, Dictionary <string, string> > iniMap, string path)
            {
                if (iniMap?.Any() != true)
                {
                    return;
                }
                var file = PathEx.Combine(path);

                try
                {
                    if (!PathEx.IsValidPath(file))
                    {
                        throw new NotSupportedException();
                    }
                    var dir = Path.GetDirectoryName(file);
                    if (string.IsNullOrEmpty(dir))
                    {
                        throw new ArgumentNullException(dir);
                    }
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                    if (!File.Exists(file))
                    {
                        File.Create(file).Close();
                    }
                }
                catch (Exception ex)
                {
                    Log.Write(ex);
                    return;
                }
                foreach (var data in iniMap)
                {
                    var section = data.Key;
                    foreach (var pair in iniMap[section])
                    {
                        var key   = pair.Key;
                        var value = pair.Value;
                        Ini.WriteDirect(section, key, value, path);
                    }
                }
            }
Esempio n. 35
0
        public override void Convert(Stream input, IResultLogWriter output, LoggingOptions loggingOptions)
        {
            input  = input ?? throw new ArgumentNullException(nameof(input));
            output = output ?? throw new ArgumentNullException(nameof(output));
            output.Initialize(id: null, automationId: null);

            var tool = new Tool
            {
                Name     = ToolFormat.PREfast,
                FullName = "PREfast Code Analysis"
            };

            output.WriteTool(tool);

            XmlReaderSettings settings = new XmlReaderSettings
            {
                XmlResolver = null
            };

            var serializer = new XmlSerializer(typeof(DefectList));

            using (var reader = XmlReader.Create(input, settings))
            {
                var defectList = (DefectList)serializer.Deserialize(reader);
                var results    = new List <Result>();
                foreach (Defect entry in defectList.Defects)
                {
                    results.Add(CreateResult(entry));
                }

                var fileInfoFactory = new FileInfoFactory(MimeType.DetermineFromFileExtension, loggingOptions);
                Dictionary <string, FileData> fileDictionary = fileInfoFactory.Create(results);

                if (fileDictionary?.Any() == true)
                {
                    output.WriteFiles(fileDictionary);
                }

                output.OpenResults();
                output.WriteResults(results);
                output.CloseResults();
            }
        }
Esempio n. 36
0
        /// <summary>
        /// Adds a mapping of custom extension values against custom attribute values for a given element to the provided
        /// extensions object.
        /// </summary>
        /// <param name="extensions">The target extensions object in which the mapped extensions and custom attribute
        /// values will be added to.</param>
        /// <param name="context">The OData context.</param>
        /// <param name="element">The target element.</param>
        internal static void AddCustomAtributesToExtensions(this IDictionary <string, IOpenApiExtension> extensions, ODataContext context, IEdmElement element)
        {
            if (extensions == null ||
                context == null ||
                element == null)
            {
                return;
            }

            Dictionary <string, string> atrributesValueMap = GetCustomXMLAtrributesValueMapping(context.Model, element, context.Settings.CustomXMLAttributesMapping);

            if (atrributesValueMap?.Any() ?? false)
            {
                foreach (var item in atrributesValueMap)
                {
                    extensions.TryAdd(item.Key, new OpenApiString(item.Value));
                }
            }
        }
Esempio n. 37
0
        private nac.CurlThin.SafeHandles.SafeSlistHandle curlSetHeader(CurlHandleType curlHandle,
                                                                       Dictionary <string, string> headers)
        {
            // followed documentation here: https://curl.se/libcurl/c/CURLOPT_HTTPHEADER.html
            if (headers?.Any() == true)
            {
                nac.CurlThin.SafeHandles.SafeSlistHandle list = SafeSlistHandle.Null;

                foreach (var pair in headers)
                {
                    list = nac.CurlThin.CurlNative.Slist.Append(list, $"{pair.Key}: {pair.Value}");
                }

                curl.SetOpt(curlHandle, CURLoption.HTTPHEADER, list.DangerousGetHandle());

                return(list); // list will need to be freed
            }

            return(null);
        }
        public static void PrintFormatted(Dictionary <string, Formatter> textAndFormats, Color fallbackColor, ConsoleWriteMethod writeMethod)
        {
            if (textAndFormats?.Any() ?? false)
            {
                foreach (var(text, format) in textAndFormats)
                {
                    switch (writeMethod)
                    {
                    case ConsoleWriteMethod.Write:
                        ColorfulConsole.WriteFormatted(text, fallbackColor, format);
                        break;

                    case ConsoleWriteMethod.WriteLine:
                    default:
                        ColorfulConsole.WriteLineFormatted(text, fallbackColor, format);
                        break;
                    }
                }
            }
        }
        public static EmailBodyModel CreateBodyHtmlTemplate(string bodyHtmlTemplatePath, BodyTemplateName bodyTemplateName, Dictionary <string, string> bodyHtmlTemplateValues = null)
        {
            Utils.IsNullOrEmptyThrowException(bodyHtmlTemplatePath, nameof(bodyHtmlTemplatePath));

            var filePath = Path.Combine(bodyHtmlTemplatePath, bodyTemplateName.Value);

            Utils.IsFileExistsThrowException(filePath);

            var template = new StreamReader(filePath).ReadToEnd();

            if (bodyHtmlTemplateValues?.Any() == true)
            {
                foreach (var item in bodyHtmlTemplateValues)
                {
                    template = template.Replace(item.Key, item.Value);
                }
            }

            return(new EmailBodyModel(template));
        }
Esempio n. 40
0
        public void Apply(ApplicationModel application)
        {
            if (_kvps?.Any() != true)
            {
                return;
            }

            var camelCased = _kvps.Select(kvp =>
                                          new KeyValuePair <string, string>(kvp.Key.ToCamelCase(), kvp.Value.ToCamelCase())
                                          ).ToList();

            // Build a list of ALL selectors, and fix up tokens.
            var anonObjects = application.Controllers.Select(cm => new
            {
                cm.ControllerName,
                selectors = cm.Selectors.Where(sm => sm.AttributeRouteModel is not null)
                            .Concat(cm.Actions.SelectMany(am =>
                                                          am.Selectors.Where(sm => sm.AttributeRouteModel is not null)
                                                          )
                                    )
            }
Esempio n. 41
0
        private static string GetEndpoint(string uri, Dictionary <string, string> parameters)
        {
            StringBuilder builder = new StringBuilder();

            if (parameters?.Any() == true)
            {
                foreach (var parameter in parameters)
                {
                    if (builder.Length == 0)
                    {
                        builder.Append($"?{parameter.Key}={parameter.Value}");
                    }
                    else
                    {
                        builder.Append($"&{parameter.Key}={parameter.Value}");
                    }
                }
            }

            return($"{uri}{builder}");
        }
Esempio n. 42
0
        IEnumerable <PropertyValue> FormatExtensions(Dictionary <string, SslExtension> extensions)
        {
            if (extensions?.Any() == false)
            {
                yield break;
            }

            var label = "Extensions";

            var values = extensions.Values.OrderBy(x => x.Position).ToArray();
            var names  = values.Select(x => $"0x{x.Type:X4} ({x.Name})").ToArray();
            var len    = names.Max(x => x.Length);

            for (int i = 0; i < values.Length; i++)
            {
                var name = names[i];
                yield return(Create(label, $"{name}{new string(' ', len - name.Length)}: {GetHex(values[i].RawData)}"));

                label = "";
            }
        }
Esempio n. 43
0
            private string BuildUpsertQuery(string[] keys, string table, bool insertKeys, object args, Dictionary <string, string> onUpdateArgs = null, Dictionary <string, string> onInsertArgs = null)
            {
                if (_connection is not SqlConnection)
                {
                    throw new InvalidOperationException("Merge is not supported for the current connection");
                }

                var type = args.GetType();

                return(_upsertCache.GetOrAdd($"{table}:{type.FullName}", _ =>
                {
                    var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(x => x.Name).ToList();

                    var argValues = string.Join(", ", props.Select(x => "@" + x));
                    var condition = keys.Select(k => $"Target.[{k}] = Source.[{k}]").Aggregate((x, y) => $"{x} AND {y}");

                    var columns = (insertKeys ? props : props.Except(keys)).Select(x => $"[{x}]").ToList();

                    var update = string.Join(", ", columns.Select(c => $"{c} = Source.{c}"));
                    var sourceColumns = string.Join(", ", columns.Select(c => $"Source.{c}"));

                    var onUpdate = onUpdateArgs?.Any() ?? false ? "," + string.Join(", ", onUpdateArgs.Select(x => $"[{x.Key}] = {x.Value}")) : "";
                    var onInsertColumns = onInsertArgs?.Any() ?? false ? "," + string.Join(", ", onInsertArgs.Select(x => $"[{x.Key}]")) : "";
                    var onInsertValues = onInsertArgs?.Any() ?? false ? "," + string.Join(", ", onInsertArgs.Select(x => $"{x.Value}")) : "";

                    var columnString = string.Join(",", columns);

                    var sql = $@"
                MERGE {table} AS Target USING ( VALUES ({argValues})) 
                AS Source ({string.Join(",", props.Select(x => $"[{x}]"))})
                ON {condition}
                WHEN MATCHED THEN 
                UPDATE SET {update}{onUpdate}
                WHEN NOT MATCHED BY TARGET THEN 
                INSERT ({columnString}{onInsertColumns}) VALUES ( {sourceColumns}{onInsertValues})
                OUTPUT INSERTED.*;";

                    return sql;
                }));
            }
Esempio n. 44
0
        public async Task RunJobAsync(string job, Dictionary <string, string> args = null, string cause = "Run through DiscordBot JenkinsService")
        {
            var endpoint  = "build";
            var argString = "";

            if (args?.Any() ?? false)
            {
                endpoint  = "buildWithParameters";
                argString = "&" + string.Join("&", args.Select(kvp => $"{kvp.Key}={HttpUtility.UrlEncode(kvp.Value)}"));
            }

            var uri = $"{JENKINS_URL}/buildByToken/{endpoint}?job={HttpUtility.UrlEncode(job)}&token={_token}{argString}";

            if (!string.IsNullOrWhiteSpace(cause))
            {
                uri += $"&cause={HttpUtility.UrlEncode(cause)}";
            }

            var resp = await _http.GetAsync(uri);

            resp.EnsureSuccessStatusCode();
        }
Esempio n. 45
0
        public override void Convert(Stream input, IResultLogWriter output, OptionallyEmittedData dataToInsert)
        {
            input = input ?? throw new ArgumentNullException(nameof(input));

            output = output ?? throw new ArgumentNullException(nameof(output));

            TSLintLog tsLintLog = logReader.ReadLog(input);

            Tool tool = new Tool
            {
                Name = "TSLint"
            };

            var run = new Run()
            {
                Tool = tool
            };

            output.Initialize(run);

            var results = new List <Result>();

            foreach (TSLintLogEntry entry in tsLintLog)
            {
                results.Add(CreateResult(entry));
            }

            var fileInfoFactory = new FileInfoFactory(MimeType.DetermineFromFileExtension, dataToInsert);
            Dictionary <string, FileData> fileDictionary = fileInfoFactory.Create(results);

            if (fileDictionary?.Any() == true)
            {
                output.WriteFiles(fileDictionary);
            }

            output.OpenResults();
            output.WriteResults(results);
            output.CloseResults();
        }
Esempio n. 46
0
        public static void FileSecureForwarding(Options option, Dictionary <string, string> fileMap)
        {
            if (fileMap?.Any() != true)
            {
                return;
            }
            foreach (var data in fileMap)
            {
                if (string.IsNullOrWhiteSpace(data.Key) || string.IsNullOrWhiteSpace(data.Value))
                {
                    continue;
                }
                var srcPath  = PathEx.Combine(data.Key);
                var destPath = PathEx.Combine(data.Value);
                if (!File.Exists(srcPath) || !PathEx.IsValidPath(srcPath) || !PathEx.IsValidPath(destPath))
                {
                    continue;
                }
                switch (option)
                {
                case Options.Exit:
                    using (var p = ProcessEx.Send($"DEL /F /Q \"{destPath}\"", Elevation.IsAdministrator, false))
                        if (p?.HasExited == false)
                        {
                            p.WaitForExit();
                        }
                    break;

                default:
                    using (var p = ProcessEx.Send($"COPY /Y \"{srcPath}\" \"{destPath}\"", Elevation.IsAdministrator, false))
                        if (p?.HasExited == false)
                        {
                            p.WaitForExit();
                        }
                    break;
                }
            }
        }
Esempio n. 47
0
            public void UnbindToServiceType()
            {
                #region OnClientConnect Method
                if (OnClientConnectMethod != null)
                {
                    Core.Log.LibDebug("Unbinding OnClientConnectMethod in the service {0}", Descriptor.Name);
                }
                OnClientConnectMethod = null;
                #endregion

                #region Events
                if (ServiceEventHandlers?.Any() != true)
                {
                    return;
                }
                foreach (var ev in ServiceEventHandlers)
                {
                    Core.Log.LibDebug("Unbinding Event: {0} on service {1}", ev.Key.Name, Descriptor.Name);
                    ev.Key.RemoveEventHandler(ServiceInstance, ev.Value);
                }
                ServiceEventHandlers.Clear();
                #endregion
            }
Esempio n. 48
0
 public void Dispose()
 {
     try
     {
         if (_toDispose?.Any() ?? false)
         {
             foreach (var toDispose in _toDispose)
             {
                 try
                 {
                     toDispose.Value.Dispose();
                 }
                 catch
                 {
                 }
             }
         }
     }
     catch
     {
         //intentional;disposing
     }
 }
Esempio n. 49
0
        /// <summary>
        /// Initialises the Test Logger with given parameters.
        /// </summary>
        /// <param name="events">Events that can be registered for.</param>
        /// <param name="parameters">Collection of parameters.</param>
        public void Initialize(TestLoggerEvents events, Dictionary <string, string> parameters)
        {
            if (events is null)
            {
                throw new ArgumentNullException(nameof(events));
            }

            if (parameters?.Any() != true)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            if (parameters.ContainsKey(Constants.LogFilePrefixKey) && parameters.ContainsKey(Constants.LogFileNameKey))
            {
                throw new ArgumentException($"The parameters {Constants.LogFileNameKey} and {Constants.LogFilePrefixKey} cannot be used together.");
            }

            var testRunDirectory = parameters[DefaultLoggerParameterNames.TestRunDirectory];

            TestParameters = parameters;
            Initialize(events, testRunDirectory);
            OnInitialize(TestParameters);
        }
        /// <summary>
        /// Génère le script SQL d'initialisation des listes reference.
        /// </summary>
        /// <param name="initDictionary">Dictionnaire des initialisations.</param>
        /// <param name="isStatic">True if generation for static list.</param>
        public void GenerateListInitScript(Dictionary <ModelClass, TableInit> initDictionary, bool isStatic)
        {
            var outputFileName = isStatic ? _parameters.StaticListFile : _parameters.ReferenceListFile;

            if (outputFileName == null)
            {
                if (initDictionary?.Any() ?? false)
                {
                    throw new ArgumentNullException(isStatic ? "StaticListFile" : "ReferenceListFile");
                }
                else
                {
                    return;
                }
            }

            Console.WriteLine("Generating init script " + outputFileName);
            DeleteFileIfExists(outputFileName);

            using (var writerInsert = File.CreateText(outputFileName))
            {
                writerInsert.WriteLine("-- =========================================================================================== ");
                writerInsert.WriteLine($"--   Application Name	:	{_appName} ");
                writerInsert.WriteLine("--   Script Name		:	"+ outputFileName);
                writerInsert.WriteLine("--   Description		:	Script d'insertion des données de références"+ (!isStatic ? " non " : " ") + "statiques. ");
                writerInsert.WriteLine("-- ===========================================================================================");

                if (initDictionary != null)
                {
                    var orderList = OrderStaticTableList(initDictionary);
                    foreach (ModelClass modelClass in orderList)
                    {
                        WriteInsert(writerInsert, initDictionary[modelClass], modelClass, isStatic);
                    }
                }
            }
        }
Esempio n. 51
0
        private Uri CreateApiUrl(string requestPath, Dictionary <string, object> queryParams = null)
        {
            var builder = new UriBuilder($"{BaseUrl}/{requestPath}");

            if (queryParams?.Any() == true)
            {
                var keyValues = new List <string>();
                foreach (var queryParam in queryParams)
                {
                    var keyValue = $"{queryParam.Key}=";
                    if (queryParam.Value != null)
                    {
                        keyValue += Uri.EscapeDataString(queryParam.Value.ToString());
                    }
                    keyValues.Add(keyValue);
                }
                builder.Query = string.Join("&", keyValues.ToArray());
            }

            var uriString = builder.ToString();
            var uri       = new Uri(uriString);

            return(uri);
        }
Esempio n. 52
0
        /// <summary>
        /// Get an adaptive card attachment with given content. It takes a Dictionary<string, string>.
        /// For each KeyValuePair in the dictionary, we'll replace "{key}" with "value" in the json string.
        /// </summary>
        /// <param name="args">content to be put into the card</param>
        /// <returns>formatted adaptive card attachment with proper values injected</returns>
        public Attachment GetAttachment(Dictionary <string, string> values = null)
        {
            var formattedCard = this.jsonContent;

            if (values?.Any() == true)
            {
                // Format the objects into the card
                var sb = new StringBuilder(formattedCard);
                foreach (var kvp in values)
                {
                    // Replace {name} with value
                    sb.Replace($"{{{kvp.Key}}}", HttpUtility.JavaScriptStringEncode(kvp.Value));
                }

                formattedCard = sb.ToString();
            }

            // Construct attachment object
            return(new Attachment()
            {
                ContentType = "application/vnd.microsoft.card.adaptive",
                Content = JsonConvert.DeserializeObject <AdaptiveCard>(formattedCard),
            });
        }
Esempio n. 53
0
        private static string GetMappedColumnName(MemberInfo member, Dictionary <string, string> columnMappings)
        {
            if (member == null)
            {
                return(null);
            }

            var attrib = (DapperColumnAttribute)Attribute.GetCustomAttribute(member, typeof(DapperColumnAttribute), false);

            if (attrib != null)
            {
                return(attrib.Name);
            }

            string mappedPropName = null;

            if (columnMappings?.Any() == true &&
                columnMappings.TryGetValue(member.Name, out mappedPropName))
            {
                return(mappedPropName);
            }

            return(null);
        }
Esempio n. 54
0
        protected override void ReadObjectProperties(JsonReader reader, DynamicObject result, Dictionary <string, Property> properties, JsonSerializer serializer)
        {
            reader.Advance();

            TypeInfo?typeInfo = null;

            void SetResult(IEnumerable <DynamicProperty>?properties = null)
            {
                reader.AssertEndObject();

                result.Type = typeInfo;
                if (properties?.Any() == true)
                {
                    result.Properties = new PropertySet(properties);
                }
            }

            if (reader.IsProperty(nameof(DynamicObject.Type)))
            {
                typeInfo = reader.Read <TypeInfo?>(serializer);
                reader.Advance();
            }

            if (reader.IsProperty("Value"))
            {
                var value = reader.Read(typeInfo, serializer);
                SetResult(new[] { new DynamicProperty(string.Empty, value) });
                return;
            }

            if (reader.IsProperty("Values"))
            {
                reader.Advance();
                if (reader.TokenType == JsonToken.Null)
                {
                    SetResult();
                    return;
                }

                if (reader.TokenType != JsonToken.StartArray)
                {
                    throw reader.CreateException($"Expected array");
                }

                var elementType = TypeHelper.GetElementType(typeInfo?.Type) ?? typeof(object);
                bool TryReadNextItem(out object?value)
                {
                    if (!reader.TryRead(elementType, serializer, out value))
                    {
                        // TODO: is max length quota required?
                        if (reader.TokenType == JsonToken.EndArray)
                        {
                            return(false);
                        }

                        throw reader.CreateException("Unexpected token structure.");
                    }

                    return(true);
                }

                var values = new List <object?>();
                while (TryReadNextItem(out var item))
                {
                    values.Add(item);
                }

                if (values.Any(x => x != null && (elementType == typeof(object) || !elementType.IsAssignableFrom(x.GetType()))) &&
                    values.All(x => x is null || x is string))
                {
                    elementType = typeof(string);
                }

                var valueArray = CastCollectionToArrayOfType(elementType, values);
                SetResult(new[] { new DynamicProperty(string.Empty, valueArray) });
                return;
            }

            if (reader.IsProperty(nameof(DynamicObject.Properties)))
            {
                reader.Advance();
                if (reader.TokenType == JsonToken.Null)
                {
                    SetResult();
                    return;
                }

                if (reader.TokenType != JsonToken.StartArray)
                {
                    throw reader.CreateException("Expected array");
                }

                var propertySet = new List <DynamicProperty>();

                bool NextItem()
                {
                    // TODO: is max length quota required?
                    reader.Advance();
                    return(reader.TokenType != JsonToken.EndArray);
                }

                while (NextItem())
                {
                    reader.AssertStartObject(false);

                    reader.AssertProperty(nameof(DynamicProperty.Name));
                    var name = reader.ReadAsString() ?? throw reader.CreateException("Property name must not be null");

                    reader.AssertProperty(nameof(Type));
                    var type = reader.Read <TypeInfo?>(serializer);

                    reader.AssertProperty(nameof(DynamicProperty.Value));
                    var value = reader.Read(type, serializer);

                    reader.AssertEndObject();
                    propertySet.Add(new DynamicProperty(name, value));
                }

                SetResult(propertySet);
                return;
            }

            throw reader.CreateException($"Unexpected token {reader.TokenType}");
        }
Esempio n. 55
0
        /// <summary>
        /// Takes a screenshot of a web page.
        /// </summary>
        /// <param name="url">The URL of the web page to screenshoot.</param>
        /// <param name="filePath">The image file to save to.</param>
        /// <param name="width">The device width of the browser</param>
        /// <returns>The full file path of the saved image</returns>
        public NavigationTiming TakeScreenshot(string url, string filePath, int?width = null)
        {
            var outputDir = Path.GetDirectoryName(filePath);

            Directory.CreateDirectory(outputDir);
            _driver.Navigate().GoToUrl(url);

            ResizeWindow();
            if (_options.HighlightBrokenLinks)
            {
                HighlightBrokenLinks(url);
            }

            // Sometimes, when this isn't high enough, the performance timings return incomplete data.
            int screenshotDelay = 3000;

            Thread.Sleep(screenshotDelay);

            var requestStats = GetRequestStats();
            var screenshot   = _driver.GetScreenshot();

            screenshot.SaveAsFile(filePath, _imageFormat);
            ClearResize();
            return(requestStats);

            // LOCAL FUNCTIONS

            NavigationTiming GetRequestStats()
            {
                try
                {
                    var stats = (string)_driver.ExecuteScript(
                        @"return (window && window.performance && JSON.stringify([...window.performance.getEntriesByType('navigation'),{ }][0])) || '{}'");
                    var deprecatedTiming = (string)_driver.ExecuteScript(
                        @"return (window && window.performance && window.performance.timing && JSON.stringify(window.performance.timing)) || '{}'");

                    Logger.Default.Log($"Stats for {url}...");
                    Logger.Default.Log(stats);
                    Logger.Default.Log(deprecatedTiming);

                    string ConvertToInt(Match m)
                    {
                        var origValue = m.Value;

                        if (!double.TryParse(origValue, out var dblVal))
                        {
                            return(origValue);
                        }
                        var intValue = (int)Math.Round(dblVal);

                        return(intValue.ToString());
                    }

                    stats = Regex.Replace(stats, @"\d+\.\d+", ConvertToInt);
                    Logger.Default.Log("stats converted to int: " + stats);

                    return(JsonConvert.DeserializeObject <NavigationTiming>((string)stats));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Error parsing request timings: " + ex.Message);
                    return(new NavigationTiming());
                }
            }

            /// <summary>
            /// Repeatedly resize the window to account for lazily loaded elements.
            /// </summary>
            /// <param name="width"></param>
            void ResizeWindow()
            {
                // Adapted from https://stackoverflow.com/a/56535317
                int       numTries = 0;
                const int maxTries = 8;
                int       prevHeight;
                int       calculatedHeight = -1;
                string    autoWidthCommand =
                    @"return Math.max(
                        window.innerWidth,
                        document.body.scrollWidth,
                        document.documentElement.scrollWidth)";

                // Repeatedly resize height to allow new elements to (lazily) load.
                do
                {
                    prevHeight = calculatedHeight;
                    var calculatedWidth = width.HasValue ? $"return {width}" : autoWidthCommand;
                    calculatedHeight = CalculateDocHeight();

                    // TODO: Set device-specific user agents.
                    Dictionary <string, object> metrics = new Dictionary <string, object>
                    {
                        ["width"]             = _driver.ExecuteScript(calculatedWidth),
                        ["height"]            = calculatedHeight,
                        ["deviceScaleFactor"] = ScaleFactor(false),
                        ["mobile"]            = _driver.ExecuteScript("return typeof window.orientation !== 'undefined'")
                    };
                    _driver.ExecuteChromeCommand("Emulation.setDeviceMetricsOverride", metrics);
                } while (calculatedHeight != prevHeight && ++numTries < maxTries);

                // LOCAL FUNCTIONS

                int CalculateDocHeight()
                {
                    // Sometimes a long, sometimes double, etc
                    object jsHeight = _driver.ExecuteScript(
                        @"return Math.max(
                        document.body.scrollHeight,
                        document.body.offsetHeight,
                        document.documentElement.clientHeight,
                        document.documentElement.scrollHeight,
                        document.documentElement.offsetHeight,
                        document.documentElement.getBoundingClientRect().height)");
                    double numericHeight = Convert.ToDouble(jsHeight);

                    return((int)Math.Ceiling(numericHeight));
                }

                // False for a 1:1 pixel ratio with the image
                // True for an easier-to-read image on the current monitor.
                double ScaleFactor(bool shouldScaleImage) =>
                shouldScaleImage
                    ? (double)_driver.ExecuteScript("return window.devicePixelRatio")
                    : 1.0;
            }

            void ClearResize()
            {
                try
                {
                    _driver.ExecuteChromeCommand("Emulation.clearDeviceMetricsOverride", new Dictionary <string, object>());
                }
                catch (Exception ex)
                {
                    // Usually thrown when the driver or browser window is closed.
                    if (!(ex is WebDriverException || ex is NoSuchWindowException))
                    {
                        throw;
                    }
                }
            }

            void HighlightBrokenLinks(string rawCallingUri)
            {
                var standardizedUri = new Uri(rawCallingUri);

                standardizedUri = standardizedUri.TryStandardize();

                if (_brokenLinks?.Any() != true)
                {
                    return;
                }

                var selectors =
                    _brokenLinks
                    .SelectMany(l => l.Value.Sources)
                    .Where(x => standardizedUri.Equals(x.CallingPage))
                    .Select(x => $@"a[href='{x.Href}']");

                var combinedSelector = string.Join(",", selectors);

                var styles = $@"
                    {combinedSelector} {{
                        border: 3px dashed red;
                    }}";

                var script = $@"
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = `{styles}`;
document.getElementsByTagName('head')[0].appendChild(style);";

                _driver.ExecuteScript(script);
            }
        }
Esempio n. 56
0
        /// <summary>
        /// 获取或创建架构属性信息
        /// </summary>
        /// <param name="type"></param>
        /// <param name="innerModel">处理内部模型</param>
        /// <param name="exceptionProperties">特别输出的属性</param>
        /// <param name="ignoreProperties">特别忽略的属性</param>
        /// <remarks>如果在特别输出参数和特别忽略参数中同时指定了同一个属性,那么最终不会输出该属性</remarks>
        /// <returns></returns>
        public static Dictionary <string, List <string> > GetOrNullForPropertyDic(this Type type, bool innerModel = true, Dictionary <string, List <string> > exceptionProperties = null, Dictionary <string, List <string> > ignoreProperties = null)
        {
            var propertyDic = type.GetPropertysOfTypeDic(exceptionProperties?.Any() == true && ignoreProperties?.Any() == true);

            if (propertyDic.Any())
            {
                goto end;
            }

            type.FilterModel((_type, prop) =>
            {
                if (!propertyDic.ContainsKey(_type.FullName))
                {
                    propertyDic.Add(_type.FullName, new List <string>()
                    {
                        prop.Name
                    });
                }
                else
                {
                    propertyDic[_type.FullName].Add(prop.Name);
                }

                if (!CacheExtention.AssemblyOfTypeDic.ContainsKey(_type.FullName))
                {
                    CacheExtention.AssemblyOfTypeDic.AddOrUpdate(_type.FullName, _type.Assembly.FullName, (key, old) => _type.Assembly.FullName);
                }
            },
                             null,
                             innerModel);

            type.SetPropertysOfTypeDic(propertyDic);

end:

            if (exceptionProperties != null)
            {
                foreach (var item in exceptionProperties)
                {
                    if (!propertyDic.ContainsKey(item.Key))
                    {
                        propertyDic.Add(item.Key, item.Value);
                    }
                    else
                    {
                        propertyDic[item.Key] = propertyDic[item.Key].Union(item.Value).ToList();
                    }
                }
            }

            if (ignoreProperties != null)
            {
                foreach (var item in ignoreProperties)
                {
                    if (propertyDic.ContainsKey(item.Key))
                    {
                        propertyDic[item.Key] = propertyDic[item.Key].Except(item.Value).ToList();
                    }
                }
            }

            return(propertyDic);
        }
Esempio n. 57
0
        public RequestResult RunRequest(string resource, string requestMethod, object body = null, int?timeout = null, Dictionary <string, object> formParameters = null)
        {
            try
            {
                var requestUrl = ZendeskUrl + resource;

                var req = WebRequest.Create(requestUrl) as HttpWebRequest;

                if (Proxy != null)
                {
                    req.Proxy = Proxy;
                }

                req.Headers["Authorization"] = GetPasswordOrTokenAuthHeader();
                req.PreAuthenticate          = true;

                req.Method  = requestMethod; //GET POST PUT DELETE
                req.Accept  = "application/json, application/xml, text/json, text/x-json, text/javascript, text/xml";
                req.Timeout = 120000;        //?? req.Timeout;

                byte[] data = null;

                if (formParameters?.Any() ?? false)
                {
                    data = GetFromData(req, formParameters);
                }
                else if (body is ZenFile zenFile)
                {
                    req.ContentType = zenFile.ContentType;
                    data            = zenFile.FileData;
                }
                else if (body != null)
                {
                    req.ContentType = "application/json";
                    data            = encoding.GetBytes(JsonConvert.SerializeObject(body, jsonSettings));
                }

                if (data != null)
                {
                    req.ContentLength = data.Length;
                    using (var dataStream = req.GetRequestStream())
                    {
                        dataStream.Write(data, 0, data.Length);
                    }
                }

                var res                = req.GetResponse();
                var response           = res as HttpWebResponse;
                var responseFromServer = string.Empty;
                using (var responseStream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        responseFromServer = reader.ReadToEnd();
                    }
                }

                return(new RequestResult {
                    Content = responseFromServer, HttpStatusCode = response.StatusCode
                });
            }
            catch (WebException ex)
            {
                var wException = GetWebException(resource, body, ex);
                throw wException;
            }
        }
        internal async static Task <(IEnumerable <IKubernetesResource>, IDictionary <string, string>)> GetFunctionsDeploymentResources(
            string name,
            string imageName,
            string @namespace,
            TriggersPayload triggers,
            IDictionary <string, string> secrets,
            string pullSecret            = null,
            string secretsCollectionName = null,
            string configMapName         = null,
            bool useConfigMap            = false,
            int?pollingInterval          = null,
            int?cooldownPeriod           = null,
            string serviceType           = "LoadBalancer",
            int?minReplicas = null,
            int?maxReplicas = null,
            string keysSecretCollectionName = null,
            bool mountKeysAsContainerVolume = false)
        {
            ScaledObjectV1Alpha1 scaledobject = null;
            var result        = new List <IKubernetesResource>();
            var deployments   = new List <DeploymentV1Apps>();
            var httpFunctions = triggers.FunctionsJson
                                .Where(b => b.Value["bindings"]?.Any(e => e?["type"].ToString().IndexOf("httpTrigger", StringComparison.OrdinalIgnoreCase) != -1) == true);
            var nonHttpFunctions = triggers.FunctionsJson.Where(f => httpFunctions.All(h => h.Key != f.Key));

            keysSecretCollectionName = string.IsNullOrEmpty(keysSecretCollectionName)
                ? $"func-keys-kube-secret-{name}"
                : keysSecretCollectionName;
            if (httpFunctions.Any())
            {
                int position         = 0;
                var enabledFunctions = httpFunctions.ToDictionary(k => $"AzureFunctionsJobHost__functions__{position++}", v => v.Key);
                //Environment variables for the func app keys kubernetes secret
                var kubernetesSecretEnvironmentVariable = FuncAppKeysHelper.FuncKeysKubernetesEnvironVariables(keysSecretCollectionName, mountKeysAsContainerVolume);
                var additionalEnvVars = enabledFunctions.Concat(kubernetesSecretEnvironmentVariable).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
                var deployment        = GetDeployment(name + "-http", @namespace, imageName, pullSecret, 1, additionalEnvVars, port: 80);
                deployments.Add(deployment);
                var service = GetService(name + "-http", @namespace, deployment, serviceType);
                result.Add(service);
            }

            if (nonHttpFunctions.Any())
            {
                int position         = 0;
                var enabledFunctions = nonHttpFunctions.ToDictionary(k => $"AzureFunctionsJobHost__functions__{position++}", v => v.Key);
                var deployment       = GetDeployment(name, @namespace, imageName, pullSecret, minReplicas ?? 0, enabledFunctions);
                deployments.Add(deployment);
                scaledobject = GetScaledObject(name, @namespace, triggers, deployment, pollingInterval, cooldownPeriod, minReplicas, maxReplicas);
            }

            // Set worker runtime if needed.
            if (!secrets.ContainsKey(Constants.FunctionsWorkerRuntime))
            {
                secrets[Constants.FunctionsWorkerRuntime] = GlobalCoreToolsSettings.CurrentWorkerRuntime.ToString();
            }

            int resourceIndex = 0;

            if (useConfigMap)
            {
                var configMap = GetConfigMap(name, @namespace, secrets);
                result.Insert(resourceIndex, configMap);
                resourceIndex++;
                foreach (var deployment in deployments)
                {
                    deployment.Spec.Template.Spec.Containers.First().EnvFrom = new ContainerEnvironmentFromV1[]
                    {
                        new ContainerEnvironmentFromV1
                        {
                            ConfigMapRef = new NamedObjectV1
                            {
                                Name = configMap.Metadata.Name
                            }
                        }
                    };
                }
            }
            else if (!string.IsNullOrEmpty(secretsCollectionName))
            {
                foreach (var deployment in deployments)
                {
                    deployment.Spec.Template.Spec.Containers.First().EnvFrom = new ContainerEnvironmentFromV1[]
                    {
                        new ContainerEnvironmentFromV1
                        {
                            SecretRef = new NamedObjectV1
                            {
                                Name = secretsCollectionName
                            }
                        }
                    };
                }
            }
            else if (!string.IsNullOrEmpty(configMapName))
            {
                foreach (var deployment in deployments)
                {
                    deployment.Spec.Template.Spec.Containers.First().EnvFrom = new ContainerEnvironmentFromV1[]
                    {
                        new ContainerEnvironmentFromV1
                        {
                            ConfigMapRef = new NamedObjectV1
                            {
                                Name = configMapName
                            }
                        }
                    };
                }
            }
            else
            {
                var secret = GetSecret(name, @namespace, secrets);
                result.Insert(resourceIndex, secret);
                resourceIndex++;
                foreach (var deployment in deployments)
                {
                    deployment.Spec.Template.Spec.Containers.First().EnvFrom = new ContainerEnvironmentFromV1[]
                    {
                        new ContainerEnvironmentFromV1
                        {
                            SecretRef = new NamedObjectV1
                            {
                                Name = secret.Metadata.Name
                            }
                        }
                    };
                }
            }

            IDictionary <string, string> resultantFunctionKeys = new Dictionary <string, string>();

            if (httpFunctions.Any())
            {
                var currentImageFuncKeys = FuncAppKeysHelper.CreateKeys(httpFunctions.Select(f => f.Key));
                resultantFunctionKeys = GetFunctionKeys(currentImageFuncKeys, await GetExistingFunctionKeys(keysSecretCollectionName, @namespace));
                if (resultantFunctionKeys?.Any() == true)
                {
                    result.Insert(resourceIndex, GetSecret(keysSecretCollectionName, @namespace, resultantFunctionKeys));
                    resourceIndex++;
                }

                //if function keys Secrets needs to be mounted as volume in the function runtime container
                if (mountKeysAsContainerVolume)
                {
                    FuncAppKeysHelper.CreateFuncAppKeysVolumeMountDeploymentResource(deployments, keysSecretCollectionName);
                }
                //Create the Pod identity with the role to modify the function kubernetes secret
                else
                {
                    var svcActName = $"{name}-function-keys-identity-svc-act";
                    var svcActDeploymentResource = GetServiceAccount(svcActName, @namespace);
                    result.Insert(resourceIndex, svcActDeploymentResource);
                    resourceIndex++;

                    var funcKeysManagerRoleName = "functions-keys-manager-role";
                    var secretManagerRole       = GetSecretManagerRole(funcKeysManagerRoleName, @namespace);
                    result.Insert(resourceIndex, secretManagerRole);
                    resourceIndex++;
                    var roleBindingName = $"{svcActName}-functions-keys-manager-rolebinding";
                    var funcKeysRoleBindingDeploymentResource = GetRoleBinding(roleBindingName, @namespace, funcKeysManagerRoleName, svcActName);
                    result.Insert(resourceIndex, funcKeysRoleBindingDeploymentResource);
                    resourceIndex++;

                    //add service account identity to the pod
                    foreach (var deployment in deployments)
                    {
                        deployment.Spec.Template.Spec.ServiceAccountName = svcActName;
                    }
                }
            }

            result = result.Concat(deployments).ToList();
            return(scaledobject != null ? result.Append(scaledobject) : result, resultantFunctionKeys);
        }
Esempio n. 59
0
        //public void AddApiFileParameter(Dictionary<string, object> multipartData, string filePath, int pictureId)
        //{
        //	var count = 0;
        //	var paths = filePath.Contains(";") ? filePath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList() : new List<string> { filePath };

        //	foreach (var path in paths)
        //	{
        //		using (var fstream = new FileStream(path, FileMode.Open, FileAccess.Read))
        //		{
        //			byte[] data = new byte[fstream.Length];
        //			fstream.Read(data, 0, data.Length);

        //			var name = Path.GetFileName(path);
        //			var id = string.Format("my-file-{0}", ++count);
        //			var apiFile = new ApiFileParameter(data, name, MimeMapping.GetMimeMapping(name));

        //			if (pictureId != 0)
        //			{
        //				apiFile.Parameters.Add("PictureId", pictureId.ToString());
        //			}

        //			// Test pass through of custom parameters
        //			apiFile.Parameters.Add("CustomValue1", string.Format("{0:N}", Guid.NewGuid()));
        //			apiFile.Parameters.Add("CustomValue2", string.Format("say hello to {0}", id));

        //			multipartData.Add(id, apiFile);

        //			fstream.Close();
        //		}
        //	}
        //}

        public HttpWebRequest StartRequest(WebApiRequestContext context, string content, Dictionary <string, object> multipartData, out StringBuilder requestContent)
        {
            requestContent = new StringBuilder();

            if (context == null || !context.IsValid)
            {
                return(null);
            }

            // Client system time must not be too far away from APPI server time! Check response header.
            // ISO-8601 utc timestamp with milliseconds (e.g. 2013-09-23T09:24:43.5395441Z).
            string timestamp = DateTime.UtcNow.ToString("o");

            byte[] data           = null;
            var    contentMd5Hash = string.Empty;

            var request = (HttpWebRequest)WebRequest.Create(context.Url);

            SetTimeout(request);

            // Optional.
            request.UserAgent = Program.ConsumerName;
            request.Method    = context.HttpMethod;

            request.Headers.Add(HttpRequestHeader.Pragma, "no-cache");
            request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache, no-store");

            request.Accept = context.HttpAcceptType;
            request.Headers.Add(HttpRequestHeader.AcceptCharset, "UTF-8");

            request.Headers.Add(WebApiGlobal.HeaderName.PublicKey, context.PublicKey);
            request.Headers.Add(WebApiGlobal.HeaderName.Date, timestamp);

            // Additional headers.
            if (context.AdditionalHeaders.HasValue())
            {
                var jsonHeaders = JObject.Parse(context.AdditionalHeaders);
                foreach (var item in jsonHeaders)
                {
                    var value = item.Value?.ToString();
                    if (item.Key.HasValue() && value.HasValue())
                    {
                        request.Headers.Add(item.Key, value);
                    }
                }
            }

            if (BodySupported(context.HttpMethod))
            {
                if (MultipartSupported(context.HttpMethod) && (multipartData?.Any() ?? false))
                {
                    var formDataBoundary = string.Format("----------{0:N}", Guid.NewGuid());

                    data           = GetMultipartFormData(multipartData, formDataBoundary, requestContent);
                    contentMd5Hash = CreateContentMd5Hash(data);

                    request.ContentLength = data.Length;
                    request.ContentType   = "multipart/form-data; boundary=" + formDataBoundary;
                }
                else if (!string.IsNullOrWhiteSpace(content))
                {
                    requestContent.Append(content);
                    data           = Encoding.UTF8.GetBytes(content);
                    contentMd5Hash = CreateContentMd5Hash(data);

                    request.ContentLength = data.Length;
                    request.ContentType   = "application/json; charset=utf-8";
                }
                else
                {
                    request.ContentLength = 0;
                }
            }

            if (!string.IsNullOrEmpty(contentMd5Hash))
            {
                // Optional. Provider returns HmacResult.ContentMd5NotMatching if there's no match.
                request.Headers.Add(HttpRequestHeader.ContentMd5, contentMd5Hash);
            }

            var messageRepresentation = CreateMessageRepresentation(context, contentMd5Hash, timestamp, true);
            //Debug.WriteLine(messageRepresentation);
            var signature = CreateSignature(context.SecretKey, messageRepresentation);

            request.Headers.Add(HttpRequestHeader.Authorization, CreateAuthorizationHeader(signature));

            if (data != null)
            {
                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }

            requestContent.Insert(0, request.Headers.ToString());

            return(request);
        }
 public bool HasRoutes()
 {
     return(_routeData?.Any() ?? false);
 }