internal static void PackageKeys(IDictionaryEnumerator dicEnu, out string keyPackage, out int keyCount)
        {
            StringBuilder keys = new StringBuilder(1024);
            keyCount = 0;

            while (dicEnu.MoveNext())
            {
                keys.Append(dicEnu.Key + "\"");
                keyCount++;
            }

            keyPackage = keys.ToString();
        }
Exemple #2
0
 /// <summary>
 /// Populates the trees' right list with objects contained in the enumerator.
 /// </summary>
 /// <param name="e"></param>
 public void Populate(IDictionaryEnumerator e) 
 {
     if (e != null)
     {
         if (_rightList == null) _rightList = new ArrayList();
         if (e is RedBlackEnumerator)
         {
             while (e.MoveNext())
             {
                 HashVector tbl = e.Value as HashVector;
                 
                 _rightList.AddRange(tbl.Keys);
             }
         }
         else
         {
             while (e.MoveNext())
             {
                 _rightList.Add(e.Key);
             }
         }
     }
 }
        /// <summary>
        /// Constructs a new instance of <see cref="MinifierResourceStrings"/>.
        /// </summary>
        /// <param name="enumerator">The dictionary to enumerate for values.</param>
        public MinifierResourceStrings(IDictionaryEnumerator enumerator)
        {
            this.NameValuePairs = new Dictionary<string, string>();

            if (enumerator != null)
            {
                // use the IDictionaryEnumerator to add properties to the collection
                while (enumerator.MoveNext())
                {
                    // get the property name
                    string propertyName = enumerator.Key.ToString();

                    // set the name/value in the resource object
                    this.NameValuePairs[propertyName] = enumerator.Value.ToString();
                }
            }
        }
		private void SetEnumerator(int i)
		{
			if (_enumerator == null)
			{
				_enumerator = _dictionary.GetEnumerator();
				_enumerator.MoveNext();
			}

			if (_currentIndex > i)
			{
				_currentIndex = 0;
				_enumerator.Reset();
				_enumerator.MoveNext();
			}

			for (; _currentIndex < i; _currentIndex++)
				_enumerator.MoveNext();
		}
Exemple #5
0
 static int VerifyDictionaryEnumerator(IDictionaryEnumerator de, IterationOrder order)
 {
     string prev = "";
     if (order == IterationOrder.DescentOrder)
         prev = "9999999999999999999";
     int i = 0;
     while (de.MoveNext())
     {
         DictionaryEntry e1 = (DictionaryEntry)de.Current;
         DictionaryEntry e2 = de.Entry;
         Tests.Assert(e1.Equals(e2));
         string k = (string)e1.Key;
         string k2 = (string)de.Key;
         Tests.Assert(k == k2);
         RecordFull v1 = (RecordFull)e1.Value;
         RecordFull v2 = (RecordFull)de.Value;
         Tests.Assert(v1.Equals(v2));
         Tests.Assert(v1.StrVal == k);
         if (order == IterationOrder.AscentOrder)
             Tests.Assert(k.CompareTo(prev) >= 0);
         else
             Tests.Assert(k.CompareTo(prev) <= 0);
         prev = k;
         i++;
     }
     Tests.VerifyDictionaryEnumeratorDone(de);
     return i;
 }
Exemple #6
0
        } // GetMachineAddress

        //
        // Core Serialization and Deserialization support
        //
        internal static Header[] GetMessagePropertiesAsSoapHeader(IMessage reqMsg)
        {
            IDictionary d = reqMsg.Properties;

            if (d == null)
            {
                return(null);
            }

            int count = d.Count;

            if (count == 0)
            {
                return(null);
            }

            IDictionaryEnumerator e = (IDictionaryEnumerator)d.GetEnumerator();

            // cycle through the headers to get a length
            bool[]         map = new bool[count];
            int            len = 0, i = 0;
            IMethodMessage msg = (IMethodMessage)reqMsg;

            while (e.MoveNext())
            {
                String key = (String)e.Key;
                if ((key.Length >= 2) &&
                    (String.CompareOrdinal(key, 0, "__", 0, 2) == 0)
                    &&
                    (
                        key.Equals("__Args")
                        ||
                        key.Equals("__OutArgs")
                        ||
                        key.Equals("__Return")
                        ||
                        key.Equals("__Uri")
                        ||
                        key.Equals("__MethodName")
                        ||
                        (key.Equals("__MethodSignature") &&
                         (!RemotingServices.IsMethodOverloaded(msg)) &&
                         (!msg.HasVarArgs))
                        ||
                        key.Equals("__TypeName")
                        ||
                        key.Equals("__Fault")
                        ||
                        (key.Equals("__CallContext") &&
                         ((e.Value != null) ? (((LogicalCallContext)e.Value).HasInfo == false) : true))
                    )
                    )
                {
                    i++;
                    continue;
                }
                map[i] = true;
                i++;
                len++;
            }
            if (len == 0)
            {
                return(null);
            }


            Header[] ret = new Header[len];
            e.Reset();
            int k = 0;

            i = 0;
            while (e.MoveNext())
            {
                Object key = e.Key;
                if (!map[k])
                {
                    k++;
                    continue;
                }

                Header h = e.Value as Header;

                // If the property is not a header, then make a header out of it.
                if (h == null)
                {
                    h =
                        new Header(
                            (String)key, e.Value, false,
                            "http://schemas.microsoft.com/clr/soap/messageProperties");
                }

                // <
                if (i == ret.Length)
                {
                    InternalRemotingServices.RemotingTrace("HTTPChannel::GetHeaders creating a new array of length " + (i + 1) + "\n");
                    Header[] newret = new Header[i + 1];
                    Array.Copy(ret, newret, i);
                    ret = newret;
                }
                ret[i] = h;
                i++;
                k++;
            }

            return(ret);
        } // GetMessagePropertiesAsSoapHeader
Exemple #7
0
        private void btnsCrea_Click(object sender, System.EventArgs e)
        {
            Classi.ManProgrammata.CreaPiano _CP = new TheSite.Classi.ManProgrammata.CreaPiano();
            if (Session["DatiList"] != null)
            {
                _CP.beginTransaction();

                try
                {
                    Hashtable             _HS          = (Hashtable)Session["DatiList"];
                    IDictionaryEnumerator myEnumerator = _HS.GetEnumerator();
                    string mesegiorno = String.Empty;

                    string mes = String.Empty;

                    while (myEnumerator.MoveNext())
                    {
                        S_Controls.Collections.S_ControlsCollection CollezioneControlli = new S_Controls.Collections.S_ControlsCollection();

                        DataGridField _campi = (DataGridField)myEnumerator.Value;

                        // DATA
                        S_Controls.Collections.S_Object s_Data = new S_Object();
                        s_Data.ParameterName = "i_DataFine";
                        s_Data.DbType        = CustomDBType.Integer;
                        s_Data.Direction     = ParameterDirection.Input;
                        s_Data.Index         = 0;
                        s_Data.Value         = Int16.Parse(cmbsAnnoA.SelectedValue);
                        CollezioneControlli.Add(s_Data);
                        // IDBL
                        S_Controls.Collections.S_Object s_Idbl = new S_Object();
                        s_Idbl.ParameterName = "i_Edificio";
                        s_Idbl.DbType        = CustomDBType.Integer;
                        s_Idbl.Direction     = ParameterDirection.Input;
                        s_Idbl.Index         = 1;
                        s_Idbl.Value         = _campi.idbl;
                        CollezioneControlli.Add(s_Idbl);
                        // IDSERVIZIO
                        S_Controls.Collections.S_Object s_IdServizio = new S_Object();
                        s_IdServizio.ParameterName = "i_Category";
                        s_IdServizio.DbType        = CustomDBType.Integer;
                        s_IdServizio.Direction     = ParameterDirection.Input;
                        s_IdServizio.Index         = 2;
                        s_IdServizio.Value         = _campi.idservizio;
                        CollezioneControlli.Add(s_IdServizio);
                        // IDADDETTO
                        S_Controls.Collections.S_Object s_IdAddetto = new S_Object();
                        s_IdAddetto.ParameterName = "p_idaddetto";
                        s_IdAddetto.DbType        = CustomDBType.Integer;
                        s_IdAddetto.Direction     = ParameterDirection.Input;
                        s_IdAddetto.Index         = 3;
                        s_IdAddetto.Value         = _campi.idaddetto;
                        CollezioneControlli.Add(s_IdAddetto);
                        //DATASTART
                        S_Controls.Collections.S_Object s_DataStart = new S_Object();
                        s_DataStart.ParameterName = "p_datastart";
                        s_DataStart.DbType        = CustomDBType.VarChar;
                        s_DataStart.Direction     = ParameterDirection.Input;
                        s_DataStart.Index         = 4;
                        s_DataStart.Value         = _campi.mesegiorno;
                        CollezioneControlli.Add(s_DataStart);
                        //IDDITTA
                        S_Controls.Collections.S_Object s_Ditta = new S_Object();
                        s_Ditta.ParameterName = "p_idditta";
                        s_Ditta.DbType        = CustomDBType.Integer;
                        s_Ditta.Direction     = ParameterDirection.Input;
                        s_Ditta.Index         = 5;
                        s_Ditta.Value         = _campi.idditta;
                        CollezioneControlli.Add(s_Ditta);

                        // PAOLO: 24/02/06
                        pippo = (resultSchedula)_CP.CreaPianoMP(CollezioneControlli);

                        // OLD:
                        //  _result = _CP.CreaPianoMP(CollezioneControlli);
                    }
                    _CP.commitTransaction();

                    // PAOLO

                    switch (pippo)
                    {
                    case  resultSchedula.NO_PROCED_MAN:
                        mes = "Nessuna procedura per l'edificio e il servizio selezionati!";
                        break;

                    case  resultSchedula.GIA_SCHEDULATO:
                        mes = "Procedura già schedulata per l'anno selezionato.!";
                        break;

                    case resultSchedula.NO_ADD_SPECIALIZZATO:
                        mes = "Nessun addetto per la specializzazione corrente!";
                        break;

                    case resultSchedula.DATA_FUORI_INTERVALLO:
                        mes = "La data selezionata è fuori dell'intervallo di validità!";
                        break;

                    case resultSchedula.NO_STAGIONALE:
                        mes = "Non è stata trovata una corrispondenza stagionale!";
                        break;

                    case resultSchedula.NO_FREQ_FISSE:
                        mes = "Non sono previste frequenze di tipo fisso per il seguente servizio!";
                        break;

                    case resultSchedula.SCHEDULAZIONE_OK:

                        // Visualizzo la stringa del messaggio di conferma AGGIORNAMENTO nel DB
                        string tot = txtTotSelezionati.Text;
                        if (Int16.Parse(tot) > 1)
                        {
                            mes = "Sono stati Pianificati " + tot + " Edifici nel Piano di Manutenzione";
                        }
                        else
                        {
                            mes = "E` stato Pianificato " + tot + " Edificio nel Piano di Manutenzione";
                        }
                        break;
                    }

                    //  FINE


                    /* if (_result==1)
                     * {
                     *
                     *      // Visualizzo la stringa del messaggio di conferma AGGIORNAMENTO nel DB
                     *      string tot=txtTotSelezionati.Text;
                     *      if(Int16.Parse(tot)>1)
                     *              mes="Sono stati Pianificati " + tot + " Edifici nel Piano di Manutenzione";
                     *      else
                     *              mes="E` stato Pianificato " + tot + " Edificio nel Piano di Manutenzione";
                     * }
                     * else
                     * {
                     *      mes="Non Tutte le attività sono state inserite nel piano";
                     * } */


                    Resetta();
                    DataGridRicerca.CurrentPageIndex = 0;
                    Ricerca(true);

                    //Visualizzo il messaggio
                    Classi.SiteJavaScript.msgBox(this.Page, mes);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    _CP.rollbackTransaction();
                    string mes = String.Empty;
                    //mes = ex.Message.ToString();
                    mes = "Si è verificato un errore durante la creazione del Piano.";
                    Classi.SiteJavaScript.msgBox(this.Page, mes);
                }
            }
            else
            {
                Classi.SiteJavaScript.msgBox(this.Page, "Nessun Edificio selezionato.");
            }
        }
        public ILocalizer Load(IDictionaryEnumerator reader, out IEnumerable<string> missing, out IEnumerable<string> extra)
        {
            var lmissing = new List<string>();
            var lextra = new List<string>();
            var newLocalizer = new Localizer();
            while (reader.MoveNext())
            {
                var entry = (DictionaryEntry) reader.Current;
                var fullKey = (string)entry.Key;
                var semi = fullKey.LastIndexOf(SEPARATOR[0]);
                var key = fullKey.Substring(0, semi);
                var type = fullKey.Substring(semi + 1);
                var val = (string)entry.Value;
                if (type == "VALUE")
                {
                    newLocalizer.Add(key, val);
                }
                else if (type == "LIST")
                {
                    newLocalizer.Add(key, val.SplitList().ToArray());
                }
                else if (type == "TEMPLATE")
                {
                    var elements = key.SplitList();
                    var usage = elements.First();
                    var fields = elements.Skip(1);
                    var patterns = val.SplitList();
                    var template = new TemplateAttribute((TemplateUsage)Enum.Parse(typeof(TemplateUsage), usage), patterns.ToArray());
                    foreach (var field in fields)
                    {
                        newLocalizer.Add(field, template);
                    }
                }
            }

            // Find missing and extra keys
            lmissing.AddRange(_translations.Keys.Except(newLocalizer._translations.Keys));
            lmissing.AddRange(_arrayTranslations.Keys.Except(newLocalizer._arrayTranslations.Keys));
            lmissing.AddRange(_templateTranslations.Keys.Except(newLocalizer._templateTranslations.Keys));
            lextra.AddRange(newLocalizer._translations.Keys.Except(_translations.Keys));
            lextra.AddRange(newLocalizer._arrayTranslations.Keys.Except(_arrayTranslations.Keys));
            lextra.AddRange(newLocalizer._templateTranslations.Keys.Except(_templateTranslations.Keys));
            missing = lmissing;
            extra = lextra;
            return newLocalizer;
        }
Exemple #9
0
 public KeyValueIteratorSequence(IDictionaryEnumerator iter)
 {
     this.iter = iter;
     if(iter != null) {
         hasNext = iter.MoveNext();
     }
 }
        private void PopulateConfiugrationObject(Object config, XmlNode node)
        {
            if (node == null || config == null)
            {
                return;
            }

            XmlAttributeCollection attribColl = node.Attributes;

            foreach (XmlAttribute xmlAttrib in attribColl)
            {
                FillConfigWithAttribValue(config, xmlAttrib);
            }

            XmlNodeList nodeList     = node.ChildNodes;
            Hashtable   sameSections = new Hashtable();

            for (int i = 0; i < nodeList.Count; i++)
            {
                XmlNode sectionNode = nodeList[i];
                Type    sectionType = null;

                if (sectionNode.Name.ToLower() == DYNAMIC_CONFIG_SECTION && sectionNode.HasChildNodes)
                {
                    ExtractDyanamicConfigSectionObjectType(sectionNode);
                }
            }
            for (int i = 0; i < nodeList.Count; i++)
            {
                XmlNode sectionNode = nodeList[i];
                Type    sectionType = null;
                if (sectionNode.Name.ToLower() == DYNAMIC_CONFIG_SECTION)
                {
                    continue;
                }

                sectionType = GetConfigSectionObjectType(config, sectionNode.Name);

                if (sectionType != null)
                {
                    if (sectionType.IsArray)
                    {
                        string    nonArrayType    = sectionType.FullName.Replace("[]", "");
                        ArrayList sameSessionList = null;
                        Hashtable tmp             = null;
                        if (!sameSections.Contains(sectionType))
                        {
                            tmp = new Hashtable();
                            tmp.Add("section-name", sectionNode.Name);

                            sameSessionList = new ArrayList();
                            tmp.Add("section-list", sameSessionList);
                            sameSections.Add(sectionType, tmp);
                        }
                        else
                        {
                            tmp             = sameSections[sectionType] as Hashtable;
                            sameSessionList = tmp["section-list"] as ArrayList;
                        }

#if !NETCORE
                        ObjectHandle objHandle           = Activator.CreateInstance(sectionType.Assembly.FullName, nonArrayType);
                        object       singleSessionObject = objHandle.Unwrap();
#elif NETCORE
                        var singleSessionObject = Activator.CreateInstance(sectionType.GetElementType()); //TODO: ALACHISOFT (This method is changed)
#endif
                        PopulateConfiugrationObject(singleSessionObject, sectionNode);
                        sameSessionList.Add(singleSessionObject);
                    }
                    else
                    {
#if !NETCORE
                        ObjectHandle objHandle     = Activator.CreateInstance(sectionType.Assembly.FullName, sectionType.FullName);
                        object       sectionConfig = objHandle.Unwrap();
#elif NETCORE
                        var sectionConfig = Activator.CreateInstance(sectionType); //TODO: ALACHISOFT (This method is changed)
#endif
                        PopulateConfiugrationObject(sectionConfig, sectionNode);
                        SetConfigSectionObject(config, sectionConfig, sectionNode.Name);
                    }
                }
            }
            if (sameSections.Count > 0)
            {
                Hashtable             tmp;
                IDictionaryEnumerator ide = sameSections.GetEnumerator();
                while (ide.MoveNext())
                {
                    Type arrType = ide.Key as Type;
                    tmp = ide.Value as Hashtable;
                    ArrayList sameSessionList = tmp["section-list"] as ArrayList;
                    string    sectionName     = tmp["section-name"] as string;
                    object[]  sessionArrayObj = Activator.CreateInstance(arrType, new object[] { sameSessionList.Count }) as object[];
                    if (sessionArrayObj != null)
                    {
                        for (int i = 0; i < sameSessionList.Count; i++)
                        {
                            sessionArrayObj[i] = sameSessionList[i];
                        }
                        SetConfigSectionObject(config, sessionArrayObj, sectionName);
                    }
                }
            }
        }
		// Implement the IEnumerator interface.
		public bool MoveNext()
				{
					if(e != null)
					{
						return e.MoveNext();
					}
					else
					{
						++index;
						if(index < properties.properties.Length)
						{
							return true;
						}
						e = properties.dict.GetEnumerator();
						return e.MoveNext();
					}
				}
        protected void LastChangeSink(CpAVTransport sender, string LC)
        {
            if (LC == "")
            {
                return;
            }
            //LC = UPnPStringFormatter.UnEscapeString(LC);
            if (LC.Substring(0, 1) != "<")
            {
                LC = UPnPStringFormatter.UnEscapeString(LC);
            }
            if (LC.Substring(0, 1) != "<")
            {
                LC = UPnPStringFormatter.UnEscapeString(LC);
            }

            StringReader  MyString = new StringReader(LC);
            XmlTextReader XMLDoc   = new XmlTextReader(MyString);

            Hashtable T = new Hashtable();

            int    ID        = -1;
            string VarName   = "";
            string VarValue  = "";
            string AttrName  = "";
            string AttrValue = "";

            XMLDoc.Read();
            XMLDoc.MoveToContent();

            XMLDoc.Read();
            XMLDoc.MoveToContent();

            while ((XMLDoc.LocalName != "Event") && (XMLDoc.EOF == false))
            {
                // At Start, should be InstanceID
                if (XMLDoc.LocalName == "InstanceID")
                {
                    XMLDoc.MoveToAttribute("val");
                    ID = int.Parse(XMLDoc.GetAttribute("val"));
                    if (T.ContainsKey(ID) == false)
                    {
                        T[ID] = new Hashtable();
                    }
                    XMLDoc.MoveToContent();

                    XMLDoc.Read();
                    XMLDoc.MoveToContent();

                    while (XMLDoc.LocalName != "InstanceID")
                    {
                        if (XMLDoc.IsStartElement() == true)
                        {
                            VarName   = XMLDoc.LocalName;
                            VarValue  = "";
                            AttrName  = "";
                            AttrValue = "";

                            for (int a_idx = 0; a_idx < XMLDoc.AttributeCount; ++a_idx)
                            {
                                XMLDoc.MoveToAttribute(a_idx);
                                if (XMLDoc.LocalName == "val")
                                {
                                    VarValue = UPnPStringFormatter.UnEscapeString(XMLDoc.GetAttribute(a_idx));
                                }
                                else
                                {
                                    AttrName  = XMLDoc.LocalName;
                                    AttrValue = XMLDoc.GetAttribute(a_idx);
                                }
                            }

                            XMLDoc.MoveToContent();

                            if (AttrName == "")
                            {
                                ((Hashtable)T[ID])[VarName] = VarValue;
                            }
                            else
                            {
                                if (((Hashtable)T[ID]).ContainsKey(VarName) == false)
                                {
                                    ((Hashtable)T[ID])[VarName] = new Hashtable();
                                }
                                if (((Hashtable)((Hashtable)T[ID])[VarName]).ContainsKey(AttrName) == false)
                                {
                                    ((Hashtable)((Hashtable)T[ID])[VarName])[AttrName] = new Hashtable();
                                }
                                ((Hashtable)((Hashtable)((Hashtable)T[ID])[VarName])[AttrName])[AttrValue] = VarValue;
                            }
                        }
                        XMLDoc.Read();
                        XMLDoc.MoveToContent();
                    }
                }
                else
                {
                    XMLDoc.Skip();
                }
                XMLDoc.Read();
                XMLDoc.MoveToContent();
            }

            XMLDoc.Close();


            IDictionaryEnumerator inEn = T.GetEnumerator();
            IDictionaryEnumerator EvEn;
            Hashtable             TT;
            string TempString;
            DText  TempParser = new DText();

            while (inEn.MoveNext())
            {
                if (inEn.Key.ToString() == InstanceID)
                {
                    TT   = (Hashtable)inEn.Value;
                    EvEn = TT.GetEnumerator();
                    while (EvEn.MoveNext())
                    {
                        switch ((string)EvEn.Key)
                        {
                        case "AVTransportURI":
                            _AVTransportURI = (string)EvEn.Value;
                            if (OnAVTransportURIChanged != null)
                            {
                                OnAVTransportURIChanged(this);
                            }
                            break;

                        case "TransportState":
                            _PlayState = (string)EvEn.Value;
                            if (OnPlayStateChanged != null)
                            {
                                OnPlayStateChanged(this);
                            }
                            break;

                        case "CurrentTrackDuration":
                            TempString          = (string)EvEn.Value;
                            TempParser.ATTRMARK = ":";
                            TempParser[0]       = TempString;
                            try
                            {
                                this._CurrentDuration = new TimeSpan(int.Parse(TempParser[1]), int.Parse(TempParser[2]), int.Parse(TempParser[3]));
                            }
                            catch (Exception)
                            {}
                            if (this.OnCurrentPositionChanged != null)
                            {
                                this.OnCurrentPositionChanged(this);
                            }
                            break;

                        case "RelativeTimePosition":
                            TempString            = (string)EvEn.Value;
                            TempParser.ATTRMARK   = ":";
                            TempParser[0]         = TempString;
                            this._CurrentPosition = new TimeSpan(int.Parse(TempParser[1]), int.Parse(TempParser[2]), int.Parse(TempParser[3]));
                            if (this.OnCurrentPositionChanged != null)
                            {
                                this.OnCurrentPositionChanged(this);
                            }
                            break;

                        case "NumberOfTracks":
                            try
                            {
                                _NumberOfTracks = UInt32.Parse((string)EvEn.Value);
                                if (OnNumberOfTracksChanged != null)
                                {
                                    OnNumberOfTracksChanged(this);
                                }
                            }
                            catch (Exception)
                            {}
                            break;

                        case "CurrentTrack":
                            try
                            {
                                _CurrentTrack = UInt32.Parse((string)EvEn.Value);
                                if (OnCurrentTrackChanged != null)
                                {
                                    OnCurrentTrackChanged(this);
                                }
                            }
                            catch (Exception)
                            {}
                            break;

                        case "CurrentTrackURI":
                            _TrackURI = (string)EvEn.Value;
                            if (OnTrackURIChanged != null)
                            {
                                OnTrackURIChanged(this);
                            }
                            break;

                        case "TransportStatus":
                            _TransportStatus = (string)EvEn.Value;
                            if (OnTransportStatusChanged != null)
                            {
                                OnTransportStatusChanged(this);
                            }
                            break;

                        case "AVTransportURIMetaData":
                            _AVTransportMetaData = (string)EvEn.Value;
                            if (this.OnCurrentURIMetaDataChanged != null)
                            {
                                OnCurrentURIMetaDataChanged(this);
                            }
                            break;

                        case "CurrentPlayMode":
                            _CurrentPlayMode = (string)EvEn.Value;
                            if (this.OnCurrentPlayModeChanged != null)
                            {
                                OnCurrentPlayModeChanged(this);
                            }
                            break;
                        }
                    }
                }
            }
        }
        private string checkInput()
        {
            string msg = "";

            int RID = DAL.User.GetUserID(txt_Analysis.Text.Trim(), 1);

            if (RID == 0)
            {
                msg += "请选择正确的分析人!";
            }
            else
            {
                hf_AnalysisID.Text = RID.ToString();
            }
            //判断是否有重复项
            List <string> All = new List <string>();
            Hashtable     ht  = new Hashtable();
            Dictionary <int, Dictionary <string, object> > modifiedDict = Grid1.GetModifiedDict();

            foreach (int rowIndex in modifiedDict.Keys)
            {
                All.Add(Grid1.DataKeys[rowIndex][1].ToString());
            }
            List <Dictionary <string, object> > newAddedList = Grid1.GetNewAddedList();

            for (int i = 0; i < newAddedList.Count; i++)
            {
                All.Add(newAddedList[i]["ItemName"].ToString());
            }
            List <int> deletedRows = Grid1.GetDeletedList();

            foreach (int rowIndex in deletedRows)
            {
                All.Remove(Grid1.DataKeys[rowIndex][1].ToString());
            }
            for (int i = 0; i < All.Count; i++)
            {
                if (ht.ContainsKey(All[i]))
                {
                    ht[All[i]] = int.Parse(ht[All[i]].ToString()) + 1;
                }
                else
                {
                    ht.Add(All[i], 1);
                }
            }
            IDictionaryEnumerator ie = ht.GetEnumerator();

            while (ie.MoveNext())
            {
                if (int.Parse(ie.Value.ToString()) > 1)
                {
                    msg += "监测项中出现重复项!";
                }
                //Console.WriteLine(ie.Key.ToString() + "记录条数:" + ie.Value);
            }

            //List<string> Add = new List<string>();
            //List<string> Add2 = new List<string>();
            //List<string> Update = new List<string>();



            //for (int i = 0; i < Add2.Count; i++)  //外循环是循环的次数
            //{
            //    for (int j = Add2.Count - 1; j > i; j--)  //内循环是 外循环一次比较的次数
            //    {

            //        if (Add2[i] == Add2[j])
            //        {
            //            Add2.RemoveAt(j);
            //        }

            //    }
            //}
            //if (Add.Count > Add2.Count)
            //{
            //    msg += "分析项中出现重复项!";
            //}

            //for (int i = 0; i < newAddedList.Count; i++)
            //{
            //    Add.Add(newAddedList[i]["ItemName"].ToString());
            //}
            //foreach (string s in Add)
            //{
            //    if (Update.Contains(s))
            //    {
            //        msg += "分析项中出现多个"+s+"!";
            //    }
            //}
            return(msg);
        }
Exemple #14
0
        public void LogInternal(APILogItem logItem)
        {
            using (StreamWriter w = File.AppendText(getFileName(logItem.LoggingTime)))
            {
                w.WriteLine(logItem.LoggingTime.ToString("MM/dd/yyyy hh:mm:ss.fff tt") + "\t" + logItem.Signature);
                if (logItem.NoOfKeys > 1)
                {
                    w.WriteLine(String.Format("{0,-30}\t Number of Keys = {1}", "", logItem.NoOfKeys.ToString()));
                }

                if (!String.IsNullOrEmpty(logItem.Key))
                {
                    w.WriteLine(String.Format("{0,-30}\t Key = {1}", " ", logItem.Key));
                }
                if (logItem.AbsolueExpiration != null)
                {
                    w.WriteLine(String.Format("{0,-30}\t Absolute Expiration = {1}", " ", logItem.AbsolueExpiration.ToString()));
                }
                if (logItem.SlidingExpiration != null)
                {
                    w.WriteLine(String.Format("{0,-30}\t Sliding Expiration = {1} milliseconds", " ", logItem.SlidingExpiration.Value.TotalMilliseconds));
                }
                if (logItem.Priority != null)
                {
                    w.WriteLine(String.Format("{0,-30}\t Priority = {1}", " ", logItem.Priority.ToString()));
                }

                if (!string.IsNullOrEmpty(logItem.Query))
                {
                    w.WriteLine(String.Format("{0,-30}\t Query = {1}", " ", logItem.Query.ToString()));
                }

                if (logItem.QueryValues != null)
                {
                    w.WriteLine(String.Format("{0,-30}\t Values:", " "));
                    IDictionaryEnumerator ide = logItem.QueryValues.GetEnumerator();
                    while (ide.MoveNext())
                    {
                        w.WriteLine(String.Format("{0,-30}\t\t Key = " + ide.Key.ToString() + "\tValue = " + ide.Value.ToString(), " "));
                    }
                }

                if (logItem.LockTimeout != null)
                {
                    w.WriteLine(String.Format("{0,-30}\t LockTimeout = {1} milliseconds", " ", logItem.LockTimeout.Value.TotalMilliseconds.ToString()));
                }
                if (logItem.AcquireLock != null)
                {
                    w.WriteLine(String.Format("{0,-30}\t AcquireLock = {1}", " ", logItem.AcquireLock.ToString()));
                }

                if (logItem.RuntimeAPILogItem != null)
                {
                    RuntimeAPILogItem rtLogItem = logItem.RuntimeAPILogItem;
                    string            avg       = rtLogItem.IsBulk ? "Average " : "";
                    if (rtLogItem.IsBulk)
                    {
                        w.WriteLine(String.Format("{0,-30}\t Number of Objects = {1}", " ", rtLogItem.NoOfObjects.ToString()));
                    }
                    w.WriteLine(String.Format("{0,-30}\t {1}Object Size (bytes) = {2}", " ", avg, rtLogItem.SizeOfObject));
                }

                if (logItem.NoOfObjectsReturned != null)
                {
                    w.WriteLine(String.Format("{0,-30}\t Number of Objects Returned = {1}", " ", logItem.NoOfObjectsReturned.ToString()));
                }
                if (logItem.ExceptionMessage != null)
                {
                    w.WriteLine(String.Format("{0,-30}\t Exception = {1}", " ", logItem.ExceptionMessage));
                }
                w.WriteLine();
            }
        }
Exemple #15
0
 private static void WriteJson(IJsonWrapper obj, JsonWriter writer)
 {
     if (obj == null)
     {
         writer.Write(null);
     }
     else if (obj.IsString)
     {
         writer.Write(obj.GetString());
     }
     else if (obj.IsBoolean)
     {
         writer.Write(obj.GetBoolean());
     }
     else if (obj.IsDouble)
     {
         writer.Write(obj.GetDouble());
     }
     else if (obj.IsInt)
     {
         writer.Write(obj.GetInt());
     }
     else if (obj.IsLong)
     {
         writer.Write(obj.GetLong());
     }
     else if (obj.IsArray)
     {
         writer.WriteArrayStart();
         IEnumerator enumerator = ((IEnumerable)obj).GetEnumerator();
         try
         {
             while (enumerator.MoveNext())
             {
                 object current = enumerator.Current;
                 WriteJson((JsonData)current, writer);
             }
         }
         finally
         {
             IDisposable disposable;
             if ((disposable = enumerator as IDisposable) != null)
             {
                 disposable.Dispose();
             }
         }
         writer.WriteArrayEnd();
     }
     else
     {
         if (!obj.IsObject)
         {
             return;
         }
         writer.WriteObjectStart();
         IDictionaryEnumerator enumerator2 = ((IDictionary)obj).GetEnumerator();
         try
         {
             while (enumerator2.MoveNext())
             {
                 DictionaryEntry dictionaryEntry = (DictionaryEntry)enumerator2.Current;
                 writer.WritePropertyName((string)dictionaryEntry.Key);
                 WriteJson((JsonData)dictionaryEntry.Value, writer);
             }
         }
         finally
         {
             IDisposable disposable2;
             if ((disposable2 = enumerator2 as IDisposable) != null)
             {
                 disposable2.Dispose();
             }
         }
         writer.WriteObjectEnd();
     }
 }
        /// <summary>
        /// Serializes the specified o.
        /// </summary>
        /// <param name="o">The o.</param>
        /// <param name="sb">The sb.</param>
        public override void Serialize(object o, StringBuilder sb)
        {
            IDictionary dic = o as IDictionary;

            if (dic == null)
            {
                throw new NotSupportedException();
            }

            IDictionaryEnumerator enumerable = dic.GetEnumerator();

            enumerable.Reset();
            bool b = true;

            if (!AjaxPro.Utility.Settings.OldStyle.Contains("renderJsonCompliant"))
            {
                sb.Append("[");
            }
            else
            {
                sb.Append("{");
            }

            while (enumerable.MoveNext())
            {
                if (b)
                {
                    b = false;
                }
                else
                {
                    sb.Append(",");
                }

                if (!AjaxPro.Utility.Settings.OldStyle.Contains("renderJsonCompliant"))
                {
                    sb.Append('[');
                    JavaScriptSerializer.Serialize(enumerable.Key, sb);
                    sb.Append(',');
                    JavaScriptSerializer.Serialize(enumerable.Value, sb);
                    sb.Append(',');
                    JavaScriptUtil.QuoteString(enumerable.Key.GetType().FullName, sb);
                    sb.Append(',');
                    JavaScriptUtil.QuoteString(enumerable.Value.GetType().FullName, sb);
                    sb.Append(']');
                }
                else
                {
                    if (enumerable.Key is String)
                    {
                        JavaScriptSerializer.Serialize(enumerable.Key, sb);
                    }
                    else if (enumerable.Key is Boolean)
                    {
                        JavaScriptSerializer.Serialize((bool)enumerable.Key == true ? "true" : "false", sb);
                    }
                    else
                    {
                        JavaScriptUtil.QuoteString(enumerable.Key.ToString(), sb);
                    }

                    sb.Append(':');
                    JavaScriptSerializer.Serialize(enumerable.Value, sb);
                }
            }

            if (!AjaxPro.Utility.Settings.OldStyle.Contains("renderJsonCompliant"))
            {
                sb.Append("]");
            }
            else
            {
                sb.Append("}");
            }
        }
 private static string DictEnumKeysToString(IDictionaryEnumerator e)
 {
     StringBuilder builder = new StringBuilder(0x100);
     if (e.MoveNext())
     {
         builder.Append(EncodeTab(e.Key));
         while (e.MoveNext())
         {
             builder.Append("\t");
             builder.Append(EncodeTab(e.Key));
         }
     }
     return builder.ToString();
 }
Exemple #18
0
        public DateTime Solve(Block[] pBlocks)
        {
            double mOverWeight = 0;

            if ((mOverWeight = AddBlocks(pBlocks)) > 0)
            {
                Console.WriteLine("\nToo much weight - your blocks are over by " + mOverWeight + " pounds.");
                return(DateTime.Now);;
            }

            double mTotalWeight = _emptyWeight + (_gasWeight * _startingGas);

            foreach (Block b in _blocks)
            {
                mTotalWeight += b.Weight;
            }
            if (mTotalWeight > _maxWeight)
            {
                Console.WriteLine("\nToo much weight - you're (overall) over by " + (mTotalWeight - _maxWeight) + " pounds.");
                return(DateTime.Now);
            }

            if (!InitCGRange())
            {
                return(DateTime.Now);
            }

            _solutionHash = new ArrayList();

            int[] mCurrent = new int[_blocks.Count];
            for (int i = 0; i < mCurrent.Length; i++)
            {
                mCurrent[i] = -1;
            }

            Hashtable             mPositions          = Positions();
            ArrayList             mAttemptedLocations = new ArrayList();
            IDictionaryEnumerator mEnum = mPositions.GetEnumerator();

            while (mEnum.MoveNext())
            {
                if (mAttemptedLocations.Contains(mEnum.Value))
                {
                    continue;
                }

                ArrayList mAlreadyAdded = new ArrayList();
                mAlreadyAdded.Add((int)mEnum.Key);

                for (int i = 0; i < mCurrent.Length; i++)
                {
                    mCurrent[i] = -1;
                }

                mAttemptedLocations.Add(mEnum.Value);
                if (Check(mCurrent, mPositions, 0, (int)mEnum.Key))
                {
                    mCurrent[0] = (int)mEnum.Key;
                    Next(mCurrent, mPositions, mAlreadyAdded, 0);
                }
            }

            Console.WriteLine("Searching " + _solutionCount + " solutions for CGs within envelope, then determining optimal CG...");

            ArrayList mCGs = new ArrayList();
            ArrayList mConfigurationHashes      = new ArrayList();
            Hashtable mConfigurations           = new Hashtable();
            Hashtable mConfigurationsAndRepeats = new Hashtable();
            bool      mRepeatConfigurationFound = false;
            double    mTotalMOI = 0;
            double    mBaseMOI  = _momentOfInertia;
            double    mCG       = 0;
            double    mHash     = 0;
            string    mVal      = "";

            if (_gasMomentSlope != 0)
            {
                mBaseMOI += ((_gasWeight * _startingGas) / _gasMomentSlope);
            }

            foreach (int[] ilist in _solutions)
            {
                if (mConfigurationsAndRepeats.Count != 0 && mConfigurationsAndRepeats.Count % 5000 == 0)
                {
                    Console.WriteLine("Searched through " + mConfigurationsAndRepeats.Count + " solutions...");
                }

                mTotalMOI = mBaseMOI;
                mVal      = "";

                for (int i = 0; i < ilist.Length; i++)
                {
                    Block mBlock = (Block)_blocks[i];
                    mBlock.ClearPosition();
                    Location mLocation = (Location)mPositions[ilist[i]];
                    mBlock.SetPosition(mLocation);
                    mVal += "\n\t" + mBlock.Name + "-" + mLocation.Name;
                }

                foreach (Location l in _locations)
                {
                    mTotalMOI += l.GetMoment();
                }

                mCG  = mTotalMOI / mTotalWeight;
                mVal = "CG: " + mCG + "\n" + mVal;

                mHash = GetHashCode(ilist);
                if (!mConfigurationHashes.Contains(mHash) && mCG >= _minCG && mCG <= _maxCG)
                {
                    if (mConfigurations.ContainsKey(mCG))
                    {
                        mRepeatConfigurationFound = true;
                        mConfigurationsAndRepeats.Add(mConfigurationsAndRepeats.Count, mVal);
                    }
                    else
                    {
                        mConfigurationsAndRepeats.Add(mCG, mVal);
                        mConfigurations.Add(mCG, mVal);
                        mCGs.Add(mCG);
                    }
                    mConfigurationHashes.Add(mHash);
                }
            }

            if (mConfigurations.Count == 0)
            {
                Console.WriteLine("\nNo valid solutions with a CG between " + _minCG + " and " + _maxCG + ".");
                return(DateTime.Now);
            }

            double mMidCG = (_maxCG + _minCG) / 2.0;
            double mDelta = double.MaxValue;
            double mOptCG = (double)mCGs[0];

            for (int i = 0; i < mCGs.Count; i++)
            {
                double mCurrentCG = (double)mCGs[i];
                if (Math.Abs(mMidCG - mCurrentCG) < mDelta)
                {
                    mOptCG = mCurrentCG;
                    mDelta = Math.Abs(mMidCG - mOptCG);
                }
            }

            Console.WriteLine("Number of solutions within envelope: " + mConfigurationsAndRepeats.Count);
            if (mRepeatConfigurationFound)
            {
                Console.WriteLine("Number of (additional) repeated solutions (same CG, different configuration): " + (mConfigurationsAndRepeats.Count - mConfigurations.Count));
            }
            Console.WriteLine("\nOptimal Solution (only for w/starting gas)\n");
            Console.WriteLine("Optimal CG: " + mMidCG);
            Console.WriteLine("Distance from optimal CG: " + mDelta);
            Console.Write((string)mConfigurations[mOptCG]);
            Console.WriteLine();

            DateTime mDone = DateTime.Now;

            Console.Write("\nView all solutions? (Enter Y for yes, anything else to quit.) ");
            string mResponse = Console.ReadLine();

            if (mResponse.ToUpper() == "Y")
            {
                int mSolutionCount = 0;
                foreach (string s in mConfigurationsAndRepeats.Values)
                {
                    mSolutionCount++;
                    Console.WriteLine("Solution #" + mSolutionCount);
                    Console.WriteLine(s);
                }
            }

            return(mDone);
        }
            public bool MoveNext()
            {
                var currentScopeMoveNext = _currentScope.MoveNext();
                if (_inParentScope == false)
                    return currentScopeMoveNext;

                if (currentScopeMoveNext)
                    return true;

                _inParentScope = false;
                _currentScope = _localScope;
                return _currentScope.MoveNext();
            }
Exemple #20
0
        private void Next(int[] pCurrentConfiguration, Hashtable pLocations, ArrayList pAlreadyAdded, int pCurrentBlockIndex)
        {
            if (((Block)_blocks[pCurrentBlockIndex + 1]).LockedInPosition)
            {
                return;
            }

            ArrayList             mAttemptedLocations = new ArrayList();
            IDictionaryEnumerator mEnum = pLocations.GetEnumerator();

            while (mEnum.MoveNext())
            {
                int i = (int)mEnum.Key;
                if (mAttemptedLocations.Contains(mEnum.Value))
                {
                    continue;
                }

                if (!pAlreadyAdded.Contains(i))
                {
                    ArrayList mAlreadyAdded = new ArrayList(pAlreadyAdded);
                    mAlreadyAdded.Add(i);

                    int mNextBlockIndex = pCurrentBlockIndex + 1;

                    _solutionCount++;
                    if (mNextBlockIndex < _blocks.Count)
                    {
                        for (int j = mNextBlockIndex; j < _blocks.Count; j++)
                        {
                            pCurrentConfiguration[j] = -1;
                        }

                        mAttemptedLocations.Add(mEnum.Value);

                        if (Check(pCurrentConfiguration, pLocations, mNextBlockIndex, i))
                        {
                            pCurrentConfiguration[mNextBlockIndex] = i;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    if (mNextBlockIndex == _blocks.Count - 1)
                    {
                        long mHash = GetHashCode(pCurrentConfiguration);
                        if (!_solutionHash.Contains(mHash))
                        {
                            _solutionHash.Add(mHash);
                            _solutions.Add(pCurrentConfiguration.Clone());
                        }
                    }
                    else
                    {
                        Next(pCurrentConfiguration, pLocations, mAlreadyAdded, mNextBlockIndex);
                    }
                }
            }
        }
        public static unoidl.com.sun.star.uno.XComponentContext defaultBootstrap_InitialComponentContext(
            string iniFile,
            IDictionaryEnumerator bootstrapParameters)
        {
            if (bootstrapParameters != null)
            {
            bootstrapParameters.Reset();
            while (bootstrapParameters.MoveNext())
            {
                string key = (string)bootstrapParameters.Key;
                string value = (string)bootstrapParameters.Value;

                native_bootstrap_set(key, key.Length, value, value.Length);
            }
            }

            System.Console.WriteLine("Bootstrap with ini " + iniFile);
            // bootstrap native uno
            IntPtr context;
            if (iniFile == null)
            {
            context = native_defaultBootstrap_InitialComponentContext();
            }
            else
            {
            context = native_defaultBootstrap_InitialComponentContext(iniFile, iniFile.Length);
            }

            return (unoidl.com.sun.star.uno.XComponentContext)ExtractObject(context);
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            // add ids to controls
            _width.ID  = "width";
            _height.ID = "height";


            // initialize validators
            _widthValidator.ValidationExpression = "0*[1-9][0-9]*";
            _widthValidator.ErrorMessage         = "Width must be an integer";
            _widthValidator.Display               = ValidatorDisplay.Dynamic;
            _widthValidator.ControlToValidate     = _width.ID;
            _heightValidator.ValidationExpression = "0*[1-9][0-9]*";
            _heightValidator.ErrorMessage         = "Height must be an integer";
            _heightValidator.ControlToValidate    = _height.ID;
            _heightValidator.Display              = ValidatorDisplay.Dynamic;

            if (!Page.IsPostBack)
            {
                string[] config = Configuration.Split("|".ToCharArray());
                if (config.Length > 0)
                {
                    _selectedButtons = config[0];

                    if (config.Length > 1)
                    {
                        if (config[1] == "1")
                        {
                            _enableRightClick.Checked = true;
                        }
                    }

                    if (config.Length > 2)
                    {
                        _advancedUsers = config[2];
                    }

                    if (config.Length > 4 && config[4].Split(',').Length > 1)
                    {
//                        if (config[3] == "1")
//                            _fullWidth.Checked = true;
//                        else
//                        {
                        _width.Text  = config[4].Split(',')[0];
                        _height.Text = config[4].Split(',')[1];
//                        }
                    }

                    // if width and height are empty or lower than 0 then set default sizes:
                    int tempWidth, tempHeight;
                    int.TryParse(_width.Text, out tempWidth);
                    int.TryParse(_height.Text, out tempHeight);
                    if (_width.Text.Trim() == "" || tempWidth < 1)
                    {
                        _width.Text = "500";
                    }
                    if (_height.Text.Trim() == "" || tempHeight < 1)
                    {
                        _height.Text = "400";
                    }

                    if (config.Length > 4)
                    {
                        _stylesheets = config[5];
                    }
                }

                // add editor buttons
                IDictionaryEnumerator ide = tinyMCEConfiguration.SortedCommands.GetEnumerator();
                while (ide.MoveNext())
                {
                    tinyMCECommand cmd = (tinyMCECommand)ide.Value;
                    ListItem       li  = new ListItem(string.Format("<img src=\"{0}\" class=\"tinymceIcon\" alt=\"{1}\" />&nbsp;", cmd.Icon, cmd.Alias), cmd.Alias);
                    if (_selectedButtons.IndexOf(cmd.Alias) > -1)
                    {
                        li.Selected = true;
                    }

                    _editorButtons.Items.Add(li);
                }

                // add users
                foreach (BusinessLogic.UserType ut in BusinessLogic.UserType.getAll)
                {
                    ListItem li = new ListItem(ut.Name, ut.Id.ToString());
                    if (("," + _advancedUsers + ",").IndexOf("," + ut.Id.ToString() + ",") > -1)
                    {
                        li.Selected = true;
                    }

                    _advancedUsersList.Items.Add(li);
                }

                // add stylesheets
                foreach (Cms.BusinessLogic.web.StyleSheet st in Cms.BusinessLogic.web.StyleSheet.GetAll())
                {
                    ListItem li = new ListItem(st.Text, st.Id.ToString());
                    if (("," + _stylesheets + ",").IndexOf("," + st.Id.ToString() + ",") > -1)
                    {
                        li.Selected = true;
                    }

                    _stylesheetList.Items.Add(li);
                }


                // Mark the current db type
                _dropdownlist.SelectedValue = _datatype.DBType.ToString();
            }
        }
Exemple #23
0
        public static string SAPDualExecute(Hashtable[] arrht, Hashtable ImportStr, Hashtable ImportData, string Function_Name, string RfcStructure_Name, string RfcStructure_Name2, string SetTable_Name)
        {
            RfcConfigParameters configParam = GetConfigParam();
            RfcDestination      destination = RfcDestinationManager.GetDestination(configParam);
            IRfcFunction        function    = destination.Repository.CreateFunction(Function_Name);

            IRfcTable rfcTable = function.GetTable(SetTable_Name);

            RfcStructureMetadata strMeta2      = destination.Repository.GetStructureMetadata(RfcStructure_Name2);
            IRfcStructure        rfcStructure2 = strMeta2.CreateStructure();

            for (int i = 0; i < arrht.Length; i++)
            {
                RfcStructureMetadata strMeta      = destination.Repository.GetStructureMetadata(RfcStructure_Name);
                IRfcStructure        rfcStructure = strMeta.CreateStructure();

                IDictionaryEnumerator ie = arrht[i].GetEnumerator();

                while (ie.MoveNext())
                {
                    if (ie.Value.ToString().Length <= 4000)
                    {
                        rfcStructure.SetValue(ie.Key.ToString(), ie.Value);
                    }
                }

                rfcTable.Append(rfcStructure);
            }

            if (ImportStr.Count > 0)
            {
                IDictionaryEnumerator ie = ImportStr.GetEnumerator();

                while (ie.MoveNext())
                {
                    if (ie.Value.ToString().Length <= 4000)
                    {
                        rfcStructure2.SetValue(ie.Key.ToString(), ie.Value);
                    }
                }
            }

            if (ImportData.Count > 0)
            {
                IDictionaryEnumerator ie = ImportData.GetEnumerator();

                while (ie.MoveNext())
                {
                    if (ie.Value.ToString().Length <= 4000)
                    {
                        function.SetValue(ie.Key.ToString(), ie.Value);
                    }
                }
            }

            function.SetValue("IV_HEADER", rfcStructure2);
            function.Invoke(destination);

            string returnCode = function.GetString("EV_E_TYPE");

            return(returnCode);
        }
Exemple #24
0
        protected virtual void WriteDictionary(IEnumerable value)
        {
            IDictionaryEnumerator enumerator = value.GetEnumerator() as IDictionaryEnumerator;

            if (enumerator == null)
            {
                throw new JsonSerializationException(String.Format(JsonWriter.ErrorIDictionaryEnumerator, new System.Object[] { value.GetType() }));
            }

            bool appendDelim = false;

            if (settings.HandleCyclicReferences)
            {
                int prevIndex = 0;
                if (this.previouslySerializedObjects.TryGetValue(value, out prevIndex))
                {
                    this.Writer.Write(JsonReader.OperatorObjectStart);
                    this.WriteObjectProperty("@ref", prevIndex);
                    this.WriteLine();
                    this.Writer.Write(JsonReader.OperatorObjectEnd);
                    return;
                }
                else
                {
                    this.previouslySerializedObjects.Add(value, this.previouslySerializedObjects.Count);
                }
            }

            this.Writer.Write(JsonReader.OperatorObjectStart);

            this.depth++;
            if (this.depth > this.settings.MaxDepth)
            {
                throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, new System.Object[] { this.settings.MaxDepth }));
            }

            try
            {
                while (enumerator.MoveNext())
                {
                    if (appendDelim)
                    {
                        this.WriteObjectPropertyDelim();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    bool handledRef = referenceHandler != null && enumerator.Entry.Value != null && referenceHandler.IsHandled(enumerator.Entry.Value.GetType());

                    if (!handledRef)
                    {
                        // Reference is not tracked, serialize it normally
                        this.WriteObjectProperty(Convert.ToString(enumerator.Entry.Key), enumerator.Entry.Value);
                    }
                    else
                    {
                        // Reference is not owned by this field, write a reference to it
                        // Dictionaries cannot own references
                        this.WriteObjectProperty(Convert.ToString(enumerator.Entry.Key), "@" + referenceHandler.GetReferenceID(enumerator.Entry.Value), typeof(string));
                    }
                }
            }
            finally
            {
                this.depth--;
            }

            if (appendDelim)
            {
                this.WriteLine();
            }
            this.Writer.Write(JsonReader.OperatorObjectEnd);
        }
Exemple #25
0
		/// <summary>
		/// Write an dictionary to a <see cref="TextWriter"/>
		/// </summary>
		/// <param name="writer">the writer to write to</param>
		/// <param name="repository">a <see cref="ILoggerRepository"/> to use for object conversion</param>
		/// <param name="value">the value to write to the writer</param>
		/// <remarks>
		/// <para>
		/// Writes the <see cref="IDictionaryEnumerator"/> to a writer in the form:
		/// </para>
		/// <code>
		/// {key1=value1, key2=value2, key3=value3}
		/// </code>
		/// <para>
		/// If the <see cref="ILoggerRepository"/> specified
		/// is not null then it is used to render the key and value to text, otherwise
		/// the object's ToString method is called.
		/// </para>
		/// </remarks>
		protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionaryEnumerator value) {
			writer.Write("{");

			bool first = true;

			// Write out all the dictionary key value pairs
			while (value.MoveNext()) {
				if (first) {
					first = false;
				} else {
					writer.Write(", ");
				}
				WriteObject(writer, repository, value.Key);
				writer.Write("=");
				WriteObject(writer, repository, value.Value);
			}

			writer.Write("}");
		}
        [System.Security.SecurityCritical]  // auto-generated
        internal void PropagateIncomingHeadersToCallContext(IMessage msg)
        {
            BCLDebug.Assert(msg != null, "Why is the message null?");

            // If it's an internal message, we can quickly tell if there are any
            //   headers.
            IInternalMessage iim = msg as IInternalMessage;

            if (iim != null)
            {
                if (!iim.HasProperties())
                {
                    // If there are no properties just return immediately.
                    return;
                }
            }

            IDictionary properties = msg.Properties;

            BCLDebug.Assert(properties != null, "Why are the properties null?");

            IDictionaryEnumerator e = (IDictionaryEnumerator)properties.GetEnumerator();

            // cycle through the properties to get a count of the headers
            int count = 0;

            while (e.MoveNext())
            {
                String key = (String)e.Key;
                if (!key.StartsWith("__", StringComparison.Ordinal))
                {
                    // We don't want to have to check for special values, so we
                    //   blanketly state that header names can't start with
                    //   double underscore.
                    if (e.Value is Header)
                    {
                        count++;
                    }
                }
            }

            // If there are headers, create array and set it to the received header property
            Header[] headers = null;
            if (count > 0)
            {
                headers = new Header[count];

                count = 0;
                e.Reset();
                while (e.MoveNext())
                {
                    String key = (String)e.Key;
                    if (!key.StartsWith("__", StringComparison.Ordinal))
                    {
                        Header header = e.Value as Header;
                        if (header != null)
                        {
                            headers[count++] = header;
                        }
                    }
                }
            }

            _recvHeaders = headers;
            _sendHeaders = null;
        } // PropagateIncomingHeadersToCallContext
Exemple #27
0
 public bool MoveNext()
 {
     return(list.MoveNext());
 }
Exemple #28
0
 private object cc(object tipo)
 {
     if (tipo == null)
     {
         return(null);
     }
     if (esConocido(tipo))
     {
         return(tipo);
     }
     else if (tipo is System.Web.UI.Triplet)
     {
         System.Web.UI.Triplet triple = (System.Web.UI.Triplet)tipo;
         return(new seriable3(cc(triple.First), cc(triple.Second), cc(triple.Third)));
     }
     else if (tipo is System.Web.UI.Pair)
     {
         System.Web.UI.Pair par = (System.Web.UI.Pair)tipo;
         return(new seriable2(cc(par.First), cc(par.Second)));
     }
     else if (tipo is ArrayList)
     {
         ArrayList trans  = (ArrayList)tipo;
         ArrayList salida = new ArrayList(trans.Count);
         foreach (object x in trans)
         {
             salida.Add(cc(x));
         }
         return(salida);
     }
     else if (tipo is Array)
     {
         Array trans  = (Array)tipo;
         Array salida = Array.CreateInstance(tipo.GetType().GetElementType(), trans.Length);
         for (int x = 0; x < trans.Length; x++)
         {
             salida.SetValue(cc(trans.GetValue(x)), x);
         }
         return(salida);
     }
     else if (tipo is Hashtable)
     {
         IDictionaryEnumerator enumerator = ((Hashtable)tipo).GetEnumerator();
         Hashtable             salida     = new Hashtable();
         while (enumerator.MoveNext())
         {
             salida.Add(cc(enumerator.Key), cc(enumerator.Value));
         }
         return(salida);
     }
     else
     {
         Type valueType       = tipo.GetType();
         Type destinationType = typeof(string);
         bool flag;
         bool flag2;
         System.ComponentModel.TypeConverter converter = System.ComponentModel.TypeDescriptor.GetConverter(valueType);
         if (((converter == null) || converter is System.ComponentModel.ReferenceConverter))
         {
             flag  = false;
             flag2 = false;
         }
         else
         {
             flag  = converter.CanConvertTo(destinationType);
             flag2 = converter.CanConvertFrom(destinationType);
         }
         if ((flag && flag2))
         {
             return(new generalCnv(valueType, converter.ConvertToInvariantString(tipo)));
         }
         else
         {
             return(tipo);
             //Salida General
         }
     }
 }
Exemple #29
0
        // The main method that causes the page to be created.
        public bool Create(Stats stats)
        {
            // Sanity check
            if (fSourceRecord == null)
            {
                return(false);
            }

            // Create the strings to use for the HTML file.
            string pageDescription = "GEDmill GEDCOM to HTML page for " + fSourceRecord.ShortTitle;
            string keywords        = "family tree history " + fSourceRecord.ShortTitle;
            string filename        = string.Concat(CConfig.Instance.OutputFolder, "\\sour", fSourceRecord.XRef);
            string fullFilename    = string.Concat(filename, ".", CConfig.Instance.HtmlExtension);

            HTMLFile f = null;

            try {
                // Create a new file with an HTML header.
                f = new HTMLFile(fullFilename, fSourceRecord.ShortTitle, pageDescription, keywords);

                // Create a navbar to main site, front page etc.
                OutputPageHeader(f, "", "", true, true);

                f.WriteLine("    <div class=\"hr\" />");
                f.WriteLine("");
                f.WriteLine("    <div id=\"page\"> <!-- page -->");

                // Write the page's title text.
                f.WriteLine("      <div id=\"main\">");
                f.WriteLine("        <div id=\"summary\">");
                f.WriteLine("          <div id=\"names\">");
                string sourName = fSourceRecord.ShortTitle;
                if (sourName == "")
                {
                    sourName = "Source ";
                    bool gotSourceName = false;
                    // Try user reference number
                    foreach (GDMUserReference urn in fSourceRecord.UserReferences)
                    {
                        if (urn.StringValue != "")
                        {
                            sourName     += urn.StringValue;
                            gotSourceName = true;
                            break;
                        }
                    }
                    if (!gotSourceName && fSourceRecord.AutomatedRecordID != null && fSourceRecord.AutomatedRecordID != "")
                    {
                        sourName += fSourceRecord.AutomatedRecordID;
                    }
                    else if (!gotSourceName)
                    {
                        sourName += fSourceRecord.XRef;
                    }
                }
                f.WriteLine("<h1>{0}</h1>", EscapeHTML(sourName, false));

                // Add repository information
                foreach (GDMRepositoryCitation src in fSourceRecord.RepositoryCitations)
                {
                    GDMRepositoryRecord rr = src.Value as GDMRepositoryRecord;
                    if (rr != null)
                    {
                        if (!string.IsNullOrEmpty(rr.RepositoryName))
                        {
                            f.WriteLine("<h2>{0}</h2>", EscapeHTML(rr.RepositoryName, false));
                        }

                        foreach (GDMNotes ns in rr.Notes)
                        {
                            string noteText;
                            if (CConfig.Instance.ObfuscateEmails)
                            {
                                noteText = ObfuscateEmail(ns.Lines.Text);
                            }
                            else
                            {
                                noteText = ns.Lines.Text;
                            }
                            f.WriteLine("<p>{0}</p>", EscapeHTML(noteText, false));
                        }
                    }

                    if (src.Notes != null && src.Notes.Count > 0)
                    {
                        foreach (GDMNotes ns in src.Notes)
                        {
                            string noteText;
                            if (CConfig.Instance.ObfuscateEmails)
                            {
                                noteText = ObfuscateEmail(ns.Lines.Text);
                            }
                            else
                            {
                                noteText = ns.Lines.Text;
                            }
                            f.WriteLine("<p>{0}</p>", EscapeHTML(noteText, false));
                        }
                    }
                }

                // Add Publication Information
                string pubFacts;
                if (CConfig.Instance.ObfuscateEmails)
                {
                    pubFacts = ObfuscateEmail(fSourceRecord.Publication.Lines.Text);
                }
                else
                {
                    pubFacts = fSourceRecord.Publication.Lines.Text;
                }
                if (!string.IsNullOrEmpty(pubFacts))
                {
                    if (pubFacts.Length > 7 && pubFacts.ToUpper().Substring(0, 7) == "HTTP://")
                    {
                        f.WriteLine("<h2><a href=\"{0}\">{1}</a></h2>", pubFacts, EscapeHTML(pubFacts, false));
                    }
                    else
                    {
                        f.WriteLine("<h2>{0}</h2>", EscapeHTML(pubFacts, false));
                    }
                }

                f.WriteLine("          </div> <!-- names -->");
                f.WriteLine("        </div> <!-- summary -->");

                // Collect together multimedia links.
                if (CConfig.Instance.AllowMultimedia)
                {
                    // Fill m_alMultimediaList:
                    AddMultimedia(fSourceRecord.MultimediaLinks, string.Concat(fSourceRecord.XRef, "mms"), string.Concat(fSourceRecord.XRef, "mos"), CConfig.Instance.MaxSourceImageWidth, CConfig.Instance.MaxSourceImageHeight, stats);
                }

                // Add pics
                OutputMultimedia(f);

                // Add textFromSource
                string cleanText = fSourceRecord.Text.Lines.Text;
                if (CConfig.Instance.ObfuscateEmails)
                {
                    cleanText = ObfuscateEmail(cleanText);
                }
                if (!string.IsNullOrEmpty(cleanText))
                {
                    f.WriteLine("        <div id=\"text\">");
                    f.WriteLine("          <h1>Text</h1>");
                    f.WriteLine("          <p class=\"pretext\">");
                    f.WriteLine(EscapeHTML(cleanText, false));
                    f.WriteLine("            </p>");
                    f.WriteLine("        </div> <!-- text -->");
                }

                // Add notes
                OutputNotes(f, fSourceRecord.Notes);

                if (CConfig.Instance.SupressBackreferences == false)
                {
                    f.WriteLine("        <div id=\"citations\">");
                    f.WriteLine("          <h1>Citations</h1>");
                    f.WriteLine("          <ul>");

                    var htBackrefs = fSourceRecord.MakeBackReferences();
                    IDictionaryEnumerator enumerator = htBackrefs.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        GDMIndividualRecord ir = (GDMIndividualRecord)(enumerator.Value);
                        if (ir != null && ir.GetVisibility())
                        {
                            string link = MakeLink(ir);
                            if (link != "")
                            {
                                f.WriteLine("<li>{0}</li>", link);
                            }
                        }
                    }

                    f.WriteLine("          </ul>");
                    f.WriteLine("        </div> <!-- citations -->");
                }

                f.WriteLine("      </div> <!-- main -->");

                // Add footer (Record date, W3C sticker, GEDmill credit etc.)
                OutputFooter(f, fSourceRecord);

                f.WriteLine("    </div> <!-- page -->");
            } catch (IOException e) {
                fLogger.WriteError("Caught IO Exception(6) : ", e);
            } catch (ArgumentException e) {
                fLogger.WriteError("Caught Argument Exception(6) : ", e);
            } finally {
                if (f != null)
                {
                    f.Close(); // Adds standard footer to the file
                }
            }
            return(true);
        }
Exemple #30
0
        private object?GetObject(string key, bool ignoreCase, bool isString)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (Reader == null || _resCache == null)
            {
                throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
            }

            object?         value = null;
            ResourceLocator resLocation;

            lock (Reader)
            {
                if (Reader == null)
                {
                    throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
                }

                if (_defaultReader != null)
                {
                    // Find the offset within the data section
                    int dataPos = -1;
                    if (_resCache.TryGetValue(key, out resLocation))
                    {
                        value   = resLocation.Value;
                        dataPos = resLocation.DataPosition;
                    }

                    if (dataPos == -1 && value == null)
                    {
                        dataPos = _defaultReader.FindPosForResource(key);
                    }

                    if (dataPos != -1 && value == null)
                    {
                        Debug.Assert(dataPos >= 0, "data section offset cannot be negative!");
                        // Normally calling LoadString or LoadObject requires
                        // taking a lock.  Note that in this case, we took a
                        // lock on the entire RuntimeResourceSet, which is
                        // sufficient since we never pass this ResourceReader
                        // to anyone else.
                        ResourceTypeCode typeCode;
                        if (isString)
                        {
                            value    = _defaultReader.LoadString(dataPos);
                            typeCode = ResourceTypeCode.String;
                        }
                        else
                        {
                            value = _defaultReader.LoadObject(dataPos, out typeCode);
                        }

                        resLocation = new ResourceLocator(dataPos, (ResourceLocator.CanCache(typeCode)) ? value : null);
                        lock (_resCache)
                        {
                            _resCache[key] = resLocation;
                        }
                    }

                    if (value != null || !ignoreCase)
                    {
                        return(value);  // may be null
                    }
                }  // if (_defaultReader != null)

                // At this point, we either don't have our default resource reader
                // or we haven't found the particular resource we're looking for
                // and may have to search for it in a case-insensitive way.
                if (!_haveReadFromReader)
                {
                    // If necessary, init our case insensitive hash table.
                    if (ignoreCase)
                    {
                        _caseInsensitiveTable ??= new Dictionary <string, ResourceLocator>(StringComparer.OrdinalIgnoreCase);
                    }

                    if (_defaultReader == null)
                    {
                        IDictionaryEnumerator en = Reader.GetEnumerator();
                        while (en.MoveNext())
                        {
                            DictionaryEntry entry   = en.Entry;
                            string          readKey = (string)entry.Key;
                            ResourceLocator resLoc  = new ResourceLocator(-1, entry.Value);
                            _resCache.Add(readKey, resLoc);
                            if (ignoreCase)
                            {
                                Debug.Assert(_caseInsensitiveTable != null);
                                _caseInsensitiveTable.Add(readKey, resLoc);
                            }
                        }
                        // Only close the reader if it is NOT our default one,
                        // since we need it around to resolve ResourceLocators.
                        if (!ignoreCase)
                        {
                            Reader.Close();
                        }
                    }
                    else
                    {
                        Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
                        Debug.Assert(_caseInsensitiveTable != null);
                        ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal();
                        while (en.MoveNext())
                        {
                            // Note: Always ask for the resource key before the data position.
                            string          currentKey = (string)en.Key;
                            int             dataPos    = en.DataPosition;
                            ResourceLocator resLoc     = new ResourceLocator(dataPos, null);
                            _caseInsensitiveTable.Add(currentKey, resLoc);
                        }
                    }
                    _haveReadFromReader = true;
                }
                object?obj            = null;
                bool   found          = false;
                bool   keyInWrongCase = false;
                if (_defaultReader != null)
                {
                    if (_resCache.TryGetValue(key, out resLocation))
                    {
                        found = true;
                        obj   = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
                    }
                }
                if (!found && ignoreCase)
                {
                    Debug.Assert(_caseInsensitiveTable != null);
                    if (_caseInsensitiveTable.TryGetValue(key, out resLocation))
                    {
                        found          = true;
                        keyInWrongCase = true;
                        obj            = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
                    }
                }
                return(obj);
            } // lock(Reader)
        }
Exemple #31
0
 private static float ReadFloat(IDictionaryEnumerator enumerator)
 {
     var value = float.Parse((string)enumerator.Current);
     enumerator.MoveNext();
     return value;
 }
        /*使用示例:
         * DataSet ds=(DataSet)Session["AdBrowseHitDayList"];
         *              string ExcelFolder=Assistant.GetConfigString("ExcelFolder");
         *              string FilePath=Server.MapPath(".")+"\\"+ExcelFolder+"\\";
         *
         *              //生成列的中文对应表
         *              Hashtable nameList = new Hashtable();
         *              nameList.Add("ADID", "广告编码");
         *              nameList.Add("ADName", "广告名称");
         *              nameList.Add("year", "年");
         *              nameList.Add("month", "月");
         *              nameList.Add("browsum", "显示数");
         *              nameList.Add("hitsum", "点击数");
         *              nameList.Add("BrowsinglIP", "独立IP显示");
         *              nameList.Add("HitsinglIP", "独立IP点击");
         *              //利用excel对象
         *              DataToExcel dte=new DataToExcel();
         *              string filename="";
         *              try
         *              {
         *                      if(ds.Tables[0].Rows.Count>0)
         *                      {
         *                              filename=dte.DataExcel(ds.Tables[0],"标题",FilePath,nameList);
         *                      }
         *              }
         *              catch
         *              {
         *                      //dte.KillExcelProcess();
         *              }
         *
         *              if(filename!="")
         *              {
         *                      Response.Redirect(ExcelFolder+"\\"+filename,true);
         *              }
         *
         * */

        #endregion

        /// <summary>
        /// 将DataTable的数据导出显示为报表(不使用Excel对象)
        /// </summary>
        /// <param name="dt">数据DataTable</param>
        /// <param name="strTitle">标题</param>
        /// <param name="FilePath">生成文件的路径</param>
        /// <param name="nameList"></param>
        /// <returns></returns>
        public string DataExcel(System.Data.DataTable dt, string strTitle, string FilePath, Hashtable nameList)
        {
            COM.Excel.cExcelFile excel = new COM.Excel.cExcelFile();
            ClearFile(FilePath);
            string filename = DateTime.Now.ToString("yyyyMMddHHmmssff") + ".xls";

            excel.CreateFile(FilePath + filename);
            excel.PrintGridLines = false;

            COM.Excel.cExcelFile.MarginTypes mt1 = COM.Excel.cExcelFile.MarginTypes.xlsTopMargin;
            COM.Excel.cExcelFile.MarginTypes mt2 = COM.Excel.cExcelFile.MarginTypes.xlsLeftMargin;
            COM.Excel.cExcelFile.MarginTypes mt3 = COM.Excel.cExcelFile.MarginTypes.xlsRightMargin;
            COM.Excel.cExcelFile.MarginTypes mt4 = COM.Excel.cExcelFile.MarginTypes.xlsBottomMargin;

            double height = 1.5;

            excel.SetMargin(ref mt1, ref height);
            excel.SetMargin(ref mt2, ref height);
            excel.SetMargin(ref mt3, ref height);
            excel.SetMargin(ref mt4, ref height);

            COM.Excel.cExcelFile.FontFormatting ff = COM.Excel.cExcelFile.FontFormatting.xlsNoFormat;
            string font     = "宋体";
            short  fontsize = 9;

            excel.SetFont(ref font, ref fontsize, ref ff);

            byte b1  = 1,
                 b2  = 12;
            short s3 = 12;

            excel.SetColumnWidth(ref b1, ref b2, ref s3);

            string header = "页眉";
            string footer = "页脚";

            excel.SetHeader(ref header);
            excel.SetFooter(ref footer);


            COM.Excel.cExcelFile.ValueTypes       vt  = COM.Excel.cExcelFile.ValueTypes.xlsText;
            COM.Excel.cExcelFile.CellFont         cf  = COM.Excel.cExcelFile.CellFont.xlsFont0;
            COM.Excel.cExcelFile.CellAlignment    ca  = COM.Excel.cExcelFile.CellAlignment.xlsCentreAlign;
            COM.Excel.cExcelFile.CellHiddenLocked chl = COM.Excel.cExcelFile.CellHiddenLocked.xlsNormal;

            // 报表标题
            int cellformat = 1;
            //			int rowindex = 1,colindex = 3;
            //			object title = (object)strTitle;
            //			excel.WriteValue(ref vt, ref cf, ref ca, ref chl,ref rowindex,ref colindex,ref title,ref cellformat);

            int rowIndex = 1;//起始行
            int colIndex = 0;



            //取得列标题
            foreach (DataColumn colhead in dt.Columns)
            {
                colIndex++;
                string name                = colhead.ColumnName.Trim();
                object namestr             = (object)name;
                IDictionaryEnumerator Enum = nameList.GetEnumerator();
                while (Enum.MoveNext())
                {
                    if (Enum.Key.ToString().Trim() == name)
                    {
                        namestr = Enum.Value;
                    }
                }
                excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref namestr, ref cellformat);
            }

            //取得表格中的数据
            foreach (DataRow row in dt.Rows)
            {
                rowIndex++;
                colIndex = 0;
                foreach (DataColumn col in dt.Columns)
                {
                    colIndex++;
                    if (col.DataType == System.Type.GetType("System.DateTime"))
                    {
                        object str = (object)(Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");;
                        excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref str, ref cellformat);
                    }
                    else
                    {
                        object str = (object)row[col.ColumnName].ToString();
                        excel.WriteValue(ref vt, ref cf, ref ca, ref chl, ref rowIndex, ref colIndex, ref str, ref cellformat);
                    }
                }
            }
            int ret = excel.CloseFile();

            //			if(ret!=0)
            //			{
            //				//MessageBox.Show(this,"Error!");
            //			}
            //			else
            //			{
            //				//MessageBox.Show(this,"请打开文件c:\\test.xls!");
            //			}
            return(filename);
        }
Exemple #33
0
 static int VerifyDictionaryEnumerator(IDictionaryEnumerator de, IterationOrder order)
 {
     long prev = long.MinValue;
     if (order == IterationOrder.DescentOrder)
         prev = long.MaxValue;
     int i = 0;
     while (de.MoveNext())
     {
         DictionaryEntry e1 = (DictionaryEntry)de.Current;
         DictionaryEntry e2 = de.Entry;
         Tests.Assert(e1.Equals(e2));
         long k = (long)e1.Key;
         long k2 = (long)de.Key;
         Tests.Assert(k == k2);
         RecordFull v1 = (RecordFull)e1.Value;
         RecordFull v2 = (RecordFull)de.Value;
         Tests.Assert(v1.Equals(v2));
         Tests.Assert(v1.Int32Val == k);
         if (order == IterationOrder.AscentOrder)
             Tests.Assert(k >= prev);
         else
             Tests.Assert(k <= prev);
         prev = k;
         i++;
     }
     Tests.VerifyDictionaryEnumeratorDone(de);
     return i;
 }
        private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
        {
            object underlyingDictionary = values is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : values;

            OnSerializing(writer, contract, underlyingDictionary);
            _serializeStack.Add(underlyingDictionary);

            WriteObjectStart(writer, underlyingDictionary, contract, member, collectionContract, containerProperty);

            if (contract.ItemContract == null)
            {
                contract.ItemContract = Serializer._contractResolver.ResolveContract(contract.DictionaryValueType ?? typeof(object));
            }

            if (contract.KeyContract == null)
            {
                contract.KeyContract = Serializer._contractResolver.ResolveContract(contract.DictionaryKeyType ?? typeof(object));
            }

            int initialDepth = writer.Top;

            // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
            IDictionaryEnumerator e = values.GetEnumerator();

            try
            {
                while (e.MoveNext())
                {
                    DictionaryEntry entry = e.Entry;

                    string propertyName = GetPropertyName(writer, entry.Key, contract.KeyContract, out bool escape);

                    propertyName = (contract.DictionaryKeyResolver != null)
                        ? contract.DictionaryKeyResolver(propertyName)
                        : propertyName;

                    try
                    {
                        object       value         = entry.Value;
                        JsonContract valueContract = contract.FinalItemContract ?? GetContractSafe(value);

                        if (ShouldWriteReference(value, null, valueContract, contract, member))
                        {
                            writer.WritePropertyName(propertyName, escape);
                            WriteReference(writer, value);
                        }
                        else
                        {
                            if (!CheckForCircularReference(writer, value, null, valueContract, contract, member))
                            {
                                continue;
                            }

                            writer.WritePropertyName(propertyName, escape);

                            SerializeValue(writer, value, valueContract, null, contract, member);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (IsErrorHandled(underlyingDictionary, contract, propertyName, null, writer.ContainerPath, ex))
                        {
                            HandleError(writer, initialDepth);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
            finally
            {
                (e as IDisposable)?.Dispose();
            }

            writer.WriteEndObject();

            _serializeStack.RemoveAt(_serializeStack.Count - 1);

            OnSerialized(writer, contract, underlyingDictionary);
        }
        protected MediaResource[] BuildResources(string Interface, IDictionaryEnumerator en)
        {
            ArrayList a = new ArrayList();
            while(en.MoveNext())
            {
                FileInfo f = (FileInfo)en.Value;
                MediaResource mr;

                ResourceBuilder.ResourceAttributes resInfo = new ResourceBuilder.ResourceAttributes();
                resInfo.contentUri = "file://" + f.FullName;
                resInfo.protocolInfo = ProtocolInfoString.CreateHttpGetProtocolInfoString(f);

                mr = ResourceBuilder.CreateResource(resInfo);
                OpenSource.UPnP.AV.Extensions.MetaData.Finder.PopulateMetaData(mr,f);

                a.Add(mr);
            }
            return((MediaResource[])a.ToArray(typeof(MediaResource)));
        }
Exemple #36
0
 bool IEnumerator.MoveNext()
 {
     return(_enumerator.MoveNext());
 }
    private static String DictEnumKeysToString(IDictionaryEnumerator e) {
        StringBuilder sb = new StringBuilder(256);

        if (e.MoveNext()) {
            sb.Append(EncodeTab(e.Key));
            while (e.MoveNext()) {
                sb.Append("\t");
                sb.Append(EncodeTab(e.Key));
            }
        }

        return sb.ToString();
    }
Exemple #38
0
 private void FillFidMapping(GetSyncStateResult results, MailboxSession session)
 {
     foreach (DeviceData deviceData in results.Devices)
     {
         foreach (SyncStateFolderData syncStateFolderData in deviceData.SyncFolders)
         {
             if (syncStateFolderData != null && !string.IsNullOrEmpty(syncStateFolderData.SyncStateBlob))
             {
                 syncStateFolderData.FolderMapping = new List <FolderMappingData>();
                 using (PooledMemoryStream pooledMemoryStream = new PooledMemoryStream(102400))
                 {
                     byte[] array = Convert.FromBase64String(syncStateFolderData.SyncStateBlob);
                     pooledMemoryStream.Write(array, 0, array.Length);
                     pooledMemoryStream.Flush();
                     pooledMemoryStream.Position = 0L;
                     int  num;
                     int  num2;
                     long num3;
                     long num4;
                     Dictionary <string, bool> dictionary;
                     GenericDictionaryData <ConstStringData, string, DerivedData <ICustomSerializableBuilder> > genericDictionaryData = SyncState.InternalDeserializeData(pooledMemoryStream, out num, out num2, out num3, out num4, out dictionary);
                     FolderIdMapping       folderIdMapping    = genericDictionaryData.Data["IdMapping"].Data as FolderIdMapping;
                     IDictionaryEnumerator syncIdIdEnumerator = folderIdMapping.SyncIdIdEnumerator;
                     while (syncIdIdEnumerator.MoveNext())
                     {
                         string        shortId       = syncIdIdEnumerator.Key as string;
                         ISyncItemId   syncItemId    = syncIdIdEnumerator.Value as ISyncItemId;
                         StoreObjectId storeObjectId = syncItemId.NativeId as StoreObjectId;
                         try
                         {
                             using (Folder folder = Folder.Bind(session, storeObjectId, new PropertyDefinition[]
                             {
                                 FolderSchema.DisplayName
                             }))
                             {
                                 DefaultFolderType defaultFolderType = session.IsDefaultFolderType(folder.Id);
                                 syncStateFolderData.FolderMapping.Add(new FolderMappingData
                                 {
                                     ShortId           = shortId,
                                     LongId            = storeObjectId.ToString(),
                                     Name              = folder.DisplayName,
                                     DefaultFolderType = defaultFolderType.ToString(),
                                     Exception         = null
                                 });
                             }
                         }
                         catch (Exception ex)
                         {
                             syncStateFolderData.FolderMapping.Add(new FolderMappingData
                             {
                                 ShortId           = shortId,
                                 LongId            = "[Error]",
                                 Name              = "[Error]",
                                 DefaultFolderType = "[Error]",
                                 Exception         = ex.ToString()
                             });
                         }
                     }
                 }
             }
         }
     }
 }
Exemple #39
0
 /// <summary>
 /// Determines whether two IDictionaryEnumerator instances are equals.
 /// </summary>
 /// <param name="source">The first IDictionaryEnumerator to compare.</param>
 /// <param name="target">The second IDictionaryEnumerator to compare.</param>
 /// <returns>Return true if the first IDictionaryEnumerator contains the same values as the second IDictionaryEnumerator, otherwise return false.</returns>
 public static bool Equals(IDictionaryEnumerator source, IDictionaryEnumerator target)
 {
     while (source.MoveNext() && target.MoveNext())
         if (source.Key.Equals(target.Key))
             if (source.Value.Equals(target.Value))
                 return true;
     return false;
 }
 public bool MoveNext()
 {
     return(_entryEnumerator?.MoveNext() ?? false);
 }
Exemple #41
0
        public static Hashtable SAPExecuteTableData_Common(Hashtable[] arrht, Hashtable ImportData, string Function_Name, string RfcStructure_Name, string Table_Name, string GetTable_Name, string GetTable_Name2)
        {
            RfcConfigParameters configParam = GetConfigParam();
            RfcDestination      destination = RfcDestinationManager.GetDestination(configParam);
            IRfcFunction        function    = destination.Repository.CreateFunction(Function_Name);

            IRfcTable rfcTable = function.GetTable(Table_Name);

            for (int i = 0; i < arrht.Length; i++)
            {
                RfcStructureMetadata strMeta      = destination.Repository.GetStructureMetadata(RfcStructure_Name);
                IRfcStructure        rfcStructure = strMeta.CreateStructure();

                //if (arrht[i] == null)
                //    continue;

                IDictionaryEnumerator ie = arrht[i].GetEnumerator();

                while (ie.MoveNext())
                {
                    if (ie.Value.ToString().Length <= 4000)
                    {
                        rfcStructure.SetValue(ie.Key.ToString(), ie.Value);
                    }
                }

                rfcTable.Append(rfcStructure);
            }

            if (ImportData.Count > 0)
            {
                IDictionaryEnumerator ie = ImportData.GetEnumerator();

                while (ie.MoveNext())
                {
                    if (ie.Value.ToString().Length <= 4000)
                    {
                        function.SetValue(ie.Key.ToString(), ie.Value);
                    }
                }
            }

            function.Invoke(destination);
            IRfcTable rfcTable2 = function.GetTable(GetTable_Name);
            IRfcTable rfcTable3 = null;

            if (GetTable_Name2 != null)
            {
                rfcTable3 = function.GetTable(GetTable_Name2);
            }

            Hashtable ht = new Hashtable();

            switch (Function_Name)
            {
            case "ZMM_SKD_PO_AND_GR":
                ht.Add("I_EBELN", function.GetString("I_EBELN"));
                ht.Add("I_MBLNR", function.GetString("I_MBLNR"));
                ht.Add("FT_RETURN_PO", rfcTable2);
                ht.Add("FT_RETURN_GR", rfcTable3);
                break;

            case "ZMM_SKD_PO":
                ht.Add("I_EBELN", function.GetString("I_EBELN"));
                ht.Add("FT_RETURN_PO", rfcTable2);
                break;

            case "ZMM_SKD_BAPI_GOODSMVT_CREATE":
                ht.Add("I_MBLNR", function.GetString("I_MBLNR"));
                ht.Add("FT_RETURN_GR", rfcTable2);
                break;
            }

            return(ht);
        }
Exemple #42
0
  public FieldsEnumerator(IDictionaryEnumerator it) 
  {
      this.it = it;
      
      bool fieldMoved = it.MoveNext();
 
      //If no elements at first level , return false
      if(!fieldMoved) {
          this.field = null;
      } else {
          //We set field to the first list iterator
          field = (((DictionaryEntry)it.Current).Value as IList).GetEnumerator();
      }
  }
Exemple #43
0
        protected virtual void WriteDictionary(IEnumerable value)
        {
            IDictionaryEnumerator enumerator = value.GetEnumerator() as IDictionaryEnumerator;

            if (enumerator == null)
            {
                throw new JsonSerializationException(String.Format(JsonWriter.ErrorIDictionaryEnumerator, value.GetType()));
            }

            bool appendDelim = false;

            if (settings.HandleCyclicReferences)
            {
                int prevIndex = 0;
                if (this.previouslySerializedObjects.TryGetValue(value, out prevIndex))
                {
                    this.Writer.Write(JsonReader.OperatorObjectStart);
                    this.WriteObjectProperty("@ref", prevIndex);
                    this.WriteLine();
                    this.Writer.Write(JsonReader.OperatorObjectEnd);
                    return;
                }
                else
                {
                    this.previouslySerializedObjects.Add(value, this.previouslySerializedObjects.Count);
                }
            }

            this.Writer.Write(JsonReader.OperatorObjectStart);

            this.depth++;
            if (this.depth > this.settings.MaxDepth)
            {
                throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.settings.MaxDepth));
            }

            try
            {
                while (enumerator.MoveNext())
                {
                    if (appendDelim)
                    {
                        this.WriteObjectPropertyDelim();
                    }
                    else
                    {
                        appendDelim = true;
                    }

                    this.WriteObjectProperty(Convert.ToString(enumerator.Entry.Key), enumerator.Entry.Value);
                }
            }
            finally
            {
                this.depth--;
            }

            if (appendDelim)
            {
                this.WriteLine();
            }
            this.Writer.Write(JsonReader.OperatorObjectEnd);
        }
Exemple #44
0
        public static IRfcTable SAPExecuteTableData2(Hashtable[] arrht, Hashtable[] arrht2, Hashtable ImportData, string Function_Name, string RfcStructure_Name, string RfcStructure_Name2, string GetTable_Name, string SetTable_Name, string SetTable_Name2)
        {
            RfcConfigParameters configParam = GetConfigParam();
            RfcDestination      destination = RfcDestinationManager.GetDestination(configParam);
            IRfcFunction        function    = destination.Repository.CreateFunction(Function_Name);

            IRfcTable rfcTable  = function.GetTable(SetTable_Name);
            IRfcTable rfcTable2 = function.GetTable(SetTable_Name2);

            for (int i = 0; i < arrht.Length; i++)
            {
                RfcStructureMetadata strMeta      = destination.Repository.GetStructureMetadata(RfcStructure_Name);
                IRfcStructure        rfcStructure = strMeta.CreateStructure();

                if (arrht[i] == null)
                {
                    continue;
                }

                IDictionaryEnumerator ie = arrht[i].GetEnumerator();

                while (ie.MoveNext())
                {
                    if (ie.Value.ToString().Length <= 4000)
                    {
                        rfcStructure.SetValue(ie.Key.ToString(), ie.Value);
                    }
                }

                rfcTable.Append(rfcStructure);
            }

            for (int i = 0; i < arrht2.Length; i++)
            {
                RfcStructureMetadata strMeta      = destination.Repository.GetStructureMetadata(RfcStructure_Name2);
                IRfcStructure        rfcStructure = strMeta.CreateStructure();

                if (arrht2[i] == null)
                {
                    continue;
                }

                IDictionaryEnumerator ie = arrht2[i].GetEnumerator();

                while (ie.MoveNext())
                {
                    if (ie.Value.ToString().Length <= 4000)
                    {
                        rfcStructure.SetValue(ie.Key.ToString(), ie.Value);
                    }
                }

                rfcTable2.Append(rfcStructure);
            }

            if (ImportData.Count > 0)
            {
                IDictionaryEnumerator ie = ImportData.GetEnumerator();

                while (ie.MoveNext())
                {
                    if (ie.Value.ToString().Length <= 4000)
                    {
                        function.SetValue(ie.Key.ToString(), ie.Value);
                    }
                }
            }

            function.Invoke(destination);

            IRfcTable rfcTable3 = function.GetTable(GetTable_Name);

            return(rfcTable3);
        }
Exemple #45
0
		/// <summary> A SearchId is only created from an ArrayVar object.  The ArrayVar 
		/// constructs a new SearchId object by passing it's current keys 
		/// stored as an enumeration, a unique string that ArrayVar creates, 
		/// and an index value used for future SearchId objects.
		/// 
		/// </summary>
		/// <param name="e">initial Enumeration
		/// </param>
		/// <param name="s">String as the unique identifier for the searchId
		/// </param>
		/// <param name="e">index value for this object
		/// </param>
		internal SearchId(IDictionaryEnumerator e, string s, int i)
		{
			enum_Renamed = e;
			str = s;
			index = i;
			hasMore = enum_Renamed.MoveNext();
			if (hasMore)
				entry = enum_Renamed.Entry;
		}
Exemple #46
0
        static string NonTerminals;                  //  список нетерминалов


        static void Execute()
        {
            Console.WriteLine("\nИсходная ");
            Info();
            RemoveEpsilonRules();
            Console.WriteLine("\nПосле удаления е-продукций");

            Grammar.Add("П S");     //дополнить грамматику правилом П -> S
            NonTerminals += "П";
            Terminals    += "$";

            Console.WriteLine("\nПравила: \n ");
            for (IEnumerator rule = Grammar.GetEnumerator(); rule.MoveNext();)
            {
                Console.WriteLine(rule.Current);
            }

            Console.WriteLine("Терминалы : " + Terminals);
            Console.WriteLine("Нетерминалы: " + NonTerminals);
            Console.WriteLine("-----");
            Console.ReadLine();

            // генерация LR(1) таблицы
            //

            ComputeFirstSets();                       // вычислить множества FIRST

            Console.WriteLine("Вычислены множества FIRST для символов грамматики и строк \n ");

            string Symbols = NonTerminals;

            for (int i = 0; i < Symbols.Length; i++)
            {  //для каждого символа грамматики X
                char X = Symbols[i];
                Console.WriteLine("First( " + X + " ): " + First(X));
            }
            Console.WriteLine();
            for (IEnumerator rule = Grammar.GetEnumerator(); rule.MoveNext();)
            {
                string str = ((string)rule.Current).Substring(2);
                Console.WriteLine("First( " + str + " ): " + First(str));
            }

            Console.ReadLine();
            ArrayList[] CArray = CreateCArray();            // создать последовательность С
            Console.WriteLine("Cоздана последовательность С: \n ");
            for (int i = 0; i < CArray.Length; i++)
            {
                Console.WriteLine("I" + i + DebugArrayList(CArray[i]));
            }

            Hashtable ACTION = CreateActionTable(CArray);   // создать ACTION таблицу

            if (ACTION == null)
            {
                Console.WriteLine("Грамматика не является LR(1)"); Console.ReadLine(); return;
            }
            Hashtable GOTO = CreateGotoTable(CArray);       // создать GOTO таблицу

            // распечатать содержимое ACTION и GOTO таблиц:
            Console.WriteLine("\nСоздана ACTION таблица \n ");

            for (IDictionaryEnumerator c = ACTION.GetEnumerator(); c.MoveNext();)
            {
                Console.WriteLine("ACTION[" + ((Tablekey)c.Key).I + ", " + ((Tablekey)c.Key).J + "] = " + c.Value);
            }
            Console.WriteLine("\nСоздана GOTO таблица \n ");

            for (IDictionaryEnumerator c = GOTO.GetEnumerator(); c.MoveNext();)
            {
                Console.WriteLine("GOTO[" + ((Tablekey)c.Key).I + ", " + ((Tablekey)c.Key).J + "] = " + c.Value);
            }

            Console.ReadLine();

            //синтакический анлиз
            string answer = "y";

            while (answer[0] == 'y')
            {
                string input;
                Console.WriteLine("Введите строку: ");
                input = Console.In.ReadLine() + "$";              //считать входную строку
                Console.WriteLine("\nВведена строка: " + input + "\n");
                Console.WriteLine("\nПроцесс вывода: \n ");
                if (input.Equals("$"))
                {                           //случай пустой строки
                    Console.WriteLine(AcceptEmptyString ?
                                      "Строка допущена" :
                                      "Строка отвергнута");
                    Console.ReadLine();
                    continue;              //  return;
                }
                Stack stack = new Stack(); //Стек автомата
                stack.Push("0");           //поместить стартовое
                //нулевое состояние
                try
                {
                    for (; ;)
                    {
                        int s = Convert.ToInt32((string)stack.Peek());
                        //вершина стека
                        char   a      = input[0]; //входной симол
                        string action = (string)ACTION[new Tablekey(s, a)];
                        //элемент
                        //ACTION -таблицы
                        if (action[0] == 's')
                        {                             //shift
                            stack.Push(a.ToString()); //поместить в стек а
                            stack.Push(action.Substring(2));
                            //поместить в стек s'
                            input = input.Substring(1);
                            //перейти к следующему символу строки
                        }
                        else if (action[0] == 'r')
                        {      //reduce
                            //rule[1] = A, rule[2] = alpha
                            string[] rule = action.Split(' ');
                            //удалить 2 * Length(alpha) элементов стека
                            for (int i = 0; i < 2 * rule[2].Length; i++)
                            {
                                stack.Pop();
                            }
                            //вершина стека
                            int state = Convert.ToInt32((string)stack.Peek());
                            //поместить в стек А и GOTO[state, A]
                            stack.Push(rule[1]);
                            stack.Push((GOTO[new Tablekey(state, rule[1][0])]).ToString());

                            //вывести правило
                            Console.WriteLine(rule[1] + "->" + rule[2]); Console.ReadLine();
                        }
                        else if (action[0] == 'a')   //accept
                        {
                            break;
                        }
                    }
                    Console.WriteLine("Строка допущена"); // Console.ReadLine();
                }
                catch (Exception) { Console.WriteLine("Строка отвергнута"); } // Console.ReadLine();
                Console.ReadLine();
                Console.WriteLine("\n Продолжить? (y or n) \n");
                answer = Console.ReadLine();
            }
        }
Exemple #47
0
        private void CompareDictionaryIgnoreOrder(string breadCrumb, IDictionaryEnumerator enumerator1,
            IDictionaryEnumerator enumerator2)
        {
            var loopedBack = false;
            var needLoopBack = false;
            var enumerator1Index = -1;
            var enumerator2Index = 0;
            int? limit = null;

            //if object2 holds more items than object1 we need to track, and then show diffs of the remaining
            //items
            var needTrackingOfObject2 = IsBigger(enumerator1, enumerator2);
            var foundObject2Items = new List<int>();

            while (enumerator1.MoveNext())
            {
                enumerator1Index++;

                //currentCrumb = AddBreadCrumb(breadCrumb, info.Name, string.Empty, i);
                var found = false;

                // expect order, but don't assume it.  this improves performance
                // where the collections are ordered in sync (wittingly, or un-), but
                // the logic is a bit different than the above index compare,

                var movedNext = enumerator2.MoveNext();

                if (!movedNext)
                {
                    enumerator2.Reset();
                    movedNext = enumerator2.MoveNext();
                    enumerator2Index = 0;
                }

                string currentBreadCrumb = breadCrumb;

                while (movedNext)
                {
                    var clone = Clone();
                    clone.Differences = new List<Difference>();

                    currentBreadCrumb = AddBreadCrumb(breadCrumb, "Current", string.Empty, enumerator1Index);

                    if (HasMatchingSpecEntry(enumerator1.Key))
                    {
                        if (clone.MatchObjects(enumerator1.Key, enumerator2.Key, ref breadCrumb))
                        {
                            found = true;
                            Compare(enumerator1.Key, enumerator2.Key, breadCrumb);
                            foundObject2Items.Add(enumerator2Index);
                            break;
                        }
                    }
                    else
                    {
                        clone.Compare(enumerator1.Key, enumerator2.Key, currentBreadCrumb);
                    }

                    if (clone.Differences.Count == 0)
                    {
                        clone.Compare(enumerator1.Value, enumerator2.Value, currentBreadCrumb);

                        if (clone.Differences.Count == 0)
                        {
                            found = true;

                            foundObject2Items.Add(enumerator2Index);

                            break;
                        }
                    }

                    movedNext = enumerator2.MoveNext();
                    enumerator2Index++;

                    if (enumerator2Index == limit)
                        break;

                    if (!movedNext && needLoopBack && !loopedBack)
                    {
                        enumerator2.Reset();
                        limit = enumerator2Index;
                        enumerator2Index = 0;
                        movedNext = enumerator2.MoveNext();
                        loopedBack = true;
                    }
                }

                if (!found)
                {
                    Difference difference = new Difference
                    {
                        ExpectedName = ExpectedName,
                        ActualName = ActualName,
                        PropertyName = currentBreadCrumb,
                        Object1Value = NiceString(enumerator1.Key),
                        Object2Value = "(null)",
                        ChildPropertyName = "Item",
                        Object1 = new WeakReference(enumerator1),
                        Object2 = null
                    };

                    AddDifference(difference);
                }

                if (Differences.Count >= MaxDifferences)
                    return;

                needLoopBack = true;
            }

            enumerator2.Reset();

            if (needTrackingOfObject2)
            {
                var j = 0;

                while (enumerator2.MoveNext())
                {
                    if (!foundObject2Items.Contains(j))
                    {
                        object objectValue2 = enumerator2.Key;
                        var matchingEntry = GetMatchingSpecEntry(objectValue2);
                        var currentCrumb = AddBreadCrumb(breadCrumb, string.Empty, (null == matchingEntry) ? string.Empty : GetMatchPhrase(objectValue2), j);

                        Compare(null, objectValue2, currentCrumb);

                        if (Differences.Count >= MaxDifferences)
                            return;
                    }

                    j++;
                }
            }
        }
Exemple #48
0
        /// <summary>
        /// Compila o resultado.
        /// </summary>
        /// <param name="resultSet">Resultado que será usado na compilação.</param>
        public void Compile(QueryResultSet resultSet)
        {
            if (!_isInitialized)
            {
                Initialize(resultSet);
            }
            else
            {
                switch (this.Type)
                {
                case QueryType.SearchKeys:
                    if (SearchKeysResult != null)
                    {
                        SearchKeysResult.AddRange(resultSet.SearchKeysResult);
                        return;
                    }
                    this.SearchKeysResult = resultSet.SearchKeysResult;
                    return;

                case QueryType.SearchEntries:
                    if (this.SearchEntriesResult != null)
                    {
                        IDictionaryEnumerator enumerator = resultSet.SearchEntriesResult.GetEnumerator();
                        while (enumerator.MoveNext())
                        {
                            SearchEntriesResult[enumerator.Key] = enumerator.Value;
                        }
                        return;
                    }
                    this.SearchEntriesResult = resultSet.SearchEntriesResult;
                    return;

                case QueryType.AggregateFunction:
                    decimal     num;
                    decimal     num2;
                    object      obj2;
                    object      obj3;
                    IComparable comparable;
                    IComparable comparable2;
                    switch (((AggregateFunctionType)this.AggregateFunctionResult.Key))
                    {
                    case AggregateFunctionType.SUM:
                    {
                        obj2 = this.AggregateFunctionResult.Value;
                        obj3 = resultSet.AggregateFunctionResult.Value;
                        decimal?nullable = null;
                        if ((obj2 == null) && (obj3 != null))
                        {
                            nullable = new decimal?((decimal)obj3);
                        }
                        else if ((obj2 != null) && (obj3 == null))
                        {
                            nullable = new decimal?((decimal)obj2);
                        }
                        else if ((obj2 != null) && (obj3 != null))
                        {
                            num      = (decimal)obj2;
                            num2     = (decimal)obj3;
                            nullable = new decimal?(num + num2);
                        }
                        if (nullable.HasValue)
                        {
                            this.AggregateFunctionResult = new DictionaryEntry(AggregateFunctionType.SUM, nullable);
                            return;
                        }
                        this.AggregateFunctionResult = new DictionaryEntry(AggregateFunctionType.SUM, null);
                        return;
                    }

                    case AggregateFunctionType.COUNT:
                    {
                        num  = (decimal)this.AggregateFunctionResult.Value;
                        num2 = (decimal)resultSet.AggregateFunctionResult.Value;
                        decimal num3 = num + num2;
                        this.AggregateFunctionResult = new DictionaryEntry(AggregateFunctionType.COUNT, num3);
                        return;
                    }

                    case AggregateFunctionType.MIN:
                    {
                        comparable  = (IComparable)this.AggregateFunctionResult.Value;
                        comparable2 = (IComparable)resultSet.AggregateFunctionResult.Value;
                        IComparable comparable3 = comparable;
                        if ((comparable == null) && (comparable2 != null))
                        {
                            comparable3 = comparable2;
                        }
                        else if ((comparable != null) && (comparable2 == null))
                        {
                            comparable3 = comparable;
                        }
                        else if ((comparable == null) && (comparable2 == null))
                        {
                            comparable3 = null;
                        }
                        else if (comparable2.CompareTo(comparable) < 0)
                        {
                            comparable3 = comparable2;
                        }
                        this.AggregateFunctionResult = new DictionaryEntry(AggregateFunctionType.MIN, comparable3);
                        return;
                    }

                    case AggregateFunctionType.MAX:
                    {
                        comparable  = (IComparable)this.AggregateFunctionResult.Value;
                        comparable2 = (IComparable)resultSet.AggregateFunctionResult.Value;
                        IComparable comparable4 = comparable;
                        if ((comparable == null) && (comparable2 != null))
                        {
                            comparable4 = comparable2;
                        }
                        else if ((comparable != null) && (comparable2 == null))
                        {
                            comparable4 = comparable;
                        }
                        else if ((comparable == null) && (comparable2 == null))
                        {
                            comparable4 = null;
                        }
                        else if (comparable2.CompareTo(comparable) > 0)
                        {
                            comparable4 = comparable2;
                        }
                        this.AggregateFunctionResult = new DictionaryEntry(AggregateFunctionType.MAX, comparable4);
                        return;
                    }

                    case AggregateFunctionType.AVG:
                    {
                        obj2 = this.AggregateFunctionResult.Value;
                        obj3 = resultSet.AggregateFunctionResult.Value;
                        AverageResult result = null;
                        if ((obj2 == null) && (obj3 != null))
                        {
                            result = (AverageResult)obj3;
                        }
                        else if ((obj2 != null) && (obj3 == null))
                        {
                            result = (AverageResult)obj2;
                        }
                        else if ((obj2 != null) && (obj3 != null))
                        {
                            AverageResult result2 = (AverageResult)obj2;
                            AverageResult result3 = (AverageResult)obj3;
                            result       = new AverageResult();
                            result.Sum   = result2.Sum + result3.Sum;
                            result.Count = result2.Count + result3.Count;
                        }
                        if (result != null)
                        {
                            this.AggregateFunctionResult = new DictionaryEntry(AggregateFunctionType.AVG, result);
                            return;
                        }
                        this.AggregateFunctionResult = new DictionaryEntry(AggregateFunctionType.AVG, null);
                        return;
                    }
                    }
                    return;
                }
            }
        }
Exemple #49
0
        private string createTransTable(IDictionaryEnumerator translist)
        {
            translist.Reset();
            string res = "";
            while (translist.MoveNext())
            {
                Translation trans = (Translation) translist.Value;
                res += "<tr>\n\t\t\t<td></td><td colspan=\"3\" bgcolor=\"dddddd\">" + trans.ToString() + "</td></tr>\n\t\t";
                res += "<tr>\n\t\t\t<td colspan=\"4\" style=\"padding:10px;\" bgcolor=\"#f4f4f4\">" +
                    this.cleanText(trans.Text, this.checkBox1.Checked) + "</td></tr>\n\t\t";

            }
            return res;
        }
Exemple #50
0
    /// <remarks>
    /// Builds ResAsm files out of resource files
    /// </remarks>
    static void Disassemble(string pattern)
    {
        string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), pattern);
        foreach (string file in files)
        {
            Hashtable resources = new Hashtable();
            int       length    = 0;
            // read resource files into the hashtable
            switch (Path.GetExtension(file).ToUpper())
            {
            case ".RESX":
                ResXResourceReader    rx = new ResXResourceReader(file);
                IDictionaryEnumerator n  = rx.GetEnumerator();
                while (n.MoveNext())
                {
                    if (!resources.ContainsKey(n.Key))
                    {
                        length = Math.Max(length, n.Key.ToString().Length);
                        resources.Add(n.Key, n.Value);
                    }
                }

                rx.Close();
                break;

            case ".RESOURCES":
                ResourceReader rr = new ResourceReader(file);
                foreach (DictionaryEntry entry in rr)
                {
                    if (!resources.ContainsKey(entry.Key))
                    {
                        length = Math.Max(length, entry.Key.ToString().Length);
                        resources.Add(entry.Key, entry.Value);
                    }
                }
                rr.Close();
                break;
            }

            // write the hashtable to the resource file
            string       fname  = Path.GetFileNameWithoutExtension(file);
            string       path   = fname + "-data";
            StreamWriter writer = File.CreateText(fname + ".res");

            writer.Write("# this file was automatically generated by ResAsm\r\n\r\n");
            foreach (DictionaryEntry entry in resources)
            {
                // strings are put directly into the resasm format
                if (entry.Value is string)
                {
                    writer.Write(entry.Key.ToString() + "=\"" + ConvertIllegalChars(entry.Value.ToString()) + "\"\r\n");
                }
                else
                {
                    // all other files are referenced as a file and the filename
                    // is saved in the resasm format, the files need to be generated.
                    string extension  = "";
                    string outputname = path + '\\' + entry.Key.ToString();
                    if (entry.Value is Icon)
                    {
                        extension = ".ico";
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        ((Icon)entry.Value).Save(File.Create(outputname + extension));
                    }
                    else if (entry.Value is Image)
                    {
                        // all bitmaps are saved in the png format
                        extension = ".png";
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                        ((Image)entry.Value).Save(outputname + extension, ImageFormat.Png);
                    }
                    else
                    {
                        Console.WriteLine("can't save " + entry.Key + " unknown format.");
                        continue;
                    }
                    writer.Write(entry.Key.ToString().PadRight(length) + " = " + outputname + extension + "\r\n");
                }
            }
            writer.Close();
        }
    }
Exemple #51
0
        public virtual object rewind(ScriptContext context)
        {
            if (iterator != null)
            {
                // we can make use of standard foreach enumerator
                enumerator = iterator.GetForeachEnumerator(true, false, null);

                isValid = enumerator.MoveNext();
            }

            return null;
        }
        public override void ExecuteCommand(ClientManager clientManager, Common.Protobuf.Command command)
        {
            CommandInfo cmdInfo = new CommandInfo();
            int         overload;
            string      exception = null;
            Stopwatch   stopWatch = new Stopwatch();

            stopWatch.Start();
            try
            {
                overload = command.MethodOverload;
                cmdInfo  = ParseCommand(command, clientManager, clientManager.CmdExecuter.ID);
            }
            catch (Exception exc)
            {
                invokeEntryProcessorResult = Command.OperationResult.Failure;
                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeExceptionResponse(exc, command.requestID, command.commandID));
                return;
            }
            NCache nCache = clientManager.CmdExecuter as NCache;

            try
            {
                OperationContext operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation);
                operationContext.Add(OperationContextFieldName.ClientLastViewId, cmdInfo.clientLastViewId);
                operationContext.Add(OperationContextFieldName.ReadThru, cmdInfo.readOptionFlag.IsBitSet(BitSetConstants.ReadThru));
                if (cmdInfo.defaultReadThru != null)
                {
                    operationContext.Add(OperationContextFieldName.ReadThruProviderName, cmdInfo.defaultReadThru);
                }

                if (!string.IsNullOrEmpty(cmdInfo.intendedRecipient))
                {
                    operationContext.Add(OperationContextFieldName.IntendedRecipient, cmdInfo.intendedRecipient);
                }

                Hashtable getResult = (Hashtable)nCache.Cache.InvokeEntryProcessor(cmdInfo.keys, cmdInfo.entryProcessor, cmdInfo.arguments, cmdInfo.writeOptionFlag, cmdInfo.defaultWriteThru, operationContext);

                stopWatch.Stop();
                Alachisoft.NCache.Common.Protobuf.Response response = new Alachisoft.NCache.Common.Protobuf.Response();
                Alachisoft.NCache.Common.Protobuf.InvokeEntryProcessorResponse invokeEntryProcessorResponse = new Alachisoft.NCache.Common.Protobuf.InvokeEntryProcessorResponse();
                response.requestId = Convert.ToInt64(cmdInfo.requestId);

                Alachisoft.NCache.Common.Protobuf.InvokeEPKeyValuePackageResponse invokeEPKeyValuePackage = new Common.Protobuf.InvokeEPKeyValuePackageResponse();
                IDictionaryEnumerator dictEnumerator = getResult.GetEnumerator();
                while (dictEnumerator.MoveNext())
                {
                    invokeEPKeyValuePackage.keys.Add((string)dictEnumerator.Key);
                    invokeEPKeyValuePackage.values.Add(CompactBinaryFormatter.ToByteBuffer(dictEnumerator.Value, nCache.CacheId));
                }
                invokeEntryProcessorResponse.keyValuePackage = invokeEPKeyValuePackage;

                response.responseType = Alachisoft.NCache.Common.Protobuf.Response.Type.INVOKE_ENTRY_PROCESSOR;
                response.invokeEntryProcessorResponse = invokeEntryProcessorResponse;

                response.commandID = command.commandID;

                _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response));
            }
            catch (Exception exc)
            {
                invokeEntryProcessorResult = OperationResult.Failure;
                //PROTOBUF:RESPONSE
                exception = exc.ToString();
                _serializedResponsePackets.Add(ResponseHelper.SerializeExceptionResponse(exc, command.requestID, command.commandID));
            }
            finally
            {
                TimeSpan executionTime = stopWatch.Elapsed;
                try
                {
                    if (Alachisoft.NCache.Management.APILogging.APILogManager.APILogManger != null && Alachisoft.NCache.Management.APILogging.APILogManager.EnableLogging)
                    {
                        APILogItemBuilder log = new APILogItemBuilder(MethodsName.Invoke.ToLower());
                        log.GenerateEntryProcessorAPILogItem(cmdInfo.keys.Length, cmdInfo.entryProcessor.ToString(), cmdInfo.readOptionFlag, cmdInfo.defaultReadThru, cmdInfo.writeOptionFlag, cmdInfo.defaultWriteThru, cmdInfo.arguments, overload, exception, executionTime, clientManager.ClientID.ToLower(), clientManager.ClientSocketId.ToString());
                    }
                }
                catch
                {
                }
            }
        }