public override ValueSerializer BuildSerializer(Serializer serializer, Type type,
            ConcurrentDictionary<Type, ValueSerializer> typeMapping)
        {
            var ser = new ObjectSerializer(type);
            typeMapping.TryAdd(type, ser);
            var elementSerializer = serializer.GetSerializerByType(typeof (DictionaryEntry));

            ValueReader reader = (stream, session) =>
            {
                var count = stream.ReadInt32(session);
                var entries = new DictionaryEntry[count];
                for (var i = 0; i < count; i++)
                {
                    var entry = (DictionaryEntry) stream.ReadObject(session);
                    entries[i] = entry;
                }
                return null;
            };

            ValueWriter writer = (stream, obj, session) =>
            {
                var dict = obj as IDictionary;
                // ReSharper disable once PossibleNullReferenceException
                stream.WriteInt32(dict.Count);
                foreach (var item in dict)
                {
                    stream.WriteObject(item, typeof (DictionaryEntry), elementSerializer,
                        serializer.Options.PreserveObjectReferences, session);
                    // elementSerializer.WriteValue(stream,item,session);
                }
            };
            ser.Initialize(reader, writer);
            
            return ser;
        }
示例#2
0
		private void BasicTests (ListDictionary ld)
		{
			Assert.AreEqual (0, ld.Count, "Count");
			Assert.IsFalse (ld.IsFixedSize, "IsFixedSize");
			Assert.IsFalse (ld.IsReadOnly, "IsReadOnly");
			Assert.IsFalse (ld.IsSynchronized, "IsSynchronized");
			Assert.AreEqual (0, ld.Keys.Count, "Keys");
			Assert.AreEqual (0, ld.Values.Count, "Values");
			Assert.IsNotNull (ld.SyncRoot, "SyncRoot");
			Assert.IsNotNull (ld.GetEnumerator (), "GetEnumerator");
			Assert.IsNotNull ((ld as IEnumerable).GetEnumerator (), "IEnumerable.GetEnumerator");

			ld.Add ("a", "1");
			Assert.AreEqual (1, ld.Count, "Count-1");
			Assert.IsTrue (ld.Contains ("a"), "Contains(a)");
			Assert.IsFalse (ld.Contains ("1"), "Contains(1)");

			ld.Add ("b", null);
			Assert.AreEqual (2, ld.Count, "Count-2");
			Assert.IsNull (ld["b"], "this[b]");

			DictionaryEntry[] entries = new DictionaryEntry[2];
			ld.CopyTo (entries, 0);

			ld["b"] = "2";
			Assert.AreEqual ("2", ld["b"], "this[b]2");

			ld.Remove ("b");
			Assert.AreEqual (1, ld.Count, "Count-3");
			ld.Clear ();
			Assert.AreEqual (0, ld.Count, "Count-4");
		}
示例#3
0
        internal override void SetSessionStateItem(string path, object value, bool writeItem)
        {
            Path name = PathIntrinsics.RemoveDriveName(path);
            path = name.TrimStartSlash();

            if (value == null)
            {
                Environment.SetEnvironmentVariable(path, null);
            }
            else
            {
                if (value is DictionaryEntry)
                {
                    value = ((DictionaryEntry)value).Value;
                }
                string str = value as string;
                if (str == null)
                {
                    str = PSObject.AsPSObject(value).ToString();
                }
                Environment.SetEnvironmentVariable(path, str);
                DictionaryEntry item = new DictionaryEntry(path, str);
                if (writeItem)
                {
                    WriteItemObject(item, path, false);
                }
            }
        }
示例#4
0
		public object this[object key]
		{
			get {
				if (_extraData == null) return null;

				foreach (DictionaryEntry entry in _extraData)
					if (entry.Key.Equals (key)) return entry.Value;

				return null;
			}

			set {
				if (_extraData == null)
				{
					_extraData = new DictionaryEntry [] { new DictionaryEntry (key, value) };
				}
				else
				{
					DictionaryEntry[] tmpData = new DictionaryEntry [_extraData.Length + 1];
					_extraData.CopyTo (tmpData, 0);
					tmpData [_extraData.Length] = new DictionaryEntry (key, value);
					_extraData = tmpData;
				}
			}
		}
        public CascadingDropDownNameValue[] GetPages(string knownCategoryValues, string category)
        {
            AnswerApp.Models.AnswerAppDataContext db = new AnswerApp.Models.AnswerAppDataContext();

            StringDictionary knownCatagories = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
            DictionaryEntry[] CatagoryArray = new DictionaryEntry[knownCatagories.Count];
            knownCatagories.CopyTo(CatagoryArray, 0);
            String SelectedSection = "Error 1";
            foreach (DictionaryEntry theEntry in CatagoryArray)
            {
                if (theEntry.Key.ToString().Equals("section"))
                {
                    SelectedSection = theEntry.Value.ToString();
                }
            }

            IQueryable<AnswerApp.Models.Page> retrieved = from theAnswers in db.Pages
                                                              where theAnswers.Section_Title.Equals(SelectedSection)//Textbook_Title)
                                                              select theAnswers;
            AnswerApp.Models.Page[] results = retrieved.ToArray<AnswerApp.Models.Page>();
            List<CascadingDropDownNameValue> theList = new List<CascadingDropDownNameValue>();
            foreach (AnswerApp.Models.Page thePage in results)
            {
                theList.Add(new CascadingDropDownNameValue(thePage.Page_Number, thePage.Page_Number));
            }
            return theList.ToArray();
        }
 /// <summary>
 /// 实例化
 /// </summary>
 /// <param name="value">对象</param>
 /// <param name="keyType">键类型</param>
 /// <param name="valueType">值类型</param>
 /// <param name="index"></param>
 /// <param name="callback"></param>
 public ReadDictionaryEventArgs(DictionaryEntry value, Type keyType,Type valueType, Int32 index, ReadObjectCallback callback)
     : base(index, callback)
 {
     Value = value;
     KeyType = keyType;
     ValueType = valueType;
 }
        public void ApplyConvention(Assembly assembly, DictionaryEntry entry)
        {
            string assemblyName = assembly.GetName().Name;
            string key = entry.Key as string;
            key = key.Replace(".baml", ".xaml");

            string uriString = String.Format("pack://application:,,,/{0};Component/{1}", assemblyName, key);

            try
            {
                if (!uriString.ToUpper().Contains("VIEW.XAML")
                    && !uriString.ToUpper().Contains("APP.XAML"))
                {
                    var dictionary = new ResourceDictionary
                                         {
                                             Source = new Uri(uriString)
                                         };

                    Application.Current.Resources.MergedDictionaries.Add(dictionary);
                }
            }
            catch
            {
                // do nothing. This allows for user controls to 'not' be loaded into the
                // Resource Dictionary
            }
        }
示例#8
0
		internal DictionaryEntry nextEntry() {
			DictionaryEntry cEntry = entry;
			hasMore = enum_Renamed.MoveNext();
			if (hasMore)
				entry = enum_Renamed.Entry;
			return cEntry;
		}
示例#9
0
 private string GetResourceKey(string resourceFileName, string key)
 {
     System.Resources.ResXResourceReader rsxr = null;
     try
     {
         rsxr = new System.Resources.ResXResourceReader(resourceFileName);
         System.Collections.DictionaryEntry d = default(System.Collections.DictionaryEntry);
         foreach (DictionaryEntry d_loopVariable in rsxr)
         {
             if (d_loopVariable.Key.ToString().ToLower().Equals(key.ToLower()))
             {
                 return(d_loopVariable.Key.ToString());
             }
         }
         return(null);
     }
     catch (Exception e)
     {
         string logMessage = $"Unable to find key {key} in resource file: {resourceFileName}.";
         logger.Warn(logMessage);
         throw new Exception(logMessage, e);
     }
     finally
     {
         if (rsxr != null)
         {
             rsxr.Close();
         }
     }
 }
示例#10
0
        private void button1_Click(object sender, EventArgs e)
        {
            List<DictionaryEntry> list = new List<DictionaryEntry>();
            DataSet dsData = new DataSet();

            dsData.ReadXml(@"..\..\..\..\..\..\Data\Orders.xml");

            //Create word document
            Document document = new Document();
            document.LoadFromFile(@"..\..\..\..\..\..\Data\Invoice.doc");

            DictionaryEntry dictionaryEntry = new DictionaryEntry("Customer", string.Empty);
            list.Add(dictionaryEntry);

            dictionaryEntry = new DictionaryEntry("Order", "Customer_Id = %Customer.Customer_Id%");
            list.Add(dictionaryEntry);

            document.MailMerge.ExecuteWidthNestedRegion(dsData, list);

            //Save doc file.
            document.SaveToFile("Sample.doc", FileFormat.Doc);

            //Launching the MS Word file.
            WordDocViewer("Sample.doc");
        }
示例#11
0
		public void All ()
		{
			HybridDictionary dict = new HybridDictionary (true);
			dict.Add ("CCC", "ccc");
			dict.Add ("BBB", "bbb");
			dict.Add ("fff", "fff");
			dict ["EEE"] = "eee";
			dict ["ddd"] = "ddd";
			
			Assert.AreEqual (5, dict.Count, "#1");
			Assert.AreEqual ("eee", dict["eee"], "#2");
			
			dict.Add ("CCC2", "ccc");
			dict.Add ("BBB2", "bbb");
			dict.Add ("fff2", "fff");
			dict ["EEE2"] = "eee";
			dict ["ddd2"] = "ddd";
			dict ["xxx"] = "xxx";
			dict ["yyy"] = "yyy";

			Assert.AreEqual (12, dict.Count, "#3");
			Assert.AreEqual ("eee", dict["eee"], "#4");

			dict.Remove ("eee");
			Assert.AreEqual (11, dict.Count, "Removed/Count");
			Assert.IsFalse (dict.Contains ("eee"), "Removed/Contains(xxx)");
			DictionaryEntry[] entries = new DictionaryEntry [11];
			dict.CopyTo (entries, 0);

			Assert.IsTrue (dict.Contains ("xxx"), "Contains(xxx)");
			dict.Clear ();
			Assert.AreEqual (0, dict.Count, "Cleared/Count");
			Assert.IsFalse (dict.Contains ("xxx"), "Cleared/Contains(xxx)");
		}
示例#12
0
 public override void Write(object obj, ES2Writer writer)
 {
     System.Collections.DictionaryEntry data = (System.Collections.DictionaryEntry)obj;
     // Add your writer.Write calls here.
     writer.Write(data.Key);
     writer.Write(data.Value);
 }
示例#13
0
		public void Ctor () {

			DictionaryEntry d = new DictionaryEntry (1, "something");
			Assert.IsNotNull (d);
			Assert.AreEqual (1, d.Key, "#01");
			Assert.AreEqual ("something", d.Value, "#02");
		}
 public void Add(object key, object value)
 {
     // Add the new key/value pair even if this key already exists in the dictionary. 
     if (ItemsInUse == items.Length)
         throw new InvalidOperationException("The dictionary cannot hold any more items.");
     items[ItemsInUse++] = new DictionaryEntry(key, value);
 }
示例#15
0
 internal override void SetSessionStateItem(string name, object value, bool writeItem)
 {
     if (value == null)
     {
         Environment.SetEnvironmentVariable(name, null);
     }
     else
     {
         if (value is DictionaryEntry)
         {
             value = ((DictionaryEntry)value).Value;
         }
         string str = value as string;
         if (str == null)
         {
             str = PSObject.AsPSObject(value).ToString();
         }
         Environment.SetEnvironmentVariable(name, str);
         DictionaryEntry item = new DictionaryEntry(name, str);
         if (writeItem)
         {
             WriteItemObject(item, name, false);
         }
     }
 }
 private static void AddressChangedCallback(object stateObject, bool signaled)
 {
     lock (s_callerArray)
     {
         s_isPending = false;
         if (s_isListening)
         {
             s_isListening = false;
             DictionaryEntry[] array = new DictionaryEntry[s_callerArray.Count];
             s_callerArray.CopyTo(array, 0);
             StartHelper(null, false, (StartIPOptions) stateObject);
             for (int i = 0; i < array.Length; i++)
             {
                 NetworkAddressChangedEventHandler key = (NetworkAddressChangedEventHandler) array[i].Key;
                 ExecutionContext context = (ExecutionContext) array[i].Value;
                 if (context == null)
                 {
                     key(null, EventArgs.Empty);
                 }
                 else
                 {
                     ExecutionContext.Run(context.CreateCopy(), s_runHandlerCallback, key);
                 }
             }
         }
     }
 }
示例#17
0
        private void ChangeProviderFactory(DictionaryEntry i)
        {
            var valueField = i.Value.GetType().GetField("_value", BindingFlags.NonPublic | BindingFlags.Instance);
            if (valueField != null)
            {
                var value = valueField.GetValue(i.Value);
                var workspaceField = value.GetType().GetField("_workspace", BindingFlags.NonPublic | BindingFlags.Instance);
                if (workspaceField != null)
                {
                    var workspace = workspaceField.GetValue(value);
                    var metadataWorkspaceField = workspace.GetType().GetField("_metadataWorkspace", BindingFlags.NonPublic | BindingFlags.Instance);
                    if (metadataWorkspaceField != null)
                    {
                        var metadataWorkspace = metadataWorkspaceField.GetValue(workspace);
                        var itemsSSpaceField = metadataWorkspace.GetType().GetField("_itemsSSpace", BindingFlags.NonPublic | BindingFlags.Instance);

                        if (itemsSSpaceField != null)
                        {
                            var itemsSSpace = itemsSSpaceField.GetValue(metadataWorkspace);
                            var providerFactoryField = itemsSSpace.GetType().GetField("_providerFactory", BindingFlags.NonPublic | BindingFlags.Instance);

                            if (providerFactoryField != null)
                            {
                                var providerFactory = providerFactoryField.GetValue(itemsSSpace);

                                providerFactoryField.SetValue(itemsSSpace, Activator.CreateInstance(GetProxyTypeForProvider(providerFactory.GetType())));
                            }
                        }
                    }
                }
            }
        }
		public void Ctor () {

			DictionaryEntry d = new DictionaryEntry (1, "something");
			AssertNotNull (d);
			AssertEquals ("#01", d.Key, 1);
			AssertEquals ("#02", d.Value, "something");
		}
示例#19
0
        internal WebCacheEnumerator(string serializationContext, Cache cache)
        {
            _cache = cache;
            _serializationContext = serializationContext;
            _de = new DictionaryEntry();

            Initialize();
        }
示例#20
0
        protected int DictentryCompare(DictionaryEntry d1, DictionaryEntry d2)
        {
            IComparable c1 = d1.Key as IComparable;
            IComparable c2 = d2.Key as IComparable;

            if(c1==null) return 0;
            return c1.CompareTo(c2);
        }
 public void TestAddBooleanParameter()
 {
     _generalSettingsManager.DeleteSelectedParameter("BOOLPARAM");
     DictionaryEntry entry = new DictionaryEntry("BOOLPARAM", true);
     _generalSettingsManager.AddParameter(entry);
     Assert.AreEqual(true, Convert.ToBoolean(_generalSettingsManager.SelectParameterValue("BOOLPARAM")));
     _generalSettingsManager.DeleteSelectedParameter("BOOLPARAM");
 }
 public void TestAddDateParameter()
 {
     _generalSettingsManager.DeleteSelectedParameter("DATEPARAM");
     DictionaryEntry entry = new DictionaryEntry("DATEPARAM", new DateTime(2006, 1, 1));
     _generalSettingsManager.AddParameter(entry);
     Assert.AreEqual(new DateTime(2006, 1, 1), Convert.ToDateTime(_generalSettingsManager.SelectParameterValue("DATEPARAM")));
     _generalSettingsManager.DeleteSelectedParameter("DATEPARAM");
 }
 public void TestAddIntParameter()
 {
     _generalSettingsManager.DeleteSelectedParameter("INTPARAM");
     DictionaryEntry entry = new DictionaryEntry("INTPARAM", 2);
     _generalSettingsManager.AddParameter(entry);
     Assert.AreEqual(2, Convert.ToInt32(_generalSettingsManager.SelectParameterValue("INTPARAM")));
     _generalSettingsManager.DeleteSelectedParameter("INTPARAM");
 }
示例#24
0
    public override object Read(ES2Reader reader)
    {
        System.Collections.DictionaryEntry data = new System.Collections.DictionaryEntry();
        data.Key   = reader.Read <System.Object>();
        data.Value = reader.Read <System.Object>();

        return(data);
    }
 /// <summary>
 /// Carrega os atributos no elemento XML.
 /// </summary>
 /// <param name="element"></param>
 internal void LoadAttributes(XmlElement element)
 {
     foreach (object obj in _stateBag)
     {
         System.Collections.DictionaryEntry entry = (System.Collections.DictionaryEntry)obj;
         element.SetAttribute((string)entry.Key, (string)((System.Web.UI.StateItem)entry.Value).Value);
     }
 }
示例#26
0
        public object SyncRoot { get { return collectionSyncLocker; } }                 //컬렉션에 대한 접근을 동기화할 때 사용하는 객체. Locker Object를 소유함으로써 멀티 쓰레드 환경에서 Mutual Exclusion을 구현한다.
        #endregion

        public SIMONCollection()
        {
            //Default 생성자.
            CollectionSize = SIMONConstants.DEFAULT_COLLECTION_SIZE;
            SIMONDictionary = new DictionaryEntry[CollectionSize];
            Count = 0;
            collectionSyncLocker = new object();
        }
示例#27
0
文件: MRUList.cs 项目: LionFree/Cush
 public void Remove(MRUEntry entry)
 {
     var de = new DictionaryEntry(entry.FullPath, entry);
     if (_mrus.Contains(de))
     {
         _mrus.Remove(de);
     }
 }
示例#28
0
		private bool IsRelevantResource(DictionaryEntry entry, string resourceName)
		{
			string entryName = entry.Key as string;
			string extension = Path.GetExtension(entryName);
			return
				string.Compare(extension, ".baml", true) == 0	&&											// the resource has a .baml extension
				entry.Value is Stream							&&											// the resource is a Stream
				(string.IsNullOrEmpty(resourceName) || string.Compare(resourceName, entryName, true) == 0);	// the resource name requested equals to current resource name
		}
示例#29
0
 private void Camera_button_Click(object sender, EventArgs e)
 {
     DictionaryEntry dict = new DictionaryEntry("Yes/No", MessageBoxServiceButton.YesNo);
     this._service.Closed += this.MessageBoxService_Closed;
     this._service.Show(
         "Do you want to...",
         "Change Profile Picture",
         (MessageBoxServiceButton)((DictionaryEntry)dict).Value);
 }
 public void TestAddDoubleParameter()
 {
     double val = 2;
     _generalSettingsManager.DeleteSelectedParameter("DOUBLEPARAM");
     DictionaryEntry entry = new DictionaryEntry("DOUBLEPARAM", val);
     _generalSettingsManager.AddParameter(entry);
     Assert.AreEqual(2, Convert.ToDouble(_generalSettingsManager.SelectParameterValue("DOUBLEPARAM")));
     _generalSettingsManager.DeleteSelectedParameter("DOUBLEPARAM");
 }
示例#31
0
 static DictionaryEntry nejmensiNezamestnanost()
 {
     DictionaryEntry min = new DictionaryEntry("MAX", 100);
     foreach (DictionaryEntry m in mesice)
     {
         if (Convert.ToDouble(m.Value) <= Convert.ToDouble(min.Value))
             min = m;
     }
     return min;
 }
示例#32
0
 static DictionaryEntry nejvetsiNezamestnanost()
 {
     DictionaryEntry max = new DictionaryEntry();
     foreach (DictionaryEntry m in mesice)
     {
         if (Convert.ToDouble(m.Value) > Convert.ToDouble(max.Value))
             max = m;
     }
     return max;
 }
示例#33
0
 public static void LoadGender(this ComboBox comboBox)
 {
     var items = comboBox.Items;
     items.Clear();
     var male = new DictionaryEntry(OGender.Male, OGender.Male.GenderString());
     var female = new DictionaryEntry(OGender.Female, OGender.Female.GenderString());
     items.Add(male);
     items.Add(female);
     comboBox.SelectedItem = male;
 }
示例#34
0
 internal override object GetSessionStateItem(string name)
 {
     object obj2 = null;
     string environmentVariable = Environment.GetEnvironmentVariable(name);
     if (environmentVariable != null)
     {
         obj2 = new DictionaryEntry(name, environmentVariable);
     }
     return obj2;
 }
示例#35
0
        public static bool getAttributes(object item, List <XmlSchemaAttribute> attributes)
        {
            if (item is XmlSchemaComplexType)
            {
                XmlSchemaComplexType complexType = (XmlSchemaComplexType)item;
                foreach (object entry in complexType.AttributeUses)
                {
                    object o = null;
                    if (entry is System.Collections.DictionaryEntry)
                    {
                        System.Collections.DictionaryEntry de = (System.Collections.DictionaryEntry)entry;
                        object key   = de.Key;
                        object value = de.Value;
                        o = value;
                    }
                    if (o is XmlSchemaAttribute)
                    {
                        attributes.Add((XmlSchemaAttribute)o);
                    }
                    else if (o is XmlSchemaAttributeGroupRef)
                    {
                        XmlSchemaAttributeGroupRef groupRef = (XmlSchemaAttributeGroupRef)o;
                        XmlQualifiedName           qname    = groupRef.RefName;
                        if (qname != null)
                        {
                            XmlSchemaAttributeGroup group = null;
                            if (SchemaManager.GetAttributeGroup(qname.Namespace, qname.Name, out group))
                            {
                                foreach (object oo in group.Attributes)
                                {
                                    if (oo is XmlSchemaAttribute)
                                    {
                                        attributes.Add((XmlSchemaAttribute)oo);
                                    }
                                }
                            }
                        }
                    }
                }

                if (complexType.ContentModel != null && complexType.ContentModel.Content is XmlSchemaComplexContentExtension)
                {
                    XmlSchemaComplexContentExtension ext = (XmlSchemaComplexContentExtension)complexType.ContentModel.Content;
                    XmlSchemaComplexType             baseType;
                    if (ext.BaseTypeName != null && SchemaManager.GetComplexType(ext.BaseTypeName.Namespace, ext.BaseTypeName.Name, out baseType))
                    {
                        getAttributes(baseType, attributes);
                    }
                }
            }

            return(attributes.Count > 0);
        }
        void SC.ICollection.CopyTo(Array array, int index)
        {
            if (array == null)
            {
                throw new ArgumentNullException("array");
            }

            if (index < 0)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            if (index >= array.Length)
            {
                throw new ArgumentException(SR.Get(SRID.Collection_CopyTo_IndexGreaterThanOrEqualToArrayLength, "index", "array"));
            }

            if (_innerDictionary.Count > array.Length - index)
            {
                throw new ArgumentException(SR.Get(SRID.Collection_CopyTo_NumberOfElementsExceedsArrayLength, index, "array"));
            }

            SC.DictionaryEntry[] typedArray = array as SC.DictionaryEntry[];
            if (typedArray != null)
            {
                // it's an array of the exact type
                foreach (KeyValuePair <XmlLanguage, string> item in _innerDictionary)
                {
                    typedArray[index++] = new SC.DictionaryEntry(item.Key, item.Value);
                }
            }
            else
            {
                // it's an array of some other type, e.g., object[]; make sure it's one dimensional
                if (array.Rank != 1)
                {
                    throw new ArgumentException(SR.Get(SRID.Collection_CopyTo_ArrayCannotBeMultidimensional));
                }

                // make sure the element type is compatible
                Type elementType = array.GetType().GetElementType();
                if (!elementType.IsAssignableFrom(typeof(SC.DictionaryEntry)))
                {
                    throw new ArgumentException(SR.Get(SRID.CannotConvertType, typeof(SC.DictionaryEntry), elementType));
                }

                foreach (KeyValuePair <XmlLanguage, string> item in _innerDictionary)
                {
                    array.SetValue(new SC.DictionaryEntry(item.Key, item.Value), index++);
                }
            }
        }
示例#37
0
        // Remote controller setting up the solution
        private void PrepareSolution(GH_Document gH_Document)
        {
            System.Collections.DictionaryEntry t = JobQueue.Cast <DictionaryEntry>().ElementAt(0);
            CurrentJobClient = ( string )t.Key;

            foreach (dynamic param in ( IEnumerable )t.Value)
            {
                IGH_DocumentObject controller = null;
                try
                {
                    controller = Document.Objects.First(doc => doc.InstanceGuid.ToString() == param.guid);
                }
                catch { }
                if (controller != null)
                {
                    switch (( string )param.inputType)
                    {
                    case "TextPanel":
                        GH_Panel panel = controller as GH_Panel;
                        panel.UserText = ( string )param.value;
                        panel.ExpireSolution(false);
                        break;

                    case "Slider":
                        GH_NumberSlider slider = controller as GH_NumberSlider;
                        slider.SetSliderValue(decimal.Parse(param.value.ToString()));
                        break;

                    case "Toggle":
                        break;

                    default:
                        break;
                    }
                }
            }
            SolutionPrepared = true;
        }
示例#38
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            _DA          = DA;
            this.Message = "JobQueue: " + JobQueue.Count;
            if (mySender == null)
            {
                return;
            }

            DA.SetData(0, Log);
            DA.SetData(1, mySender.StreamId);

            if (!mySender.IsConnected)
            {
                return;
            }
            if (JobQueue.Count == 0)
            {
                return;
            }

            if (!solutionPrepared)
            {
                System.Collections.DictionaryEntry t = JobQueue.Cast <DictionaryEntry>().ElementAt(0);
                CurrentJobClient = ( string )t.Key;
                PrepareSolution(( IEnumerable )t.Value);
                solutionPrepared = true;
                return;
            }
            else
            {
                solutionPrepared = false;

                var BucketObjects = GetData();

                var convertedObjects = Converter.Serialise(BucketObjects).Select(obj =>
                {
                    if (ObjectCache.ContainsKey(obj.Hash))
                    {
                        return new SpeckleObjectPlaceholder()
                        {
                            Hash = obj.Hash, DatabaseId = ObjectCache[obj.Hash].DatabaseId
                        }
                    }
                    ;
                    return(obj);
                });

                List <SpeckleInputParam>  inputControllers  = null;
                List <SpeckleOutputParam> outputControllers = null;
                GetDefinitionIO(ref inputControllers, ref outputControllers);

                List <ISpeckleControllerParam> measures = new List <ISpeckleControllerParam>();
                foreach (var x in inputControllers)
                {
                    measures.Add(x);
                }
                foreach (var x in outputControllers)
                {
                    measures.Add(x);
                }

                PayloadStreamCreate myNewStreamPayload = new PayloadStreamCreate
                {
                    IsComputed     = true,
                    Parent         = mySender.StreamId,
                    GlobalMeasures = measures,
                    Name           = this.NickName,
                    Layers         = GetLayers(),
                    Objects        = convertedObjects
                };

                mySender.StreamCreateAsync(myNewStreamPayload).ContinueWith(tres =>
                {
                    Dictionary <string, object> args = new Dictionary <string, object>();
                    args["eventType"] = "computation-result";
                    args["streamId"]  = tres.Result.Stream.StreamId;
                    args["outputRef"] = outputControllers;

                    mySender.SendMessage(CurrentJobClient, args);
                    int k = 0;
                    foreach (var obj in convertedObjects)
                    {
                        obj.DatabaseId = tres.Result.Stream.Objects[k++];

                        ObjectCache[obj.Hash] = obj;
                    }
                });

                JobQueue.RemoveAt(0);
                this.Message = "JobQueue: " + JobQueue.Count;
                if (JobQueue.Count != 0)
                {
                    Rhino.RhinoApp.MainApplicationWindow.Invoke(ExpireComponentAction);
                }
            }
        }
示例#39
0
 public Pair(System.Collections.DictionaryEntry entry)
 {
     this.First  = (TKey)((object)entry.Key);
     this.Second = (TValue)((object)entry.Value);
 }
示例#40
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (mySender == null)
            {
                return;
            }

            if (this.EnableRemoteControl)
            {
                this.Message = "JobQueue: " + JobQueue.Count;
            }

            StreamId = mySender.StreamId;

            DA.SetData(0, Log);
            DA.SetData(1, mySender.StreamId);

            if (!mySender.IsConnected)
            {
                return;
            }

            if (WasSerialised && FirstSendUpdate)
            {
                FirstSendUpdate = false;
                return;
            }

            this.State = "Expired";

            // All flags are good to start an update
            if (!this.EnableRemoteControl && !this.ManualMode)
            {
                UpdateData();
                return;
            }
            //
            else if (!this.EnableRemoteControl && this.ManualMode)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "State is expired, update push is required.");
                return;
            }

            #region RemoteControl

            // Code below deals with the remote control functionality.
            // Proceed at your own risk.
            if (JobQueue.Count == 0)
            {
                SetDefaultState();
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Updated default state for remote control.");
                return;
            }

            // prepare solution and exit
            if (!SolutionPrepared && JobQueue.Count != 0)
            {
                System.Collections.DictionaryEntry t = JobQueue.Cast <DictionaryEntry>().ElementAt(0);
                Document.ScheduleSolution(1, PrepareSolution);
                return;
            }

            // send out solution and exit
            if (SolutionPrepared)
            {
                SolutionPrepared = false;
                var BucketObjects    = GetData();
                var BucketLayers     = GetLayers();
                var convertedObjects = Converter.Serialise(BucketObjects).Select(obj =>
                {
                    if (ObjectCache.ContainsKey(obj.Hash))
                    {
                        return new SpecklePlaceholder()
                        {
                            Hash = obj.Hash, _id = ObjectCache[obj.Hash]._id
                        }
                    }
                    ;
                    return(obj);
                });


                // theoretically this should go through the same flow as in DataSenderElapsed(), ie creating
                // buckets for staggered updates, etc. but we're lazy to untangle that logic for now

                var responseClone  = mySender.StreamCloneAsync(this.StreamId).Result;
                var responseStream = new SpeckleStream();

                responseStream.IsComputedResult = true;

                responseStream.Objects = convertedObjects.ToList();
                responseStream.Layers  = BucketLayers;

                List <SpeckleInput>  speckleInputs  = null;
                List <SpeckleOutput> speckleOutputs = null;
                GetSpeckleParams(ref speckleInputs, ref speckleOutputs);

                responseStream.GlobalMeasures = new { input = speckleInputs, output = speckleOutputs };

                // go unblocking
                var responseCloneUpdate = mySender.StreamUpdateAsync(responseClone.Clone.StreamId, responseStream).ContinueWith(tres =>
                {
                    mySender.SendMessage(CurrentJobClient, new { eventType = "compute-response", streamId = responseClone.Clone.StreamId });
                });


                JobQueue.RemoveAt(0);
                this.Message = "JobQueue: " + JobQueue.Count;

                if (JobQueue.Count != 0)
                {
                    Rhino.RhinoApp.MainApplicationWindow.Invoke(ExpireComponentAction);
                }
            }

            #endregion
        }
 public static System.Collections.Generic.KeyValuePair <K, V> DictionaryEntryToKeyValuePairConverter <K, V>(Object item)
 {
     System.Collections.DictionaryEntry dictionaryEntry = (System.Collections.DictionaryEntry)item;
     return(new System.Collections.Generic.KeyValuePair <K, V>((K)dictionaryEntry.Key, (V)dictionaryEntry.Value));
 }