/// <summary></summary>
		public ClientWorkflowInvoker(IDictionary properties, IClientChannelSinkProvider clientSinkProvider) 
		{	
			try 
			{	
                // configuration file
			    if(properties.Contains("timeout"))
                    _TimeOut = Convert.ToInt32(properties["timeout"]);
                if (properties.Contains("name"))
                    _ChannelName = Convert.ToString(properties["name"]);
                if (properties.Contains("callcontextActor"))
                    _CallContextActor = Convert.ToString(properties["callcontextActor"]);
             
				// channel provider
				_Provider = clientSinkProvider == null ? new BinaryClientFormatterSinkProvider() : clientSinkProvider;

				// add the ClientWorkflowInvokerProvider at the end
				IClientChannelSinkProvider provider = _Provider;
                while (provider.Next != null)
                {
                    provider = provider.Next;
                }
				provider.Next = new ClientWorkflowInvokerProvider();
			}
			catch(Exception ex) 
			{
                Trace.WriteLine(ex);
			}
		}
        public AndroidNotificationPayload(IDictionary _payloadDict)
        {
            AndroidProperties		= new AndroidSpecificProperties();

            // Alert
            if (_payloadDict.Contains(NPSettings.Notification.Android.ContentTextKey))
            {
                //Check here which key is being received.
                Console.Log(Constants.kDebugTag, "[BillingTransaction] " + _payloadDict.ToJSON());//TODO
                object _alertUnknownType	= _payloadDict[ContentTextKey] as object;

                // String type
                if ((_alertUnknownType as string) != null)
                {
                    AlertBody	= _alertUnknownType as string;
                }
            }

            if (_payloadDict.Contains(UserInfoKey))
                UserInfo		= _payloadDict[UserInfoKey] as IDictionary;

            // Fire date
            long _secsFromNow	= _payloadDict.GetIfAvailable<long>(kFireDate);

            FireDate			= _secsFromNow.ToDateTimeFromJavaTime();

            // Sound, Badge
            AndroidProperties.ContentTitle		=  	_payloadDict.GetIfAvailable<string>(ContentTitleKey);
            AndroidProperties.TickerText		=  	_payloadDict.GetIfAvailable<string>(TickerTextKey);
            AndroidProperties.Tag				=  	_payloadDict.GetIfAvailable<string>(TagKey);

            //Added in 1.03
            AndroidProperties.CustomSound		= 	_payloadDict.GetIfAvailable<string>(kCustomSound);
            AndroidProperties.LargeIcon			= 	_payloadDict.GetIfAvailable<string>(kLargeIcon);
        }
    public void postAction(string actionId, IDictionary actionProperties, string objectId,
                           IDictionary objectProperties, string objectInstanceId = null,
                           CarrotRequestResponse callback = null)
    {
        if(string.IsNullOrEmpty(objectId))
        {
            throw new ArgumentNullException("objectId must not be null or empty string.", "objectId");
        }

        if(string.IsNullOrEmpty(actionId))
        {
            throw new ArgumentNullException("actionId must not be null or empty string.", "actionId");
        }

        if(objectProperties == null)
        {
            throw new ArgumentNullException("objectProperties must not be null.", "objectProperties");
        }
        else if(!objectProperties.Contains("title") ||
                !objectProperties.Contains("description") ||
                !objectProperties.Contains("image"))
        {
            throw new ArgumentException("objectProperties must contain keys for 'title', 'description', and 'image'.", "objectProperties");
        }

        objectProperties["object_type"] = objectId;
        if(!string.IsNullOrEmpty(objectInstanceId)) objectProperties["object_instance_id"] = objectInstanceId;
        Dictionary<string, object> parameters = new Dictionary<string, object>() {
            {"action_id", actionId},
            {"action_properties", actionProperties == null ? new Dictionary<string, object>() : actionProperties},
            {"object_properties", objectProperties}
        };
        StartCoroutine(cachedRequestCoroutine(ServiceType.Post, "/me/actions.json", parameters, callback));
    }
示例#4
0
 /// <summary> Returns a value cast to a specific type
 /// *
 /// </summary>
 /// <param name="aBrc">- The BRERuleContext object
 /// </param>
 /// <param name="aMap">- The IDictionary of parameters from the XML
 /// </param>
 /// <param name="aStep">- The step that it is on
 /// </param>
 /// <returns> The value cast to the specified type
 /// 
 /// </returns>
 public object ExecuteRule(IBRERuleContext aBrc, IDictionary aMap, object aStep)
 {
     bool staticCall = false;
     if (!aMap.Contains(OBJECTID))
     {
         if (!aMap.Contains(TYPE))
             throw new BRERuleException("Parameter 'Type' or 'ObjectId' not found");
         else staticCall = true;
     }
     if (!aMap.Contains(MEMBER))
     {
         throw new BRERuleException("Parameter 'Member' not found");
     }
     else
     {
         if (staticCall)
             return Reflection.ClassCall((string)aMap[TYPE],
                                            (string)aMap[MEMBER],
                                            GetArguments(aMap));
         else
             return Reflection.ObjectCall(aBrc.GetResult(aMap[OBJECTID]).Result,
                                            (string)aMap[MEMBER],
                                            GetArguments(aMap));
     }
 }
示例#5
0
 public string Get(string key)
 {
     if (_dict?.Contains(key) == true)
     {
         return(_dict[key]?.ToString());
     }
     return(null);
 }
示例#6
0
 /// <summary>
 /// Drops the BackgroundImage property
 /// </summary>
 /// <param name="properties">properties to remove BackGroundImage from</param>
 protected override void PreFilterProperties(IDictionary properties)
 {
     base.PreFilterProperties(properties);
     if (properties.Contains("BackgroundImage"))
         properties.Remove("BackgroundImage");
     if (properties.Contains("DrawGrid"))
         properties.Remove("DrawGrid");
 }
	public void InitializeData(IDictionary JSON) {

		

		if(JSON.Contains("id")) {
			_id 								= System.Convert.ToString(JSON["id"]);
		}


		if(JSON.Contains("birthday")) {
			_Birthday 							=DateTime.Parse(System.Convert.ToString(JSON["birthday"])); 
		}


		if(JSON.Contains("name")) {
			_name 								= System.Convert.ToString(JSON["name"]);
		}

		if(JSON.Contains("first_name")) {
			_first_name 								= System.Convert.ToString(JSON["first_name"]);
		}

		if(JSON.Contains("last_name")) {
			_last_name 								= System.Convert.ToString(JSON["last_name"]);
		}

		if(JSON.Contains("username")) {
			_username 								= System.Convert.ToString(JSON["username"]);
		}

		if(JSON.Contains("link")) {
			_profile_url 								= System.Convert.ToString(JSON["link"]);
		}

		if(JSON.Contains("email")) {
			_email 								= System.Convert.ToString(JSON["email"]);
		}

		if(JSON.Contains("locale")) {
			_locale 								= System.Convert.ToString(JSON["locale"]);
		}

		if(JSON.Contains("location")) {
			IDictionary loc = JSON["location"] as IDictionary;
			_location							= System.Convert.ToString(loc["name"]);
		}

		if(JSON.Contains("gender")) {
			string g = System.Convert.ToString(JSON["gender"]);
			if(g.Equals("male")) {
				_gender = FB_Gender.Male;
			} else {
				_gender = FB_Gender.Female;
			}
		}


	}
示例#8
0
        public DynamoErrorLog(IDictionary config)
        {
            if (config == null)
                throw new ArgumentNullException("config");
            if (!config.Contains("applicationName"))
                throw new InvalidOperationException("'applicationName' attribute missing from Elmah config");
            string appName = (string)config["applicationName"];
            ApplicationName = appName;

            if (config.Contains("tableName"))
                s_TableName = (string)config["tableName"];
        }
示例#9
0
 private static double GetScaleMeters(IDictionary source, string key, IFactory factory)
 {
     var lengthMeters = Node.Net.Factories.Extension.IDictionaryExtension.GetLengthMeters(source, key);
     if (source.Contains(key)) return lengthMeters;
     if (key.Contains(","))
     {
         var keys = key.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
         foreach (var k in keys)
         {
             if (source.Contains(k)) return lengthMeters;
         }
     }
     return 1;
 }
示例#10
0
		public bool Accept(String name, IDictionary options, TextWriter writer)
		{
			if (!"project".Equals(name))
			{
				return false;
			}
			else if (options.Count == 1)
			{
				writer.WriteLine("Creates a new VS.Net 2003 project structure");
				writer.WriteLine("");
				writer.WriteLine("name     : Project name");
				writer.WriteLine("outdir   : Target directory (must exists)");
				writer.WriteLine("windsor  : [Optional] Enable WindsorContainer Integration");
				writer.WriteLine("view     : [Optional] aspnet|nvelocity (defaults to nvelocity)");
				writer.WriteLine("lang     : [Optional] c#|vb.net (defaults to c#)");
				writer.WriteLine("");
				writer.WriteLine("Example:");
				writer.WriteLine("");
				writer.WriteLine(@"> generator project name:My.CoR.Project windsor outdir:c:\temp");
				writer.WriteLine("");

				return false;
			}
			else if (!options.Contains("outdir"))
			{
				writer.WriteLine("outdir must be specified");
				
				return false;
			}
			else if (!options.Contains("name"))
			{
				writer.WriteLine("name must be specified");
				
				return false;
			}
			else 
			{
				DirectoryInfo info = new DirectoryInfo(options["outdir"] as String);

				if (!info.Exists)
				{
					// info.Create(); // Is it safe to use it?
					writer.WriteLine("Error: The specified outdir does not exists.");

					return false;
				}
			}

			return true;
		}
示例#11
0
        /// <summary> If passed the parameter Increment it will increment the index.
        /// Otherwise it will just return the current value of the index
        /// *
        /// </summary>
        /// <param name="aBrc">- The BRERuleContext object
        /// </param>
        /// <param name="aMap">- The IDictionary of parameters from the XML
        /// </param>
        /// <param name="aStep">- The step that it is on
        /// </param>
        /// <returns> The current value of the increment
        /// 
        /// </returns>
        public object ExecuteRule(IBRERuleContext aBrc, IDictionary aMap, object aStep)
        {
            if (aMap.Contains(INCREMENT))
                sIdx = sIdx + Int32.Parse((string) aMap[INCREMENT]);

            return sIdx;
        }
示例#12
0
 public void Contains(IDictionary dic)
 {
     foreach (DictionaryEntry de in dic)
     {
         bool b = dic.Contains(de.Key);
     }
 }
示例#13
0
 public static void Send(String to, String body, String Subject, IDictionary replacements = null)
 {
     init();
     char[] c = { ',', ';', ':' };
     String[] To = to.Split(c);
     for (int i = 0; i < To.Length; i++)
     {
         MailDefinition m = new MailDefinition();
         if (!replacements.Contains("\n"))
         {
             replacements.Add("\n", "<br/>");
         }
         m.IsBodyHtml = true;
         m.Subject = Subject;
         m.From = "*****@*****.**";
         try
         {
             mails.AddLast(m.CreateMailMessage(To[i], replacements, body, new System.Web.UI.Control()));
         }
         catch (Exception)//TODO
         { };
     }
     if (!isSending)
     {
         next(null, null);
     }
 }
示例#14
0
        public static void SendNew(String to, String body, String Subject, IDictionary replacements = null)
        {
            init();
            if (replacements.Contains("%webkey%"))
            {
                replacements.Remove("%webkey%");
            }
            String webkey;
            webkey = stored.NewWebkey(to);
            WWebkey key = new WWebkey(new webkeysets() { ConnectionKey = webkey, Status="actief" });
            key.add(key.getSet());

            System.Reflection.Assembly thisExe = System.Reflection.Assembly.GetExecutingAssembly();
            string path = thisExe.Location;
            DirectoryInfo dirinfo = new DirectoryInfo(path);
            string folderName = dirinfo.Parent.FullName;
            path = folderName + "\\Config.txt";
            Uri uri = new Uri(path);
            String s = File.ReadAllText(uri.AbsolutePath);
            String[] split = { "server: " };
            String[] server = s.Split(split, StringSplitOptions.RemoveEmptyEntries);
            webkey = server[0] + webkey;
            replacements.Add("%webkey%", "<a href='" + webkey + "'>" + webkey + "</a>");
            Send(to, body, Subject, replacements);
        }
        private void DoCreateStandardAttributeTable(IDictionary parameters, IDictionary std)
        {
            // contentType will be absent if we're trying to generate a counter signature.
            if (parameters.Contains(CmsAttributeTableParameter.ContentType))
            {
                if (!std.Contains(CmsAttributes.ContentType))
                {
                    DerObjectIdentifier contentType = (DerObjectIdentifier)
                        parameters[CmsAttributeTableParameter.ContentType];
                    Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.ContentType,
                        new DerSet(contentType));
                    std[attr.AttrType] = attr;
                }
            }

            if (!std.Contains(CmsAttributes.SigningTime))
            {
                Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.SigningTime,
                    new DerSet(new Time(DateTime.UtcNow)));
                std[attr.AttrType] = attr;
            }

            if (!std.Contains(CmsAttributes.MessageDigest))
            {
                byte[] messageDigest = (byte[])parameters[CmsAttributeTableParameter.Digest];
                Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(CmsAttributes.MessageDigest,
                    new DerSet(new DerOctetString(messageDigest)));
                std[attr.AttrType] = attr;
            }
        }
示例#16
0
        public static void SendNew(String to, String body, String Subject, String hetType, IDictionary replacements = null)
        {
            init();
            if (replacements.Contains("%webkey%"))
            {
                replacements.Remove("%webkey%");
            }

            // Webkey aanmaken
            String key;
            key = stored.NewWebkey(to);

            // In database is het leraar, in de webview docent (freakytime aanpassing)
            String webkeyType = "student";
            if (hetType.Equals("docent"))
            {
                webkeyType = "leraar";
            }

            webkeys webkey = new webkeys() { webkey = key, type = webkeyType, email = to };

            // Webkey opslaan in database
            WStored.StageManagerEntities.webkeys.Add(webkey);
            WStored.PushToDB();

            // construct URL
            key = "http://stagemanager.modupro.nl/" + hetType + "/" + webkey.webkey;
            replacements.Add("%webkey%", "<a href='" + key + "'>" + key + "</a>");

            // Send
            Send(to, body, Subject, replacements);
        }
示例#17
0
		/// <summary>
		/// Returns name of Cache from the property map.
		/// </summary>
		/// <param name="properties">properties map</param>
		/// <returns>cache name.</returns>
		static private CacheInfo GetCacheInfo(IDictionary properties)
		{
			if(!properties.Contains("cache"))
				throw new ConfigurationException("Missing configuration attribute 'cache'");

			CacheInfo inf = new CacheInfo();
			IDictionary cacheConfig = (IDictionary)properties[ "cache" ];

			string schemeName = "";
			if(cacheConfig.Contains("name"))
				inf.Name = Convert.ToString(cacheConfig["name"]).Trim();

			if(!cacheConfig.Contains("class"))
				throw new ConfigurationException("Missing configuration attribute 'class'");
				
			schemeName = Convert.ToString(cacheConfig[ "class" ]);
			if(inf.Name.Length < 1)
				inf.Name = schemeName;

			if(!cacheConfig.Contains("cache-classes"))
				throw new ConfigurationException("Missing configuration section 'cache-classes'");
			IDictionary cacheClasses = (IDictionary)cacheConfig[ "cache-classes" ];
			
			if(!cacheClasses.Contains(schemeName.ToLower()))
                throw new ConfigurationException("Cannot find cache class '" + schemeName + "'");
			IDictionary schemeProps = (IDictionary)cacheClasses[ schemeName.ToLower() ];

			if(!schemeProps.Contains("type"))
                throw new ConfigurationException("Cannot find the type of cache, invalid configuration for cache class '" + schemeName + "'");

			inf.ClassName = Convert.ToString(schemeProps["type"]);
			return inf;
		}
 private void AddRemoveCorrelationToken(Type interfaceType, IDictionary properties, object corrRefProperty)
 {
     if (interfaceType != null)
     {
         object[] corrProvAttribs = interfaceType.GetCustomAttributes(typeof(CorrelationProviderAttribute), false);
         object[] corrParamAttribs = interfaceType.GetCustomAttributes(typeof(CorrelationParameterAttribute), false);
         if (corrProvAttribs.Length != 0 || corrParamAttribs.Length != 0)
         {
             if (!properties.Contains("CorrelationToken"))
                 properties.Add("CorrelationToken", corrRefProperty);
             return;
         }
     }
     if (properties.Contains("CorrelationToken"))
         properties.Remove("CorrelationToken");
 }
示例#19
0
		public static string GetRestActionName(string action, IDictionary actions, string httpMethod)
		{
			if (IsCollectionAction(action))
			{
				switch (httpMethod.ToUpper())
				{
					case "GET":
						return "Index";						
					case "POST":
						return "Create";
				}
			}

			if (IsNewAction(action))
			{
				return "New";
			}

			if (!actions.Contains(action))
			{
				switch (httpMethod.ToUpper())
				{
					case "GET":
						return "Show";
					case "PUT":
						return "Update";
					case "DELETE":
						return "Destroy";						
				}
			}

			return null;
		}
        public void TestContains()
        {
            dictionary = new Dictionary<string, int>();
            string[] names = { "Cero", "Uno", "Dos", "Tres", "Cuatro", "Cinco" };
            //int[] numbers = (from i in Enumerable.Range(0, 6).ToArray() select i).ToArray();

            for (int i = 0; i < 6; i++)
            {
                dictionary.Add(names[i], i);

            }

            Assert.AreEqual(true, dictionary.Contains(new KeyValuePair<string, int>("Cero", 0)));
            Assert.AreEqual(false, dictionary.Contains(new KeyValuePair<string, int>("Cero", 2)));
            Assert.AreEqual(false, dictionary.Contains(new KeyValuePair<string, int>("Once", 0)));
        }
        public XmlDocument Run(IDictionary context)
        {
            if (context == null || !context.Contains("Project"))
            {
                return Descriptor;
            }

            Project = (Project)context["Project"];

            foreach (var table in Project.Database.Tables)
            {
                foreach (var column in table.Columns)
                {
                    if (column.Property == null || !MustStoreAsText(column))
                        continue;

                    var property = column.Property;
                    column.DbType = System.Data.DbType.String;
                    column.Size = GetColumnSize(property);


                    // Change BaseSave method
                    // Example: persistence.AddParameterAsText("@Customer_Gender", this.Gender, SoftFluent.Samples.Gender.Male);
                    property.SetAttributeValue(Constants.ModelProducerNamespacePrefix, "addParameterMethodName", Constants.ModelProducerNamespaceUri, "AddParameterAsText");

                    // Change ReadRecord method
                    // Example: this._gender = CodeFluentPersistence.GetReaderValue(reader, "Customer_Gender", Gender.Male);
                    var readerExpression = string.Format("CodeFluentPersistence.GetReaderValue(reader, \"{1}\", {2})", property.ClrFullTypeName, property.Column.Name, property.DefaultValue);
                    column.Property.SetAttributeValue(Constants.ModelProducerNamespacePrefix, "readValueExpression", Constants.ModelProducerNamespaceUri, readerExpression);
                }
            }

            return Descriptor;
        }
示例#22
0
文件: DBHelper.cs 项目: dayletter/103
    public static DataRow Insert(string tableName, IDictionary input)
    {
        var helper = DBHelper.GetTable(tableName);
        var row = helper.Table.NewRow();
        var cols = helper.Table.Columns.Cast<DataColumn>();

        try
        {
            foreach (var col in cols)
            {
                if (!col.AutoIncrement && input.Contains(col.ColumnName))
                {
                    row[col] = input[col.ColumnName] as object ?? DBNull.Value;
                }
            }

            helper.Table.Rows.Add(row);
            helper.Adapter.Update(helper.Table);
            // quick dirty fix for auto-increment value problem
            helper.Table.Clear();
            helper.Adapter.Fill(helper.Table);
            return helper.Table.AsEnumerable().Last();
            //return row;
        }
        catch (Exception ex)
        {
            row.RejectChanges();
            throw ex;
        }
    }
示例#23
0
        /// <summary>
        /// Overloaded constructor. Takes the properties as a map.
        /// </summary>
        /// <param name="cacheSchemes">collection of cache schemes (config properties).</param>
        /// <param name="properties">properties collection for this cache.</param>
        /// <param name="listener">cache events listener</param>
        /// <param name="timeSched">scheduler to use for periodic tasks</param>
        public IndexedLocalCache(IDictionary cacheClasses, CacheBase parentCache, IDictionary properties, ICacheEventsListener listener, CacheRuntimeContext context)
            : base(cacheClasses, parentCache, properties, listener, context)
        {
            IDictionary props = null;
            if (properties.Contains("indexes"))
            {
                props = properties["indexes"] as IDictionary;
            }

            _queryIndexManager = new QueryIndexManager(props, this, _context.CacheRoot.Name);
            if (!_queryIndexManager.Initialize()) _queryIndexManager = null;


            //+Numan16122014
            _cacheStore.ISizableQueryIndexManager = _queryIndexManager;            
            _cacheStore.ISizableEvictionIndexManager = _evictionPolicy;
            _cacheStore.ISizableExpirationIndexManager = _context.ExpiryMgr;

            _stats.MaxCount = _cacheStore.MaxCount;
            _stats.MaxSize = _cacheStore.MaxSize;

            //+Numan16122014

            if (_context.PerfStatsColl != null)
            {
                if (_queryIndexManager != null)
                    _context.PerfStatsColl.SetQueryIndexSize(_queryIndexManager.IndexInMemorySize);                
            }
        }
		protected void AssertKeyExists( IDictionary names, NodeBase node, object key, String message )
		{
			if (!names.Contains(key))
			{
				RaiseErrorEvent( node.LexicalInfo, message );
			}
		}
 public IDictionary Convert(IDictionary source)
 {
     if (source != null && source.Contains(nameof(Type)))
     {
         var type = source[nameof(Type)].ToString();
         if (Types != null && Types.ContainsKey(type))
         {
             try
             {
                 var _type = Types[type];
                 if (_type == null) throw new Exception($"Types['{type}'] was null");
                 var dictionary = Activator.CreateInstance(_type) as IDictionary;
                 if(dictionary == null)
                 {
                     throw new Exception($"unable to create instance of type {_type.FullName}");
                 }
                 Copy(source, dictionary);
                 return dictionary;
             }
             catch(Exception ex)
             {
                 throw new Exception($"Exception while converting type '{type}', fullname {Types[type].FullName}", ex);
             }
         }
         
     }
     if(source != null)
     {
         var result = Activator.CreateInstance(source.GetType()) as IDictionary;
         Copy(source, result);
         return result;
     }
     return source;
 }
示例#26
0
文件: Decrement.cs 项目: Ghasan/NxBRE
 /// <summary> If passed the parameter Decrement it will decrement the index.
 /// Otherwise it will just return the current value of the index
 /// *
 /// </summary>
 /// <param name="aBrc">- The BRERuleContext object
 /// </param>
 /// <param name="aMap">- The IDictionary of parameters from the XML
 /// </param>
 /// <param name="aStep">- The step that it is on
 /// </param>
 /// <returns> The current value of the index
 /// 
 /// </returns>
 public virtual object ExecuteRule(IBRERuleContext aBrc, IDictionary aMap, object aStep)
 {
     if (aMap.Contains(DECREMENT))
     {
         sIdx = sIdx - System.Int32.Parse((System.String) aMap[DECREMENT]);
     }
     return sIdx;
 }
示例#27
0
        public BlobErrorLog(IDictionary config)
        {
            if (!config.Contains("connectionStringName"))
                throw new System.ApplicationException("Configuration string is missing for the Windows Azure Blob Storage Error Log.");

            this.connectionStringName = (string)config["connectionStringName"];
            this.Initialize();
        }
 /// <summary>
 /// Helper method to get a key that doesn't already exist within the dictionary
 /// </summary>
 /// <param name="dictionary"></param>
 protected object GetNewKey(IDictionary dictionary)
 {
     int seed = 840;
     object missingKey = CreateTKey(seed++);
     while (dictionary.Contains(missingKey) || missingKey.Equals(null))
         missingKey = CreateTKey(seed++);
     return missingKey;
 }
示例#29
0
		public DictionaryScope(IDictionary dictionary, object key, object value)
        {
            if (dictionary.Contains(key))
				previousValue = dictionary[key];
			dictionary[key] = value;
            this.key = key;
            this.dictionary = dictionary;
		}
示例#30
0
 /// <summary> Returns a value cast to a specific type
 /// *
 /// </summary>
 /// <param name="aBrc">- The BRERuleContext object
 /// </param>
 /// <param name="aMap">- The IDictionary of parameters from the XML
 /// </param>
 /// <param name="aStep">- The step that it is on
 /// </param>
 /// <returns> The value cast to the specified type
 /// 
 /// </returns>
 public object ExecuteRule(IBRERuleContext aBrc, IDictionary aMap, object aStep)
 {
     if (!aMap.Contains(TYPE))
     {
         throw new BRERuleException("Parameter 'Type' not found");
     }
     else
     {
         if (!aMap.Contains(VALUE))
         {
             ObjectLookup ol = new ObjectLookup();
             object[] arguments = ol.GetArguments(aMap);
             return Reflection.ClassNew((string)aMap[TYPE], arguments);
         }
         return Reflection.CastValue(aMap[VALUE], (string)aMap[TYPE]);
     }
 }
        public XmlDocument Run(IDictionary context)
        {
            if (context == null || !context.Contains("Project"))
                return Descriptor;

            Project = (Project)context["Project"];
            Project.StepChanging += Project_StepChanging;
            return Descriptor;
        }
示例#32
0
        public static string GetFullName(this object instance)
        {
            IDictionary?metaData = Internal.MetaData.Default.GetMetaData(instance);

            if (metaData?.Contains("FullName") == true)
            {
#pragma warning disable CS8603 // Possible null reference return.
#pragma warning disable CS8602 // Dereference of a possibly null reference.
                return(metaData["FullName"].ToString());

#pragma warning restore CS8602 // Dereference of a possibly null reference.
#pragma warning restore CS8603 // Possible null reference return.
            }

            return(string.Empty);
        }
示例#33
0
        internal static TemplateSearchCache ConvertTemplateDiscoveryMetadata(TemplateDiscoveryMetadata discoveryMetadata, IReadOnlyDictionary <string, Func <object, object> >?additionalDataReaders)
        {
            List <TemplatePackageSearchData> packageData = new List <TemplatePackageSearchData>();

            foreach (var package in discoveryMetadata.PackToTemplateMap)
            {
                List <TemplateSearchData> templateData = new List <TemplateSearchData>();
                foreach (var template in package.Value.TemplateIdentificationEntry)
                {
                    var foundTemplate = discoveryMetadata.TemplateCache.FirstOrDefault(t => t.Identity.Equals(template.Identity, StringComparison.OrdinalIgnoreCase));
                    if (foundTemplate == null)
                    {
                        continue;
                    }
                    if (additionalDataReaders != null)
                    {
                        Dictionary <string, object> data = new Dictionary <string, object>();
                        foreach (var reader in additionalDataReaders)
                        {
                            if (discoveryMetadata.AdditionalData.TryGetValue(reader.Key, out object?legacyData))
                            {
                                IDictionary?dict = legacyData as IDictionary;
                                if (dict?.Contains(template.Identity) ?? false)
                                {
                                    data[reader.Key] = dict[template.Identity];
                                }
                            }
                        }
                        templateData.Add(new TemplateSearchData(foundTemplate, data));
                    }
                    else
                    {
                        templateData.Add(new TemplateSearchData(foundTemplate));
                    }
                }
                packageData.Add(new TemplatePackageSearchData(new PackInfo(package.Key, package.Value.Version, package.Value.TotalDownloads, package.Value.Owners, package.Value.Verified), templateData));
            }
            return(new TemplateSearchCache(packageData));
        }
示例#34
0
        private GeometryModel3D CreateFromDictionary(IDictionary source)
        {
            if (source == null)
            {
#pragma warning disable CS8603 // Possible null reference return.
                return(null);

#pragma warning restore CS8603 // Possible null reference return.
            }

            if (ParentFactory != null && source?.Contains("Type") == true)
            {
#pragma warning disable CS8602 // Dereference of a possibly null reference.
                string?type = source["Type"].ToString();
#pragma warning restore CS8602 // Dereference of a possibly null reference.
#pragma warning disable CS8602 // Dereference of a possibly null reference.
                if (type.Length > 0)
#pragma warning restore CS8602 // Dereference of a possibly null reference.
                {
                    string?         name            = $"GeometryModel3D.{type}.xaml";
                    GeometryModel3D?geometryModel3D = ParentFactory.Create <GeometryModel3D>(name);
                    if (geometryModel3D != null)
                    {
                        return(geometryModel3D);
                    }

                    MeshGeometry3D?mesh = ParentFactory.Create <MeshGeometry3D>(source);
                    if (mesh != null)
                    {
                        return(CreateFromMeshGeometry3D(mesh));
                    }
                }
            }

#pragma warning disable CS8603 // Possible null reference return.
            return(null);

#pragma warning restore CS8603 // Possible null reference return.
        }
示例#35
0
        /// <summary>
        /// Configures the passed JSON Patch so that it yields modified when applied to original
        /// - Adding fields to the patch present in modified, missing from original
        /// - Setting fields to the patch present in modified and original with different values
        /// - Delete fields present in original, missing from modified through
        /// - IFF map field - set to nil in patch ???
        /// - IFF list of maps && merge strategy - use deleteDirective for the elements ???
        /// - IFF list of primitives && merge strategy - use parallel deletion list ???
        /// - IFF list of maps or primitives with replace strategy (default) - set patch value to the value in modified ???
        /// - Build $retainKeys directive for fields with retainKeys patch strategy ???
        /// </summary>
        /// <param name="original">The original object</param>
        /// <param name="modified">The modified object</param>
        /// <param name="type">The type that original and modified represent (even if they are not actually that type, but a PSObject)</param>
        /// <param name="path">The JSON pointer to the currently inspected values</param>
        /// <param name="mergeStrategy">The strategy to use for patching (replace or merge with mergeKey)</param>
        public void CreateTwoWayPatch(object original, object modified, Type type, JsonPatchDocument patch, string path = "", MergeStrategyAttribute mergeStrategy = null, bool ignoreDeletions = false, bool ignoreAdditionsAndModifications = false)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (patch == null)
            {
                throw new ArgumentNullException(nameof(patch));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            logger.LogTrace($"Path: {path}");
            if (modified == null && original == null)
            {
                return;
            }
            if (modified == null && original != null)
            {
                if (!ignoreDeletions)
                {
                    patch.Replace(path, modified);
                }
                return;
            }
            if (original == null && modified != null)
            {
                if (!ignoreAdditionsAndModifications)
                {
                    patch.Replace(path, modified);
                }
                return;
            }

            // From this point, original and modified are known to be non-null

            logger.LogTrace($"Type: original {original?.GetType().Name} modified {modified?.GetType().Name} expected {type?.Name}");

            // string, int, float, bool, enum, DateTime
            if (modified is string || type.IsValueType)
            {
                logger.LogTrace($"Is value type, comparing {original} <-> {modified}");
                // Replace if changed, otherwise do nothing
                // We NEED to use Equals() here instead of != because the static type is object, meaning the scalar is boxed.
                // Since operators are resolved at compile time, this would use the == implementation for object,
                // while Equals() is dynamically dispatched on the real boxed type.
                if (!original.Equals(modified))
                {
                    patch.Replace(path, modified);
                }
                return;
            }

            // From this point, original and modified are known to be reference types

            if (System.Object.ReferenceEquals(original, modified))
            {
                // Same object, short cut
                return;
            }

            if (modified is IList)
            {
                logger.LogTrace("Is List");
                Type valueType = type.GetGenericArguments()[0];
                // Handle lists
                // Really just casting to generic IEnumerable get access to more LINQ. It's all object anyway.
                IEnumerable <object> originalEnumerable = ((IList)original).Cast <object>();
                IEnumerable <object> modifiedEnumerable = ((IList)modified).Cast <object>();
                // Check if the list property has a strategic merge strategy attribute
                if (mergeStrategy != null)
                {
                    if (mergeStrategy.Key != null)
                    {
                        logger.LogTrace("List is unordered set keyed by merge key");
                        // The lists are to be treated like dictionaries, keyed by Key
                        logger.LogTrace($"Merge key: {mergeStrategy.Key}");
                        Func <object, object> keySelector = listElement => {
                            PropertyInfo mergeProperty = ModelHelpers.FindJsonProperty(valueType, mergeStrategy.Key);
                            object       value         = listElement.GetDynamicPropertyValue(mergeProperty.Name);
                            if (value == null)
                            {
                                throw new Exception($"Merge key {mergeProperty} on type {valueType.FullName} cannot be null");
                            }
                            logger.LogTrace($"Merge property value: {value}");
                            return(value);
                        };
                        // The merge key value is *not* guaranteed to be string,
                        // for example ContainerPortV1 has the merge key ContainerPort which is type int
                        Dictionary <object, object> originalDict = originalEnumerable.ToDictionary(keySelector);
                        Dictionary <object, object> modifiedDict = modifiedEnumerable.ToDictionary(keySelector);
                        var removeOperations = new List <Action>();
                        int index            = 0;
                        foreach (var originalElement in originalEnumerable)
                        {
                            object elementKey  = originalElement.GetDynamicPropertyValue(ModelHelpers.FindJsonProperty(valueType, mergeStrategy.Key).Name);
                            string elementPath = path + "/" + index;
                            if (!modifiedDict.ContainsKey(elementKey))
                            {
                                if (!ignoreDeletions)
                                {
                                    // Entry removed in modified
                                    // Check that the value at the given index is really the value we want to modify,
                                    // to make sure indexes were not modified on the server
                                    // Queue these up because they shift array indexes around and for simplicity we want to get the modifications add first
                                    // This makes the patch easier to reason about.
                                    removeOperations.Add(() => patch.Test(elementPath + "/" + escapeJsonPointer(mergeStrategy.Key), elementKey));
                                    removeOperations.Add(() => patch.Remove(elementPath));
                                }
                            }
                            else
                            {
                                // Entry present in both, merge recursively
                                patch.Test(elementPath + "/" + escapeJsonPointer(mergeStrategy.Key), elementKey);
                                var countBefore = patch.Operations.Count;
                                CreateTwoWayPatch(
                                    original: originalElement,
                                    modified: modifiedDict[elementKey],
                                    type: valueType,
                                    patch: patch,
                                    path: elementPath,
                                    ignoreDeletions: ignoreDeletions,
                                    ignoreAdditionsAndModifications: ignoreAdditionsAndModifications
                                    );
                                if (patch.Operations.Count == countBefore)
                                {
                                    // Test was not needed, element was not modified
                                    patch.Operations.RemoveAt(patch.Operations.Count - 1);
                                }
                            }
                            index++;
                        }
                        // Modifications are done, add remove operations
                        foreach (var action in removeOperations)
                        {
                            action();
                        }
                        if (!ignoreAdditionsAndModifications)
                        {
                            // Entries added in modified
                            foreach (var modifiedEntry in modifiedDict)
                            {
                                if (!originalDict.ContainsKey(modifiedEntry.Key))
                                {
                                    // An element that was added in modified
                                    patch.Add(path + "/-", modifiedEntry.Value);
                                }
                            }
                        }
                    }
                    else
                    {
                        logger.LogTrace("List is unordered set");
                        // Lists are to be treated like unordered sets
                        HashSet <object> originalSet = originalEnumerable.ToHashSet();
                        HashSet <object> modifiedSet = modifiedEnumerable.ToHashSet();
                        // The index to adress the element on the server after applying every operation in the patch so far.
                        int index = 0;
                        foreach (var originalElement in originalEnumerable)
                        {
                            string elementPath = path + "/" + index;
                            if (!modifiedSet.Contains(originalElement))
                            {
                                // Deleted from modified
                                if (!ignoreDeletions)
                                {
                                    // When patching indexes, make sure elements didn't get moved around on the server
                                    // Can directly add them here because unordered sets do not use replace operations,
                                    // only remove and adding to the end
                                    patch.Test(elementPath, originalElement);
                                    patch.Remove(elementPath);
                                }
                            }
                            // Present in both: do nothing
                            index++;
                        }
                        if (!ignoreAdditionsAndModifications)
                        {
                            foreach (var modifiedElement in modifiedSet)
                            {
                                if (!originalSet.Contains(modifiedElement))
                                {
                                    // Added in modified
                                    patch.Add(path + "/-", modifiedElement);
                                }
                            }
                        }
                    }
                }
                else
                {
                    logger.LogTrace("List is ordered list");
                    // List is to be treated as an ordered list, e.g. ContainerV1.Command
                    List <object> originalList     = originalEnumerable.ToList();
                    List <object> modifiedList     = modifiedEnumerable.ToList();
                    var           removeOperations = new List <Action>();
                    int           index            = 0;
                    foreach (var originalElement in originalList.Take(modifiedList.Count))
                    {
                        string elementPath = path + "/" + index;
                        if (index >= modifiedList.Count)
                        {
                            // Not present in modified, remove
                            if (!ignoreDeletions)
                            {
                                removeOperations.Add(() => patch.Test(elementPath, originalElement));
                                removeOperations.Add(() => patch.Remove(elementPath));
                            }
                        }
                        else
                        {
                            // Present in both, merge recursively
                            // Add a test to check that indexes were not moved on the server
                            patch.Test(elementPath, originalElement);
                            int countBefore = patch.Operations.Count;
                            CreateTwoWayPatch(
                                original: originalElement,
                                modified: modifiedList[index],
                                type: valueType,
                                patch: patch,
                                path: elementPath,
                                ignoreDeletions: ignoreDeletions,
                                ignoreAdditionsAndModifications: ignoreAdditionsAndModifications
                                );
                            if (patch.Operations.Count == countBefore)
                            {
                                // Test was not needed, element was not modified
                                patch.Operations.RemoveAt(patch.Operations.Count - 1);
                            }
                        }
                        index++;
                    }
                    // Modifications are done, register remove operations
                    foreach (var action in removeOperations)
                    {
                        action();
                    }
                    // Continue on modifiedList (if it's longer) to add added elements
                    for (; index < modifiedList.Count; index++)
                    {
                        // Added in modifiedList
                        object addedElement = modifiedList[index];
                        patch.Add(path + "/-", addedElement);
                    }
                }
            }
            else if (modified is IDictionary)
            {
                logger.LogTrace("Is Dictionary");
                Type valueType = type.GetGenericArguments()[1];
                // Handle maps (e.g. KubeResourceV1.Annotations)
                IDictionary originalDict = (IDictionary)original;
                IDictionary modifiedDict = (IDictionary)modified;
                // Always merge maps
                foreach (DictionaryEntry originalEntry in originalDict)
                {
                    string entryKey   = (string)originalEntry.Key;
                    object entryValue = (object)originalEntry.Value;
                    string entryPath  = path + "/" + escapeJsonPointer(entryKey);
                    if (!modifiedDict.Contains(originalEntry.Key))
                    {
                        if (!ignoreDeletions)
                        {
                            // Entry removed in modified
                            patch.Remove(entryPath);
                        }
                    }
                    else
                    {
                        // Entry present in both, merge recursively
                        CreateTwoWayPatch(
                            original: entryValue,
                            modified: modifiedDict[originalEntry.Key],
                            type: valueType,
                            patch: patch,
                            path: entryPath,
                            ignoreDeletions: ignoreDeletions,
                            ignoreAdditionsAndModifications: ignoreAdditionsAndModifications
                            );
                    }
                }
                if (!ignoreAdditionsAndModifications)
                {
                    // Entries added in modified
                    foreach (DictionaryEntry modifiedEntry in modifiedDict)
                    {
                        string entryKey   = (string)modifiedEntry.Key;
                        object entryValue = (object)modifiedEntry.Value;
                        if (!originalDict.Contains(entryKey))
                        {
                            // An element that was added in modified
                            patch.Add(path + "/" + escapeJsonPointer(entryKey), entryValue);
                        }
                    }
                }
            }
            else
            {
                logger.LogTrace("Is other object");
                // resourceVersion: a string that identifies the internal version of this object that can be used by
                // clients to determine when objects have changed. This value MUST be treated as opaque by clients
                // and passed unmodified back to the server.
                // https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#metadata
                // Add this test before traversing into other properties
                if (type.IsSubclassOf(typeof(KubeResourceV1)))
                {
                    var resourceVersion = (string)original.GetDynamicPropertyValue("Metadata")?.GetDynamicPropertyValue("ResourceVersion");
                    if (!String.IsNullOrEmpty(resourceVersion))
                    {
                        patch.Test(path + "/metadata/resourceVersion", resourceVersion);
                    }
                }
                // Warn if properties were passed that are not recognized to highlight mistakes
                foreach (var propName in modified.GetDynamicPropertyNames().Where(name => type.GetProperty(name) == null))
                {
                    logger.LogWarning($"Unknown property \"{propName}\" on {type.Name} at path \"{path}\"");
                }
                // KubeObjects, compare properties recursively
                foreach (PropertyInfo prop in type.GetProperties())
                {
                    logger.LogTrace($"Property {prop.Name}");

                    // Ignore properties that are not part of modified
                    if (modified is PSObject psObject && psObject.Properties[prop.Name] == null)
                    {
                        continue;
                    }

                    JsonPropertyAttribute jsonAttribute = (JsonPropertyAttribute)prop.GetCustomAttribute(typeof(JsonPropertyAttribute));
                    string propPath = path + "/" + escapeJsonPointer(jsonAttribute.PropertyName);

                    object originalValue = original.GetDynamicPropertyValue(prop.Name);
                    object modifiedValue = modified.GetDynamicPropertyValue(prop.Name);

                    if (!isPropertyUpdateable(type, prop))
                    {
                        continue;
                    }

                    // Pass patch strategy attribute to diff function for the property we're looking at
                    MergeStrategyAttribute attribute = (MergeStrategyAttribute)Attribute.GetCustomAttribute(prop, typeof(MergeStrategyAttribute));
                    CreateTwoWayPatch(
                        original: originalValue,
                        modified: modifiedValue,
                        type: prop.PropertyType,
                        patch: patch,
                        path: propPath,
                        mergeStrategy: attribute,
                        ignoreDeletions: ignoreDeletions,
                        ignoreAdditionsAndModifications: ignoreAdditionsAndModifications
                        );
                }
            }
        }
示例#36
0
        private static object MergeHelper(object vars, object diff)
        {
            if (Util.IsNumber(diff) || diff is bool? || diff is string || diff is char?)
            {
                return(diff);
            }
            if (diff == null)
            {
                return(vars);
            }

            // Merge arrays.
            if (vars is IList)
            {
                IDictionary diffMap  = diff is IDictionary ? diff as IDictionary : null;
                IEnumerable diffKeys = diffMap != null ? diffMap.Keys : diff as IEnumerable;
                IList       varsList = vars is IList ? vars as IList : null;

                var merged = new List <object>();
                foreach (object lpVariable in varsList)
                {
                    merged.Add(MergeHelper(lpVariable, null));
                }

                // Merge values from server
                //
                // Array values from server come as Dictionary
                // Example:
                // string[] items = new string[] { "Item 1", "Item 2"};
                // args.With<string[]>("Items", items); // Action Context arg value
                // "vars": {
                //      "Items": {
                //                  "[1]": "Item 222", // Modified value from server
                //                  "[0]": "Item 111"  // Modified value from server
                //              }
                //  }
                if (diffMap != null)
                {
                    foreach (object varSubscript in diffKeys)
                    {
                        var    strSubscript = (string)varSubscript;
                        int    subscript    = Convert.ToInt32(strSubscript.Substring(1, strSubscript.Length - 1 - 1));
                        object lpVariable   = diffMap.Contains(varSubscript) ? diffMap[varSubscript] : null;
                        while (subscript >= merged.Count)
                        {
                            merged.Add(null);
                        }
                        merged[subscript] = MergeHelper(merged[subscript], lpVariable);
                    }
                }
                return(merged);
            }

            // Merge dictionaries.
            if (vars is IDictionary || diff is IDictionary)
            {
                IDictionary diffMap  = diff is IDictionary ? diff as IDictionary: null;
                IDictionary varsMap  = vars is IDictionary ? vars as IDictionary: null;
                IEnumerable diffKeys = diffMap != null ? diffMap.Keys : diff as IEnumerable;
                IEnumerable varsKeys = varsMap != null ? varsMap.Keys : vars as IEnumerable;

                var merged = new Dictionary <object, object>();
                if (varsKeys != null)
                {
                    foreach (object lpVariable in varsKeys)
                    {
                        if (!diffMap.Contains(lpVariable))
                        {
                            merged[lpVariable] = MergeHelper(varsMap.Contains(lpVariable) ? varsMap[lpVariable] : null, null);
                        }
                    }
                }
                foreach (object lpVariable in diffKeys)
                {
                    IDictionary <string, object> varsDic = Json.Deserialize(Json.Serialize(varsMap)) as IDictionary <string, object>;
                    // If varsDic is null, there is a nested container - retrieve value from original varsMap.
                    if (varsDic == null)
                    {
                        merged[lpVariable] =
                            MergeHelper(varsMap != null && varsMap.Contains(lpVariable) ? varsMap[lpVariable] : null,
                                        diffMap != null && diffMap.Contains(lpVariable) ? diffMap[lpVariable] : null);
                    }
                    else
                    {
                        merged[lpVariable] =
                            MergeHelper(varsDic != null && varsDic.ContainsKey((string)lpVariable)
                                            ? varsDic[(string)lpVariable] : null,
                                        diffMap != null && diffMap.Contains(lpVariable)
                                            ? diffMap[lpVariable] : null);
                    }
                }
                return(merged);
            }
            return(null);
        }
示例#37
0
        public override bool Equals(object obj)
        {
            IDictionary <TKey, TValue> other = obj as IDictionary <TKey, TValue>;

            if (other == null)
            {
                return(false);
            }

            // Verify Dictionary counts match
            if (this.Count != other.Count)
            {
                return(false);
            }

            // Try to compare keys in order (faster than lookup for each key)
            using (IEnumerator <KeyValuePair <TKey, TValue> > thisEnumerator = GetEnumerator())
                using (IEnumerator <KeyValuePair <TKey, TValue> > otherEnumerator = other.GetEnumerator())
                {
                    int countCompared = 0;

                    while (thisEnumerator.MoveNext())
                    {
                        // If other ran out of items first, definite non-match
                        if (!otherEnumerator.MoveNext())
                        {
                            return(false);
                        }

                        KeyValuePair <TKey, TValue> thisPair  = thisEnumerator.Current;
                        KeyValuePair <TKey, TValue> otherPair = otherEnumerator.Current;

                        // If keys don't match, they aren't in the same order; must fall back
                        if (!thisPair.Key.Equals(otherPair.Key))
                        {
                            break;
                        }

                        // If keys matched but values different, definite non-match
                        if (!object.Equals(thisPair.Value, otherPair.Value))
                        {
                            return(false);
                        }

                        countCompared++;
                    }

                    // If we got fully through the lists, they match
                    if (countCompared == this.Count)
                    {
                        return(true);
                    }
                }

            // Otherwise, retrieve values by key (any order) and compare values)
            foreach (KeyValuePair <TKey, TValue> pair in this)
            {
                if (!other.Contains(pair))
                {
                    return(false);
                }
            }

            return(true);
        }
 public bool Contains(KeyValuePair <K, V> item)
 {
     return(_dict.Contains(item));
 }
 bool ICollection <KeyValuePair <string, object> > .Contains(KeyValuePair <string, object> value) => _additionalProperties.Contains(value);
        private static ApplicationHistoryManagerOnTimelineStore.ApplicationReportExt ConvertToApplicationReport
            (TimelineEntity entity, ApplicationHistoryManagerOnTimelineStore.ApplicationReportField
            field)
        {
            string user         = null;
            string queue        = null;
            string name         = null;
            string type         = null;
            long   createdTime  = 0;
            long   finishedTime = 0;
            ApplicationAttemptId latestApplicationAttemptId = null;
            string diagnosticsInfo = null;
            FinalApplicationStatus         finalStatus              = FinalApplicationStatus.Undefined;
            YarnApplicationState           state                    = null;
            ApplicationResourceUsageReport appResources             = null;
            IDictionary <ApplicationAccessType, string> appViewACLs = new Dictionary <ApplicationAccessType
                                                                                      , string>();
            IDictionary <string, object> entityInfo = entity.GetOtherInfo();

            if (entityInfo != null)
            {
                if (entityInfo.Contains(ApplicationMetricsConstants.UserEntityInfo))
                {
                    user = entityInfo[ApplicationMetricsConstants.UserEntityInfo].ToString();
                }
                if (entityInfo.Contains(ApplicationMetricsConstants.AppViewAclsEntityInfo))
                {
                    string appViewACLsStr = entityInfo[ApplicationMetricsConstants.AppViewAclsEntityInfo
                                            ].ToString();
                    if (appViewACLsStr.Length > 0)
                    {
                        appViewACLs[ApplicationAccessType.ViewApp] = appViewACLsStr;
                    }
                }
                if (field == ApplicationHistoryManagerOnTimelineStore.ApplicationReportField.UserAndAcls)
                {
                    return(new ApplicationHistoryManagerOnTimelineStore.ApplicationReportExt(ApplicationReport
                                                                                             .NewInstance(ConverterUtils.ToApplicationId(entity.GetEntityId()), latestApplicationAttemptId
                                                                                                          , user, queue, name, null, -1, null, state, diagnosticsInfo, null, createdTime,
                                                                                                          finishedTime, finalStatus, null, null, 1.0F, type, null), appViewACLs));
                }
                if (entityInfo.Contains(ApplicationMetricsConstants.QueueEntityInfo))
                {
                    queue = entityInfo[ApplicationMetricsConstants.QueueEntityInfo].ToString();
                }
                if (entityInfo.Contains(ApplicationMetricsConstants.NameEntityInfo))
                {
                    name = entityInfo[ApplicationMetricsConstants.NameEntityInfo].ToString();
                }
                if (entityInfo.Contains(ApplicationMetricsConstants.TypeEntityInfo))
                {
                    type = entityInfo[ApplicationMetricsConstants.TypeEntityInfo].ToString();
                }
                if (entityInfo.Contains(ApplicationMetricsConstants.AppCpuMetrics))
                {
                    long vcoreSeconds = long.Parse(entityInfo[ApplicationMetricsConstants.AppCpuMetrics
                                                   ].ToString());
                    long memorySeconds = long.Parse(entityInfo[ApplicationMetricsConstants.AppMemMetrics
                                                    ].ToString());
                    appResources = ApplicationResourceUsageReport.NewInstance(0, 0, null, null, null,
                                                                              memorySeconds, vcoreSeconds);
                }
            }
            IList <TimelineEvent> events = entity.GetEvents();

            if (events != null)
            {
                foreach (TimelineEvent @event in events)
                {
                    if (@event.GetEventType().Equals(ApplicationMetricsConstants.CreatedEventType))
                    {
                        createdTime = @event.GetTimestamp();
                    }
                    else
                    {
                        if (@event.GetEventType().Equals(ApplicationMetricsConstants.FinishedEventType))
                        {
                            finishedTime = @event.GetTimestamp();
                            IDictionary <string, object> eventInfo = @event.GetEventInfo();
                            if (eventInfo == null)
                            {
                                continue;
                            }
                            if (eventInfo.Contains(ApplicationMetricsConstants.LatestAppAttemptEventInfo))
                            {
                                latestApplicationAttemptId = ConverterUtils.ToApplicationAttemptId(eventInfo[ApplicationMetricsConstants
                                                                                                             .LatestAppAttemptEventInfo].ToString());
                            }
                            if (eventInfo.Contains(ApplicationMetricsConstants.DiagnosticsInfoEventInfo))
                            {
                                diagnosticsInfo = eventInfo[ApplicationMetricsConstants.DiagnosticsInfoEventInfo]
                                                  .ToString();
                            }
                            if (eventInfo.Contains(ApplicationMetricsConstants.FinalStatusEventInfo))
                            {
                                finalStatus = FinalApplicationStatus.ValueOf(eventInfo[ApplicationMetricsConstants
                                                                                       .FinalStatusEventInfo].ToString());
                            }
                            if (eventInfo.Contains(ApplicationMetricsConstants.StateEventInfo))
                            {
                                state = YarnApplicationState.ValueOf(eventInfo[ApplicationMetricsConstants.StateEventInfo
                                                                     ].ToString());
                            }
                        }
                    }
                }
            }
            return(new ApplicationHistoryManagerOnTimelineStore.ApplicationReportExt(ApplicationReport
                                                                                     .NewInstance(ConverterUtils.ToApplicationId(entity.GetEntityId()), latestApplicationAttemptId
                                                                                                  , user, queue, name, null, -1, null, state, diagnosticsInfo, null, createdTime,
                                                                                                  finishedTime, finalStatus, appResources, null, 1.0F, type, null), appViewACLs));
        }
示例#41
0
 public bool Contains(KeyValuePair <T, K> item)
 {
     return(_dictionaryImplementation.Contains(item));
 }
        private static ContainerReport ConvertToContainerReport(TimelineEntity entity, string
                                                                serverHttpAddress, string user)
        {
            int            allocatedMem             = 0;
            int            allocatedVcore           = 0;
            string         allocatedHost            = null;
            int            allocatedPort            = -1;
            int            allocatedPriority        = 0;
            long           createdTime              = 0;
            long           finishedTime             = 0;
            string         diagnosticsInfo          = null;
            int            exitStatus               = ContainerExitStatus.Invalid;
            ContainerState state                    = null;
            string         nodeHttpAddress          = null;
            IDictionary <string, object> entityInfo = entity.GetOtherInfo();

            if (entityInfo != null)
            {
                if (entityInfo.Contains(ContainerMetricsConstants.AllocatedMemoryEntityInfo))
                {
                    allocatedMem = (int)entityInfo[ContainerMetricsConstants.AllocatedMemoryEntityInfo
                                   ];
                }
                if (entityInfo.Contains(ContainerMetricsConstants.AllocatedVcoreEntityInfo))
                {
                    allocatedVcore = (int)entityInfo[ContainerMetricsConstants.AllocatedVcoreEntityInfo
                                     ];
                }
                if (entityInfo.Contains(ContainerMetricsConstants.AllocatedHostEntityInfo))
                {
                    allocatedHost = entityInfo[ContainerMetricsConstants.AllocatedHostEntityInfo].ToString
                                        ();
                }
                if (entityInfo.Contains(ContainerMetricsConstants.AllocatedPortEntityInfo))
                {
                    allocatedPort = (int)entityInfo[ContainerMetricsConstants.AllocatedPortEntityInfo
                                    ];
                }
                if (entityInfo.Contains(ContainerMetricsConstants.AllocatedPriorityEntityInfo))
                {
                    allocatedPriority = (int)entityInfo[ContainerMetricsConstants.AllocatedPriorityEntityInfo
                                        ];
                }
                if (entityInfo.Contains(ContainerMetricsConstants.AllocatedHostHttpAddressEntityInfo
                                        ))
                {
                    nodeHttpAddress = (string)entityInfo[ContainerMetricsConstants.AllocatedHostHttpAddressEntityInfo
                                      ];
                }
            }
            IList <TimelineEvent> events = entity.GetEvents();

            if (events != null)
            {
                foreach (TimelineEvent @event in events)
                {
                    if (@event.GetEventType().Equals(ContainerMetricsConstants.CreatedEventType))
                    {
                        createdTime = @event.GetTimestamp();
                    }
                    else
                    {
                        if (@event.GetEventType().Equals(ContainerMetricsConstants.FinishedEventType))
                        {
                            finishedTime = @event.GetTimestamp();
                            IDictionary <string, object> eventInfo = @event.GetEventInfo();
                            if (eventInfo == null)
                            {
                                continue;
                            }
                            if (eventInfo.Contains(ContainerMetricsConstants.DiagnosticsInfoEventInfo))
                            {
                                diagnosticsInfo = eventInfo[ContainerMetricsConstants.DiagnosticsInfoEventInfo].ToString
                                                      ();
                            }
                            if (eventInfo.Contains(ContainerMetricsConstants.ExitStatusEventInfo))
                            {
                                exitStatus = (int)eventInfo[ContainerMetricsConstants.ExitStatusEventInfo];
                            }
                            if (eventInfo.Contains(ContainerMetricsConstants.StateEventInfo))
                            {
                                state = ContainerState.ValueOf(eventInfo[ContainerMetricsConstants.StateEventInfo
                                                               ].ToString());
                            }
                        }
                    }
                }
            }
            NodeId      allocatedNode = NodeId.NewInstance(allocatedHost, allocatedPort);
            ContainerId containerId   = ConverterUtils.ToContainerId(entity.GetEntityId());
            string      logUrl        = WebAppUtils.GetAggregatedLogURL(serverHttpAddress, allocatedNode.
                                                                        ToString(), containerId.ToString(), containerId.ToString(), user);

            return(ContainerReport.NewInstance(ConverterUtils.ToContainerId(entity.GetEntityId
                                                                                ()), Resource.NewInstance(allocatedMem, allocatedVcore), NodeId.NewInstance(allocatedHost
                                                                                                                                                            , allocatedPort), Priority.NewInstance(allocatedPriority), createdTime, finishedTime
                                               , diagnosticsInfo, logUrl, exitStatus, state, nodeHttpAddress));
        }
        private static ApplicationAttemptReport ConvertToApplicationAttemptReport(TimelineEntity
                                                                                  entity)
        {
            string      host                   = null;
            int         rpcPort                = -1;
            ContainerId amContainerId          = null;
            string      trackingUrl            = null;
            string      originalTrackingUrl    = null;
            string      diagnosticsInfo        = null;
            YarnApplicationAttemptState state  = null;
            IList <TimelineEvent>       events = entity.GetEvents();

            if (events != null)
            {
                foreach (TimelineEvent @event in events)
                {
                    if (@event.GetEventType().Equals(AppAttemptMetricsConstants.RegisteredEventType))
                    {
                        IDictionary <string, object> eventInfo = @event.GetEventInfo();
                        if (eventInfo == null)
                        {
                            continue;
                        }
                        if (eventInfo.Contains(AppAttemptMetricsConstants.HostEventInfo))
                        {
                            host = eventInfo[AppAttemptMetricsConstants.HostEventInfo].ToString();
                        }
                        if (eventInfo.Contains(AppAttemptMetricsConstants.RpcPortEventInfo))
                        {
                            rpcPort = (int)eventInfo[AppAttemptMetricsConstants.RpcPortEventInfo];
                        }
                        if (eventInfo.Contains(AppAttemptMetricsConstants.MasterContainerEventInfo))
                        {
                            amContainerId = ConverterUtils.ToContainerId(eventInfo[AppAttemptMetricsConstants
                                                                                   .MasterContainerEventInfo].ToString());
                        }
                    }
                    else
                    {
                        if (@event.GetEventType().Equals(AppAttemptMetricsConstants.FinishedEventType))
                        {
                            IDictionary <string, object> eventInfo = @event.GetEventInfo();
                            if (eventInfo == null)
                            {
                                continue;
                            }
                            if (eventInfo.Contains(AppAttemptMetricsConstants.TrackingUrlEventInfo))
                            {
                                trackingUrl = eventInfo[AppAttemptMetricsConstants.TrackingUrlEventInfo].ToString
                                                  ();
                            }
                            if (eventInfo.Contains(AppAttemptMetricsConstants.OriginalTrackingUrlEventInfo))
                            {
                                originalTrackingUrl = eventInfo[AppAttemptMetricsConstants.OriginalTrackingUrlEventInfo
                                                      ].ToString();
                            }
                            if (eventInfo.Contains(AppAttemptMetricsConstants.DiagnosticsInfoEventInfo))
                            {
                                diagnosticsInfo = eventInfo[AppAttemptMetricsConstants.DiagnosticsInfoEventInfo].
                                                  ToString();
                            }
                            if (eventInfo.Contains(AppAttemptMetricsConstants.StateEventInfo))
                            {
                                state = YarnApplicationAttemptState.ValueOf(eventInfo[AppAttemptMetricsConstants.
                                                                                      StateEventInfo].ToString());
                            }
                        }
                    }
                }
            }
            return(ApplicationAttemptReport.NewInstance(ConverterUtils.ToApplicationAttemptId
                                                            (entity.GetEntityId()), host, rpcPort, trackingUrl, originalTrackingUrl, diagnosticsInfo
                                                        , state, amContainerId));
        }
示例#44
0
 public bool Contains(KeyValuePair <string, string> item)
 {
     return(_storage.Contains(item));
 }
示例#45
0
 public bool Contains(KeyValuePair <string, object> item)
 {
     return(_dictionary.Contains(item));
 }
 public virtual bool Contains(KeyValuePair <TKey, TValue> item)
 {
     using (new ReadOnlyLock(dictionaryLock)) {
         return(dict.Contains(item));
     }
 }
示例#47
0
        /// <summary>
        /// Gets the deep copy
        /// </summary>
        /// <param name="source">The object to be copied</param>
        /// <param name="target">The object which will be the copy</param>
        /// <param name="copiedObjects">Collection of objects and their copied equivalents. Will be populated and queried during copy.</param>
        /// <param name="path">Relative path to location where files will be copied to</param>
        /// <param name="copyValue">Indicates whether the new object should refer to a copy or to the same object</param>
        private static void Copy(object source, object target, Hashtable copiedObjects, string path, bool copyValue)
        {
            if (source is IList)
            {
                IList copiedArray = (IList)target;
                copiedArray.Clear();
                for (int j = 0; j < ((IList)source).Count; j++)
                {
                    object copiedArrayValue = ((IList)source)[j];
                    if (copyValue)
                    {
                        copiedArrayValue = ObjectSupport.GetCopy(copiedArrayValue, copiedObjects, path);
                    }
                    copiedArray.Add(copiedArrayValue);
                }
            }
            else if (source is IDictionary)
            {
                IDictionary copiedArray = (IDictionary)target;
                copiedArray.Clear();

                IDictionaryEnumerator dictionaryEnumerator = ((IDictionary)source).GetEnumerator();
                while (dictionaryEnumerator.MoveNext())
                {
                    object copiedArrayKey   = dictionaryEnumerator.Key;
                    object copiedArrayValue = dictionaryEnumerator.Value;
                    if (copyValue)
                    {
                        copiedArrayKey   = ObjectSupport.GetCopy(copiedArrayKey, copiedObjects, path);
                        copiedArrayValue = ObjectSupport.GetCopy(copiedArrayValue, copiedObjects, path);
                    }

                    if (!copiedArray.Contains(copiedArrayKey))
                    {
                        copiedArray.Add(copiedArrayKey, copiedArrayValue);
                    }
                }
            }
            // Special handling for files
            else if (source is FileSystemInfo)
            {
                if (copyValue && (path != null) && (!path.Trim().Equals("")))
                {
                    object copiedValue = CopyFile((FileSystemInfo)source, path);
                }
            }
            else
            {
                PropertyInfo[] property = source.GetType().GetProperties();
                for (int i = 0; i < property.Length; i++)
                {
                    object sourceValue = property[i].GetValue(source, null);

                    if (sourceValue != null)
                    {
                        // Default copied value. This is just a reference to the original value
                        object copiedValue = sourceValue;

                        // If the value has been copied before, use the same copied equivalent
                        if (copiedObjects.ContainsKey(sourceValue))
                        {
                            copiedValue = copiedObjects[sourceValue];
                        }
                        else
                        {
                            // Determine whether the property is to be copied
                            bool copyPropertyValue = (Boolean)MetaInfo.GetAttributeDefault(source.GetType(), property[i].Name, "ObjectCopy", false);

                            if (copyPropertyValue)
                            {
                                if (property[i].CanWrite)
                                {
                                    copiedValue = ObjectSupport.GetCopy(sourceValue, copiedObjects, path);
                                }
                                else
                                {
                                    object targetValue = property[i].GetValue(target, null);
                                    Copy(sourceValue, targetValue, copiedObjects, path);
                                }
                            }
                            else if ((sourceValue is IList) || (sourceValue is IDictionary))
                            {
                                object targetValue = property[i].GetValue(target, null);
                                Copy(sourceValue, targetValue, copiedObjects, path, copyPropertyValue);
                            }
                        }

                        // Populate the target object
                        if (property[i].CanWrite)
                        {
                            property[i].SetValue(target, copiedValue, null);
                        }

                        if (!copiedObjects.Contains(sourceValue))
                        {
                            copiedObjects.Add(sourceValue, copiedValue);
                        }
                    }
                }
            }
        }
示例#48
0
 bool ICollection <KeyValuePair <TKey, TValue> > .Contains(KeyValuePair <TKey, TValue> item)
 {
     return(m_dictionary.Contains(item));
 }
        private void TotalPVDesmontar(string[] a)
        {
            var resumo = new ConciliacaoUseRedeEEVDTotalPontoVendaStruct()
            {
                is_tipo_registro      = Convert.ToInt32(a[0]),
                nm_tipo_registro      = "Total ponto de venda",
                is_numero_ponto_venda = Convert.ToDecimal(a[1]).ToString(),
                is_quantidade_resumo_vendas_acatados = Convert.ToDecimal(a[2]),
                is_quantidade_comprovante_vendas     = Convert.ToDecimal(a[3]),
                is_total_bruto              = Convert.ToDecimal(a[4]) / 100,
                is_total_desconto           = Convert.ToDecimal(a[5]) / 100,
                is_total_liquido            = Convert.ToDecimal(a[6]) / 100,
                is_valor_bruto_predatado    = Convert.ToDecimal(a[7]) / 100,
                is_valor_desconto_predatado = Convert.ToDecimal(a[8]) / 100,
                is_valor_liquido_predatado  = Convert.ToDecimal(a[9]) / 100,
                rede = 1
            };

            io_arl_pv.Add(resumo);

            string estabelecimento = a[1];

            if (io_hsm_totalizador_estabelecimento.Contains(estabelecimento))
            {
                TotalizadorEstabelecimento totalizador_estabelecimento = (TotalizadorEstabelecimento)io_hsm_totalizador_estabelecimento[estabelecimento];
                io_hsm_totalizador_estabelecimento.Remove(estabelecimento);
                io_hsm_totalizador_estabelecimento.Add(estabelecimento, new TotalizadorEstabelecimento
                {
                    prev_pagamento  = Convert.ToDateTime(data_pagamento),
                    total_realizado = totalizador_estabelecimento.total_realizado + resumo.is_total_liquido,
                    estabelecimento = Convert.ToInt32(estabelecimento)
                });
            }
            else
            {
                io_hsm_totalizador_estabelecimento.Add(estabelecimento, new TotalizadorEstabelecimento
                {
                    prev_pagamento  = Convert.ToDateTime(data_pagamento),
                    total_realizado = resumo.is_total_liquido,
                    estabelecimento = Convert.ToInt32(estabelecimento)
                });
            }

            if (io_hsm_totalizador_banco.Contains(banco))
            {
                TotalizadorBanco totalizador_banco = (TotalizadorBanco)io_hsm_totalizador_banco[banco];
                io_hsm_totalizador_banco.Remove(banco);
                io_hsm_totalizador_banco.Add(banco, new TotalizadorBanco
                {
                    data_prevista   = Convert.ToDateTime(data_pagamento),
                    total_realizado = totalizador_banco.total_realizado + resumo.is_total_liquido,
                    id_banco        = Convert.ToInt32(banco)
                });
            }
            else
            {
                io_hsm_totalizador_banco.Add(banco, new TotalizadorBanco
                {
                    data_prevista   = Convert.ToDateTime(data_pagamento),
                    total_realizado = resumo.is_total_liquido,
                    id_banco        = Convert.ToInt32(banco)
                });
            }

            Decimal valor_total         = 0;
            Decimal valor_total_liquido = 0;

            if (io_hsm_totalizador_produto.Contains("debito"))
            {
                TotalizadorProduto totalizador_produto = (TotalizadorProduto)io_hsm_totalizador_produto["debito"];
                valor_total         = totalizador_produto.valor_bruto + resumo.is_total_bruto;
                valor_total_liquido = totalizador_produto.valor_liquido + resumo.is_total_liquido;
                io_hsm_totalizador_produto.Remove("debito");
                io_hsm_totalizador_produto.Add("debito", new TotalizadorProduto
                {
                    data_prevista = Convert.ToDateTime(data_pagamento),
                    valor_bruto   = valor_total,
                    valor_liquido = valor_total_liquido,
                    ds_produto    = "Débito",
                    rede          = "Userede"
                });
            }
            else
            {
                io_hsm_totalizador_produto.Add("debito", new TotalizadorProduto
                {
                    data_prevista = Convert.ToDateTime(data_pagamento),
                    valor_bruto   = resumo.is_total_bruto,
                    valor_liquido = resumo.is_total_liquido,
                    ds_produto    = "Débito",
                    rede          = "Userede"
                });
            }
        }
示例#50
0
        public static string GetJsConnectString(IDictionary user, NameValueCollection request, string clientID, string secret, bool secure, string hash)
        {
            if (request == null)
            {
                request = System.Web.HttpContext.Current.Request.QueryString;
            }

            IDictionary error = null;

            int timestamp = 0;

            try {
                timestamp = System.Convert.ToInt32(request["timestamp"]);
            } catch {
                timestamp = 0;
            }
            int currentTimestamp = jsConnect.Timestamp();

            if (secure)
            {
                if (request["v"] == null)
                {
                    error = jsConnect.Error("invalid_request", "Missing the v parameter.");
                }
                else if (request["v"] != jsConnect.Version)
                {
                    error = jsConnect.Error("invalid_request", "Unsupported version " + request["v"] + ".");
                }
                else if (request["client_id"] == null)
                {
                    error = jsConnect.Error("invalid_request", "Missing the client_id parameter.");
                }
                else if (request["client_id"] != clientID)
                {
                    error = jsConnect.Error("invalid_client", "Unknown client " + request["client_id"] + ".");
                }
                else if (request["timestamp"] == null && request["signature"] == null)
                {
                    if (user != null && user.Count > 0)
                    {
                        error             = new SortedList();
                        error["name"]     = user["name"];
                        error["photourl"] = user.Contains("photourl") ? user["photourl"] : "";
                        error["signedin"] = true;
                    }
                    else
                    {
                        error             = new SortedList();
                        error["name"]     = "";
                        error["photourl"] = "";
                    }
                }
                else if (timestamp == 0)
                {
                    error = jsConnect.Error("invalid_request", "The timestamp is missing or invalid.");
                }
                else if (request["sig"] == null)
                {
                    error = jsConnect.Error("invalid_request", "Missing the sig paremeter.");
                }
                else if (Math.Abs(currentTimestamp - timestamp) > jsConnect.Timeout)
                {
                    error = jsConnect.Error("invalid_request", "The timestamp is invalid.");
                }
                else if (request["nonce"] == null)
                {
                    error = jsConnect.Error("invalid_request", "Missing the nonce parameter.");
                }
                else if (request["ip"] == null)
                {
                    error = jsConnect.Error("invalid_request", "Missing the ip parameter.");
                }
                else
                {
                    // Make sure the signature checks out.
                    string sig = jsConnect.Hash(request["ip"] + request["nonce"] + timestamp.ToString() + secret, hash);
                    if (sig != request["sig"])
                    {
                        error = jsConnect.Error("access_denied", "Signature invalid.");
                    }
                }
            }

            IDictionary result;

            if (error != null)
            {
                result = error;
            }
            else if (user != null && user.Count > 0)
            {
                user.Add("ip", request["ip"]);
                user.Add("nonce", request["nonce"]);
                result = new SortedList(user);
                SignJsConnect(result, clientID, secret, true, hash);
                result.Add("v", jsConnect.Version);
            }
            else
            {
                result             = new SortedList();
                result["name"]     = "";
                result["photourl"] = "";
            }

            string json = jsConnect.JsonEncode(result);

            if (request["callback"] == null)
            {
                return(json);
            }
            else
            {
                return(request["callback"] + "(" + json + ")");
            }
        }
示例#51
0
        private IEnumerator CreatePolygon(GameObject parent, string kind, string type, IList subject, List <object> clips, IDictionary properties, Layer layer, bool delayedLoad)
        {
            GameObject polygon = null;

            try {
                PolygonHandler poly = new PolygonHandler(subject, clips);

                RenderingOptions renderingOptions = null;
                foreach (RenderingOptions r in layer.renderingOptions)
                {
                    if (r.kind == kind)
                    {
                        renderingOptions = r;
                        break;
                    }
                }

                float    height   = layer.defaultRendering.polygonHeight;
                float    defaultZ = -layer.defaultRendering.distanceFromFloor;
                Material material = GetMaterial(layer.defaultRendering, poly.center);
                Material roofMat  = layer.defaultRendering.roofMaterial == null ? layer.defaultRendering.material : layer.defaultRendering.roofMaterial;

                if (renderingOptions != null)
                {
                    height   = renderingOptions.polygonHeight;
                    material = GetMaterial(renderingOptions, poly.center);
                    defaultZ = renderingOptions.distanceFromFloor;
                    roofMat  = renderingOptions.roofMaterial;
                }

                //Group buildings by center coordinates
                if (layer.json == "buildings")
                {
                    GameObject centerContainer = findNearestCenter(poly.center, parent, material);
                    parent   = centerContainer;
                    material = centerContainer.GetComponent <MatHolder>().material;
                }


                Int64 sort;
                if (properties.Contains("sort_key"))
                {
                    sort = (Int64)properties["sort_key"];
                }
                else
                {
                    sort = (Int64)properties["sort_rank"];
                }

                if (material)
                {
                    material.renderQueue = -(int)sort;
                }
                if (roofMat)
                {
                    roofMat.renderQueue = -(int)sort;
                }

                if (defaultZ == 0f)
                {
                    defaultZ = -sort / 1000.0f;
                }

                if (layer.useRealHeight && properties.Contains("height"))
                {
                    double h = (double)properties["height"];
                    height = (float)h;
                }
                if (layer.useRealHeight && properties.Contains("min_height"))
                {
                    double hm = (double)properties["min_height"];
                    defaultZ = (float)hm;
                    height   = (float)height - (float)hm;
                }

                polygon = poly.CreateModel(layer, height);
                if (polygon == null)
                {
                    yield break;
                }

                polygon.name             = layer.name;
                polygon.transform.parent = parent.transform;

                if (layer.useRealHeight)
                {
                    //				GameObject roof = poly.CreateModel(layer,0);
                    GameObject roof = poly.CreateRoof();
                    roof.name             = "roof";
                    roof.transform.parent = polygon.transform;
                    roof.GetComponent <MeshRenderer>().material = roofMat;
                    roof.transform.position = new Vector3(roof.transform.position.x, height + 0.1f, roof.transform.position.z);

                    if (properties.Contains("roof_material"))
                    {
                        roof.name = "roofmat_" + (string)properties["roof_material"];
                    }

                    if (properties.Contains("roof_color"))
                    {
                        Debug.LogError("Roof color: " + (string)properties["roof_color"]);
                        polygon.name = "roofx";
                    }
                }

                Vector3 pos = polygon.transform.position;
                pos.z = defaultZ;
                polygon.transform.position      = pos;
                polygon.transform.localPosition = pos;

                Attributes attributes = polygon.AddComponent <Attributes>();
                attributes.type = type;
                attributes.loadWithDictionary((Dictionary <string, object>)properties);

                polygon.GetComponent <Renderer>().material = material;

                if (layer.OnFeatureLoad != null)
                {
                    layer.OnFeatureLoad.Invoke(poly.mesh2D, layer, kind, poly.center);
                }
            }
            catch (Exception ex) {
                GameObject.Destroy(polygon);
                Debug.Log(ex);
            }
            if (delayedLoad)
            {
                yield return(null);
            }
        }
示例#52
0
 bool ICollection <KeyValuePair <int, IList <object> > > .Contains(
     KeyValuePair <int, IList <object> > keyValuePair
     )
 {
     return(entries.Contains(keyValuePair));
 }
示例#53
0
 public override bool Contains(object k)
 {
     return(d.Contains(k));
 }
 public bool Contains(KeyValuePair <string, TOut> item)
 {
     return(toWrap.Contains(new KeyValuePair <string, TIn>(item.Key,
                                                           (TIn)Conversion.ConvertTo <TIn>(item.Value))));
 }
 public bool Contains(KeyValuePair <TKey, TValue> item) => original.Contains(item);
示例#56
0
 public bool Contains(KeyValuePair <TKey, TValue> item)
 {
     return(_dictionary.Contains(item));
 }
示例#57
0
 public bool Contains(KeyValuePair <TKey, TValue> item)
 {
     return(mUnderlyingDictionary.Contains(item));
 }
示例#58
0
        public static bool GetNestedMember(this object target, string propName, ref object parent, ref string memberName,
                                           bool createSubKeysIfNotExists = false, Func <object> factory = null)
        {
            if (target == null)
            {
                return(false);
            }
            if (propName.IsNullOrWhiteSpace())
            {
                return(false);
            }

            parent = target;
            if (!propName.Contains("."))
            {
                memberName = propName;
                return(true);
            }
            else
            {
                int pos = propName.IndexOf(".");
                if (pos < 0)
                {
                    return(false);
                }

                string spropName = propName.Substring(0, pos);
                if (spropName.IsNullOrWhiteSpace())
                {
                    return(false);
                }

                if (pos + 1 >= propName.Length)
                {
                    return(false);
                }

                string remPropName = propName.Substring(pos + 1);

                if (target is IDictionary)
                {
                    IDictionary dict = target as IDictionary;
                    if (dict.Contains(spropName))
                    {
                        return(GetNestedMember(dict[spropName], remPropName, ref parent, ref memberName, createSubKeysIfNotExists, factory));
                    }
                    else
                    {
                        if (!createSubKeysIfNotExists)
                        {
                            return(false);
                        }
                        else
                        {
                            memberName = spropName;
                            var child = factory != null?factory() : null;

                            if (child == null)
                            {
                                return(false);
                            }

                            dict.Add(spropName, child);
                            return(GetNestedMember(dict[spropName], remPropName, ref parent, ref memberName, createSubKeysIfNotExists, factory));
                        }
                    }
                }
                else if (target is IDictionary <string, object> )
                {
                    IDictionary <string, object> dict = target as IDictionary <string, object>;
                    if (dict.ContainsKey(spropName))
                    {
                        return(GetNestedMember(dict[spropName], remPropName, ref parent, ref memberName, createSubKeysIfNotExists, factory));
                    }
                    else
                    {
                        return(false);
                    }
                }
                else if (target is IList)
                {
                    int   index = 0;
                    IList list  = (IList)target;
                    if (int.TryParse(spropName, out index))
                    {
                        if (index < list.Count)
                        {
                            return(GetNestedMember(list[index], remPropName, ref parent, ref memberName, createSubKeysIfNotExists, factory));
                        }
                        else
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(GetNestedMember(ChoType.GetPropertyValue(target, spropName), remPropName, ref parent, ref memberName, createSubKeysIfNotExists, factory));
                }
            }
        }
示例#59
0
        public void Load(DataRow dataRow, object o, Dictionary <DataRow, object> loadedObjects)
        {
            Type type = o.GetType();

            PropertyInfo[] properties = GetProperties(type);


            foreach (PropertyInfo propertyInfo in properties)
            {
                string relationName;
                //object[] propertyAttributes = propertyInfo.GetCustomAttributes(typeof(PropertyAttribute), true);
                PropertyAttribute propertyAttribute = GetPropertyAttribute(propertyInfo);
                if (propertyAttribute != null)
                {
                    //PropertyAttribute propertyAttribute = (PropertyAttribute)propertyAttributes[0];

                    switch (propertyAttribute.PropertyType)
                    {
                    case PropertyType.Column:

                        if (dataRow.Table.Columns.Contains(propertyInfo.Name))
                        {
                            DataColumn dataColumn = dataRow.Table.Columns[propertyInfo.Name];

                            object value = dataRow[dataColumn];
                            if (propertyInfo.GetSetMethod() != null)
                            {
                                if (value is DBNull || (dataColumn.DataType is object && value.ToString().ToLower() == "null"))
                                {
                                    value = null;
                                    if (propertyAttribute.Default != null)
                                    {
                                        value = propertyAttribute.Default;
                                    }
                                }
                                else
                                {
                                    if (propertyInfo.PropertyType.BaseType != null && propertyInfo.PropertyType.BaseType.FullName == "System.Enum")
                                    {
                                        if (Enum.IsDefined(propertyInfo.PropertyType, value.ToString()))
                                        {
                                            value = Enum.Parse(propertyInfo.PropertyType, value.ToString());
                                        }
                                        else
                                        {
                                            value = null;
                                        }
                                    }
                                }
                                try
                                {
                                    propertyInfo.SetValue(o, value, null);
                                }
                                catch { }
                            }
                        }
                        break;

                    case PropertyType.Parent:
                        if (dataRow.Table.Columns.Contains(propertyInfo.Name))
                        {
                            DataColumn dataColumn = dataRow.Table.Columns[propertyInfo.Name];
                            ParentPropertyAttribute parentPropertyAttribute = (ParentPropertyAttribute)propertyAttribute;
                            relationName = parentPropertyAttribute.RelationName ?? propertyInfo.Name;
                            DataRow parentRow = dataRow.GetParentRow(relationName);
                            object  parent    = propertyInfo.GetValue(o, null);
                            if (parentRow == null)
                            {
                                if (parent != null)
                                {
                                    if (propertyInfo.GetSetMethod() != null)
                                    {
                                        propertyInfo.SetValue(o, null, null);
                                    }
                                }
                            }
                            else
                            {
                                if (parent == null)
                                {
                                    Type     propertyType    = propertyInfo.PropertyType;
                                    object[] classAttributes = propertyType.GetCustomAttributes(typeof(ClassConfigAttribute), true);

                                    if (loadedObjects.ContainsKey(parentRow))
                                    {
                                        parent = loadedObjects[parentRow];
                                        propertyInfo.SetValue(o, parent, null);
                                    }
                                    else
                                    {
                                        if (classAttributes.Length == 1 && classAttributes[0] is ClassConfigAttribute)
                                        {
                                            ClassConfigAttribute classAttribute = (ClassConfigAttribute)classAttributes[0];
                                            if (!string.IsNullOrEmpty(classAttribute.DerivedTypesColumnName))
                                            {
                                                PropertyInfo derivedTypesProperty = propertyType.GetProperty(classAttribute.DerivedTypesColumnName);
                                                if (derivedTypesProperty != null)
                                                {
                                                    object[] derivedTypesPropertyAttributes = derivedTypesProperty.GetCustomAttributes(typeof(DerivedTypePropertyAttribute), true);
                                                    if (derivedTypesPropertyAttributes.Length > 0)
                                                    {
                                                        if (dataRow[classAttribute.DerivedTypesColumnName] != null)
                                                        {
                                                            string typeNickName = dataRow[classAttribute.DerivedTypesColumnName].ToString();
                                                            foreach (DerivedTypePropertyAttribute derivedTypePropertyAttribute in derivedTypesPropertyAttributes)
                                                            {
                                                                if (derivedTypePropertyAttribute.Name == typeNickName)
                                                                {
                                                                    parent = System.Activator.CreateInstance(derivedTypePropertyAttribute.Type);
                                                                    loadedObjects.Add(parentRow, parent);
                                                                    propertyInfo.SetValue(o, parent, null);
                                                                    break;
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    if (parent == null)
                                    {
                                        parent = System.Activator.CreateInstance(propertyType);
                                        loadedObjects.Add(parentRow, parent);
                                        propertyInfo.SetValue(o, parent, null);
                                    }
                                }
                                Load(parentRow, parent, loadedObjects);
                            }
                        }
                        break;

                    case PropertyType.Children:
                        ChildrenPropertyAttribute childrenPropertyAttribute = (ChildrenPropertyAttribute)propertyAttribute;
                        relationName = childrenPropertyAttribute.RelationName ?? propertyInfo.Name;
                        DataRow[] childrenRows = dataRow.GetChildRows(relationName);

                        object children = propertyInfo.GetValue(o, null);
                        object child    = null;
                        if (children != null)
                        {
                            bool isDictionary = children is IDictionary;

                            IDictionary dictionary          = null;
                            DataColumn  dictionaryKeyColumn = null;
                            if (isDictionary)
                            {
                                dictionary = (IDictionary)children;
                                string dictionaryKeyColumnName = childrenPropertyAttribute.DictionaryKeyColumnName;
                                Type   childrenType            = childrenPropertyAttribute.Type;

                                DataRelation dataRelation = dataRow.Table.DataSet.Relations[relationName];

                                if (dataRelation == null)
                                {
                                    dataRelation = CompleteDataRelationStructure(dataRow.Table.DataSet, dataRow.Table, childrenPropertyAttribute.TableName ?? childrenType.Name, childrenType, propertyInfo, childrenPropertyAttribute);
                                }

                                DataTable childrenTable = dataRelation.ChildTable;

                                if (childrenTable.Columns.Contains(dictionaryKeyColumnName))
                                {
                                    dictionaryKeyColumn = childrenTable.Columns[dictionaryKeyColumnName];
                                }
                            }

                            if (children is IList)
                            {
                                ((IList)children).Clear();
                            }

                            foreach (DataRow childRow in childrenRows)
                            {
                                if (isDictionary && dictionaryKeyColumn != null)
                                {
                                    object key = childRow[dictionaryKeyColumn];
                                    if (dictionary.Contains(key))
                                    {
                                        child = dictionary[key];
                                    }
                                    else
                                    {
                                        child = null;
                                        try
                                        {
                                            if (!childrenPropertyAttribute.Type.IsAbstract)
                                            {
                                                child = Activator.CreateInstance(childrenPropertyAttribute.Type);
                                                dictionary.Add(key, child);
                                            }
                                        }
                                        catch { }
                                    }
                                }
                                else if (children is IList)
                                {
                                    if (!loadedObjects.ContainsKey(childRow))
                                    {
                                        child = Activator.CreateInstance(childrenPropertyAttribute.Type);
                                        ((IList)children).Add(child);
                                    }
                                }
                                else
                                {
                                    throw new NotSupportedException();
                                }

                                if (child != null)
                                {
                                    if (!loadedObjects.ContainsKey(childRow))
                                    {
                                        loadedObjects.Add(childRow, child);
                                        Load(childRow, child, loadedObjects);
                                    }
                                }
                            }
                        }

                        break;

                    default:
                        throw new NotSupportedException();
                    }
                }
            }

            //OnObjectLoaded(new ObjectLoadedEventArgs(dataRow, o, loadedObjects, this));
        }
 public bool Contains(KeyValuePair <TKey, TValue> item)
 {
     return(_inner.Contains(item));
 }