public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
        {
            var action = base.SelectAction(odataPath, controllerContext, actionMap);
            if (action != null)
            {
                var routeValues = controllerContext.RouteData.Values;
                if (routeValues.ContainsKey(ODataRouteConstants.Key))
                {
                    var keyRaw = routeValues[ODataRouteConstants.Key] as string;
                    IEnumerable<string> compoundKeyPairs = keyRaw.Split(',');
                    if (compoundKeyPairs == null || !compoundKeyPairs.Any())
                    {
                        return action;
                    }

                    foreach (var compoundKeyPair in compoundKeyPairs)
                    {
                        string[] pair = compoundKeyPair.Split('=');
                        if (pair == null || pair.Length != 2)
                        {
                            continue;
                        }
                        var keyName = pair[0].Trim();
                        var keyValue = pair[1].Trim();

                        routeValues.Add(keyName, keyValue);
                    }
                }
            }

            return action;
        }
Example #2
0
 public DirectoryCache(BuildContext context, string directory)
 {
     this.context = context;
     files = Directory.EnumerateFiles(directory, "*.*", SearchOption.AllDirectories)
         .Select(f => f.Remove(0, directory.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar))
         .ToLookup(f => Path.GetFileName(f), StringComparer.CurrentCultureIgnoreCase);
 }
Example #3
0
        public void LoadEntries(DataFile file, IndexEntry indexEntry)
        {
            var list = new List<RootEntry>();
            var blteEntry = new BinaryReader(DataFile.LoadBLTEEntry(indexEntry, file.readStream));

            while (blteEntry.BaseStream.Position < blteEntry.BaseStream.Length)
            {
                var entries = new RootEntry[blteEntry.ReadInt32()];

                blteEntry.BaseStream.Position += 4;

                var locales = (Locales)blteEntry.ReadUInt32();

                blteEntry.BaseStream.Position += (entries.Length << 2);

                for (var i = 0; i < entries.Length; i++)
                {
                    list.Add(new RootEntry
                    {
                        MD5 = blteEntry.ReadBytes(16),
                        Hash = blteEntry.ReadUInt64(),
                        Locales = locales
                    });
                }
            }

            entries = list.ToLookup(re => re.Hash);
        }
        /// <summary>
        /// Selects the action for OData requests.
        /// </summary>
        /// <param name="odataPath">The OData path.</param>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="actionMap">The action map.</param>
        /// <returns>
        ///   <c>null</c> if the request isn't handled by this convention; otherwise, the name of the selected action
        /// </returns>
        public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
        {
            if (odataPath == null)
            {
                throw Error.ArgumentNull("odataPath");
            }

            if (controllerContext == null)
            {
                throw Error.ArgumentNull("controllerContext");
            }

            if (actionMap == null)
            {
                throw Error.ArgumentNull("actionMap");
            }

            if (odataPath.PathTemplate == "~/entityset/key" ||
                odataPath.PathTemplate == "~/entityset/key/cast")
            {
                HttpMethod httpMethod = controllerContext.Request.Method;
                string httpMethodName;

                switch (httpMethod.ToString().ToUpperInvariant())
                {
                    case "GET":
                        httpMethodName = "Get";
                        break;
                    case "PUT":
                        httpMethodName = "Put";
                        break;
                    case "PATCH":
                    case "MERGE":
                        httpMethodName = "Patch";
                        break;
                    case "DELETE":
                        httpMethodName = "Delete";
                        break;
                    default:
                        return null;
                }

                Contract.Assert(httpMethodName != null);

                IEdmEntityType entityType = odataPath.EdmType as IEdmEntityType;

                // e.g. Try GetCustomer first, then fallback on Get action name
                string actionName = actionMap.FindMatchingAction(
                    httpMethodName + entityType.Name,
                    httpMethodName);

                if (actionName != null)
                {
                    KeyValuePathSegment keyValueSegment = odataPath.Segments[1] as KeyValuePathSegment;
                    controllerContext.RouteData.Values[ODataRouteConstants.Key] = keyValueSegment.Value;
                    return actionName;
                }
            }
            return null;
        }
        /// <summary>
        /// Selects the action for OData requests.
        /// </summary>
        /// <param name="odataPath">The OData path.</param>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="actionMap">The action map.</param>
        /// <returns>
        ///   <c>null</c> if the request isn't handled by this convention; otherwise, the name of the selected action
        /// </returns>
        public string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
        {
            if (odataPath == null)
            {
                throw Error.ArgumentNull("odataPath");
            }

            if (controllerContext == null)
            {
                throw Error.ArgumentNull("controllerContext");
            }

            if (actionMap == null)
            {
                throw Error.ArgumentNull("actionMap");
            }

            if (odataPath.PathTemplate == "~")
            {
                return "GetServiceDocument";
            }

            if (odataPath.PathTemplate == "~/$metadata")
            {
                return "GetMetadata";
            }

            return null;
        }
        public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
        {
            var controllerType = controllerContext.ControllerDescriptor.ControllerType;

            if (typeof(CustomersController) == controllerType)
            {
                if (odataPath.PathTemplate.Equals("~/entityset/key/navigation")) //POST OR GET
                {
                    controllerContext.RouteData.Values["orderID"] = ((KeySegment)odataPath.Segments[1]).Keys.Single().Value;
                    return controllerContext.Request.Method.ToString();
                }
            }
            else if (typeof(OrdersController) == controllerType)
            {
                if (odataPath.PathTemplate.Equals("~/entityset/key/navigation")) //POST OR GET
                {
                    controllerContext.RouteData.Values["customerID"] = ((KeySegment)odataPath.Segments[1]).Keys.Single().Value;
                    return controllerContext.Request.Method.ToString();
                }
                if (odataPath.PathTemplate.Equals("~/entityset/key/navigation/key")) //PATCH OR DELETE
                {
                    controllerContext.RouteData.Values["customerID"] = ((KeySegment)odataPath.Segments[1]).Keys.Single().Value;

                    controllerContext.RouteData.Values["key"] = ((KeySegment)odataPath.Segments[3]).Keys.Single().Value;
                    return controllerContext.Request.Method.ToString();
                }
            }

            return base.SelectAction(odataPath, controllerContext, actionMap);
        }
    private static ExplorerItem GetChildItem(ILookup<Type, ExplorerItem> elementTypeLookup, PropertyInfo childProp) {
      // If the property's type is in our list of entities, then it's a Many:1 (or 1:1) reference.
      // We'll assume it's a Many:1 (we can't reliably identify 1:1s purely from reflection).
      if (elementTypeLookup.Contains(childProp.PropertyType))
        return new ExplorerItem(childProp.Name, ExplorerItemKind.ReferenceLink, ExplorerIcon.ManyToOne) {
          HyperlinkTarget = elementTypeLookup[childProp.PropertyType].First(),
          // FormatTypeName is a helper method that returns a nicely formatted type name.
          ToolTipText = DataContextDriver.FormatTypeName(childProp.PropertyType, true)
        };

      // Is the property's type a collection of entities?
      Type ienumerableOfT = childProp.PropertyType.GetInterface("System.Collections.Generic.IEnumerable`1");
      if (ienumerableOfT != null) {
        Type elementType = ienumerableOfT.GetGenericArguments()[0];
        if (elementTypeLookup.Contains(elementType))
          return new ExplorerItem(childProp.Name, ExplorerItemKind.CollectionLink, ExplorerIcon.OneToMany) {
            HyperlinkTarget = elementTypeLookup[elementType].First(),
            ToolTipText = DataContextDriver.FormatTypeName(elementType, true)
          };
      }

      // Ordinary property:
      var isKey = childProp.GetCustomAttributes(false).Any(a => a.GetType().Name == "KeyAttribute");
      return new ExplorerItem(childProp.Name + " (" + DataContextDriver.FormatTypeName(childProp.PropertyType, false) + ")",
        ExplorerItemKind.Property, isKey ? ExplorerIcon.Key : ExplorerIcon.Column) { DragText = childProp.Name };
    }
        /// <summary>
        /// Selects the appropriate action based on the parsed OData URI.
        /// </summary>
        /// <param name="odataPath">Parsed OData URI</param>
        /// <param name="controllerContext">Context for HttpController</param>
        /// <param name="actionMap">Mapping from action names to HttpActions</param>
        /// <returns>String corresponding to controller action name</returns>
        public string SelectAction(
            ODataPath odataPath,
            HttpControllerContext controllerContext,
            ILookup<string, HttpActionDescriptor> actionMap)
        {
            // TODO GitHubIssue#44 : implement action selection for $ref, navigation scenarios, etc.
            Ensure.NotNull(odataPath, "odataPath");
            Ensure.NotNull(controllerContext, "controllerContext");
            Ensure.NotNull(actionMap, "actionMap");

            if (!(controllerContext.Controller is RestierController))
            {
                // RESTier cannot select action on controller which is not RestierController.
                return null;
            }

            HttpMethod method = controllerContext.Request.Method;

            if (method == HttpMethod.Get && !IsMetadataPath(odataPath))
            {
                return MethodNameOfGet;
            }

            ODataPathSegment lastSegment = odataPath.Segments.LastOrDefault();
            if (lastSegment != null && lastSegment.SegmentKind == ODataSegmentKinds.UnboundAction)
            {
                return MethodNameOfPostAction;
            }

            // Let WebAPI select default action
            return null;
        }
        protected virtual void AddDescendantNodes(
            ISiteMap siteMap,
            ISiteMapNode currentNode,
            IList<ISiteMapNodeToParentRelation> sourceNodes,
            ILookup<string, ISiteMapNodeToParentRelation> sourceNodesByParent,
            HashSet<string> nodesAlreadyAdded)
        {
            if (sourceNodes.Count == 0)
            {
                return;
            }

            var children = sourceNodesByParent[currentNode.Key].OrderBy(x => x.Node.Order).ToArray();
            if (children.Count() == 0)
            {
                return;
            }

            foreach (var child in children)
            {
                if (sourceNodes.Count == 0)
                {
                    return;
                }

                this.AddAndTrackNode(siteMap, child, currentNode, sourceNodes, nodesAlreadyAdded);

                if (sourceNodes.Count == 0)
                {
                    return;
                }

                this.AddDescendantNodes(siteMap, child.Node, sourceNodes, sourceNodesByParent, nodesAlreadyAdded);
            }
        }
            public ViewComponentDescriptorCache(ViewComponentDescriptorCollection collection)
            {
                Version = collection.Version;

                _lookupByShortName = collection.Items.ToLookup(c => c.ShortName, c => c);
                _lookupByFullName = collection.Items.ToLookup(c => c.FullName, c => c);
            }
            private static ViewComponentDescriptor Select(
                ILookup<string, ViewComponentDescriptor> candidates,
                string name)
            {
                var matches = candidates[name];

                var count = matches.Count();
                if (count == 0)
                {
                    return null;
                }
                else if (count == 1)
                {
                    return matches.Single();
                }
                else
                {
                    var matchedTypes = new List<string>();
                    foreach (var candidate in matches)
                    {
                        matchedTypes.Add(Resources.FormatViewComponent_AmbiguousTypeMatch_Item(
                            candidate.Type.FullName,
                            candidate.FullName));
                    }

                    var typeNames = string.Join(Environment.NewLine, matchedTypes);
                    throw new InvalidOperationException(
                        Resources.FormatViewComponent_AmbiguousTypeMatch(name, Environment.NewLine, typeNames));
                }
            }
 //计算各URI通过网关的成功率和时延,也可以指定uri
 public void getPostAndGetGateWay(Itemset hs, ILookup<string, string> m_dicTransactions)
 {
     var gn = from p in sqlserver_gn_table
              where p.Event_Type == 4
              where p.SynDirection == 0
              //where p.my_URI_Main=="qq.com" || p.my_URI_Main==string.Empty
              //group p by new { ABC = p.DEST_IP == 2885681162 } into ttt
              //group p by p.my_DEST_IP into ttt
              //where detail == true ? p.my_URI_Main == "10086.cn" : p.my_URI_Main != null
              where hs.Contains(p.Prefix_IMEI)
              group p by p.Prefix_IMEI into ttt
              select new
              {
                  //abc = ttt.Key.ABC.ToString(),
                  abc = ttt.Key.ToString(),
                  type = m_dicTransactions[ttt.Key.ToString()].Where(e => e.IndexOf("iphone") != -1|e.IndexOf("iPhone") != -1).FirstOrDefault(),
                  cnt = ttt.Count(),
                  suc = ttt.Where(e => e.Resp != null).Count(),
                  percent = 1.0 * ttt.Where(e => e.Resp != null).Count() / ttt.Count(),
                  uri_size = ttt.Average(e => e.my_URI_Len),
                  size = ttt.Average(e => e.IP_LEN_DL),  //这里只去下行
                  rate = ttt.Average(e => e.Duration) == null ? 0 :
                  1.0 * ttt.Average(e => e.IP_LEN_DL) / ttt.Average(e => (double)e.Duration),
                  delay = ttt.Average(e => e.Duration)  //这里不取第1个包
              };
     MicroObjectDumper.Write(gn.OrderByDescending(e => e.cnt));
 }
        static TDCacheService()
        {
            // this data is fetchable via http://nrodwiki.rockshore.net/index.php/ReferenceData

            List<TDElement> allSmartData = new List<TDElement>();

            foreach (string smartExtract in Directory.GetFiles("..\\", "SMARTExtract*.json"))
            {
                Trace.TraceInformation("Loading SMART data from {0}", smartExtract);
                string smartData = File.ReadAllText(smartExtract);
                allSmartData.AddRange(JsonConvert.DeserializeObject<TDContainer>(smartData).BERTHDATA);
            }
            _tdElementsByArea = allSmartData
                .Where(td => !string.IsNullOrEmpty(td.STANOX))
                .ToLookup(td => td.TD);

            var dbTiplocs = _tiplocRepo.Get();

            string tiplocData = File.ReadAllText("..\\CORPUSExtract.json");
            _tiplocByStanox = JsonConvert.DeserializeObject<TiplocContainer>(tiplocData).TIPLOCDATA
                .Select(t => t.ToTiplocCode())
                .ToLookup(t => t.Stanox);

            _missedEntryTimer.Elapsed += _missedEntryTimer_Elapsed;
            _missedEntryTimer.Start();
        }
Example #14
0
        public ContentTypeDetector(IEnumerable<ContentType> contentTypes)
        {
            if (null == contentTypes)
                throw new ArgumentNullException(nameof(contentTypes));

            ContentTypes = contentTypes.ToArray();

            ExtensionLookup = ContentTypes
                .SelectMany(ct => ct.FileExts, (ct, ext) => new
                {
                    ext,
                    ContentType = ct
                })
                .ToLookup(arg => arg.ext, x => x.ContentType, StringComparer.OrdinalIgnoreCase);

            var mimeTypes = ContentTypes
                .Select(ct => new
                {
                    ct.MimeType,
                    ContentType = ct
                });

            var alternateMimeTypes = ContentTypes
                .Where(ct => null != ct.AlternateMimeTypes)
                .SelectMany(ct => ct.AlternateMimeTypes, (ct, mime) => new
                {
                    MimeType = mime,
                    ContentType = ct
                });

            MimeLookup = alternateMimeTypes
                .Union(mimeTypes)
                .ToLookup(arg => arg.MimeType, x => x.ContentType, StringComparer.OrdinalIgnoreCase);
        }
Example #15
0
        RuleIndex(string fileName, XDocument document, ProgressDialog dialog)
        {
            this.name = fileName;
            if (dialog != null) { dialog.SetDescription("Building elements..."); }

            int max = document.Root.Elements().Count();
            int current = 0;

            foreach (XElement element in document.Root.Elements())
            {
                if (dialog != null) { dialog.SetProgress(current++, max); }
                RuleElement re = new RuleElement(element);
                this.elements.Add(re.Id, re);
            }

            current = 0;
            if (dialog != null) { dialog.SetDescription("Binding categories..."); }
            foreach (RuleElement element in this.elements.Values)
            {
                if (dialog != null) { dialog.SetProgress(current++, this.elements.Count); }
                element.BindCategories(this);
            }

            current = 0;
            if (dialog != null) { dialog.SetDescription("Binding rules..."); }
            foreach (RuleElement element in this.elements.Values)
            {
                if (dialog != null) { dialog.SetProgress(current++, this.elements.Count); }
                element.BindRules(this);
            }

            if (dialog != null) { dialog.SetDescription("Reticulating splines..."); }
            this.elementsByName = this.elements.Values.ToLookup(e => e.Name);
            this.elementsByFullName = this.elements.Values.ToLookup(e => e.FullName);
        }
Example #16
0
        public override string SelectAction(ODataPath odataPath, HttpControllerContext context,
            ILookup<string, HttpActionDescriptor> actionMap)
        {
            if (context.Request.Method == HttpMethod.Get &&
                odataPath.PathTemplate == "~/entityset/key/navigation/key")
            {
                NavigationPathSegment navigationSegment = odataPath.Segments[2] as NavigationPathSegment;
                IEdmNavigationProperty navigationProperty = navigationSegment.NavigationProperty.Partner;
                IEdmEntityType declaringType = navigationProperty.DeclaringType as IEdmEntityType;

                string actionName = "Get" + declaringType.Name;
                if (actionMap.Contains(actionName))
                {
                    // Add keys to route data, so they will bind to action parameters.
                    KeyValuePathSegment keyValueSegment = odataPath.Segments[1] as KeyValuePathSegment;
                    context.RouteData.Values[ODataRouteConstants.Key] = keyValueSegment.Value;

                    KeyValuePathSegment relatedKeySegment = odataPath.Segments[3] as KeyValuePathSegment;
                    context.RouteData.Values[ODataRouteConstants.RelatedKey] = relatedKeySegment.Value;

                    return actionName;
                }
            }
            // Not a match.
            return null;
        }
Example #17
0
 public void InitCaches()
 {
     var db = new FacesDBDataContext(_connectionString);
     _faceUKeyLookup = db.Faces.ToDictionary(x => x.FaceUKey, x => (api.Face) new FaceImpl(x, _m, null));
     var query =  (from f in db.Faces join p in db.Persons on f.PersonID equals p.PersonID select new { f, p });
     _Faces = new Dictionary<api.Face,api.Person>();
     Dictionary<int, api.Person> persons = new Dictionary<int,api.Person>();
     foreach (var x in query) {
         // todo; build pers dic at same time...
         api.Person person = null;
         if (!persons.TryGetValue(x.p.PersonID, out person))
         {
             person = (api.Person)new PersonImpl(x.p.FirstName, x.p.LastName, x.p.PersonID);
             persons.Add(person.Id, person);
         }
         api.Face thisFace = _faceUKeyLookup[x.f.FaceUKey];
         thisFace.Person = person;
         _Faces.Add(thisFace, person);
     }
     _Persons = _Faces.GroupBy(x => x.Value).ToDictionary(x => x.Key, x => x.Select(y=>y.Key).ToList());
     _allPersonsLookup = persons;
     foreach (var pers in db.Persons) // add in other persons that don't have faces.
     {
         if (!_allPersonsLookup.ContainsKey(pers.PersonID))
             _allPersonsLookup.Add(pers.PersonID, (api.Person)new PersonImpl(pers.FirstName, pers.LastName, pers.PersonID));
     }
     _PicturesToFaces = db.Faces
         .ToLookup(x => x.PictureID, x => _faceUKeyLookup[x.FaceUKey]);
 }
Example #18
0
        public MenuService([NotNull] IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
                throw new ArgumentNullException("serviceProvider");

            var menuProviders = new ExtensionsCache<MenuProviderInfo, IMenuProvider>(serviceProvider);

            _menuProvidersLookup =
                menuProviders
                    .GetAllExtensions()
                    .ToLookup(
                        menuProvider => menuProvider.MenuName,
                        StringComparer.OrdinalIgnoreCase);

            // WTF?
            menuProviders
                .GetAllExtensions()
                .OfType<IDynamicMenuProvider>()
                .Select(
                    dynamicMenuProvider =>
                    {
                        _menuCache.Drop(dynamicMenuProvider.MenuName);
                        return
                            dynamicMenuProvider.MenuChanged.Subscribe(
                                arg => _menuChanged.OnNext(dynamicMenuProvider.MenuName));
                    });

            _menuCache = new ElementsCache<string, IMenuRoot>(CreateMenu);
        }
 void AssertDescriptorMatches(ILookup<string, SecurityAttributeDescriptor> descriptors, string signature, ICustomAttributeProvider element)
 {
     if (descriptors.Contains(signature))
         AssertContainsAttribute(element, descriptors[signature].Single().AttributeTypeName);
     else
         AssertContainsNoAttribute(element);
 }
Example #20
0
 public CommitDiffModel(string[] lines, IEnumerable<CommitCommentModel> comments, int fontSize)
 {
     Lines = lines;
     FontSize = fontSize;
     Comments = comments.ToList();
     CommentsLookup = Comments.ToLookup(x => x.Line);
 }
Example #21
0
 /// <summary>
 /// Clears the cache.
 /// </summary>
 public void Clear()
 {
     Root = null;
     _groups = null;
     _entries = null;
     Database = null;
 }
Example #22
0
        /// <summary>
        /// Where Tuple<int,int> represents a child_id|parent_id relationship
        /// </summary>
        /// <param name="relations"></param>
        public Hierarchy(List<Relation> relations)
        {
            if (relations == null)
                relations = new List<Relation>();

            for (int i = 0; i < relations.Count; i++)
            {
                var item = relations[i];

                if (item.Child == item.Parent)
                    continue;

                // the child is a relation of itself; the parent is a relation of itself, too
                this.Add(relations, new Relation { Child = item.Child, Parent = item.Child });
                this.Add(relations, new Relation{ Child = item.Parent, Parent = item.Parent});

                // if this 'parent' is the child of another item G, then this 'child' is also a child of G.
                var grandparents = relations.Where(r => item.Parent == r.Child);
                var grandchildren = relations.Where(r => r.Parent == item.Child).Select(r => r.Child);
                var list = grandparents.Select(g => new Relation { Child = g.Child, Parent = item.Parent }).ToList();
                foreach (var g in list)
                    this.Add(relations, g);
            }

            //parents = relations.GroupBy(i => i.Item1, i => i.Item2).ToLookup(g => g.Key, g => g.ToList());
            parents = relations.ToLookup(i => i.Child, i => i.Parent);
            children = relations.ToLookup(i => i.Parent, i => i.Child);

            this.relationHash = new HashSet<int>(relations.Select(r => r.GetHashCode()));
        }
 public string SelectAction(
     ODataPath odataPath,
     HttpControllerContext controllerContext,
     ILookup<string, HttpActionDescriptor> actionMap)
 {
     return null;
 }
Example #24
0
		public MenuService([NotNull] IServiceProvider serviceProvider)
		{
			if (serviceProvider == null)
				throw new ArgumentNullException(nameof(serviceProvider));

			var menuProviders = new ExtensionsCache<MenuProviderInfo, IMenuProvider>(serviceProvider);

			_menuProvidersLookup =
				menuProviders
					.GetAllExtensions()
					.ToLookup(
						menuProvider => menuProvider.MenuName,
						StringComparer.OrdinalIgnoreCase);

			// WTF?
			//menuProviders
			//	.GetAllExtensions()
			//	.OfType<IDynamicMenuProvider>()
			//	.Select(
			//		dynamicMenuProvider =>
			//		{
			//			_menuCache.Drop(dynamicMenuProvider.MenuName);
			//			return 
			//				dynamicMenuProvider.MenuChanged.Subscribe(
			//					arg => _menuChanged.OnNext(dynamicMenuProvider.MenuName));
			//		});

			_menuCache = LazyDictionary.Create<string, IMenuRoot>(CreateMenu, false);
		}
            private static WidgetDescriptor Select(ILookup<string, WidgetDescriptor> candidates, string name)
            {
                var matches = candidates[name];

                var count = matches.Count();
                if (count == 0)
                {
                    return null;
                }
                else if (count == 1)
                {
                    return matches.Single();
                }
                else
                {
                    var matchedTypes = new List<string>();
                    foreach (var candidate in matches)
                    {
                        matchedTypes.Add($"Type: {candidate.Type.FullName}, Name: {candidate.FullName}");
                    }

                    var typeNames = string.Join(Environment.NewLine, matchedTypes);
                    throw new InvalidOperationException($"The widget name matched multiple types:{Environment.NewLine}{typeNames}");
                }
            }
Example #26
0
        public static bool ShouldReplicateBlob(ILookup<string, string> headers, string container, string blob)
        {
            bool retval = false;
            if (DashConfiguration.IsBlobReplicationEnabled)
            {
                bool evaluated = false;
                string replicaMetadata = DashConfiguration.ReplicationMetadataName;
                if (headers != null && !String.IsNullOrWhiteSpace(replicaMetadata))
                {
                    string replicateHeader = "x-ms-meta-" + replicaMetadata;
                    if (headers.Contains(replicateHeader))
                    {
                        retval = String.Equals(DashConfiguration.ReplicationMetadataValue, headers[replicateHeader].First(), StringComparison.OrdinalIgnoreCase);
                        evaluated = true;
                    }
                }
                if (!evaluated)
                {
                    if (_replicationPathExpression != null)
                    {
                        retval = _replicationPathExpression.IsMatch(PathUtils.CombineContainerAndBlob(container, blob));
                    }
                }

            }
            return retval;
        }
        private void OnSerialize(StreamingContext context)
        {
            RepopulateHyperMedia();

            if (ResourceConverter.IsResourceConverterContext(context))
            {
                // put all embedded resources and lists of resources into Embedded for the _embedded serializer
                var resourceList = new List<IResource>();
                foreach (var prop in GetType().GetProperties().Where(p => IsEmbeddedResourceType(p.PropertyType)))
                {
                    var val = prop.GetValue(this, null);
                    if (val != null)
                    {
                        // remember embedded resource property for restoring after serialization
                        embeddedResourceProperties.Add(prop, val);
                        // add embedded resource to collection for the serializtion
                        var res = val as IResource;
                        if (res != null)
                            resourceList.Add(res);
                        else
                            resourceList.AddRange((IEnumerable<IResource>) val);
                        // null out the embedded property so it doesn't serialize separately as a property
                        prop.SetValue(this, null, null);
                    }
                }
                foreach (var res in resourceList.Where(r => string.IsNullOrEmpty(r.Rel)))
                    res.Rel = "unknownRel-" + res.GetType().Name;
                Embedded = resourceList.Count > 0 ? resourceList.ToLookup(r => r.Rel) : null;
            }
        }
 public ValidatingEventListener()
 {
     lookup = typeof (ValidatingEventListener)
         .Assembly.GetTypes()
         .Where(x => !x.IsAbstract && typeof(IValidateBusinessRules).IsAssignableFrom(x))
         .Select(x=>(IValidateBusinessRules)Activator.CreateInstance(x))
         .ToLookup(x => x.ForType);
 }
Example #29
0
 public Expression Rewrite(Expression expression)
 {
     _lookup = new AggregateGatherer().Gather(expression).ToLookup(x => x.GroupByAlias);
     return(Visit(expression));
 }
Example #30
0
 public void Clear()
 {
     _searchPaths.Clear();
     _projects = null;
 }
Example #31
0
 public void Setup()
 {
     Rankings            = MajesticMillionHelper.LoadSiteRankings();
     Table               = new SiteRankingTable(Rankings);
     LookupRankingsByTLD = Rankings.ToLookup(r => r.TopLevelDomain, StringComparer.OrdinalIgnoreCase);
 }
Example #32
0
        private static FileReference MatchInBitTorrentFiles(Dictionary <string, FileReference> bittorrentFiles, FileReference dropboxFile, ILookup <string, FileReference> bittorrentFilesByName)
        {
            var path = dropboxFile.path.Replace("./SourceName/", "./TargetName/").Replace("./SourceName2/", "./TargetName2/").ToLower();

            FileReference matchingBittorrentFile;

            if (bittorrentFiles.TryGetValue(path, out matchingBittorrentFile))
            {
                return(matchingBittorrentFile);
            }
            matchingBittorrentFile = bittorrentFilesByName[GetFileSearchkey(dropboxFile)].FirstOrDefault();
            if (matchingBittorrentFile == null)
            {
            }
            else
            {
            }

            return(matchingBittorrentFile);
        }
        private IEnumerable <ISearchTarget> CreateObjectBasedSearchTarget(DbObject[] dbObjects, ILookup <long, DbColumn> dbColumnsByTableId)
        {
            var list = new List <ISearchTarget>();

            foreach (var dbObject in dbObjects)
            {
                var simplifiedType = DbObjectType.Parse(dbObject.Type);

                if (simplifiedType.Category == DbSimplifiedType.Constraint)
                {
                    list.Add(new ConstraintSearchTarget(dbObject));
                }
                else if (simplifiedType.Category == DbSimplifiedType.Table)
                {
                    list.Add(new TableSearchTarget(dbObject, dbColumnsByTableId[dbObject.ObjectId].ToArray()));
                }
                else if (simplifiedType.Category == DbSimplifiedType.Other)
                {
                    list.Add(new OtherSearchTarget(dbObject));
                }
                else
                {
                    list.Add(new ObjectSearchTarget(dbObject));
                }
            }

            return(list);
        }
 /// <summary>
 /// Creates a new instance of WebhookMiddleware.
 /// </summary>
 /// <param name="next">The next delegate to be called in the middleware pipeline.</param>
 /// <param name="consumers">The webhook consumers to be configured.</param>
 public WebhookMiddleware(RequestDelegate next, ILookup <Tuple <string, string, string>, Tuple <Delegate, Func <HttpContext, bool> > > consumers) : this(next, consumers, null)
 {
 }
Example #35
0
        public static void DeleteFiles(this IProjectSystem project, IEnumerable <IPackageFile> files, IEnumerable <IPackage> otherPackages, IDictionary <FileTransformExtensions, IPackageFileTransformer> fileTransformers)
        {
            IPackageFileTransformer        transformer;
            ILookup <string, IPackageFile> lookup = Enumerable.ToLookup <IPackageFile, string>(files, p => Path.GetDirectoryName(ResolveTargetPath(project, fileTransformers, fte => fte.UninstallExtension, p.EffectivePath, out transformer)));

            foreach (string str in from grouping in lookup
                     from directory in FileSystemExtensions.GetDirectories(grouping.Key)
                     orderby directory.Length descending
                     select directory)
            {
                IEnumerable <IPackageFile> enumerable = lookup.Contains(str) ? lookup[str] : Enumerable.Empty <IPackageFile>();
                if (project.DirectoryExists(str))
                {
                    IBatchProcessor <string> processor = project as IBatchProcessor <string>;
                    try
                    {
                        if (processor != null)
                        {
                            Func <IPackageFile, string> < > 9__6;
                            Func <IPackageFile, string> func5 = < > 9__6;
                            if (< > 9__6 == null)
                            {
                                Func <IPackageFile, string> local5 = < > 9__6;
                                func5 = < > 9__6 = file => ResolvePath(fileTransformers, fte => fte.UninstallExtension, file.EffectivePath);
                            }
                            processor.BeginProcessing(Enumerable.Select <IPackageFile, string>(enumerable, func5), PackageAction.Uninstall);
                        }
                        foreach (IPackageFile file in enumerable)
                        {
                            if (!file.IsEmptyFolder())
                            {
                                string path = ResolveTargetPath(project, fileTransformers, fte => fte.UninstallExtension, file.EffectivePath, out transformer);
                                if (project.IsSupportedFile(path))
                                {
                                    Func <IPackage, IEnumerable <IPackageFile> > < > 9__9;
                                    if (transformer == null)
                                    {
                                        project.DeleteFileSafe(path, new Func <Stream>(file.GetStream));
                                        continue;
                                    }
                                    Func <IPackage, IEnumerable <IPackageFile> > func4 = < > 9__9;
                                    if (< > 9__9 == null)
                                    {
                                        Func <IPackage, IEnumerable <IPackageFile> > local7 = < > 9__9;
                                        func4 = < > 9__9 = p => project.GetCompatibleItemsCore <IPackageFile>(p.GetContentFiles());
                                    }
                                    IEnumerable <IPackageFile> matchingFiles = from <> h__TransparentIdentifier0 in Enumerable.SelectMany(otherPackages, func4, (p, otherFile) => new {
                                        p         = p,
                                        otherFile = otherFile
                                    })
                                                                               where < > h__TransparentIdentifier0.otherFile.EffectivePath.Equals(file.EffectivePath, StringComparison.OrdinalIgnoreCase)
                                                                               select <> h__TransparentIdentifier0.otherFile;
                                    try
                                    {
                                        transformer.RevertFile(file, path, matchingFiles, project);
                                    }
                                    catch (Exception exception)
                                    {
                                        project.Logger.Log(MessageLevel.Warning, exception.Message, new object[0]);
                                    }
                                }
                            }
                        }
                        if (!project.GetFilesSafe(str).Any <string>() && !project.GetDirectoriesSafe(str).Any <string>())
                        {
                            project.DeleteDirectorySafe(str, false);
                        }
                    }
                    finally
                    {
                        if (processor != null)
                        {
                            processor.EndProcessing();
                        }
                    }
                }
            }
        }
 private AggregateRewriter(Expression expr)
 {
     this.map    = new Dictionary <DbAggregateSubqueryExpression, Expression>();
     this.lookup = AggregateGatherer.Gather(expr).ToLookup(a => a.GroupByAlias);
 }
        /// <summary>
        /// Create the template output
        /// </summary>
        public virtual string TransformText()
        {
            this.Write("\r\n");

            #line 9 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\Index.tt"

            var title = "ASP.NET Web API Help Page";
            // Group APIs by controller
            ILookup <string, ApiDescription> apiGroups = Model.ToLookup(api => api.ActionDescriptor.ControllerDescriptor.ControllerName);


            #line default
            #line hidden
            this.Write("\r\n<html>\r\n<head>\r\n    <title>");

            #line 17 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\Index.tt"
            this.Write(this.ToStringHelper.ToStringWithCulture(title));

            #line default
            #line hidden
            this.Write("</title>\r\n\t<style type=\"text/css\">\r\n\t\t");
            this.Write("pre.wrapped {\r\n    white-space: -moz-pre-wrap;\r\n    white-space: -pre-wrap;\r\n    " +
                       "white-space: -o-pre-wrap;\r\n    white-space: pre-wrap;\r\n}\r\n\r\n.warning-message-con" +
                       "tainer {\r\n    margin-top: 20px;\r\n    padding: 0 10px;\r\n    color: #525252;\r\n    " +
                       "background: #EFDCA9;\r\n    border: 1px solid #CCCCCC;\r\n}\r\n\r\n.help-page-table {\r\n " +
                       "   width: 100%;\r\n    border-collapse: collapse;\r\n    text-align: left;\r\n    marg" +
                       "in: 0px 0px 20px 0px;\r\n    border-top: 2px solid #D4D4D4;\r\n}\r\n\r\n    .help-page-t" +
                       "able th {\r\n        text-align: left;\r\n        font-weight: bold;\r\n        border" +
                       "-bottom: 2px solid #D4D4D4;\r\n        padding: 8px 6px 8px 6px;\r\n    }\r\n\r\n    .he" +
                       "lp-page-table td {\r\n        border-bottom: 2px solid #D4D4D4;\r\n        padding: " +
                       "15px 8px 15px 8px;\r\n        vertical-align: top;\r\n    }\r\n\r\n    .help-page-table " +
                       "pre, .help-page-table p {\r\n        margin: 0px;\r\n        padding: 0px;\r\n        " +
                       "font-family: inherit;\r\n        font-size: 100%;\r\n    }\r\n\r\n    .help-page-table t" +
                       "body tr:hover td {\r\n        background-color: #F3F3F3;\r\n    }\r\n\r\na:hover {\r\n    " +
                       "background-color: transparent;\r\n}\r\n\r\n.sample-header {\r\n    border: 2px solid #D4" +
                       "D4D4;\r\n    background: #76B8DB;\r\n    color: #FFFFFF;\r\n    padding: 8px 15px;\r\n  " +
                       "  border-bottom: none;\r\n    display: inline-block;\r\n    margin: 10px 0px 0px 0px" +
                       ";\r\n}\r\n\r\n.sample-content {\r\n    display: block;\r\n    border-width: 0;\r\n    paddin" +
                       "g: 15px 20px;\r\n    background: #FFFFFF;\r\n    border: 2px solid #D4D4D4;\r\n    mar" +
                       "gin: 0px 0px 10px 0px;\r\n}\r\n\r\n.api-name {\r\n    width: 40%;\r\n}\r\n\r\n.api-documentati" +
                       "on {\r\n    width: 60%;\r\n}\r\n\r\n.parameter-name {\r\n    width: 20%;\r\n}\r\n\r\n.parameter-" +
                       "documentation {\r\n    width: 50%;\r\n}\r\n\r\n.parameter-source {\r\n    width: 30%;\r\n}");
            this.Write("\r\n\t</style>\r\n</head>\r\n<body>\r\n<header>\r\n    <div class=\"content-wrapper\">\r\n      " +
                       "  <div class=\"float-left\">\r\n            <h1>");

            #line 26 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\Index.tt"
            this.Write(this.ToStringHelper.ToStringWithCulture(title));

            #line default
            #line hidden
            this.Write(@"</h1>
        </div>
    </div>
</header>
<div id=""body"">
    <section class=""featured"">
        <div class=""content-wrapper"">
            <h2>Introduction</h2>
            <p>
                Provide a general description of your APIs here.
            </p>
        </div>
    </section>
    <section class=""content-wrapper main-content clear-fix"">
        ");

            #line 40 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\Index.tt"
            foreach (IGrouping <string, ApiDescription> controllerGroup in apiGroups)
            {
            #line default
            #line hidden
                this.Write("            ");
                this.Write("<h2 id=\"");

            #line 1 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\DisplayTemplates\ApiGroup.tt"
                this.Write(this.ToStringHelper.ToStringWithCulture(controllerGroup.Key));

            #line default
            #line hidden
                this.Write("\">");

            #line 1 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\DisplayTemplates\ApiGroup.tt"
                this.Write(this.ToStringHelper.ToStringWithCulture(controllerGroup.Key));

            #line default
            #line hidden
                this.Write("</h2>\r\n<table class=\"help-page-table\">\r\n\t<thead>\r\n\t\t<tr><th>API</th><th>Descripti" +
                           "on</th></tr>\r\n\t</thead>\r\n\t<tbody class=\"ui-widget-content\">\r\n\t");

            #line 7 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\DisplayTemplates\ApiGroup.tt"
                foreach (var api in controllerGroup)
                {
            #line default
            #line hidden
                    this.Write("\t\t<tr>\r\n\t\t\t<td class=\"api-name\"><a href=\"");

            #line 10 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\DisplayTemplates\ApiGroup.tt"
                    this.Write(this.ToStringHelper.ToStringWithCulture(ApiLinkFactory(api.GetFriendlyId())));

            #line default
            #line hidden
                    this.Write("\">");

            #line 10 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\DisplayTemplates\ApiGroup.tt"
                    this.Write(this.ToStringHelper.ToStringWithCulture(api.HttpMethod.Method));

            #line default
            #line hidden
                    this.Write(" ");

            #line 10 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\DisplayTemplates\ApiGroup.tt"
                    this.Write(this.ToStringHelper.ToStringWithCulture(api.RelativePath));

            #line default
            #line hidden
                    this.Write("</a></td>\r\n\t\t\t<td class=\"api-documentation\">\r\n\t\t\t");

            #line 12 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\DisplayTemplates\ApiGroup.tt"
                    if (api.Documentation != null)
                    {
            #line default
            #line hidden
                        this.Write("\t\t\t\t<p>");

            #line 14 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\DisplayTemplates\ApiGroup.tt"
                        this.Write(this.ToStringHelper.ToStringWithCulture(api.Documentation));

            #line default
            #line hidden
                        this.Write("</p>\r\n\t\t\t");

            #line 15 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\DisplayTemplates\ApiGroup.tt"
                    }
                    else
                    {
            #line default
            #line hidden
                        this.Write("\t\t\t\t<p>No documentation available.</p>\r\n\t\t\t");

            #line 19 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\DisplayTemplates\ApiGroup.tt"
                    }

            #line default
            #line hidden
                    this.Write("\t\t\t</td>\r\n\t\t</tr>\r\n\t");

            #line 22 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\DisplayTemplates\ApiGroup.tt"
                }

            #line default
            #line hidden
                this.Write("\t</tbody>\r\n</table>");
                this.Write("\r\n        ");

            #line 43 "D:\Tools\webapi-html-help-generation\C#\WebApiHelpPageGenerator\Views\Index.tt"
            }

            #line default
            #line hidden
            this.Write("    </section>\r\n</div>\r\n</body>\r\n</html>");
            return(this.GenerationEnvironment.ToString());
        }
        private static async Task <Solution> UpdateReferencesAsync(Solution updatedSolution, string propertyName, bool nameChanged, ILookup <Document, ReferenceLocation> getReferencesByDocument, ILookup <Document, ReferenceLocation> setReferencesByDocument, CancellationToken cancellationToken)
        {
            var allReferenceDocuments = getReferencesByDocument.Concat(setReferencesByDocument).Select(g => g.Key).Distinct();

            foreach (var referenceDocument in allReferenceDocuments)
            {
                cancellationToken.ThrowIfCancellationRequested();

                updatedSolution = await UpdateReferencesInDocumentAsync(
                    propertyName, nameChanged, updatedSolution, referenceDocument,
                    getReferencesByDocument[referenceDocument],
                    setReferencesByDocument[referenceDocument],
                    cancellationToken).ConfigureAwait(false);
            }

            return(updatedSolution);
        }
Example #39
0
        /// <summary>
        /// Obtient toutes les données du projet spécifié.
        /// </summary>
        /// <param name="projectId">L'identifiant du projet.</param>
        public virtual async Task <RestitutionData> GetFullProjectDetails(int projectId) =>
        await Task.Run(async() =>
        {
            using (var context = ContextFactory.GetNewContext(_securityContext.CurrentUser, _localizationManager))
            {
                IDictionary <ProcessReferentialIdentifier, bool> referentialsUsed = await _sharedScenarioActionsOperations.GetReferentialsUse(context, projectId);
                Referentials referentials = await Queries.LoadAllReferentialsOfProject(context, projectId, referentialsUsed);

                //await context.Videos.Where(v => v.ProjectId == projectId).ToArrayAsync();
                await context.ScenarioNatures.ToArrayAsync();
                await context.ScenarioStates.ToArrayAsync();
                await context.ActionTypes.ToArrayAsync();
                await context.ActionValues.ToArrayAsync();

                Project project = await context.Projects
                                  .Include(nameof(Project.Process))
                                  .Include($"{nameof(Project.Process)}.{nameof(Procedure.Videos)}")
                                  .Include($"{nameof(Project.Process)}.{nameof(Procedure.UserRoleProcesses)}")
                                  .Include($"{nameof(Project.Process)}.{nameof(Procedure.UserRoleProcesses)}.{nameof(UserRoleProcess.User)}")
                                  .Include($"{nameof(Project.Process)}.{nameof(Procedure.UserRoleProcesses)}.{nameof(UserRoleProcess.User)}.{nameof(User.DefaultLanguage)}")
                                  .Include(nameof(Project.Scenarios))
                                  .Include($"{nameof(Project.Scenarios)}.{nameof(Scenario.Actions)}")
                                  .Include(nameof(Project.Objective))
                                  .FirstAsync(s => s.ProjectId == projectId);

                project.ScenariosCriticalPath = PrepareService.GetSummary(project, true);

                // Scénarios
                foreach (Scenario scenario in project.Scenarios.Where(s => s.OriginalScenarioId.HasValue))
                {
                    // Remapper l'original
                    scenario.Original = project.Scenarios.Single(s => s.ScenarioId == scenario.OriginalScenarioId);

                    ScenarioCriticalPath matchingCriticalItem = project.ScenariosCriticalPath.FirstOrDefault(i => i.Id == scenario.ScenarioId);
                    if (matchingCriticalItem != null)
                    {
                        matchingCriticalItem.OriginalLabel = scenario.Original.Label;
                    }
                }

                ProjectReferential[] projectReferentials = await context.ProjectReferentials.Where(pr => pr.ProjectId == projectId).ToArrayAsync();

                User user = await context.Users.FirstAsync(u => u.UserId == project.CreatedByUserId);

                ModificationsUsers modificationsUsers = new ModificationsUsers
                {
                    CreatedByFullName      = (await context.Users.FirstAsync(u => u.UserId == project.ModifiedByUserId)).FullName,
                    LastModifiedByFullName = (await context.Users.FirstAsync(u => u.UserId == project.ModifiedByUserId)).FullName
                };

                Scenario[] scenarios = await context.Scenarios
                                       .Where(s => s.ProjectId == projectId)
                                       .ToArrayAsync();

                await Queries.LoadScenariosDetails(context, scenarios, referentialsUsed);

                ILookup <int, KAction> actionsToLoad = scenarios
                                                       .SelectMany(a => a.Actions)
                                                       .Where(a => a.IsReduced && a.OriginalActionId.HasValue)
                                                       .ToLookup(a => a.OriginalActionId.Value, a => a);

                if (actionsToLoad.Any())
                {
                    foreach (var duration in await _sharedScenarioActionsOperations.GetActionsBuildDurations(context, actionsToLoad.Select(g => g.Key)))
                    {
                        foreach (KAction action in actionsToLoad[duration.ActionId])
                        {
                            action.Reduced.Saving = duration.BuildDuration - action.BuildDuration;
                        }
                    }
                }

                ScenarioActionHierarchyHelper.MapScenariosActionsOriginals(scenarios);

                return(new RestitutionData()
                {
                    Project = project,
                    ProjectCreatedByUser = user,
                    Scenarios = scenarios,
                    ActionCategories = referentials.Categories,
                    ModificationsUsers = modificationsUsers,
                    ReferentialsUse = projectReferentials,
                });
            }
        });
            /// <summary>
            /// Executes the procedure.
            /// </summary>
            /// <returns>The collection of reason codes.</returns>
            public PagedResult <ReasonCode> Execute()
            {
                const string GetReasonCodesQueryString = @"
                (
                    SELECT
                        icv.[REASONCODEID]                AS REASONCODEID,
                        icv.[RECID]                     AS RECID,
                        icv.[ONCEPERTRANSACTION]        AS ONCEPERTRANSACTION,
                        icv.[PRINTPROMPTONRECEIPT]      AS PRINTPROMPTONRECEIPT,
                        icv.[PRINTINPUTONRECEIPT]       AS PRINTINPUTONRECEIPT,
                        icv.[PRINTINPUTNAMEONRECEIPT]   AS PRINTINPUTNAMEONRECEIPT,
                        icv.[INPUTTYPE]                 AS INPUTTYPE,
                        icv.[MINIMUMVALUE]              AS MINIMUMVALUE,
                        icv.[MAXIMUMVALUE]              AS MAXIMUMVALUE,
                        icv.[MINIMUMLENGTH]             AS MINIMUMLENGTH,
                        icv.[MAXIMUMLENGTH]             AS MAXIMUMLENGTH,
                        icv.[INPUTREQUIRED]             AS INPUTREQUIRED,
                        icv.[LINKEDREASONCODEID]          AS LINKEDREASONCODEID,
                        icv.[RANDOMFACTOR]              AS RANDOMFACTOR,
                        icv.[RETAILUSEINFOCODE]         AS RETAILUSEINFOCODE,
                        icv.[PRIORITY]                  AS PRIORITY,
                        COALESCE(rict.[DESCRIPTION], rictd.[DESCRIPTION], icv.[REASONCODEID]) AS DESCRIPTION,
                        COALESCE(rict.[PROMPT], rictd.[PROMPT], icv.[REASONCODEID]) AS PROMPT,
                        COALESCE(rict.[LANGUAGEID], rictd.[LANGUAGEID]) AS LANGUAGEID
                    FROM [crt].[INFOCODEVIEW] icv
                    LEFT JOIN [ax].[RETAILINFOCODETRANSLATION] rict
                        ON icv.[RECID]               = rict.[INFOCODE]
                            AND icv.[DATAAREAID]    = rict.[DATAAREAID]
                            AND rict.[LANGUAGEID]   = @languageId
                    LEFT JOIN [ax].[RETAILINFOCODETRANSLATION] rictd
                        ON icv.[RECID]              = rictd.[INFOCODE]
                            AND icv.[DATAAREAID]    = rictd.[DATAAREAID]
                            AND rictd.[LANGUAGEID]  = @defaultlanguageId
                    WHERE icv.[DATAAREAID] = @DataAreaId
                            AND ((SELECT COUNT(STRINGID) FROM @tvp_groupIds) = 0 OR icv.[GROUPID] IN (SELECT STRINGID FROM @tvp_groupIds))
                )";

                SqlPagedQuery query = new SqlPagedQuery(this.request.QueryResultSettings)
                {
                    From           = GetReasonCodesQueryString,
                    Aliased        = true,
                    DatabaseSchema = string.Empty,
                    OrderBy        = new SortingInfo(ReasonCode.PriorityColumn, false).ToString()
                };

                PagedResult <ReasonCode> reasonCodes;

                query.Parameters["@defaultlanguageId"] = this.defaultLanguageId;
                query.Parameters["@languageId"]        = this.employeeLanguageId;
                query.Parameters["@DataAreaId"]        = this.request.RequestContext.GetChannelConfiguration().InventLocationDataAreaId;

                using (SqliteDatabaseContext context = new SqliteDatabaseContext(this.request.RequestContext))
                    using (StringIdTableType groupIds = new StringIdTableType(this.request.ReasonCodeIds, "GROUPID"))
                    {
                        // the view sets the INFOCODEID to GROUPID when the reason code is not part of a group, so we always query by GROUPID
                        query.Parameters["@tvp_groupIds"] = groupIds.DataTable;

                        reasonCodes = context.ReadEntity <ReasonCode>(query);

                        if (reasonCodes.Results.Any())
                        {
                            IEnumerable <string> reasonCodeIds = reasonCodes.Results.Select(x => x.ReasonCodeId);

                            QueryResultSettings        subCodeSettings   = QueryResultSettings.AllRecords;
                            GetSubReasonCodesProcedure getSubReasonCodes = new GetSubReasonCodesProcedure(
                                this.request.RequestContext,
                                context,
                                reasonCodeIds,
                                reasonSubCodeId: null,
                                settings: subCodeSettings,
                                defaultlanguageId: this.defaultLanguageId,
                                employeeLanguageId: this.employeeLanguageId);

                            ILookup <string, ReasonSubCode> subcodes = getSubReasonCodes.Execute().ToLookup(x => x.ReasonCodeId);

                            foreach (var infoCode in reasonCodes.Results)
                            {
                                infoCode.ReasonSubCodes.Clear();
                                infoCode.ReasonSubCodes.AddRange(subcodes[infoCode.ReasonCodeId]);
                            }
                        }
                    }

                return(reasonCodes);
            }
Example #41
0
 internal ObservationDataRecord(Dictionary <SatelliteSystem, GnssObservation> obsMetaData)
 {
     _obsMetaData = obsMetaData.ToLookup(t => t.Key, t => t.Value);
 }
Example #42
0
 private XmlElementValueCollection(IList <XmlElementValue> list, ILookup <string, XmlElementValue> nameMap)
 {
     Debug.Assert(list != null, "FromList should replace null list with XmlElementValueCollection.empty");
     this.values     = list;
     this.nameLookup = nameMap;
 }
Example #43
0
        private AirFireInfo getAntifireKind(Mem_ship shipData, List <Mst_slotitem> slotData)
        {
            Mst_ship mst_ship = Mst_DataManager.Instance.Mst_ship[shipData.Ship_id];
            ILookup <int, Mst_slotitem> lookup = slotData.ToLookup((Mst_slotitem x) => x.Type4);
            HashSet <int> hashSet = new HashSet <int>();

            hashSet.Add(54);
            HashSet <int> hashSet2 = hashSet;

            hashSet = new HashSet <int>();
            hashSet.Add(428);
            HashSet <int>         hashSet3   = hashSet;
            AirFireInfo           result     = null;
            Dictionary <int, int> dictionary = new Dictionary <int, int>();

            dictionary.Add(1, 65);
            dictionary.Add(2, 58);
            dictionary.Add(3, 50);
            dictionary.Add(4, 52);
            dictionary.Add(5, 55);
            dictionary.Add(6, 40);
            dictionary.Add(7, 45);
            dictionary.Add(8, 50);
            dictionary.Add(9, 40);
            dictionary.Add(10, 60);
            dictionary.Add(11, 55);
            dictionary.Add(12, 45);
            dictionary.Add(13, 35);
            Dictionary <int, int> dictionary2 = dictionary;
            int        num  = (int)Utils.GetRandDouble(0.0, 100.0, 1.0, 1);
            List <int> list = new List <int>();

            if (hashSet2.Contains(mst_ship.Ctype))
            {
                if (!lookup.Contains(16))
                {
                    return(null);
                }
                List <Mst_slotitem> list2 = lookup[16].ToList().FindAll((Mst_slotitem x) => x.Tyku >= 8);
                List <Mst_slotitem> list3 = new List <Mst_slotitem>();
                if (lookup.Contains(11))
                {
                    list3 = lookup[11].ToList().FindAll((Mst_slotitem x) => x.Tyku >= 2);
                }
                if (list2.Count >= 2 && list3.Count >= 1 && num < dictionary2[1])
                {
                    list.Add(list2[0].Id);
                    list.Add(list2[1].Id);
                    list.Add(list3[0].Id);
                    result = new AirFireInfo(shipData.Rid, 1, list);
                }
                else if (list2.Count >= 1 && list3.Count >= 1 && num < dictionary2[2])
                {
                    list.Add(list2[0].Id);
                    list.Add(list3[0].Id);
                    result = new AirFireInfo(shipData.Rid, 2, list);
                }
                else if (list2.Count >= 2 && num < dictionary2[3])
                {
                    list.Add(list2[0].Id);
                    list.Add(list2[1].Id);
                    result = new AirFireInfo(shipData.Rid, 3, list);
                }
                return(result);
            }
            if (hashSet3.Contains(mst_ship.Id) && lookup.Contains(16) && lookup.Contains(15))
            {
                List <Mst_slotitem> list4 = lookup[16].ToList();
                List <Mst_slotitem> list5 = lookup[15].ToList().FindAll((Mst_slotitem x) => x.Tyku >= 9);
                List <Mst_slotitem> list6 = new List <Mst_slotitem>();
                if (lookup.Contains(11))
                {
                    list6 = lookup[11].ToList().FindAll((Mst_slotitem x) => x.Tyku >= 2);
                }
                if (list5.Count > 0 && list6.Count > 0 && num < dictionary2[10])
                {
                    list.Add(list4[0].Id);
                    list.Add(list5[0].Id);
                    list.Add(list6[0].Id);
                    return(new AirFireInfo(shipData.Rid, 10, list));
                }
                if (list5.Count > 0 && num < dictionary2[11])
                {
                    list.Add(list4[0].Id);
                    list.Add(list5[0].Id);
                    return(new AirFireInfo(shipData.Rid, 11, list));
                }
            }
            List <Mst_slotitem> list7 = new List <Mst_slotitem>();

            if (lookup.Contains(16))
            {
                list7 = lookup[16].ToList().FindAll((Mst_slotitem x) => x.Tyku >= 8);
            }
            List <Mst_slotitem> list8 = new List <Mst_slotitem>();

            if (lookup.Contains(11))
            {
                list8 = lookup[11].ToList().FindAll((Mst_slotitem x) => x.Tyku >= 2);
            }
            if (lookup.Contains(30) && lookup.Contains(3) && lookup.Contains(12) && list8.Count >= 1 && num < dictionary2[4])
            {
                list.Add(lookup[3].First().Id);
                list.Add(lookup[12].First().Id);
                list.Add(lookup[30].First().Id);
                return(new AirFireInfo(shipData.Rid, 4, list));
            }
            if (list7.Count >= 2 && list8.Count >= 1 && num < dictionary2[5])
            {
                list.Add(list7[0].Id);
                list.Add(list7[1].Id);
                list.Add(list8[0].Id);
                return(new AirFireInfo(shipData.Rid, 5, list));
            }
            if (lookup.Contains(30) && lookup.Contains(3) && lookup.Contains(12) && num < dictionary2[6])
            {
                list.Add(lookup[3].First().Id);
                list.Add(lookup[12].First().Id);
                list.Add(lookup[30].First().Id);
                return(new AirFireInfo(shipData.Rid, 6, list));
            }
            if (lookup.Contains(30) && lookup.Contains(16) && list8.Count >= 1 && num < dictionary2[7])
            {
                Mst_slotitem mst_slotitem = (list7.Count <= 0) ? lookup[16].First() : list7[0];
                list.Add(mst_slotitem.Id);
                list.Add(lookup[30].First().Id);
                list.Add(list8[0].Id);
                return(new AirFireInfo(shipData.Rid, 7, list));
            }
            if (list7.Count >= 1 && list8.Count >= 1 && num < dictionary2[8])
            {
                list.Add(list7[0].Id);
                list.Add(list8[0].Id);
                return(new AirFireInfo(shipData.Rid, 8, list));
            }
            if (lookup.Contains(30) && lookup.Contains(16) && num < dictionary2[9])
            {
                Mst_slotitem mst_slotitem2 = (list7.Count <= 0) ? lookup[16].First() : list7[0];
                list.Add(mst_slotitem2.Id);
                list.Add(lookup[30].First().Id);
                return(new AirFireInfo(shipData.Rid, 9, list));
            }
            List <Mst_slotitem> list9 = new List <Mst_slotitem>();

            new List <Mst_slotitem>();
            List <Mst_slotitem> list10 = new List <Mst_slotitem>();

            if (lookup.Contains(15))
            {
                list9 = lookup[15].ToList().FindAll((Mst_slotitem x) => x.Tyku >= 9);
                List <Mst_slotitem> collection = lookup[15].ToList().FindAll((Mst_slotitem x) => x.Tyku >= 3);
                list10.AddRange(list9);
                list10.AddRange(collection);
            }
            if (list10.Count >= 2 && list8.Count >= 1 && num < dictionary2[12])
            {
                list.Add(list10[0].Id);
                list.Add(list10[1].Id);
                list.Add(list8[0].Id);
                return(new AirFireInfo(shipData.Rid, 12, list));
            }
            if (hashSet3.Contains(mst_ship.Id))
            {
                return(result);
            }
            if (list7.Count >= 1 && list9.Count >= 1 && list8.Count >= 1 && num < dictionary2[13])
            {
                list.Add(list7[0].Id);
                list.Add(list9[0].Id);
                list.Add(list8[0].Id);
                return(new AirFireInfo(shipData.Rid, 13, list));
            }
            return(result);
        }
Example #44
0
 public WebhookMiddleware(RequestDelegate next, ILookup <Tuple <string, string, string>, Delegate> consumers) : this(next, consumers, null)
 {
 }
 /// <summary>
 /// Implementation of join using lookup plus selectmany
 /// </summary>
 public void SelectManyWithLookup(ILookup <int?, Purchase> purchaseLookup, RestfulServiceDatabaseEntities dbContext)
 {
     var result = from c in dbContext.Customer
                  from p in purchaseLookup[c.ID]
                  select new { c.Name, p.Id, p.Price };
 }
Example #46
0
 protected void FreeReentrant()
 {
     this.context = null;
 }
Example #47
0
 private static ImmutableArray <DiagnosticData> GetDiagnosticData(ILookup <DocumentId, DiagnosticData> lookup, DocumentId documentId)
 {
     return(lookup.Contains(documentId) ? lookup[documentId].ToImmutableArrayOrEmpty() : ImmutableArray <DiagnosticData> .Empty);
 }
Example #48
0
 public override async IAsyncEnumerable <SeedTree> ScrapeAsync(ISeed parent,
                                                               ILookup <string, SeedContent> rootSeeds, ILookup <string, SeedContent> childSeeds,
                                                               ILookup <string, SeedContent> siblingSeeds)
 {
     yield return("TestDependent", $"{rootSeeds["Test"].First()} from Dependent Scraper");
 }
Example #49
0
        /// <summary>
        /// Selects the action.
        /// </summary>
        /// <param name="odataPath">The odata path.</param>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="actionMap">The action map.</param>
        /// <returns></returns>
        public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup <string, HttpActionDescriptor> actionMap)
        {
            if (odataPath == null)
            {
                throw Error.ArgumentNull("odataPath");
            }

            if (controllerContext == null)
            {
                throw Error.ArgumentNull("controllerContext");
            }

            if (actionMap == null)
            {
                throw Error.ArgumentNull("actionMap");
            }

            HttpMethod requestMethod = controllerContext.Request.Method;

            if (odataPath.PathTemplate == "~/entityset/key/$links/navigation")
            {
                if (requestMethod == HttpMethod.Post || requestMethod == HttpMethod.Put)
                {
                    AddLinkInfoToRouteData(controllerContext.RouteData, odataPath);
                    return("CreateLink");
                }
                else if (requestMethod == HttpMethod.Delete)
                {
                    AddLinkInfoToRouteData(controllerContext.RouteData, odataPath);
                    return("DeleteLink");
                }
            }
            else if (odataPath.PathTemplate == "~/entityset/key/$links/navigation/key" && requestMethod == HttpMethod.Delete)
            {
                AddLinkInfoToRouteData(controllerContext.RouteData, odataPath);
                KeyValuePathSegment relatedKeySegment = odataPath.Segments[4] as KeyValuePathSegment;
                controllerContext.RouteData.Values.Add(ODataRouteConstants.RelatedKey, relatedKeySegment.Value);
                return("DeleteLink");
            }
            return(null);
        }
        private IReadOnlyDictionary <string, object> MergeVariables(
            IReadOnlyDictionary <string, object> variables,
            OperationDefinitionNode operation)
        {
            if (_exportedVariables.Count == 0)
            {
                return(variables);
            }

            ILookup <string, ExportedVariable> exported =
                _exportedVariables.ToLookup(t => t.Name);
            var merged = new Dictionary <string, object>();

            foreach (VariableDefinitionNode variableDefinition in
                     operation.VariableDefinitions)
            {
                string variableName = variableDefinition.Variable.Name.Value;

                if (!exported[variableName].Any())
                {
                    if (variables != null &&
                        variables.TryGetValue(variableName, out var value))
                    {
                        merged[variableName] = value;
                    }
                }
                else if (variableDefinition.Type.IsListType())
                {
                    var list = new List <object>();

                    if (variables != null &&
                        variables.TryGetValue(variableName, out var value))
                    {
                        if (value is IReadOnlyCollection <object> l)
                        {
                            list.AddRange(l);
                        }
                        else
                        {
                            list.Add(value);
                        }
                    }

                    foreach (ExportedVariable variable in
                             exported[variableName])
                    {
                        SerializeListValue(
                            variable,
                            variableDefinition.Type,
                            list);
                    }

                    merged[variableName] = list;
                }
                else
                {
                    if (variables != null &&
                        variables.TryGetValue(variableName, out var value))
                    {
                        merged[variableName] = value;
                    }
                    else
                    {
                        merged[variableName] = Serialize(
                            exported[variableName].FirstOrDefault(),
                            variableDefinition.Type);
                    }
                }
            }

            return(merged);
        }
Example #51
0
        internal static Relation CreateFrom(ISqlHelper sqlHelper, IDictionary <string, object> values, ILookup <Identifier, RelationField> relationFields)
        {
            var result =
                new Relation(sqlHelper)
            {
                RelationId           = values["RDB$RELATION_ID"].DbValueToInt32().GetValueOrDefault(),
                MetadataRelationType = (MetadataRelationType)values["RDB$RELATION_TYPE"].DbValueToInt32().GetValueOrDefault(),
                RelationName         = new Identifier(sqlHelper, values["RDB$RELATION_NAME"].DbValueToString()),
                Description          = values["RDB$DESCRIPTION"].DbValueToString(),
                ViewSource           = values["RDB$VIEW_SOURCE"].DbValueToString(),
                ExternalFile         = values["RDB$EXTERNAL_FILE"].DbValueToString(),
                ExternalDescription  = values["RDB$EXTERNAL_DESCRIPTION"].DbValueToString(),
                OwnerName            = values["RDB$OWNER_NAME"].DbValueToString(),
                SystemFlag           = (SystemFlagType)values["RDB$SYSTEM_FLAG"].DbValueToInt32().GetValueOrDefault()
            };

            result.Fields = relationFields[result.RelationName].ToArray();

            return(result);
        }
Example #52
0
 public Runner(Listener listener, ILookup <string, string> options)
 {
     this.listener = listener;
     this.options  = options;
 }
Example #53
0
 public WebhookMiddleware(RequestDelegate next, ILookup <Tuple <string, string, string>, Delegate> consumers, Func <HttpContext, bool> webhookAuthorization)
 {
     _next                 = next;
     _consumers            = consumers;
     _webhookAuthorization = webhookAuthorization;
 }
        // Route the action to a method with the same name as the action.
        public string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup <string, HttpActionDescriptor> actionMap)
        {
            // OData actions must be invoked with HTTP POST.
            if (controllerContext.Request.Method == HttpMethod.Post)
            {
                if (odataPath.PathTemplate == "~/action")
                {
                    ActionPathSegment  actionSegment = odataPath.Segments.First() as ActionPathSegment;
                    IEdmFunctionImport action        = actionSegment.Action;

                    if (!action.IsBindable && actionMap.Contains(action.Name))
                    {
                        return(action.Name);
                    }
                }
            }
            return(null);
        }
        public void ProcessJob(TaskScheduling task)
        {
            List <User> ownerUsers = new List <User>();
            List <IdentityStoreObject> orphanGrps      = this.GetOrphanGroups(null);
            IStoreTypeHelper           storeHelper     = Helper.GetStoreTypeHelper(Helper.CurrentTask.get_IdentityStoreId());
            ILookup <string, User>     addOwnersLookup = null;
            List <string> supportedObjectTypes         = new List <string>();

            if (storeHelper != null)
            {
                supportedObjectTypes = storeHelper.GetSupportedObjectTypes(Helper.KnownProviderAttributes.get_Owner());
                if (supportedObjectTypes.Count > 0)
                {
                    List <string> strs1 = new List <string>();
                    orphanGrps.ForEach((IdentityStoreObject g) => {
                        List <string> strs = strs1;
                        List <Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute> values = g.get_AttributesBusinessObject().GetValues("XAdditionalOwner");
                        Func <Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute, string> u003cu003e9_12 = OrphanGroupProcessor.< > c.< > 9__1_2;
                        if (u003cu003e9_12 == null)
                        {
                            u003cu003e9_12 = (Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute o) => o.get_Value();
                            OrphanGroupProcessor.< > c.< > 9__1_2 = u003cu003e9_12;
                        }
                        strs.AddRange(values.Select <Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute, string>(u003cu003e9_12));
                    });
                    ServicesUserServiceClient serviceUser = new ServicesUserServiceClient(false);
                    List <User> owners = serviceUser.Get(Helper.CurrentTask.get_IdentityStoreId(), strs1, new List <string>());
                    addOwnersLookup = owners.ToLookup <User, string>((User o) => o.get_ObjectIdFromIdentityStore(), StringComparer.OrdinalIgnoreCase);
                }
            }
            List <IdentityStoreObject> orphansList = new List <IdentityStoreObject>();

            foreach (IdentityStoreObject oGrp in orphanGrps)
            {
                if (oGrp.get_AttributesBusinessObject().IsIn(Helper.KnownProviderAttributes.get_Container()))
                {
                    oGrp.get_AttributesBusinessObject().Remove(Helper.KnownProviderAttributes.get_Container());
                }
                if (oGrp.get_AttributesBusinessObject().IsIn(Helper.KnownProviderAttributes.get_DisplayName()))
                {
                    oGrp.get_AttributesBusinessObject().Remove(Helper.KnownProviderAttributes.get_DisplayName());
                }
                if (oGrp.get_AttributesBusinessObject().IsIn(Helper.KnownProviderAttributes.get_DistinguishedName()))
                {
                    oGrp.get_AttributesBusinessObject().Remove(Helper.KnownProviderAttributes.get_DistinguishedName());
                }
                if (oGrp.get_AttributesBusinessObject().IsIn(Helper.KnownProviderAttributes.get_CommonName()))
                {
                    oGrp.get_AttributesBusinessObject().Remove(Helper.KnownProviderAttributes.get_CommonName());
                }
                Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute additionalOwner = this.GetAdditionalOwnerToPromote(oGrp.get_AttributesBusinessObject().GetValues("XAdditionalOwner"), addOwnersLookup, supportedObjectTypes);
                if (additionalOwner != null)
                {
                    ServicesUserServiceClient serviceUser = new ServicesUserServiceClient(false);
                    User additionaOwnerDN = serviceUser.Get(Helper.CurrentTask.get_IdentityStoreId(), additionalOwner.get_Value(), new List <string>()
                    {
                        Helper.KnownProviderAttributes.get_DistinguishedName(),
                        Helper.KnownProviderAttributes.get_EmailAddress(),
                        Helper.KnownProviderAttributes.get_DisplayName()
                    }, false);
                    if ((additionaOwnerDN == null ? false : additionaOwnerDN.get_AttributesBusinessObject().HasValue(Helper.KnownProviderAttributes.get_DistinguishedName())))
                    {
                        oGrp.set_ObjectName(additionalOwner.get_Value());
                        ownerUsers.Add(additionaOwnerDN);
                        additionaOwnerDN.set_ObjectIdFromIdentityStore(additionalOwner.get_Value());
                        additionalOwner.set_Action(2);
                        string dnValue = additionaOwnerDN.get_AttributesBusinessObject().get_AttributesCollection()[Helper.KnownProviderAttributes.get_DistinguishedName()][0].get_Value();
                        if (oGrp.get_AttributesBusinessObject().HasValue(Helper.KnownProviderAttributes.get_Owner()))
                        {
                            oGrp.get_AttributesBusinessObject().get_AttributesCollection()[Helper.KnownProviderAttributes.get_Owner()][0].set_Value(dnValue);
                            oGrp.get_AttributesBusinessObject().get_AttributesCollection()[Helper.KnownProviderAttributes.get_Owner()][0].set_Action(1);
                        }
                        else if (!oGrp.get_AttributesBusinessObject().IsIn(Helper.KnownProviderAttributes.get_Owner()))
                        {
                            Dictionary <string, List <Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute> > attributesCollection = oGrp.get_AttributesBusinessObject().get_AttributesCollection();
                            string owner = Helper.KnownProviderAttributes.get_Owner();
                            List <Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute> attributes = new List <Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute>();
                            Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute        attribute  = new Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute();
                            attribute.set_Action(1);
                            attribute.set_Value(dnValue);
                            attributes.Add(attribute);
                            attributesCollection.Add(owner, attributes);
                        }
                        else
                        {
                            Dictionary <string, List <Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute> > attributesCollection1 = oGrp.get_AttributesBusinessObject().get_AttributesCollection();
                            string str = Helper.KnownProviderAttributes.get_Owner();
                            List <Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute> attributes1 = new List <Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute>();
                            Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute        attribute1  = new Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute();
                            attribute1.set_Action(1);
                            attribute1.set_Value(dnValue);
                            attributes1.Add(attribute1);
                            attributesCollection1[str] = attributes1;
                        }
                        orphansList.Add(oGrp);
                    }
                }
            }
            if (orphansList.Count > 0)
            {
                ServicesGroupServiceClient groupServiceClient = new ServicesGroupServiceClient(false);
                string cData = DataCompressionHelper.CompressObjects <List <IdentityStoreObject> >(orphansList);
                if (groupServiceClient.UpdateManyWithCompression(Helper.CurrentTask.get_IdentityStoreId(), cData, typeof(IdentityStoreObject).FullName).get_Status() == 0)
                {
                    List <IdentityStoreObject> idObjectsList = Helper.PrepareCompressedData(orphansList);
                    groupServiceClient.SendOwnerUpdateNotification(Helper.CurrentTask.get_IdentityStoreId(), idObjectsList, ownerUsers);
                }
            }
        }
Example #56
0
 public Meetup(int month, int year)
 {
     days = Enumerable.Range(1, DateTime.DaysInMonth(year, month))
            .Select(day => new DateTime(year, month, day))
            .ToLookup(d => d.DayOfWeek);
 }
        private Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute GetAdditionalOwnerToPromote(List <Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute> additionalOwners, ILookup <string, User> addOwnersLookup, List <string> supportedObjectTypes)
        {
            Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute attribute;
            MembershipType val;
            MembershipType val;

            if (additionalOwners.Count == 0)
            {
                attribute = null;
            }
            else if ((addOwnersLookup == null ? false : supportedObjectTypes.Count != 0))
            {
                foreach (Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute additionalOwner in additionalOwners)
                {
                    User user = addOwnersLookup[additionalOwner.get_Value()].FirstOrDefault <User>();
                    if ((user == null ? false : supportedObjectTypes.Any <string>((string t) => StringUtility.EqualsIgnoreCase(t, user.get_ObjectType()))))
                    {
                        if ((additionalOwner.get_AttributeCollection() == null ? false : additionalOwner.get_AttributeCollection().ContainsKey("XOwnershipType")))
                        {
                            Enum.TryParse <MembershipType>(additionalOwner.get_AttributeCollection()["XOwnershipType"], out val);
                            if (val == 1)
                            {
                                attribute = additionalOwner;
                                return(attribute);
                            }
                        }
                        else
                        {
                            attribute = additionalOwner;
                            return(attribute);
                        }
                    }
                }
                attribute = null;
            }
            else
            {
                foreach (Imanami.GroupID.DataTransferObjects.DataContracts.Services.Attribute additionalOwner in additionalOwners)
                {
                    if ((additionalOwner.get_AttributeCollection() == null ? false : additionalOwner.get_AttributeCollection().ContainsKey("XOwnershipType")))
                    {
                        Enum.TryParse <MembershipType>(additionalOwner.get_AttributeCollection()["XOwnershipType"], out val);
                        if (val == 1)
                        {
                            attribute = additionalOwner;
                            return(attribute);
                        }
                    }
                    else
                    {
                        attribute = additionalOwner;
                        return(attribute);
                    }
                }
                attribute = null;
            }
            return(attribute);
        }
Example #58
0
 private ILookup <string, XmlElementValue> EnsureLookup()
 {
     return(this.nameLookup ?? (this.nameLookup = this.values.ToLookup(value => value.Name)));
 }
        public string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap)
        {
            if (odataPath.PathTemplate != "~/entityset/key/property")
            {
                return null;
            }

            var entitySetPathSegment = odataPath.Segments.OfType<EntitySetPathSegment>().Single();
            var keyValuePathSegment = odataPath.Segments.OfType<KeyValuePathSegment>().Single();
            var propertyAccessPathSegment = odataPath.Segments.OfType<PropertyAccessPathSegment>().Single();

            var actionName = string.Format(CultureInfo.InvariantCulture, "GetPropertyFrom{0}", entitySetPathSegment.EntitySetName);

            if (actionMap.Contains(actionName) && actionMap[actionName].Any(desc => MatchHttpMethod(desc, controllerContext.Request.Method)))
            {
                controllerContext.RouteData.Values.Add("propertyName", propertyAccessPathSegment.PropertyName);

                if (!CompositeODataKeyHelper.TryEnrichRouteValues(keyValuePathSegment.Value, controllerContext.RouteData.Values))
                {
                    controllerContext.RouteData.Values.Add("key", keyValuePathSegment.Value);
                }

                return actionName;
            }

            return null;
        }
        private static async Task WriteLinksAsync(IDictionary<string, int> zones, ILookup<string, string> aliases)
        {
            var cs = ConfigurationManager.ConnectionStrings["tzdb"].ConnectionString;
            using (var connection = new SqlConnection(cs))
            {
                var command = new SqlCommand("[Tzdb].[AddLink]", connection) { CommandType = CommandType.StoredProcedure };
                command.Parameters.Add("@LinkZoneId", SqlDbType.Int);
                command.Parameters.Add("@CanonicalZoneId", SqlDbType.Int);

                await connection.OpenAsync();

                foreach (var alias in aliases)
                {
                    var canonicalId = zones[alias.Key];
                    foreach (var link in alias)
                    {
                        command.Parameters[0].Value = zones[link];
                        command.Parameters[1].Value = canonicalId;
                        await command.ExecuteNonQueryAsync();
                    }
                }

                connection.Close();
            }
        }