Example #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 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);
        }
Example #3
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();
        }
Example #5
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);
			}
		}
Example #6
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;
        }
        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;
        }
        internal static void Deserialize(CharacterFilterBase filter, Dictionary<string, object> fieldDict)
        {
            if (fieldDict == null || !fieldDict.Any())
                return;

            filter.Version = fieldDict.GetDoubleOrNull(_VERSION);
        }
        /// <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);
            }
        }
        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);
        }
        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;
        }
        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);
            }
        }
Example #14
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;
        }
Example #15
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;
        }
Example #16
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;
        }
Example #17
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;
        }
Example #18
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 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--;
                    }
                }
            }
        }
Example #20
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;
        }
Example #21
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();
        }
Example #22
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)
				});
			}
		}
 public void CreateLiveConnectFoldersSkyDrive(Dictionary<string, object> folderDictionary, EventHandler<LiveOperationCompletedEventArgs> callback)
 {
     if (folderDictionary.Any())
     {
         CreateLiveConnectFolders("me/skydrive", folderDictionary, callback);
     }
 }
Example #24
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;
        }
        public void DictionaryExtensions_Any_ReturnsFalseIfDictionaryDoesNotContainItems()
        {
            var dictionary = new Dictionary<Int32, String>();

            var result = dictionary.Any();

            TheResultingValue(result).ShouldBe(false);
        }
Example #26
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;
 }
        /// <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);
        }
        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;
        }
Example #29
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);
			}
		}
Example #30
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;
        }