public void TestClearBasic() { StringBuilder sblMsg = new StringBuilder(99); SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); String s1 = null; String s2 = null; int i = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(this); // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // now Clear the list and verify the Count sl2.Clear(); //removes 0 element Assert.Equal(0, sl2.Count); // Testcase: add few key-val pairs for (i = 0; i < 100; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add(s1, s2); } // now get the list Count and verify Assert.Equal(100, sl2.Count); // now Clear the list and verify the Count sl2.Clear(); //removes all the 100 elements Assert.Equal(0, sl2.Count); }
//return how closely an input string resembles a single memory entry protected int calculateMatchRate(ArrayList input, ArrayList memory) { int matchRate = 0; IEnumerator i = input.GetEnumerator(); IEnumerator m = memory.GetEnumerator(); while(i.MoveNext()) { while(m.MoveNext()) { SortedList isNewWord = new SortedList(); string cc = (string)i.Current; string bb = (string)m.Current; cc.ToLower(); bb.ToLower(); //mehrfachwertung für ein wort vermeiden z.b. eine 3 für 3x "ich" if(!isNewWord.Contains(bb)) { isNewWord.Add(bb, bb); if(cc == bb) { matchRate++; } } isNewWord.Clear(); } } return matchRate; }
static public int Clear(IntPtr l) { try { System.Collections.SortedList self = (System.Collections.SortedList)checkSelf(l); self.Clear(); pushValue(l, true); return(1); } catch (Exception e) { return(error(l, e)); } }
public void ClearDoesNotTouchCapacity () { SortedList sl = new SortedList (); // according to MSDN docs Clear () does not change capacity for (int i = 0; i < 18; i++) { sl.Add (i, i); } int capacityBeforeClear = sl.Capacity; sl.Clear (); int capacityAfterClear = sl.Capacity; Assert.AreEqual (capacityBeforeClear, capacityAfterClear); }
/// <summary> /// see if any patches are missing; is there a direct line between FCurrentlyInstalledVersion and FLatestAvailablePatch? /// </summary> /// <returns>return a list of all patches that should be applied. empty list if there is a problem</returns> public SortedList CheckPatchesConsistent(SortedList AOrderedListOfAllPatches) { SortedList ResultPatchList = new SortedList(); TFileVersionInfo testPatchVersion; // get the latest patch that is available FLatestAvailablePatch = new TFileVersionInfo(FCurrentlyInstalledVersion); foreach (string patch in AOrderedListOfAllPatches.GetValueList()) { testPatchVersion = TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(patch); if (testPatchVersion.Compare(FLatestAvailablePatch) > 0) { FLatestAvailablePatch = testPatchVersion; } } // drop unnecessary patch files // ie. patch files leading to the same version, eg. 2.2.11-1 and 2.2.12-2 to 2.2.12-3 // we only want the biggest step testPatchVersion = new TFileVersionInfo(FCurrentlyInstalledVersion); bool patchesAvailable = true; while (patchesAvailable) { StringCollection applyingPatches = new StringCollection(); foreach (string patch in AOrderedListOfAllPatches.GetValueList()) { if (TPatchFileVersionInfo.PatchApplies(testPatchVersion, patch)) { applyingPatches.Add(patch); } } patchesAvailable = (applyingPatches.Count > 0); if (applyingPatches.Count > 0) { // see which of the applying patches takes us further string highestPatch = applyingPatches[0]; TFileVersionInfo highestPatchVersion = TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(highestPatch); foreach (string patch in applyingPatches) { if (TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(patch).Compare(highestPatchVersion) > 0) { highestPatch = patch; highestPatchVersion = TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(highestPatch); } } ResultPatchList.Add(highestPatch, highestPatch); testPatchVersion = highestPatchVersion; } } if (FLatestAvailablePatch.Compare(testPatchVersion) != 0) { // check for a generic patch file, starting from version 0.0.99.99 foreach (string patch in AOrderedListOfAllPatches.GetValueList()) { if (patch.Contains("0.0.99.99")) { testPatchVersion = TPatchFileVersionInfo.GetLatestPatchVersionFromDiffZipName(patch); ResultPatchList.Clear(); ResultPatchList.Add(patch, patch); } } } if (FLatestAvailablePatch.Compare(testPatchVersion) != 0) { TLogging.Log("missing patchfile from version " + testPatchVersion.ToString() + " to " + FLatestAvailablePatch.ToString()); return new SortedList(); } return ResultPatchList; }
public void TestClear () { SortedList sl1 = new SortedList (10); sl1.Add ("kala", 'c'); sl1.Add ("kala2", 'd'); Assert.AreEqual (10, sl1.Capacity, "#A1"); Assert.AreEqual (2, sl1.Count, "#A2"); sl1.Clear (); Assert.AreEqual (0, sl1.Count, "#B1"); #if !NET_2_0 // no such expectation as it is broken in .NET 2.0 Assert.AreEqual (16, sl1.Capacity, "#B2"); #endif }
public void Clear_Capacity_Reset () { SortedList sl = new SortedList (0); Assert.AreEqual (0, sl.Capacity, "#1"); sl.Clear (); // reset to class default (16) Assert.AreEqual (16, sl.Capacity, "#2"); sl.Capacity = 0; Assert.AreEqual (16, sl.Capacity, "#3"); // note: we didn't return to 0 - so Clear cahnge the default capacity }
public void TestGetValueListBasic() { StringBuilder sblMsg = new StringBuilder(99); SortedList sl2 = null; IEnumerator en = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); int i3 = 0; int i = 0; int j = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(); // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // Testcase: Set - null key, ArgExc expected Assert.Throws<ArgumentNullException>(() => { sl2[null] = 0; }); Assert.Equal(0, sl2.Count); // Testcase: Set - null val sl2[(object)100] = (object)null; Assert.Equal(1, sl2.Count); // Testcase: vanila Set sl2[(object)100] = 1; Assert.Equal(1, sl2.Count); sl2.Clear(); Assert.Equal(0, sl2.Count); // Testcase: add key-val pairs for (i = 0; i < 100; i++) { sl2.Add(i + 100, i); } Assert.Equal(100, sl2.Count); for (i = 0; i < 100; i++) { j = i + 100; Assert.True(sl2.ContainsKey((int)j)); Assert.True(sl2.ContainsValue(i)); object o2 = sl2[(int)j]; Assert.NotNull(o2); Assert.True(o2.Equals(i), "Error, entry for key " + j.ToString() + " is " + o2.ToString() + " but should have been " + i.ToString()); } // FOR // testcase: GetValueList // ICollection.GetEnumerator() first test the boundaries on the Remove method thru GetEnumerator implementation en = (IEnumerator)sl2.GetValueList().GetEnumerator(); // Boundary for Current Assert.Throws<InvalidOperationException>(() => { object throwaway = en.Current; } ); j = 0; // go over the enumarator en = (IEnumerator)sl2.GetValueList().GetEnumerator(); while (en.MoveNext()) { // Current to see the order i3 = (int)en.Current; Assert.Equal(i3, j); // GetObject again to see the same order i3 = (int)en.Current; Assert.Equal(i3, j); j++; } // Boundary for GetObject Assert.Throws<InvalidOperationException>(() => { object throwawayobj = en.Current; } ); // Boundary for MoveNext: call MoveNext to make sure it returns false Assert.False((en.MoveNext()) || (j != 100)); // call again MoveNext to make sure it still returns false Assert.False(en.MoveNext()); Assert.Equal(100, sl2.Count); // now modify the sortedlist while enumerator is still active en = (IEnumerator)sl2.GetKeyList().GetEnumerator(); //can remove an item thru en en.MoveNext(); sl2[1] = 0; // Set (int index, object val) // this works fine // Boundary for MoveNext Assert.Throws<InvalidOperationException>(() => { en.MoveNext(); }); }
private void but_eliminar_libro_Click(object sender, EventArgs e) { StringBuilder errorMessages = new StringBuilder(); Libro lib = new Libro(); if (tex_isbn.Text.Length == 0) { this.inicializarDatos(); MessageBox.Show("Debe ingresar un ISBN", "Eliminar Libro", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { try { lib.v_isbn = tex_isbn.Text; if ((lib.ConsultarLibro(lib)).v_isbn.Length != 0) { tex_isbn.Text = lib.v_isbn; tex_titulo.Text = lib.v_titulo; tex_edicion.Text = lib.v_edicion; tex_autor.Text = lib.v_autor; tex_año.Text = lib.v_año; SLeditorial = new SortedList(); SLeditorial.Add(lib.v_Deditorial, lib.v_Deditorial); com_editorial.DataSource = SLeditorial.GetValueList(); com_editorial.Show(); com_editorial.Enabled = false; SLeditorial.Clear(); SLtipolibro = new SortedList(); SLtipolibro.Add(lib.v_Dtipo_libro, lib.v_Dtipo_libro); com_tipo_libro.DataSource = SLtipolibro.GetValueList(); com_tipo_libro.Show(); com_tipo_libro.Enabled = false; SLtipolibro.Clear(); SLidioma = new SortedList(); SLidioma.Add(lib.v_Didioma, lib.v_Didioma); com_idioma.DataSource = SLidioma.GetValueList(); com_idioma.Show(); com_idioma.Enabled = false; SLidioma.Clear(); lib.v_usuario_m = this.usuario; if ((MessageBox.Show("¿Desea eliminar el Libro con Titulo: " + lib.v_titulo + " ?", "Eliminar Libro", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)) { try { if (lib.EliminarLibro(lib) != 0) { this.inicializarDatos(); MessageBox.Show("Libro eliminada correctamente", "Eliminar Libro", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (SqlException ex) { for (int i = 0; i < ex.Errors.Count; i++) { errorMessages.Append("Index #" + i + "\n" + "Message: " + ex.Errors[i].Message + "\n" + "LineNumber: " + ex.Errors[i].LineNumber + "\n" + "Source: " + ex.Errors[i].Source + "\n" + "Procedure: " + ex.Errors[i].Procedure + "\n"); } Console.WriteLine(errorMessages.ToString()); this.inicializarDatos(); MessageBox.Show(ex.Errors[0].Message.ToString(), "Eliminar Libro", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } } catch (SqlException ex) { for (int i = 0; i < ex.Errors.Count; i++) { errorMessages.Append("Index #" + i + "\n" + "Message: " + ex.Errors[i].Message + "\n" + "LineNumber: " + ex.Errors[i].LineNumber + "\n" + "Source: " + ex.Errors[i].Source + "\n" + "Procedure: " + ex.Errors[i].Procedure + "\n"); } Console.WriteLine(errorMessages.ToString()); this.inicializarDatos(); MessageBox.Show(ex.Errors[0].Message.ToString(), "Eliminar Libro", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }
public override void Clear() { lock (_root) { _list.Clear(); } }
private void logCamtrackFrame() { if(Project.camTrackOn) { CameraTrack cameraTrack = WaypointsCache.CameraManager.CameraTrack; XmlDocument xmlDoc = cameraTrack.XmlDoc; XmlNode wNode = xmlDoc.CreateNode(XmlNodeType.Element, "waypoints", null); XmlAttribute attr = xmlDoc.CreateAttribute("description"); attr.InnerText = "Waypoints: " + DateTime.Now; wNode.Attributes.Append(attr); XmlNode tNode = xmlDoc.CreateNode(XmlNodeType.Element, "trackpoints", null); attr = xmlDoc.CreateAttribute("description"); attr.InnerText = "Trackpoints: " + DateTime.Now; tNode.Attributes.Append(attr); ArrayList trackIds = new ArrayList(); SortedList tmpList = new SortedList(); // trackpoints are added to tmplist, other waypoints are added directly to <waypoints>: foreach(Waypoint wpt in WaypointsCache.WaypointsDisplayed) { try { if(wpt.TrackId != -1) { tmpList.Add(wpt.DateTime, wpt); } else { XmlNode wptNode = wpt.ToCamtrackXmlNode(xmlDoc); wNode.AppendChild(wptNode); } } // we will probably lose some trackpoints (with same time, up to second). The benefit is that we will have a sorted list. #if DEBUG catch (Exception e) { LibSys.StatusBar.Error("" + e); } #else catch { } #endif } attr = xmlDoc.CreateAttribute("count"); attr.InnerText = "" + wNode.ChildNodes.Count; wNode.Attributes.Append(attr); cameraTrack.log(wNode); // now convert trackpoints list to nodes under <trackpoints> for(int i=0; i < tmpList.Count ;i++) { Waypoint wpt = (Waypoint)tmpList.GetByIndex(i); XmlNode wptNode = wpt.ToCamtrackXmlNode(xmlDoc); tNode.AppendChild(wptNode); if(!trackIds.Contains(wpt.TrackId)) { trackIds.Add(wpt.TrackId); } } tmpList.Clear(); attr = xmlDoc.CreateAttribute("count"); attr.InnerText = "" + tNode.ChildNodes.Count; tNode.Attributes.Append(attr); cameraTrack.log(tNode); // make a list of track IDs used by trackpoints under <tracks>: XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, "tracks", null); foreach(long trackId in trackIds) { Track trk = WaypointsCache.getTrackById(trackId); if(trk != null) { XmlNode trkNode = xmlDoc.CreateNode(XmlNodeType.Element, "trk", null); attr = xmlDoc.CreateAttribute("trkid"); attr.InnerText = "" + trk.Id; trkNode.Attributes.Append(attr); trkNode.InnerText = trk.Name; node.AppendChild(trkNode); } } attr = xmlDoc.CreateAttribute("count"); attr.InnerText = "" + node.ChildNodes.Count; node.Attributes.Append(attr); cameraTrack.log(node); } }
//Ver capaz hay q cargar para la familia Cheques Diferidos _DP_ private static void DeclareTypes() { //mapH = Read( path ); /* * foreach (MAPStaticInfoItem item in mapH.ArregloItems) * { * lista.Add(item.Key, item.Valor); * } */ if (!_loaded) { _tableFamiliasTDCompTesoreria = new DataTable(); _tableFamiliasTDCompTesoreria.Columns.Add("Key"); _tableFamiliasTDCompTesoreria.Columns.Add("Description"); DataRow row0 = _tableFamiliasTDCompTesoreria.NewRow(); row0["Key"] = "_TD_"; row0["Description"] = "Tarjetas de Débito"; _tableFamiliasTDCompTesoreria.Rows.Add(row0); DataRow row1 = _tableFamiliasTDCompTesoreria.NewRow(); row1["Key"] = "_TC_"; row1["Description"] = "Tarjetas de Crédito"; _tableFamiliasTDCompTesoreria.Rows.Add(row1); DataRow row2 = _tableFamiliasTDCompTesoreria.NewRow(); row2["Key"] = "_DT_,_D_"; row2["Description"] = "Cheques Diferidos"; _tableFamiliasTDCompTesoreria.Rows.Add(row2); DataRow row3 = _tableFamiliasTDCompTesoreria.NewRow(); row3["Key"] = "_T_,_C_"; row3["Description"] = "Cheques"; _tableFamiliasTDCompTesoreria.Rows.Add(row3); DataRow row4 = _tableFamiliasTDCompTesoreria.NewRow(); row4["Key"] = "_RET_"; row4["Description"] = "Retenciones"; _tableFamiliasTDCompTesoreria.Rows.Add(row4); DataRow row5 = _tableFamiliasTDCompTesoreria.NewRow(); row5["Key"] = string.Empty; row5["Description"] = string.Empty; _tableFamiliasTDCompTesoreria.Rows.Add(row5); _dataFDP = mz.erp.businessrules.tui_ConfiguracionFormasDePago.GetList(); _dataFamiliaFDPEntidades = mz.erp.businessrules.tui_ConfiguracionFamiliaFDPEntidades.GetList(); _nameBDFDP.Clear(); _nameFamilia.Clear(); _nameFDP.Clear(); _nameFDPFamilia.Clear(); foreach (DataRow row in _dataFDP.Tables[0].Rows) { string IdTDCompTesoreria = Convert.ToString(row["IdTDCompTesoreria"]); string ClaveCorta = Convert.ToString(row["ClaveCorta"]); string ClaveLarga = Convert.ToString(row["ClaveLarga"]); string Familia = Convert.ToString(row["Familia"]); _nameFDP.Add(IdTDCompTesoreria, ClaveLarga); _nameBDFDP.Add(IdTDCompTesoreria, ClaveCorta); _nameFDPFamilia.Add(IdTDCompTesoreria, Familia); } foreach (DataRow row in _dataFamiliaFDPEntidades.Tables[0].Rows) { string IdEntidad = Convert.ToString(row["IdEntidad"]); string Familia = Convert.ToString(row["Familia"]); _nameFamilia.Add(IdEntidad, Familia); } _loaded = true; } }
private void DataGridView1_SelectionChanged(object sender, EventArgs e) { SortedList sList = new SortedList(); try { //ClearTextBox(); string packno = ""; int rCount = dgv_PackInfo.SelectedRows.Count; if (rCount != 0) { for (int i = 0; i < rCount; i++) { sList.Add(int.Parse(dgv_PackInfo.SelectedRows[i].Cells[1].Value.ToString()), i); } } if (sList.Count != 0) { foreach (int i in sList.Keys) { packno += i + "、"; } packno = packno.Substring(0, packno.Length - 1); txtCurPackage.Text = "第 "+ packno + " 包"; } else { txtCurPackage.Text = ""; } LoadPackList(); } finally { sList.Clear(); GC.Collect(); } }
public static SortedList MakeOidList(int selectedIndex, PacketLog log, out int currentRegion, out int currentZone) { SortedList oidInfo = new SortedList(); currentRegion = -1; currentZone = -1; ushort playerOid = 0; string CharName = "UNKNOWN"; for (int i = 0; i < selectedIndex; ++i) { Packet pak = log[i]; if (pak is StoC_0xD4_PlayerCreate) { StoC_0xD4_PlayerCreate player = (StoC_0xD4_PlayerCreate)pak; oidInfo[player.Oid] = new LivingInfo(pak.Time, "PLR", player.Name, player.Level, player.GuildName); } else if (pak is StoC_0x4B_PlayerCreate_172) { StoC_0x4B_PlayerCreate_172 player = (StoC_0x4B_PlayerCreate_172)pak; oidInfo[player.Oid] = new LivingInfo(pak.Time, "PLR", player.Name, player.Level, player.GuildName); if (currentZone == -1) currentZone = player.ZoneId; } else if (pak is StoC_0x12_CreateMovingObject) { StoC_0x12_CreateMovingObject obj = (StoC_0x12_CreateMovingObject)pak; oidInfo[obj.ObjectOid] = new ObjectInfo(pak.Time, "MOVE", obj.Name, 0); } else if (pak is StoC_0x6C_KeepComponentOverview) { StoC_0x6C_KeepComponentOverview keep = (StoC_0x6C_KeepComponentOverview)pak; oidInfo[keep.Uid] = new ObjectInfo(pak.Time, "Keep", string.Format("keepId:0x{0:X4} componentId:{1}", keep.KeepId, keep.ComponentId), 0); } else if (pak is StoC_0xD1_HouseCreate) { StoC_0xD1_HouseCreate house = (StoC_0xD1_HouseCreate)pak; oidInfo[house.HouseId] = new ObjectInfo(pak.Time, "HOUS", house.Name, 0); } else if (pak is StoC_0xDA_NpcCreate) { StoC_0xDA_NpcCreate npc = (StoC_0xDA_NpcCreate)pak; oidInfo[npc.Oid] = new LivingInfo(pak.Time, "NPC", npc.Name, npc.Level, npc.GuildName); } else if (pak is CtoS_0xA9_PlayerPosition) { CtoS_0xA9_PlayerPosition plr = (CtoS_0xA9_PlayerPosition)pak; if (currentZone == -1) currentZone = plr.CurrentZoneId; } else if (pak is StoC_0xD9_ItemDoorCreate) { StoC_0xD9_ItemDoorCreate item = (StoC_0xD9_ItemDoorCreate)pak; string type = "ITEM"; if (item.ExtraBytes > 0) type = "DOOR"; oidInfo[item.Oid] = new ObjectInfo(pak.Time, type, item.Name, 0); } else if (pak is StoC_0xB7_RegionChange) { StoC_0xB7_RegionChange region = (StoC_0xB7_RegionChange)pak; // if (region.RegionId != currentRegion) // { currentRegion = region.RegionId; currentZone = region.ZoneId; oidInfo.Clear(); // } } else if (pak is StoC_0x20_PlayerPositionAndObjectID_171) { StoC_0x20_PlayerPositionAndObjectID_171 region = (StoC_0x20_PlayerPositionAndObjectID_171)pak; // if (region.Region!= currentRegion) // { currentRegion = region.Region; oidInfo.Clear(); // } playerOid = region.PlayerOid; oidInfo[region.PlayerOid] = new LivingInfo(pak.Time, "YOU", CharName, 0, ""); } else if (pak is StoC_0x16_VariousUpdate) { if (playerOid != 0) { StoC_0x16_VariousUpdate stat = (StoC_0x16_VariousUpdate)pak; if (stat.SubCode == 3) { StoC_0x16_VariousUpdate.PlayerUpdate subData = (StoC_0x16_VariousUpdate.PlayerUpdate)stat.SubData; if (oidInfo[playerOid] != null) { LivingInfo plr = (LivingInfo)oidInfo[playerOid]; plr.level = subData.playerLevel; plr.guildName = subData.guildName; oidInfo[playerOid] = plr; } } } } else if (pak is CtoS_0x10_CharacterSelectRequest) { CtoS_0x10_CharacterSelectRequest login = (CtoS_0x10_CharacterSelectRequest)pak; CharName = login.CharName; } } return oidInfo; }
public override void Clear() { lock (host.SyncRoot) { host.Clear(); } }
private void btn_p5_termList_Click(object sender, EventArgs e) { string line = "", Term = "", POS = "", DocNO_tag = ""; //資料列, 詞彙, 詞性標記 int index = 0, value = 0, pt = 0; StringBuilder SB5 = new StringBuilder(); List<string> temp_list = new List<string>(); SortedList Term_DF_slist = new SortedList(); //整個文件集之"詞彙列表" 及詞會出現次數 DF List<KeyValuePair<string, int>> Doctermtf_list = new List<KeyValuePair<string, int>>(); //-記錄每篇文件出現之詞彙集詞頻 - // if ((openFileDialog1.ShowDialog() == DialogResult.OK) && ((txt_p5_fileName.Text = openFileDialog1.FileName) != null)) //開啟Window開啟檔案管理對話視窗 //{ using (StreamReader myTextFileReader = new StreamReader(@txt_p5_fileName.Text, Encoding.Default)) { SortedList DocTermTF_slist = new SortedList(); //暫存每篇文件之"詞彙列表" 及詞會出現次數 TF // ---- 處理文件集中的每一篇文件與文件中的所有詞彙 (詞彙列表 ,計算 TF , 計算 DF)---- while (myTextFileReader.EndOfStream != true) //非資料檔案結尾 { line = (myTextFileReader.ReadLine().Trim()) + " "; // ----- 若為一篇新文件的開始 if (line.Contains("<DocNo>")) { TotalDocNum++; DocNO_tag = line.Substring(line.IndexOf("<DocNo>"), ((line.IndexOf("</DocNo>") + 8) - line.IndexOf("<DocNo>"))); //line = line.Remove(line.IndexOf("<DocNo>"), ((line.IndexOf("</DocNo>") + 8) - line.IndexOf("<DocNo>"))); // -------------------------------------- 計算詞彙之 DF --------------------------------------------------- if (temp_list.Count != 0) { foreach (string str in temp_list) //複製與計算出現在每一文件之詞彙的"DF" { //-- 計算詞彙之 DF -- if ((index = Term_DF_slist.IndexOfKey(str)) != -1) //在termList中找尋特定的Term,若Term不存在怎則傳回-1 { value = (int)Term_DF_slist.GetByIndex(index); value++; //該term存在,則term的出現次數加1 Term_DF_slist.SetByIndex(index, value); } else Term_DF_slist.Add(str, 1); //該詞彙(term)不存在於termList中,則加入該新詞彙(term) } temp_list.Clear(); //清除紀錄每一篇文件內之詞彙的SortedList } //--------------記錄每篇文件出現之詞彙集詞頻 -Doctermtf_list ----------- if (DocTermTF_slist.Count != 0) { foreach (DictionaryEntry obj in DocTermTF_slist) { KeyValuePair<string, int> x = new KeyValuePair<string, int>((string)obj.Key, (int)obj.Value); Doctermtf_list.Add(x); } DocTermTF_slist.Clear(); } KeyValuePair<string, int> x1 = new KeyValuePair<string, int>(DocNO_tag, 0); //加入文件編號標籤 Doctermtf_list.Add(x1); continue; } // ---------------------------------- 記錄並產生整個文件集之"詞彙列表" 及詞會出現次數 TF------------------------------------------ string[] terms = line.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); foreach (string str in terms) { if (str.IndexOf("(") == -1 || str.IndexOf(")") == -1) //找不到'()',就不處理/ continue; Term = str.Substring(0, str.IndexOf("(")); POS = str.Substring(str.IndexOf("(")); if (Term.Length != 0) //若有"詞彙"存在 { //--- 記錄每篇文件之詞彙及其出現次數 --- if ((pt = DocTermTF_slist.IndexOfKey((Term + POS))) != -1) { value = (int)DocTermTF_slist.GetByIndex(pt); value++; //該term存在,則term的出現次數加1 DocTermTF_slist.SetByIndex(pt, value); //紀錄整個文件集之"詞彙列表" 及詞會出現次數 TF } else DocTermTF_slist.Add((Term + POS), 1); //該詞彙(term)不存在於termList中,則加入該新詞彙(term) // --- 紀錄出現在每一文件之詞彙有哪些,用於計算詞彙之DF if ((index = temp_list.IndexOf((Term + POS))) == -1) temp_list.Add((Term + POS)); //紀錄出現在每一文件之詞彙有哪些,用於計算詞彙之DF } } //TF詞頻比較 if (Doctermtf_list.Count != 0) { foreach (KeyValuePair<string, int> kvp in Doctermtf_list) { //KeyValuePair<string, int> x = new KeyValuePair<string, int>((string)obj.Key, (int)obj.Value); } } }//End of while每一文件 // ----記錄並計算最後一篇文件之詞彙 DF -------- if (temp_list.Count != 0) { foreach (string str in temp_list) //複製與計算出現在每一文件之詞彙的"DF" { //-- 計算詞彙之 DF -- if ((index = Term_DF_slist.IndexOfKey(str)) != -1) //在termList中找尋特定的Term,若Term不存在怎則傳回-1 { value = (int)Term_DF_slist.GetByIndex(index); value++; //該term存在,則term的出現次數加1 Term_DF_slist.SetByIndex(index, value); } else Term_DF_slist.Add(str, 1); //該詞彙(term)不存在於termList中,則加入該新詞彙(term) } temp_list.Clear(); //清除紀錄每一篇文件內之詞彙的SortedList } if (DocTermTF_slist.Count != 0) { foreach (DictionaryEntry obj in DocTermTF_slist) { KeyValuePair<string, int> x = new KeyValuePair<string, int>((string)obj.Key, (int)obj.Value); Doctermtf_list.Add(x); } DocTermTF_slist.Clear(); } }//End of using // --- 顯示詞彙列表 "term-tf" (未過濾前) --- StringBuilder SB = new StringBuilder(); //StringBuilder適合未知數目之字串動態串接,此處使用string物件則無法完成此大資料檔案的讀取串接 foreach (KeyValuePair<string, int> kvp in Doctermtf_list) SB.AppendLine(kvp.Key + " " + kvp.Value); rtb_p5_souce.Text = SB.ToString(); //顯示經詞彙挑選後資料 //}//End of if // ============================================== 依詞彙出現次數挑選過濾詞彙 ============================================== int tf = int.Parse(txt_p5_tf.Text); //過濾掉詞彙次數tf(txt_p5_tf.Text)以下之詞彙 List<KeyValuePair<string, int>> DoctermtfSelected_list = new List<KeyValuePair<string, int>>(); MaxTfValue = 0; foreach (KeyValuePair<string, int> kvp in Doctermtf_list) { if (kvp.Value >= tf || kvp.Value == 0) { DoctermtfSelected_list.Add(kvp); //建立"挑選過濾後之詞彙-詞彙頻率列表" if (kvp.Value > MaxTfValue) //找尋最大"詞彙頻率TF"值 MaxTfValue = kvp.Value; } if (kvp.Value > tf && Term_list.Contains(kvp.Key) == false) Term_list.Add(kvp.Key); //建立"挑選過濾後之全部詞彙列表" Term_list.Sort(); } // --- 顯示詞彙列表 "term-tf" (過濾後) --- Dictionary<string, int> termSelected_DF_dic = new Dictionary<string, int>(); //挑選過濾後之"詞彙總數"列表及詞彙之"文件頻df" rtb_p5_selected.Clear(); StringBuilder SB1 = new StringBuilder(); //StringBuilder適合未知數目之字串動態串接,此處使用string物件則無法完成此大資料檔案的讀取串接 StringBuilder SB2 = new StringBuilder(); foreach (KeyValuePair<string, int> kvp in DoctermtfSelected_list) { SB1.AppendLine(kvp.Key + " " + kvp.Value.ToString()); if (((index = Term_DF_slist.IndexOfKey(kvp.Key)) != -1) && (termSelected_DF_dic.ContainsKey(kvp.Key) == false)) //詞彙挑選後之"term-TF" 與 "term-DF"相互配對對應 { termSelected_DF_dic.Add((string)Term_DF_slist.GetKey(index), (int)Term_DF_slist.GetByIndex(index)); SB2.AppendLine((string)Term_DF_slist.GetKey(index) + " " + (int)Term_DF_slist.GetByIndex(index)); } } rtb_p5_selected.Text = SB1.ToString(); //顯示經詞彙挑選後資料 rtb_p5_termDF.Text = SB2.ToString(); //顯示經詞彙挑選後資料 /*/ ============================================= 計算詞彙的權重 "tf_idf" ============================================= StringBuilder SB3 = new StringBuilder(); Dictionary<string, double> termSelected_TDIDF_dic = new Dictionary<string, double>(); int TF = 0, DF = 0; double idf = 0.0, tf_idf = 0.0; foreach (KeyValuePair<string, int> kvp in DoctermtfSelected_list) { if (kvp.Key.Contains("<DocNo>") && (kvp.Value == 0)) { KeyValuePair<string, double> tag = new KeyValuePair<string, double>(kvp.Key, 0.0); DocTermtfidf_list.Add(tag); tf_idf = 0.0; } TF = kvp.Value; if (termSelected_DF_dic.TryGetValue(kvp.Key, out DF)) { idf = 1 / (double)DF; tf_idf = (TF / (double)MaxTfValue) * (Math.Log(1 / idf)); //基底=e } KeyValuePair<string, double> x = new KeyValuePair<string, double>(kvp.Key, tf_idf); DocTermtfidf_list.Add(x); SB3.AppendLine(kvp.Key + " " + tf_idf); } rtb_p5_tfidf.Text = SB3.ToString(); //顯示經詞彙挑選後之"詞彙與tfidf" // ---- 顯示經詞彙出現次數挑選後出現在每一篇文件中的所有詞彙 StringBuilder SB4 = new StringBuilder(); foreach (string str in Term_list) SB4.AppendLine(str); rtb_p5_TermList.Text = SB4.ToString(); }//End 0f Event Fuction */ // ============================================= 詞彙的權重都設為1 ============================================= StringBuilder SB3 = new StringBuilder(); Dictionary<string, double> termSelected_TDIDF_dic = new Dictionary<string, double>(); int TF = 0, DF = 0; double idf = 0.0, tf_idf = 0.0; foreach (KeyValuePair<string, int> kvp in DoctermtfSelected_list) { if (kvp.Key.Contains("<DocNo>") && (kvp.Value == 0)) { KeyValuePair<string, double> tag = new KeyValuePair<string, double>(kvp.Key, 0.0); DocTermtfidf_list.Add(tag); tf_idf = 0.0; } // TF = kvp.Value; if (termSelected_DF_dic.TryGetValue(kvp.Key, out DF)) { //idf = 1 / (double)DF; tf_idf = 1; //基底=e } KeyValuePair<string, double> x = new KeyValuePair<string, double>(kvp.Key, tf_idf); DocTermtfidf_list.Add(x); SB3.AppendLine(kvp.Key + " " + tf_idf); } rtb_p5_tfidf.Text = SB3.ToString(); //顯示經詞彙挑選後之"詞彙與tfidf" // ---- 顯示經詞彙出現次數挑選後出現在每一篇文件中的所有詞彙 StringBuilder SB4 = new StringBuilder(); foreach (string str in Term_list) SB4.AppendLine(str); rtb_p5_TermList.Text = SB4.ToString(); }//End 0f Event Fuction
public static void Reset() { _controls.Clear(); }
/// <summary> /// Returns the sorted connection list. /// </summary> /// <returns></returns> private SortedList<string, int> GetSortedList() { SortedList<string, int> Retval = new SortedList<string, int>(); try { int Index = 0; foreach (DatabasePreference.OnlineConnectionDetail ConnectionDetail in this.OnlineDatabaseDetails) { if (ConnectionDetail.DIConnectionDetails.ServerType == DIServerType.MsAccess) { //-- In case of access, add the dbname only. Retval.Add(Path.GetFileName(ConnectionDetail.DIConnectionDetails.DbName), Index); } else { //-- In case of other Db, add the connection name. Retval.Add(ConnectionDetail.Connection, Index); } Index += 1; } } catch (Exception ex) { Retval.Clear(); } return Retval; }
public void TestGetKeyListBasic() { StringBuilder sblMsg = new StringBuilder(99); // SortedList sl2 = null; IEnumerator en = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); int i3 = 0; int i = 0; int j = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(); //using default IComparable implementation from Integer4 // which is used here as key-val elements. // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // Testcase: Set - null key, ArgExc expected Assert.Throws<ArgumentNullException>(() => { sl2[null] = 0; }); Assert.Equal(0, sl2.Count); // Testcase: Set - null val sl2[(Object)100] = (Object)null; Assert.Equal(1, sl2.Count); // Testcase: vanila Set sl2[(Object)100] = 1; Assert.Equal(1, sl2.Count); sl2.Clear(); Assert.Equal(0, sl2.Count); // Testcase: add key-val pairs for (i = 0; i < 100; i++) { sl2.Add(i + 100, i); } Assert.Equal(100, sl2.Count); for (i = 0; i < 100; i++) { j = i + 100; Assert.True(sl2.ContainsKey((int)j)); Assert.True(sl2.ContainsValue(i)); } // testcase: GetKeyList // first test the boundaries on the Remove method thru GetEnumerator implementation en = (IEnumerator)sl2.GetKeyList().GetEnumerator(); // Boundary for Current Assert.Throws<InvalidOperationException>(() => { Object objThrowAway = en.Current; } ); j = 100; // go over the enumarator en = (IEnumerator)sl2.GetKeyList().GetEnumerator(); while (en.MoveNext()) { // Current to see the order i3 = (int)en.Current; Assert.Equal(i3, j); // Current again to see the same order i3 = (int)en.Current; Assert.Equal(i3, j); j++; } // Boundary for Current Assert.Throws<InvalidOperationException>(() => { Object objThrowAway = en.Current; } ); // Boundary for MoveNext: call MoveNext to make sure it returns false Assert.False((en.MoveNext()) || (j != 200)); // call again MoveNext to make sure it still returns false Assert.False(en.MoveNext()); }
/// <summary> /// 返回模块权限记录表 /// </summary> /// <param name="ConnectInfo"></param> /// <param name="UserCode"></param> /// <returns></returns> public SortedList GetModuleRights(String[] ConnectInfo,String UserCode,out DataTable returnDT) { //DataTable dt; SortedList ModuleRightList=new SortedList(); int i; CModuleRight tempModuleRight;; try { ConnectInfo=ConnectInfo; //读取该用户的模块权限 returnDT=this.GetModuleRightTable(UserCode); ModuleRightList.Clear(); for(i=0;i<=returnDT.Rows.Count-1;i++) { tempModuleRight=new CModuleRight(ConnectInfo, returnDT.Rows[i]); ModuleRightList.Add(tempModuleRight.ModuleCode,tempModuleRight); //模块编码做键值 } return ModuleRightList; } catch(Exception ee) { //returnDT=null; throw new Exception(ee.Message ); //return null; } }
internal void Clear() { list.Clear(); }
public void TestIndexOfValueBasic() { StringBuilder sblMsg = new StringBuilder(99); // SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); string s1 = null; string s2 = null; string s3 = null; string s4 = null; int i = 0; int j = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(this); // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // with null - should return -1 // null val j = sl2.IndexOfValue((string)null); Assert.Equal(-1, j); // invalid val - should return -1 j = sl2.IndexOfValue("No_Such_Val"); Assert.Equal(-1, j); // null is a valid value sl2.Add("Key_0", null); j = sl2.IndexOfValue(null); Assert.NotEqual(-1, j); // first occurrence check sl2.Add("Key_1", "Val_Same"); sl2.Add("Key_2", "Val_Same"); j = sl2.IndexOfValue("Val_Same"); Assert.Equal(1, j); sl2.Clear(); // Testcase: add few key-val pairs for (i = 0; i < 100; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add(s1, s2); } // // Testcase: test IndexOfVal // for (i = 0; i < sl2.Count; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); //key sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("val_"); //value sblMsg.Append(i); s2 = sblMsg.ToString(); // now use IndexOfKey and IndexOfVal to obtain the same object and check s3 = (string)sl2.GetByIndex(sl2.IndexOfKey(s1)); //Get the index of this key and then get object s4 = (string)sl2.GetByIndex(sl2.IndexOfValue(s2)); //Get the index of this val and then get object Assert.True(s3.Equals(s4)); // now Get using the index obtained thru IndexOfKey () and compare it with s2 s3 = (string)sl2.GetByIndex(sl2.IndexOfKey(s1)); Assert.True(s3.Equals(s2)); } // // Remove a key and then check // sblMsg.Length = 0; sblMsg.Append("key_50"); s1 = sblMsg.ToString(); sl2.Remove(s1); //removes "Key_50" j = sl2.IndexOfValue(s1); Assert.Equal(-1, j); }
/// <summary> /// 批量插入表中的所有数据 /// </summary> /// <param name="TableName"></param> /// <param name="FieldValueList"></param> /// <param name="PrimaryKeyList"></param> /// <returns></returns> public void UpdateRightDataTable(string TableName, DataTable MyDataTable, string UserCode) { System.Data.SqlClient.SqlConnection conn; System.Data.SqlClient.SqlDataAdapter dbAdpter; //数据适配器 System.Data.SqlClient.SqlCommand dbCommand; //数据操作命令 System.Data.SqlClient.SqlCommand dbCommand2; //数据操作命令 System.Data.SqlClient.SqlCommandBuilder dbCommandBuilder; //提供自动生成表单的命令方法 //System.Data.SqlClient.SqlTransaction tempTran; DataRow dr; SortedList tempForkeyList = new SortedList(); conn = new SqlConnection(mConnectInfo); conn.Open(); //开始事务 //tempTran = conn.BeginTransaction(); dbCommand = new SqlCommand(); //dbCommand.Transaction =tempTran; dbCommand.CommandText = "select * from " + TableName + " where za0100 is null"; dbCommand.Connection = conn; dbCommand2 = new SqlCommand(); //dbCommand2.Transaction = tempTran; dbCommand2.CommandText = "Delete from " + TableName + " where ZA0100='" + UserCode + "'"; dbCommand2.Connection = conn; dbCommand2.ExecuteNonQuery(); dbAdpter = new SqlDataAdapter(dbCommand); dbCommandBuilder = new SqlCommandBuilder(dbAdpter); //dbAdpter.Fill(tempDT); SortedList tempFieldValueList = new SortedList(); SortedList tempLocateList = new SortedList(); tempForkeyList.Add("ZA0100", UserCode); //设置每行的ID值 for (int i = 0; i <= MyDataTable.Rows.Count - 1; i++) { MyDataTable.Rows[i][TableName + "ID"] = this.GetChildSetAddId(TableName, tempForkeyList); dr = MyDataTable.Rows[i]; tempFieldValueList.Clear(); tempLocateList.Clear(); tempLocateList.Add("ZA0100", "1"); for (int j = 0; j <= MyDataTable.Columns.Count - 1; j++) { tempFieldValueList.Add(MyDataTable.Columns[j].ColumnName, dr[j]); } this.AddOneRec(TableName, tempFieldValueList, tempLocateList); } //dbAdpter.Update(MyDataTable); //提交事务 //tempTran.Commit(); }//UpdataDataTable
protected TreeNode ProcessEmbeddedDevice(UPnPDevice device) { SortedList TempList = new SortedList(); TreeNode Parent; TreeNode Child; Parent = new TreeNode(device.FriendlyName, 1, 1); Parent.Tag = device; /* for(int x=0;x<device.Services.Length;++x) { device.Services[x].OnInvokeError += new UPnPService.UPnPServiceInvokeErrorHandler(HandleInvokeError); device.Services[x].OnInvokeResponse += new UPnPService.UPnPServiceInvokeHandler(HandleInvoke); } */ for (int cid = 0; cid < device.Services.Length; ++cid) { Child = new TreeNode(device.Services[cid].ServiceURN, 2, 2); Child.Tag = device.Services[cid]; TreeNode stateVarNode = new TreeNode("State variables", 6, 6); Child.Nodes.Add(stateVarNode); UPnPStateVariable[] varList = device.Services[cid].GetStateVariables(); TempList.Clear(); foreach (UPnPStateVariable var in varList) { TreeNode varNode = new TreeNode(var.Name, 5, 5); varNode.Tag = var; TempList.Add(var.Name, varNode); //stateVarNode.Nodes.Add(varNode); } IDictionaryEnumerator sve = TempList.GetEnumerator(); while (sve.MoveNext()) { stateVarNode.Nodes.Add((TreeNode)sve.Value); } TempList.Clear(); foreach (UPnPAction action in device.Services[cid].GetActions()) { string argsstr = ""; foreach (UPnPArgument arg in action.ArgumentList) { if (arg.IsReturnValue == false) { if (argsstr != "") argsstr += ", "; argsstr += arg.RelatedStateVar.ValueType + " " + arg.Name; } } TreeNode methodNode = new TreeNode(action.Name + "(" + argsstr + ")", 4, 4); methodNode.Tag = action; //Child.Nodes.Add(methodNode); TempList.Add(action.Name, methodNode); } IDictionaryEnumerator ide = TempList.GetEnumerator(); while (ide.MoveNext()) { Child.Nodes.Add((TreeNode)ide.Value); } Parent.Nodes.Add(Child); } for (int cid = 0; cid < device.EmbeddedDevices.Length; ++cid) { Child = ProcessEmbeddedDevice(device.EmbeddedDevices[cid]); Child.Tag = device.EmbeddedDevices[cid]; Parent.Nodes.Add(Child); } return (Parent); }
public void Linkage() { Layer lay1 = null; string stype = ""; int year = 0; SortedList LineList = new SortedList(); SortedList subList = new SortedList(); lay1 = tlVectorControl1.SVGDocument.CurrentLayer; try { year = Convert.ToInt32(lay1.Label.Substring(0, 4)); //if(lay1.Label.Contains("变电站")){ // stype = "变电站"; //} //if (lay1.Label.Contains("线路")) //{ // stype = "线路"; //} //if(stype==""){ // MessageBox.Show("选择的图层名称不包含线路或变电站信息。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); // stype = ""; // return; //} } catch (Exception e1) { MessageBox.Show("选择图层的图层名称不包含年份信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } foreach (SvgElement ele in lay1.GraphList) { if (ele.Name == "use") { subList.Add(ele.ID, ele); } if (ele.Name == "polyline" && ele.GetAttribute("IsLead") == "1") { LineList.Add(ele.ID, ele); } } foreach (Layer layer in tlVectorControl1.SVGDocument.Layers) { string str_lb = layer.Label; if (str_lb.Length > 4) { if (IsNumber(str_lb.Substring(0, 4))) { if (Convert.ToInt32(str_lb.Substring(0, 4)) > year/* && str_lb.Contains(stype)*/) { foreach (SvgElement ele in layer.GraphList) { if (ele.Name == "use") { SvgElement sub = (SvgElement)subList[ele.GetAttribute("CopyOf")]; if (sub != null) { ele.SetAttribute("x", sub.GetAttribute("x")); ele.SetAttribute("y", sub.GetAttribute("y")); ele.SetAttribute("transform", sub.GetAttribute("transform")); string larid = ""; larid = ((SvgElement)ele).GetAttribute("layer"); if (!ChangeLayerList.Contains(larid)) { ChangeLayerList.Add(larid); } substation sub1 = new substation(); sub1.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid; sub1.EleID = sub.GetAttribute("id"); sub1 = (substation)Services.BaseService.GetObject("SelectsubstationByEleID", sub1); if (sub1 != null) { substation sub2 = new substation(); sub2.EleID = ele.ID; sub2.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid; sub2 = (substation)Services.BaseService.GetObject("SelectsubstationByEleID", sub2); if (sub2 != null) { string uid = sub2.UID; string eleid = sub2.EleID; sub2 = sub1; sub2.UID = uid; sub2.EleID = eleid; Services.BaseService.Update<substation>(sub2); } } } } if (ele.Name == "polyline" && ele.GetAttribute("IsLead") == "1") { SvgElement line = (SvgElement)LineList[ele.GetAttribute("CopyOf")]; if (line != null) { ((Polyline)ele).Points = ((Polyline)line).Points.Clone() as PointF[]; if (line.GetAttribute("transform") != "") { ele.SetAttribute("transform", line.GetAttribute("transform")); } string larid = ""; larid = ((SvgElement)ele).GetAttribute("layer"); if (!ChangeLayerList.Contains(larid)) { ChangeLayerList.Add(larid); } //((Polyline)ele).Transform.Matrix.TransformPoints(((Polyline)ele).Points); LineInfo line1 = new LineInfo(); line1.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid; line1.EleID = line.GetAttribute("id"); line1 = (LineInfo)Services.BaseService.GetObject("SelectLineInfoByEleID", line1); if (line1 != null) { LineInfo line2 = new LineInfo(); line2.EleID = ele.ID; line2.SvgUID = tlVectorControl1.SVGDocument.SvgdataUid; line2 = (LineInfo)Services.BaseService.GetObject("SelectLineInfoByEleID", line2); if (line2 != null) { string uid = line2.UID; string eleid = line2.EleID; line2 = line1; line2.UID = uid; line2.EleID = eleid; Services.BaseService.Update<LineInfo>(line2); } } } } } } } } } stype = ""; subList.Clear(); LineList.Clear(); tlVectorControl1.Refresh(); }
/// <summary> /// Writes the log. /// </summary> /// <param name="context">The context.</param> /// <param name="stream">The stream.</param> /// <param name="callback">The callback for UI updates.</param> public void WriteLog(IExecutionContext context, Stream stream, ProgressCallback callback) { SortedList oidInfo = new SortedList(); IList CombatWaitMessage = new ArrayList(); Hashtable styleIcons = new Hashtable(); Hashtable plrInfo = new Hashtable(); weapons = new StoC_0x02_InventoryUpdate.Item[4]; PlayerInfo playerInfo = null;// = new PlayerInfo(); int playerOid = -1; string nameKey = ""; string statKey = ""; string plrName = ""; string plrClass = ""; int plrLevel = 0; int countBC = 0; using (StreamWriter s = new StreamWriter(stream)) { foreach (PacketLog log in context.LogManager.Logs) { for (int i = 0; i < log.Count; i++) { if (callback != null && (i & 0xFFF) == 0) // update progress every 4096th packet callback(i, log.Count - 1); Packet pak = log[i]; // Enter region (get new self OID) if (pak is StoC_0x20_PlayerPositionAndObjectID) { StoC_0x20_PlayerPositionAndObjectID plr = (StoC_0x20_PlayerPositionAndObjectID) pak; playerOid = plr.PlayerOid; oidInfo.Clear(); oidInfo[plr.PlayerOid] = new ObjectInfo(eObjectType.player, "You", 0); s.WriteLine("{0, -16} playerOid:0x{1:X4}", pak.Time.ToString(), playerOid); } // Fill objects OID else if (pak is StoC_0xD4_PlayerCreate) { StoC_0xD4_PlayerCreate player = (StoC_0xD4_PlayerCreate) pak; oidInfo[player.Oid] = new ObjectInfo(eObjectType.player, player.Name, player.Level); } else if (pak is StoC_0x4B_PlayerCreate_172) { StoC_0x4B_PlayerCreate_172 player = (StoC_0x4B_PlayerCreate_172) pak; oidInfo[player.Oid] = new ObjectInfo(eObjectType.player, player.Name, player.Level); } else if (pak is StoC_0x12_CreateMovingObject) { StoC_0x12_CreateMovingObject obj = (StoC_0x12_CreateMovingObject) pak; oidInfo[obj.ObjectOid] = new ObjectInfo(eObjectType.movingObject, obj.Name, 0); } else if (pak is StoC_0x6C_KeepComponentOverview) { StoC_0x6C_KeepComponentOverview keep = (StoC_0x6C_KeepComponentOverview) pak; oidInfo[keep.Uid] = new ObjectInfo(eObjectType.keep, string.Format("keepId:0x{0:X4} componentId:{1}", keep.KeepId, keep.ComponentId), 0); } else if (pak is StoC_0xDA_NpcCreate) { StoC_0xDA_NpcCreate npc = (StoC_0xDA_NpcCreate) pak; oidInfo[npc.Oid] = new ObjectInfo(eObjectType.npc, npc.Name, npc.Level); } else if (pak is StoC_0xD9_ItemDoorCreate) { StoC_0xD9_ItemDoorCreate item = (StoC_0xD9_ItemDoorCreate) pak; eObjectType type = eObjectType.staticObject; if (item.ExtraBytes > 0) type = eObjectType.door; oidInfo[item.Oid] = new ObjectInfo(type, item.Name, 0); } // Fill current weapons else if (pak is StoC_0x02_InventoryUpdate) { StoC_0x02_InventoryUpdate invPack = (StoC_0x02_InventoryUpdate) pak; if (invPack.PreAction == 1 || invPack.PreAction == 0) { VisibleSlots = invPack.VisibleSlots; for (int j = 0; j < invPack.SlotsCount; j++) { StoC_0x02_InventoryUpdate.Item item = (StoC_0x02_InventoryUpdate.Item) invPack.Items[j]; switch (item.slot) { case 10: weapons[0] = item; break; case 11: weapons[1] = item; break; case 12: weapons[2] = item; break; case 13: weapons[3] = item; break; default: break; } } } } // Fill character stats else if (pak is StoC_0x16_VariousUpdate) { // name, level, class StoC_0x16_VariousUpdate stat = (StoC_0x16_VariousUpdate) pak; if (stat.SubCode == 3) { StoC_0x16_VariousUpdate.PlayerUpdate subData = (StoC_0x16_VariousUpdate.PlayerUpdate) stat.SubData; nameKey = "N:" + subData.playerName + "L:" + subData.playerLevel; statKey = ""; plrName = subData.playerName; plrLevel = subData.playerLevel; plrClass = subData.className; s.WriteLine("{0, -16} 0x16:3 nameKey:{1} plrName:{2} {3} {4}", pak.Time.ToString(), nameKey, plrName, plrLevel, plrClass); } // mainhand spec, mainhand DPS else if (stat.SubCode == 5) { StoC_0x16_VariousUpdate.PlayerStateUpdate subData = (StoC_0x16_VariousUpdate.PlayerStateUpdate) stat.SubData; string key = string.Format("WD:{0}.{1}WS:{2}", subData.weaponDamageHigh, subData.weaponDamageLow, (subData.weaponSkillHigh << 8) + subData.weaponSkillLow); if (nameKey != "") { if (plrInfo.ContainsKey(nameKey + key)) { playerInfo = (PlayerInfo) plrInfo[nameKey + key]; } else { playerInfo = new PlayerInfo(); playerInfo.name = plrName; playerInfo.level = plrLevel; playerInfo.className = plrClass; playerInfo.weaponDamage = string.Format("{0,2}.{1,-3}", subData.weaponDamageHigh, subData.weaponDamageLow); playerInfo.weaponSkill = (subData.weaponSkillHigh << 8) + subData.weaponSkillLow; plrInfo.Add(nameKey + key, playerInfo); } plrInfo[nameKey + key] = playerInfo; } statKey = key; s.WriteLine("{0, -16} 0x16:5 S:{1} {2} {3} {4} {5}", pak.Time.ToString(), statKey, playerInfo.name, playerInfo.level, playerInfo.weaponDamage, playerInfo.weaponSkill); } // Fill styles if (stat.SubCode == 1) { StoC_0x16_VariousUpdate.SkillsUpdate subData = (StoC_0x16_VariousUpdate.SkillsUpdate) stat.SubData; styleIcons.Clear(); if (log.Version < 186) { styleIcons.Add((ushort)0x01F4, "Bow prepare"); styleIcons.Add((ushort)0x01F5, "Lefthand hit"); styleIcons.Add((ushort)0x01F6, "Bothhands hit"); styleIcons.Add((ushort)0x01F7, "Bow shoot"); // styleIcons.Add((ushort)0x01F9, "Volley aim ?"); // styleIcons.Add((ushort)0x01FA, "Volley ready ?"); // styleIcons.Add((ushort)0x01FB, "Volley shoot ?"); } else { styleIcons.Add((ushort)0x3E80, "Bow prepare"); styleIcons.Add((ushort)0x3E81, "Lefthand hit"); styleIcons.Add((ushort)0x3E82, "Bothhands hit"); styleIcons.Add((ushort)0x3E83, "Bow shoot"); // styleIcons.Add((ushort)0x3E85, "Volley aim ?"); // styleIcons.Add((ushort)0x3E86, "Volley ready ?"); // styleIcons.Add((ushort)0x3E87, "Volley shoot ?"); } foreach (StoC_0x16_VariousUpdate.Skill skill in subData.data) { if (skill.page == StoC_0x16_VariousUpdate.eSkillPage.Styles) { styleIcons[skill.icon] = skill.name; // s.WriteLine("{0, -16} 0x16:1 icon:0x{1:X4} name:{2}", pak.Time.ToString(), skill.icon, styleIcons[skill.icon]); } } /* foreach (DictionaryEntry entry in styleIcons) { ushort icon = (ushort)entry.Key; s.WriteLine("{0, -16} 0x16:1 icon:0x{1:X4} name:{2}", pak.Time.ToString(), icon, entry.Value); }*/ } } // Combat animation else if (pak is StoC_0xBC_CombatAnimation && (playerInfo != null)) { StoC_0xBC_CombatAnimation combat = (StoC_0xBC_CombatAnimation) pak; CombatWaitMessage.Clear(); ObjectInfo targetObj = oidInfo[combat.DefenderOid] as ObjectInfo; string styleName = (combat.StyleId == 0 /* || (combat.Result & 0x7F) != 0x0B)*/) ? "" : (styleIcons[combat.StyleId] == null ? "not found " + combat.StyleId.ToString() : (styleIcons[combat.StyleId]).ToString()); string targetName = targetObj == null ? "" : " target:" + targetObj.name + " (" + targetObj.type + ")"; if (combat.Stance == 0 && combat.AttackerOid == playerOid /* && combat.DefenderOid != 0*/) { switch (combat.Result & 0x7F) { case 0: CombatWaitMessage.Add(new WaitMessage(0x11, "You miss!")); CombatWaitMessage.Add(new WaitMessage(0x11, "You were strafing in combat and miss!")); break; case 1: if (targetObj != null) CombatWaitMessage.Add(new WaitMessage(0x11, targetObj.GetFirstFullName + " parries your attack!")); break; case 2: // if (targetObj != null)//TODO // CombatWaitMessage.Add(new WaitMessage(0x11, targetObj.GetFirstFullName + " The Midgardian Assassin attacks you and you block the blow!")); break; case 3: if (targetObj != null) CombatWaitMessage.Add(new WaitMessage(0x11, targetObj.GetFirstFullName + " evades your attack!")); break; case 4: CombatWaitMessage.Add(new WaitMessage(0x11, "You fumble the attack and take time to recover!")); break; case 0xA: if (targetObj != null) CombatWaitMessage.Add( new WaitMessage(0x11, "You attack " + targetObj.GetFullName + " with your % and hit for % damage!")); break; case 0xB: CombatWaitMessage.Add(new WaitMessage(0x11, "You perform your " + styleName + " perfectly. %")); if (targetObj != null) { CombatWaitMessage.Add( new WaitMessage(0x11, "You attack " + targetObj.GetFullName + " with your % and hit for % damage!")); } break; case 0x14: if (targetObj != null) CombatWaitMessage.Add(new WaitMessage(0x11, "You hit " + targetObj.GetFullName + " for % damage!")); break; default: break; } } if (combat.AttackerOid == playerOid) { s.WriteLine("{0, -16} 0xBC attackerOid:0x{1:X4}(You) defenderOid:0x{2:X4} style:0x{4:X4} result:0x{3:X2}{5}{6}", pak.Time.ToString(), combat.AttackerOid, combat.DefenderOid, combat.Result, combat.StyleId, styleName == "" ? "" : " styleName:" + styleName, targetName); foreach (WaitMessage msg in CombatWaitMessage) { s.WriteLine(" WAITING 0xAF 0x{0:X2} {1}", msg.msgType, msg.message); } countBC++; } } // Messages else if (pak is StoC_0xAF_Message) { StoC_0xAF_Message msg = (StoC_0xAF_Message) pak; switch (msg.Type) { // case 0x10: // Your cast combat case 0x11: // Your Melee combat // case 0x1B: // resist // case 0x1D: // X hits you // case 0x1E: // X miss you s.WriteLine("{0, -16} 0xAF 0x{1:X2} {2} ", pak.Time.ToString(), msg.Type, msg.Text); break; default: break; } } } } if (nameKey != "" && statKey != "") plrInfo[nameKey + statKey] = playerInfo; } }
public void TestGetEnumeratorBasic() { StringBuilder sblMsg = new StringBuilder(99); // SortedList sl2 = null; IDictionaryEnumerator dicen = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); int i3 = 0; int i2 = 0; int i = 0; int j = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(this); // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // Testcase: Set - null key, ArgExc expected Assert.Throws<ArgumentNullException>(() => { sl2[null] = 0; }); Assert.Equal(0, sl2.Count); // Testcase: Set - null val sl2[(object)100] = (object)null; Assert.Equal(1, sl2.Count); // Testcase: vanila Set sl2[(object)100] = 1; Assert.Equal(1, sl2.Count); sl2.Clear(); Assert.Equal(0, sl2.Count); // Testcase: add key-val pairs for (i = 0; i < 100; i++) { sl2.Add(i + 100, i); } Assert.Equal(100, sl2.Count); for (i = 0; i < 100; i++) { j = i + 100; Assert.True(sl2.ContainsKey((int)j)); Assert.True(sl2.ContainsValue(i)); object o2 = sl2[(object)(j)]; //need to cast: Get (object key) Assert.NotNull(o2); i2 = (int)o2; i3 = (int)sl2.GetByIndex(i); //Get (index i) Assert.False((i3 != i) || (i2 != i)); // testcase: GetEnumerator dicen = (IDictionaryEnumerator)sl2.GetEnumerator(); // Boundary for Current Assert.Throws<InvalidOperationException>(() => { object throwaway = dicen.Current; } ); j = 0; // go over the enumarator while (dicen.MoveNext()) { // Current to see the order i3 = (int)dicen.Value; Assert.True(j.Equals(i3)); // Current again to see the same order i3 = (int)dicen.Value; Assert.Equal(i3, j); j++; } // Boundary for Current Assert.Throws<InvalidOperationException>(() => { object throwaway = dicen.Current; } ); // Boundary for MoveNext: call MoveNext to make sure it returns false Assert.False((dicen.MoveNext()) || (j != 100)); // call again MoveNext to make sure it still returns false Assert.False(dicen.MoveNext()); } }
private void but_consultar_libro_Click(object sender, EventArgs e) { if (tex_isbn.Text.Length == 0) { this.inicializarDatos(); MessageBox.Show("Debe ingresar un ISBN", "Consultar Libro", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { try { Libro lib = new Libro(); lib.v_isbn = tex_isbn.Text; if ((lib.ConsultarLibro(lib)).v_isbn.Length != 0) { tex_isbn.Text = lib.v_isbn; tex_titulo.Text = lib.v_titulo; tex_edicion.Text = lib.v_edicion; tex_autor.Text = lib.v_autor; tex_año.Text = lib.v_año; SLeditorial = new SortedList(); SLeditorial.Add(lib.v_Deditorial, lib.v_Deditorial); com_editorial.DataSource = SLeditorial.GetValueList(); com_editorial.Show(); com_editorial.Enabled = false; SLeditorial.Clear(); SLtipolibro = new SortedList(); SLtipolibro.Add(lib.v_Dtipo_libro, lib.v_Dtipo_libro); com_tipo_libro.DataSource = SLtipolibro.GetValueList(); com_tipo_libro.Show(); com_tipo_libro.Enabled = false; SLtipolibro.Clear(); SLidioma = new SortedList(); SLidioma.Add(lib.v_Didioma, lib.v_Didioma); com_idioma.DataSource = SLidioma.GetValueList(); com_idioma.Show(); com_idioma.Enabled = false; SLidioma.Clear(); } } catch (SqlException ex) { for (int i = 0; i < ex.Errors.Count; i++) { errorMessages.Append("Index #" + i + "\n" + "Message: " + ex.Errors[i].Message + "\n" + "LineNumber: " + ex.Errors[i].LineNumber + "\n" + "Source: " + ex.Errors[i].Source + "\n" + "Procedure: " + ex.Errors[i].Procedure + "\n"); } Console.WriteLine(errorMessages.ToString()); this.inicializarDatos(); MessageBox.Show(ex.Errors[0].Message.ToString(), "Consultar Libro", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }
public void Clear_Capacity () { // strangely Clear change the default capacity (while Capacity doesn't) for (int i = 0; i <= 16; i++) { SortedList sl = new SortedList (i); Assert.AreEqual (i, sl.Capacity, "#1:"+ i); sl.Clear (); // reset to class default (16) Assert.AreEqual (16, sl.Capacity, "#2:" + i); } }
public void TestGetKeyBasic() { StringBuilder sblMsg = new StringBuilder(99); SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); string s1 = null; string s2 = null; int i = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(this); // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // Testcase: GetKey - key at index 0 , ArgExc expected Assert.Throws<ArgumentOutOfRangeException>(() => { sl2.GetKey(0); }); // Testcase: GetKey - null val, should pass sl2["first key"] = (string)null; Assert.Equal(1, sl2.Count); // Testcase: vanila Set sl2.Clear(); // Testcase: add key-val pairs for (i = 0; i < 50; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add(s1, s2); } // // now get their keys using GetKey // for (i = 0; i < 50; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); Assert.True(((string)sl2.GetKey(sl2.IndexOfKey(s1))).Equals(s1)); } Assert.Equal(50, sl2.Count); }
public void TestClear () { SortedList sl1 = new SortedList (10); sl1.Add ("kala", 'c'); sl1.Add ("kala2", 'd'); Assert.AreEqual (10, sl1.Capacity, "#A1"); Assert.AreEqual (2, sl1.Count, "#A2"); sl1.Clear (); Assert.AreEqual (0, sl1.Count, "#B1"); }
/// <summary> /// Sparar till Excel-fil /// </summary> public static LoadOrSaveResult GetAllEntriesFromExcelFile( KontoutdragInfoForLoad kontoutdragInfoForLoad, SortedList saveToTable, SaldoHolder saldoHolder, Hashtable entriesLoadedFromDataStore) { // Töm alla tidigare entries i minnet om det ska laddas helt ny fil el. likn. if (kontoutdragInfoForLoad.clearContentBeforeReadingNewFile) { saveToTable.Clear(); } // Görs i Ui-handling, UpdateEntriesToSaveMemList(); // Skapa kontoentries // För att se om det laddats något, så UI-uppdateras etc. Så returneras bool om det... return SkapaKontoEntries(saveToTable, entriesLoadedFromDataStore, saldoHolder); }
private void btnGenerate_Click(object sender, EventArgs e) { ulong baseFreq = 0; double fps = 0; ulong maxResults = 0; SortedList<double, ArrayList> timingInfos = new SortedList<double, ArrayList>(); timingInfos.Clear(); if (!double.TryParse(txtFps.Text, out fps)) { return; } if (!ulong.TryParse(txtBaseFreq.Text, out baseFreq)) { return; } if (!ulong.TryParse(txtResults.Text, out maxResults)) { return; } double clock = (double)baseFreq / fps; uint t1Min = SelectedModel.T1min; uint t1Max = SelectedModel.T1max; uint t2Min = SelectedModel.T2min; uint t2Max = SelectedModel.T2max; for (uint t1 = t1Min; t1 <= t1Max; t1++) { uint t2_a = (uint)Math.Floor(clock / (double)t1); uint t2_b = (uint)Math.Ceiling(clock / (double)t1); if ((t2_a > t2Min && t2_a < t2Max) && (t2_b > t2Min && t2_b < t2Max)) { double exactFps_a = Math.Round((double)baseFreq / t1 / t2_a, 9); double exactFps_b = Math.Round((double)baseFreq / t1 / t2_b, 9); if ((Math.Abs(exactFps_a - fps) < MaxDelta) && (Math.Abs(exactFps_b - fps) < MaxDelta)) { TimingInfo info_a = new TimingInfo(t1, t2_a, exactFps_a); TimingInfo info_b = new TimingInfo(t1, t2_b, exactFps_b); AddInfo(timingInfos, info_a); AddInfo(timingInfos, info_b); } } } double[] filtered = FilterEntries(timingInfos, fps, maxResults); DisplayResults(timingInfos, filtered); return; }
//private void mostrarLista() //{ // StringBuilder errorMessages = new StringBuilder(); // Editorial edi = new Editorial(); // try // { // if ((edi.OptenerPais(edi)).v_pais.Count != 0) // { // SLpais = new SortedList(); // foreach (String pais in edi.v_pais) // { // SLpais.Add(pais, pais); // } // com_pais.DataSource = SLpais.GetValueList(); // com_pais.Show(); // } // } // catch (SqlException ex) // { // for (int i = 0; i < ex.Errors.Count; i++) // { // errorMessages.Append("Index #" + i + "\n" + // "Message: " + ex.Errors[i].Message + "\n" + // "LineNumber: " + ex.Errors[i].LineNumber + "\n" + // "Source: " + ex.Errors[i].Source + "\n" + // "Procedure: " + ex.Errors[i].Procedure + "\n"); // } // Console.WriteLine(errorMessages.ToString()); // MessageBox.Show(ex.Errors[0].Message.ToString(), // "Eliminar Editorial", // MessageBoxButtons.OK, // MessageBoxIcon.Warning); // } //} private void but_eliminar_persona_Click(object sender, EventArgs e) { StringBuilder errorMessages = new StringBuilder(); Editorial edi = new Editorial(); if (tex_nombre_editorial.Text.Length == 0) { this.inicializarDatos(); MessageBox.Show("Debe ingresar un Nombre", "Eliminar Editorial", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { try { edi.v_nombre_editorial = tex_nombre_editorial.Text; //edi.v_Dpais = com_pais.SelectedItem.ToString(); edi.v_usuario_m = this.usuario; if ((edi.ConsultarEditorial(edi)).v_nombre_editorial.Length != 0) { tex_nombre_editorial.Text = edi.v_nombre_editorial; tex_direccion.Text = edi.v_direccion_editorial; SLpais = new SortedList(); SLpais.Add(edi.v_Dpais, edi.v_Dpais); com_pais.DataSource = SLpais.GetValueList(); com_pais.Show(); com_pais.Enabled = false; if ((MessageBox.Show("¿Desea eliminar la Editorial con Nombre: " + edi.v_nombre_editorial + " ?", "Eliminar Editorial", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)) { try { if (edi.EliminarEditorial(edi) != 0) { SLpais.Clear(); com_pais.DataSource = null; com_pais.Show(); this.inicializarDatos(); MessageBox.Show("Editorial eliminada correctamente", "Eliminar Editorial", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (SqlException ex) { for (int i = 0; i < ex.Errors.Count; i++) { SLpais.Clear(); com_pais.DataSource = null; com_pais.Show(); errorMessages.Append("Index #" + i + "\n" + "Message: " + ex.Errors[i].Message + "\n" + "LineNumber: " + ex.Errors[i].LineNumber + "\n" + "Source: " + ex.Errors[i].Source + "\n" + "Procedure: " + ex.Errors[i].Procedure + "\n"); } Console.WriteLine(errorMessages.ToString()); this.inicializarDatos(); MessageBox.Show(ex.Errors[0].Message.ToString(), "Eliminar Editorial", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } } catch (SqlException ex) { for (int i = 0; i < ex.Errors.Count; i++) { errorMessages.Append("Index #" + i + "\n" + "Message: " + ex.Errors[i].Message + "\n" + "LineNumber: " + ex.Errors[i].LineNumber + "\n" + "Source: " + ex.Errors[i].Source + "\n" + "Procedure: " + ex.Errors[i].Procedure + "\n"); } SLpais.Clear(); com_pais.DataSource = null; com_pais.Show(); Console.WriteLine(errorMessages.ToString()); this.inicializarDatos(); MessageBox.Show(ex.Errors[0].Message.ToString(), "Eliminar Editorial", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } }
public void TestGetCountBasic() { StringBuilder sblMsg = new StringBuilder(99); // SortedList sl2 = null; StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); string s1 = null; string s2 = null; int i = 0; // // Constructor: Create SortedList using this as IComparer and default settings. // sl2 = new SortedList(this); // Verify that the SortedList is not null. Assert.NotNull(sl2); // Verify that the SortedList is empty. Assert.Equal(0, sl2.Count); // Testcase: Set - null val, should pass sl2["first key"] = (string)null; Assert.Equal(1, sl2.Count); // Testcase: vanila Set sl2["first key"] = "first value"; Assert.Equal(1, sl2.Count); sl2.Clear(); Assert.Equal(0, sl2.Count); // Testcase: add key-val pairs for (i = 0; i < 50; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2.Add(s1, s2); } Assert.Equal(50, sl2.Count); // // Testcase: now set 100 key-val pairs, this includes the first 50 pairs that // we just added, their values must be changed to the new values set // for (i = 0; i < 100; i++) { sblMsg.Length = 0; sblMsg.Append("key_"); sblMsg.Append(i); s1 = sblMsg.ToString(); sblMsg.Length = 0; sblMsg.Append("new_val_"); sblMsg.Append(i); s2 = sblMsg.ToString(); sl2[s1] = s2; } Assert.Equal(100, sl2.Count); // clear and check the Count == 0 sl2.Clear(); Assert.Equal(0, sl2.Count); }
/// <summary> /// Activates a log action. /// </summary> /// <param name="context">The context.</param> /// <param name="selectedPacket">The selected packet.</param> /// <returns><c>true</c> if log data tab should be updated.</returns> public override bool Activate(IExecutionContext context, PacketLocation selectedPacket) { PacketLog log = context.LogManager.GetPacketLog(selectedPacket.LogIndex); int selectedIndex = selectedPacket.PacketIndex; SortedList m_inventoryItems = new SortedList(); int preAction = 0; int lastVaultPreAction = -1; int vaultNumber = -1; int VisibleSlots = 0xFF; for (int i = 0; i <= selectedIndex; i++) { Packet pak = log[i]; if (pak is StoC_0x20_PlayerPositionAndObjectID_171) { VisibleSlots = 0xFF; m_inventoryItems.Clear(); } else if (pak is StoC_0x02_InventoryUpdate) { StoC_0x02_InventoryUpdate invPack = (StoC_0x02_InventoryUpdate)pak; if (invPack.PreAction != 0 && invPack.PreAction != 10) preAction = invPack.PreAction; // rememer last opened inventory action, if it not update if (preAction > 10) preAction -= 10; if (invPack.PreAction == 1 || invPack.PreAction == 0 || invPack.PreAction == 11 || invPack.PreAction == 10) VisibleSlots = invPack.VisibleSlots; if (invPack.PreAction == 2) { for (byte j = 40; j < 80; j++) { if (m_inventoryItems.ContainsKey(j)) m_inventoryItems.Remove(j); } } else if (invPack.PreAction == 7) { for (byte j = 80; j <= 95; j++) { if (m_inventoryItems.ContainsKey(j)) m_inventoryItems.Remove(j); } } else if (invPack.PreAction == 3) { for (byte j = 110; j < 150; j++) { if (m_inventoryItems.ContainsKey(j)) m_inventoryItems.Remove(j); } } else if (invPack.PreAction == 4 || invPack.PreAction == 5 || invPack.PreAction == 6) { lastVaultPreAction = invPack.PreAction; vaultNumber = invPack.VisibleSlots; for (byte j = 150; j < 250; j++) { if (m_inventoryItems.ContainsKey(j)) m_inventoryItems.Remove(j); } } for (int j = 0; j < invPack.SlotsCount; j++) { StoC_0x02_InventoryUpdate.Item item = (StoC_0x02_InventoryUpdate.Item)invPack.Items[j]; if (item.name == null || item.name == "") { if (m_inventoryItems.ContainsKey(item.slot)) m_inventoryItems.Remove(item.slot); } else { if (m_inventoryItems.ContainsKey(item.slot)) m_inventoryItems[item.slot] = item; else m_inventoryItems.Add(item.slot, item); } } } } StringBuilder str = new StringBuilder(); str.AppendFormat("VisibleSlots:0x{0:X2} last initialized preAction:{1}({2})\n", VisibleSlots, preAction, (StoC_0x02_InventoryUpdate.ePreActionType)preAction); eWindowType prevWindowType = eWindowType.Unknown; eWindowType windowType = eWindowType.Unknown; foreach (StoC_0x02_InventoryUpdate.Item item in m_inventoryItems.Values) { // if (item.slot > 95 /*&& item.slot < 1000*/) { string selected = " "; if (item.slot >= 7 && item.slot <= 9) windowType = eWindowType.Horse; else if (item.slot >= 10 && item.slot <= 13) { windowType = eWindowType.Weapon; if (((item.slot - 10) == (VisibleSlots & 0x0F)) || ((item.slot - 10) == ((VisibleSlots >> 4) & 0x0F))) selected = "*"; } else if (item.slot >= 14 && item.slot <= 17) windowType = eWindowType.Quiver; else if (item.slot >= 21 && item.slot <= 37) windowType = eWindowType.Doll; else if (item.slot >= 40 && item.slot <= 79) windowType = eWindowType.Backpack; else if (item.slot >= 80 && item.slot <= 95) windowType = eWindowType.Horsebag; else if (item.slot >= 110 && item.slot <= 149) windowType = eWindowType.Vault; else if (item.slot >= 150 && item.slot <= 249) windowType = eWindowType.HouseVault; if (windowType != prevWindowType) { str.Append('\n'); str.Append(windowType); if (windowType == eWindowType.HouseVault) { if (lastVaultPreAction == 4 && vaultNumber != -1) { str.Append(' '); str.Append(vaultNumber); } str.AppendFormat(" ({0})", (StoC_0x02_InventoryUpdate.ePreActionType)lastVaultPreAction); } } str.AppendFormat("\n{16}slot:{0,-3} level:{1,-2} value1:0x{2:X2} value2:0x{3:X2} hand:0x{4:X2} damageType:0x{5:X2} objectType:0x{6:X2} weight:{7,-4} con:{8,-3} dur:{9,-3} qual:{10,-3} bonus:{11,-2} model:0x{12:X4} color:0x{13:X4} effect:0x{14:X2} \"{15}\"", item.slot, item.level, item.value1, item.value2, item.hand, item.damageType, item.objectType, item.weight, item.condition, item.durability, item.quality, item.bonus, item.model, item.color, item.effect, item.name, selected); if (item.name != null && item.name != "") str.AppendFormat(" ({0})", (StoC_0x02_InventoryUpdate.eObjectType)item.objectType); prevWindowType = windowType; } } InfoWindowForm infoWindow = new InfoWindowForm(); infoWindow.Text = "Player inventory info (right click to close)"; infoWindow.Width = 800; infoWindow.Height = 400; infoWindow.InfoRichTextBox.Text = str.ToString(); infoWindow.StartWindowThread(); return false; }