Remove() public method

public Remove ( Object key ) : void
key Object
return void
        //---------------------------------------------------------------------
        public bool Close(string SocketID_in)
        {
            SocketHandler Connection = default(SocketHandler);

            Connection = (SocketHandler)this.Sockets[SocketID_in];
            if ((Connection == null))
            {
                return(false);
            }
            try
            {
                if ((Connection.Socket != null))
                {
                    if (Connection.Socket.Connected)
                    {
                        //TraceText("T", "SocketManager::Close", "Closing [" & Connection.Socket.RemoteEndPoint.ToString() & "].")
                        Connection.Socket.Shutdown(System.Net.Sockets.SocketShutdown.Both);
                    }
                }
            }
            catch (Exception ex)
            {
                //TraceText("E", "SocketManager::Close", ex.ToString())
                Sockets.Remove(Connection.SocketID);
                return(false);
            }
            Sockets.Remove(Connection.SocketID);
            return(true);
        }
 static public int Remove(IntPtr l)
 {
     try {
         System.Collections.SortedList self = (System.Collections.SortedList)checkSelf(l);
         System.Object a1;
         checkType(l, 2, out a1);
         self.Remove(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemplo n.º 3
0
        private void deleteLevelSide(
            MamdaOrderBookPriceLevel level,
            TreeMap bookSide)
        {
            MamaPrice price = level.getPrice();

            if (bookSide.ContainsKey(price))
            {
                /* We actually need to process this properly because the
                 * update may not contain all entries, just updated
                 * ones. */
                bookSide.Remove(price);
            }
        }
Exemplo n.º 4
0
        public void TestGetIsReadOnlyBasic()
        {
            String strValue;
            SortedList dic1;

            dic1 = new SortedList();
            for (int i = 0; i < 10; i++)
            {
                strValue = "String_" + i;
                dic1.Add(i, strValue);
            }

            for (int i = 0; i < 10; i++)
            {
                Assert.True(dic1.Contains(i));
            }

            //we'll do the ReadOnly test
            Assert.False(dic1.IsReadOnly);

            //we'll make sure by doing a modifiable things!!
            dic1.Remove(0);
            Assert.False(dic1.Contains(0));
        }
Exemplo n.º 5
0
        /// <summary>
        /// add songs to SortedList (Song as value,song-number as key)
        /// </summary>
        /// <returns>SortedList containing all songs, null on error</returns>
        public SortedList GetSongs(SortedList songs, string url, bool imp)
        {
            long start = Util.getCurrentTicks();
            try
            {
                this.doc.Load(url);
                this.InitStyles(url);
                XmlNodeList nodes = this.doc.GetElementsByTagName("Song");
                for (int i = 0; i < nodes.Count; i++)
                {
                    XmlNode songNode = nodes[i];

                    int nr;
                    string title;
                    string text;

                    string id = songNode.Attributes["id"].Value;
                    string desc = songNode.Attributes["zus"].Value;
                    string translations = songNode.Attributes["trans"].Value;

                    if (songNode["Number"] != null &&
                        songNode["Title"] != null &&
                        songNode["Text"] != null)
                    {
                        nr = Int32.Parse(songNode["Number"].InnerText);
                        highestID = nr > highestID ? nr : highestID;
                        title = songNode["Title"].InnerText;
                        text = songNode["Text"].InnerText;
                    }
                    else
                    {
                        throw new NotValidException();
                    }

                    Song newSong = new Song(nr, title, text, id, desc, imp);

                    if (songNode.Attributes["style"] != null && !string.IsNullOrEmpty(songNode.Attributes["style"].InnerText))
                    {
                        Guid styleId = Guid.Parse(songNode.Attributes["style"].InnerText);
                        newSong.Style = Styles.FirstOrDefault(s => s.ID == styleId);
                        newSong.UseDefaultStyle = false;
                    }
                    else
                    {
                        // use default style for this song
                        newSong.Style = Styles.FirstOrDefault(s => s.IsDefault);
                        newSong.UseDefaultStyle = true;
                    }

                    this.GetTranslations(newSong, translations, imp);

                    try
                    {
                        songs.Add(newSong.ID, newSong);
                    }
                    catch (ArgumentException)
                    {
                        string msg = "Wollen Sie Lied Nr." + nr + " ersetzen?\n";
                        msg += "(drücken Sie \"abbrechen\", wenn Sie das Lied überspringen wollen.)";
                        DialogResult dr = MessageBox.Show(msg, "lyra import",
                                                          MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                        if (dr == DialogResult.Yes)
                        {
                            songs.Remove(newSong.ID);
                            songs.Add(newSong.ID, newSong);
                        }
                        else if (dr == DialogResult.No)
                        {
                            newSong.nextID();
                            songs.Add(newSong.ID, newSong);
                        }
                        else
                        {
                            // cancel <-> ignore song
                        }
                        continue;
                    }
                }
                Util.addLoadTime(Util.getCurrentTicks() - start);
                // return SortedList with songs
                return songs;
            }
            catch (XmlException xmlEx)
            {
                Util.MBoxError(xmlEx.Message, xmlEx);
            }
            catch (NotValidException nValEx)
            {
                Util.MBoxError(nValEx.Message, nValEx);
            }
            catch (Exception e)
            {
                Util.MBoxError(e.Message, e);
            }
            return null;
        }
        /// <summary>
        /// Constructor for a grid cell; creates cell and reads in environmental data
        /// </summary>
        /// <param name="latitude">The latitude of the grid cell</param>
        /// <param name="latIndex">The latitudinal index of the grid cell</param>
        /// <param name="longitude">The longitude of the grid cell</param>
        /// <param name="lonIndex">The longitudinal index of the grid cell</param>
        /// <param name="latCellSize">The latitudinal dimension of the grid cell</param>
        /// <param name="lonCellSize">The longitudinal dimension of the grid cell</param>
        /// <param name="dataLayers">A list of environmental data variables in the model</param>
        /// <param name="missingValue">The missing value to be applied to all data in the grid cell</param>
        /// <param name="cohortFunctionalGroups">The definitions for cohort functional groups in the model</param>
        /// <param name="stockFunctionalGroups">The definitions for stock functional groups in the model</param>
        /// <param name="globalDiagnostics">A list of global diagnostic variables for the model grid</param>
        /// <param name="tracking">Whether process-tracking is enabled</param>
        /// <param name="specificLocations">Whether the model is being run for specific locations</param>
        public GridCell(float latitude, uint latIndex, float longitude, uint lonIndex, float latCellSize, float lonCellSize, 
            SortedList<string, EnviroData> dataLayers, double missingValue, FunctionalGroupDefinitions cohortFunctionalGroups, 
            FunctionalGroupDefinitions stockFunctionalGroups, SortedList<string, double> globalDiagnostics,Boolean tracking,
            bool specificLocations)
        {
            // Boolean to track when environmental data are missing
            Boolean EnviroMissingValue;

            // Initialise the utility functions
            Utilities = new UtilityFunctions();

            // Temporary vector for holding initial values of grid cell properties
            double[] tempVector;

            // Initialise deltas sorted list
            _Deltas = new Dictionary<string, Dictionary<string, double>>();

            // Initialize delta abundance sorted list with appropriate processes
            Dictionary<string, double> DeltaAbundance = new Dictionary<string, double>();
            DeltaAbundance.Add("mortality", 0.0);

            // Add delta abundance sorted list to deltas sorted list
            _Deltas.Add("abundance", DeltaAbundance);

            // Initialize delta biomass sorted list with appropriate processes
            Dictionary<string, double> DeltaBiomass = new Dictionary<string, double>();
            DeltaBiomass.Add("metabolism", 0.0);
            DeltaBiomass.Add("predation", 0.0);
            DeltaBiomass.Add("herbivory", 0.0);
            DeltaBiomass.Add("reproduction", 0.0);

            // Add delta biomass sorted list to deltas sorted list
            _Deltas.Add("biomass", DeltaBiomass);

            // Initialize delta reproductive biomass vector with appropriate processes
            Dictionary<string, double> DeltaReproductiveBiomass = new Dictionary<string, double>();
            DeltaReproductiveBiomass.Add("reproduction", 0.0);

            // Add delta reproduction sorted list to deltas sorted list
            _Deltas.Add("reproductivebiomass", DeltaReproductiveBiomass);

            // Initialize organic pool delta vector with appropriate processes
            Dictionary<string, double> DeltaOrganicPool = new Dictionary<string, double>();
            DeltaOrganicPool.Add("herbivory", 0.0);
            DeltaOrganicPool.Add("predation", 0.0);
            DeltaOrganicPool.Add("mortality", 0.0);

            // Add delta organic pool sorted list to deltas sorted list
            _Deltas.Add("organicpool", DeltaOrganicPool);

            // Initialize respiratory CO2 pool delta vector with appropriate processes
            Dictionary<string, double> DeltaRespiratoryCO2Pool = new Dictionary<string, double>();
            DeltaRespiratoryCO2Pool.Add("metabolism", 0.0);

            // Add delta respiratory CO2 pool to deltas sorted list
            _Deltas.Add("respiratoryCO2pool", DeltaRespiratoryCO2Pool);

            // Set the grid cell values of latitude, longitude and missing value as specified
            _Latitude = latitude;
            _Longitude = longitude;

            // Initialise list of environmental data layer values
            _CellEnvironment = new SortedList<string, double[]>();

            //Add the latitude and longitude
            tempVector = new double[1];
            tempVector[0] = latitude;
            _CellEnvironment.Add("Latitude", tempVector);
            tempVector = new double[1];
            tempVector[0] = longitude;
            _CellEnvironment.Add("Longitude", tempVector);

            // Add an organic matter pool to the cell environment to track organic biomass not held by animals or plants with an initial value of 0
            tempVector = new double[1];
            tempVector[0] = 0.0;
            _CellEnvironment.Add("Organic Pool", tempVector);

            // Add a repsiratory CO2 pool to the cell environment with an initial value of 0
            tempVector = new double[1];
            tempVector[0] = 0.0;
            _CellEnvironment.Add("Respiratory CO2 Pool", tempVector);

            // Add the grid cell area (in km2) to the cell environment with an initial value of 0
            tempVector = new double[1];
            // Calculate the area of this grid cell
            tempVector[0] = Utilities.CalculateGridCellArea(latitude, lonCellSize, latCellSize);
            // Add it to the cell environment
            _CellEnvironment.Add("Cell Area", tempVector);

            //Add the latitude and longitude indices
            tempVector = new double[1];
            tempVector[0] = latIndex;
            _CellEnvironment.Add("LatIndex", tempVector);
            tempVector = new double[1];
            tempVector[0] = lonIndex;
            _CellEnvironment.Add("LonIndex", tempVector);

            // Add the missing value of data in the grid cell to the cell environment
            tempVector = new double[1];
            tempVector[0] = missingValue;
            _CellEnvironment.Add("Missing Value", tempVector);

            // Loop through environmental data layers and extract values for this grid cell
            // Also standardise missing values

            // Loop over variables in the list of environmental data
            foreach (string LayerName in dataLayers.Keys)
            {
                // Initiliase the temporary vector of values to be equal to the number of time intervals in the environmental variable
                tempVector = new double[dataLayers[LayerName].NumTimes];
                // Loop over the time intervals in the environmental variable
                for (int hh = 0; hh < dataLayers[LayerName].NumTimes; hh++)
                {
                    // Add the value of the environmental variable at this time interval to the temporary vector
                    tempVector[hh] = dataLayers[LayerName].GetValue(_Latitude, _Longitude, (uint)hh, out EnviroMissingValue,latCellSize,lonCellSize);
                    // If the environmental variable is a missing value, then change the value to equal the standard missing value for this cell
                    if (EnviroMissingValue)
                        tempVector[hh] = missingValue;
                }
                // Add the values of the environmental variables to the cell environment, with the name of the variable as the key
                _CellEnvironment.Add(LayerName, tempVector);
            }

            if (_CellEnvironment.ContainsKey("LandSeaMask"))
            {
                if (_CellEnvironment["LandSeaMask"][0].CompareTo(0.0) == 0)
                {
                    if (ContainsData(_CellEnvironment["OceanTemp"], _CellEnvironment["Missing Value"][0]))
                    {
                        //This is a marine cell
                        tempVector = new double[1];
                        tempVector[0] = 2.0;
                        _CellEnvironment.Add("Realm", tempVector);

                        _CellEnvironment.Add("NPP", _CellEnvironment["OceanNPP"]);
                        _CellEnvironment.Add("DiurnalTemperatureRange", _CellEnvironment["OceanDTR"]);
                        if (_CellEnvironment.ContainsKey("Temperature"))
                        {
                            if(_CellEnvironment.ContainsKey("SST"))
                            {
                                _CellEnvironment["Temperature"] = _CellEnvironment["SST"];
                            }
                            else
                            {
                            }
                        }
                        else
                        {
                            _CellEnvironment.Add("Temperature", _CellEnvironment["SST"]);
                        }

                    }
                    else
                    {
                        //This is a freshwater cell and in this model formulation is characterised as belonging to the terrestrial realm
                        tempVector = new double[1];
                        tempVector[0] = 2.0;
                        _CellEnvironment.Add("Realm", tempVector);

                        _CellEnvironment.Add("NPP", _CellEnvironment["LandNPP"]);
                        _CellEnvironment.Add("DiurnalTemperatureRange", _CellEnvironment["LandDTR"]);
                    }
                }
                else
                {
                    //This is a land cell
                    tempVector = new double[1];
                    tempVector[0] = 1.0;
                    _CellEnvironment.Add("Realm", tempVector);

                    _CellEnvironment.Add("NPP", _CellEnvironment["LandNPP"]);
                    _CellEnvironment.Add("DiurnalTemperatureRange", _CellEnvironment["LandDTR"]);

                }
            }
            else
            {
                Debug.Fail("No land sea mask defined - a mask is required to initialise appropriate ecology");
            }

            //Calculate and add the standard deviation of monthly temperature as a measure of seasonality
            //Also calculate and add the annual mean temperature for this cell
            tempVector = new double[12];
            double[] sdtemp = new double[12];
            double[] meantemp = new double[12];

            tempVector = _CellEnvironment["Temperature"];

            double Average = tempVector.Average();
            meantemp[0] = Average;
            double SumOfSquaresDifferences = tempVector.Select(val => (val - Average) * (val - Average)).Sum();
            sdtemp[0] = Math.Sqrt(SumOfSquaresDifferences / tempVector.Length);

            _CellEnvironment.Add("SDTemperature", sdtemp);
            _CellEnvironment.Add("AnnualTemperature", meantemp);

            //Remove unrequired cell environment layers
            if (_CellEnvironment.ContainsKey("LandNPP")) _CellEnvironment.Remove("LandNPP");
            if (_CellEnvironment.ContainsKey("LandDTR")) _CellEnvironment.Remove("LandDTR");
            if (_CellEnvironment.ContainsKey("OceanNPP")) _CellEnvironment.Remove("OceanNPP");
            if (_CellEnvironment.ContainsKey("OceanDTR")) _CellEnvironment.Remove("OceanDTR");
            if (_CellEnvironment.ContainsKey("SST")) _CellEnvironment.Remove("SST");

            // CREATE NPP SEASONALITY LAYER
            _CellEnvironment.Add("Seasonality", CalculateNPPSeasonality(_CellEnvironment["NPP"], _CellEnvironment["Missing Value"][0]));

            // Calculate other climate variables from temperature and precipitation
            // Declare an instance of the climate variables calculator
            ClimateVariablesCalculator CVC = new ClimateVariablesCalculator();

            // Calculate the fraction of the year that experiences frost
            double[] NDF = new double[1];
            NDF[0] = CVC.GetNDF(_CellEnvironment["FrostDays"], _CellEnvironment["Temperature"],_CellEnvironment["Missing Value"][0]);
            _CellEnvironment.Add("Fraction Year Frost", NDF);

            double[] frostMonthly = new double[12];
            frostMonthly[0] = Math.Min(_CellEnvironment["FrostDays"][0] / 31.0, 1.0);
            frostMonthly[1] = Math.Min(_CellEnvironment["FrostDays"][1] / 28.0, 1.0);
            frostMonthly[2] = Math.Min(_CellEnvironment["FrostDays"][2] / 31.0, 1.0);
            frostMonthly[3] = Math.Min(_CellEnvironment["FrostDays"][3] / 30.0, 1.0);
            frostMonthly[4] = Math.Min(_CellEnvironment["FrostDays"][4] / 31.0, 1.0);
            frostMonthly[5] = Math.Min(_CellEnvironment["FrostDays"][5] / 30.0, 1.0);
            frostMonthly[6] = Math.Min(_CellEnvironment["FrostDays"][6] / 31.0, 1.0);
            frostMonthly[7] = Math.Min(_CellEnvironment["FrostDays"][7] / 31.0, 1.0);
            frostMonthly[8] = Math.Min(_CellEnvironment["FrostDays"][8] / 30.0, 1.0);
            frostMonthly[9] = Math.Min(_CellEnvironment["FrostDays"][9] / 31.0, 1.0);
            frostMonthly[10] = Math.Min(_CellEnvironment["FrostDays"][10] / 30.0, 1.0);
            frostMonthly[11] = Math.Min(_CellEnvironment["FrostDays"][11] / 31.0, 1.0);

            _CellEnvironment.Add("Fraction Month Frost", frostMonthly);
            _CellEnvironment.Remove("FrostDays");

            // Calculate AET and the fractional length of the fire season
            Tuple<double[], double, double> TempTuple = new Tuple<double[], double, double>(new double[12], new double(), new double());
            TempTuple = CVC.MonthlyActualEvapotranspirationSoilMoisture(_CellEnvironment["AWC"][0], _CellEnvironment["Precipitation"], _CellEnvironment["Temperature"]);
            _CellEnvironment.Add("AET", TempTuple.Item1);
            _CellEnvironment.Add("Fraction Year Fire", new double[1] { TempTuple.Item3 / 360 });

            // Designate a breeding season for this grid cell, where a month is considered to be part of the breeding season if its NPP is at
            // least 80% of the maximum NPP throughout the whole year
            double[] BreedingSeason = new double[12];
            for (int i = 0; i < 12; i++)
            {
                if ((_CellEnvironment["Seasonality"][i] / _CellEnvironment["Seasonality"].Max()) > 0.5)
                {
                    BreedingSeason[i] = 1.0;
                }
                else
                {
                    BreedingSeason[i] = 0.0;
                }
            }
            _CellEnvironment.Add("Breeding Season", BreedingSeason);

            // Initialise the grid cell cohort and stock handlers
            _GridCellCohorts = new GridCellCohortHandler(cohortFunctionalGroups.GetNumberOfFunctionalGroups());
            _GridCellStocks = new GridCellStockHandler(stockFunctionalGroups.GetNumberOfFunctionalGroups());
        }
Exemplo n.º 7
0
 public override void Remove(Object key)
 {
     lock (_root) {
         _list.Remove(key);
     }
 }
Exemplo n.º 8
0
        private void ShowUsers()
        {
            Cursor csr = null;
            Database db;
            ListViewItem UsersListViewItem;

            try
            {
                csr = this.Cursor;   // Save the old cursor
                this.Cursor = Cursors.WaitCursor;   // Display the waiting cursor

                // Clear the user list
                UsersListView.Items.Clear();

                // Limit the properties returned to just those that we use
                SqlServerSelection.SetDefaultInitFields(typeof(User),
                    new string[] { "Name", "Login", "ID" });

                // Show the current users for the selected database
                if (DatabasesComboBox.SelectedIndex >= 0)
                {
                    db = (Database)DatabasesComboBox.SelectedItem;

                    // Load list of logins
                    SortedList logins =
                        new SortedList(SqlServerSelection.Logins.Count);

                    foreach (Login userLogin in SqlServerSelection.Logins)
                    {
                        logins.Add(userLogin.Name, null);
                    }

                    // Add users to list view and remove from logins
                    foreach (User usr in db.Users)
                    {
                        UsersListViewItem = UsersListView.Items.Add(usr.Name);
                        UsersListViewItem.SubItems.Add(usr.Login);
                        UsersListViewItem.SubItems.Add(usr.ID.ToString(
                            System.Globalization.CultureInfo.InvariantCulture));

                        // Remove from logins
                        logins.Remove(usr.Login);
                    }

                    // Populate the logins combo box
                    LoginsComboBox.Items.Clear();
                    foreach (DictionaryEntry dictLogin in logins)
                    {
                        // Eliminate sa login from list
                        if ((string)dictLogin.Key != "sa")
                        {
                            LoginsComboBox.Items.Add(dictLogin.Key);
                        }
                    }

                    // Select the first item in the list
                    if (UsersListView.Items.Count > 0)
                    {
                        UsersListView.Items[0].Selected = true;
                        UsersListView.Items[0].EnsureVisible();
                    }
                }
            }
            catch (SmoException ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex);
                emb.Show(this);
            }
            finally
            {
                this.Cursor = csr;  // Restore the original cursor
            }
        }
Exemplo n.º 9
0
		public void TestRemove ()
		{
			SortedList sl1 = new SortedList (24);
			string s = null;
			int k;
			for (int i = 0; i < 50; i++) sl1.Add ("kala " + i, i);

			try {
				sl1.Remove (s);
				Assert.Fail ("#A");
			} catch (ArgumentNullException) {
			}

			k = sl1.Count;
			sl1.Remove ("kala ");
			Assert.AreEqual (k, sl1.Count, "#B");

			try {
				sl1.Remove (15);
				Assert.Fail ("#C");
			} catch (InvalidOperationException) {
			}

			for (int i = 15; i < 20; i++)
				sl1.Remove ("kala " + i);
			for (int i = 45; i < 55; i++)
				sl1.Remove ("kala " + i);

			Assert.AreEqual (40, sl1.Count, "#D1");
			for (int i = 45; i < 55; i++)
				Assert.IsNull (sl1 ["kala " + i], "#D2:" + i);
		}
Exemplo n.º 10
0
        private void deleteLevelSide(
			MamdaOrderBookPriceLevel level,
			TreeMap bookSide)
        {
            MamaPrice price = level.getPrice();
            if (bookSide.ContainsKey(price))
            {
                /* We actually need to process this properly because the
                 * update may not contain all entries, just updated
                 * ones. */
                bookSide.Remove(price);
            }
        }
Exemplo n.º 11
0
        /// <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 = doc.GetElementsByTagName("Songs")[0];

                // remove all, if songs have been replaced!
                if (Util.DELALL)
                {
                    XmlNode translations = 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 = 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 = 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();
                            }
                            curSong.BackgroundPicture = Util.handlePicture(curSong.BackgroundPicture);
                            // check if background already existed:
                            if (children.Count == 4)
                            {
                                XmlNodeList bgdesc = children[3].ChildNodes;
                                if (children[3].Name == "Background" && bgdesc.Count == 3 && bgdesc[0].Name == "uri"
                                    && bgdesc[1].Name == "transparency" && bgdesc[2].Name == "scale")
                                {
                                    bgdesc[0].InnerText = curSong.BackgroundPicture;
                                    bgdesc[1].InnerText = curSong.Transparency.ToString();
                                    bgdesc[2].InnerText = curSong.Scale ? "yes" : "no";
                                }
                                else
                                {
                                    throw new NotValidException("background node not valid");
                                }
                            }
                            else
                            {
                                XmlNode bgdesc = doc.CreateNode(XmlNodeType.Element, "Background", doc.NamespaceURI);
                                XmlNode uri = doc.CreateNode(XmlNodeType.Element, "uri", doc.NamespaceURI);
                                uri.InnerText = curSong.BackgroundPicture;
                                XmlNode transp = doc.CreateNode(XmlNodeType.Element, "transparency", doc.NamespaceURI);
                                transp.InnerText = curSong.Transparency.ToString();
                                XmlNode scale = doc.CreateNode(XmlNodeType.Element, "scale", doc.NamespaceURI);
                                scale.InnerText = curSong.Scale ? "yes" : "no";
                                bgdesc.AppendChild(uri);
                                bgdesc.AppendChild(transp);
                                bgdesc.AppendChild(scale);
                                curNode.AppendChild(bgdesc);
                            }
                        }
                            // id doesn't exist
                        else
                        {
                            // create node
                            newNode = doc.CreateNode(XmlNodeType.Element, "Song", doc.NamespaceURI);

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

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

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

                            idattr = doc.CreateAttribute("id", doc.NamespaceURI);
                            idattr.Value = "";
                            descattr = doc.CreateAttribute("zus", doc.NamespaceURI);
                            descattr.Value = "";
                            XmlNode bgdesc = null;
                            if (curSong.BackgroundPicture != "")
                            {
                                bgdesc = doc.CreateNode(XmlNodeType.Element, "Background", doc.NamespaceURI);
                                XmlNode uri = doc.CreateNode(XmlNodeType.Element, "uri", doc.NamespaceURI);
                                curSong.BackgroundPicture = Util.handlePicture(curSong.BackgroundPicture);
                                uri.InnerText = curSong.BackgroundPicture;
                                XmlNode transp = doc.CreateNode(XmlNodeType.Element, "transparency", doc.NamespaceURI);
                                transp.InnerText = curSong.Transparency.ToString();
                                XmlNode scale = doc.CreateNode(XmlNodeType.Element, "scale", doc.NamespaceURI);
                                scale.InnerText = curSong.Scale ? "yes" : "no";
                                bgdesc.AppendChild(uri);
                                bgdesc.AppendChild(transp);
                                bgdesc.AppendChild(scale);
                            }

                            newNode.AppendChild(nr);
                            newNode.AppendChild(title);
                            newNode.AppendChild(text);
                            if (bgdesc != null)
                            {
                                newNode.AppendChild(bgdesc);
                            }
                            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;
                    }
                }
                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;
            }
        }
Exemplo n.º 12
0
        private SortedList Param()
        {
            string POSTStr = PostInput();
            SortedList SortList = new SortedList();
            int index = POSTStr.IndexOf("&");
            string[] Arr = { };
            if (index != -1) //参数传递不只一项
            {
                Arr = POSTStr.Split('&');
                for (int i = 0; i < Arr.Length; i++)
                {
                    int equalindex = Arr[i].IndexOf('=');
                    string paramN = Arr[i].Substring(0, equalindex);
                    string paramV = Arr[i].Substring(equalindex + 1);
                    if (!SortList.ContainsKey(paramN)) //避免用户传递相同参数
                    { SortList.Add(paramN, paramV); }
                    else //如果有相同的,一直删除取最后一个值为准
                    { SortList.Remove(paramN); SortList.Add(paramN, paramV); }
                }
            }
            else //参数少于或等于1项
            {
                int equalindex = POSTStr.IndexOf('=');
                if (equalindex != -1)
                { //参数是1项
                    string paramN = POSTStr.Substring(0, equalindex);
                    string paramV = POSTStr.Substring(equalindex + 1);
                    SortList.Add(paramN, paramV);

                }
                else //没有传递参数过来
                { SortList = null; }
            }
            return SortList;
        }
Exemplo n.º 13
0
 //Removes recursive.
 //Returns true if this is recursive.
 private bool RemoveRecursive(DependicyInfo opt, Hashtable optimized, Hashtable notOptimized, SortedList history, Hashtable processed)
 {
     //(29.11.2006 12:15)
     if (processed.Contains(opt))
     {
         return (bool)processed[opt];
     }
     if (notOptimized[opt.Key] == null)
     {
         if (opt.Deps == null)
         {
             processed[opt] = false;
             return false;
         }
         bool recursive = false;
         //Check each dependicy if it is recursive.
         foreach (string depName in opt.Deps)
         {
             string historyKey = opt.Key + " " + depName;
             if (history[historyKey] != null)
             {
                 //Recursive.
                 //(B001)
                 notOptimized[depName] = depName;
                 recursive = true;
             }
             else
             {
                 //Check with property dependicy.
                 int propIndex = depName.IndexOf(Calculator.PROPERTY_CHAR);
                 string variableName = depName.Substring(0, propIndex);
                 object depObj = m_calculator.Variable(variableName);
                 if (depObj is IOptimizable)
                 {
                     IOptimizable depOpt = (IOptimizable)depObj;
                     if (depOpt.PropertyDependices != null)
                     {
                         foreach (PropertyDependicy propertyDep in depOpt.PropertyDependices)
                         {
                             if (propertyDep.ChildProperty == depName.Substring(propIndex + 1))
                             {
                                 string parentKey = variableName + Calculator.PROPERTY_CHAR + propertyDep.ParentProperty;
                                 if (history[opt.Key + " " + parentKey] != null)
                                 {
                                     //Recursive.
                                     //(B001)
                                     notOptimized[depName] = depName;
                                     recursive = true;
                                 }
                             }
                         }
                     }
                 }
             }
         }
         //Search in each not-recursive dependicy.
         foreach (string depName in opt.Deps)
         {
             string historyKey = opt.Key + " " + depName;
             if (notOptimized[depName] == null)
             {
                 history.Add(historyKey, true);
                 if (this.RemoveRecursive((DependicyInfo)optimized[depName], optimized, notOptimized, history, processed))
                 {
                     recursive = true;
                 }
                 else
                 {
                     history.Remove(historyKey);
                 }
             }
         }
         if (recursive)
         {
             if (notOptimized[opt.Key] == null)
             {
                 notOptimized.Add(opt.Key, opt.Key);
             }
         }
         processed[opt] = recursive;
         return recursive;
     }
     else
     {
         processed[opt] = true;
         return true;
     }
 }
Exemplo n.º 14
0
        protected void collapseVectors(SortedList vectors)
        {
            ArrayList vertices;
            int steps = 0;
            while (vectors.Count > 0) {
                VectorPixel vectorOld = (VectorPixel)vectors.GetByIndex(0); // ensures we begin at start/end of some line (as opposed to an inner segment)
                IntVector2 startPnt = vectorOld.fromPnt;
                VectorPixel vectorNow;
                VectorPixel vectorNew;
                VectorPixel vectorPrev = null;
                Line line = new Line(vectorOld);
                vertices = new ArrayList(1000);
                do {
                    printProgress(ref steps, 2000);
                    vectorNow = (VectorPixel)vectors[vectorOld.toPnt];
                    vectorNew = (VectorPixel)vectors[vectorNow.toPnt];
                    if (!vectorNow.fromPnt.Equals(startPnt) && !vectorNow.toPnt.Equals(startPnt) && vectorNow.linkVector() && line.sameDir(vectorNow) && !vectorNew.linkVector() && line.sameDir(vectorNew) ) {
                        if (line.satisfiesInner(vectorNew)) {
                            // new segment ok, let's try the next one
                            line.update(vectorNew);
                            vectors.Remove(vectorNow.fromPnt);
                            vectorOld = vectorNew;
                        } else if (line.satisfiesOuter(vectorNew)) {
                            // vectorNow can be an outer segment
                            line.update(vectorNew);

                            vertices.Add(new DoubleVector2(line.toPnt));
                            vectors.Remove(vectorNew.fromPnt);
                            vectors.Remove(vectorNow.fromPnt);
                            vectorOld = (VectorPixel)vectors[vectorNew.toPnt];
                            line = new Line(vectorOld);
                        } else {
                            // new segment off, but link is ok as an outer segment
                            line.update(vectorNow);
                            vertices.Add(new DoubleVector2(line.toPnt));
                            vectors.Remove(vectorNow.fromPnt);
                            vectorOld = vectorNew;
                            line = new Line(vectorOld);
                        }
                    } else if (!vectorNow.fromPnt.Equals(startPnt) && line.sameDir(vectorNow)) {
                        // vectorNow is not a simple link between two segments
                        if (line.satisfiesInner(vectorNow)) {
                            // new segment ok, let's try the next one
                            line.update(vectorNow);
                            vectorOld = vectorNow;
                        } else if (line.satisfiesOuter(vectorNow)) {
                            // vectorNow can be an outer segment
                            line.update(vectorNow);
                            vertices.Add(new DoubleVector2(line.toPnt));
                            vectors.Remove(vectorNow.fromPnt);
                            vectorOld = vectorNew;
                            line = new Line(vectorOld);
                        } else {
                            // vectorNow just won't fit - process it separately
                            vertices.Add(new DoubleVector2(line.toPnt));
                            vectorOld = vectorNow;
                            line = new Line(vectorOld);
                        }
                    } else {
                        // vectorNow just won't fit - process it separately
                        vertices.Add(new DoubleVector2(line.toPnt));
                        vectorOld = vectorNow;
                        line = new Line(vectorOld);
                    }
                    if (vectorPrev != null)
                        vectors.Remove(vectorPrev.fromPnt);
                    vectorPrev = vectorOld;
                } while (!vectorOld.fromPnt.Equals(startPnt));
                vectors.Remove(startPnt);
                vertices.TrimToSize();
                polygons.Add(vertices);
            }
        }
Exemplo n.º 15
0
        private void txtPack_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar) && e.KeyChar != 13)
            {
                e.Handled = true;
            }

            if (e.KeyChar == 13)
            {
                if (CheckNullEvent())
                {
                    SortedList sList = new SortedList(); // 可以打多包

                    int pVolume = int.Parse(txtVolume.Text.Trim());// 每包册数

                    int pNumber = int.Parse(txtItem.Text.Trim());// 每件包数

                    int totalNumber = int.Parse(txtPack.Text.Trim());//总包数

                    // ------------------------------------------------------------//

                    int Index = 1;  //件数

                    int packagenum = 0;

                    int totalVolume = totalNumber * pVolume; // 当前总册数

                    int MaxVolume = BookInfo.PxVolume - BookInfo.DbVolume;//最多可发数量

                    if (totalVolume > MaxVolume)
                    {
                        PMess("发货数量不能大于开单数量, 最多可发" + MaxVolume + "册");
                        return;
                    }

                    if (totalNumber < pNumber)
                    {
                        NNetworkDAO.BuildBatchPackage(ref sList, Index, totalVolume);
                    }
                    else
                    {
                        Index = totalNumber / pNumber; //总件数

                        NNetworkDAO.BuildBatchPackage(ref sList, Index, pNumber * pVolume);

                        if (!(totalNumber % pNumber).Equals(0))
                        {
                            NNetworkDAO.BuildBatchPackage(ref sList, 1, (totalNumber % pNumber) * pVolume);
                        }
                    }

                    if (sList.Count != 0)
                    {
                        sList.Remove(sList.GetKey(sList.Count - 1));
                    }

                    if (sList.Count > 0)
                    {
                        printer.Remark = txtCode.Text.Trim();
                        printer.PackType = 0;
                        printer.Dgv = dgv_PackInfo;
                        printer.PrintList = sList;
                        printer.Print();
                    }

                    //打包进度
                    ScanProgress();
                    SBookInfo();
                    txtItem.Text = "";
                    txtPack.Text = "";
                    txtVolume.Text = "";
                    txtBarcode.Text = "";
                    txtBarcode.Focus();
                    LoadPacksInfo();
                }
            }
        }
Exemplo n.º 16
0
 protected SortedList createVectors(byte[,] pixelOn, Bitmap bmp)
 {
     SortedList vectors = new SortedList(bmp.Width * bmp.Height / 32);
     Hashtable vectorsReverse = new Hashtable(bmp.Width * bmp.Height / 32);
     int steps = 0;
     for (int j = 0; j < bmp.Height + 1; j++)
         for (int i = 0; i < bmp.Width + 1; i++) {
             printProgress(ref steps, 400000);
             int type =
                 (pixelOn[i, j] & 1) +
                 ((pixelOn[i + 1, j] & 1) << 1) +
                 ((pixelOn[i, j + 1] & 1) << 2) +
                 ((pixelOn[i + 1, j + 1] & 1) << 3);
             if (type == 1 + 8 || type == 2 + 4) { // get rid of illegal situations
                 pixelOn[i, j] |= 1;
                 pixelOn[i + 1, j] |= 1;
                 pixelOn[i, j + 1] |= 1;
                 pixelOn[i + 1, j + 1] |= 1;
                 printWarning("\nillegal pixel configuration at [" + i + ", " + j + "]");
             }
         }
     for (int j = 0; j < bmp.Height; j++)
         for (int i = 0; i < bmp.Width; i++) {
             printProgress(ref steps, 800000);
             if ((pixelOn[i + 1, j + 1] & 1) == 1) {
                 int type1 =
                     (pixelOn[i + 1, j] & 1) +
                     (pixelOn[i + 1, j + 2] & 1);
                 int type2 =
                     (pixelOn[i, j + 1] & 1) +
                     (pixelOn[i + 2, j + 1] & 1);
                 if (type1 == 2 && type2 == 0 || type1 == 0 && type2 == 2 ) { // get rid of illegal situations
                     pixelOn[i + 2, j + 1] |= 1;
                     pixelOn[i + 1, j + 2] |= 1;
                     printWarning("\nillegal pixel configuration at [" + i + ", " + j + "]");
                 }
             }
         }
     for (int j = -1; j < bmp.Height; j++)
         for (int i = -1; i < bmp.Width; i++) {
             printProgress(ref steps, 400000);
             int type =
                 (pixelOn[i + 1, j + 1] & 1) +
                 ((pixelOn[i + 2, j + 1] & 1) << 1) +
                 ((pixelOn[i + 1, j + 2] & 1) << 2) +
                 ((pixelOn[i + 2, j + 2] & 1) << 3);
             IntVector2 fromPnt = new IntVector2();
             IntVector2 toPnt = new IntVector2();
             switch (type) { // create horizontal and vertical vectors between adjacent pixels
                 case 3:
                     // xx
                     // --
                     fromPnt = new IntVector2(i, j);
                     toPnt = new IntVector2(i + 1, j);
                     break;
                 case 12:
                     // --
                     // xx
                     fromPnt = new IntVector2(i + 1, j + 1);
                     toPnt = new IntVector2(i, j + 1);
                     break;
                 case 5:
                     // x-
                     // x-
                     fromPnt = new IntVector2(i, j + 1);
                     toPnt = new IntVector2(i, j);
                     break;
                 case 10:
                     // -x
                     // -x
                     fromPnt = new IntVector2(i + 1, j);
                     toPnt = new IntVector2(i + 1, j + 1);
                     break;
                 case 14:
                     // -x
                     // xx
                     fromPnt = new IntVector2(i + 1, j);
                     toPnt = new IntVector2(i, j + 1);
                     break;
                 case 13:
                     // x-
                     // xx
                     fromPnt = new IntVector2(i + 1, j + 1);
                     toPnt = new IntVector2(i, j);
                     break;
                 case 11:
                     // xx
                     // -x
                     fromPnt = new IntVector2(i, j);
                     toPnt = new IntVector2(i + 1, j + 1);
                     break;
                 case 7:
                     // xx
                     // x-
                     fromPnt = new IntVector2(i, j + 1);
                     toPnt = new IntVector2(i + 1, j);
                     break;
             }
             if (fromPnt.defined) {
                 if (vectorsReverse.Contains(fromPnt)) {
                     VectorPixel oldVP = (VectorPixel)vectorsReverse[fromPnt];
                     if ((toPnt - fromPnt).extension(oldVP.toPnt - oldVP.fromPnt))  {
                         vectors.Remove(oldVP.fromPnt);
                         vectorsReverse.Remove(oldVP.toPnt);
                         fromPnt = oldVP.fromPnt;
                     }
                 }
                 if (vectors.Contains(toPnt)) {
                     VectorPixel oldVP = (VectorPixel)vectors[toPnt];
                     if ((toPnt - fromPnt).extension(oldVP.toPnt - oldVP.fromPnt))  {
                         vectors.Remove(oldVP.fromPnt);
                         vectorsReverse.Remove(oldVP.toPnt);
                         toPnt = oldVP.toPnt;
                     }
                 }
                 if (!fromPnt.Equals(toPnt)) { // do not add null vectors, they ugly :/
                     VectorPixel newVP = new VectorPixel(fromPnt, toPnt);
                     if (vectors.Contains(newVP.fromPnt))
                         throw new Exception("illegal edge configuration at pixel [" + newVP.fromPnt.x + ", " + newVP.fromPnt.y + "]");
                     else
                         vectors.Add(newVP.fromPnt, newVP);
                     if (vectorsReverse.Contains(newVP.toPnt))
                         throw new Exception("illegal edge configuration at pixel [" + newVP.toPnt.x + ", " + newVP.toPnt.y + "]");
                     else
                         vectorsReverse.Add(newVP.toPnt, newVP);
                 }
             }
         }
     return vectors;
 }
Exemplo n.º 17
0
		internal PswaAuthorizationRule RemoveRule(SortedList<int, PswaAuthorizationRule> allRules, int id)
		{
			PswaAuthorizationRule item = null;
			if (allRules.ContainsKey(id))
			{
				item = allRules[id];
				allRules.Remove(id);
			}
			return item;
		}
Exemplo n.º 18
0
        public void TestRemoveBasic()
        {
            StringBuilder sblMsg = new StringBuilder(99);
            //

            SortedList sl2 = null;

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

            string s1 = null;
            string s2 = null;
            string s3 = null;

            int i = 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);

            Assert.Null(s3);

            //   Testcase: add few key-val pairs
            for (i = 0; i < 100; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg.Length = 0;
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                sl2.Add(s1, s2);
            }

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

            //
            //   Testcase: test Remove (Object)
            //
            for (i = 0; i < 100; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sl2.Remove(s1); // remove the current object
                Assert.Equal(sl2.Count, (100 - (i + 1)));
            }

            //
            // Boundary - Remove a invalid key: No_Such_Key
            //
            sblMsg.Length = 0;
            sblMsg.Append("No_Such_Key");
            s1 = sblMsg.ToString();
            sl2.Remove(s1);

            //
            // Boundary - null key - pk
            //
            Assert.Throws<ArgumentNullException>(() => { sl2.Remove((string)null); });
        }
Exemplo n.º 19
0
        /// <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;
            }
        }
 private static SortedList VerifyResourceNames(Dictionary<string, ResourceData> resourceList, CodeDomProvider codeProvider, ArrayList errors, out Hashtable reverseFixupTable)
 {
     reverseFixupTable = new Hashtable(0, StringComparer.InvariantCultureIgnoreCase);
     SortedList list = new SortedList(StringComparer.InvariantCultureIgnoreCase, resourceList.Count);
     foreach (KeyValuePair<string, ResourceData> pair in resourceList)
     {
         string key = pair.Key;
         if ((string.Equals(key, "ResourceManager") || string.Equals(key, "Culture")) || (typeof(void) == pair.Value.Type))
         {
             errors.Add(key);
         }
         else
         {
             if (((key.Length <= 0) || (key[0] != '$')) && (((key.Length <= 1) || (key[0] != '>')) || (key[1] != '>')))
             {
                 if (!codeProvider.IsValidIdentifier(key))
                 {
                     string str2 = VerifyResourceName(key, codeProvider, false);
                     if (str2 == null)
                     {
                         errors.Add(key);
                         goto Label_0185;
                     }
                     string item = (string) reverseFixupTable[str2];
                     if (item != null)
                     {
                         if (!errors.Contains(item))
                         {
                             errors.Add(item);
                         }
                         if (list.Contains(str2))
                         {
                             list.Remove(str2);
                         }
                         errors.Add(key);
                         goto Label_0185;
                     }
                     reverseFixupTable[str2] = key;
                     key = str2;
                 }
                 ResourceData data = pair.Value;
                 if (!list.Contains(key))
                 {
                     list.Add(key, data);
                 }
                 else
                 {
                     string str4 = (string) reverseFixupTable[key];
                     if (str4 != null)
                     {
                         if (!errors.Contains(str4))
                         {
                             errors.Add(str4);
                         }
                         reverseFixupTable.Remove(key);
                     }
                     errors.Add(pair.Key);
                     list.Remove(key);
                 }
             }
         Label_0185:;
         }
     }
     return list;
 }
Exemplo n.º 21
0
        private void MatchCheques(object sender, DoWorkEventArgs e)
        {
            //Note to future self. Input sheet must contain three columns: CHQNum, Date, Stale. Column order doesn't matter. Names must be exact.

            CheckForIllegalCrossThreadCalls = false; //bad practice, but don't care :)

            BackgroundWorker worker = sender as BackgroundWorker;

            string delimiter = ",";

            GenericParserAdapter myParser = new GenericParserAdapter();
            myParser.SetDataSource(tbStaleChequeList.Text);
            myParser.FirstRowHasHeader = true;
            myParser.ColumnDelimiter = ',';
            System.Data.DataTable myDataTable = myParser.GetDataTable();

            SortedList<int, Tuple<string, string>> chequeList = new SortedList<int, Tuple<string, string>>();//KV pair with Schema(ChequeNumber, <Date,Amount>)

            FileStream errorStream = File.Create(tbOutputLocation.Text + ".errors.csv");
            int errorCount = 0;

            //Loop over each row/cheque, first checking if stale and if so, adding it to a list to find
            foreach (DataRow currentRow in myDataTable.Rows)
            {
                try
                {
                    if (Double.Parse((string)currentRow["Stale"]) > 0.00)
                    {
                        //myDataTable.Select("CHQNum = " + chqnumber);
                        int chqNum = 0;
                        try
                        {
                            chqNum = Int32.Parse((string)currentRow["CHQNum"]);
                            chequeList.Add(chqNum, new Tuple<string,string>((string)currentRow["Date"],(string)currentRow["Stale"]));
                        }
                        catch (Exception chqNumFailureException)
                        {
                            //Try to write out a message and the cheque number to the errorStream. If something fails here, the CHQ number is REALLY BAD.
                            try
                            {
                                AddText(errorStream, "Failed to parse cheque number. Cheque Number was " + (string)currentRow["CHQNum"] + ". Associated exception message: \"" + chqNumFailureException.Message + "\"" +delimiter);
                            }
                            catch (Exception chqNumMajorFailureException)
                            {
                                AddText(errorStream, "Failed to parse cheque number. Could not get cheque number due to critical failure. Associated exception message: \"" + chqNumMajorFailureException.Message + "\"" + delimiter);
                            }
                        }
                    }
                }
                catch (Exception staleParseFailure)
                {
                    //Try to write out a message and the cheque number to the errorStream. If something fails here, the stale column is REALLY BAD.
                    try
                    {
                        AddText(errorStream, "Didn't find anything useful in stale column; continuing. Stale Column contents were " + (string)currentRow["Stale"] + "Associated exception message: \"" + staleParseFailure.Message + "\"" + delimiter);
                    }
                    catch (Exception majorStaleParseFailure)
                    {
                        AddText(errorStream, "Didn't find anything useful in stale column; continuing. Could not get column contents due to critical failure. Associated exception message: \"" + majorStaleParseFailure.Message + "\"" + delimiter);
                    }
                }
            }

            //Open each file which potentially contains what we want, and search for each cheque number. If found, dump the line and filename into a csv
            FileStream outputFileStream = File.Create(tbOutputLocation.Text);
            AddText(outputFileStream, "\"ChequeNum\"" + delimiter);
            AddText(outputFileStream, "\"Date\"" + delimiter);
            AddText(outputFileStream, "\"Amount\"" + Environment.NewLine);

            var filesToCheck = System.IO.Directory.EnumerateFiles(@tbRootCHQFolder.Text, "*", SearchOption.AllDirectories);

            int totalSteps = filesToCheck.Count();

            Excel._Application oExcel = new Excel.Application();
            oExcel.Visible = false;
            oExcel.ScreenUpdating = false;
            oExcel.DisplayAlerts = false;

            int iterations = 0;

            foreach (var currentFile in filesToCheck)
            {
                lock (thisLock)
                {
                    iterations += 1;
                    try
                    {
                        Excel.Workbook myWorkBook = oExcel.Workbooks.Open(currentFile);

                        //Check each worksheet in the book
                        foreach (Excel.Worksheet currWorksheet in myWorkBook.Worksheets)
                        {
                            Excel.Range lastCell = currWorksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);

                            //if there's something in the worksheet then try and find the cheque
                            if (lastCell.Column > 1)
                            {
                                Excel.Range firstCell = currWorksheet.get_Range("A1", Type.Missing);
                                Excel.Range entireSheetRange = currWorksheet.get_Range(firstCell, lastCell);
                                //foreach (var currCheque in chequeList) //I want to remove items as I'm going so am using the iterate backwards method, and using an enumerator causes errors!
                                for (int currChequeIndex = chequeList.Count - 1; currChequeIndex > -1; currChequeIndex--)
                                {
                                    int currChequeKey = chequeList.Keys[currChequeIndex];
                                    Tuple<string, string> currChequeValues = chequeList.Values[currChequeIndex];
                                    Excel.Range currentFind = null;

                                    currentFind = entireSheetRange.Find(currChequeKey, Type.Missing,
                                                 Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlWhole,
                                                 Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, false,
                                                 Type.Missing, Type.Missing);
                                    //Found the cheque, write out the info we want
                                    if (currentFind != null)
                                    {
                                        //Remove the cheque from our list, as we're now wasting time looking for it
                                        chequeList.Remove(currChequeKey);

                                        AddText(outputFileStream, "\"" + currChequeKey.ToString() + "\"" + delimiter);
                                        AddText(outputFileStream, "\"" + currChequeValues.Item1 + "\"" + delimiter);
                                        AddText(outputFileStream, "\"" + currChequeValues.Item2 + "\"" + delimiter);
                                        AddText(outputFileStream, "\"" + currentFile + "\"" + delimiter);
                                        int numCols = currentFind.EntireRow.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Column;
                                        for (int i = 1; i <= numCols; i++)
                                        {
                                            if (i != numCols)
                                            {
                                                AddText(outputFileStream, "\"" + currentFind.EntireRow.Cells[1, i].Text + "\"" + delimiter);
                                            }
                                            else
                                            {
                                                AddText(outputFileStream, "\"" + currentFind.EntireRow.Cells[1, i].Text + "\"" + Environment.NewLine);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        myWorkBook.Close(false, false, Type.Missing);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(myWorkBook); //http://support.microsoft.com/kb/317109

                    }
                    catch (Exception excelOpenFailure)
                    {

                        AddText(errorStream, "\"Excel operation error occurred. Trying to continue. Exception message: " + excelOpenFailure.Message + "\"" + Environment.NewLine);
                        errorCount += 1;
                        lblErrorCount.Text = ("Excel Error Count: " + errorCount);
                        /*//if we fail, try and close the Excel instance if poss, and recreate it! If this completely fails, crash inelegantly :(
                        try
                        {
                            oExcel.Visible = false;
                            oExcel.ScreenUpdating = false;
                            oExcel.DisplayAlerts = false;
                            oExcel.Quit();
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel); //http://support.microsoft.com/kb/317109
                        }
                        catch (Exception doublecrash)
                        {
                            //Do nothing
                        }*/

                        oExcel = null;
                        oExcel = new Excel.Application();
                        oExcel.Visible = false;
                        oExcel.ScreenUpdating = false;
                        oExcel.DisplayAlerts = false;
                    }

                    //Report progress
                    worker.ReportProgress((int)(((double)iterations / (double)totalSteps) * 100));
                }
            }

            //Dump unfound cheques
            FileStream outputFileStream2 = File.Create(tbOutputLocation.Text + ".faileddump.csv");
            if (chequeList.Count != 0)
            {
                foreach (var currCheque in chequeList)
                {
                    AddText(outputFileStream2, "\"" + currCheque.Key.ToString() + "\"" + Environment.NewLine);
                }
            }

            //Shut down everything
            outputFileStream.Close();
            outputFileStream = null;
            outputFileStream2.Close();
            outputFileStream2 = null;
            errorStream.Close();
            errorStream = null;
            oExcel.Visible = true;
            oExcel.ScreenUpdating = true;
            oExcel.DisplayAlerts = true;
            oExcel.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel); //http://support.microsoft.com/kb/317109
        }
Exemplo n.º 22
0
        //, Excluder excluder)
        private List<RouteInstance> findPath(DateTime requestTime, RouteNode origin, RouteNode goal, int weight, int volume, NodeEvaluator evaluator, RouteExcluder excluder)
        {
            Delivery delivery = new Delivery();
            delivery.Origin = origin;
            delivery.Destination = goal;
            delivery.WeightInGrams = weight;
            delivery.VolumeInCm3 = volume;
            delivery.TimeOfRequest = requestTime;

            originPath = new Dictionary<RouteNode, RouteInstance>();
            nodeCost = new Dictionary<RouteNode, double>();
            closed = new HashSet<RouteNode>();
            var rc = new RouteComparer();
            fringe = new SortedList<RouteNode, double>(rc);

            fringe.Add(origin, 0);
            originPath.Add(origin, new OriginRouteInstance(requestTime));

            //if the queue is empty return null (no path)
            while (fringe.Count > 0)
            {
                //take new node off the top of the stack
                //this is guaranteed to be the best way to the node
                RouteNode curNode = fringe.Keys[0];

                if (closed.Contains(curNode))
                    continue;

                nodeCost.Add(curNode, fringe.Values[0]);
                closed.Add(curNode);
                fringe.RemoveAt(0);

                //if it's the goal node exit and return path
                if (curNode.Equals(goal))
                    return completeDelivery(curNode);

                //grab a list of all of the routes where the given node is the origin
                IEnumerable<Route> routes = routeService.GetAll(curNode);

                //take each route that hasn't been ommited and evaluate
                foreach (Route path in excluder.Omit(routes))
                {
                    RouteInstance nextInstance = evaluator.GetNextInstance(path);
                    RouteNode nextNode = path.Destination;

                    double totalCost = evaluator.GetValue(nextInstance, delivery);

                    //if the node is not in the fringe
                    //or the current value is lower than
                    //the new cost then set the new parent
                    if (!fringe.ContainsKey(nextNode))
                    {
                        originPath.Add(nextNode, nextInstance);
                        fringe.Add(nextNode, totalCost);
                    }
                    else if (fringe[nextNode] > totalCost)
                    {
                        originPath.Remove(nextNode);
                        fringe.Remove(nextNode);

                        originPath.Add(nextNode, nextInstance);
                        fringe.Add(nextNode, totalCost);
                    }
                }
            }
            return null;
        }
Exemplo n.º 23
0
        protected void RunFormatTests(String workbookName, CellValue valueGetter)
        {

            OpenWorkbook(workbookName);

            ReadFlags(workbook);

            SortedList<string, object> runCategories = new SortedList<string, object>(StringComparer.InvariantCultureIgnoreCase);
            String RunCategoryList = flagString("Categories", "");
            Regex regex = new Regex("\\s*,\\s*");
            if (RunCategoryList != null)
            {
                foreach (string s in regex.Split(RunCategoryList))
                    if (!runCategories.ContainsKey(s))
                        runCategories.Add(s, null);
                runCategories.Remove(""); // this can be found and means nothing
            }

            ISheet sheet = workbook.GetSheet("Tests");
            int end = sheet.LastRowNum;
            // Skip the header row, therefore "+ 1"
            for (int r = sheet.FirstRowNum + 1; r <= end; r++)
            {
                IRow row = sheet.GetRow(r);
                if (row == null)
                    continue;
                int cellnum = 0;
                String expectedText = row.GetCell(cellnum).StringCellValue;
                String format = row.GetCell(1).StringCellValue;
                String testCategoryList = row.GetCell(3).StringCellValue;
                bool byCategory = RunByCategory(runCategories, testCategoryList);
                if ((expectedText.Length > 0 || format.Length > 0) && byCategory)
                {
                    ICell cell = row.GetCell(2);
                    tryFormat(r, expectedText, format, valueGetter, cell);
                }
            }
        }
Exemplo n.º 24
0
 public void DeleteServer(mcServer Server)
 {
     Servers.Remove(Server.HashKey);
 }
Exemplo n.º 25
0
    public void TestConTable() {
      SortedList list = new SortedList();
      for (int i = 0; i < 10; i++) {
	AHAddress address = new AHAddress(new RNGCryptoServiceProvider());
	SimNode node = new SimNode(address, NatType.Public, 0);
	list[address] = node;
      }
      SimNode n0 = (SimNode) list.GetByIndex(0);
      for (int i = 1; i < 10; i++) {
	SimNode n = (SimNode) list.GetByIndex(i);
	n0.AddConnection(n, (i%2 == 0)?ConType.Near:ConType.Shortcut);
      }
      Assert.AreEqual(n0.ConnectionTable.GetConnections(ConType.Near).Count, 4);
      Assert.AreEqual(n0.ConnectionTable.GetConnections(ConType.Shortcut).Count, 5);
      Assert.AreEqual(n0.ConnectionTable.GetAllConnections().Count, 9);      

      //make sure all connections are sorted in n0 table
      ArrayList n0_con = n0.ConnectionTable.GetAllConnections();
      for (int i = 0; i < n0_con.Count; i++) {
	AHAddress target = (AHAddress) n0_con[i];
	SimNode n = (SimNode) list.GetByIndex(i+1);
	Assert.AreEqual(target, n.LocalAddress);
      }
      //connection table is sorted (fine);
      SimNode n5 = (SimNode) list.GetByIndex(5);
      int idx = n0.ConnectionTable.IndexOf(n5.LocalAddress);
      Assert.IsTrue(idx > 0);
      Assert.AreEqual(idx, 4);


      idx = n0.ConnectionTable.IndexOf(n0.LocalAddress);
      Assert.IsTrue(idx < 0);
      idx = ~idx;
      Assert.IsTrue(idx == 0);

      for (int trials = 0; trials < 100; trials++) {
	AHAddress test_address = new AHAddress(new RNGCryptoServiceProvider());
	SimNode test_node = new SimNode(test_address, NatType.Public, 0);
	list[test_address] = test_node;
	int test_idx = list.IndexOfKey(test_address);
	//address of this newly generated address
	idx = n0.ConnectionTable.IndexOf(test_address);
	Assert.IsTrue(idx < 0);
	idx = ~idx;
	if (test_idx == 0) {
	  Assert.IsTrue(idx == 0);	
	} else {
	  Assert.IsTrue(idx == test_idx - 1);
	}
	list.Remove(test_address);
      }

      //do some unit tests for LeftInclusiveCount and RightInclusiveCount;
      for (int i = 1; i < 10; i++) {
	Assert.AreEqual(i-1, n0.ConnectionTable.LeftInclusiveCount(n0.LocalAddress, (AHAddress) list.GetKey(i)));
	//Console.WriteLine(n0.ConnectionTable.RightInclusiveCount(n0.LocalAddress, (AHAddress) list.GetKey(i)));	
	Assert.AreEqual(list.Count - i - 1, n0.ConnectionTable.RightInclusiveCount(n0.LocalAddress, (AHAddress) list.GetKey(i)));


      }

      

    }
Exemplo n.º 26
0
        /// <summary>
        /// this will return a SortedList, the key is the interface name,
        /// and the value is the type definition of the class that implements that interface;
        /// connectors are identified namespace ending with Connectors
        /// </summary>
        private static SortedList <string, TypeDeclaration>GetConnectors(List <CSParser>ACSFiles)
        {
            SortedList <string, TypeDeclaration>Result = new SortedList <string, TypeDeclaration>();

            foreach (CSParser CSFile in ACSFiles)
            {
                foreach (TypeDeclaration t in CSFile.GetClasses())
                {
                    if (t.UserData.ToString().EndsWith("Connectors"))
                    {
                        string Interface = CSParser.GetImplementedInterface(t);

                        if (Interface.Length > 0)
                        {
                            string ServerNamespace = t.UserData.ToString();
                            string ServerNamespaceWithClassName = ServerNamespace + "." + t.Name;
                            string key = ServerNamespaceWithClassName + ":" + Interface;

                            if (Result.ContainsKey(ServerNamespaceWithClassName))
                            {
                                // there is already the other part of the partial class

                                TypeDeclaration partialType = Result[ServerNamespaceWithClassName];

                                Result.Remove(ServerNamespaceWithClassName);

                                foreach (INode child in partialType.Children)
                                {
                                    t.AddChild(child);
                                }
                            }

                            Result.Add(key, t);

                            if (TLogging.DebugLevel > 1)
                            {
                                // TLogging.Log("adding new Connector " + key);
                            }
                        }
                        // either a webconnector, or a partial class
                        else
                        {
                            // web connectors don't derive from an interface, because the methods are static

                            string ServerNamespace = t.UserData.ToString();
                            string key = ServerNamespace + "." + t.Name;

                            if (Result.ContainsKey(key))
                            {
                                // partial class
                                foreach (INode child in t.Children)
                                {
                                    Result[key].AddChild(child);
                                }
                            }
                            else if (t.Name.EndsWith("UIConnector"))
                            {
                                // this could be the partial class of a UIConnector
                                // try to find a key that starts with this type
                                bool foundType = false;

                                foreach (string k in Result.Keys)
                                {
                                    if (k.StartsWith(key + ":"))
                                    {
                                        foundType = true;

                                        foreach (INode child in t.Children)
                                        {
                                            Result[k].AddChild(child);
                                        }
                                    }
                                }

                                if (!foundType)
                                {
                                    Result.Add(key, t);
                                }
                            }
                            else
                            {
                                Result.Add(key, t);
                            }

                            if (TLogging.DebugLevel > 1)
                            {
                                // TLogging.Log("adding new Connector " + key);
                            }
                        }
                    }
                }
            }

            return Result;
        }
Exemplo n.º 27
0
        private static SortedList<string, ResourceData> VerifyResourceNames(Dictionary<string, ResourceData> resourceList,
            CodeDomProvider codeProvider, List<ResourceErrorData> invalidResources, out Dictionary<string, string> reverseFixupTable)
        {
            reverseFixupTable = new Dictionary<string, string>(0, StringComparer.InvariantCultureIgnoreCase);

            SortedList<string, ResourceData> validResources = new SortedList<string, ResourceData>(resourceList.Count,
                StringComparer.InvariantCultureIgnoreCase);
            Dictionary<string, ResourceData>.Enumerator resourceListEnumerator = resourceList.GetEnumerator();
            try
            {
                while (resourceListEnumerator.MoveNext())
                {
                    KeyValuePair<string, ResourceData> resourcePair = resourceListEnumerator.Current;

                    string resourceKey = resourcePair.Key;
                    if ((string.Equals(resourceKey, ResMgrPropertyName) ||
                        string.Equals(resourceKey, CultureInfoPropertyName) ||
                        string.Equals(resourceKey, InternalSyncObjectPropertyName)) ||
                        (typeof(void) == resourcePair.Value.Type))
                    {
                        invalidResources.Add(new ResourceErrorData(resourceKey,
                            string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource, resourceKey)));

                        continue;
                    }

                    if (((resourceKey.Length <= 0) || (resourceKey[0] != '$')) &&
                        (((resourceKey.Length <= 1) || (resourceKey[0] != '>')) || (resourceKey[1] != '>')))
                    {
                        if (!codeProvider.IsValidIdentifier(resourceKey))
                        {
                            string adjustedResourceKey = VerifyResourceName(resourceKey, codeProvider, false);
                            if (adjustedResourceKey == null)
                            {
                                invalidResources.Add(new ResourceErrorData(resourceKey,
                                    string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource, resourceKey)));

                                continue;
                            }

                            string originalResourceKey;
                            if (reverseFixupTable.TryGetValue(adjustedResourceKey, out originalResourceKey))
                            {
                                if (!ContainsInvalidKey(invalidResources, originalResourceKey))
                                {
                                    invalidResources.Add(new ResourceErrorData(originalResourceKey,
                                        string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource,
                                            originalResourceKey)));
                                }

                                if (validResources.ContainsKey(adjustedResourceKey))
                                    validResources.Remove(adjustedResourceKey);

                                invalidResources.Add(new ResourceErrorData(resourceKey,
                                    string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource, resourceKey)));

                                continue;
                            }

                            reverseFixupTable[adjustedResourceKey] = resourceKey;
                            resourceKey = adjustedResourceKey;
                        }

                        ResourceData resourceData = resourcePair.Value;
                        if (!validResources.ContainsKey(resourceKey))
                        {
                            validResources.Add(resourceKey, resourceData);
                            continue;
                        }

                        string initialResourceKey;
                        if (reverseFixupTable.TryGetValue(resourceKey, out initialResourceKey))
                        {
                            if (!ContainsInvalidKey(invalidResources, initialResourceKey))
                            {
                                invalidResources.Add(new ResourceErrorData(initialResourceKey,
                                    string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource,
                                        initialResourceKey)));
                            }

                            reverseFixupTable.Remove(resourceKey);
                        }

                        invalidResources.Add(new ResourceErrorData(resourcePair.Key,
                            string.Format(CultureInfo.CurrentCulture, CannotCreatePropertyForResource,
                                resourcePair.Key)));
                        validResources.Remove(resourceKey);
                    }
                }
            }
            finally
            {
                resourceListEnumerator.Dispose();
            }

            return validResources;
        }
Exemplo n.º 28
0
        public void SelectIDs(int[] ids)
        {
            int theFirstSelectedIndex = -1;
            this.lvErrors.SelectedItems.Clear();

            if (ids == null || ids.Length == 0)
                return;

            SortedList theSortedIDs = new SortedList(ids.Length);
            for (int i = 0; i < ids.Length; i++)
                theSortedIDs.Add(ids[i], ids[i]);

            for (int i = 0; i < this.lvErrors.Items.Count; i++)
            {
                if (theSortedIDs.ContainsKey(this.lvErrors.Items[i].Tag))
                {
                    this.lvErrors.Items[i].Selected = true;
                    if (theFirstSelectedIndex == -1)
                        theFirstSelectedIndex = i;
                    theSortedIDs.Remove(this.lvErrors.Items[i].Tag);
                }

                if (theSortedIDs.Count == 0)
                    break;
            }

            if (theFirstSelectedIndex >= 0)
                this.lvErrors.EnsureVisible(theFirstSelectedIndex);
        }
Exemplo n.º 29
0
        public void TestIndexOfValueBasic()
        {
            StringBuilder sblMsg = new StringBuilder(99);
            //

            SortedList sl2 = null;

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

            string s1 = null;
            string s2 = null;
            string s3 = null;
            string s4 = null;

            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);

            //  with null - should return -1
            // null val
            j = sl2.IndexOfValue((string)null);
            Assert.Equal(-1, j);

            //  invalid val - should return -1
            j = sl2.IndexOfValue("No_Such_Val");
            Assert.Equal(-1, j);

            // null is a valid value
            sl2.Add("Key_0", null);
            j = sl2.IndexOfValue(null);
            Assert.NotEqual(-1, j);

            // first occurrence check
            sl2.Add("Key_1", "Val_Same");
            sl2.Add("Key_2", "Val_Same");

            j = sl2.IndexOfValue("Val_Same");
            Assert.Equal(1, j);

            sl2.Clear();

            //   Testcase: add few key-val pairs
            for (i = 0; i < 100; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg.Length = 0;
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                sl2.Add(s1, s2);
            }

            //
            //   Testcase: test IndexOfVal 
            //
            for (i = 0; i < sl2.Count; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_"); //key
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg.Length = 0;
                sblMsg.Append("val_"); //value
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                //  now use IndexOfKey and IndexOfVal to obtain the same object and check
                s3 = (string)sl2.GetByIndex(sl2.IndexOfKey(s1)); //Get the index of this key and then get object
                s4 = (string)sl2.GetByIndex(sl2.IndexOfValue(s2)); //Get the index of this val and then get object
                Assert.True(s3.Equals(s4));

                // now Get using the index obtained thru IndexOfKey () and compare it with s2
                s3 = (string)sl2.GetByIndex(sl2.IndexOfKey(s1));
                Assert.True(s3.Equals(s2));
            }

            //
            // Remove a key and then check
            //
            sblMsg.Length = 0;
            sblMsg.Append("key_50");
            s1 = sblMsg.ToString();

            sl2.Remove(s1); //removes "Key_50"
            j = sl2.IndexOfValue(s1);
            Assert.Equal(-1, j);
        }
Exemplo n.º 30
0
        public void UpdateErrors(ErrorDisplay[] updateList)
        {
            if (updateList == null || updateList.Length == 0)
                return;

            SortedList theIndex = new SortedList(updateList.Length);
            for (int i = 0; i < updateList.Length; i++)
                theIndex.Add(updateList[i].ID, updateList[i]);

            foreach (object theItemObj in this.lvErrors.Items)
            {
                ListViewItem theItem = (ListViewItem)theItemObj;

                if (theIndex.ContainsKey(theItem.Tag))
                {
                    ErrorDisplay theError = (ErrorDisplay)theIndex[theItem.Tag];

                    theItem.SubItems[0].Text = theError.ErrorType;
                    theItem.SubItems[1].Text = theError.ID.ToString();
                    theItem.SubItems[2].Text = theError.Status;
                    theItem.SubItems[3].Text = theError.CanDefer.ToString();
                    theItem.SubItems[4].Text = theError.CanExcept.ToString();

                    theIndex.Remove(theItem.Tag);
                }

                if (theIndex.Count == 0)
                    break;
            }
        }
Exemplo n.º 31
0
        public void Test01()
        {
            StringBuilder sblMsg = new StringBuilder(99);

            SortedList sl2 = null;

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

            string s1 = null;
            string s2 = null;
            string s3 = null;

            int i = 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: No_Such_Get
            Assert.Null((string)sl2["No_Such_Get"]);

            //   Testcase: add few key-val pairs
            for (i = 0; i < 100; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                sblMsg.Length = 0;
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                sl2.Add(s1, s2);
            }
            //
            //   Testcase: test Get (Object)
            //
            for (i = 0; i < sl2.Count; i++)
            {
                sblMsg.Length = 0;
                sblMsg.Append("key_");
                sblMsg.Append(i);
                s1 = sblMsg.ToString();

                s3 = (string)sl2[s1];

                sblMsg.Length = 0;
                sblMsg.Append("val_");
                sblMsg.Append(i);
                s2 = sblMsg.ToString();

                Assert.True(s3.Equals(s2));
            }

            //
            // Remove a key and then check
            //
            sblMsg.Length = 0;
            sblMsg.Append("key_50");
            s1 = sblMsg.ToString();

            sl2.Remove(s1); //removes "Key_50"
            s3 = (string)sl2[s1];
            Assert.Null(s3);

            //
            // Insert some items and change the current culture and verify we can still get every item
            //
            sl2 = new SortedList();

            CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
            var somePopularCultureNames = new string[] {
                    "cs-CZ","da-DK","de-DE","el-GR","en-US",
                    "es-ES","fi-FI","fr-FR","hu-HU","it-IT",
                    "ja-JP","ko-KR","nb-NO","nl-NL","pl-PL",
                    "pt-BR","pt-PT","ru-RU","sv-SE","tr-TR",
                    "zh-CN","zh-HK","zh-TW" };

            CultureInfo[] installedCultures = new CultureInfo[somePopularCultureNames.Length];
            string[] cultureDisplayNames = new string[installedCultures.Length];
            int uniqueDisplayNameCount = 0;
            foreach (string cultureName in somePopularCultureNames)
            {
                CultureInfo culture = new CultureInfo(cultureName);
                installedCultures[uniqueDisplayNameCount] = culture;
                cultureDisplayNames[uniqueDisplayNameCount] = culture.DisplayName;
                sl2.Add(cultureDisplayNames[uniqueDisplayNameCount], culture);

                uniqueDisplayNameCount++;
            }

            //In Czech ch comes after h if the comparer changes based on the current culture of the thread
            //we will not be able to find some items
            CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("cs-CZ");

            for (i = 0; i < uniqueDisplayNameCount; ++i)
            {
                Assert.Equal(installedCultures[i], sl2[installedCultures[i].DisplayName]);
            }

            CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-US");
        }
        /// <summary>
        /// Activates a log action.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="selectedPacket">The selected packet.</param>
        /// <returns><c>true</c> if log data tab should be updated.</returns>
        public override bool Activate(IExecutionContext context, PacketLocation selectedPacket)
        {
            PacketLog log = context.LogManager.GetPacketLog(selectedPacket.LogIndex);
            int selectedIndex = selectedPacket.PacketIndex;
            SortedList m_inventoryItems = new SortedList();

            int preAction = 0;
            int lastVaultPreAction = -1;
            int vaultNumber = -1;
            int VisibleSlots = 0xFF;
            for (int i = 0; i <= selectedIndex; i++)
            {
                Packet pak = log[i];
                if (pak is StoC_0x20_PlayerPositionAndObjectID_171)
                {
                    VisibleSlots = 0xFF;
                    m_inventoryItems.Clear();
                }
                else if (pak is StoC_0x02_InventoryUpdate)
                {
                    StoC_0x02_InventoryUpdate invPack = (StoC_0x02_InventoryUpdate)pak;
                    if (invPack.PreAction != 0 && invPack.PreAction != 10)
                        preAction = invPack.PreAction; // rememer last opened inventory action, if it not update
                    if (preAction > 10)
                        preAction -= 10;
                    if (invPack.PreAction == 1 || invPack.PreAction == 0 || invPack.PreAction == 11 || invPack.PreAction == 10)
                        VisibleSlots = invPack.VisibleSlots;
                    if (invPack.PreAction == 2)
                    {
                        for (byte j = 40; j < 80; j++)
                        {
                            if (m_inventoryItems.ContainsKey(j))
                                m_inventoryItems.Remove(j);
                        }
                    }
                    else if (invPack.PreAction == 7)
                    {
                        for (byte j = 80; j <= 95; j++)
                        {
                            if (m_inventoryItems.ContainsKey(j))
                                m_inventoryItems.Remove(j);
                        }
                    }
                    else if (invPack.PreAction == 3)
                    {
                        for (byte j = 110; j < 150; j++)
                        {
                            if (m_inventoryItems.ContainsKey(j))
                                m_inventoryItems.Remove(j);
                        }
                    }
                    else if (invPack.PreAction == 4 || invPack.PreAction == 5 || invPack.PreAction == 6)
                    {
                        lastVaultPreAction = invPack.PreAction;
                        vaultNumber = invPack.VisibleSlots;
                        for (byte j = 150; j < 250; j++)
                        {
                            if (m_inventoryItems.ContainsKey(j))
                                m_inventoryItems.Remove(j);
                        }
                    }
                    for (int j = 0; j < invPack.SlotsCount; j++)
                    {
                        StoC_0x02_InventoryUpdate.Item item = (StoC_0x02_InventoryUpdate.Item)invPack.Items[j];
                        if (item.name == null || item.name == "")
                        {
                            if (m_inventoryItems.ContainsKey(item.slot))
                                m_inventoryItems.Remove(item.slot);
                        }
                        else
                        {
                            if (m_inventoryItems.ContainsKey(item.slot))
                                m_inventoryItems[item.slot] = item;
                            else
                                m_inventoryItems.Add(item.slot, item);
                        }
                    }
                }
            }
            StringBuilder str = new StringBuilder();
            str.AppendFormat("VisibleSlots:0x{0:X2} last initialized preAction:{1}({2})\n", VisibleSlots, preAction, (StoC_0x02_InventoryUpdate.ePreActionType)preAction);
            eWindowType prevWindowType = eWindowType.Unknown;
            eWindowType windowType = eWindowType.Unknown;
            foreach (StoC_0x02_InventoryUpdate.Item item in m_inventoryItems.Values)
            {
            //				if (item.slot > 95 /*&& item.slot < 1000*/)
                {
                    string selected = " ";
                    if (item.slot >= 7 && item.slot <= 9)
                        windowType = eWindowType.Horse;
                    else if (item.slot >= 10 && item.slot <= 13)
                    {
                        windowType = eWindowType.Weapon;
                        if (((item.slot - 10) == (VisibleSlots & 0x0F)) || ((item.slot - 10) == ((VisibleSlots >> 4) & 0x0F)))
                            selected = "*";
                    }
                    else if (item.slot >= 14 && item.slot <= 17)
                        windowType = eWindowType.Quiver;
                    else if (item.slot >= 21 && item.slot <= 37)
                        windowType = eWindowType.Doll;
                    else if (item.slot >= 40 && item.slot <= 79)
                        windowType = eWindowType.Backpack;
                    else if (item.slot >= 80 && item.slot <= 95)
                        windowType = eWindowType.Horsebag;
                    else if (item.slot >= 110 && item.slot <= 149)
                        windowType = eWindowType.Vault;
                    else if (item.slot >= 150 && item.slot <= 249)
                        windowType = eWindowType.HouseVault;
                    if (windowType != prevWindowType)
                    {
                        str.Append('\n');
                        str.Append(windowType);
                        if (windowType == eWindowType.HouseVault)
                        {
                            if (lastVaultPreAction == 4 && vaultNumber != -1)
                            {
                                str.Append(' ');
                                str.Append(vaultNumber);
                            }
                            str.AppendFormat(" ({0})", (StoC_0x02_InventoryUpdate.ePreActionType)lastVaultPreAction);
                        }
                    }
                    str.AppendFormat("\n{16}slot:{0,-3} level:{1,-2} value1:0x{2:X2} value2:0x{3:X2} hand:0x{4:X2} damageType:0x{5:X2} objectType:0x{6:X2} weight:{7,-4} con:{8,-3} dur:{9,-3} qual:{10,-3} bonus:{11,-2} model:0x{12:X4} color:0x{13:X4} effect:0x{14:X2} \"{15}\"",
                        item.slot, item.level, item.value1, item.value2, item.hand, item.damageType, item.objectType, item.weight, item.condition, item.durability, item.quality, item.bonus, item.model, item.color, item.effect, item.name, selected);
                    if (item.name != null && item.name != "")
                        str.AppendFormat(" ({0})", (StoC_0x02_InventoryUpdate.eObjectType)item.objectType);
                    prevWindowType = windowType;
                }
            }

            InfoWindowForm infoWindow = new InfoWindowForm();
            infoWindow.Text = "Player inventory info (right click to close)";
            infoWindow.Width = 800;
            infoWindow.Height = 400;
            infoWindow.InfoRichTextBox.Text = str.ToString();
            infoWindow.StartWindowThread();

            return false;
        }
Exemplo n.º 33
0
        public static void Generate()
        {
            // Check if the unicode files exist
            {
                FileInfo f1 = new FileInfo("CompositionExclusions.txt");
                FileInfo f2 = new FileInfo("UnicodeData.txt");
                bool tmpBool;
                if (File.Exists(f1.FullName))
                    tmpBool = true;
                else
                    tmpBool = Directory.Exists(f1.FullName);
                bool tmpBool2;
                if (File.Exists(f2.FullName))
                    tmpBool2 = true;
                else
                    tmpBool2 = Directory.Exists(f2.FullName);
                if (!tmpBool || !tmpBool2)
                {
                    Console.WriteLine("Unable to find UnicodeData.txt or CompositionExclusions.txt.");
                    Console.WriteLine("Please download the latest version of these file from:");
                    Console.WriteLine("http://www.unicode.org/Public/UNIDATA/");
                    System.Environment.Exit(1);
                }
            }

            ArrayList exclusions = new ArrayList();
            {
                StreamReader r = new StreamReader("CompositionExclusions.txt", System.Text.Encoding.Default);
                string line;
                while (null != (line = r.ReadLine()))
                {
                    line = stripComment(line);
                    line = line.Trim();
                    if (line.Length == 0)
                    {
                        // Empty line
                    }
                    else if (line.Length == 4)
                    {
                        exclusions.Add(line);
                    }
                    else
                    {
                        // Skip code points > 0xffff
                    }
                }
                r.Close();
            }

            // Read UnicodeData

            SortedList canonical = new SortedList();
            SortedList compatibility = new SortedList();
            SortedList combiningClasses = new SortedList();
            {
                StreamReader r = new StreamReader("UnicodeData.txt", Encoding.Default);
                string line;
                while (null != (line = r.ReadLine()))
                {
                    line = stripComment(line);
                    line = line.Trim();

                    if (line.Length == 0)
                    {
                        // Empty line
                    }
                    else
                    {
                        string[] f = split(line, ';');

                        if (f[0].Length == 4)
                        {
                            if (!f[5].Equals(""))
                            {
                                if (isCompatibilityMapping(f[5]))
                                {
                                    compatibility[f[0]] = stripCompatibilityTag(f[5]);
                                }
                                else
                                {
                                    compatibility[f[0]] = f[5];
                                    if (!exclusions.Contains(f[0]))
                                    {
                                        canonical[f[0]] = f[5];
                                    }
                                }
                            }
                            if (!f[3].Equals("0"))
                            {
                                //UPGRADE_TODO: Method 'java.lang.Integer.parseInt' was converted to 'System.Convert.ToInt32' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                                combiningClasses[(int)System.Convert.ToInt32(f[0], 16)] = f[3];
                            }
                        }
                        else
                        {
                            // Skip code points > 0xffff
                        }
                    }
                }
                r.Close();
            }

            // Recursively apply compatibility mappings
            while (true)
            {
                bool replaced = false;

                IEnumerator i = new HashSet(compatibility.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string)i.Current;
                    string v = (string)compatibility[k];

                    string d = decompose(v, compatibility);
                    if (!d.Equals(v))
                    {
                        replaced = true;
                        compatibility[k] = d;
                    }
                }

                if (!replaced)
                {
                    break;
                }
            }

            // Eliminate duplicate mappings
            SortedList compatibilityKeys = new SortedList();
            ArrayList compatibilityMappings = new ArrayList();
            {
                IEnumerator i = new HashSet(compatibility.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string)i.Current;
                    string v = (string)compatibility[k];

                    int index = compatibilityMappings.IndexOf(v);
                    if (index == -1)
                    {
                        index = compatibilityMappings.Count;
                        compatibilityMappings.Add(v);
                    }
                    compatibilityKeys[k] = (int)index;
                }
            }

            // Create composition tables
            SortedList firstMap = new SortedList();
            SortedList secondMap = new SortedList();
            {
                IEnumerator i = new HashSet(canonical.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string)i.Current;
                    string v = (string)canonical[k];

                    string[] s = split(v, ' ');

                    if (s.Length == 2)
                    {
                        // If both characters have the same combining class, they
                        // won't be combined (in the sequence AB, B is blocked from
                        // A if both have the same combining class)
                        string cc1 = (string)combiningClasses[(int)System.Convert.ToInt32(s[0], 16)];
                        string cc2 = (string)combiningClasses[(int)System.Convert.ToInt32(s[1], 16)];
                        if (cc1 != null || (cc1 != null && cc1.Equals(cc2)))
                        {
                            // Ignore this composition
                            // TODO check this
                            //i.remove();
                            canonical.Remove(k);
                            continue;
                        }

                        if (firstMap.ContainsKey(s[0]))
                        {
                            int c = (int)firstMap[s[0]];
                            firstMap[s[0]] = (int)(c + 1);
                        }
                        else
                        {
                            firstMap[s[0]] = 1;
                        }

                        if (secondMap.ContainsKey(s[1]))
                        {
                            int c = (int)secondMap[s[1]];
                            secondMap[s[1]] = (int)(c + 1);
                        }
                        else
                        {
                            secondMap[s[1]] = 1;
                        }
                    }
                    else if (s.Length > 2)
                    {
                        Console.WriteLine("? wrong canonical mapping for " + k);
                        System.Environment.Exit(1);
                    }
                }
            }

            SortedList singleFirstComposition = new SortedList();
            SortedList singleSecondComposition = new SortedList();
            SortedList complexComposition = new SortedList();

            int composeLookupMax = 0;
            {
                IEnumerator i = new HashSet(canonical.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string) i.Current;
                    string v = (string) canonical[k];

                    string[] s = split(v, ' ');

                    if (s.Length == 2)
                    {
                        // TODO, check this
                        int first = 0;
                        if(firstMap.Contains(s[0]))
                            first = (int) firstMap[s[0]];

                        int second = 0;
                        if (secondMap.Contains(s[1]))
                            second = (int) secondMap[s[1]];
                        // TODO, check this

                        if (first == 1)
                        {
                            singleFirstComposition[s[0]] = new string[] { s[1], k };
                            composeLookupMax = System.Math.Max(composeLookupMax, System.Convert.ToInt32(s[0], 16));
                        }
                        else if (second == 1)
                        {
                            singleSecondComposition[s[1]] = new string[] { s[0], k };
                            composeLookupMax = System.Math.Max(composeLookupMax, System.Convert.ToInt32(s[1], 16));
                        }
                        else
                        {
                            if (complexComposition.ContainsKey(s[0]))
                            {
                                SortedList m = (SortedList)complexComposition[s[0]];
                                if (m.ContainsKey(s[1]))
                                {
                                    Console.WriteLine("? ambiguous canonical mapping for " + s[0]);
                                    System.Environment.Exit(1);
                                }
                                m[s[1]] = k;
                            }
                            else
                            {
                                SortedList m = new SortedList();
                                m[s[1]] = k;
                                complexComposition[s[0]] = m;
                            }
                            composeLookupMax = System.Math.Max(composeLookupMax, System.Convert.ToInt32(s[0], 16));
                            composeLookupMax = System.Math.Max(composeLookupMax, System.Convert.ToInt32(s[1], 16));
                        }
                    }
                }
            }

            Console.WriteLine("Generating CombiningClass.cs file...");

            // Dump combining classes
            {
                StreamWriter w = new StreamWriter("CombiningClass.cs", false, Encoding.Default);
                w.WriteLine("// Do not edit !!!");
                w.WriteLine("// this file is generated automatically");
                w.WriteLine();
                w.WriteLine("public class CombiningClass");
                w.WriteLine("{");
                w.WriteLine("\tpublic static readonly int[,] c = new int[,] {");
                System.Text.StringBuilder index = new System.Text.StringBuilder();

                int count = 0;

                for (int i = 0; i < 256; i++)
                {
                    bool empty = true;

                    StringBuilder page = new StringBuilder();
                    page.Append("    { /* Page " + i + " */");

                    for (int j = 0; j < 256; j++)
                    {
                        int c = (int)((i << 8) + j);
                        string cc = (string)combiningClasses[c];

                        if (0 == (j & 31))
                        {
                            page.Append("\r\n      ");
                        }
                        if (cc == null)
                        {
                            page.Append("0, ");
                        }
                        else
                        {
                            page.Append(cc + ", ");
                            empty = false;
                        }
                    }
                    page.Append("\r\n    },");

                    index.Append("    ");

                    if (!empty)
                    {
                        w.WriteLine(page.ToString());
                        index.Append(count++);
                        index.Append(",\r\n");
                    }
                    else
                    {
                        index.Append("-1,\r\n");
                    }
                }
                w.WriteLine("  };\r\n");

                w.WriteLine("\tpublic static readonly int[] i = new int[] {");
                w.Write(index.ToString());
                w.WriteLine("  };");
                w.WriteLine("}");
                w.Close();
            }

            //Console.WriteLine(" Ok.");
            Console.WriteLine("Generating DecompositionKeys.cs file...");

            // Dump compatibility decomposition
            {
                StreamWriter w = new StreamWriter("DecompositionKeys.cs", false, Encoding.Default);
                w.WriteLine("// Do not edit !!!");
                w.WriteLine("// this file is generated automatically");
                w.WriteLine();
                w.WriteLine("public class DecompositionKeys");
                w.WriteLine("{");

                w.WriteLine("\tpublic static readonly int[] k = new int[] {");
                IEnumerator i = new HashSet(compatibilityKeys.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string)i.Current;
                    int index = ((int)compatibilityKeys[k]);
                    w.WriteLine("    '\\u" + k + "', " + index + ",");
                }
                w.WriteLine("  };");
                w.WriteLine("}");
                w.Close();
            }

            //Console.WriteLine(" Ok.");
            Console.WriteLine("Generating DecompositionMappings.cs file...");

            {
                StreamWriter w = new StreamWriter("DecompositionMappings.cs", false, Encoding.Default);
                w.WriteLine("// Do not edit !!!");
                w.WriteLine("// this file is generated automatically");
                w.WriteLine();
                w.WriteLine("public class DecompositionMappings");
                w.WriteLine("{");
                w.WriteLine("\tpublic static readonly string[] m = new string[] {");
                IEnumerator i = compatibilityMappings.GetEnumerator();
                while (i.MoveNext())
                {
                    string m = (string)i.Current;
                    w.WriteLine("    \"" + toString(m) + "\",");
                }
                w.WriteLine("  };");
                w.WriteLine("}");
                w.Close();
            }

            //Console.WriteLine(" Ok.");
            Console.WriteLine("Generating Composition.cs file...");

            // Dump canonical composition
            {
                StreamWriter w = new StreamWriter("Composition.cs", false, Encoding.Default);
                w.WriteLine("// Do not edit !!!");
                w.WriteLine("// this file is generated automatically");
                w.WriteLine();
                w.WriteLine("public class Composition");
                w.WriteLine("{");

                IEnumerator i;
                int index = 0;

                SortedList indices = new SortedList();

                i = new HashSet(complexComposition.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string s0 = (string)i.Current;
                    indices[(int)System.Convert.ToInt32(s0, 16)] = (int)index;
                    index++;
                }

                int multiSecondStart = index;
                w.WriteLine("\t/* jagged Array */");
                w.WriteLine("\tpublic static readonly char[][] multiFirst = new char[][] {");
                //w.WriteLine("  public final static char[][] multiFirst = new char[][] {");
                i = new HashSet(complexComposition.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string s0 = (string)i.Current;
                    SortedList m = (SortedList)complexComposition[s0];

                    SortedList line = new SortedList();
                    int maxIndex = 1;

                    System.Collections.IEnumerator i2 = new HashSet(m.Keys).GetEnumerator();
                    while (i2.MoveNext())
                    {
                        string s1 = (string)i2.Current;
                        string k = (string)m[s1];

                        int s1i = (int)System.Convert.ToInt32(s1, 16);

                        if (!indices.ContainsKey(s1i))
                        {
                            indices[s1i] = (int)index;
                            index++;
                        }
                        line[indices[s1i]] = k;
                        maxIndex = System.Math.Max(maxIndex, ((int)indices[s1i]));
                    }

                    w.Write("\tnew char[] { ");
                    for (int j = multiSecondStart; j <= maxIndex; j++)
                    {
                        if (line.ContainsKey((int)j))
                        {
                            string s = (string)line[(int)j];
                            w.Write("'" + toString(s) + "', ");
                        }
                        else
                        {
                            //w.Write("       0, ");
                            w.Write("'" + toString("0000") + "', ");
                        }
                    }
                    w.WriteLine("},");
                }
                w.WriteLine("  };");

                int singleFirstStart = index;

                w.WriteLine("\tpublic static readonly char[,] singleFirst = new char[,] {");
                i = new HashSet(singleFirstComposition.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string)i.Current;
                    string[] v = ((string[])singleFirstComposition[k]);
                    w.WriteLine("    { '" + toString(v[0]) + "', '" + toString(v[1]) + "' },");

                    if (indices.ContainsKey((int)System.Convert.ToInt32(k, 16)))
                    {
                        Console.WriteLine(k + " already indexed!");
                    }

                    indices[(int)System.Convert.ToInt32(k, 16)] = (int)index;
                    index++;
                }
                w.WriteLine("  };");

                int singleSecondStart = index;

                w.WriteLine("\tpublic static readonly char[,] singleSecond = new char[,] {");
                i = new HashSet(singleSecondComposition.Keys).GetEnumerator();
                while (i.MoveNext())
                {
                    string k = (string)i.Current;
                    string[] v = ((string[])singleSecondComposition[k]);
                    w.WriteLine("    { '" + toString(v[0]) + "', '" + toString(v[1]) + "' },");

                    indices[(int)System.Convert.ToInt32(k, 16)] = (int)index;
                    index++;
                }
                w.WriteLine("  };");

                w.WriteLine("\tpublic static readonly int multiSecondStart = " + multiSecondStart + ";");
                w.WriteLine("\tpublic static readonly int singleFirstStart = " + singleFirstStart + ";");
                w.WriteLine("\tpublic static readonly int singleSecondStart = " + singleSecondStart + ";");

                System.Text.StringBuilder compositionPages = new System.Text.StringBuilder();

                w.WriteLine("\tpublic static readonly int[] composePage = new int[] {");
                int pageCount = 0;
                for (int j = 0; j * 256 < composeLookupMax + 255; j++)
                {
                    bool empty = true;
                    StringBuilder page = new StringBuilder();
                    for (int k = 0; k < 256; k++)
                    {
                        if (k % 16 == 0)
                        {
                            page.Append("\r\n      ");
                        }
                        if (indices.ContainsKey((int)(j * 256 + k)))
                        {
                            page.Append(indices[(int)(j * 256 + k)]);
                            page.Append(", ");
                            empty = false;
                        }
                        else
                        {
                            page.Append("-1, ");
                        }
                    }

                    if (empty)
                    {
                        w.WriteLine("    -1,");
                    }
                    else
                    {
                        w.WriteLine("    " + pageCount + ",");
                        compositionPages.Append("\t{");
                        compositionPages.Append(page);
                        compositionPages.Append("\r\n    },\r\n");
                        pageCount++;
                    }
                }
                w.WriteLine("  };");
                //w.WriteLine("\t/* jagged Array */");
                w.WriteLine("\tpublic static readonly int[,] composeData = new int[,] {");
                w.Write(compositionPages);
                w.WriteLine("  };");
                w.WriteLine("}");
                w.Close();
            }

            //Console.WriteLine(" Ok.");
            Console.WriteLine("Finished!");
        }
Exemplo n.º 34
0
        // 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);
        }
Exemplo n.º 35
0
        /// <summary>
        /// Resolve the dependencies for a table (this is a helper method for GetSortedTableNames).
        /// </summary>
        /// <param name="tableName">The name of the table to resolve.</param>
        /// <param name="unsortedTableNames">The unsorted table names.</param>
        /// <param name="sortedTableNames">The sorted table names.</param>
        private void ResolveTableDependencies(string tableName, SortedList unsortedTableNames, StringCollection sortedTableNames)
        {
            unsortedTableNames.Remove(tableName);

            foreach (ColumnDefinition columnDefinition in this.tableDefinitions[tableName].Columns)
            {
                // no dependency to resolve because this column doesn't reference another table
                if (null == columnDefinition.KeyTable)
                {
                    continue;
                }

                foreach (string keyTable in columnDefinition.KeyTable.Split(';'))
                {
                    if (tableName == keyTable)
                    {
                        continue; // self-referencing dependency
                    }
                    else if (sortedTableNames.Contains(keyTable))
                    {
                        continue; // dependent table has already been sorted
                    }
                    else if (!this.tableDefinitions.Contains(keyTable))
                    {
                        this.core.OnMessage(WixErrors.MissingTableDefinition(keyTable));
                    }
                    else if (unsortedTableNames.Contains(keyTable))
                    {
                        this.ResolveTableDependencies(keyTable, unsortedTableNames, sortedTableNames);
                    }
                    else
                    {
                        // found a circular dependency, so ignore it (this assumes that the tables will
                        // use a finalize method to nest their elements since the ordering will not be
                        // deterministic
                    }
                }
            }

            sortedTableNames.Add(tableName);
        }
Exemplo n.º 36
0
 public override void Remove(object key)
 {
     lock (host.SyncRoot) {
         host.Remove(key);
     }
 }