GetEnumerator() public method

public GetEnumerator ( ) : IDictionaryEnumerator
return IDictionaryEnumerator
コード例 #1
0
ファイル: SortedList.cs プロジェクト: zuimengaitianya/corefx
 public override IDictionaryEnumerator GetEnumerator()
 {
     lock (_root)
     {
         return(_list.GetEnumerator());
     }
 }
コード例 #2
0
ファイル: xml.aspx.cs プロジェクト: saciervo/Umbraco-CMS
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "text/xml";
            int pageId;

            XmlNode root = _xd.CreateElement("tasks");

            if (int.TryParse(Request["id"], out pageId))
            {
                var t = new Task(pageId);
                if (t.User.Id == base.getUser().Id || t.ParentUser.Id == base.getUser().Id)
                {
                    XmlNode x = CreateTaskNode(t, _xd);
                    root.AppendChild(x);

                    xmlContents.Text = root.OuterXml;

                    Response.AddHeader("Content-Disposition", "attachment; filename=" + t.Node.Text.Replace(" ", "_") + ".xml");
                }
            }
            else
            {
                var nodes = new SortedList();
                int totalWords = 0;

                foreach (Task t in Task.GetTasks(base.getUser(), false))
                {
                    if (!nodes.ContainsKey(t.Node.Path))
                    {
                        var xTask = CreateTaskNode(t, _xd);
                        totalWords += int.Parse(xTask.Attributes.GetNamedItem("TotalWords").Value);
                        nodes.Add(t.Node.Path, xTask);
                    }
                }

                // Arrange nodes in tree
                var ide = nodes.GetEnumerator();
                while (ide.MoveNext())
                {
                    var x = (XmlElement)ide.Value;
                    var parentXpath = UmbracoSettings.UseLegacyXmlSchema ? "//node [@id = '" + x.SelectSingleNode("//node").Attributes.GetNamedItem("parentID").Value + "']" :
                        "//* [@isDoc and @id = '" + x.SelectSingleNode("//* [@isDoc]").Attributes.GetNamedItem("parentID").Value + "']";
                    var parent = _xd.SelectSingleNode(parentXpath);

                    if (parent == null)
                        parent = root;
                    else
                        parent = parent.ParentNode;

                    parent.AppendChild((XmlElement)ide.Value);
                }

                root.Attributes.Append(XmlHelper.AddAttribute(_xd, "TotalWords", totalWords.ToString()));
                xmlContents.Text = root.OuterXml;
                Response.AddHeader("Content-Disposition", "attachment; filename=all.xml");

            }
        }
コード例 #3
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            pp_name.Text = ui.Text("name");
            pp_renderControl.Text = ui.Text("renderControl");
            pane_settings.Text = ui.Text("settings");
            pp_guid.Text = ui.Text("guid");


            _id = int.Parse(Request.QueryString["id"]);
            dt = cms.businesslogic.datatype.DataTypeDefinition.GetDataTypeDefinition(_id);


            f = new cms.businesslogic.datatype.controls.Factory();

            if (!IsPostBack)
            {
                txtName.Text = dt.Text;

                SortedList datatypes = new SortedList();

                foreach (interfaces.IDataType df in f.GetAll())
                    datatypes.Add(df.DataTypeName + "|" + Guid.NewGuid().ToString(), df.Id);

                IDictionaryEnumerator ide = datatypes.GetEnumerator();

                string datatTypeId = dt.DataType != null ? dt.DataType.Id.ToString() : String.Empty;
                while (ide.MoveNext())
                {
                    ListItem li = new ListItem();
                    li.Text = ide.Key.ToString().Substring(0, ide.Key.ToString().IndexOf("|"));
                    li.Value = ide.Value.ToString();

                    //SJ Fixes U4-2488 Edit datatype: Media Picker appears incorrectly
                    //Apparently in some installs the media picker rendercontrol is installed twice with 
                    //the exact same ID so we need to check for duplicates
                    if (ddlRenderControl.Items.Contains(li))
                        continue;

                    if (!String.IsNullOrEmpty(datatTypeId) && li.Value.ToString() == datatTypeId) li.Selected = true;
                    ddlRenderControl.Items.Add(li);
                }

                ClientTools
                    .SetActiveTreeType(TreeDefinitionCollection.Instance.FindTree<loadDataTypes>().Tree.Alias)
                    .SyncTree("-1,init," + _id.ToString(), false);

            }

            if (dt.DataType != null)
                litGuid.Text = dt.DataType.Id.ToString();
            Panel1.Text = umbraco.ui.Text("edit") + " datatype: " + dt.Text;
            insertPrevalueEditor();
        }
コード例 #4
0
ファイル: Search.cs プロジェクト: BackupTheBerlios/lyra2-svn
 public string queryTrans(SortedList trans, bool text)
 {
     string query = "";
     IDictionaryEnumerator en = trans.GetEnumerator();
     en.Reset();
     while (en.MoveNext())
     {
         query += ((Translation) en.Value).Title;
         if (text) query += " " + ((Translation) en.Value).Text;
     }
     return query;
 }
コード例 #5
0
 static public int GetEnumerator(IntPtr l)
 {
     try {
         System.Collections.SortedList self = (System.Collections.SortedList)checkSelf(l);
         var ret = self.GetEnumerator();
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #6
0
ファイル: PatientAssociateArray.cs プロジェクト: OSEHRA/mdws
 public PatientAssociateArray(SortedList lst)
 {
     if (lst == null || lst.Count == 0)
     {
         count = 0;
         return;
     }
     pas = new PatientAssociateTO[lst.Count];
     IDictionaryEnumerator e = lst.GetEnumerator();
     int i = 0;
     while (e.MoveNext())
     {
         pas[i++] = new PatientAssociateTO((PatientAssociate)e.Value);
     }
     count = lst.Count;
 }
コード例 #7
0
 public PersonArray(SortedList lst)
 {
     if (lst == null || lst.Count == 0)
     {
         count = 0;
         return;
     }
     persons = new PersonTO[lst.Count];
     IDictionaryEnumerator e = lst.GetEnumerator();
     int i = 0;
     while (e.MoveNext())
     {
         persons[i++] = new PersonTO((Person)e.Value);
     }
     count = lst.Count;
 }
コード例 #8
0
ファイル: CityArray.cs プロジェクト: OSEHRA/mdws
 public CityArray(SortedList lst)
 {
     if (lst == null || lst.Count == 0)
     {
         count = 0;
         return;
     }
     cities = new CityTO[lst.Count];
     IDictionaryEnumerator e = lst.GetEnumerator();
     int i = 0;
     while (e.MoveNext())
     {
         cities[i++] = new CityTO((City)e.Value);
     }
     count = lst.Count;
 }
コード例 #9
0
		private void updateCultureList() 
		{
            SortedList sortedCultures = new SortedList();
            Cultures.Items.Clear();
            Cultures.Items.Add(new ListItem(ui.Text("choose") + "...", ""));
            foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
                sortedCultures.Add(ci.DisplayName + "|||" + Guid.NewGuid().ToString(), ci.Name);

            IDictionaryEnumerator ide = sortedCultures.GetEnumerator();
            while (ide.MoveNext())
            {
                ListItem li = new ListItem(ide.Key.ToString().Substring(0, ide.Key.ToString().IndexOf("|||")), ide.Value.ToString());
                if (ide.Value.ToString() == currentLanguage.CultureAlias)
                    li.Selected = true;

                Cultures.Items.Add(li);
            }
        }
コード例 #10
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // get all existing languages

            sbmt.Text = ui.Text("create");
            SortedList sortedCultures = new SortedList();
            Cultures.Items.Clear();
            Cultures.Items.Add(new ListItem(ui.Text("choose") + "...", ""));
            foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures))
            {
                    sortedCultures.Add(ci.DisplayName + "|||" + Guid.NewGuid().ToString(), ci.Name);
            }

            IDictionaryEnumerator ide = sortedCultures.GetEnumerator();
            while (ide.MoveNext())
            {
                ListItem li = new ListItem(ide.Key.ToString().Substring(0, ide.Key.ToString().IndexOf("|||")), ide.Value.ToString());
                Cultures.Items.Add(li);
            }
        }
コード例 #11
0
ファイル: SiteArray.cs プロジェクト: OSEHRA/mdws
 public SiteArray(SortedList lst)
 {
     if (lst == null || lst.Count == 0)
     {
         count = 0;
         return;
     }
     ArrayList al = new ArrayList(lst.Count);
     IDictionaryEnumerator e = lst.GetEnumerator();
     while (e.MoveNext())
     {
         Site s = (Site)e.Value;
         if (s != null)
         {
             al.Add(new SiteTO(s));
         }
     }
     sites = (SiteTO[])al.ToArray(typeof(SiteTO));
     count = sites.Length;
 }
コード例 #12
0
ファイル: GetEnumerator.cs プロジェクト: GTuritto/ngenerics
        public void Simple()
        {
            var sortedList = new SortedList<int>();

            for (var i = 0; i < 20; i++)
            {
                sortedList.Add(i);
            }

            var counter = 0;
            var enumerator = sortedList.GetEnumerator();

            while (enumerator.MoveNext())
            {
                Assert.AreEqual(enumerator.Current, counter);
                counter++;
            }

            Assert.AreEqual(counter, 20);
        }
コード例 #13
0
ファイル: Search.cs プロジェクト: BackupTheBerlios/lyra2-svn
        public bool SearchCollection(string query, SortedList list, ListBox resultBox,
            bool text, bool matchCase, bool whole, bool trans)
        {
            long start = Util.getCurrentTicks();
            IDictionaryEnumerator en = list.GetEnumerator();
            en.Reset();
            string target = "";
            Song song;
            bool found = false;
            while (en.MoveNext())
            {
                song = (Song) en.Value;

                // only title?
                target = text ? (song.Title + " " + song.Text) : song.Title;

                // with translations?
                if (trans)
                {
                    target += (" " + song.queryTrans(this, text));
                }

                // if case doesn't need to be matched, make all letters small ones...
                if (!matchCase)
                {
                    target = target.ToLower();
                    query = query.ToLower();
                }

                if (this.Or(query, this.cleanTarget(target), whole))
                {
                    resultBox.Items.Add(song);
                    found = true;
                }
            }
            Util.addSearchTime(Util.getCurrentTicks() - start);
            return found;
        }
コード例 #14
0
ファイル: resourcewriter.cs プロジェクト: ItsVeryWindy/mono
        [SecuritySafeCritical]  // Asserts permission to create & delete a temp file.
        public void Generate()
        {
            if (_resourceList == null)
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceWriterSaved"));

            BinaryWriter bw = new BinaryWriter(_output, Encoding.UTF8);
            List<String> typeNames = new List<String>();
                
            // Write out the ResourceManager header
            // Write out magic number
            bw.Write(ResourceManager.MagicNumber);
                
            // Write out ResourceManager header version number
            bw.Write(ResourceManager.HeaderVersionNumber);

            MemoryStream resMgrHeaderBlob = new MemoryStream(240);
            BinaryWriter resMgrHeaderPart = new BinaryWriter(resMgrHeaderBlob);

            // Write out class name of IResourceReader capable of handling 
            // this file.
            resMgrHeaderPart.Write(MultitargetingHelpers.GetAssemblyQualifiedName(typeof(ResourceReader),typeConverter));

            // Write out class name of the ResourceSet class best suited to
            // handling this file.
            // This needs to be the same even with multi-targeting. It's the 
            // full name -- not the ----sembly qualified name.
            resMgrHeaderPart.Write(ResourceManager.ResSetTypeName);
            resMgrHeaderPart.Flush();

            // Write number of bytes to skip over to get past ResMgr header
            bw.Write((int)resMgrHeaderBlob.Length);

            // Write the rest of the ResMgr header
            bw.Write(resMgrHeaderBlob.GetBuffer(), 0, (int)resMgrHeaderBlob.Length);
            // End ResourceManager header


            // Write out the RuntimeResourceSet header
            // Version number
            bw.Write(RuntimeResourceSet.Version);
#if RESOURCE_FILE_FORMAT_DEBUG
            // Write out a tag so we know whether to enable or disable 
            // debugging support when reading the file.
            bw.Write("***DEBUG***");
#endif

            // number of resources
            int numResources = _resourceList.Count;
            if (_preserializedData != null)
                numResources += _preserializedData.Count;
            bw.Write(numResources);
                
            // Store values in temporary streams to write at end of file.
            int[] nameHashes = new int[numResources];
            int[] namePositions = new int[numResources];
            int curNameNumber = 0;
            MemoryStream nameSection = new MemoryStream(numResources * AverageNameSize);
            BinaryWriter names = new BinaryWriter(nameSection, Encoding.Unicode);

            // The data section can be very large, and worse yet, we can grow the byte[] used
            // for the data section repeatedly.  When using large resources like ~100 images,
            // this can lead to both a fragmented large object heap as well as allocating about
            // 2-3x of our storage needs in extra overhead.  Using a temp file can avoid this.
            // Assert permission to get a temp file name, which requires two permissions.
            // Additionally, we may be running under an account that doesn't have permission to
            // write to the temp directory (enforced via a Windows ACL).  Fall back to a MemoryStream.
            Stream dataSection = null;  // Either a FileStream or a MemoryStream
            String tempFile = null;
#if FEATURE_MONO_CAS
            PermissionSet permSet = new PermissionSet(PermissionState.None);
            permSet.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
            permSet.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
#endif
            try {
#if FEATURE_MONO_CAS
                permSet.Assert();
#endif
                tempFile = Path.GetTempFileName();
                File.SetAttributes(tempFile, FileAttributes.Temporary | FileAttributes.NotContentIndexed);
                // Explicitly opening with FileOptions.DeleteOnClose to avoid complicated File.Delete
                // (safe from ----s w/ antivirus software, etc)
                dataSection = new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite, FileShare.Read,
                                             4096, FileOptions.DeleteOnClose | FileOptions.SequentialScan);
            }
            catch (UnauthorizedAccessException) {
                // In case we're running under an account that can't access a temp directory.
                dataSection = new MemoryStream();
            }
            catch (IOException) {
                // In case Path.GetTempFileName fails because no unique file names are available
                dataSection = new MemoryStream();
            }
            finally {
#if FEATURE_MONO_CAS
                PermissionSet.RevertAssert();
#endif
            }

            using(dataSection) {
                BinaryWriter data = new BinaryWriter(dataSection, Encoding.UTF8);
#if FEATURE_SERIALIZATION
                IFormatter objFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.File | StreamingContextStates.Persistence));
#endif // FEATURE_SERIALIZATION

#if RESOURCE_FILE_FORMAT_DEBUG
                // Write NAMES right before the names section.
                names.Write(new byte[] { (byte) 'N', (byte) 'A', (byte) 'M', (byte) 'E', (byte) 'S', (byte) '-', (byte) '-', (byte) '>'});
            
                // Write DATA at the end of the name table section.
                data.Write(new byte[] { (byte) 'D', (byte) 'A', (byte) 'T', (byte) 'A', (byte) '-', (byte) '-', (byte)'-', (byte)'>'});
#endif

                // We've stored our resources internally in a Hashtable, which 
                // makes no guarantees about the ordering while enumerating.  
                // While we do our own sorting of the resource names based on their
                // hash values, that's only sorting the nameHashes and namePositions
                // arrays.  That's all that is strictly required for correctness,
                // but for ease of generating a patch in the future that 
                // modifies just .resources files, we should re-sort them.

                SortedList sortedResources = new SortedList(_resourceList, FastResourceComparer.Default);
                if (_preserializedData != null) {
                    foreach (KeyValuePair<String, PrecannedResource> entry in _preserializedData)
                        sortedResources.Add(entry.Key, entry.Value);
                }

                IDictionaryEnumerator items = sortedResources.GetEnumerator();
                // Write resource name and position to the file, and the value
                // to our temporary buffer.  Save Type as well.
                while (items.MoveNext()) {
                    nameHashes[curNameNumber] = FastResourceComparer.HashFunction((String)items.Key);
                    namePositions[curNameNumber++] = (int)names.Seek(0, SeekOrigin.Current);
                    names.Write((String)items.Key); // key
                    names.Write((int)data.Seek(0, SeekOrigin.Current)); // virtual offset of value.
#if RESOURCE_FILE_FORMAT_DEBUG
                    names.Write((byte) '*');
#endif
                    Object value = items.Value;
                    ResourceTypeCode typeCode = FindTypeCode(value, typeNames);

                    // Write out type code
                    Write7BitEncodedInt(data, (int)typeCode);

                    // Write out value
                    PrecannedResource userProvidedResource = value as PrecannedResource;
                    if (userProvidedResource != null) {
                        data.Write(userProvidedResource.Data);
                    }
                    else {
#if FEATURE_SERIALIZATION
                        WriteValue(typeCode, value, data, objFormatter);
#else 
                        WriteValue(typeCode, value, data);
#endif
                    }

#if RESOURCE_FILE_FORMAT_DEBUG
                    data.Write(new byte[] { (byte) 'S', (byte) 'T', (byte) 'O', (byte) 'P'});
#endif
                }

                // At this point, the ResourceManager header has been written.
                // Finish RuntimeResourceSet header
                //   Write size & contents of class table
                bw.Write(typeNames.Count);
                for (int i = 0; i < typeNames.Count; i++)
                    bw.Write(typeNames[i]);

                // Write out the name-related items for lookup.
                //  Note that the hash array and the namePositions array must
                //  be sorted in parallel.
                Array.Sort(nameHashes, namePositions);

                //  Prepare to write sorted name hashes (alignment fixup)
                //   Note: For 64-bit machines, these MUST be aligned on 8 byte 
                //   boundaries!  Pointers on IA64 must be aligned!  And we'll
                //   run faster on X86 machines too.
                bw.Flush();
                int alignBytes = ((int)bw.BaseStream.Position) & 7;
                if (alignBytes > 0) {
                    for (int i = 0; i < 8 - alignBytes; i++)
                        bw.Write("PAD"[i % 3]);
                }

                //  Write out sorted name hashes.
                //   Align to 8 bytes.
                Contract.Assert((bw.BaseStream.Position & 7) == 0, "ResourceWriter: Name hashes array won't be 8 byte aligned!  Ack!");
#if RESOURCE_FILE_FORMAT_DEBUG
                bw.Write(new byte[] { (byte) 'H', (byte) 'A', (byte) 'S', (byte) 'H', (byte) 'E', (byte) 'S', (byte) '-', (byte) '>'} );
#endif
                foreach (int hash in nameHashes)
                    bw.Write(hash);
#if RESOURCE_FILE_FORMAT_DEBUG
                Console.Write("Name hashes: ");
                foreach(int hash in nameHashes)
                    Console.Write(hash.ToString("x")+"  ");
                Console.WriteLine();
#endif

                //  Write relative positions of all the names in the file.
                //   Note: this data is 4 byte aligned, occuring immediately 
                //   after the 8 byte aligned name hashes (whose length may 
                //   potentially be odd).
                Contract.Assert((bw.BaseStream.Position & 3) == 0, "ResourceWriter: Name positions array won't be 4 byte aligned!  Ack!");
#if RESOURCE_FILE_FORMAT_DEBUG
                bw.Write(new byte[] { (byte) 'P', (byte) 'O', (byte) 'S', (byte) '-', (byte) '-', (byte) '-', (byte) '-', (byte) '>' } );
#endif
                foreach (int pos in namePositions)
                    bw.Write(pos);
#if RESOURCE_FILE_FORMAT_DEBUG
                Console.Write("Name positions: ");
                foreach(int pos in namePositions)
                    Console.Write(pos.ToString("x")+"  ");
                Console.WriteLine();
#endif

                // Flush all BinaryWriters to their underlying streams.
                bw.Flush();
                names.Flush();
                data.Flush();

                // Write offset to data section
                int startOfDataSection = (int)(bw.Seek(0, SeekOrigin.Current) + nameSection.Length);
                startOfDataSection += 4;  // We're writing an int to store this data, adding more bytes to the header
                BCLDebug.Log("RESMGRFILEFORMAT", "Generate: start of DataSection: 0x" + startOfDataSection.ToString("x", CultureInfo.InvariantCulture) + "  nameSection length: " + nameSection.Length);
                bw.Write(startOfDataSection);

                // Write name section.
                bw.Write(nameSection.GetBuffer(), 0, (int)nameSection.Length);
                names.Close();

                // Write data section.
                Contract.Assert(startOfDataSection == bw.Seek(0, SeekOrigin.Current), "ResourceWriter::Generate - start of data section is wrong!");
                dataSection.Position = 0;
                dataSection.CopyTo(bw.BaseStream);
                data.Close();
            } // using(dataSection)  <--- Closes dataSection, which was opened w/ FileOptions.DeleteOnClose
            bw.Flush();

            // Indicate we've called Generate
            _resourceList = null;
        }
コード例 #15
0
        /// <summary>
        /// Retrieves a list of all datatypedefinitions
        /// </summary>
        /// <returns>A list of all datatypedefinitions</returns>
        public static DataTypeDefinition[] GetAll()
        {
            SortedList retvalSort = new SortedList();
            Guid[] tmp = CMSNode.getAllUniquesFromObjectType(_objectType);
            DataTypeDefinition[] retval = new DataTypeDefinition[tmp.Length];
            for (int i = 0; i < tmp.Length; i++)
            {
                DataTypeDefinition dt = DataTypeDefinition.GetDataTypeDefinition(tmp[i]);
                retvalSort.Add(dt.Text + "|||" + Guid.NewGuid().ToString(), dt);
            }

            IDictionaryEnumerator ide = retvalSort.GetEnumerator();
            int counter = 0;
            while (ide.MoveNext())
            {
                retval[counter] = (DataTypeDefinition)ide.Value;
                counter++;
            }
            return retval;
        }
 public static void BuildComplexTypeParser(Hashtable SequenceTable, Hashtable ChoiceTable, CodeProcessor cs, SortedList SortedServiceList, string pc_methodPrefix, string pc_methodLibPrefix)
 {
     IDictionaryEnumerator en = SortedServiceList.GetEnumerator();
     while (en.MoveNext())
     {
         UPnPService service = (UPnPService)en.Value;
         foreach (UPnPComplexType CT in service.GetComplexTypeList())
         {
             int SeqX = 0;
             int ChoX = 0;
             cs.Append("struct " + CT.Name_LOCAL + "* " + pc_methodPrefix + "Parse_" + CT.Name_LOCAL + "(struct " + pc_methodLibPrefix + "XMLNode *node)" + cl);
             cs.Append("{" + cl);
             cs.Append("	struct " + pc_methodLibPrefix + "XMLNode *current = node;" + cl);
             cs.Append("	struct " + CT.Name_LOCAL + " *RetVal;" + cl);
             cs.Append("	" + cl);
             cs.Append("	int OK;" + cl);
             cs.Append("	char *text;" + cl);
             cs.Append("	int textLength;" + cl);
             cs.Append("	if ((RetVal = (struct " + CT.Name_LOCAL + "*)malloc(sizeof(struct " + CT.Name_LOCAL + "))) == NULL) ILIBCRITICALEXIT(254);" + cl);
             cs.Append(cl);
             cs.Append("	memset(RetVal, 0, sizeof(struct " + CT.Name_LOCAL + "));" + cl);
             cs.Append(cl);
             cs.Append("	while(node != NULL)" + cl);
             cs.Append("	{" + cl);
             cs.Append("		textLength = " + pc_methodLibPrefix + "ReadInnerXML(node, &text);" + cl);
             foreach (UPnPComplexType.GenericContainer gc in CT.Containers)
             {
                 foreach (UPnPComplexType.ItemCollection ic in gc.Collections)
                 {
                     BuildComplexTypeParser_Collection("", SequenceTable, ChoiceTable, ref SeqX, ref ChoX, cs, ic, pc_methodPrefix);
                 }
             }
             cs.Append("	node = node->Peer;" + cl);
             cs.Append("	}" + cl);
             cs.Append("	return(RetVal);" + cl);
             cs.Append("}" + cl);
         }
     }
 }
コード例 #17
0
 protected List<MediaItem> getSelectedItemsFromMediaItemList(ListBox _listView)
 {
     Object trackInfo;
     MediaItem mediaItem;
     IEnumerator selectedItemsEnum = _listView.SelectedItems.GetEnumerator();
     List<MediaItem> list = new List<MediaItem>();
     SortedList<int, MediaItem> listSorted = new SortedList<int, MediaItem>();
     while (selectedItemsEnum.MoveNext())
     {
         trackInfo = selectedItemsEnum.Current;
         mediaItem = (MediaItem)trackInfo;
         listSorted.Add(mediaItem.listIndex, mediaItem);
     }
     selectedItemsEnum = listSorted.GetEnumerator();
     foreach (var pair in listSorted)
     {
         mediaItem = (MediaItem)pair.Value;
         list.Add(mediaItem);
     }
     return list;
 }
コード例 #18
0
 private void LoadFunctionSets(int FileVer)
 {
     string left = Main.pvStr(FileVer, ".");
     cfgFile cfgFile = new cfgFile(Main.AppPath() + "Config\\FunctionSets.cfg");
     SortedList sortedList = new SortedList();
     Regex regex = new Regex("^\\d{2}\\.\\d{2}\\.\\d{2}\\.\\d{2}$");
     cfgFile.cfgSection[] sections = cfgFile.Sections;
     checked
     {
         for (int i = 0; i < sections.Length; i++)
         {
             cfgFile.cfgSection cfgSection = sections[i];
             bool flag = regex.Match(cfgSection.Name).Success;
             if (flag)
             {
                 sortedList.Add(cfgSection.Name, cfgSection);
             }
         }
         IDictionaryEnumerator enumerator = sortedList.GetEnumerator();
         while (enumerator.MoveNext())
         {
             object expr_98 = enumerator.Current;
             DictionaryEntry dictionaryEntry2;
             DictionaryEntry dictionaryEntry = (expr_98 != null) ? ((DictionaryEntry)expr_98) : dictionaryEntry2;
             bool flag = Operators.ConditionalCompareObjectLess(left, dictionaryEntry.Key, false);
             if (!flag)
             {
                 cfgFile.cfgSection cfgSection2 = (cfgFile.cfgSection)dictionaryEntry.Value;
                 cfgFile.cfgKey[] keys = cfgSection2.Keys;
                 for (int j = 0; j < keys.Length; j++)
                 {
                     cfgFile.cfgKey cfgKey = keys[j];
                     flag = this.FunctionSets.ContainsKey(cfgKey.Name);
                     if (flag)
                     {
                         this.FunctionSets[cfgKey.Name] = cfgKey.Value;
                     }
                     else
                     {
                         this.FunctionSets.Add(cfgKey.Name, cfgKey.Value);
                     }
                 }
             }
         }
     }
 }
コード例 #19
0
		/// <summary>
		/// Compute the condensation graph and store it in the supplied graph 'cg'
		/// </summary>
		/// <param name="cg">
		/// Instance of mutable graph in which the condensation graph 
		/// transformation is stored
		/// </param>
		public void Create( IMutableVertexAndEdgeListGraph cg )	
        {
			if (cg==null)
				throw new ArgumentNullException("cg");			

			if (components==null)
				ComputeComponents();			
					
			//  components list contains collection of 
            // input graph Vertex for each SCC Vertex_ID 
            // (i.e Vector< Vector<Vertex> > )
			//	Key = SCC Vertex ID 
			sccVertexMap = BuildSCCVertexMap(components);
			
			//	Lsit of SCC vertices
			VertexCollection toCgVertices = new VertexCollection();
			IDictionaryEnumerator it = sccVertexMap.GetEnumerator();
			while( it.MoveNext() )	
				//	as scc_vertex_map is a sorted list, order of SCC IDs will match CG vertices
			{
				IVertex curr = cg.AddVertex();
				OnInitCondensationGraphVertex(new CondensationGraphVertexEventArgs(curr, (IVertexCollection)it.Value));
				toCgVertices.Add(curr);
			}
			
			for( int srcSccId=0; srcSccId<sccVertexMap.Keys.Count; srcSccId++ )	
            {   
				VertexCollection adj = new VertexCollection();
				foreach( IVertex u in (IVertexCollection)sccVertexMap[srcSccId] )	
                {					
					foreach(IEdge e in VisitedGraph.OutEdges(u))	{
						IVertex v = e.Target;        			
						int targetSccId = components[v];
						if (srcSccId != targetSccId)	
                        {
							// Avoid loops in the condensation graph
							IVertex sccV = toCgVertices[targetSccId];
							if( !adj.Contains(sccV) )		// Avoid parallel edges
								adj.Add(sccV);
						}
					}
				}
				IVertex s = toCgVertices[srcSccId];
				foreach( IVertex t in adj )
					cg.AddEdge(s, t);
			}
		}
コード例 #20
0
ファイル: Program.cs プロジェクト: anneilb/ce-dev
        //Generic SQL Update method for direct update using an UPDATE statement
        public int UpdateDirect(string strTable, string strWhere, SortedList slValues)
        {
            IDictionaryEnumerator objDEItem;
            SqlCommand cmd;
            int intResult = 0;
            string strSQL = "";
            string strKey = "";
            string strValues = "";
            string strFilter = "";

            if (CreateConnection())
            {
                cmd = m_conDB.CreateCommand();
                cmd.CommandType = System.Data.CommandType.Text;

                if (slValues.Count > 0)
                {
                    objDEItem = slValues.GetEnumerator();

                    //Loop through field values collection and update row
                    while (objDEItem.MoveNext())
                    {
                        //Determine key and use it to update corresponding column
                        strKey = objDEItem.Key.ToString();

                        if (strValues.Length > 0)
                        {
                            strValues = strValues + ", ";
                        }

                        strValues = strValues + strKey + "=" + FormatSQLValue(objDEItem.Value);
                    }

                    //strValues = "(" + strValues + ")";
                }

                //Build Where clause
                if (strWhere.Length > 0)
                {
                    strFilter = " WHERE " + strWhere;
                }

                //Compose the full SQL command
                strSQL = "UPDATE " + strTable + " SET " + strValues + strFilter;
                cmd.CommandText = strSQL;

                intResult = cmd.ExecuteNonQuery();

                CloseConnection();
            }

            return intResult;
        }
コード例 #21
0
ファイル: XmlTools.cs プロジェクト: appliedi/MerchantTribe
        public static bool WriteSingleUpsPackage(ref XmlTextWriter xw, ref Package p)
        {
            bool result = true;

            decimal dGirth = 0;

            decimal dLength = 0;
            decimal dHeight = 0;
            decimal dwidth = 0;

            SortedList sar = new SortedList(2);
            sar.Add(1, p.Length);
            sar.Add(2, p.Width);
            sar.Add(3, p.Height);

            IDictionaryEnumerator myEnumerator = sar.GetEnumerator();
            int place = 0;
            while (myEnumerator.MoveNext())
            {
                place += 1;
                switch (place)
                {
                    case 1:
                        dLength = Convert.ToDecimal(myEnumerator.Value);
                        break;
                    case 2:
                        dwidth = Convert.ToDecimal(myEnumerator.Value);
                        break;
                    case 3:
                        dHeight = Convert.ToDecimal(myEnumerator.Value);
                        break;
                }
            }
            myEnumerator = null;

            dGirth = dwidth + dwidth + dHeight + dHeight;


            //--------------------------------------------
            // Package
            xw.WriteStartElement("Package");

            xw.WriteStartElement("PackagingType");
            string packagingCode = Convert.ToInt32(p.Packaging).ToString();
            if (packagingCode.Length < 2)
            {
                packagingCode = "0" + packagingCode;
            }
            xw.WriteElementString("Code", packagingCode);
            if (p.Description != string.Empty)
            {
                xw.WriteElementString("Description", p.Description);
            }
            xw.WriteEndElement();

            if (p.Packaging == PackagingType.CustomerSupplied)
            {
                if (dLength > 0 | dHeight > 0 | dwidth > 0)
                {
                    xw.WriteStartElement("Dimensions");
                    xw.WriteStartElement("UnitOfMeasure");
                    switch (p.DimensionalUnits)
                    {
                        case UnitsType.Imperial:
                            xw.WriteElementString("Code", "IN");
                            break;
                        case UnitsType.Metric:
                            xw.WriteElementString("Code", "CM");
                            break;
                        default:
                            xw.WriteElementString("Code", "IN");
                            break;
                    }
                    xw.WriteEndElement();
                    xw.WriteElementString("Length", Math.Round(dLength, 0).ToString());
                    xw.WriteElementString("Width", Math.Round(dwidth, 0).ToString());
                    xw.WriteElementString("Height", Math.Round(dHeight, 0).ToString());
                    xw.WriteEndElement();
                }
            }

            // Weight
            if (p.Weight > 0)
            {
                xw.WriteStartElement("PackageWeight");
                xw.WriteStartElement("UnitOfMeasure");
                switch (p.WeightUnits)
                {
                    case UnitsType.Imperial:
                        xw.WriteElementString("Code", "LBS");
                        break;
                    case UnitsType.Metric:
                        xw.WriteElementString("Code", "KGS");
                        break;
                    default:
                        xw.WriteElementString("Code", "LBS");
                        break;
                }
                xw.WriteEndElement();
                xw.WriteElementString("Weight", Math.Round(p.Weight, 1).ToString());
                xw.WriteEndElement();
            }

            // Oversize Checks
            decimal oversizeCheck = dGirth + dLength;
            if (oversizeCheck > 84)
            {
                if (oversizeCheck < 108 & p.Weight < 30)
                {
                    xw.WriteElementString("OversizePackage", "1");
                }
                else
                {
                    if (p.Weight < 70)
                    {
                        xw.WriteElementString("OversizePackage", "2");
                    }
                    else
                    {
                        xw.WriteElementString("OversizePackage", "0");
                    }
                }
            }

            // ReferenceNumber
            if (p.ReferenceNumber != string.Empty)
            {
                xw.WriteStartElement("ReferenceNumber");
                string codeType = ConvertReferenceNumberCodeToString(p.ReferenceNumberType);
                xw.WriteElementString("Code", codeType);
                xw.WriteElementString("Value", XmlTools.TrimToLength(p.ReferenceNumber, 35));
                xw.WriteEndElement();
            }
            // ReferenceNumber2
            if (p.ReferenceNumber2 != string.Empty)
            {
                xw.WriteStartElement("ReferenceNumber");
                string codeType = ConvertReferenceNumberCodeToString(p.ReferenceNumber2Type);
                xw.WriteElementString("Code", codeType);
                xw.WriteElementString("Value", XmlTools.TrimToLength(p.ReferenceNumber2, 35));
                xw.WriteEndElement();
            }

            // Additional Handling
            if (p.AdditionalHandlingIsRequired == true)
            {
                xw.WriteElementString("AdditionalHandling", "");
            }

            //-------------------------------------------
            // Start Service Options
            xw.WriteStartElement("PackageServiceOptions");


            // Delivery Confirmation
            if (p.DeliveryConfirmation == true)
            {
                xw.WriteStartElement("DeliveryConfirmation");
                xw.WriteElementString("DCISType", Convert.ToInt32(p.DeliveryConfirmationType).ToString());
                if (p.DeliveryConfirmationControlNumber != string.Empty)
                {
                    xw.WriteElementString("DCISNumber", XmlTools.TrimToLength(p.DeliveryConfirmationControlNumber, 11));
                }
                xw.WriteEndElement();
            }

            // InsuredValue
            if (p.InsuredValue > 0)
            {
                xw.WriteStartElement("InsuredValue");
                xw.WriteElementString("MonetaryValue", p.InsuredValue.ToString());
                xw.WriteElementString("CurrencyCode", XmlTools.ConvertCurrencyCodeToString(p.InsuredValueCurrency));
                xw.WriteEndElement();
            }

            // COD
            if (p.COD == true)
            {
                xw.WriteStartElement("COD");
                xw.WriteElementString("CODCode", "3");
                xw.WriteElementString("CODFundsCode", Convert.ToInt32(p.CODPaymentType).ToString());
                xw.WriteStartElement("CODAmount");
                xw.WriteElementString("CurrencyCode", XmlTools.ConvertCurrencyCodeToString(p.CODCurrencyCode));
                xw.WriteElementString("MonetaryValue", p.CODAmount.ToString());
                xw.WriteEndElement();
                xw.WriteEndElement();
            }

            // Verbal Confirmation
            if (p.VerbalConfirmation == true)
            {
                xw.WriteStartElement("VerbalConfirmation");
                xw.WriteStartElement("ContactInfo");
                if (p.VerbalConfirmationName != string.Empty)
                {
                    xw.WriteElementString("Name", p.VerbalConfirmationName);
                }
                if (p.VerbalConfirmationPhoneNumber != string.Empty)
                {
                    xw.WriteElementString("PhoneNumber", p.VerbalConfirmationPhoneNumber);
                }
                xw.WriteEndElement();
                xw.WriteEndElement();
            }

            xw.WriteEndElement();
            // End Service Options
            //-------------------------------------------

            xw.WriteEndElement();
            // End Package
            //--------------------------------------------

            return result;
        }
        private void Build_DispatchMethods(CodeProcessor cs, Hashtable serviceNames)
        {
            SortedList SL = new SortedList();

            IDictionaryEnumerator en = serviceNames.GetEnumerator();
            UPnPService service;
            string name;

            while (en.MoveNext())
            {
                SL[en.Value] = en.Key;
            }

            en = SL.GetEnumerator();

            while (en.MoveNext())
            {
                int numArgs = 0;
                service = (UPnPService)en.Value;
                name = (string)en.Key;
                foreach (UPnPAction action in service.Actions)
                {
                    numArgs = 0;
                    foreach (UPnPArgument args in action.ArgumentList)
                    {
                        if (args.Direction == "in") { ++numArgs; }
                    }

                    // Define a macro version
                    if (numArgs == 0)
                    {
                        cs.Define("#define " + pc_methodPrefixDef + "Dispatch_" + name + "_" + action.Name + "(buffer,offset,bufferLength, session)\\");
                        cs.Append("{\\" + cl);
                        if (name != "DeviceSecurity")
                        {
                            if (Configuration.EXTERN_Callbacks == false)
                            {
                                cs.Append("	if (" + pc_methodPrefix + "FP_" + name + "_" + action.Name + " == NULL)\\" + cl);
                                cs.Append("		" + pc_methodPrefix + "Response_Error(session,501,\"No Function Handler\");\\" + cl);
                                cs.Append("	else\\" + cl);
                                cs.Append("		" + pc_methodPrefix + "FP_" + name + "_" + action.Name + "((void*)session);\\" + cl);
                            }
                            else
                            {
                                cs.Append("	" + pc_methodPrefix + name + "_" + action.Name + "((void*)session);\\" + cl);
                            }
                        }
                        else
                        {
                            cs.Append("	" + pc_methodLibPrefix + name + "_" + action.Name + "((void*)session);\\" + cl);
                        }
                        cs.Append("}" + cl);
                        cs.Append(cl);
                    }

                    if (numArgs > 0)
                    {
                        cs.Define("void " + pc_methodPrefixDef + "Dispatch_" + name + "_" + action.Name + "(char *buffer, int offset, int bufferLength, struct " + this.pc_methodLibPrefix + "WebServer_Session *ReaderObject)");
                        cs.Append("{" + cl);

                        bool varlong = false;
                        bool varlongtemp = false;
                        bool varulong = false;
                        bool varulongtemp = false;
                        bool varuuri = false;
                        bool varok = false;
                        foreach (UPnPArgument args in action.ArgumentList)
                        {
                            if (args.Direction == "in")
                            {
                                varok = true;
                                switch (args.RelatedStateVar.GetNetType().ToString())
                                {
                                    case "System.Uri":
                                        varuuri = true;
                                        break;
                                    case "System.Byte":
                                    case "System.UInt16":
                                    case "System.UInt32":
                                        varulong = true;
                                        if (args.RelatedStateVar.Maximum != null || args.RelatedStateVar.Minimum != null)
                                        {
                                            varulongtemp = true;
                                        }
                                        break;
                                    case "System.SByte":
                                    case "System.Int16":
                                    case "System.Int32":
                                        varlong = true;
                                        if (args.RelatedStateVar.Maximum != null || args.RelatedStateVar.Minimum != null)
                                        {
                                            varlongtemp = true;
                                        }
                                        break;
                                    case "System.Boolean":
                                    case "System.Char":
                                    case "System.Single":
                                    case "System.Double":
                                    case "System.Byte[]":
                                    case "System.String":
                                        break;
                                }
                            }
                        }

                        //cs.Append("	char *TempString;"+cl);
                        if (varlong == true)
                        {
                            cs.Append("	long TempLong;" + cl);
                            if (varlongtemp && Configuration.DynamicObjectModel)
                            {
                                cs.Append("	long TempLong2;" + cl);
                            }
                        }
                        if (varulong == true)
                        {
                            cs.Append("	unsigned long TempULong;" + cl);
                            if (varulongtemp && Configuration.DynamicObjectModel)
                            {
                                cs.Append("	unsigned long TempULong2;" + cl);
                            }
                        }
                        if (varuuri == true) cs.Append("	struct parser_result *TempParser;" + cl);
                        if (varok == true) cs.Append("	int OK = 0;" + cl);

                        //cs.Comment("Service Variables");

                        foreach (UPnPArgument args in action.ArgumentList)
                        {
                            if (args.Direction == "in")
                            {
                                cs.Append("	char *p_" + args.Name + " = NULL;" + cl);
                                cs.Append("	int p_" + args.Name + "Length = 0;" + cl);
                                if (args.RelatedStateVar.ComplexType == null)
                                {
                                    cs.Append("	" + ToCType(args.RelatedStateVar.GetNetType().FullName) + " _" + args.Name + " = " + ToEmptyValue(args.RelatedStateVar.GetNetType().FullName) + ";" + cl);
                                    if (ToCType(args.RelatedStateVar.GetNetType().FullName) == "char*" || ToCType(args.RelatedStateVar.GetNetType().FullName) == "unsigned char*")
                                    {
                                        cs.Append("	int _" + args.Name + "Length;" + cl);
                                    }
                                }
                                else
                                {
                                    cs.Append(" struct " + args.RelatedStateVar.ComplexType.Name_LOCAL + " *_" + args.Name + "=NULL;" + cl);
                                }
                            }
                        }

                        //
                        // Setup the XML Parsing
                        //
                        cs.Append("	struct " + this.pc_methodLibPrefix + "XMLNode *xnode = " + this.pc_methodLibPrefix + "ParseXML(buffer, offset, bufferLength);" + cl);
                        cs.Append("	struct " + this.pc_methodLibPrefix + "XMLNode *root = xnode;" + cl);
                        foreach (UPnPArgument args in action.ArgumentList)
                        {
                            if (args.Direction == "in" && args.RelatedStateVar.ComplexType != null)
                            {
                                cs.Append("	struct " + this.pc_methodLibPrefix + "XMLNode *tnode, *tnode_root;" + cl);
                                cs.Append("	char* tempText;" + cl);
                                cs.Append("	int tempTextLength;" + cl);
                                break;
                            }
                        }
                        cs.Append("	if (" + this.pc_methodLibPrefix + "ProcessXMLNodeList(root)!=0)" + cl);
                        cs.Append("	{" + cl);
                        cs.Comment("The XML is not well formed!");
                        cs.Append("	" + this.pc_methodLibPrefix + "DestructXMLNodeList(root);" + cl);
                        cs.Append("	" + this.pc_methodPrefix + "Response_Error(ReaderObject, 501, \"Invalid XML\");" + cl);
                        cs.Append("	return;" + cl);
                        cs.Append("	}" + cl);

                        cs.Append("	while(xnode != NULL)" + cl);
                        cs.Append("	{" + cl);
                        cs.Append("		if (xnode->StartTag != 0 && xnode->NameLength == 8 && memcmp(xnode->Name, \"Envelope\", 8)==0)" + cl);
                        cs.Append("		{" + cl);
                        cs.Append("			// Envelope" + cl);
                        cs.Append("			xnode = xnode->Next;" + cl);
                        cs.Append("			while(xnode != NULL)" + cl);
                        cs.Append("			{" + cl);
                        cs.Append("				if (xnode->StartTag!=0 && xnode->NameLength == 4 && memcmp(xnode->Name, \"Body\", 4) == 0)" + cl);
                        cs.Append("				{" + cl);
                        cs.Append("					// Body" + cl);
                        cs.Append("					xnode = xnode->Next;" + cl);
                        cs.Append("					while(xnode != NULL)" + cl);
                        cs.Append("					{" + cl);
                        cs.Append("						if (xnode->StartTag != 0 && xnode->NameLength == " + action.Name.Length.ToString() + " && memcmp(xnode->Name, \"" + action.Name + "\"," + action.Name.Length.ToString() + ") == 0)" + cl);
                        cs.Append("						{" + cl);
                        cs.Append("							// Inside the interesting part of the SOAP" + cl);
                        cs.Append("							xnode = xnode->Next;" + cl);
                        cs.Append("							while(xnode != NULL)" + cl);
                        cs.Append("							{" + cl);

                        int argflag = 1;
                        string eLsE = "";
                        foreach (UPnPArgument arg in action.ArgumentList)
                        {
                            if (arg.Direction == "in")
                            {
                                cs.Append("								" + eLsE + "if (xnode->NameLength == " + arg.Name.Length.ToString() + " && memcmp(xnode->Name, \"" + arg.Name + "\"," + arg.Name.Length.ToString() + ")==0)" + cl);
                                cs.Append("								{" + cl);
                                if (arg.RelatedStateVar.ComplexType == null)
                                {
                                    cs.Append("									p_" + arg.Name + "Length = " + this.pc_methodLibPrefix + "ReadInnerXML(xnode, &p_" + arg.Name + ");" + cl);
                                    if ((arg.RelatedStateVar.GetNetType().FullName == "System.String") || (arg.RelatedStateVar.GetNetType().FullName == "System.Uri"))
                                    {
                                        cs.Append("									p_" + arg.Name + "[p_" + arg.Name + "Length]=0;" + cl);
                                    }
                                }
                                else
                                {
                                    // Complex Type
                                    cs.Append("									tempTextLength = " + this.pc_methodLibPrefix + "ReadInnerXML(xnode, &tempText);" + cl);
                                    cs.Append("									tempText[tempTextLength] = 0;" + cl);
                                    cs.Append("									if (ReaderObject->Reserved9 == 0)" + cl);
                                    cs.Append("									{" + cl);
                                    cs.Append("										// Legacy" + cl);
                                    cs.Append("										tempTextLength = " + this.pc_methodLibPrefix + "InPlaceXmlUnEscape(tempText);" + cl);
                                    cs.Append("										tnode_root = tnode = " + this.pc_methodLibPrefix + "ParseXML(tempText,0,tempTextLength);" + cl);
                                    cs.Append("										" + this.pc_methodLibPrefix + "ProcessXMLNodeList(tnode_root);" + cl);
                                    cs.Append("										_" + arg.Name + " = " + this.pc_methodPrefix + "Parse_" + arg.RelatedStateVar.ComplexType.Name_LOCAL + "(tnode);" + cl);
                                    cs.Append("										" + this.pc_methodLibPrefix + "DestructXMLNodeList(tnode_root);" + cl);
                                    cs.Append("									}" + cl);
                                    cs.Append("									else" + cl);
                                    cs.Append("									{" + cl);
                                    cs.Append("										// UPnP/1.1 Enabled" + cl);
                                    cs.Append("										_" + arg.Name + " = " + this.pc_methodPrefix + "Parse_" + arg.RelatedStateVar.ComplexType.Name_LOCAL + "(xnode->Next);" + cl);
                                    cs.Append("									}" + cl);
                                }
                                cs.Append("										OK |= " + argflag + ";" + cl);
                                argflag = argflag << 1;
                                cs.Append("								}" + cl);
                                eLsE = "else ";
                            }
                        }

                        cs.Append("								if (xnode->Peer == NULL)" + cl);
                        cs.Append("								{" + cl);
                        cs.Append("									xnode = xnode->Parent;" + cl);
                        cs.Append("									break;" + cl);
                        cs.Append("								}" + cl);
                        cs.Append("								else" + cl);
                        cs.Append("								{" + cl);
                        cs.Append("									xnode = xnode->Peer;" + cl);
                        cs.Append("								}" + cl);

                        cs.Append("							}" + cl);
                        cs.Append("						}" + cl);
                        cs.Append("						if (xnode != NULL)" + cl);
                        cs.Append("						{" + cl);
                        cs.Append("							if (xnode->Peer == NULL)" + cl);
                        cs.Append("							{" + cl);
                        cs.Append("								xnode = xnode->Parent;" + cl);
                        cs.Append("								break;" + cl);
                        cs.Append("							}" + cl);
                        cs.Append("							else" + cl);
                        cs.Append("							{" + cl);
                        cs.Append("								xnode = xnode->Peer;" + cl);
                        cs.Append("							}" + cl);
                        cs.Append("						}" + cl);
                        cs.Append("					}" + cl);
                        cs.Append("				}" + cl);
                        cs.Append("				if (xnode != NULL)" + cl);
                        cs.Append("				{" + cl);
                        cs.Append("					if (xnode->Peer == NULL)" + cl);
                        cs.Append("					{" + cl);
                        cs.Append("						xnode = xnode->Parent;" + cl);
                        cs.Append("						break;" + cl);
                        cs.Append("					}" + cl);
                        cs.Append("					else" + cl);
                        cs.Append("					{" + cl);
                        cs.Append("						xnode = xnode->Peer;" + cl);
                        cs.Append("					}" + cl);
                        cs.Append("				}" + cl);
                        cs.Append("			}" + cl);
                        cs.Append("		}" + cl);
                        cs.Append("		if (xnode != NULL){xnode = xnode->Peer;}" + cl);
                        cs.Append("	}" + cl);
                        cs.Append("	" + this.pc_methodLibPrefix + "DestructXMLNodeList(root);" + cl);

                        cs.Append("	if (OK != " + (argflag - 1) + ")" + cl);
                        cs.Append("	{" + cl);
                        if (Configuration.ExplicitErrorEncoding == true)
                        {
                            cs.Append("		" + pc_methodPrefix + "Response_Error(ReaderObject, 402, \"Incorrect Arguments\");" + cl);
                        }
                        else
                        {
                            cs.Append("		" + pc_methodPrefix + "Response_Error(ReaderObject, 402, \"Illegal value\");" + cl);
                        }
                        cs.Append("		return;" + cl);
                        cs.Append("	}" + cl);
                        cs.Append(cl);

                        cs.Comment("Type Checking");

                        foreach (UPnPArgument args in action.ArgumentList)
                        {
                            if (args.Direction == "in")
                            {
                                switch (args.RelatedStateVar.GetNetType().FullName)
                                {
                                    case "System.Boolean":
                                        TypeCheckBoolean(cs, args);
                                        break;
                                    case "System.Int16":
                                    case "System.Int32":
                                    case "System.UInt16":
                                    case "System.UInt32":
                                    case "System.Byte":
                                    case "System.SByte":
                                        TypeCheckIntegral(cs, args);
                                        break;
                                    case "System.Uri":
                                        TypeCheckURI(cs, args);
                                        break;
                                    case "System.DateTime":
                                        TypeCheckDateTime(cs, args);
                                        break;
                                    case "System.Byte[]":
                                        cs.Append("	_" + args.Name + "Length = " + this.pc_methodLibPrefix + "Base64Decode(p_" + args.Name + ",p_" + args.Name + "Length,&_" + args.Name + ");" + cl);
                                        break;
                                    case "System.String":
                                    default:
                                        if (args.RelatedStateVar.ComplexType == null)
                                        {
                                            TypeCheckString(cs, args);
                                        }
                                        break;
                                }
                            }
                        }

                        string FPtrType = "(void (__cdecl *)(void *";
                        foreach (UPnPArgument arg in action.Arguments)
                        {
                            if (arg.Direction == "in")
                            {
                                FPtrType += ("," + ToCType(arg.RelatedStateVar.GetNetType().ToString()));
                            }
                        }
                        FPtrType += "))";

                        if (name != "DeviceSecurity")
                        {
                            if (Configuration.EXTERN_Callbacks == false)
                            {
                                cs.Append("	if (" + pc_methodPrefix + "FP_" + name + "_" + action.Name + " == NULL)" + cl);
                                cs.Append("		" + pc_methodPrefix + "Response_Error(ReaderObject,501,\"No Function Handler\");" + cl);
                                cs.Append("	else" + cl);
                                cs.Append("		" + pc_methodPrefix + "FP_" + name + "_" + action.Name + "((void*)ReaderObject");
                            }
                            else
                            {
                                cs.Append("	" + pc_methodPrefix + name + "_" + action.Name + "((void*)ReaderObject");
                            }
                        }
                        else
                        {
                            cs.Append("	" + pc_methodLibPrefix + name + "_" + action.Name + "((void*)ReaderObject");
                        }
                        foreach (UPnPArgument args in action.ArgumentList)
                        {
                            if (args.Direction == "in")
                            {
                                cs.Append(",_" + args.Name);
                                if (args.RelatedStateVar.GetNetType().FullName == "System.Byte[]")
                                {
                                    cs.Append(",_" + args.Name + "Length");
                                }
                            }
                        }

                        cs.Append(");" + cl);

                        foreach (UPnPArgument args in action.ArgumentList)
                        {
                            if (args.Direction == "in")
                            {
                                if (args.RelatedStateVar.GetNetType().FullName == "System.Byte[]")
                                {
                                    cs.Append("free(_" + args.Name + ");" + cl);
                                }
                            }
                        }

                        cs.Append("}" + cl);
                        cs.Append(cl);
                    }
                }
            }
        }
 public static void BuildComplexTypeParser_Header(CodeProcessor cs, SortedList SortedServiceList, string pc_methodPrefix, string pc_methodLibPrefix)
 {
     cs.Append(cl);
     cs.Comment("Complex Type Parsers");
     IDictionaryEnumerator en = SortedServiceList.GetEnumerator();
     while (en.MoveNext())
     {
         UPnPService service = (UPnPService)en.Value;
         foreach (UPnPComplexType CT in service.GetComplexTypeList())
         {
             cs.Append("struct " + CT.Name_LOCAL + "* " + pc_methodPrefix + "Parse_" + CT.Name_LOCAL + "(struct " + pc_methodLibPrefix + "XMLNode *node);" + cl);
         }
     }
     cs.Append(cl);
 }
        private void Build_TypeCheckString(CodeProcessor cs, Hashtable serviceNames)
        {
            SortedList SL = new SortedList();
            IDictionaryEnumerator en = serviceNames.GetEnumerator();

            while (en.MoveNext())
            {
                SL[en.Value] = en.Key;
            }
            en = SL.GetEnumerator();

            cs.Define("int " + pc_methodPrefixDef + "TypeCheckString(char* inVar, int inVarLength, char* ServiceName, char* StateVariable, char** outVar, int* outVarLength, char* varName, struct HTTPReaderObject *ReaderObject)");
            cs.Append("{" + cl);
            cs.Append("	int OK = 0;" + cl);
            cs.Append("	char* msg;" + cl);
            while (en.MoveNext())
            {
                UPnPService S = (UPnPService)en.Value;
                string key = (string)en.Key;

                bool Needed = false;
                foreach (UPnPStateVariable V in S.GetStateVariables())
                {
                    if (V.AllowedStringValues != null)
                    {
                        Needed = true;
                        break;
                    }
                }

                if (Needed)
                {
                    cs.Append("	if (strncmp(ServiceName,\"" + key + "\"," + key.Length.ToString() + ") == 0)" + cl);
                    cs.Append("	{" + cl);
                    foreach (UPnPStateVariable V in S.GetStateVariables())
                    {
                        if (V.AllowedStringValues != null)
                        {
                            cs.Append("		if (strncmp(StateVariable,\"" + V.Name + "\"," + V.Name.Length.ToString() + ") == 0)" + cl);
                            cs.Append("		{" + cl);
                            cs.Append("			OK = -1;" + cl);
                            bool first = true;
                            foreach (string AllowedString in V.AllowedStringValues)
                            {
                                if (first == false) cs.Append("else ");
                                first = false;
                                cs.Append("			if (inVarLengt h== " + AllowedString.Length.ToString() + ")" + cl);
                                cs.Append("			{" + cl);
                                cs.Append("				if (memcmp(inVar,\"" + AllowedString + "\"," + AllowedString.Length.ToString() + ") == 0) {OK = 0;}" + cl);
                                cs.Append("			}" + cl);
                            }
                            cs.Append("			if (OK != 0)" + cl);
                            cs.Append("			{" + cl);
                            if (Configuration.ExplicitErrorEncoding == true)
                            {
                                cs.Append("				if ((msg = (char*)malloc(65)) == NULL) ILIBCRITICALEXIT(254);" + cl);
                                cs.Append("				snprintf(msg, 65, \"Argument[%s] contains a value that is not in AllowedValueList\", varName);" + cl);
                                cs.Append("				" + pc_methodPrefix + "Response_Error(ReaderObject, 402, msg);" + cl);
                                cs.Append("				free(msg);" + cl);
                            }
                            else
                            {
                                cs.Append("				" + pc_methodPrefix + "Response_Error(ReaderObject, 402, \"Illegal value\");" + cl);
                            }
                            cs.Append("				return -1;" + cl);
                            cs.Append("			}" + cl);
                            cs.Append("			*outVar = inVar;" + cl);
                            cs.Append("			*outVarLength = inVarLength;" + cl);
                            cs.Append("			return(0);" + cl);
                            cs.Append("		}" + cl);
                        }
                    }
                    cs.Append("	}" + cl);
                }
            }
            cs.Append("}" + cl);
        }
コード例 #25
0
ファイル: PhysicalXML.cs プロジェクト: ogirard/lyra2
        // throws NotValidException, XmlException
        public string CommitTranslations(SortedList trans)
        {
            string list = "";
            XmlNode translations = this.doc.GetElementsByTagName("Translations")[0];

            Translation curTrans;
            XmlNode transNode;
            XmlNode newTrans, title, text;
            XmlAttribute lang, id, uf;

            // Delete
            int j = 0;
            int top = trans.Count;
            for (int i = 0; i < top; i++)
            {
                curTrans = (Translation)trans.GetByIndex(j);
                if (curTrans.Deleted)
                {
                    trans.Remove(curTrans.ID);
                    j--;
                    if ((transNode = this.doc.GetElementById(curTrans.ID)) != null)
                    {
                        translations.RemoveChild(transNode);
                    }
                }
                j++;
            }

            IDictionaryEnumerator en = trans.GetEnumerator();
            en.Reset();
            while (en.MoveNext())
            {
                curTrans = (Translation)en.Value;
                list += curTrans.ID + ",";
                if (curTrans.ToUpdate)
                {
                    if ((transNode = this.doc.GetElementById(curTrans.ID)) != null)
                    {
                        XmlNodeList transChildren = transNode.ChildNodes;
                        if ((transChildren[0].Name == "Title") &&
                            (transChildren[1].Name == "Text"))
                        {
                            transChildren[0].InnerText = curTrans.Title;
                            transChildren[1].InnerText = curTrans.Text;
                            transNode.Attributes["lang"].Value = Util.getLanguageString(curTrans.Language, true);
                            transNode.Attributes["id"].Value = curTrans.ID;
                            transNode.Attributes["unform"].Value = curTrans.Unformatted ? "yes" : "no";
                        }
                        else
                        {
                            throw new NotValidException();
                        }
                    }
                    // doesn't exist, create new Node
                    else
                    {
                        newTrans = this.doc.CreateNode(XmlNodeType.Element, "Translation", this.doc.NamespaceURI);

                        title = this.doc.CreateNode(XmlNodeType.Element, "Title", this.doc.NamespaceURI);
                        text = this.doc.CreateNode(XmlNodeType.Element, "Text", this.doc.NamespaceURI);
                        lang = this.doc.CreateAttribute("lang", this.doc.NamespaceURI);
                        id = this.doc.CreateAttribute("id", this.doc.NamespaceURI);
                        uf = this.doc.CreateAttribute("unform", this.doc.NamespaceURI);

                        lang.Value = Util.getLanguageString(curTrans.Language, true);
                        id.Value = curTrans.ID;
                        uf.Value = curTrans.Unformatted ? "yes" : "no";
                        title.InnerText = curTrans.Title;
                        text.InnerText = curTrans.Text;

                        newTrans.Attributes.Append(lang);
                        newTrans.Attributes.Append(id);
                        newTrans.Attributes.Append(uf);
                        newTrans.AppendChild(title);
                        newTrans.AppendChild(text);

                        translations.AppendChild(newTrans);
                    }
                }
            }
            int len = list.Length - 1 < 0 ? 0 : list.Length - 1;
            return list.Substring(0, len);
        }
コード例 #26
0
ファイル: PhysicalXML.cs プロジェクト: ogirard/lyra2
        /// <summary>
        /// Commit current workspace
        /// </summary>
        /// <param name="internList">SortedList of current songs. From Storage.</param>
        /// <returns>successful?</returns>
        public bool Commit(SortedList internList)
        {
            try
            {
                XmlNode curNode, newNode, nr, title, text;
                XmlAttribute transattr, idattr, descattr;

                XmlNode songs = this.doc.GetElementsByTagName("Songs")[0];

                // remove all, if songs have been replaced!
                if (Util.DELALL)
                {
                    XmlNode translations = this.doc.GetElementsByTagName("Translations")[0];
                    songs.RemoveAll();
                    translations.RemoveAll();
                }

                Song curSong;

                // Delete
                int j = 0;
                int top = internList.Count;
                for (int i = 0; i < top; i++)
                {
                    curSong = (Song)internList.GetByIndex(j);
                    if (curSong.Deleted)
                    {
                        j--;
                        internList.Remove(curSong.ID);
                        if ((curNode = this.doc.GetElementById(curSong.ID)) != null)
                        {
                            songs.RemoveChild(curNode);
                            curSong.UpdateTranslations(this);
                        }
                    }
                    j++;
                }

                IDictionaryEnumerator en = internList.GetEnumerator();
                en.Reset();

                // iterate through current SongList and update/store each song!
                while (en.MoveNext())
                {
                    curSong = (Song)en.Value;
                    if (curSong.ToUpdate)
                    {
                        // id exists
                        if ((curNode = this.doc.GetElementById(curSong.ID)) != null)
                        {
                            // update node
                            XmlNodeList children = curNode.ChildNodes;
                            if ((children[0].Name == "Number") &&
                                (children[1].Name == "Title") &&
                                (children[2].Name == "Text"))
                            {
                                children[0].InnerText = curSong.Number.ToString();
                                children[1].InnerText = curSong.Title;
                                children[2].InnerText = curSong.Text;
                            }
                            else
                            {
                                throw new NotValidException();
                            }

                            if (curNode.Attributes["style"] == null)
                            {
                                XmlAttribute styleAttr = this.doc.CreateAttribute("style");
                                curNode.Attributes.Append(styleAttr);
                            }
                            curNode.Attributes["style"].InnerText = curSong.UseDefaultStyle ? "" : curSong.Style.ID.ToString().Trim('{', '}');
                        }
                        // id doesn't exist
                        else
                        {
                            // create node
                            newNode = this.doc.CreateNode(XmlNodeType.Element, "Song", this.doc.NamespaceURI);

                            nr = this.doc.CreateNode(XmlNodeType.Element, "Number", this.doc.NamespaceURI);
                            title = this.doc.CreateNode(XmlNodeType.Element, "Title", this.doc.NamespaceURI);
                            text = this.doc.CreateNode(XmlNodeType.Element, "Text", this.doc.NamespaceURI);

                            nr.InnerText = curSong.Number.ToString();
                            title.InnerText = curSong.Title;
                            text.InnerText = curSong.Text;

                            transattr = this.doc.CreateAttribute("trans", this.doc.NamespaceURI);
                            transattr.Value = "";

                            idattr = this.doc.CreateAttribute("id", this.doc.NamespaceURI);
                            idattr.Value = "";
                            descattr = this.doc.CreateAttribute("zus", this.doc.NamespaceURI);
                            descattr.Value = "";

                            newNode.Attributes.Append(this.doc.CreateAttribute("id"));
                            newNode.Attributes["id"].InnerText = curSong.Style.ID.ToString().Trim('{', '}');

                            newNode.AppendChild(nr);
                            newNode.AppendChild(title);
                            newNode.AppendChild(text);

                            newNode.Attributes.Append(idattr);
                            newNode.Attributes.Append(transattr);
                            newNode.Attributes.Append(descattr);
                            curNode = songs.AppendChild(newNode);
                        }

                        // translations
                        string transList = curSong.UpdateTranslations(this);
                        curNode.Attributes["trans"].Value = transList;
                        curNode.Attributes["id"].Value = curSong.ID;
                        curNode.Attributes["zus"].Value = curSong.Desc;
                    }
                }
                this.doc.Save(Util.BASEURL + "\\" + Util.URL);
                return true;
            }
            // on any error: return false => not commited!
            catch (Exception e)
            {
                Util.MBoxError(e.Message, e);
                return false;
            }
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: anneilb/ce-dev
        //Generic SQL Insert method for direct insertion using an INSERT statement
        public int InsertDirect(string strTable, SortedList slValues)
        {
            IDictionaryEnumerator objDEItem;
            SqlCommand cmd;
            int intResult = 0;
            string strSQL = "";
            string strKey = "";
            string strFields = "";
            string strValues = "";

            if (CreateConnection())
            {
                cmd = m_conDB.CreateCommand();
                cmd.CommandType = System.Data.CommandType.Text;

                if (slValues.Count > 0)
                {
                    objDEItem = slValues.GetEnumerator();

                    //Loop through field values collection and insert row
                    while (objDEItem.MoveNext())
                    {
                        //Determine key and use it to insert data into corresponding column
                        strKey = objDEItem.Key.ToString();

                        if (strFields.Length > 0)
                        {
                            strFields = strFields + ", ";
                        }
                        //build up the field names to insert
                        strFields = strFields + strKey;

                        if (strValues.Length > 0)
                        {
                            strValues = strValues + ", ";
                        }
                        //build up the values to insert
                        strValues = strValues + FormatSQLValue(objDEItem.Value);
                    }

                    strFields = "(" + strFields + ")";
                    strValues = "(" + strValues + ")";
                }

                //Compose the full SQL command
                strSQL = "INSERT INTO " + strTable + " " + strFields + " VALUES " + strValues;
                cmd.CommandText = strSQL;

                intResult = cmd.ExecuteNonQuery();

                CloseConnection();
            }

            return intResult;
        }
        private void BuildMain_SetFunctionPointers(CodeProcessor cs, UPnPDevice device, Hashtable serviceNames)
        {
            string cppobj = "";
            if (this.Language == LANGUAGES.CPP) { cppobj = "microstack->"; }

            SortedList SL = new SortedList();
            IDictionaryEnumerator en = serviceNames.GetEnumerator();

            while (en.MoveNext())
            {
                SL[en.Value] = en.Key;
            }
            en = SL.GetEnumerator();

            while (en.MoveNext())
            {
                UPnPService S = (UPnPService)en.Value;
                string name = (string)en.Key;

                if (name != "DeviceSecurity")
                {
                    foreach (UPnPAction A in S.Actions)
                    {
                        cs.Append("    " + cppobj + pc_methodPrefix + "FP_" + name + "_" + A.Name + " = (UPnP_ActionHandler_" + name + "_" + A.Name + ")&" + pc_methodPrefix + name + "_" + A.Name + ";" + cl);
                    }
                }
            }
            cs.Append(cl);
        }
コード例 #29
0
ファイル: GetEnumeratorTests.cs プロジェクト: johnhhm/corefx
        public void TestGetEnumeratorBasic()
        {
            StringBuilder sblMsg = new StringBuilder(99);
            //

            SortedList sl2 = null;

            IDictionaryEnumerator dicen = null;

            StringBuilder sbl3 = new StringBuilder(99);
            StringBuilder sbl4 = new StringBuilder(99);
            StringBuilder sblWork1 = new StringBuilder(99);

            int i3 = 0;
            int i2 = 0;

            int i = 0;
            int j = 0;

            //
            // 	Constructor: Create SortedList using this as IComparer and default settings.
            //
            sl2 = new SortedList(this);

            //  Verify that the SortedList is not null.
            Assert.NotNull(sl2);

            //  Verify that the SortedList is empty.
            Assert.Equal(0, sl2.Count);

            //   Testcase: Set - null key, ArgExc expected
            Assert.Throws<ArgumentNullException>(() =>
                {
                    sl2[null] = 0;
                });

            Assert.Equal(0, sl2.Count);

            //   Testcase: Set - null val
            sl2[(object)100] = (object)null;
            Assert.Equal(1, sl2.Count);

            //   Testcase: vanila Set
            sl2[(object)100] = 1;
            Assert.Equal(1, sl2.Count);

            sl2.Clear();
            Assert.Equal(0, sl2.Count);

            //   Testcase: add key-val pairs
            for (i = 0; i < 100; i++)
            {
                sl2.Add(i + 100, i);
            }

            Assert.Equal(100, sl2.Count);

            for (i = 0; i < 100; i++)
            {
                j = i + 100;

                Assert.True(sl2.ContainsKey((int)j));
                Assert.True(sl2.ContainsValue(i));

                object o2 = sl2[(object)(j)]; //need to cast: Get (object key)
                Assert.NotNull(o2);
                i2 = (int)o2;

                i3 = (int)sl2.GetByIndex(i); //Get (index i)
                Assert.False((i3 != i) || (i2 != i));

                //  testcase: GetEnumerator
                dicen = (IDictionaryEnumerator)sl2.GetEnumerator();

                //  Boundary for Current
                Assert.Throws<InvalidOperationException>(() =>
                                 {
                                     object throwaway = dicen.Current;
                                 }
                );

                j = 0;
                //  go over the enumarator
                while (dicen.MoveNext())
                {
                    //  Current to see the order
                    i3 = (int)dicen.Value;
                    Assert.True(j.Equals(i3));

                    //  Current again to see the same order
                    i3 = (int)dicen.Value;
                    Assert.Equal(i3, j);

                    j++;
                }

                //  Boundary for Current
                Assert.Throws<InvalidOperationException>(() =>
                                 {
                                     object throwaway = dicen.Current;
                                 }
                );
                //  Boundary for MoveNext: call MoveNext to make sure it returns false
                Assert.False((dicen.MoveNext()) || (j != 100));

                //  call again MoveNext to make sure it still returns false
                Assert.False(dicen.MoveNext());
            }
        }
コード例 #30
0
ファイル: SortedList.cs プロジェクト: yonder/mono
 public override IDictionaryEnumerator GetEnumerator()
 {
     lock (host.SyncRoot) {
         return(host.GetEnumerator());
     }
 }
コード例 #31
0
ファイル: CallTreeForm.cs プロジェクト: engincancan/utilities
        /* show the stack and/or some other info */
        private void ShowCurrentStack(object obj, EventArgs args)
        {
            if(callTreeView == null)
            {
                SetcallTreeView();
            }
            TreeNode node = (TreeNode)callTreeView.SelectedItem;
            if(node == null)
            {
                return;
            }

            int stackid = node.stackid;
            if(stackid < 0)
            {
                return;
            }

            stackView.ListViewItemSorter = null;
            stackView.Items.Clear();

            int[] stacktrace = IndexToStacktrace(stackid);

            /* show stack trace */
            subtreeline = -1;
            for(int i = (node.nodetype == TreeNode.NodeType.Allocation ? 2 : 0); i < stacktrace.Length; i++)
            {
                int functionId = stacktrace[i];
                GlobalCallStats s = globalCallStats[functionId];

                string[] subitems = new string[]
                {
                    names[functionId],
                    s.timesCalled.ToString(),
                    s.totalBytesAllocated.ToString(),
                    s.totalFunctionsCalled.ToString(),
                    s.totalNewFunctionsBroughtIn.ToString()
                };
                stackView.Items.Add(new ListViewItem(subitems));
            }

            /* build and show child subtree */
            if (node.nodetype == TreeNode.NodeType.Call && fShowSubtree)
            {
                SortedList fns = new SortedList();
                GetChildren( node, fns );

                if (fns.Count > 0 )
                {
                    //  Add a separator
                    string functionName;

                    if (stacktrace == null || stacktrace.Length == 0)
                    {
                        functionName = "All";
                    }
                    else
                    {
                        functionName = names[stacktrace[stacktrace.Length - 1]];
                    }

                    subtreeline = stackView.Items.Count;
                    stackView.Items.Add( "<-------- Subtree of " + functionName + " --------> " );
                }

                IDictionaryEnumerator enumFns = fns.GetEnumerator();

                while(enumFns.MoveNext())
                {
                    GlobalCallStats s = (GlobalCallStats)enumFns.Value;
                    int fid = (int)enumFns.Key;
                    string[] subitems = new string[]
                    {
                        fid > 0 ? names[fid] : types[-fid],
                        s.timesCalled.ToString(),
                        s.totalBytesAllocated.ToString(),
                        s.totalFunctionsCalled.ToString(),
                        s.totalNewFunctionsBroughtIn.ToString()
                    };

                    ListViewItem item = new ListViewItem(subitems);
                    if (fid < 0)
                    {
                        //  Allocation item
                        item.ForeColor = Color.Green;
                    }

                    stackView.Items.Add(item);
                }
            }

            /* and optionally some global info about the allocated object */
            if(node.nodetype == TreeNode.NodeType.Allocation)
            {
                int typeId = stacktrace[0];
                GlobalAllocStats s = globalAllocStats[typeId];
                string[] subitems = new string[]
                {
                    types[typeId],  // "Name"
                    s.timesAllocated.ToString(),
                    s.totalBytesAllocated.ToString()
                };
                ListViewItem item = new ListViewItem(subitems);
                item.ForeColor = Color.Green;
                stackView.Items.Add(item);
            }

            /* [re]set the columns if necessary */
            if(stackView.Columns.Count != 5 && node.nodetype != TreeNode.NodeType.Allocation)
            {
                stackView.Columns.Clear();
                stackView.Columns.Add("Name", 150, HorizontalAlignment.Left);
                stackView.Columns.Add("Times Called", 60, HorizontalAlignment.Left);
                stackView.Columns.Add("Bytes Allocated", 60, HorizontalAlignment.Left);
                stackView.Columns.Add("Functions Called", 60, HorizontalAlignment.Left);
                stackView.Columns.Add("New Functions", 60, HorizontalAlignment.Left);
            }
            if(stackView.Columns.Count != 4 && node.nodetype == TreeNode.NodeType.Allocation)
            {
                stackView.Columns.Clear();
                stackView.Columns.Add("Name", 150, HorizontalAlignment.Left);
                stackView.Columns.Add("Times Called/Allocated", 100, HorizontalAlignment.Left);
                stackView.Columns.Add("Bytes", 60, HorizontalAlignment.Left);
            }
        }
コード例 #32
0
ファイル: KMPManager.cs プロジェクト: Jumba/KerbalMultiPlayer
        private void writeSecondaryUpdates()
        {
            if (inactiveVesselsPerUpdate > 0)
            {
                //Write the inactive vessels nearest the active vessel
                SortedList<float, Vessel> nearest_vessels = new SortedList<float, Vessel>();

                foreach (Vessel vessel in FlightGlobals.Vessels)
                {
                    if (vessel != FlightGlobals.ActiveVessel && vessel.loaded && !vessel.name.Contains(" [Past]") && !vessel.name.Contains(" [Future]"))
                    {
                        float distance = (float)Vector3d.Distance(vessel.GetWorldPos3D(), FlightGlobals.ship_position);
                        if (distance < INACTIVE_VESSEL_RANGE)
                        {
                            try
                            {
                                Part root = vessel.rootPart;
                                bool include = true;
                                if (serverVessels_InUse.ContainsKey(vessel.id) ? !serverVessels_InUse[vessel.id]: false)
                                {
                                    foreach (Guid vesselID in serverVessels_Parts.Keys)
                                    {
                                        if (serverVessels_Parts[vesselID].Contains(root))
                                        {
                                            include=false;
                                            break;
                                        }
                                    }
                                }
                                if (include) nearest_vessels.Add(distance, vessel);
                            }
                            catch (ArgumentException)
                            {
                            }
                        }
                    }
                }

                int num_written_vessels = 0;

                //Write inactive vessels to file in order of distance from active vessel
                IEnumerator<KeyValuePair<float, Vessel>> enumerator = nearest_vessels.GetEnumerator();
                while (num_written_vessels < inactiveVesselsPerUpdate
                    && num_written_vessels < MAX_INACTIVE_VESSELS_PER_UPDATE && enumerator.MoveNext())
                {
                    bool newVessel = !serverVessels_RemoteID.ContainsKey(enumerator.Current.Value.id);
                    KMPVesselUpdate update = getVesselUpdate(enumerator.Current.Value);
                    if (update != null)
                    {
                        if (! //Don't keep sending a secondary vessel that will stay destroyed for any other client:
                           ((update.situation == Situation.DESCENDING || update.situation == Situation.FLYING) //If other vessel is flying/descending
                            && enumerator.Current.Value.mainBody.atmosphere //and is near a body with atmo
                            && enumerator.Current.Value.altitude < enumerator.Current.Value.mainBody.maxAtmosphereAltitude //and is in atmo
                            && !newVessel)) //and isn't news to the server, then it shouldn't be sent
                        {
                            update.distance = enumerator.Current.Key;
                            update.state = State.INACTIVE;
                            if (enumerator.Current.Value.loaded && (serverVessels_InUse.ContainsKey(enumerator.Current.Value.id) ? serverVessels_InUse[enumerator.Current.Value.id] : false) && FlightGlobals.ActiveVessel.altitude > 10000d)
                            {
                                //Rendezvous relative position data
                                KMPClientMain.DebugLog ("sending docking-mode update, distance: " + enumerator.Current.Key);
                                update.relativeTo = FlightGlobals.ActiveVessel.id;
                                Vector3d w_pos = Vector3d.zero;
                                try
                                {
                                    w_pos = enumerator.Current.Value.findWorldCenterOfMass() - FlightGlobals.ActiveVessel.findWorldCenterOfMass();
                                } catch {
                                    KMPClientMain.DebugLog("couldn't get CoM!");
                                    w_pos = enumerator.Current.Value.GetWorldPos3D() - FlightGlobals.ship_position;
                                }
                                Vector3d o_vel = enumerator.Current.Value.GetObtVelocity() - FlightGlobals.ActiveVessel.GetObtVelocity();
                                update.clearProtoVessel();
                                for (int i = 0; i < 3; i++)
                                {
                                    update.w_pos[i] = w_pos[i];
                                    update.o_vel[i] = o_vel[i];
                                }
                            }
                            byte[] update_bytes = KSP.IO.IOUtils.SerializeToBinary(update);
                            KMPClientMain.DebugLog ("sending secondary update for: " + enumerator.Current.Value.id);
                            if (newVessel)
                                enqueuePluginInteropMessage(KMPCommon.PluginInteropMessageID.PRIMARY_PLUGIN_UPDATE, update_bytes);
                            else
                                enqueuePluginInteropMessage(KMPCommon.PluginInteropMessageID.SECONDARY_PLUGIN_UPDATE, update_bytes);
                            num_written_vessels++;
                        }
                    }
                }
            }
        }
コード例 #33
0
ファイル: Program.cs プロジェクト: anneilb/ce-dev
        //Generic SQL Update method
        public int Update(string strTable, string strWhere, SortedList slValues)
        {
            SqlDataAdapter da;
            SqlCommandBuilder cb;
            DataSet ds;
            DataRow[] aDr = null;
            IDictionaryEnumerator objDEItem;
            string strSQL = "";
            string strKey = "";
            int intResult = 0;

            if (CreateConnection())
            {
                strSQL = "SELECT * FROM " + strTable;
                da = new SqlDataAdapter();

                //Get the dataset using the Select query that has been composed
                ds = GetDataSet(strTable, strSQL, ref da);

                //use the command builder to generate the Update command that we'll need later
                cb = new SqlCommandBuilder(da);
                da.UpdateCommand = cb.GetUpdateCommand();

                //Get the records to Update using where clause
                if (strWhere.Length > 0)
                {
                    aDr = ds.Tables[strTable].Select(strWhere);
                }
                else
                {
                    aDr = ds.Tables[strTable].Select();
                }

                if (aDr != null)
                {
                    //Loop through each row
                    foreach (DataRow dr in aDr)
                    {
                        objDEItem = slValues.GetEnumerator();

                        //Loop through field values collection and update row
                        while (objDEItem.MoveNext())
                        {
                            //Determine key and use it to update corresponding column in datarow
                            //strKey = slValues.GetKey(slValues.IndexOfValue(o)).ToString();
                            strKey = objDEItem.Key.ToString();
                            dr[strKey] = objDEItem.Value;
                        }
                    }
                }

                //Update table and determine number of rows affected
                intResult = da.Update(ds, strTable);

                CloseConnection();
            }

            return intResult;
        }