public void UnitPt_oCompareTo() { var objectSortedList = new System.Collections.SortedList(); Product pt1 = new Product(new int[] { 3, 4, 5 }); Product pt2 = new Product(pt1); Product pt3 = new Product(pt1); pt1.Rank = 10; pt2.Rank = 30; pt3.Rank = 20; objectSortedList.Add(pt1, 10); objectSortedList.Add(pt2, 30); objectSortedList.Add(pt3, 20); int expectedValue = 10; foreach (System.Collections.DictionaryEntry item in objectSortedList) { int actualIndex = (int)item.Value; Assert.AreEqual(expectedValue, actualIndex); expectedValue += 10; } Assert.AreEqual(40, expectedValue); }
/// <summary> /// добавить типы по шаблону /// </summary> /// <param name="dataObjectTypeTmplate"></param> /// <param name="usageTypes"></param> public void AddUseTypesAs(Type dataObjectTypeTmplate, params Type[] usageTypes) { lock (m_objNull) { ICSSoft.STORMNET.Collections.TypesArrayList types; if (usetypeascollection.Contains(dataObjectTypeTmplate)) { types = (ICSSoft.STORMNET.Collections.TypesArrayList)usetypeascollection[dataObjectTypeTmplate]; types.Clear(); } else if (usageTypes == null) { types = new ICSSoft.STORMNET.Collections.TypesArrayList(); types.Add(dataObjectTypeTmplate); usetypeascollection.Add(dataObjectTypeTmplate, types); return; } else { types = new ICSSoft.STORMNET.Collections.TypesArrayList(); typeusagecollection.Add(dataObjectTypeTmplate, types); } foreach (Type t in usageTypes) { if (!types.Contains(t)) { types.Add(t); } } } }
IActivity getMatchingLogActivity(int index, int count) { //Note: the activity list may not be in perfect order, sort the tail if (activities == null || activities.Count != count) { activities = new System.Collections.SortedList(count); int logIndex = Plugin.Instance.Application.Logbook.Activities.Count - 1; for (int i = 0; i < count; i++) { //TBD: Only use My Activities and ignore My Friends Activities? while (logIndex >= 0 && activities.ContainsKey(Plugin.Instance.Application.Logbook.Activities[logIndex].StartTime)) { logIndex--; } if (logIndex > 0) { IActivity activity = Plugin.Instance.Application.Logbook.Activities[logIndex]; activities.Add(activity.StartTime, activity); } else { activities.Add(DateTime.MinValue, null); } } } return((IActivity)activities.GetByIndex(index)); }
public void Add(string key, T info) { if (list.ContainsKey(key)) { list.Remove(key); } list.Add(key, info); }
private void GlavnaForma_Load(object sender, EventArgs e) { komboboks.Add("PO IMENU", new ListaVozaca.SortDelagate(this.SortIme)); komboboks.Add("PO PREZIMENU", new ListaVozaca.SortDelagate(this.SortPrezime)); komboboks.Add("PO BROJU VOZACKE DOZVOLE", new ListaVozaca.SortDelagate(this.SortVozacka)); cbxBiraj.DataSource = komboboks.Keys; lblTacnoVreme.Text = ""; timer1.Start(); }
public void ChangeSizes() { m_nWhichSizes = (m_nWhichSizes + 1) % 3; System.Collections.SortedList aSizes = new System.Collections.SortedList(); switch (m_nWhichSizes) { case 0: aSizes.Add(0.0, 1.0); aSizes.Add(0.6, 1.0); aSizes.Add(0.8, 0.1); aSizes.Add(1.0, 0.9); break; case 1: aSizes.Add(0.0, 1.0); aSizes.Add(1.0, 1.0); break; default: aSizes.Add(0.0, 0.3); aSizes.Add(1.0, 0.01); aSizes.Add(1.1, 0.01); break; } this.SetSizeList(aSizes); }
public void IntegerSortedList_ShouldBehaveSame() { var sysList = new System.Collections.SortedList(); var mmList = new MarkerMetro.Unity.WinLegacy.Plugin.Collections.SortedList(); sysList.Add(1, "one"); sysList.Add(0, "zero"); sysList.Add(2, "two"); mmList.Add(1, "one"); mmList.Add(0, "zero"); mmList.Add(2, "two"); CollectionAssert.AreEquivalent(sysList.Values, mmList.Values); }
public void IntegerSortedList_SecondElementByIndex_ShouldBeTheSame() { var sysList = new System.Collections.SortedList(); var mmList = new MarkerMetro.Unity.WinLegacy.Plugin.Collections.SortedList(); sysList.Add(1, "one"); sysList.Add(0, "zero"); sysList.Add(2, "two"); mmList.Add(1, "one"); mmList.Add(0, "zero"); mmList.Add(2, "two"); Assert.AreEqual(sysList.GetByIndex(1), mmList.GetByIndex(1)); }
public void Add(ProCommon.Communal.Account acc) { if (!_list.ContainsKey(acc.ID)) { _list.Add(acc.ID, acc); } }
/// <summary> /// Gets all User data source names for the local machine. /// </summary> public System.Collections.SortedList GetUserDataSourceNames() { System.Collections.SortedList dsnList = new System.Collections.SortedList(); // get user dsn's Microsoft.Win32.RegistryKey reg = (Microsoft.Win32.Registry.LocalMachine).OpenSubKey("Software"); if (reg != null) { reg = reg.OpenSubKey("ODBC"); if (reg != null) { reg = reg.OpenSubKey("ODBCINST.INI"); if (reg != null) { reg = reg.OpenSubKey("ODBC Drivers"); if (reg != null) { // Get all DSN entries defined in DSN_LOC_IN_REGISTRY. foreach (string sName in reg.GetValueNames()) { dsnList.Add(sName, DataSourceType.User); } } try { reg.Close(); } catch { /* ignore this exception if we couldn't close */ } } } } return(dsnList); }
public InterpolatorColor(System.Collections.SortedList colorKeyFrames) { //_colors = a_colorKeyFrames; _interpolators = new List<Interpolator>(); for (int i = 0; i < 4; i++) { Interpolator ip = new Interpolator(); _interpolators.Add(ip); System.Collections.SortedList a = new System.Collections.SortedList(); for (int nClrNum = 0; nClrNum < colorKeyFrames.Count; nClrNum++) { Color clr = (Color)colorKeyFrames.GetByIndex(nClrNum); double dVal = 0; if (i == 0) dVal = clr.A; else if (i == 1) dVal = clr.R; else if (i == 2) dVal = clr.G; else if (i == 3) dVal = clr.B; a.Add(colorKeyFrames.GetKey(nClrNum), dVal); } ip.KeyFramesList = a; } }
private void vGeraPersonalizavel() { System.Text.StringBuilder strbPersonalizavel = new System.Text.StringBuilder(); System.Collections.SortedList sortLstDSEPE = new System.Collections.SortedList(new mdlComponentesColecoes.clsComparerNumbersTexts()); // Ordenando for (int i = 0; i < m_typDatSetDSEsPEs.tbDSEsPEs.Rows.Count; i++) { mdlDataBaseAccess.Tabelas.XsdTbDSEsPEs.tbDSEsPEsRow dtrwDSEPE = (mdlDataBaseAccess.Tabelas.XsdTbDSEsPEs.tbDSEsPEsRow)m_typDatSetDSEsPEs.tbDSEsPEs.Rows[i]; if ((dtrwDSEPE.RowState != System.Data.DataRowState.Deleted) && (dtrwDSEPE.nIdExportador == m_nIdExportador) && (dtrwDSEPE.strIdPE == m_strIdPe)) { sortLstDSEPE.Add(GetDSENumero(dtrwDSEPE.nIdDSE), dtrwDSEPE); } } // Inserindo for (int i = 0; i < sortLstDSEPE.Count; i++) { mdlDataBaseAccess.Tabelas.XsdTbDSEsPEs.tbDSEsPEsRow dtrwDSEPE = (mdlDataBaseAccess.Tabelas.XsdTbDSEsPEs.tbDSEsPEsRow)sortLstDSEPE.GetByIndex(i); if (strbPersonalizavel.ToString() != "") { strbPersonalizavel.Append(" , "); } strbPersonalizavel.Append(sortLstDSEPE.GetKey(i).ToString()); } m_strPersonalizavel = strbPersonalizavel.ToString(); if (m_typDatSetPes.tbPEs.Rows.Count > 0) { mdlDataBaseAccess.Tabelas.XsdTbPes.tbPEsRow dtrwPE = (mdlDataBaseAccess.Tabelas.XsdTbPes.tbPEsRow)m_typDatSetPes.tbPEs.Rows[0]; dtrwPE.mstrDSE = m_strPersonalizavel; } }
private static System.Collections.SortedList getDataSourceNames(Microsoft.Win32.RegistryKey baseReg) { System.Collections.SortedList dsnList = new System.Collections.SortedList(); // get system dsn's Microsoft.Win32.RegistryKey reg = baseReg.OpenSubKey("Software"); if (reg != null) { reg = reg.OpenSubKey("ODBC"); if (reg != null) { reg = reg.OpenSubKey("ODBC.INI"); if (reg != null) { reg = reg.OpenSubKey("ODBC Data Sources"); if (reg != null) { // Get all DSN entries defined in DSN_LOC_IN_REGISTRY. foreach (string sName in reg.GetValueNames()) { dsnList.Add(sName, sName); } } try { reg.Close(); } catch { /* ignore this exception if we couldn't close */ } } } } return(dsnList); }
private void vArmadoresRefresh(ref System.Windows.Forms.ListView lvArmadores) { lvArmadores.Items.Clear(); // Sorting System.Collections.SortedList sortListArmadores = new System.Collections.SortedList(); foreach (mdlDataBaseAccess.Tabelas.XsdTbArmadores.tbArmadoresRow dtrwArmador in m_typDatSetArmadores.tbArmadores.Rows) { if ((dtrwArmador.RowState != System.Data.DataRowState.Deleted) && (!dtrwArmador.IsstrNomeNull())) { if (!sortListArmadores.ContainsKey(dtrwArmador.strNome)) { sortListArmadores.Add(dtrwArmador.strNome, dtrwArmador); } } } // Insert for (int i = 0; i < sortListArmadores.Count; i++) { mdlDataBaseAccess.Tabelas.XsdTbArmadores.tbArmadoresRow dtrwArmadorInserir = (mdlDataBaseAccess.Tabelas.XsdTbArmadores.tbArmadoresRow)sortListArmadores.GetByIndex(i); System.Windows.Forms.ListViewItem lviInsert = lvArmadores.Items.Add(dtrwArmadorInserir.strNome); lviInsert.Tag = dtrwArmadorInserir.nIdArmador; if ((m_nIdSelect != -1) && (dtrwArmadorInserir.nIdArmador == m_nIdSelect)) { lviInsert.Selected = true; m_nIdSelect = -1; } } }
/// <summary> /// 方法:添加相机实体 /// </summary> /// <param name="cam"></param> public void Add(Camera cam) { if (!_list.ContainsKey(cam.ID)) { _list.Add(cam.ID, cam); } }
/// <summary> /// Gets all System data source names for the local machine. /// </summary> public System.Collections.SortedList GetSystemDataSourceNames() { System.Collections.SortedList dsnList = new System.Collections.SortedList(); // get system dsn's Microsoft.Win32.RegistryKey reg = (Microsoft.Win32.Registry.LocalMachine).OpenSubKey("Software"); if (reg != null) { reg = reg.OpenSubKey("ODBC"); if (reg != null) { reg = reg.OpenSubKey("ODBC.INI"); if (reg != null) { reg = reg.OpenSubKey("ODBC Data Sources"); if (reg != null) { // Get all DSN entries defined in DSN_LOC_IN_REGISTRY. foreach (string sName in reg.GetValueNames()) { dsnList.Add(sName, DataSourceType.System); } } try { reg.Close(); } catch { /* ignore this exception if we couldn't close */ } } } } return dsnList; }
public void Add(ProCommon.Communal.WebProperty webProperty) { if (!_list.ContainsKey(webProperty.ID)) { _list.Add(webProperty.ID, webProperty); } }
private void cb_Bank_Deposit_Type_SelectedIndexChanged(object sender, EventArgs e) { try { Lst_Bank_Deposit_Type = new System.Collections.SortedList(); if (cb_Bank_Deposit_Type.ValueMember != null && cb_Bank_Deposit_Type.ValueMember != "" && cb_Bank_Deposit_Type.SelectedIndex > -1) { DataTable dt = DataClass.RetrieveData("SELECT BDT.Bank_Deposit_Type_ID, BDT.Acct_Deposit_From, BDT.Credit_Card_Deposit, BDT.CC_Discount_Acct, BDT.CC_Fees, BDT.Cash_Short_Over_Acct, BDT.Override_Fees, BDT.Bank_Account_ID, BAS.Bank_GL_Account FROM dbo.Bank_Deposit_Type AS BDT INNER JOIN dbo.Bank_Account_Setup AS BAS ON BDT.Bank_Account_ID = BAS.Bank_Account_ID WHERE (BDT.Bank_Deposit_Type_ID = " + cb_Bank_Deposit_Type.SelectedValue.ToString() + ")"); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Columns.Count; i++) { Lst_Bank_Deposit_Type.Add(dt.Columns[i].ColumnName, dt.Rows[0][i]); } lblCashOverSort.Visible = !(bool)Lst_Bank_Deposit_Type["Credit_Card_Deposit"]; lblCredit_Fees.Visible = (bool)Lst_Bank_Deposit_Type["Credit_Card_Deposit"]; if ((bool)Lst_Bank_Deposit_Type["Credit_Card_Deposit"]) { txtCash_Fees.ReadOnly = !(bool)Lst_Bank_Deposit_Type["Override_Fees"]; Calc_CC_Fees(); } else { txtCash_Fees.ReadOnly = false; } } } } catch (Exception ex) { MessageBox.Show(ex.Message, "General Ledger"); } }
public void Add(ProCommon.Communal.PlcProperty plcProperty) { if (!_list.ContainsKey(plcProperty.ID)) { _list.Add(plcProperty.ID, plcProperty); } }
protected void carregaDadosInterfaceEndereco(ref mdlComponentesGraficos.TextBox ctbEndereco, ref mdlComponentesGraficos.TextBox ctbCidade, ref mdlComponentesGraficos.TextBox ctbEstado, ref mdlComponentesGraficos.ComboBox cbPaises) { try { System.Collections.SortedList srlPaises = new System.Collections.SortedList(); foreach (mdlDataBaseAccess.Tabelas.XsdTbPaises.tbPaisesRow dtrwRowTbPaisesSorted in m_typDatSetTbPaises.tbPaises.Rows) { srlPaises.Add(dtrwRowTbPaisesSorted.nmPais, dtrwRowTbPaisesSorted); } mdlDataBaseAccess.Tabelas.XsdTbPaises.tbPaisesRow dtrwRowTbPaises; ctbEndereco.Text = m_strEnderecoEntrega; ctbCidade.Text = m_strCidadeEntrega; ctbEstado.Text = m_strEstadoEntrega; if (srlPaises != null) { for (int nCont = 0; nCont < srlPaises.Count; nCont++) { dtrwRowTbPaises = (mdlDataBaseAccess.Tabelas.XsdTbPaises.tbPaisesRow)srlPaises.GetByIndex(nCont); cbPaises.AddItem(dtrwRowTbPaises.nmPais, dtrwRowTbPaises.idPais); if (dtrwRowTbPaises.idPais == m_nIdPais) { cbPaises.SelectedIndex = nCont; m_strPaisEntrega = dtrwRowTbPaises.nmPais; } } } } catch (Exception err) { Object erro = err; m_cls_ter_tratadorErro.trataErro(ref erro); } }
protected void carregaDadosInterfacePaises(ref mdlComponentesGraficos.ComboBox cbPaises) { try { System.Collections.SortedList srlPaises = new System.Collections.SortedList(); foreach (mdlDataBaseAccess.Tabelas.XsdTbPaises.tbPaisesRow dtrwRowTbPaisesSorted in m_typDatSetTbPaises.tbPaises.Rows) { srlPaises.Add(dtrwRowTbPaisesSorted.nmPais, dtrwRowTbPaisesSorted); } mdlDataBaseAccess.Tabelas.XsdTbPaises.tbPaisesRow dtrwRowTbPaises; if (srlPaises != null) { for (int nCont = 0; nCont < srlPaises.Count; nCont++) { dtrwRowTbPaises = (mdlDataBaseAccess.Tabelas.XsdTbPaises.tbPaisesRow)srlPaises.GetByIndex(nCont); cbPaises.AddItem(dtrwRowTbPaises.nmPais, dtrwRowTbPaises.idPais); } } } catch (Exception err) { Object erro = err; m_cls_ter_tratadorErro.trataErro(ref erro); } }
/// <summary> /// Given the 2 maps fills a document for 1 word. /// </summary> private static int Index(System.Collections.IDictionary word2Nums, System.Collections.IDictionary num2Words, System.String g, Document doc) { var keys = (System.Collections.IList)word2Nums[g]; // get list of key#'s var i2 = keys.GetEnumerator(); var already = new System.Collections.SortedList(); // keep them sorted // pass 1: fill up 'already' with all words while (i2.MoveNext()) // for each key# { foreach (var item in ((System.Collections.IList)num2Words[i2.Current]).Cast <object>().Where(item => already.Contains(item) == false)) { already.Add(item, item); } } var num = 0; already.Remove(g); // of course a word is it's own syn var it = already.GetEnumerator(); while (it.MoveNext()) { var cur = (String)it.Key; // don't store things like 'pit bull' -> 'american pit bull' if (!IsDecent(cur)) { continue; } num++; doc.Add(new Field(F_SYN, cur, Field.Store.YES, Field.Index.NO)); } return(num); }
public InterpolatorColor(System.Collections.SortedList colorKeyFrames) { //_colors = a_colorKeyFrames; _interpolators = new List <Interpolator>(); for (int i = 0; i < 4; i++) { Interpolator ip = new Interpolator(); _interpolators.Add(ip); System.Collections.SortedList a = new System.Collections.SortedList(); for (int nClrNum = 0; nClrNum < colorKeyFrames.Count; nClrNum++) { Color clr = (Color)colorKeyFrames.GetByIndex(nClrNum); double dVal = 0; if (i == 0) { dVal = clr.A; } else if (i == 1) { dVal = clr.R; } else if (i == 2) { dVal = clr.G; } else if (i == 3) { dVal = clr.B; } a.Add(colorKeyFrames.GetKey(nClrNum), dVal); } ip.KeyFramesList = a; } }
static void Main(string[] args) { System.Collections.SortedList sl = new System.Collections.SortedList(); sl.Add(1, "ќдин"); sl.Add(5, "ѕ¤ть"); sl.Add(3, "“ри"); sl.Add(2, "ƒва"); sl.Add(4, "„етыре"); foreach (System.Collections.DictionaryEntry item in sl) { Console.WriteLine(item.Value); } Console.ReadLine(); }
public void Add(ProCommon.Communal.SerialPortProperty serialPortProperty) { if (!_list.ContainsKey(serialPortProperty.ID)) { _list.Add(serialPortProperty.ID, serialPortProperty); } }
/// <summary> /// 读取AD用户信息 /// </summary> /// <param name= "ADUsername "> 用户 </param> /// <param name= "ADPassword "> 密码 </param> /// <param name= "domain "> 域名 </param> /// <returns> </returns> public System.Collections.SortedList AdUserInfo(string ADUsername, string ADPassword, string domain) { System.DirectoryServices.DirectorySearcher src; string ADPath = "LDAP:// " + domain;// "ou=总公司,DC=abc,DC=com,DC=cn "; + ",ou=总公司 " System.Collections.SortedList sl = new System.Collections.SortedList(); string domainAndUsername = domain + @"\" + ADUsername; System.DirectoryServices.DirectoryEntry de = new System.DirectoryServices.DirectoryEntry(ADPath, domainAndUsername, ADPassword); src = new System.DirectoryServices.DirectorySearcher(de); src.Filter = "(SAMAccountName=" + ADUsername + ")"; src.PageSize = 10000;// 此参数可以任意设置,但不能不设置,如不设置读取AD数据为0~999条数据,设置后可以读取大于1000条数据。 // src.SizeLimit = 2000; src.SearchScope = System.DirectoryServices.SearchScope.Subtree; try { foreach (System.DirectoryServices.SearchResult res in src.FindAll()) { sl.Add(res.GetDirectoryEntry().Properties["Name"].Value, res.GetDirectoryEntry().InvokeGet("Description")); } } catch (Exception ex) { throw new Exception("Get Ad Info ", ex); } return(sl); }
public void Add(ProCommon.Communal.CameraProperty camProperty) { if (!_list.ContainsKey(camProperty.ID)) { _list.Add(camProperty.ID, camProperty); } }
private void initConfig() { Application["product"] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; Application["version"] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; resources = new System.Resources.ResourceManager("SharpWebMail", System.Reflection.Assembly.GetExecutingAssembly()); Application["resources"] = resources; System.Collections.Hashtable config = (System.Collections.Hashtable)System.Configuration.ConfigurationSettings.GetConfig("sharpwebmail"); foreach (System.Collections.DictionaryEntry item in config) { Application.Add(item.Key.ToString(), item.Value); } config = null; if (Application["sharpwebmail/send/addressbook"] != null) { Application["sharpwebmail/general/addressbooks"] = true; } if ((bool)Application["sharpwebmail/read/message/useserverencoding"]) { anmar.SharpMimeTools.SharpMimeHeader.EncodingDefault = System.Text.Encoding.Default; } TestAvailableCultures(); System.Collections.SortedList availablecultures_values = new System.Collections.SortedList(availablecultures.Count); foreach (System.Collections.DictionaryEntry item in availablecultures) { availablecultures_values.Add(item.Value, item.Key); } Application["AvailableCultures"] = availablecultures_values; initInvariantCulture(); Application["sharpwebmail/read/message/temppath"] = parseTempFolder(Server.MapPath("/"), Application["sharpwebmail/read/message/temppath"]); Application["sharpwebmail/send/message/temppath"] = parseTempFolder(Server.MapPath("/"), Application["sharpwebmail/send/message/temppath"]); }
public void Add(ProCommon.Communal.BoardProperty brdProperty) { if (!_list.ContainsKey(brdProperty.ID)) { _list.Add(brdProperty.ID, brdProperty); } }
protected void Page_Load(object sender, EventArgs e) { GooglePageBase google = Page as GooglePageBase; DataQuery query = new DataQuery(); query.Ids = "ga:" + google.Settings.Current.Id; query.Metrics = "ga:pageviews"; query.Dimensions = "ga:browser,ga:browserVersion"; query.Sort = "ga:browser,ga:pageviews"; query.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-1).ToString("yyyy-MM-dd"); query.GAEndDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); if (google.Referringpage != null) { query.Filters = "ga:pagePath==" + google.Referringpage; } DataFeed actual = google.Analytics.Query(query); System.Data.DataTable browsers = new System.Data.DataTable("Browser"); browsers.Columns.Add("Browser"); browsers.Columns.Add("Views", typeof(int)); System.Data.DataTable versions = new System.Data.DataTable("BrowserVersion"); versions.Columns.Add("Browser"); versions.Columns.Add("Version"); versions.Columns.Add("Views", typeof(int)); System.Collections.SortedList values = new System.Collections.SortedList(); foreach (DataEntry entry in actual.Entries) { string browser = entry.Dimensions[0].Value.ToString(); string version = entry.Dimensions[1].Value.ToString(); int visits = int.Parse(entry.Metrics[0].Value); if (values.ContainsKey(browser)) { int current = int.Parse(values[browser].ToString()); current += int.Parse(entry.Metrics[0].Value); values[browser] = current; } else { values.Add(browser, int.Parse(entry.Metrics[0].Value)); } versions.Rows.Add(new object[] { browser, version, visits }); } foreach (String key in values.Keys) { browsers.Rows.Add(new object[] { key, int.Parse(values[key].ToString()) }); } this.pie_Browsers.GviEnableEvents = true; this.pie_Browsers.ChartData(browsers); this.tbl_Versions.ChartData(versions); }
// Returns a list of data source names from the local machine. public System.Collections.SortedList GetAllDataSourceNames() { // Get the list of user DSN's first. System.Collections.SortedList dsnList = GetUserDataSourceNames(); // Get list of System DSN's and add them to the first list. System.Collections.SortedList systemDsnList = GetSystemDataSourceNames(); for (int i = 0; i < systemDsnList.Count; i++) { string sName = systemDsnList.GetKey(i) as string; DataSourceType type = (DataSourceType)systemDsnList.GetByIndex(i); try { // This dsn to the master list dsnList.Add(sName, type); } catch { // An exception can be thrown if the key being added is a duplicate so // we just catch it here and have to ignore it. } } return(dsnList); }
private void vContatosRefresh(int nIdTerminal, ref System.Windows.Forms.ListView lvContatos) { lvContatos.Items.Clear(); // Sorting System.Collections.SortedList sortListContatos = new System.Collections.SortedList(); foreach (mdlDataBaseAccess.Tabelas.XsdTbTerminaisContatos.tbTerminaisContatosRow dtrwContato in m_typDatSetTerminaisContatos.tbTerminaisContatos.Rows) { if ((dtrwContato.RowState != System.Data.DataRowState.Deleted) && (dtrwContato.nIdTerminal == nIdTerminal) && (!dtrwContato.IsstrNomeNull())) { if (!sortListContatos.ContainsKey(dtrwContato.strNome)) { sortListContatos.Add(dtrwContato.strNome, dtrwContato); } } } // Insert for (int i = 0; i < sortListContatos.Count; i++) { mdlDataBaseAccess.Tabelas.XsdTbTerminaisContatos.tbTerminaisContatosRow dtrwContatoInserir = (mdlDataBaseAccess.Tabelas.XsdTbTerminaisContatos.tbTerminaisContatosRow)sortListContatos.GetByIndex(i); System.Windows.Forms.ListViewItem lviInsert = lvContatos.Items.Add(dtrwContatoInserir.strNome); lviInsert.Tag = dtrwContatoInserir.nIdContato; if ((m_nIdSelectContato != -1) && (dtrwContatoInserir.nIdContato == m_nIdSelectContato)) { lviInsert.Selected = true; m_nIdSelectContato = -1; } } }
///<summary> /// ///</summary> public virtual void Randomize() { System.Random Rnd = new System.Random(); System.Collections.SortedList List = new System.Collections.SortedList(); foreach (System.Object Value in this) { List.Add(Rnd.Next(), Value); } this.Clear(); this.AddRange(List.Values); }
public void ChangeSizes() { m_nWhichSizes = (m_nWhichSizes+1)%3; System.Collections.SortedList aSizes = new System.Collections.SortedList(); switch (m_nWhichSizes) { case 0: aSizes.Add(0.0, 1.0); aSizes.Add(0.6, 1.0); aSizes.Add(0.8, 0.1); aSizes.Add(1.0, 0.9); break; case 1: aSizes.Add(0.0, 1.0); aSizes.Add(1.0, 1.0); break; default: aSizes.Add(0.0, 0.3); aSizes.Add(1.0, 0.01); aSizes.Add(1.1, 0.01); break; } this.SetSizeList(aSizes); }
/// <summary/> public void ResetSortedList(ref System.Collections.SortedList list, string[] saContents) { list = new System.Collections.SortedList(); foreach (string s in saContents) if (s != null && !list.ContainsKey(s)) list.Add(s, s); #if TestingOnly Console.WriteLine("sorted list contains:"); for ( int i = 0; i < list.Count; i++ ) { Console.WriteLine( " {0}:{1}", list.GetKey(i), list.GetByIndex(i) ); } #endif }
/// <summary> /// Retrieve OID name by OID string. /// </summary> /// <param name="inOidStr">source OID string.</param> /// <returns>OID name.</returns> public string GetOidName(string inOidStr) { if (oidDictionary == null) //Initialize oidDictionary: { oidDictionary = new StringDictionary(); string path = Application.ExecutablePath; string oidFile = System.IO.Path.GetDirectoryName(path) + "\\OID.txt"; string oidBackupFile = System.IO.Path.GetDirectoryName(path) + "\\OID.Backup.txt"; string oidStr = ""; string oidDesc = ""; bool loadOidError = false; int dbCounter = 0; try { using (StreamReader sr = new StreamReader(oidFile)) { string line; while ((line = sr.ReadLine()) != null) { string[] strs = line.Split(','); if (strs.Length < 2) continue; oidStr = strs[0].Trim(); oidDesc = strs[1].Trim(); try { oidDictionary.Add(oidStr, oidDesc); } catch(Exception ex) { loadOidError = true; string msg = ex.Message; dbCounter ++; } } } if (loadOidError) { using (StreamWriter sw = new StreamWriter(oidBackupFile)) { using (StreamReader sr = new StreamReader(oidFile)) { string line; while ((line = sr.ReadLine()) != null) { sw.Write(line+"\r\n"); } } } System.Collections.SortedList sList = new System.Collections.SortedList(); using (StreamWriter sw = new StreamWriter(oidFile)) { string val = ""; foreach ( System.Collections.DictionaryEntry de in oidDictionary ) { if (!sList.ContainsKey(de.Key)) sList.Add(de.Key, de.Value); } for(int i=0; i<sList.Count; i++) { val = String.Format("{0}, {1}\r\n", sList.GetKey(i), sList.GetByIndex(i)); sw.Write(val); } } MessageBox.Show(String.Format("Duplicated OIDs were found in the OID table: {0}.\r\n" + "The duplicate has been removed; the table is sorted.\r\n" + "The original OID file is copied as: {1}\r\n", oidFile, oidBackupFile)); } } catch(Exception ex) { MessageBox.Show("Failed to read OID values from file." + ex.Message); } } return oidDictionary[inOidStr]; }
private void OnGotPM(object sender, BasicCommunication.MessageParser.Got_PM_EventArgs e) { string Message = e.Message.ToLower().Replace("\'", "\\\'").Replace("\"", "\\\""); string[] Inv=new string[64]; int maxlen = 4; bool validCommand = false; if (Message[0] != '#') { Message = "#" + Message; } string[] CommandArray = Message.Split(' '); if (CommandArray[0] == "#reserve" ) { bool disabled = TheMySqlManager.CheckIfCommandIsDisabled("#reserve", Settings.botid); string str1 = "", str2 = ""; if (TheInventory.GettingInventoryItems == true) { str2 = "I am building my inventory list, please try again in a few seconds"; str1 = str1.PadRight(str2.Length, '='); str1 = "[" + str1; str2 = "[" + str2; TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str2)); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); return; } if (disabled == true) { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "This command is disabled")); return; } int rank = TheMySqlManager.GetUserRank(e.username, Settings.botid); if (rank < TheMySqlManager.GetCommandRank("#reserve", Settings.botid)) { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "You are not authorized to use this command!")); return; } if (this.TheTradeHandler.AmITrading() && e.username != TradeHandler.username) { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "I am currently trading, please retry shortly.")); return; } if (CommandArray.Length <= 1) goto WrongArguments; if (CommandArray[1] == "withdraw") { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "Still working on this function...")); validCommand = true; } if (CommandArray[1] == "details") { TheMySqlManager.reservedDetails(Settings.botid, e.username); validCommand = true; } if (CommandArray[1] == "list") { validCommand = true; // list all of the inventory items that have reserved amounts //set up the current inventory list System.Collections.ArrayList MyInventoryList = TheInventory.GetInventoryList(); //set up a sorted inventory list for output purposes System.Collections.SortedList TheInventoryList = new System.Collections.SortedList(); //loop through the inventory finding reserved amounts foreach (Inventory.inventory_item MyInventoryItem in MyInventoryList) { //find the largest name length for output purposes if (maxlen < MyInventoryItem.name.Length && (MyInventoryItem.pos < 36)) maxlen = MyInventoryItem.name.Length; //if it's not in the output array, put it there if (TheInventoryList.Contains(MyInventoryItem.SqlID) && MyInventoryItem.pos < 36) { //add the item quantities (these should be the unstackables...) Inventory.inventory_item TempInventoryItem = (Inventory.inventory_item)TheInventoryList[MyInventoryItem.SqlID]; TempInventoryItem.quantity += MyInventoryItem.quantity; TheInventoryList[MyInventoryItem.SqlID] = TempInventoryItem; } else { if (MyInventoryItem.pos < 36) { TheInventoryList.Add(MyInventoryItem.SqlID, MyInventoryItem); } } } //loop through the storage finding reserved amounts System.Collections.ArrayList MyStorageList = TheStorage.GetStorageList(); foreach (Storage.StorageItem MyStorageItem in MyStorageList) { if (maxlen < MyStorageItem.name.Length) { maxlen = MyStorageItem.name.Length; } if (TheInventoryList.Contains(MyStorageItem.knownItemsID)) { //already in the list, do nothing since storage quantity is already the total //and it repeats, kinda like an unstackable item } else { Inventory.inventory_item MyInventoryItem = new Inventory.inventory_item(); MyInventoryItem.name = MyStorageItem.name; MyInventoryItem.SqlID = MyStorageItem.knownItemsID; MyInventoryItem.quantity = MyStorageItem.quantity; MyInventoryItem.reservedQuantity = MyStorageItem.reservedQuantity; TheInventoryList.Add(MyInventoryItem.SqlID, MyInventoryItem); } } // pm the reserved items string str = ""; string msg = ""; str = "["; str = str.PadRight(maxlen + 27, '-'); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); foreach (Inventory.inventory_item MyInventoryItem in TheInventoryList.Values) { uint reservedQuantity = TheMySqlManager.ReservedAmount(MyInventoryItem.SqlID); if (MyInventoryItem.pos < 36 && reservedQuantity > 0) { msg = "["; msg += MyInventoryItem.name + " " + reservedQuantity + " of " + MyInventoryItem.quantity; TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, msg)); } } str = "["; str = str.PadRight(maxlen + 27, '-'); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); } if (CommandArray.Length > 2) { validCommand = true; try { if (CommandArray[1] == "delete") { Int32 rowIndex = Int32.Parse(CommandArray[2]); if (TheMySqlManager.reservedDelete(Settings.botid, e.username, rowIndex)) { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[Row Deleted.")); } else { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[Index not found.")); } } else { Int32 numberToReserve = Int32.Parse(CommandArray[1]); int i; string itemName = ""; for (i = 2; i < CommandArray.Length; i++) { itemName += CommandArray[i] + " "; } int itemId = TheMySqlManager.GetItemID(itemName,false); if (itemId > 0) { if (TheMySqlManager.reserveItem(itemId, (uint)numberToReserve, e.username) == true) { TheTradeHandler.AddTrade(itemId, 0, (uint)numberToReserve, "reserved"); TradeHandler.TradeLogItem myItem = new TradeHandler.TradeLogItem(); myItem.KnownItemsSqlID = itemId; myItem.quantity = (uint)numberToReserve; myItem.action = "reserved by"; TheMySqlManager.LogTrade(myItem, e.username, Settings.botid, true); TheInventory.requestInventory(); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[You just reserved " + myItem.quantity + " " + TheMySqlManager.GetKnownItemsname(myItem.KnownItemsSqlID))); } else //probably never get to this one... { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[Item not found!")); } } else { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[Item not found!")); } } } catch { goto WrongArguments; } } else { if (!validCommand) { goto WrongArguments; } } } return; WrongArguments: TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[----------------------------------------------------")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[Here is the usage of the #reserve command: ")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[#reserve <list>[withdraw] <amount item> ")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[----------------------------------------------------")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[Example: #reserve list ")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[Example: #reserve amount item ")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[Example: #reserve details ")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[Example: #reserve delete <idx>* ")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[*<idx> provided by #reserve details command. ")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[----------------------------------------------------")); return; }
private void Script_GET_NPCS(string inp) { string sdest = Get_String(ref inp); ScriptVariable dest = Get_Var(sdest); if (dest.Type == Var_Types.ARRAYLIST) { ((System.Collections.ArrayList)dest.Value).Clear(); } else if (dest.Type == Var_Types.SORTEDLIST) { ((System.Collections.SortedList)dest.Value).Clear(); } else { ScriptEngine.Script_Error("INVLAID DESTINATION TYPE"); return; } Globals.NPCLock.EnterReadLock(); try { foreach (NPCInfo npc in Globals.gamedata.nearby_npcs.Values) { Script_ClassData cd = new Script_ClassData(); cd.Name = "NPC"; cd._Variables.Add("ID", new ScriptVariable((long)npc.ID, "ID", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("X", new ScriptVariable((long)npc.X, "X", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("Y", new ScriptVariable((long)npc.Y, "Y", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("Z", new ScriptVariable((long)npc.Z, "Z", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("NAME", new ScriptVariable(Util.GetNPCName(npc.NPCID), "NAME", Var_Types.STRING, Var_State.PUBLIC)); cd._Variables.Add("NPC_ID", new ScriptVariable((long)npc.NPCID, "NPC_ID", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("TITLE", new ScriptVariable(npc.Title, "TITLE", Var_Types.STRING, Var_State.PUBLIC)); cd._Variables.Add("ATTACKABLE", new ScriptVariable((long)npc.isAttackable, "ATTACKABLE", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("LEVEL", new ScriptVariable((long)npc.Level, "LEVEL", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("HP", new ScriptVariable((long)npc.Cur_HP, "HP", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("MAX_HP", new ScriptVariable((long)npc.Max_HP, "MAX_HP", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("MP", new ScriptVariable((long)npc.Cur_MP, "MP", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("MAX_MP", new ScriptVariable((long)npc.Max_MP, "MAX_MP", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("CP", new ScriptVariable((long)npc.Cur_CP, "CP", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("MAX_CP", new ScriptVariable((long)npc.Max_CP, "MAX_CP", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("PER_HP", new ScriptVariable(Math.Round((double)npc.Cur_HP / (double)npc.Max_HP * 100, 2), "PER_HP", Var_Types.DOUBLE, Var_State.PUBLIC)); cd._Variables.Add("PER_MP", new ScriptVariable(Math.Round((double)npc.Cur_MP / (double)npc.Max_MP * 100, 2), "PER_MP", Var_Types.DOUBLE, Var_State.PUBLIC)); cd._Variables.Add("PER_CP", new ScriptVariable(Math.Round((double)npc.Cur_CP / (double)npc.Max_CP * 100, 2), "PER_CP", Var_Types.DOUBLE, Var_State.PUBLIC)); cd._Variables.Add("KARMA", new ScriptVariable((long)npc.Karma, "KARMA", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("ATTACK_SPEED", new ScriptVariable((long)(npc.PatkSpeed * npc.AttackSpeedMult), "ATTACK_SPEED", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("CAST_SPEED", new ScriptVariable((long)npc.PatkSpeed, "CAST_SPEED", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("RUN_SPEED", new ScriptVariable((long)(npc.RunSpeed * npc.MoveSpeedMult), "RUN_SPEED", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("TARGET_ID", new ScriptVariable((long)npc.TargetID, "TARGET_ID", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("FOLLOW_TARGET_ID", new ScriptVariable((long)npc.MoveTarget, "FOLLOW_TARGET_ID", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("DEST_X", new ScriptVariable((long)npc.Dest_X, "DEST_X", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("DEST_Y", new ScriptVariable((long)npc.Dest_Y, "DEST_Y", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("DEST_Z", new ScriptVariable((long)npc.Dest_Z, "DEST_Z", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("LOOKS_DEAD", new ScriptVariable((long)npc.isAlikeDead, "LOOKS_DEAD", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("IN_COMBAT", new ScriptVariable((long)npc.isInCombat, "IN_COMBAT", Var_Types.INT, Var_State.PUBLIC)); try { System.Collections.SortedList buffs = new System.Collections.SortedList(); foreach (CharBuff buff in npc.my_buffs.Values) { Script_ClassData ncd = new Script_ClassData(); ncd.Name = "EFFECT"; ncd._Variables.Add("ID", new ScriptVariable((long)buff.ID, "ID", Var_Types.INT, Var_State.PUBLIC)); ncd._Variables.Add("LEVEL", new ScriptVariable((long)buff.SkillLevel, "LEVEL", Var_Types.INT, Var_State.PUBLIC)); ncd._Variables.Add("DURATION", new ScriptVariable((long)buff.ExpiresTime, "DURATION", Var_Types.INT, Var_State.PUBLIC)); ncd._Variables.Add("NAME", new ScriptVariable(Util.GetSkillName(buff.ID, buff.SkillLevel), "NAME", Var_Types.STRING, Var_State.PUBLIC)); ScriptVariable nsv = new ScriptVariable(ncd, "EFFECT", Var_Types.CLASS, Var_State.PUBLIC); buffs.Add(buff.ID.ToString(), nsv); } cd._Variables.Add("EFFECTS", new ScriptVariable((System.Collections.SortedList)buffs, "EFFECTS", Var_Types.SORTEDLIST, Var_State.PUBLIC)); } catch { System.Collections.SortedList empty = new System.Collections.SortedList(); cd._Variables.Add("EFFECTS", new ScriptVariable((System.Collections.SortedList)empty, "EFFECTS", Var_Types.SORTEDLIST, Var_State.PUBLIC)); } ScriptVariable sv = new ScriptVariable(cd, "NPC", Var_Types.CLASS, Var_State.PUBLIC); if (dest.Type == Var_Types.ARRAYLIST) { ((System.Collections.ArrayList)dest.Value).Add(sv); } else if (dest.Type == Var_Types.SORTEDLIST) { ((System.Collections.SortedList)dest.Value).Add(npc.ID.ToString(), sv); } } } finally { Globals.NPCLock.ExitReadLock(); } }
/// <summary> /// Create an ASCII Ramp with from the given font and characters /// </summary> /// <param name="font">Font to be used</param> /// <param name="characters">The characters to be used for the ramp</param> /// <returns>A new ASCII ramp</returns> public static string CreateRamp(Font font, string characters) { if (characters == null || characters.Length < 1) return null; if (characters.Length == 1) return characters; string characterstring = ""; foreach (char c in characters.ToCharArray()) { if (characterstring.IndexOf(c) == -1) { characterstring += c.ToString(); } } System.Collections.SortedList list = new System.Collections.SortedList(); int min = 255; int max = 0; CharacterValue charval; for (int i = 0; i < characterstring.Length; i++) { charval = new CharacterValue(characterstring[i], font); if (list.ContainsKey(charval.Value)) { if (charval.Score < ((CharacterValue)list[charval.Value]).Score) { list[charval.Value] = charval; } } else { if (charval.Value < min) min = charval.Value; if (charval.Value > max) max = charval.Value; list.Add(charval.Value, charval); } } list.TrimToSize(); string result = ""; System.Collections.IDictionaryEnumerator idenu = list.GetEnumerator(); // move to the first object idenu.MoveNext(); int current = (int)idenu.Key; int next, mid; // loop through and fill in the gaps while (idenu.MoveNext()) { next = (int)idenu.Key; mid = ((next - current) / 2) + current; for (int i = current; i < mid; i++) { result += list[current]; } for (int i = mid; i < next; i++) { result += list[next]; } current = next; } return result; }
/// <summary> /// Analyzes the first <code>nLines</code> of the ascii stream. /// </summary> /// <param name="nLines">The number of lines to analyze. It is no error if the stream contains a less number of lines than provided here.</param> /// <param name="defaultImportOptions">The default import options.</param> /// <returns>Import options that can be used in a following step to read in the ascii stream. Null is returned if the stream contains no data.</returns> public AsciiImportOptions Analyze(int nLines, AsciiImportOptions defaultImportOptions) { string sLine; stream.Position = 0; System.IO.StreamReader sr = new System.IO.StreamReader(stream,System.Text.Encoding.Default,true); System.Collections.ArrayList result = new System.Collections.ArrayList(); for(int i=0;i<nLines;i++) { sLine = sr.ReadLine(); if(null==sLine) break; result.Add(new AsciiLineAnalyzer(i,sLine)); } if(result.Count==0) return null; // there is nothing to analyze // now view the results // calc the frequency o System.Collections.SortedList sl= new System.Collections.SortedList(); int nItems; // first the tabs /* sl.Clear(); for(int i=0;i<result.Count;i++) { nItems = ((AsciiLineAnalyzer)result[i]).nNumberOfTabs; if(0!=nItems) { if(null==sl[nItems]) sl.Add(nItems,1); else sl[nItems] = 1+(int)sl[nItems]; } } // get the tab count with the topmost frequency int nMaxNumberOfSameTabs = 0; int nMaxTabsOfSameNumber = 0; for(int i=0;i<sl.Count;i++) { if(nMaxNumberOfSameTabs<(int)sl.GetByIndex(i)) { nMaxNumberOfSameTabs = (int)sl.GetByIndex(i); nMaxTabsOfSameNumber = (int)sl.GetKey(i); } } */ // Count the commas sl.Clear(); for(int i=0;i<result.Count;i++) { nItems = ((AsciiLineAnalyzer)result[i]).nNumberOfCommas; if(0!=nItems) { if(null==sl[nItems]) sl.Add(nItems,1); else sl[nItems] = 1+(int)sl[nItems]; } } // get the comma count with the topmost frequency int nMaxNumberOfSameCommas = 0; int nMaxCommasOfSameNumber = 0; for(int i=0;i<sl.Count;i++) { if(nMaxNumberOfSameCommas<(int)sl.GetByIndex(i)) { nMaxNumberOfSameCommas = (int)sl.GetByIndex(i); nMaxCommasOfSameNumber = (int)sl.GetKey(i); } } // Count the semicolons sl.Clear(); for(int i=0;i<result.Count;i++) { nItems = ((AsciiLineAnalyzer)result[i]).nNumberOfSemicolons; if(0!=nItems) { if(null==sl[nItems]) sl.Add(nItems,1); else sl[nItems] = 1+(int)sl[nItems]; } } // get the tab count with the topmost frequency int nMaxNumberOfSameSemicolons = 0; int nMaxSemicolonsOfSameNumber = 0; for(int i=0;i<sl.Count;i++) { if(nMaxNumberOfSameSemicolons<(int)sl.GetByIndex(i)) { nMaxNumberOfSameSemicolons = (int)sl.GetByIndex(i); nMaxSemicolonsOfSameNumber = (int)sl.GetKey(i); } } NumberAndStructure[] st = new NumberAndStructure[3]; for(int i=0;i<3;i++) { st[i].nLines = GetPriorityOf(result,(AsciiLineAnalyzer.Separation)i,ref st[i].structure); } // look for the top index int nMaxLines = int.MinValue; double maxprtylines=0; int nBestSeparator = int.MinValue; for(int i=0;i<3;i++) { double prtylines = (double)st[i].nLines * st[i].structure.Priority; if(prtylines==maxprtylines) { if(st[i].nLines > nMaxLines) { nMaxLines = st[i].nLines; nBestSeparator = i; } } else if(prtylines>maxprtylines) { maxprtylines = prtylines; nBestSeparator = i; nMaxLines=st[i].nLines; } } AsciiImportOptions opt = defaultImportOptions.Clone(); opt.bDelimited = true; opt.cDelimiter = nBestSeparator==0 ? '\t' : (nBestSeparator==1 ? ',' : ';'); opt.recognizedStructure = st[nBestSeparator].structure; // look how many header lines are in the file by comparing the structure of the first lines with the recognized structure for(int i=0;i<result.Count;i++) { opt.nMainHeaderLines=i; if(((AsciiLineAnalyzer)result[i]).structure[nBestSeparator].IsCompatibleWith(opt.recognizedStructure)) break; } // calculate the total statistics of decimal separators opt.m_DecimalSeparatorCommaCount=0; opt.m_DecimalSeparatorDotCount=0; for(int i=0;i<result.Count;i++) { opt.m_DecimalSeparatorDotCount += ((AsciiLineAnalyzer)result[i]).structure[nBestSeparator].DecimalSeparatorDotCount; opt.m_DecimalSeparatorCommaCount += ((AsciiLineAnalyzer)result[i]).structure[nBestSeparator].DecimalSeparatorCommaCount; } return opt; }
/// <summary> /// Returns a portion of the list whose keys are less than the limit object parameter. /// </summary> /// <param name="l">The list where the portion will be extracted.</param> /// <param name="limit">The end element of the portion to extract.</param> /// <returns>The portion of the collection whose elements are less than the limit object parameter.</returns> public static System.Collections.SortedList HeadMap(System.Collections.SortedList l, System.Object limit) { System.Collections.Comparer comparer = System.Collections.Comparer.Default; System.Collections.SortedList newList = new System.Collections.SortedList(); for (int i = 0; i < l.Count; i++) { if (comparer.Compare(l.GetKey(i), limit) >= 0) break; newList.Add(l.GetKey(i), l[l.GetKey(i)]); } return newList; }
private System.Collections.SortedList GetUserDataSourceNames() { System.Collections.SortedList dsnList = new System.Collections.SortedList(); Microsoft.Win32.RegistryKey reg = (Microsoft.Win32.Registry.CurrentUser).OpenSubKey("Software"); if (reg != null) { reg = reg.OpenSubKey("ODBC"); if (reg != null) { reg = reg.OpenSubKey("ODBC.INI"); if (reg != null) { reg = reg.OpenSubKey("ODBC Data Sources"); if (reg != null) { foreach (string sName in reg.GetValueNames()) { dsnList.Add(sName, sName); } } try { reg.Close(); } catch { /* ignore this exception if we couldn't close */ } } } } return dsnList; }
/// <summary> /// Returns a key/value pair representing the attributes in the element. /// </summary> /// <param name="reader">The bufferred xml to analyze.</param> /// <returns>A sorted list of the attributes with the name as the key and the value as the value.</returns> /// <remarks>Executing this method querries the current node for the attributes without advancing to the next node.</remarks> private System.Collections.SortedList GetAttributes(System.Xml.XmlReader reader) { System.Collections.SortedList _List = new System.Collections.SortedList(); //FIX: December 9, 2005 - Fix to handle reading attributes from ReadXml routine if ((reader.NodeType != System.Xml.XmlNodeType.None) & (reader.MoveToFirstAttribute())) { do { if (reader.NodeType == System.Xml.XmlNodeType.Attribute) { _List.Add(reader.Name, reader.Value); } } while (reader.MoveToNextAttribute() | reader.NodeType != System.Xml.XmlNodeType.Attribute); } if (reader.NodeType == System.Xml.XmlNodeType.Attribute) { reader.MoveToElement(); } return _List; }
/// <summary> /// Returns a portion of the list whose keys are greater that the lowerLimit parameter less than the upperLimit parameter. /// </summary> /// <param name="l">The list where the portion will be extracted.</param> /// <param name="limit">The start element of the portion to extract.</param> /// <param name="limit">The end element of the portion to extract.</param> /// <returns>The portion of the collection.</returns> public static System.Collections.SortedList SubMap(System.Collections.SortedList list, System.Object lowerLimit, System.Object upperLimit) { System.Collections.Comparer comparer = System.Collections.Comparer.Default; System.Collections.SortedList newList = new System.Collections.SortedList(); if (list != null) { if ((list.Count > 0) && (!(lowerLimit.Equals(upperLimit)))) { int index = 0; while (comparer.Compare(list.GetKey(index), lowerLimit) < 0) index++; for (; index < list.Count; index++) { if (comparer.Compare(list.GetKey(index), upperLimit) >= 0) break; newList.Add(list.GetKey(index), list[list.GetKey(index)]); } } } return newList; }
/// <summary> /// Returns a portion of the list whose keys are greater than the limit object parameter. /// </summary> /// <param name="l">The list where the portion will be extracted.</param> /// <param name="limit">The start element of the portion to extract.</param> /// <returns>The portion of the collection whose elements are greater than the limit object parameter.</returns> public static System.Collections.SortedList TailMap(System.Collections.SortedList list, System.Object limit) { System.Collections.Comparer comparer = System.Collections.Comparer.Default; System.Collections.SortedList newList = new System.Collections.SortedList(); if (list != null) { if (list.Count > 0) { int index = 0; while (comparer.Compare(list.GetKey(index), limit) < 0) index++; for (; index < list.Count; index++) newList.Add(list.GetKey(index), list[list.GetKey(index)]); } } return newList; }
protected void Page_Load(object sender, EventArgs e) { if (!base.IsPostBack) { string personCode = CurrentUserInfo.Personcode; string companyId = CurrentUserInfo.CompanyId; string module_Code = this.Request.QueryString["ModuleCode"].ToString(); ModuleCode.Value = module_Code; dt = hrmDepartmentBll.getOrgTree(personCode, companyId, module_Code); //=================加載樹================= this.UltraWebTreeData.Nodes.Clear(); System.Collections.SortedList allTreeNodes = new System.Collections.SortedList(); Color foreColor; string strDeleted = ""; foreach (System.Data.DataRow row in dt.Rows) { switch (row["levelcode"].ToString()) { case "0": foreColor = Color.Blue; break; case "1": foreColor = Color.Maroon; break; case "2": foreColor = Color.SaddleBrown; break; case "3": foreColor = Color.Red; break; default: foreColor = Color.Black; break; } if (row["Deleted"].ToString() == "Y") { foreColor = Color.DarkGray; strDeleted = "[Disabled]"; } else { strDeleted = ""; } allTreeNodes.Add(System.Convert.ToString(row["depcode"]), base.CreateNode(System.Convert.ToString(row["depcode"]), System.Convert.ToString(row["depname"]) + "[" + System.Convert.ToString(row["depcode"]) + "]" + strDeleted, false, System.Convert.ToDecimal(dt.Compute("count(depcode)", "parentdepcode='" + row["depcode"] + "'")) == 0, foreColor)); if (row["parentdepcode"].ToString().Trim().Length > 0) { if (allTreeNodes.IndexOfKey(row["parentdepcode"]) >= 0) { ((Infragistics.WebUI.UltraWebNavigator.Node)allTreeNodes.GetByIndex(allTreeNodes.IndexOfKey(row["parentdepcode"]))).Nodes.Add((Infragistics.WebUI.UltraWebNavigator.Node)allTreeNodes.GetByIndex(allTreeNodes.IndexOfKey(row["depcode"]))); } else { this.UltraWebTreeData.Nodes.Add((Infragistics.WebUI.UltraWebNavigator.Node)allTreeNodes.GetByIndex(allTreeNodes.IndexOfKey(System.Convert.ToString(row["depcode"])))); } } else { this.UltraWebTreeData.Nodes.Add((Infragistics.WebUI.UltraWebNavigator.Node)allTreeNodes.GetByIndex(allTreeNodes.IndexOfKey(System.Convert.ToString(row["depcode"])))); } } //=================加載完成================= foreach (Node node in this.UltraWebTreeData.Nodes) { node.Expand(false); } } }
public void ChangeColors() { m_nWhichColors = (m_nWhichColors+1)%3; System.Collections.SortedList aColors = new System.Collections.SortedList(); switch (m_nWhichColors) { case 0: aColors.Add(0.0, Color.FromArgb(0,255,0)); aColors.Add(0.5, Color.FromArgb(255,0,0)); aColors.Add(0.7, Color.FromArgb(255,0,0)); aColors.Add(0.75, Color.FromArgb(255,255,255)); aColors.Add(0.8, Color.FromArgb(100,0,255)); aColors.Add(1.0, Color.FromArgb(0,0,255)); break; case 1: aColors.Add(0.0, Color.FromArgb(255,255,0)); aColors.Add(0.5, Color.FromArgb(255,0,0)); aColors.Add(1.0, Color.FromArgb(0,0,0)); break; default: aColors.Add(0.0, Color.FromArgb(0,0,0)); aColors.Add(0.3, Color.FromArgb(0,0,0)); aColors.Add(0.7, Color.FromArgb(0,0,255)); aColors.Add(0.85, Color.FromArgb(0,255,0)); aColors.Add(1.0, Color.FromArgb(0,0,0)); break; } this.SetColorList(aColors); }
/// <summary> /// Creates a matrix from three selected columns. This must be a x-column, a y-column, and a value column. /// </summary> /// <param name="xcol">Column of x-values.</param> /// <param name="ycol">Column of y-values.</param> /// <param name="vcol">Column of v-values.</param> /// <param name="originalTable">The source table. This is only needed to get the names of the columns.</param> /// <param name="newtable">On return, contains the newly created table matrix.</param> /// <returns>Null if no error occurs, or an error message.</returns> public static string XYVToMatrix(DataColumn xcol, DataColumn ycol, DataColumn vcol, DataTable originalTable, out DataTable newtable) { newtable = null; System.Collections.SortedList xx = new System.Collections.SortedList(); System.Collections.SortedList yy = new System.Collections.SortedList(); int len = xcol.Count; len = Math.Min(len, ycol.Count); len = Math.Min(len, vcol.Count); // Fill the xx and yy lists for (int i = 0; i < len; ++i) { if (!xx.Contains(xcol[i])) xx.Add(xcol[i], null); if (!yy.Contains(ycol[i])) yy.Add(ycol[i], null); } DataColumn xnew = (DataColumn)Activator.CreateInstance(xcol.GetType()); DataColumn ynew = (DataColumn)Activator.CreateInstance(ycol.GetType()); xnew.Clear(); ynew.Clear(); for (int i = xx.Count - 1; i >= 0; --i) { xnew[i] = (AltaxoVariant)xx.GetKey(i); xx[xx.GetKey(i)] = i; } for (int i = yy.Count - 1; i >= 0; --i) { ynew[1 + i] = (AltaxoVariant)yy.GetKey(i); // 1 + is because the table will get an additional x-column yy[yy.GetKey(i)] = i; } DataColumn vtemplate = (DataColumn)Activator.CreateInstance(vcol.GetType()); // make a new table with yy.Count number of columns DataColumn[] vcols = new DataColumn[yy.Count]; for (int i = yy.Count - 1; i >= 0; --i) { vcols[i] = (DataColumn)vtemplate.Clone(); } // now fill the columns for (int i = 0; i < len; ++i) { int xidx = (int)xx[xcol[i]]; int yidx = (int)yy[ycol[i]]; vcols[yidx][xidx] = vcol[i]; } // assemble all columns together in a table newtable = new DataTable(); // add the x-column to the data collection string xname = null; if (null != originalTable) xname = originalTable.DataColumns.GetNameOfChildObject(xcol); if (string.IsNullOrEmpty(xname)) xname = "X"; newtable.DataColumns.Add(xnew, xname, ColumnKind.X, 0); // add the y-column to the property collection string yname = null; if (null != originalTable) yname = originalTable.DataColumns.GetNameOfChildObject(ycol); if (string.IsNullOrEmpty(yname)) yname = "Y"; newtable.PropertyColumns.Add(ynew, yname, ColumnKind.Y, 0); // add the v-columns to the data collection string vname = null; if (null != originalTable) vname = originalTable.DataColumns.GetNameOfChildObject(vcol); if (string.IsNullOrEmpty(vname)) vname = "V"; for (int i = 0; i < vcols.Length; ++i) newtable.DataColumns.Add(vcols[i], vname + i.ToString(), ColumnKind.V, 0); return null; }
/// <summary> /// Given the 2 maps fills a document for 1 word. /// </summary> private static int Index(System.Collections.IDictionary word2Nums, System.Collections.IDictionary num2Words, System.String g, Document doc) { var keys = (System.Collections.IList) word2Nums[g]; // get list of key#'s var i2 = keys.GetEnumerator(); var already = new System.Collections.SortedList(); // keep them sorted // pass 1: fill up 'already' with all words while (i2.MoveNext()) // for each key# { foreach (var item in ((System.Collections.IList) num2Words[i2.Current]).Cast<object>().Where(item => already.Contains(item) == false)) { already.Add(item, item); } } var num = 0; already.Remove(g); // of course a word is it's own syn var it = already.GetEnumerator(); while (it.MoveNext()) { var cur = (String) it.Key; // don't store things like 'pit bull' -> 'american pit bull' if (!IsDecent(cur)) { continue; } num++; doc.Add(new Field(F_SYN, cur, Field.Store.YES, Field.Index.NO)); } return num; }
public override bool Next() { if (termEnum == null) return false; // another term in this field? if (termEnum.Next() && (System.Object) termEnum.Term().Field() == (System.Object) field) return true; // yes, keep going termEnum.Close(); // close old termEnum // find the next field with terms, if any if (fieldIterator == null) { System.Collections.Comparer comparer = System.Collections.Comparer.Default; System.Collections.SortedList newList = new System.Collections.SortedList(); if (Enclosing_Instance.fieldToReader != null) { if (Enclosing_Instance.fieldToReader.Count > 0) { int index = 0; while (comparer.Compare(Enclosing_Instance.fieldToReader.GetKey(index), field) < 0) index++; for (; index < Enclosing_Instance.fieldToReader.Count; index++) { newList.Add(Enclosing_Instance.fieldToReader.GetKey(index), Enclosing_Instance.fieldToReader[Enclosing_Instance.fieldToReader.GetKey(index)]); } } } fieldIterator = newList.Keys.GetEnumerator(); fieldIterator.MoveNext(); System.Object generatedAux = fieldIterator.Current; // Skip field to get next one } while (fieldIterator.MoveNext()) { field = ((System.String) fieldIterator.Current); termEnum = ((IndexReader) Enclosing_Instance.fieldToReader[field]).Terms(new Term(field)); Term term = termEnum.Term(); if (term != null && (System.Object) term.Field() == (System.Object) field) return true; else termEnum.Close(); } return false; // no more fields }
private void OnGotPM(object sender, BasicCommunication.MessageParser.Got_PM_EventArgs e) { int UsedSlots = 0; string Message = e.Message.ToLower().Replace("\'", "\\\'").Replace("\"", "\\\""); string[] Inv=new string[64]; int maxlen = 4; if (Message[0] != '#') { Message = "#" + Message; } string[] CommandArray = Message.Split(' '); bool isinv = false,isinvmembers = false; if (CommandArray[0] == "#inv" || CommandArray[0] == "#i" || CommandArray[0] == "#inb" || CommandArray[0] == "#sell" || CommandArray[0] == "#selling" || CommandArray[0] == "#inventory") isinv = true; if (CommandArray[0] == "#invmembers" || CommandArray[0] == "#im" || CommandArray[0] == "#invmemvers" || CommandArray[0] == "#invmember" || CommandArray[0] == "#invmemver") isinvmembers = true; if (isinv || isinvmembers) { bool disabled = TheMySqlManager.CheckIfCommandIsDisabled("#inv", Settings.botid); string str1 = "", str2 = ""; if (TheInventory.GettingInventoryItems == true) { str2 = "I am building my inventory list, please try again in a few seconds"; str1 = str1.PadRight(str2.Length, '='); str1 = "[" + str1; str2 = "[" + str2; TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str2)); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); return; } if (disabled == true) { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "This command is disabled")); return; } if (Settings.IsTradeBot == false) { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "Sorry, I am not a trade bot!")); return; } int rank = TheMySqlManager.GetUserRank(e.username, Settings.botid); if (rank < TheMySqlManager.GetCommandRank("#inv", Settings.botid)) { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "You are not authorized to use this command!")); return; } if ((CommandArray[0] == "#im" || CommandArray[0] == "#invmembers" || CommandArray[0] == "#invmemvers" || CommandArray[0] == "#invmember" || CommandArray[0] == "#invmemver") && ((rank < TheMySqlManager.GetCommandRank("#invmembers", Settings.botid)) && TheMySqlManager.CheckIfBannedGuild( e.username, Settings.botid) < 1)) { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "You are not authorized to use this command!")); return; } if (this.TheTradeHandler.AmITrading() && e.username != TradeHandler.username) { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "I am currently trading, please retry shortly.")); return; } if (CommandArray.Length < 1) goto WrongArguments; char invFiller = TheMySqlManager.getInvFiller(); System.Collections.ArrayList MyInventoryList = TheInventory.GetInventoryList(); System.Collections.Hashtable MySellingItemsList = TheMySqlManager.GetSellingItemList(0); // sum up all inventory items if the items are on sale System.Collections.SortedList TheInventoryList = new System.Collections.SortedList(); foreach (Inventory.inventory_item MyInventoryItem in MyInventoryList) { //adjust the number of slots used... if (MyInventoryItem.pos < 36) { if (MyInventoryItem.is_stackable) UsedSlots++; else UsedSlots = UsedSlots + (int)(MyInventoryItem.quantity); } //adjust the amount //only display if in selling list if (MySellingItemsList.Contains(MyInventoryItem.SqlID)) { //if already in inventory output (eg.., two slots) just sum the quantity //otherwise add to inventory output if (TheInventoryList.Contains(MyInventoryItem.SqlID) && MyInventoryItem.pos < 36) { Inventory.inventory_item TempInventoryItem = (Inventory.inventory_item)TheInventoryList[MyInventoryItem.SqlID]; TempInventoryItem.quantity += MyInventoryItem.quantity; TheInventoryList[MyInventoryItem.SqlID] = TempInventoryItem; } else { if (MyInventoryItem.pos < 36) { TheInventoryList.Add(MyInventoryItem.SqlID, MyInventoryItem); } } } } //foreach (Inventory.inventory_item MyInventoryItem in TheInventoryList.Values) //{ // if(maxlen<MyInventoryItem.name.Length && (MyInventoryItem.pos < 36)) // maxlen = MyInventoryItem.name.Length; //} //maxlen++; maxlen = 20 + 25 - Settings.Loginname.Length; // pm all summed up inventory items on sale int i = 0; for (i = 0; i < 64; i++) Inv[i] = "ZZZZZZZZZZZZZZZZ"; int c = 0; string str = ""; str2 = ""; str = "["; str = str.PadRight(maxlen + 27, '-'); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); bool Member = (TheMySqlManager.CheckIfTradeMember(e.username, Settings.botid) == true); str = "[name".PadRight(maxlen, ' '); str = str + "|qty".PadRight(7, ' '); str = str + "|price".PadRight(14, ' '); str = str + "|id".PadRight(6, ' '); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); str = "["; str = str.PadRight(maxlen + 27, '-'); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); string msg, msg2; foreach (Inventory.inventory_item MyInventoryItem in TheInventoryList.Values) { if (MyInventoryItem.pos < 36) { msg = ("[" + MyInventoryItem.name).PadRight(maxlen, i == 0 ? ' ' : invFiller); { uint tempAmount = 0; if ((TheMySqlManager.ReservedAmount(MyInventoryItem.SqlID)) < MyInventoryItem.quantity) { tempAmount = MyInventoryItem.quantity; tempAmount = tempAmount - (TheMySqlManager.ReservedAmount(MyInventoryItem.SqlID)); } else { continue; } msg2 = tempAmount.ToString(); } msg2 = msg2.PadLeft(6, i == 0 ? ' ' : invFiller); msg = msg + "|" + msg2; TradeHandler.SellingItem MySellingItem = (TradeHandler.SellingItem)(MySellingItemsList[MyInventoryItem.SqlID]); if(isinv) msg2 = MySellingItem.pricesale.ToString(); else msg2 = MySellingItem.pricesalemembers.ToString(); if (!msg2.Contains(".")) msg2 += ".00gc"; else if (msg2[msg2.Length - 2] == '.') msg2 += "0gc"; else msg2 += "gc"; msg2 = msg2.PadLeft(13, i == 0 ? ' ' : invFiller); msg = msg + "|" + msg2; msg2 = MyInventoryItem.SqlID.ToString().PadLeft(5, i == 0 ? ' ' : invFiller); msg = msg + "|" + msg2; Inv[c] = msg; c++; i = 1 - i; } } int d; // for (d = 0; d < c; d++) // { // str = Inv[d].Substring(16) + Inv[d].Substring(0, 16); // Inv[d] = str; // } Array.Sort(Inv); i = maxlen + 13; string filter = ""; if (CommandArray.Length > 1) { bool firstTime = true; foreach (string filterPart in CommandArray) { if (firstTime) { firstTime = false; continue; } filter += (" " + filterPart); } //filter = Message.Substring(CommandArray[0].Length); } else filter = ""; for (d = 0; d < c; d++) { str = Inv[d]; //27 chars after the name.... if (filter == "" || Inv[d].ToLower().Contains(filter.ToLower().Trim())) { string[] outFields = Inv[d].Split('|'); string outString = Inv[d]; if (outFields[0].Length > maxlen) { outString = outFields[0].Substring(0, maxlen - 3) + "..."; outString = outString.PadRight(maxlen, ' ') + "|".PadRight(7, ' ') + "|".PadRight(14, ' ') + "|".PadRight(6, ' '); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, outString)); outString = ("[..." + outFields[0].Substring(maxlen - 3).Trim()).PadRight(maxlen, ' '); int count = 0; foreach (string tempString in outFields) { if (count == 0) { count++; continue; } outString += "|" + tempString; } } TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, outString)); } else { //for (i = 1; i < CommandArray.Length; i++) { //if (Inv[d].ToLower().Contains(CommandArray[i].ToLower().Trim())) Console.WriteLine("inv(d): " + Inv[d] + " filter: " + filter); if (Inv[d].ToLower().Contains(filter.ToLower().Trim())) { string[] outFields = Inv[d].Split('|'); string outString = Inv[d]; if (outFields[0].Length > maxlen) { outString = outFields[0].Substring(0, maxlen - 3) + "..."; outString = outString.PadRight(maxlen, ' ') + "|".PadRight(14, ' ') + "|".PadRight(9, ' '); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, outString)); outString = ("[..." + outFields[0].Substring(maxlen - 3).Trim()).PadRight(maxlen, ' '); foreach (string tempString in outFields) { outString += "|" + tempString; } } TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, outString)); i = CommandArray.Length; } } } } int Phys = TheMySqlManager.GetBotPhysqiue(Settings.botid); int Coord = TheMySqlManager.GetBotCoordination(Settings.botid); int carry = (Phys + Coord) * 10; //int UsedSpace = TheMySqlManager.GetBotUsedSpace(Settings.botid); //int UsedSlots = TheMySqlManager.GetBotUsedSlots(Settings.botid); int UsedSpace = TheStats.MyCurrentCarryingAmt; int FreeSpace = carry - UsedSpace; str = "["; str = str.PadRight(maxlen + 27, '-'); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); str = "["; str += FreeSpace.ToString() + " EMU Avail|"; str += (36-UsedSlots).ToString() + " Open slot(s)"; if (rank > 89) { //str += TheMySqlManager.moneylevel(Settings.botid).ToString() + " gc"; str += "|"+TheInventory.GetMoneyAmount().ToString() + " gc"; } str = str.PadRight(maxlen + 27, ' '); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); str = "["; if (Member) { if ((CommandArray[0] != "#im" && CommandArray[0] != "#invmembers" && CommandArray[0] != "#invmemvers" && CommandArray[0] != "#invmember" && CommandArray[0] != "#invmemver")) { str = str.PadRight(maxlen + 27, '-'); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); str = "[Use invmembers (im) to see member prices"; str = str.PadRight(maxlen + 27, ' '); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); } //if (isinv) //{ // str = "[to see member prices use invmembers or im"; // str = str.PadRight(maxlen + 28, ' '); // TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); //} } str = "["; str = str.PadRight(maxlen + 27, '-'); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); return; } return; WrongArguments: TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[--------------------------------------")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[Here is the usage of the #inv command:")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[#inv ")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[--------------------------------------")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[Example: #inv ")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[Example: #inv silver ore ")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "[--------------------------------------")); return; }
private void OnGotPM(object sender, BasicCommunication.MessageParser.Got_PM_EventArgs e) { int UsedSlots = 0; string Message = e.Message.ToLower().Replace("\'", "\\\'").Replace("\"", "\\\""); string[] Inv = new string[512]; if (Message[0] != '#') { Message = "#" + Message; } string[] CommandArray = Message.Split(' '); if (CommandArray[0] == "#invlist" || CommandArray[0] == "#il") { bool disabled = TheMySqlManager.CheckIfCommandIsDisabled("#invlist", Settings.botid); if (disabled == true) { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "This command is disabled")); return; } int rank = TheMySqlManager.GetUserRank(e.username, Settings.botid); if (rank < TheMySqlManager.GetCommandRank("#invlist", Settings.botid)) { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "You are not authorized to use this command!")); return; } if (this.TheTradeHandler.AmITrading() && e.username != TradeHandler.username) { TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, "I am currently trading, please retry shortly.")); return; } char invFiller = TheMySqlManager.getInvFiller(); string str1 = "", str2 = ""; if (TheInventory.GettingInventoryItems == true) { str2 = "I am building my inventory list, please try again in a few seconds"; str1 = str1.PadRight(str2.Length, '='); str1 = "[" + str1; str2 = "[" + str2; TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str2)); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); return; } if (CommandArray.Length < 1) goto WrongArguments; System.Collections.ArrayList MyInventoryList = TheInventory.GetInventoryList(); System.Collections.Hashtable MySellingItemsList = TheMySqlManager.GetSellingItemList(0); // sum up all inventory items if the items are on sale int i = 0; for (i = 0; i < 512; i++) Inv[i] = "ZZZZZZZZZZZZZZZZ"; int c = 0; System.Collections.SortedList TheInventoryList = new System.Collections.SortedList(); System.Collections.SortedList TheWornList = new System.Collections.SortedList(); int ii = 0; foreach (Inventory.inventory_item MyInventoryItem in MyInventoryList) { ii++; if (TheInventoryList.Contains(MyInventoryItem.SqlID) && MyInventoryItem.pos < 36) { // if (MyInventoryItem.pos < 36) { Inventory.inventory_item TempInventoryItem = (Inventory.inventory_item)TheInventoryList[MyInventoryItem.SqlID]; TempInventoryItem.quantity += MyInventoryItem.quantity; TheInventoryList[MyInventoryItem.SqlID] = TempInventoryItem; } } else { if (MyInventoryItem.pos < 36) { TheInventoryList.Add(MyInventoryItem.SqlID, MyInventoryItem); } } if (MyInventoryItem.pos > 35 && MyInventoryItem.pos < 44) { TheWornList.Add(MyInventoryItem.SqlID, MyInventoryItem); } } int maxlen = 4; foreach (Inventory.inventory_item MyInventoryItem in TheInventoryList.Values) { // if (maxlen < MyInventoryItem.name.Length && MyInventoryItem.pos < 44) if (maxlen < MyInventoryItem.name.Length && MyInventoryItem.pos < 36) { maxlen = MyInventoryItem.name.Length; } } foreach (Inventory.inventory_item MyInventoryItem in TheWornList.Values) { if (maxlen <= MyInventoryItem.name.Length + 3) maxlen = MyInventoryItem.name.Length + 3; } str2 = ""; str1= "["; str1= str1.PadRight(maxlen + 16, '-'); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); str1= "[ id |"; str2 = "quantity"; str2 = str2.PadRight(9, ' ')+"|"; str1+= str2; str2 = "name"; str2 = str2.PadRight(maxlen, ' '); str1= str1+ str2; TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); str1= "["; str1= str1.PadRight(maxlen + 16, '-'); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); // pm all summed up inventory items on sale c=0; i = 1; foreach (Inventory.inventory_item MyInventoryItem in TheWornList.Values) { if (MyInventoryItem.pos < 44) { if (MyInventoryItem.pos < 36) { if (MyInventoryItem.is_stackable) UsedSlots++; else UsedSlots = UsedSlots + (int)(MyInventoryItem.quantity); } str1 = ""; str2 = ""; str2 += MyInventoryItem.SqlID.ToString(); str2 = str2.PadLeft(4, i == 0 ? ' ' : invFiller); str2 = "[" + str2 + "|"; str1 = MyInventoryItem.quantity.ToString(); str1 = str1.PadLeft(9, i == 0 ? ' ' : invFiller); str2 += str1 + "|"; if (MyInventoryItem.pos > 35) str1 = "{E}" + MyInventoryItem.name; else str1 = MyInventoryItem.name; str1 = str1.PadRight(maxlen, i == 0 ? ' ' : invFiller); str1 = str2 + str1; //TradeHandler.SellingItem MySellingItem = (TradeHandler.SellingItem)(MySellingItemsList[MyInventoryItem.SqlID]); //TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); Inv[c++] = str1; //i = 1 - i; } } foreach (Inventory.inventory_item MyInventoryItem in TheInventoryList.Values) { if (MyInventoryItem.pos < 44) { if (MyInventoryItem.pos < 36) { if (MyInventoryItem.is_stackable) UsedSlots++; else UsedSlots = UsedSlots + (int)(MyInventoryItem.quantity); } str1 = ""; str2 = ""; str2 += MyInventoryItem.SqlID.ToString(); str2 = str2.PadLeft(4, i == 0 ? ' ' : invFiller); str2 = "[" + str2 + "|"; str1 = MyInventoryItem.quantity.ToString(); str1 = str1.PadLeft(9, i == 0 ? ' ' : invFiller); str2 += str1+"|"; if (MyInventoryItem.pos > 35) str1 = "{E}" + MyInventoryItem.name; else str1 = MyInventoryItem.name; str1 = str1.PadRight(maxlen, i == 0 ? ' ' : invFiller); str1 = str2 + str1; //TradeHandler.SellingItem MySellingItem = (TradeHandler.SellingItem)(MySellingItemsList[MyInventoryItem.SqlID]); //TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); Inv[c++] = str1; //i = 1 - i; } } int d; string str; for (d = 0; d < c; d++) { str = Inv[d].Substring(16) + Inv[d].Substring(0, 16); Inv[d] = str; } Array.Sort(Inv); i = maxlen + 13; string filter = ""; if (CommandArray.Length > 1) { bool firstTime = true; foreach (string filterPart in CommandArray) { if (firstTime) { firstTime = false; continue; } filter += (" " + filterPart); } //filter = Message.Substring(CommandArray[0].Length); } else filter = ""; //for (d = c - 1; d >= 0; d--) for (d = 0; d <c; d++) { i = Inv[d].Length - 16; str = Inv[d].Substring(i); str += Inv[d].Substring(0, i); Inv[d] = str.Substring(str.Length - 16); if (filter == "" || str.ToLower().Contains(filter.ToLower().Trim())) { //string[] outFields = Inv[d].Split('|'); //string outString = Inv[d]; //if (outFields[0].Length > maxlen) //{ // outString = outFields[0].Substring(0, maxlen - 3) + "..."; // outString = outString.PadRight(maxlen, ' ') + "|".PadRight(14, ' ') + "|".PadRight(9, ' '); // TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, outString)); // outString = "[...".PadRight(maxlen, ' '); // foreach (string tempString in outFields) // { // outString += "|" + tempString; // } //} TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); } else { //for (i = 1; i < CommandArray.Length; i++) { if (str.ToLower().Contains(filter.ToLower().Trim())) { //string[] outFields = Inv[d].Split('|'); //string outString = Inv[d]; //if (outFields[0].Length > maxlen) //{ // outString = outFields[0].Substring(0, maxlen - 3) + "..."; // outString = outString.PadRight(maxlen, ' ') + "|".PadRight(14, ' ') + "|".PadRight(9, ' '); // TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, outString)); // outString = "[...".PadRight(maxlen, ' '); // foreach (string tempString in outFields) // { // outString += "|" + tempString; // } //} TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str)); i = CommandArray.Length; } } } } int Phys = TheMySqlManager.GetBotPhysqiue(Settings.botid); int Coord = TheMySqlManager.GetBotCoordination(Settings.botid); int carry = (Phys + Coord) * 10; int UsedSpace = TheStats.MyCurrentCarryingAmt; int FreeSpace = carry - UsedSpace; str1= "["; str1= str1.PadRight(maxlen + 16, '-'); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); str1 = "["; str1 += FreeSpace.ToString() + " EMU Avail|"; str1 += (36 - UsedSlots).ToString() + " Open slot(s)"; if (rank > 89) { str1 += "|"+TheInventory.GetMoneyAmount().ToString() + " gc"; } str1 = str1.PadRight(maxlen + 16, ' '); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); str1= "["; str1= str1.PadRight(maxlen + 16, '-'); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username, str1)); return; } return; WrongArguments: TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username,"[Here is the usage of the #invlist command:")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username,"[#invlist ")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username,"[------------------------------------------")); TheTCPWrapper.Send(CommandCreator.SEND_PM(e.username,"[Example: #invlist ")); return; }
private void initConfig() { Application["product"] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; Application["version"] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; resources = new System.Resources.ResourceManager("SharpWebMail", System.Reflection.Assembly.GetExecutingAssembly()); Application["resources"] = resources; System.Collections.Hashtable config = (System.Collections.Hashtable)System.Configuration.ConfigurationSettings.GetConfig("sharpwebmail"); foreach ( System.Collections.DictionaryEntry item in config ) { Application.Add(item.Key.ToString(), item.Value); } config = null; if ( Application["sharpwebmail/send/addressbook"]!=null ) { Application["sharpwebmail/general/addressbooks"] = true; } if ( (bool)Application["sharpwebmail/read/message/useserverencoding"] ) { anmar.SharpMimeTools.SharpMimeHeader.EncodingDefault = System.Text.Encoding.Default; } TestAvailableCultures(); System.Collections.SortedList availablecultures_values = new System.Collections.SortedList(availablecultures.Count); foreach ( System.Collections.DictionaryEntry item in availablecultures ) { availablecultures_values.Add(item.Value, item.Key); } Application["AvailableCultures"] = availablecultures_values; initInvariantCulture(); Application["sharpwebmail/read/message/temppath"] = parseTempFolder(Server.MapPath("/"), Application["sharpwebmail/read/message/temppath"]); Application["sharpwebmail/send/message/temppath"] = parseTempFolder(Server.MapPath("/"), Application["sharpwebmail/send/message/temppath"]); }
public void MainLoop() { string sXMLSourceDirectory = @"c:\mediafiles\backup"; bool bFound = false; RetryXMLFileList retrylist = new RetryXMLFileList(); bool bVerbose = false; #if DEBUG log.WriteLog("Sleeping for 10 seconds"); System.Threading.Thread.Sleep(10000); #endif ActiveThreadCount = 0; MaxActiveThreadCount = 1; // begin routine // determine how many encoders can be active at once try { Microsoft.Win32.RegistryKey regKey = log.CarverLabRegistryKey(); MaxActiveThreadCount = (int)regKey.GetValue("MaxUploadThreadCount",1); int itemp; itemp = (int)regKey.GetValue("EncoderResponseTimeoutMinutes",7); if (itemp > short.MaxValue) EncoderResponseTimeoutMinutes = short.MaxValue; else EncoderResponseTimeoutMinutes = (short)itemp; log.bDebugMode = ((string)regKey.GetValue("DebugMode") == "1"); itemp = (int)regKey.GetValue("EncoderRetryFileIntervalSeconds",300); if (itemp > short.MaxValue) EncoderRetryFileIntervalSeconds = short.MaxValue; else EncoderRetryFileIntervalSeconds = (short)itemp; itemp = (int)regKey.GetValue("VerboseLogOutput"); if (itemp > 0) { bVerbose = true; log.WriteLog("*** Verbose output enabled! ***"); } } catch (System.Exception regex) { log.WriteLog("Registry read error: " + regex.Message); } log.WriteLog("Oyster Encoder will spawn at most " + MaxActiveThreadCount + " encoding threads."); // create a thread sync'ed list to hold thread instances ThreadList = new EncoderThreadList(); // get the directory name that video and xml files are dropped // into and store into vdirectory try { bFound = false; OysterClassLibrary.Oyster o = new OysterClassLibrary.Oyster(); foreach (OysterClassLibrary.ForwardingServer fs in o.FORWARDINGSERVERS) { if (fs.Address != "Not Assigned") { foreach (OysterClassLibrary.MediaBufferServer mbs in fs.CurrentMediaBufferServers) { if (mbs.Address != "Not Assigned") { sXMLSourceDirectory = mbs.StorageDirectory; bFound = true; // get OysterRootDirectory from the system OysterRootDirectory = (string) o.GetVideoStorageServerById(fs.CurrentVideoStorageServer.ID).CurrentVideoStorageServerType["OysterRootDirectory"]; // get OysterSourceDirectory from the system OysterSourceDirectory = (string) o.GetVideoStorageServerById(fs.CurrentVideoStorageServer.ID).CurrentVideoStorageServerType["OysterSourceDirectory"]; // get OysterProfileName from the system OysterProfileName = (string) o.GetVideoStorageServerById(fs.CurrentVideoStorageServer.ID).CurrentVideoStorageServerType["OysterProfile"]; break; } } } } if (!bFound) { log.WriteLog("Could not find a source directory in the configuration. There is nothing to do. Aborting."); return; } } catch (System.Exception oex) { log.WriteLog("MainLoop: When attempting to open the OysterClassLibrary and exception occured: " + oex.Message); return; } if (false == System.IO.Directory.Exists(sXMLSourceDirectory)) { try { System.IO.Directory.CreateDirectory(sXMLSourceDirectory); } catch (System.Exception dex) { log.WriteLog("Unable to create the directory " + sXMLSourceDirectory + ": " + dex.Message + ". Aborting."); return; } } log.WriteLog("Reading files from " + sXMLSourceDirectory); m_EventMonitor = new System.Threading.ManualResetEvent(true); CarverLab.Utility.EncodingServiceInfo esi = new CarverLab.Utility.EncodingServiceInfo(); esi.Initialize(@"c:\EncodingServiceInfo.xml"); dtStart = System.DateTime.Now; string FAILEDFILE = ""; // while this thread is active log.WriteLog("Entering work loop..."); while (false == IsDone) { try { #if !DEBUG System.Threading.Thread.Sleep(5000); #endif if (bVerbose) { log.WriteLog("Serializing EncodingServiceInfo"); } esi.Serialize(); // get a list of all files in vdirectory with a .xml extension System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sXMLSourceDirectory); System.IO.FileInfo[] fiFileInfoList = di.GetFiles("*.xml"); System.Collections.SortedList slFileInfoList = new System.Collections.SortedList(new FileInfoDateComparer(FileInfoDateComparer.DateCompareType.CreationTime)); System.IO.FileInfo[] fiFileInfoErrorList = di.GetFiles("*.err"); // check to see that the system is still running... // for each file in vdirectory if (bVerbose) { log.WriteLog("Read XML files from " + sXMLSourceDirectory); } System.Collections.ArrayList alErrs = new System.Collections.ArrayList(); if (esi.m_esi.CurrentEncodings != null) { for (int i = 0; i < esi.m_esi.CurrentEncodings.Length; i++) { CarverLab.Utility.Encoding enc = esi.m_esi.CurrentEncodings[i]; if (enc.XMLPathFile.EndsWith(".err")) { if (!System.IO.File.Exists(enc.XMLPathFile)) { alErrs.Add(enc); } } } } m_EventMonitor.WaitOne(10000,false); foreach (object obj in alErrs) { CarverLab.Utility.Encoding enc = (CarverLab.Utility.Encoding) obj; esi.Remove(enc.UniqueIdentifier); } m_EventMonitor.Set(); if (bVerbose) { log.WriteLog("Scanning files..."); } foreach (System.IO.FileInfo fi in fiFileInfoErrorList) { if (esi.UniqueIdentifierOfXMLFile(fi.FullName) == null) { m_EventMonitor.WaitOne(10000,false); string su = esi.Add(fi.FullName,"","",-1.0); esi.AddError(su,"Error File"); m_EventMonitor.Set(); if (bVerbose) { log.WriteLog("Error file: " + fi.FullName); } } } System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); foreach (System.IO.FileInfo fi in fiFileInfoList) { if (esi.UniqueIdentifierOfXMLFile(fi.FullName) == null) { FAILEDFILE = fi.FullName; CheckAndFixXMLInput(fi.FullName); CarverLab.Utility.CARDVIDEO cv = (CarverLab.Utility.CARDVIDEO)Deserialize(fi.FullName, typeof(CarverLab.Utility.CARDVIDEO)); m_EventMonitor.WaitOne(10000,false); if (cv == null) { esi.Add(fi.FullName,"","",-1.0); } else { esi.Add(fi.FullName,cv.FILENAME,cv.FILETITLE,-1.0); } if (bVerbose) { log.WriteLog("File: " + fi.FullName); } m_EventMonitor.Set(); } if (!retrylist.Contains(fi.FullName)) { slFileInfoList.Add(fi,fi); } else { TimeSpan ts = DateTime.Now - retrylist[fi.FullName].LastChecked; if (ts.TotalSeconds > EncoderRetryFileIntervalSeconds) { retrylist.Remove(fi.FullName); } } } foreach (System.Collections.DictionaryEntry entry in slFileInfoList) { System.IO.FileInfo fi = entry.Value as System.IO.FileInfo; if (bVerbose) { log.WriteLog("Considering " + fi.FullName); } // } // foreach (System.IO.FileInfo fi in fiFileInfoList) // { // sleep a bit to save processor time #if !DEBUG System.Threading.Thread.Sleep(1000); #endif if (ActiveThreadCount >= MaxActiveThreadCount) { break; } string sXMLFilename, sVideoFilename; FAILEDFILE = fi.FullName; sXMLFilename = fi.FullName; // search for filename in thread list // if filename exists in thread list skip to next file if (ThreadList.Contains(sXMLFilename)) { if (bVerbose) { log.WriteLog(fi.FullName + " is already active"); } continue; } // endif // open the xml file if (bVerbose) { log.WriteLog("Reading XML file " + sXMLFilename); } CarverLab.Utility.CARDVIDEO cv = (CarverLab.Utility.CARDVIDEO)Deserialize(sXMLFilename, typeof(CarverLab.Utility.CARDVIDEO)); // read the video file name in the xml file sVideoFilename = cv.FILENAME; // if no matching video file exists continue with the next file if (bVerbose) { log.WriteLog("Checking for matching video file"); } if (false == System.IO.File.Exists(sVideoFilename)) { m_EventMonitor.WaitOne(10000,false); ErrorRenameXML(null,sXMLFilename,"*ERROR* " + sVideoFilename + " does not exist for " + sXMLFilename); m_EventMonitor.Set(); continue; } System.IO.FileStream tfs; try { if (bVerbose) { log.WriteLog("Opening file: " + sVideoFilename); } tfs = System.IO.File.Open(sVideoFilename,System.IO.FileMode.Open); if (null == tfs) { m_EventMonitor.WaitOne(10000,false); ErrorRenameXML(null,sXMLFilename,"*ERROR* " + sVideoFilename + " could not open file."); m_EventMonitor.Set(); continue; } } catch (Exception ex1) { m_EventMonitor.WaitOne(10000,false); ErrorRenameXML(null,sXMLFilename,"*ERROR* " + sVideoFilename + " could not open file: " + ex1.Message); m_EventMonitor.Set(); continue; } if (bVerbose) { log.WriteLog("Checking length of file " + sVideoFilename); } long len = tfs.Length; tfs.Close(); if (len < (256 * 1024)) { m_EventMonitor.WaitOne(10000,false); ErrorRenameXML(null,sXMLFilename,"*ERROR* " + sVideoFilename + " file is too small, will not process."); m_EventMonitor.Set(); continue; } if (bVerbose) { log.WriteLog("Creating encoder for " + sVideoFilename); } EncoderThreadItem eti = new EncoderThreadItem(); // create a new thread that is suspended // assign the EncodeFile routine to the new thread System.Threading.Thread thr = new System.Threading.Thread(new System.Threading.ThreadStart(eti.Encode)); // pass the thread list index into the new thread eti.log = this.log; eti.m_bIsCompleted = false; eti.m_EncodeFileThread = thr; eti.m_sXMLFilename = sXMLFilename; eti.OysterProfileName = this.OysterProfileName; eti.OysterRootDirectory = this.OysterRootDirectory; eti.OysterSourceDirectory = this.OysterSourceDirectory; eti.m_EventMonitor = this.m_EventMonitor; eti.m_esi = esi; // place filename into the thread list ThreadList.Add(sXMLFilename,eti); // activate the new thread thr.Start(); //ActiveThreadCount++; log.WriteLog("New encoding thread created. ActiveThreadCount = " + (ActiveThreadCount + 1) + " of " + MaxActiveThreadCount); FAILEDFILE = ""; // endfor } fiFileInfoList = null; di = null; } catch (System.Exception whex) { if (FAILEDFILE.Length > 0) { retrylist[FAILEDFILE] = new RetryXMLFile(); TimeSpan ts = DateTime.Now - retrylist[FAILEDFILE].LastChecked; retrylist[FAILEDFILE].LastChecked = DateTime.Now; if (ts.TotalSeconds > 15) // if (retrylist[FAILEDFILE].CheckedCount++ > 5) { log.WriteLog(FAILEDFILE + " being renamed."); System.IO.FileInfo fi = new System.IO.FileInfo(FAILEDFILE); fi.MoveTo(System.IO.Path.ChangeExtension(fi.FullName,"failed")); } } else { log.WriteLog("*ERROR* EncodeLauncher.MainLoop Exception: " + whex.Message); log.WriteLog(" Pausing for one second before continuing..."); } System.Threading.Thread.Sleep(1000); } // cleanup any completed threads System.Collections.ArrayList al = new System.Collections.ArrayList(); foreach (string ss in ThreadList) { EncoderThreadItem ti = ThreadList[ss]; bool bAddIt, bAbortIt; bAddIt = false; bAbortIt = false; if (ti.IsCompleted) { bAddIt = true; log.WriteLog(ti.m_sXMLFilename + " is scheduled for release."); } else { try { // if no error on the encoder // check for the encoder lockup by comparing the the encoding // time right now with the encoding time save one minute ago. if (false == ti.IsEncoderResponding(EncoderResponseTimeoutMinutes)) { log.WriteLog(ti.m_sXMLFilename + " is scheduled for emergency release."); bAddIt = true; bAbortIt = true; } } catch (System.Exception handlerex) { log.WriteLog("In the Thread Freeze handler: " + handlerex.Message); bAddIt = true; if (null != ti.m_EncodeFileThread) bAbortIt = true; } } if (bAddIt) { if (!bAbortIt) { al.Add(ti.m_sXMLFilename); //ActiveThreadCount--; } //log.WriteLog(ss + ": encoding thread destroyed. ActiveThreadCount = " + ActiveThreadCount // + " of " + MaxActiveThreadCount); } if (bAbortIt) { log.WriteLog(ss + ": encoder not responding, **ABORTING** thread."); log.WriteLog(ss + ": Performing Emergency Stop."); ti.EmergencyStop(); m_EventMonitor.WaitOne(10000,false); ThreadList.Remove(ti.m_sXMLFilename); m_EventMonitor.Set(); log.WriteLog(ss + ": Thread removed from management list."); ActiveThreadCount--; } } foreach (string ss in al) { string sXMLFilename, sVideoFilename; sXMLFilename = ss; // open the xml file CarverLab.Utility.CARDVIDEO cv = (CarverLab.Utility.CARDVIDEO)Deserialize(sXMLFilename, typeof(CarverLab.Utility.CARDVIDEO)); // read the video file name in the xml file sVideoFilename = cv.FILENAME; // delete the XML and video files log.WriteLog("Cleaning up XML and video source files"); try { if (ThreadList[sXMLFilename].DidEncodingFail) { // skip deletion of files log.WriteLog("\t" + sXMLFilename + " is being skipped for deletion."); } else { log.WriteLog("\t" + sXMLFilename); System.IO.File.Delete(sXMLFilename); log.WriteLog("\t" + sVideoFilename); System.IO.File.Delete(sVideoFilename); } m_EventMonitor.WaitOne(10000,false); esi.Remove(ThreadList[ss].m_sUniqueIdentifier); m_EventMonitor.Set(); } catch(System.Exception fdex) { log.WriteLog("Unable to delete file: " + fdex.Message); //esi.UpdateError(ThreadList[ss].m_sUniqueIdentifier,"Failed to stop."); } ThreadList.Remove(ss); } // end while } // end routine esi.DeInitialize(); log.WriteLog("Clean exit."); }
private void Script_GET_PARTY(string inp) { string sdest = Get_String(ref inp); ScriptVariable dest = Get_Var(sdest); if (dest.Type == Var_Types.ARRAYLIST) { ((System.Collections.ArrayList)dest.Value).Clear(); } else if (dest.Type == Var_Types.SORTEDLIST) { ((System.Collections.SortedList)dest.Value).Clear(); } else { ScriptEngine.Script_Error("INVLAID DESTINATION TYPE"); return; } Globals.PartyLock.EnterReadLock(); try { foreach (PartyMember pl in Globals.gamedata.PartyMembers.Values) { CharInfo ch; Globals.PlayerLock.EnterReadLock(); try { ch = Util.GetChar(pl.ID); } finally { Globals.PlayerLock.ExitReadLock(); } Script_ClassData cd = new Script_ClassData(); cd.Name = "PLAYER"; cd._Variables.Add("ID", new ScriptVariable((long)pl.ID, "ID", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("NAME", new ScriptVariable(pl.Name, "NAME", Var_Types.STRING, Var_State.PUBLIC)); cd._Variables.Add("CLASS", new ScriptVariable((long)pl.Class, "CLASS", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("LEVEL", new ScriptVariable((long)pl.Level, "LEVEL", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("HP", new ScriptVariable((long)pl.Cur_HP, "HP", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("MAX_HP", new ScriptVariable((long)pl.Max_HP, "MAX_HP", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("MP", new ScriptVariable((long)pl.Cur_MP, "MP", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("MAX_MP", new ScriptVariable((long)pl.Max_MP, "MAX_MP", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("CP", new ScriptVariable((long)pl.Cur_CP, "CP", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("MAX_CP", new ScriptVariable((long)pl.Max_CP, "MAX_CP", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("PER_HP", new ScriptVariable(Math.Round((double)pl.Cur_HP / (double)pl.Max_HP * 100, 2), "PER_HP", Var_Types.DOUBLE, Var_State.PUBLIC)); cd._Variables.Add("PER_MP", new ScriptVariable(Math.Round((double)pl.Cur_MP / (double)pl.Max_MP * 100, 2), "PER_MP", Var_Types.DOUBLE, Var_State.PUBLIC)); cd._Variables.Add("PER_CP", new ScriptVariable(Math.Round((double)pl.Cur_CP / (double)pl.Max_CP * 100, 2), "PER_CP", Var_Types.DOUBLE, Var_State.PUBLIC)); try { System.Collections.SortedList buffs = new System.Collections.SortedList(); foreach (CharBuff buff in pl.my_buffs.Values) { Script_ClassData ncd = new Script_ClassData(); ncd.Name = "EFFECT"; ncd._Variables.Add("ID", new ScriptVariable((long)buff.ID, "ID", Var_Types.INT, Var_State.PUBLIC)); ncd._Variables.Add("LEVEL", new ScriptVariable((long)buff.SkillLevel, "LEVEL", Var_Types.INT, Var_State.PUBLIC)); ncd._Variables.Add("DURATION", new ScriptVariable((long)buff.ExpiresTime, "DURATION", Var_Types.INT, Var_State.PUBLIC)); ncd._Variables.Add("NAME", new ScriptVariable(Util.GetSkillName(buff.ID, buff.SkillLevel), "NAME", Var_Types.STRING, Var_State.PUBLIC)); ScriptVariable nsv = new ScriptVariable(ncd, "EFFECT", Var_Types.CLASS, Var_State.PUBLIC); buffs.Add(buff.ID.ToString(), nsv); } cd._Variables.Add("EFFECTS", new ScriptVariable((System.Collections.SortedList)buffs, "EFFECTS", Var_Types.SORTEDLIST, Var_State.PUBLIC)); } catch { System.Collections.SortedList empty = new System.Collections.SortedList(); cd._Variables.Add("EFFECTS", new ScriptVariable((System.Collections.SortedList)empty, "EFFECTS", Var_Types.SORTEDLIST, Var_State.PUBLIC)); } if (ch == null) { cd._Variables.Add("X", new ScriptVariable((long)pl.X, "X", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("Y", new ScriptVariable((long)pl.Y, "Y", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("Z", new ScriptVariable((long)pl.Z, "Z", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("TITLE", new ScriptVariable("", "TITLE", Var_Types.STRING, Var_State.PUBLIC)); cd._Variables.Add("CLAN", new ScriptVariable(0L, "CLAN", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("ALLY", new ScriptVariable(0L, "ALLY", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("RACE", new ScriptVariable(0L, "RACE", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("SEX", new ScriptVariable(0L, "SEX", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("PVPFLAG", new ScriptVariable(0L, "PVPFLAG", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("KARMA", new ScriptVariable(0L, "KARMA", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("ATTACK_SPEED", new ScriptVariable(0L, "ATTACK_SPEED", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("CAST_SPEED", new ScriptVariable(0L, "CAST_SPEED", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("RUN_SPEED", new ScriptVariable(0L, "RUN_SPEED", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("TARGET_ID", new ScriptVariable(0L, "TARGET_ID", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("DEST_X", new ScriptVariable(0L, "DEST_X", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("DEST_Y", new ScriptVariable(0L, "DEST_Y", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("DEST_Z", new ScriptVariable(0L, "DEST_Z", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("LOOKS_DEAD", new ScriptVariable(0L, "LOOKS_DEAD", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("IN_COMBAT", new ScriptVariable(0L, "IN_COMBAT", Var_Types.INT, Var_State.PUBLIC)); //cd._Variables.Add("EFFECTS", new ScriptVariable((System.Collections.SortedList)pl.my_buffs, "EFFECTS", Var_Types.SORTEDLIST, Var_State.PUBLIC)); } else { cd._Variables.Add("X", new ScriptVariable((long)ch.X, "X", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("Y", new ScriptVariable((long)ch.Y, "Y", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("Z", new ScriptVariable((long)ch.Z, "Z", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("TITLE", new ScriptVariable(ch.Title, "TITLE", Var_Types.STRING, Var_State.PUBLIC)); cd._Variables.Add("CLAN", new ScriptVariable((long)ch.ClanID, "CLAN", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("ALLY", new ScriptVariable((long)ch.AllyID, "ALLY", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("RACE", new ScriptVariable((long)ch.Race, "RACE", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("SEX", new ScriptVariable((long)ch.Sex, "SEX", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("PVPFLAG", new ScriptVariable((long)ch.PvPFlag, "PVPFLAG", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("KARMA", new ScriptVariable((long)ch.Karma, "KARMA", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("ATTACK_SPEED", new ScriptVariable((long)(ch.PatkSpeed * ch.AttackSpeedMult), "ATTACK_SPEED", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("CAST_SPEED", new ScriptVariable((long)ch.MatkSpeed, "CAST_SPEED", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("RUN_SPEED", new ScriptVariable((long)(ch.RunSpeed * ch.MoveSpeedMult), "RUN_SPEED", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("TARGET_ID", new ScriptVariable((long)ch.TargetID, "TARGET_ID", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("DEST_X", new ScriptVariable((long)ch.Dest_X, "DEST_X", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("DEST_Y", new ScriptVariable((long)ch.Dest_Y, "DEST_Y", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("DEST_Z", new ScriptVariable((long)ch.Dest_Z, "DEST_Z", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("LOOKS_DEAD", new ScriptVariable((long)ch.isAlikeDead, "LOOKS_DEAD", Var_Types.INT, Var_State.PUBLIC)); cd._Variables.Add("IN_COMBAT", new ScriptVariable((long)ch.isInCombat, "IN_COMBAT", Var_Types.INT, Var_State.PUBLIC)); //cd._Variables.Add("EFFECTS", new ScriptVariable((System.Collections.SortedList)pl.my_buffs, "EFFECTS", Var_Types.SORTEDLIST, Var_State.PUBLIC)); } ScriptVariable sv = new ScriptVariable(cd, "PLAYER", Var_Types.CLASS, Var_State.PUBLIC); if (dest.Type == Var_Types.ARRAYLIST) { ((System.Collections.ArrayList)dest.Value).Add(sv); } else if (dest.Type == Var_Types.SORTEDLIST) { ((System.Collections.SortedList)dest.Value).Add(pl.ID.ToString(), sv); } } } finally { Globals.PartyLock.ExitReadLock(); } }
/// <summary> /// This function will return the smallest possible group number, which is currently not in use. /// </summary> /// <returns>The smallest unused group number (starting at 0).</returns> public int GetUnusedColumnGroupNumber() { System.Collections.SortedList groupNums = new System.Collections.SortedList(); for(int i=0;i<ColumnCount;i++) { int group = this.GetColumnGroup(i); if(!groupNums.ContainsKey(group)) groupNums.Add(group,null); } for(int i=0;i<int.MaxValue;i++) { if(!groupNums.Contains(i)) return i; } return 0; }
private void AdvertTimer_Tick(object sender, ElapsedEventArgs e) { try { int i = 0; uint advertchannel = TheMySqlManager.advertchannel(Settings.botid); Random RandomClass = new Random(); string advertstr = "", str2 = "", endm = TheMySqlManager.advertendmessage().Trim(); if (TheTradeHandler.AmITrading() || (TheInventory.GettingInventoryItems == true)) { this.AdvertTimer.Interval = (1 * 1000);// +RandomClass.Next(0, (60 * 60 * 1000)); ;//m*s*us=1 hour TheLogger.Debug("Advert delayed due to current trade\n"); return; } if (advertchannel != 99999999) { //this.AdvertTimer.Interval = (15 * 60 * 1000) + RandomClass.Next(0, (60 * 60 * 1000)); ;//m*s*us=1 hour //this.AdvertTimer.Interval=60* i = TheMySqlManager.minadverttime() * 1000; i += (RandomClass.Next(0, TheMySqlManager.randomadvertdelay()) * 1000); if (i < 900000) i = 900000;//minimum 15 minute delay this.AdvertTimer.Interval = i; } else { if (MainClass.serverName == "test") { this.AdvertTimer.Interval = 1000; } } TheLogger.Debug("New AdvertTimer.Interval: " + this.AdvertTimer.Interval + "\n"); if (advertchannel != 99999999 && TheMySqlManager.lastadverttime(Settings.botid) < TheMySqlManager.minadverttime() && MainClass.serverName != "test") return; //Start the advertising here, if it's set to true... //Assumptions: 140 characters max length //Need to get advert_rates from the database for this bot to see how the weights are distributed if (TheMySqlManager.advertise()) { //decide if we should do a text message or a _goods_ message //get the rate for text adverts, it's a number between 0 and 1 //then get a random number between 0 and one, if the random number is less than the advert rate, do the advert //otherwise, do a _goods_ advert (buying and selling...) double advertTextRate = TheMySqlManager.getAdvertTextRate(); double sellRate = TheMySqlManager.getSellRate(); Random randomDouble = new Random(); double randomRate = randomDouble.NextDouble(); if (randomRate < advertTextRate) { //do a text advert //get a random row from the adverts table and use it as the advertisement //select * from adverts where botid = 2 order by rand() LIMIT 1; advertstr = TheMySqlManager.getTextAdvert(); } else { //do a goods advert (buying and selling) //get the selling rate, it's between 0 and 1 //get a random number between 0 and 1, if the rate is less than the selling rate, do a "selling" advert //otherwise, do a "buying" advert System.Collections.ArrayList MyInventoryList = TheInventory.GetInventoryList(); System.Collections.ArrayList MySellingItemsList = TheMySqlManager.GetSellingList(1); // sum up all inventory items if the items are on sale System.Collections.SortedList TheInventoryList = new System.Collections.SortedList(); System.Collections.ArrayList MyWantedItemsList = TheMySqlManager.GetWantedList(1); //add up the inventory stuff foreach (Inventory.inventory_item MyInventoryItem in MyInventoryList) { if (TheInventoryList.Contains(MyInventoryItem.SqlID) && MyInventoryItem.pos < 36) { Inventory.inventory_item TempInventoryItem = (Inventory.inventory_item)TheInventoryList[MyInventoryItem.SqlID]; TempInventoryItem.quantity += MyInventoryItem.quantity; TheInventoryList[MyInventoryItem.SqlID] = TempInventoryItem; } else { if (MyInventoryItem.pos < 36) { TheInventoryList.Add(MyInventoryItem.SqlID, MyInventoryItem); } } } randomRate = randomDouble.NextDouble(); if (randomRate < sellRate) { //selling advertstr = "Selling:"; foreach (TradeHandler.SellingItem MySellingItem in MySellingItemsList) { if (TheInventoryList.Contains(MySellingItem.KnownItemsSqlID)) { Inventory.inventory_item MyInventoryItem = (Inventory.inventory_item)TheInventoryList[MySellingItem.KnownItemsSqlID]; if (MySellingItem.pricesale > 0) { uint tempAmount = 0; if ((TheMySqlManager.ReservedAmount(MyInventoryItem.SqlID)) < MyInventoryItem.quantity) { tempAmount = MyInventoryItem.quantity; tempAmount = tempAmount - (TheMySqlManager.ReservedAmount(MyInventoryItem.SqlID)); } else { continue; } str2 = tempAmount.ToString() + " " + MyInventoryItem.name + ":" + MySellingItem.pricesale.ToString() + "gc"; if (advertstr.Length + str2.Length + endm.Length < 140) { if (advertstr.Length > 8) advertstr += ", "; advertstr += str2; } } } } if (advertstr.Length > 8) { advertstr += "|" + endm; } else { advertstr = ""; } } else { //buying advertstr = "Buying:"; foreach (TradeHandler.WantedItem MyWantedItem in MyWantedItemsList) { if (TheInventoryList.Contains(MyWantedItem.KnownItemsSqlID)) { Inventory.inventory_item MyInventoryItem = (Inventory.inventory_item)TheInventoryList[MyWantedItem.KnownItemsSqlID]; if (MyWantedItem.pricepurchase > 0 && MyInventoryItem.quantity < MyWantedItem.maxquantity) { str2 = TheMySqlManager.GetKnownItemsname(MyWantedItem.KnownItemsSqlID) + ":" + MyWantedItem.pricepurchase.ToString() + "gc"; if (advertstr.Length + str2.Length + endm.Length < 140) { if (advertstr.Length > 7) advertstr += ", "; advertstr += str2; } } } else { if (MyWantedItem.pricepurchase > 0) { str2 = TheMySqlManager.GetKnownItemsname(MyWantedItem.KnownItemsSqlID) + ":" + MyWantedItem.pricepurchase.ToString() + "gc"; if (advertstr.Length + str2.Length + endm.Length < 140) { if (advertstr.Length > 7) advertstr += ", "; advertstr += str2; } } } } if (advertstr.Length > 7) { advertstr += "|" + endm; } else { advertstr = ""; } } } } if (advertstr != "") { TheTCPWrapper.Send(CommandCreator.RAW_TEXT("#jc " + advertchannel.ToString())); TheTCPWrapper.Send(CommandCreator.RAW_TEXT("@" + advertstr)); TheTCPWrapper.Send(CommandCreator.RAW_TEXT("#lc " + advertchannel.ToString())); TheMySqlManager.advertlog("@@" + advertchannel.ToString() + " " + advertstr); string sql = "UPDATE bots SET lastadverttime = NOW() WHERE botid = " + Settings.botid; TheMySqlManager.raw_sql(sql); } advertstr = ""; } catch (Exception exception) { TheErrorHandler.writeErrorMessage("Exception raised in the advert handler..." + exception); } finally { } }