Esempio n. 1
0
 public ActionResult RetailAndPowerTrend(IDictionary<string, GraphModel> graphModels)
 {
     var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
     var months = graphModels.Select(x => x.Key.Substring(0, 3));
     ViewBag.months = serializer.Serialize(months);
     var actualManpowers = graphModels.Select(x => x.Value.ActualManPower);
     ViewBag.actualManPowers = serializer.Serialize(actualManpowers);
     var retails = graphModels.Select(x => x.Value.Retail);
     ViewBag.retails = serializer.Serialize(retails);
     var planManpower = graphModels.Select(x => x.Value.PlanManPower);
     ViewBag.planManPower = serializer.Serialize(planManpower);
     return PartialView();
 }
Esempio n. 2
0
        static SchemaManager()
        {
            const short arraySize = 3;

            CsdlNamespaces = new Dictionary<Version, XNamespace>(arraySize);
            CsdlNamespaces.Add(EntityFrameworkVersion.Version1, XNamespace.Get("http://schemas.microsoft.com/ado/2006/04/edm"));
            CsdlNamespaces.Add(EntityFrameworkVersion.Version2, XNamespace.Get("http://schemas.microsoft.com/ado/2008/09/edm"));
            CsdlNamespaces.Add(EntityFrameworkVersion.Version3, XNamespace.Get("http://schemas.microsoft.com/ado/2009/11/edm"));
            CsdlNamespaceNames = CsdlNamespaces.Select(n => n.Value.NamespaceName).ToArray();

            MslNamespaces = new Dictionary<Version, XNamespace>(arraySize);
            MslNamespaces.Add(EntityFrameworkVersion.Version1, XNamespace.Get("urn:schemas-microsoft-com:windows:storage:mapping:CS"));
            MslNamespaces.Add(EntityFrameworkVersion.Version2, XNamespace.Get("http://schemas.microsoft.com/ado/2008/09/mapping/cs"));
            MslNamespaces.Add(EntityFrameworkVersion.Version3, XNamespace.Get("http://schemas.microsoft.com/ado/2009/11/mapping/cs"));
            MslNamespaceNames = MslNamespaces.Select(n => n.Value.NamespaceName).ToArray();

            SsdlNamespaces = new Dictionary<Version, XNamespace>(arraySize);
            SsdlNamespaces.Add(EntityFrameworkVersion.Version1, XNamespace.Get("http://schemas.microsoft.com/ado/2006/04/edm/ssdl"));
            SsdlNamespaces.Add(EntityFrameworkVersion.Version2, XNamespace.Get("http://schemas.microsoft.com/ado/2009/02/edm/ssdl"));
            SsdlNamespaces.Add(EntityFrameworkVersion.Version3, XNamespace.Get("http://schemas.microsoft.com/ado/2009/11/edm/ssdl"));
            SsdlNamespaceNames = SsdlNamespaces.Select(n => n.Value.NamespaceName).ToArray();

            EdmxNamespaces = new Dictionary<Version, XNamespace>(arraySize);
            EdmxNamespaces.Add(EntityFrameworkVersion.Version1, XNamespace.Get("http://schemas.microsoft.com/ado/2007/06/edmx"));
            EdmxNamespaces.Add(EntityFrameworkVersion.Version2, XNamespace.Get("http://schemas.microsoft.com/ado/2008/10/edmx"));
            EdmxNamespaces.Add(EntityFrameworkVersion.Version3, XNamespace.Get("http://schemas.microsoft.com/ado/2009/11/edmx"));
            EdmxNamespaceNames = EdmxNamespaces.Select(n => n.Value.NamespaceName).ToArray();

            NamespaceToVersionReverseLookUp = new Dictionary<XNamespace, Version>();
            foreach (var kvp in CsdlNamespaces.Concat(MslNamespaces).Concat(SsdlNamespaces).Concat(EdmxNamespaces))
            {
                NamespaceToVersionReverseLookUp.Add(kvp.Value, kvp.Key);
            }
        }
Esempio n. 3
0
 public void Remap(IDictionary<string, AppFunc> map)
 {
     _map = map
         .Select(kv => Tuple.Create(kv.Key, kv.Value))
         .OrderByDescending(m => m.Item1.Length)
         .ToArray();
 }
Esempio n. 4
0
		/// <summary>
		/// Converts the specified parameters.
		/// </summary>
		/// <param name="parameters">The parameters.</param>
		/// <returns></returns>
		public static NameValuePairList Convert(IDictionary<string, string> parameters)
		{
			return new NameValuePairList {
				Count = (uint)parameters.Count,
				Pairs = parameters.Select(p => new NameValuePair(p.Key, p.Value)).ToArray()
			};
		}
 /// <summary>
 /// Constructor.
 /// </summary>
 public UncompressedMemoryArchive(IDictionary<string, byte[]> files)
 {
     _contents = files
         .Select(kvp => new UncompressedMemoryArchiveFile(kvp.Key, kvp.Value))
         .Cast<IArchiveFile>()
         .ToList();
 }
 /// <summary>
 ///   <para>Modifies target URL address by adding by adding given list of name/value pairs to its Query component.</para>
 ///   <para>Names and values of query string parameters are URL-encoded.</para>
 /// </summary>
 /// <param name="self">URI address to be modified.</param>
 /// <param name="parameters">Map of name/value parameters for query string.</param>
 /// <returns>Updated URI address.</returns>
 /// <exception cref="ArgumentNullException">If either <paramref name="self"/> or <paramref name="parameters"/> is a <c>null</c> reference.</exception>
 /// <seealso cref="Query(Uri, object)"/>
 /// <seealso cref="Query(Uri, IDictionary{string, object})"/>
 public static Uri Query(this Uri self, IDictionary<string, string> parameters)
 {
   var builder = new UriBuilder(self);
   var query = parameters.Select(parameter => $"{parameter.Key.UrlEncode()}={parameter.Value.UrlEncode()}").Join("&");
   builder.Query = builder.Query.Length > 1 ? builder.Query.Substring(1) + (query.IsEmpty() ? string.Empty : "&" + query) : query;
   return builder.Uri;
 }
        public CSharpCompilation GetCompilation(string assemblyName, IDictionary<string, string> files, out SyntaxTree[] trees)
        {
            var options = new CSharpParseOptions(_languageVersion);
            trees = files.Select(x =>
            {
                var text = x.Value;
                var tree = CSharpSyntaxTree.ParseText(text, options: options);
                if (tree.GetDiagnostics().Any())
                    throw new Exception(string.Format("Syntax error in file \"{0}\".", x.Key));
                return tree;
            }).ToArray();

            // adding everything is going to cause issues with dynamic assemblies
            // so we would want to filter them anyway... but we don't need them really
            //var refs = AssemblyUtility.GetAllReferencedAssemblyLocations().Select(x => new MetadataFileReference(x));
            // though that one is not ok either since we want our own reference
            //var refs = Enumerable.Empty<MetadataReference>();
            // so use the bare minimum
            var asms = ReferencedAssemblies;
            var a1 = typeof(Builder).Assembly;
            asms.Add(a1);
            foreach (var a in GetDeepReferencedAssemblies(a1)) asms.Add(a);
            var refs = asms.Select(x => MetadataReference.CreateFromFile(x.Location));

            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            var compilation = CSharpCompilation.Create(
                assemblyName,
                /*syntaxTrees:*/ trees,
                /*references:*/ refs,
                compilationOptions);

            return compilation;
        }
 static string FormUrlEncode(IDictionary<string, string> data)
 {
     var pairs = data.Select(pair => string.Format("{0}={1}",
         WebUtility.UrlEncode(pair.Key),
         WebUtility.UrlEncode(pair.Value)));
     return string.Join("&", pairs);
 }
        private static string CreateQueryString(
            IDictionary<string, string> clientFilters,
            int page)
        {
            // Go through, replacing the page.number query param's value with
            // the actual page. Preserves other query parameters, since they're
            // still needed to provide the correct pagination links.
            var queries = clientFilters.Select(kv =>
            {
                var key = kv.Key;
                var value = kv.Key == Constants.PageNumberQueryName ? page.ToString() : kv.Value;

                if (string.IsNullOrEmpty(value))
                {
                    return null;
                }

                var parserMatch = queryParser.Match(key);

                if (!parserMatch.Success)
                {
                    return new { Key = key, Value = value };
                }

                var left = parserMatch.Groups["left"].Value;
                var right = parserMatch.Groups["right"].Value;
                return new { Key = left + $"[{right}]", Value = value };
            }).Where(k => k != null).ToList();

            return queries.Any()
                ? "?" + string.Join("&", queries.Select(kv => $"{kv.Key}={kv.Value}"))
                : null;
        }
Esempio n. 10
0
        public static Type CompileDocumentType(Type baseType, IDictionary<string, Type> fields)
        {
            string signature = baseType.FullName + string.Join(";", fields.Select(f => f.ToString()));

            Type type = null;
            lock (_cachedTypes)
            {
                if (_cachedTypes.ContainsKey(signature))
                {
                    type = _cachedTypes[signature];
                }
            }

            if (type == null)
            {
                type = CompileDocumentTypeInternal(baseType, fields);
                lock (_cachedTypes)
                {
                    if (!_cachedTypes.ContainsKey(signature))
                    {
                        _cachedTypes.Add(signature, type);
                    }
                }
            }

            return type;
        }
Esempio n. 11
0
 private static string GetBdmtTitles(IDictionary<Language, string> bdmtTitles)
 {
     return !bdmtTitles.Any()
                ? null
                : string.Join(Environment.NewLine,
                              bdmtTitles.Select(pair => string.Format("{0}: {1}", pair.Key.ISO_639_2, pair.Value)));
 }
Esempio n. 12
0
 public static string ToQueryString(IDictionary<string, string> pairs)
 {
     // http://stackoverflow.com/questions/829080/how-to-build-a-query-string-for-a-url-in-c/829138#829138
     return string.Join("&", pairs.Select(
         (pair) => string.Format("{0}={1}", UrlEncode(pair.Key), UrlEncode(pair.Value))
     ));
 }
Esempio n. 13
0
        private static string CreateQueryString(
            IDictionary<string, string> clientFilters,
            int page)
        {
            // Go through, replacing the page.number query param's value with
            // the actual page. Preserves other query parameters, since they're
            // still needed to provide the correct pagination links.
            var queries = clientFilters.Select(kv =>
            {
                var key = kv.Key;
                var value = kv.Key == Constants.QueryNames.PageNumber ? page.ToString() : kv.Value;

                if (string.IsNullOrEmpty(value))
                {
                    return null;
                }

                if (!key.Contains("."))
                {
                    return new { Key = key, Value = value };
                }

                var left = key.Substring(0, key.IndexOf(".", StringComparison.InvariantCulture));
                var right = key.Substring(left.Length + 1);
                return new { Key = left + $"[{right}]", Value = value };
            }).Where(k => k != null).ToList();

            return queries.Any()
                ? "?" + string.Join("&", queries.Select(kv => $"{kv.Key}={kv.Value}"))
                : null;
        }
Esempio n. 14
0
 private void TestStrings(
     IEnumerable<string> testData,
     IDictionary<string, string> testQueries,
     Func<string, Expression<Func<TestDatabaseExtensions.Simple, bool>>> filterExpressionForTest)
 {
     TestStrings(testData, testQueries.Select(test => Tuple.Create(test.Key, test.Value)).ToList(), filterExpressionForTest);
 }
Esempio n. 15
0
        public static string CreateSign(IDictionary<string, string> parameters, string key, string charset)
        {
            string[] array = parameters.Select(item => string.Format("{0}={1}", item.Key, item.Value)).ToArray();
            string originalstr = string.Concat(string.Join("&", array), key);

            return CryptoUtil.MD5(originalstr, charset);
        }
Esempio n. 16
0
 private static HeaderDetails[] ConvertDictionaryToHeaderDetails(IDictionary<string, object> headers)
 {
     return headers.Select(header => new HeaderDetails
     {
         key = header.Key,
         value = ParseHeaderValue(header.Value)
     }).ToArray();
 }
Esempio n. 17
0
 public IEnumerable<IDataParameter> CreateParameters(IDictionary<string, object> parameters)
 {
     return parameters.Select(parameter => new OleDbParameter
     {
         ParameterName = "?",
         Value = parameter.Value
     });
 }
 public void Save(IDictionary<string, string> data)
 {
     XElement root = new XElement("root",
         data.Select(pair => new XElement("pair",
             new XAttribute("key", pair.Key),
             pair.Value)));
     root.Save(_repositoryFile);
 }
Esempio n. 19
0
 /// <summary>
 /// Transforms GET parameters into a string.
 /// </summary>
 private static string GetParametersString( IDictionary<string, string> parameters )
 {
     if ( parameters == null || parameters.Count == 0 )
     {
         return string.Empty;
     }
     return "?" + string.Join( "&", parameters.Select( p => p.Key + "=" + WebUtility.UrlEncode( p.Value ) ) );
 }
Esempio n. 20
0
 public IEnumerable<IDataParameter> CreateParameters(IDictionary<string, object> parameters)
 {
     return parameters.Select(parameter => new SqlParameter
     {
         ParameterName = string.Format("@{0}", parameter.Key),
         Value = parameter.Value
     });
 }
Esempio n. 21
0
 public string ExpandSuccessUrl(IDictionary<string, string> parameters)
 {
     var sb = new StringBuilder();
     sb.Append(SuccessUrl);
     sb.Append("?");
     sb.Append(string.Join("&", parameters.Select(x => x.Key + "=" + Uri.EscapeDataString(x.Value))));
     return sb.ToString();
 }
		/// <summary>
		/// Converts a dictionary of <string, string> to a URL-encoded string
		/// </summary>
		/// <param name="parameters">Dictionary of <string,string> values</param>
		public static string ConvertDictionaryToQueryString(IDictionary<string, string> parameters) {
			var result = String.Join(
				"&",
				parameters.Select(kvp => String.Format("{0}={1}", WebUtility.UrlEncode(kvp.Key), ((kvp.Value != null) ? WebUtility.UrlEncode(kvp.Value) : "")))
			);

			return result.ToString();
		}
Esempio n. 23
0
        public static TestBlobCache OverrideGlobals(IDictionary<string, object> initialContents, IScheduler scheduler = null)
        {
            var initialSerializedContents = initialContents
            .Select(item => new KeyValuePair<string, byte[]>(item.Key, JsonSerializationMixin.SerializeObject(item.Value)))
            .ToArray();

            return OverrideGlobals(scheduler, initialSerializedContents);
        }
Esempio n. 24
0
        private string Template(object model, IDictionary<string, string> allAtts)
        {
            var atts = allAtts.Select(attr => string.Format("{0}=\"{1}\"", attr.Key, attr.Value)).ToList();

            var attrSb = string.Join(" ", atts);

            return string.Format("<li {0}>{1}</li>", attrSb, Reflector.GetValue(model, _textFieldName));
        }
Esempio n. 25
0
		private static string ApiUrl (string path, IDictionary<string, string> args)
		{
			string queryString;
			if (args == null)
				queryString = "";
			else
				queryString = "?" + String.Join ("&", args.Select (kvp => String.Format ("{0}={1}", kvp.Key, Uri.EscapeUriString (kvp.Value))));
			return String.Format ("https://performancebot.mono-project.com/api{0}{1}", path, queryString);
		}
Esempio n. 26
0
 public LineSeries CreateSeries(String name, IDictionary<Double, Double> data)
 {
     LineSeries ls = new LineSeries(name);
     IList<IDataPoint> points = data.Select(x => ((IDataPoint)new DataPoint(x.Key, x.Value))).ToList();
     ls.Points = points;
     ls.Color = colors.First();
     colors.Remove(ls.Color);
     return ls;
 }
Esempio n. 27
0
 private string GetUpdateClause(string tableName, IDictionary<string, object> data)
 {
     var table = _schema.FindTable(tableName);
     var setClause = string.Join(", ",
         data.Select(
             kvp =>
             string.Format("{0} = {1}", table.FindColumn(kvp.Key).QuotedName, _commandBuilder.AddParameter(kvp.Value))));
     return string.Format("update {0} set {1}", table.QuotedName, setClause);
 }
Esempio n. 28
0
 /// <summary>
 /// Get a single line string to write out to our file for a given metric.
 /// </summary>
 private string MetricToString(IDictionary<string, string> properties, Metric metric)
 {
     return metric.Name + ", " +
         metric.Data + ", " +
         metric.TimeStamp.ToString() + ", " +
         metric.Type + ", " +
         "{" + String.Join("; ", properties
             .Select(property => property.Key + ": " + property.Value)
             .ToArray()) + "}";
 }
 /// <summary>
 /// Renders the attributes.
 /// </summary>
 /// <param name="htmlHelper">The HTML helper.</param>
 /// <param name="attributes">The attributes.</param>
 /// <returns></returns>
 public static MvcHtmlString RenderAttributes(this HtmlHelper htmlHelper, IDictionary<string, string> attributes)
 {
     return MvcHtmlString.Create(
         string.Join(
             " ",
             attributes
                 .Select((key, value) => string.Format("{0}=\"{1}\"", key, value))
                 .ToArray()
         ));
 }
Esempio n. 30
0
        public static void ServiceMessage(this ILog log, string messageName, IDictionary<string, string> values)
        {
            if (!serviceMessagesEnabled)
                return;

            log.InfoFormat(
                "##teamcity[{0} {1}]",
                messageName,
                string.Join(" ", values.Select(v => v.Key + "='" + EscapeValue(v.Value) + "'")));
        }
Esempio n. 31
0
        public static void Dump <TKey, TValue>(this IDictionary <TKey, TValue> o, string name)
        {
            int keyWidth = o.Keys.Max(k => k.ToString().Length);

            Console.WriteLine($"{name}\n{string.Join("\n", o.Select(kv => $"{kv.Key.ToString().PadRight(keyWidth)}: {kv.Value}"))}");
        }
Esempio n. 32
0
        /// <summary>
        /// Creates a new assignment with the given data.
        /// </summary>
        public TestDatabaseBuilder AddAssignment(
            string classroomName,
            string assignmentGroupName,
            string assignmentName,
            IDictionary <string, DateTime> sectionDueDates,
            IDictionary <string, string[]> questionsByCategory,
            bool isPrivate           = false,
            bool combinedSubmissions = false,
            bool answerInOrder       = false)
        {
            var classroom = _buildContext.Classrooms
                            .Include(c => c.Sections)
                            .Single(c => c.Name == classroomName);

            var sections = classroom.Sections
                           .ToDictionary(s => s.Name, s => s.Id);

            var allQuestions = _buildContext.Questions
                               .Include(q => q.QuestionCategory)
                               .ToList()
                               .GroupBy(q => q.QuestionCategory.Name)
                               .ToDictionary(group => group.Key, group => group.ToDictionary(q => q.Name, q => q.Id));

            var assignment = new Assignment()
            {
                ClassroomId         = classroom.Id,
                Name                = assignmentName,
                GroupName           = assignmentGroupName,
                IsPrivate           = isPrivate,
                CombinedSubmissions = combinedSubmissions,
                AnswerInOrder       = answerInOrder,
                DueDates            = sectionDueDates?.Select
                                      (
                    kvp => new AssignmentDueDate()
                {
                    SectionId = sections[kvp.Key],
                    DueDate   = kvp.Value
                }
                                      )?.ToList(),
                Questions = questionsByCategory
                            .SelectMany
                            (
                    qs => qs.Value,
                    (kvp, questionName) => new
                {
                    Category = kvp.Key,
                    Name     = questionName
                }
                            )
                            .Select
                            (
                    (q, index) => new AssignmentQuestion()
                {
                    QuestionId = allQuestions[q.Category][q.Name],
                    Points     = 1.0,
                    Name       = q.Name,
                    Order      = index
                }
                            ).ToList()
            };

            _buildContext.Assignments.Add(assignment);
            _buildContext.SaveChanges();

            return(this);
        }
Esempio n. 33
0
 public IEnumerable <EncryptedMessage> GetAll()
 {
     return(State.Select(m => m.Value));
 }
Esempio n. 34
0
 public HuffmanCoding(IDictionary <int, T> occurenceValueDictionary)
 {
     _occurenceValue = occurenceValueDictionary.Select(item => new HuffmanLeafNode <T>(item.Key, item.Value));
 }
Esempio n. 35
0
 private static string DictionarySegment(IDictionary <string, string[]> values) => ToString(values.Select(x => ToStringSegment(x.Key, x.Value, EnumerableSegment)).ToArray());
Esempio n. 36
0
        public virtual async Task ConfirmProjectsStartedAsync(IDictionary <int, Project> projects, CancellationToken cancellationToken)
        {
            string projectPluralization = projects.Count == 1 ? "project" : "projects";
            string hasPluralization     = projects.Count == 1 ? "has" : "have";

            _console.WriteDefaultLine($"Confirming {projectPluralization} {hasPluralization} started: {string.Join(", ", projects.Select(p => $"{p.Value.Name} ({p.Key})"))}");

            IList <int> activePorts = new List <int>();

            while (projects.Count > activePorts.Count && !cancellationToken.IsCancellationRequested)
            {
                await Task.Delay(200);

                foreach (var port in projects.Keys.Where(k => !activePorts.Contains(k)))
                {
                    if (_networkingService.IsPortListening(port))
                    {
                        activePorts.Add(port);
                    }
                }
            }

            cancellationToken.ThrowIfCancellationRequested();

            _console.WriteSuccessLine("All projects started", ConsoleLineStyle.LineBeforeAndAfter);
        }
Esempio n. 37
0
 public void Table(Context ctx, IDictionary <IntStringKey, PhpValue> dict, string[] header)
 {
     Table(
         dict.Select(pair => new[] { pair.Key.ToString(), Export(ctx, pair.Value) }),
         header);
 }
Esempio n. 38
0
        public async Task <ActionResult> EditProject(int id)
        {
            var projects = await unitOfWork.ProjectRepository.GetByID(id);

            if (projects != null)
            {
                ProjectEntity projectEntity = await unitOfWork.ProjectRepository.GetByID(id);

                IEnumerable <AccountEntity> allAccountEntity = await unitOfWork.AccountRepository.GetAll();

                IEnumerable <TaskEntity> allTaskEntity = await unitOfWork.TaskRepository.GetAll();

                IEnumerable <RoleEntity> roleByProjectEntity = await unitOfWork.RoleRepository.GetAll();

                IEnumerable <Teammate> teammatesInProject = projectEntity.Teammates;

                IList <TaskEntity> tasksInProject = new List <TaskEntity>();
                foreach (var task in allTaskEntity)
                {
                    if (task.ProjectId == projectEntity.ProjectId)
                    {
                        tasksInProject.Add(
                            new TaskEntity
                        {
                            TaskId      = task.TaskId,
                            Title       = task.Title,
                            ProjectId   = task.ProjectId,
                            Description = task.Description
                        });
                    }
                }

                var model = new ManageProjectManagementModel
                {
                    ProjectId   = projectEntity.ProjectId,
                    ProjectName = projectEntity.Name,
                    Description = projectEntity.Description,
                    Task        = allTasks.Select(taskEntity => new TaskEntity
                    {
                        TaskId = taskEntity.Key,
                        Title  = taskEntity.Value,
                    }),
                    TasksInProject = tasksInProject,
                    TeamMember     = teammatesInProject.Select(accountEntity => new AccountEntity
                    {
                        AccountId = accountEntity.AccountId,
                        Name      = accountEntity.Account.Name,
                        Surname   = accountEntity.Account.Surname
                    }),
                    Role = teammatesInProject.Select(roleEntity => new RoleEntity
                    {
                        RoleId = roleEntity.RoleId,
                        Name   = roleEntity.Role.Name,
                    }),
                    TeammatesInProject = teammatesInProject
                };

                return(View("EditProject", model));
            }
            else
            {
                //если это новый ид (добавление нового проекта)
                ProjectEntity projectEntity = await unitOfWork.ProjectRepository.GetByID(id);

                IEnumerable <AccountEntity> allAccountEntity = await unitOfWork.AccountRepository.GetAll();

                IEnumerable <TaskEntity> allTaskEntity = await unitOfWork.TaskRepository.GetAll();

                IEnumerable <RoleEntity> roleByProjectEntity = await unitOfWork.RoleRepository.GetAll();

                var newProjectModel = new ManageProjectManagementModel
                {
                    ProjectId   = id,
                    ProjectName = "",
                    Description = "",
                    Task        = allTasks.Select(taskEntity => new TaskEntity
                    {
                        TaskId = taskEntity.Key,
                        Title  = taskEntity.Value,
                    }),
                    TeamMember = allAccountEntity.Select(accountEntity => new AccountEntity
                    {
                        AccountId = accountEntity.AccountId,
                        Name      = accountEntity.Name,
                        Surname   = accountEntity.Surname
                    }),
                    Role = roleByProjectEntity.Select(roleEntity => new RoleEntity
                    {
                        RoleId = roleEntity.RoleId,
                        Name   = roleEntity.Name,
                    })
                };

                return(View("EditProject", newProjectModel));
            }
        }
Esempio n. 39
0
 private string GetCustomParametersString()
 {
     return(customParameters.Select(x => string.Format("{0}={1}", x.Key, x.Value)).Join("&"));
 }
 private string WithQueryParams(string url, IDictionary <string, string> queryParams)
 => queryParams != null && queryParams.Any()
         ? (url ?? string.Empty) + "?" + string.Join("&", queryParams.Select(kvp => $"{kvp.Key}={kvp.Value}"))
         : url;
Esempio n. 41
0
 private string GetRequestHeadersAsString(IDictionary <string, IEnumerable <string> > headers)
 {
     return(string.Join("&", headers.Select(r => $"{r.Key}={string.Join("; ", r.Value)}")));
 }
Esempio n. 42
0
 private static string CreateQueryString(IDictionary <string, string> queryString)
 {
     return(String.Join("&", queryString.Select(kvp => kvp.Key + "=" + kvp.Value).ToArray()));
 }
Esempio n. 43
0
        public Task HandleEventList(Stream logStream, IDictionary <string, string> eventProperties, CancellationToken cancellationToken)
        {
            eventProperties = eventProperties ?? new Dictionary <string, string>();
            StreamReader reader        = new StreamReader(logStream);
            string       eventMessages = reader.ReadToEnd();

            this.Events.Add(eventMessages);
            return(Task.Run(() => Trace.WriteLine(string.Format("Messages : {0}, Properties: [{1}]", eventMessages, string.Join(";", eventProperties.Select(x => x.Key + "=" + x.Value).ToArray()))), cancellationToken));
        }
Esempio n. 44
0
 public static Assembly SingleAssembly(this IDictionary <string, AssemblyInfo> assemblies)
 {
     return(assemblies?.Select(x => x.Value.Assembly).Single());
 }
 public static string ToDebugString <TKey, TValue>(this IDictionary <TKey, TValue> dictionary)
 {
     return(dictionary == null
         ? string.Empty
         : string.Join("," + Environment.NewLine, dictionary.Select(kv => kv.Key + " = " + kv.Value)));
 }
 /// <summary>
 /// 创建 CacheToken
 /// </summary>
 /// <param name="typeName">类型名,一般可以取 Action 的名称</param>
 /// <param name="parameters">参数列表,一般可以使用 Action 的参数列表</param>
 /// <returns>针对指定类型和参数的 CacheToken</returns>
 public static CacheToken CreateToken(string typeName, IDictionary <string, object> parameters)
 {
     return(CacheToken.CreateToken(typeName, parameters.Select(pair => pair.Key + ":" + pair.Value).ToArray()));
 }
Esempio n. 47
0
 /// <summary>
 /// Returns an enumerator that iterates through the collection.
 /// </summary>
 /// <returns>
 /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
 /// </returns>
 /// <filterpriority>1</filterpriority>
 public IEnumerator <TestTarget> GetEnumerator() =>
 targets.Select(c => c.Value.Value).GetEnumerator();
Esempio n. 48
0
 private void DumpMap <K, V>(string caption, IDictionary <K, V> items, StringWriter sw)
 {
     sw.Write("    {0}", caption);
     sw.WriteLine(string.Join(" ", items.Select(e => string.Format("{0}:{1}", e.Key, e.Value)).OrderBy(e => e)));
 }
 public Task <IEnumerable <Member> > ReadAllAsync()
 {
     return(Task.FromResult(Members.Select(x => x.Value)));
 }
Esempio n. 50
0
 /// <summary>创建参数数组</summary>
 /// <param name="ps"></param>
 /// <returns></returns>
 public virtual IDataParameter[] CreateParameters(IDictionary <String, Object> ps) => ps?.Select(e => CreateParameter(e.Key, e.Value)).ToArray();
Esempio n. 51
0
 public IEnumerator <KeyValuePair <TIndex, TData> > GetEnumerator() =>
 _savedItems.Select(kv => new KeyValuePair <TIndex, TData>(kv.Key.FromJson <TIndex>(), kv.Value.FromJson <TData>())).GetEnumerator();
Esempio n. 52
0
        static void Main(string[] args)
        {
            try
            {
                if (args != null && args.Length > 0)
                {
                    _cmdArgs = string.Join(" ", args);
                }

                GameserverSDK.Start(true);
                GameserverSDK.RegisterShutdownCallback(OnShutdown);
                GameserverSDK.RegisterHealthCallback(GetGameHealth);
                GameserverSDK.RegisterMaintenanceCallback(OnMaintenanceScheduled);

                IDictionary <string, string> gsdkConfiguration = GameserverSDK.getConfigSettings();
                if (gsdkConfiguration.TryGetValue("RealPort", out string listeningPortString))
                {
                    _listeningPort = int.Parse(listeningPortString);
                }

                string address = $"http://*:{_listeningPort}/";
                _listener.Prefixes.Add(address);
                _listener.Start();

                string applicationDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                if (File.Exists(Path.Combine(applicationDirectory, AssetFilePath)))
                {
                    _assetFileText = File.ReadAllText(Path.Combine(applicationDirectory, AssetFilePath));
                }

                // See if we have a configured timeout in the App.config, this was
                // used in our initial round of stress tests to make sure sessions ended
                string timeoutstr = ConfigurationManager.AppSettings.Get(SessionTimeoutInSecondsName);
                if (!string.IsNullOrEmpty(timeoutstr))
                {
                    // failure to convert is intentionally unhandled
                    long timeoutint = Convert.ToInt64(timeoutstr.Trim());

                    _sessionTimeoutTimestamp = DateTimeOffset.Now.AddSeconds(timeoutint);
                }

                IDictionary <string, string> initialConfig = GameserverSDK.getConfigSettings();
                if (initialConfig?.ContainsKey("winRunnerTestCert") == true)
                {
                    string    expectedThumbprint = initialConfig["winRunnerTestCert"];
                    X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                    store.Open(OpenFlags.ReadOnly);
                    X509Certificate2Collection certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, expectedThumbprint, false);

                    if (certificateCollection.Count > 0)
                    {
                        _installedCertThumbprint = certificateCollection[0].Thumbprint;
                    }
                    else
                    {
                        LogMessage("Could not find installed game cert in LocalMachine\\My. Expected thumbprint is: " + expectedThumbprint);
                    }
                }
                else
                {
                    LogMessage("Config did not contain cert! Config is: " + string.Join(";", initialConfig.Select(x => x.Key + "=" + x.Value)));
                }

                Thread t = new Thread(ProcessRequests);
                t.Start();


                string titleId = initialConfig[GameserverSDK.TitleIdKey];
                string buildId = initialConfig[GameserverSDK.BuildIdKey];
                string region  = initialConfig[GameserverSDK.RegionKey];

                LogMessage($"Processing requests for title:{titleId} build:{buildId} in region {region}");

                GameserverSDK.ReadyForPlayers();
                _isActivated = true;

                initialConfig = GameserverSDK.getConfigSettings();

                LogMessage("Config Settings");
                foreach (KeyValuePair <string, string> configTuple in initialConfig)
                {
                    LogMessage($"\t{configTuple.Key}={configTuple.Value}");
                }

                SessionCookie sessionCookie = new SessionCookie();

                if (initialConfig.TryGetValue(GameserverSDK.SessionCookieKey, out string sessionCookieStr))
                {
                    try
                    {
                        if (sessionCookieStr.StartsWith(TimeoutSessionCookiePrefix,
                                                        StringComparison.InvariantCultureIgnoreCase))
                        {
                            if (long.TryParse(sessionCookieStr.Substring(TimeoutSessionCookiePrefix.Length),
                                              out long timeoutSecs))
                            {
                                sessionCookie.TimeoutSecs = timeoutSecs;
                            }
                        }
                        else
                        {
                            sessionCookie = JsonConvert.DeserializeObject <SessionCookie>(sessionCookieStr);
                        }
                    }
                    catch (Exception e)
                    {
                        LogMessage(e.ToString());
                    }
                }

                // If a secret key was specified
                // try to get the title data for this title
                string secretKey = ConfigurationManager.AppSettings.Get(DeveloperSecretKeyName);
                if (!string.IsNullOrWhiteSpace(secretKey))
                {
                    LogMessage("Getting title data");
                    GetTitleData(titleId, secretKey).Wait();
                }
                else
                {
                    LogMessage("Secret Key not specified in app.config. Skipping retrieval of title config");
                }

                // If the session cookie contained a timeout. Shutdown at this time.
                // this overrides whatever may have been set in the App config above
                // We use it for stress testing to make sessions end at random times.
                EnforceTimeout(sessionCookie);
            }
            catch (Exception e)
            {
                LogMessage(e.Message);
                throw;
            }
        }
Esempio n. 53
0
 public IEnumerable <KeyValuePair <string, ID> > AsEnumerable()
 {
     return(List.Select(x => x));
 }
Esempio n. 54
0
 internal string ToSerializedString()
 {
     return(string.Join(new string(PairSeparator, 1), _fields.Select(x => string.Join(new string(KeyValueSeparator, 1), new[] { x.Key, x.Value })).ToArray()));
 }
Esempio n. 55
0
 public IList <IData> GetVariables()
 {
     return(_variables
            .Select(kvp => kvp.Value)
            .ToList());
 }
 public T Get <T>(IDictionary <string, object> parameters) => parameters == null
     ? this.kernel.Get <T>()
     : this.kernel.Get <T>(parameters.Select(IocHelpers.MapParameter).ToArray());
Esempio n. 57
0
 private Task LogTrace(string eventName, string eventMessage, IDictionary <string, string> eventProperties, CancellationToken cancellationToken, string logLevel)
 {
     this.Events.Add(eventName);
     eventProperties = eventProperties ?? new Dictionary <string, string>();
     return(Task.Run(() => Trace.WriteLine(string.Format("{3} {0} : {1} [{2}]", eventName, eventMessage, string.Join(";", eventProperties.Select(x => x.Key + "=" + x.Value).ToArray()), logLevel)), cancellationToken));
 }
 public object Get(Type type, IDictionary <string, object> parameters) => parameters == null
     ? this.kernel.Get(type)
     : this.kernel.Get(type, parameters.Select(IocHelpers.MapParameter).ToArray());
 public IEnumerator <T> GetEnumerator()
 {
     return(Dictionary.Select(GetItem).GetEnumerator());
 }
 public static string JoinAsString <TKey, TValue>(this IDictionary <TKey, TValue> This, string prefix = "", string separator = ": ", string suffix = "\r\n") =>
 This
 .Select(x => $"{prefix}{x.Key}{separator}{x.Value}{suffix}")
 .JoinAsString();