private static Match[] MatchSubstring(string i_source, string i_matchPattern, bool i_uniqueMatch) { //<note> use RegexOptions.Multiline, otherwise it will treat the whole thing as 1 string Regex regex = new Regex(i_matchPattern, RegexOptions.Multiline); MatchCollection matchCollection = regex.Matches(i_source); Match[] result; if (!i_uniqueMatch) { result = new Match[matchCollection.Count]; matchCollection.CopyTo(result, 0); } else { //<note> cannot use HashSet<Match> because each Match object is unique, even though they may have same value (string). Can use HashSet<string> //SortedList is more like sorted Dictionary<key, value> SortedList uniqueMatchCollection = new SortedList(); foreach(Match match in matchCollection) { if (!uniqueMatchCollection.ContainsKey(match.Value)) { uniqueMatchCollection.Add(match.Value, match); } } result = new Match[uniqueMatchCollection.Count]; uniqueMatchCollection.Values.CopyTo(result, 0); //<note> cannot use uniqueMatchCollection.CopyTo(...) since SortedList member is not type-match with destination array member } Console.WriteLine("Found {0} matches", result.Length); return result; }
public override DialogueAct Parse(SortedList speech, SortedList gesture, Agent agent) { DialogueAct dlgAct = null; // Test for actions if (speech.ContainsKey("intention")) { dlgAct = new DialogueAct(agent, speech, gesture, DialogueActType.Intend); return dlgAct; } if (this._prevDlgResp != null && this._prevDlgResp.Count > 0) { // Test for answer to previous questions foreach (DialogueResponse resp in this._prevDlgResp) { if (resp.DlgRespType == DialogueResponseType.speechQuestion || resp.DlgRespType == DialogueResponseType.listPlainOptions || resp.DlgRespType == DialogueResponseType.listMapLayerOptions || resp.DlgRespType == DialogueResponseType.listOptionsWithExamples) { if (speech.ContainsKey("affirmative")) { dlgAct = new DialogueAct(agent, speech, gesture, DialogueActType.Accept); } else if (speech.ContainsKey("negative")) { dlgAct = new DialogueAct(agent, speech, gesture, DialogueActType.Reject); } else { dlgAct = new DialogueAct(agent, speech, gesture, DialogueActType.Answer); } return dlgAct; } } // Test for feedback to previous actions foreach (DialogueResponse resp in this._prevDlgResp) { if (resp.DlgRespType == DialogueResponseType.drawPolygonStarted) { dlgAct = new DialogueAct(agent, speech, gesture, DialogueActType.Feedback); return dlgAct; } else if (resp.DlgRespType == DialogueResponseType.selectByAttributes) { dlgAct = new DialogueAct(agent, speech, gesture, DialogueActType.Feedback); return dlgAct; } } } return dlgAct; }
public static AddedAndReplacedEntriesCounter AddNewEntries(SortedList oldKontoEntries, SortedList newEntries) { var somethingChanged = false; var addedEntries = 0; var replacedEntries = 0; foreach (KontoEntry entry in newEntries.Values) // _newKontoEntries.Values) { if (!entry.ThisIsDoubleDoNotAdd) { if (!oldKontoEntries.ContainsKey(entry.KeyForThis)) // (detta ska redan vara kollat) { if (string.IsNullOrEmpty(entry.ReplaceThisKey)) // Add new { entry.FontFrontColor = Color.Lime; oldKontoEntries.Add(entry.KeyForThis, entry); addedEntries++; } else // Replace old { entry.FontFrontColor = Color.Blue; // ev. skulle man sätta replacethiskey till den gamla keyn med den som ersatte, för att kunna spåra förändringar if (oldKontoEntries.ContainsKey(entry.ReplaceThisKey)) { oldKontoEntries[entry.ReplaceThisKey] = entry; } else { MessageBox.Show("Error: key not found! : " + entry.ReplaceThisKey); } replacedEntries++; } somethingChanged = true; // Här har man tagit in nytt som inte är sparat } else { Console.WriteLine("Double key found!: " + entry.KeyForThis); } } } return new AddedAndReplacedEntriesCounter { SomethingChanged = somethingChanged, Added = addedEntries, Replaced = replacedEntries }; }
public static void AddNewEntryFromStringArray( BankRow entryStrings, SortedList kontoEntries, SortedList newKontoEntries, SortedList newBatchOfKontoEntriesAlreadyRed) { var newKeyFromHtml = new KontoEntry(entryStrings); var key = newKeyFromHtml.KeyForThis; if (!kontoEntries.ContainsKey(key) && !newKontoEntries.ContainsKey(key)) // Kollas även senare { // if (newKontoEntries != null) {// && !newKontoEntries.ContainsKey(key)) { if (key != null) { newKontoEntries.Add(key, newKeyFromHtml); // } // else { // //Dubblett // } } // Handle Doubles } else if (!newBatchOfKontoEntriesAlreadyRed.ContainsKey(key)) { // Om man hade entryn i Excel, innan laddning, och innan man gick igenom nya, så kan man (förutsätter att man då det inte finns saldo (i allkort-kredit), så läses hela listan in i ett svep, det är inte en lista, det kan ev. bli dubblet om två datum hamnar på olika allkort-kredit-fakturor) var userDecision = MessageBox.Show( "Found potential double: " + newKeyFromHtml.KeyForThis, "Double, SaveThisEntry?", MessageBoxButtons.YesNo); if (userDecision.Equals(DialogResult.Yes)) { // Detta är en dubblett, men om det finns fler än 2 dubbletter så måste man se till att nyckeln är unik while (newKontoEntries.ContainsKey(newKeyFromHtml.KeyForThis)) { // Stega upp saldo, tills en unik nyckel skapats newKeyFromHtml.SaldoOrginal += newKeyFromHtml.KostnadEllerInkomst != 0 ? newKeyFromHtml.KostnadEllerInkomst : 1; } newKontoEntries.Add(newKeyFromHtml.KeyForThis, newKeyFromHtml); } // För annat än Allkortskredit, så ordnar Detta sig, så länge saldot är med i nyckeln, det är den, så det gäller bara att ha rätt saldo i xls //Om man tagit utt t.ex. 100kr 2 ggr samma dag, från samma bankomat. hm, sätt 1 etta efteråt, men det göller ju bara det som är såna, hm, får ta dem manuellt } }
static void Main(string[] args) { if(args.Length == 0) { Console.WriteLine( "Usage: DumpTypeHashes <assembly> ..." ); return; } foreach(string s in args) { Assembly assm = Assembly.LoadFrom( s ); SortedList sl = new SortedList(); foreach(Type t in assm.GetTypes()) { if(sl.ContainsKey( t.FullName ) == false) { sl.Add( t.FullName, Microsoft.SPOT.Debugger.BinaryFormatter.LookupHash( t ) ); } } foreach(string s2 in sl.Keys) { Console.WriteLine( "{2} {1:X8} {0}", s2, sl[ s2 ], assm.GetName() ); } } }
public static Shop.shop_sold_item sort_sold_items(Shop.shop_sold_item sold_items) { Shop.shop_sold_item sold_items_sorted = new Shop.shop_sold_item(); System.Collections.SortedList used = new System.Collections.SortedList(); for (int i = 0; i < sold_items._shop_sold_item.Rows.Count; ++i) { Shop.shop_sold_item.shop_sold_itemRow row = sold_items._shop_sold_item[i]; if (used.ContainsKey(row.idx)) { continue; } if (row.type == 1) { sold_items_sorted._shop_sold_item.ImportRow(row); foreach (Shop.shop_sold_item.shop_sold_itemRow r in sold_items._shop_sold_item.Rows) { if (r.parent == row.idx) { sold_items_sorted._shop_sold_item.ImportRow(r); used[r.idx] = 1; } } } else { sold_items_sorted._shop_sold_item.ImportRow(row); } } return(sold_items_sorted); }
public static Match[] FindSubstrings(string source, string matchPattern, bool findAllUnique) { SortedList uniqueMatches = new SortedList(); Match[] retArray = null; Regex RE = new Regex(matchPattern, RegexOptions.Multiline); MatchCollection theMatches = RE.Matches(source); if (findAllUnique) { for (int counter = 0; counter < theMatches.Count; counter++) { if (!uniqueMatches.ContainsKey(theMatches[counter].Value)) { uniqueMatches.Add(theMatches[counter].Value, theMatches[counter]); } } retArray = new Match[uniqueMatches.Count]; uniqueMatches.Values.CopyTo(retArray, 0); } else { retArray = new Match[theMatches.Count]; theMatches.CopyTo(retArray, 0); } return (retArray); }
private void AddInfo(SortedList<double, ArrayList> timingInfos, TimingInfo newInfo) { if (!timingInfos.ContainsKey(newInfo.Fps)) { timingInfos.Add(newInfo.Fps, new ArrayList()); } bool found = false; foreach (TimingInfo info in timingInfos[newInfo.Fps]) { if (info.T1Value == newInfo.T1Value && info.T2Value == newInfo.T2Value) { found = true; } if (info.T2Value == newInfo.T1Value && info.T1Value == newInfo.T2Value) { //found = true; } } if (!found) { timingInfos[newInfo.Fps].Add(newInfo); } }
public IEnumerable<KeyValuePair<int, double>> Rank(IEnumerable<string> queryTerms, SortedDictionary<string, Term> terms, int documentCount) { SortedList<int, double> scores = new SortedList<int, double>(); foreach (var queryTerm in queryTerms) { if (!terms.ContainsKey(queryTerm)) return null; Term currentTerm = terms[queryTerm]; int documentFrequency = currentTerm.Frequency; foreach (var posting in currentTerm.Postings) { int docId = posting.Key; int termFrequency = posting.Value; double weight = GetTfIdf(termFrequency, documentCount, documentFrequency); if (scores.ContainsKey(docId)) { scores[docId] += weight; } else { scores.Add(docId, weight); } } } return scores.OrderByDescending(kvp => kvp.Value); }
/// <summary> /// The main entry point of the application - does all the work, really. /// </summary> public static void Main() { SortedList table = new SortedList(); string fileData = string.Empty; Console.WriteLine("This program counts how many times each word occurs in a file."); Console.Write("Enter the filename of the file to read from:\n > "); string filename = Console.ReadLine(); while (string.IsNullOrEmpty(filename)) { Console.Write("You cannot enter a blank path name - try again:\n > "); filename = Console.ReadLine(); } // Try to access the file and bail out if an error occurred try { fileData = File.ReadAllText(filename); } catch { Console.WriteLine("File was not accessible. Please make sure it exists and you have appropriate permission to read it."); return; } // Get the file contents, convert to lowercase and remove all non-alpha and non-space characters, // then get a raw array (still contains duplicates) of all the words string[] rawWordArray = WordCountExampleProgram.GetWordsArray(fileData.ToLower()); // For each for in the array... for (int i = 0; i < rawWordArray.Length; i++) { if (!table.ContainsKey(rawWordArray[i])) { // If the table does not already contain the key, add it to the list with a count of 1 table.Add(rawWordArray[i], 1); } else { // Otherwise it was already in the table, increment its previous count by one table[rawWordArray[i]] = Convert.ToInt32(table[rawWordArray[i]]) + 1; } } // Make a variable to count total words int totalWords = 0; // Print out the key and value of each along with some headers Console.WriteLine("\nWord" + string.Empty.PadRight(50 - "Word".Length, ' ') + "Count\n" + string.Empty.PadRight(50 + "Count".Length, '-')); for (int i = 0; i < table.Count; i++) { int value = Convert.ToInt32(table.GetByIndex(i)); totalWords += value; Console.WriteLine(String.Format("{0,-50}{1}", table.GetKey(i), value)); } Console.WriteLine("{0,-50}{1}\n", "TOTAL", totalWords); }
protected void Page_Load(object sender, EventArgs e) { Response.ContentType = "text/xml"; int pageId; XmlNode root = _xd.CreateElement("tasks"); if (int.TryParse(Request["id"], out pageId)) { var t = new Task(pageId); if (t.User.Id == base.getUser().Id || t.ParentUser.Id == base.getUser().Id) { XmlNode x = CreateTaskNode(t, _xd); root.AppendChild(x); xmlContents.Text = root.OuterXml; Response.AddHeader("Content-Disposition", "attachment; filename=" + t.Node.Text.Replace(" ", "_") + ".xml"); } } else { var nodes = new SortedList(); int totalWords = 0; foreach (Task t in Task.GetTasks(base.getUser(), false)) { if (!nodes.ContainsKey(t.Node.Path)) { var xTask = CreateTaskNode(t, _xd); totalWords += int.Parse(xTask.Attributes.GetNamedItem("TotalWords").Value); nodes.Add(t.Node.Path, xTask); } } // Arrange nodes in tree var ide = nodes.GetEnumerator(); while (ide.MoveNext()) { var x = (XmlElement)ide.Value; var parentXpath = UmbracoSettings.UseLegacyXmlSchema ? "//node [@id = '" + x.SelectSingleNode("//node").Attributes.GetNamedItem("parentID").Value + "']" : "//* [@isDoc and @id = '" + x.SelectSingleNode("//* [@isDoc]").Attributes.GetNamedItem("parentID").Value + "']"; var parent = _xd.SelectSingleNode(parentXpath); if (parent == null) parent = root; else parent = parent.ParentNode; parent.AppendChild((XmlElement)ide.Value); } root.Attributes.Append(XmlHelper.AddAttribute(_xd, "TotalWords", totalWords.ToString())); xmlContents.Text = root.OuterXml; Response.AddHeader("Content-Disposition", "attachment; filename=all.xml"); } }
public virtual System.Data.DataTable Transform(DataTable sourceTable) { DataTable retTable = sourceTable.Clone(); // only clones the structure SortedList<string, string> transposeNames = new SortedList<string, string>(); PrepareColumns(sourceTable, retTable, transposeNames); SortedList<string, DataRow> keyRows = new SortedList<string, DataRow>(); for (int i = 0; i < sourceTable.Rows.Count; i++) { DataRow sourceRow = sourceTable.Rows[i]; // PrepareTransposeKeyKeyColumns(sourceTable, retTable, transposeNames); // Null values are normalized to be an empty string string trKeyName = String.Empty; object sourceNameObject = sourceRow[transposeDefinition.SourceNameColumnName]; if (sourceNameObject != null) { trKeyName = sourceNameObject.ToString(); } string dataKeyName = String.Empty; object dataKeyNameObject = sourceRow[transposeDefinition.KeyColumnName]; if (dataKeyNameObject != null) { dataKeyName = dataKeyNameObject.ToString(); } //** if (!keyRows.ContainsKey(dataKeyName)) { DataRow dr = retTable.NewRow(); keyRows.Add(dataKeyName, dr); retTable.Rows.Add(dr); FillRow(sourceTable, sourceRow, dr, trKeyName); } else { FillRow(sourceTable, sourceRow, keyRows[dataKeyName], trKeyName); } } ReshuffleColumns(retTable, transposeNames); return retTable; }
public string GetFunctionsAndAggregates() { SortedList sortedList = new SortedList(_aggregateNames.Count + _functionNames.Count); foreach (string key in _aggregateNames.Keys) { if (!sortedList.ContainsKey(key)) sortedList.Add(key, null); } foreach (string key in _functionNames.Keys) { if (!sortedList.ContainsKey(key)) sortedList.Add(key, null); } return GetKeys(sortedList); }
/// <summary> /// Build the Modification list of what files will be built /// with this Release /// </summary> /// <param name="mods"></param> /// <returns></returns> public static Modification[] AnalyzeModifications(IList mods) { // Hashtables are used so we can compare on the keys in search of duplicates SortedList allFiles = new SortedList(); foreach (Modification mod in mods) { string key = mod.FolderName + mod.FileName; if (!allFiles.ContainsKey(key)) allFiles.Add(key, mod); else { // If the revision number on the original is larger, then // do the comparision against the original modification // in search to see which revision is higher // example: 1.64.1 < 1.65 but you need to compare against the // larger string of 1.64.1 because we are splitting the numbers individually // so 1 is compared to 1 and 64 is compared to 65. Modification compareMod = allFiles[key] as Modification; string[] originalVersion = compareMod.Version.Split(char.Parse(".")); string[] currentVersion = mod.Version.Split(char.Parse(".")); int len1 = originalVersion.Length; int len2 = currentVersion.Length; int usingLen; int otherLen; if (len1 >= len2) { usingLen = len1; otherLen = len2; } else { usingLen = len2; otherLen = len1; } for (int i = 0; i < usingLen; i++) { if (i > otherLen) continue; if (Convert.ToInt32(currentVersion[i], CultureInfo.CurrentCulture) > Convert.ToInt32(originalVersion[i], CultureInfo.CurrentCulture)) { allFiles[compareMod.FolderName + compareMod.FileName] = mod; break; } } } } // Convert the Hashtables to Modification arrays Modification[] validMods = new Modification[allFiles.Count]; int count = 0; foreach (string key in allFiles.Keys) { validMods[count++] = allFiles[key] as Modification; } return validMods; }
internal void Add(GridItem grid_item) { string key = grid_item.Label; while (list.ContainsKey(key)) { key += "_"; } list.Add(key, grid_item); }
public static string GetFamilia(string IdTDCompTesoreria) { if (!_loaded) { DeclareTypes(); } if (_nameFDPFamilia.ContainsKey(IdTDCompTesoreria)) { return(Convert.ToString(_nameFDPFamilia[IdTDCompTesoreria])); } return(string.Empty); }
/** * Creates array of all possible cell edges. In HTML (and FO) cells from * different rows and same column should have same width, otherwise spanning * shall be used. * * @param table * table to build cell edges array from * @return array of cell edges (including leftest one) in twips */ public static int[] BuildTableCellEdgesArray(Table table) { SortedList<int, int> edges = new SortedList<int, int>(); for (int r = 0; r < table.NumRows; r++) { TableRow tableRow = table.GetRow(r); for (int c = 0; c < tableRow.NumCells(); c++) { TableCell tableCell = tableRow.GetCell(c); if (!edges.ContainsKey(tableCell.GetLeftEdge())) edges.Add(tableCell.GetLeftEdge(), 0); if (!edges.ContainsKey(tableCell.GetLeftEdge() + tableCell.GetWidth())) edges.Add(tableCell.GetLeftEdge() + tableCell.GetWidth(), 0); } } int[] result = new int[edges.Count]; edges.Keys.CopyTo(result, 0); return result; }
public static SortedList GetNewBatchOfKontoEntriesAlreadyRed( SortedList kontoEntries, SortedList newKontoEntries) { var newBatchOfKontoEntriesAlreadyRed = new SortedList(); foreach (DictionaryEntry entry in newKontoEntries) { if (!newBatchOfKontoEntriesAlreadyRed.ContainsKey(entry.Key)) { newBatchOfKontoEntriesAlreadyRed.Add(entry.Key, entry.Value); } } foreach (DictionaryEntry entry in kontoEntries) { if (!newBatchOfKontoEntriesAlreadyRed.ContainsKey(entry.Key)) { newBatchOfKontoEntriesAlreadyRed.Add(entry.Key, entry.Value); } } return newBatchOfKontoEntriesAlreadyRed; }
private void deleteLevelSide( MamdaOrderBookPriceLevel level, TreeMap bookSide) { MamaPrice price = level.getPrice(); if (bookSide.ContainsKey(price)) { /* We actually need to process this properly because the * update may not contain all entries, just updated * ones. */ bookSide.Remove(price); } }
static public int ContainsKey(IntPtr l) { try { System.Collections.SortedList self = (System.Collections.SortedList)checkSelf(l); System.Object a1; checkType(l, 2, out a1); var ret = self.ContainsKey(a1); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } }
private void addLevelSide( MamdaOrderBookPriceLevel level, TreeMap bookSide) { MamaPrice price = level.getPrice(); if (!bookSide.ContainsKey(price)) { bookSide.Add(price, level); } else { bookSide[price] = level; // Overwrite it anyway } }
public ChannelPrograms(DateTime lowerBoundTime, DateTime upperBoundTime, GuideProgramSummary[] guidePrograms) { _lowerBoundTime = lowerBoundTime; _upperBoundTime = upperBoundTime; _programs = new SortedList<DateTime, GuideProgramSummary>(); foreach (GuideProgramSummary guideProgram in guidePrograms) { // Normally this should not happen, but in case there's bad guide data and two programs start at // the same time, let's make sure we only display one of them. if (!_programs.ContainsKey(guideProgram.StartTime)) { _programs.Add(guideProgram.StartTime, guideProgram); } } }
public void Append(String tickerKey, SortedList<DateTime, double> data, double defaultValue) { double curValue = defaultValue; foreach (DateTime pivotDate in this.PivotDates) { if (data.ContainsKey(pivotDate)) { // ok we have data curValue = data[pivotDate]; } AppendData(pivotDate, tickerKey, curValue); } this.RegisteredTickerKeys.Add(tickerKey); }
/// <summary> /// The get length list. /// </summary> /// <returns> /// The <see cref="ArrayList"/>. /// </returns> public ArrayList GetLengthList() { var list = new SortedList(); for (int i = 0; i < Cardinality; i++) { int l = ((BaseChain)this[i]).GetLength(); if (list.ContainsKey(l)) { continue; } list.Add(l, l); } return new ArrayList(list.Keys); }
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { Reference retval = null; try { edSvc = (System.Windows.Forms.Design.IWindowsFormsEditorService)provider.GetService(typeof(System.Windows.Forms.Design.IWindowsFormsEditorService)); ModelRoot root = null; if (context.Instance is Relation) root = (ModelRoot)((Relation)context.Instance).Root; else if (context.Instance is Table) root = (ModelRoot)((Table)context.Instance).Root; var tableCollection = root.Database.Tables; //Create the list box var newBox = new System.Windows.Forms.ListBox(); newBox.Click += new EventHandler(newBox_Click); newBox.IntegralHeight = false; var sortedList = new SortedList(); foreach (Table table in tableCollection) { //Ensure key is unique to avoid error var text = table.Name.ToLower(); var key = text; var ii = 0; while (sortedList.ContainsKey(key)) { key = text + ii.ToString(); ii++; } sortedList.Add(key, table); } //Re-add them in order foreach (DictionaryEntry di in sortedList) newBox.Items.Add((Table)di.Value); edSvc.DropDownControl(newBox); if ((newBox.SelectedIndex > -1) && (newBox.SelectedItem != null)) retval = ((Table)newBox.SelectedItem).CreateRef(); } catch (Exception ex) { } return retval; }
public void TestGetIsFixedSizeBasic() { SortedList srt1; //vanila - IsFixedSize should return false and we should be able to add items to the HT srt1 = new SortedList(); Assert.False(srt1.IsFixedSize); for (int i = 0; i < 100; i++) srt1.Add(i, i); Assert.Equal(100, srt1.Count); for (int i = 0; i < srt1.Count; i++) { Assert.True(srt1.ContainsKey(i)); Assert.Equal((int)srt1[i], i); } }
private void updateLevelSide( MamdaOrderBookPriceLevel level, TreeMap bookSide) { MamaPrice price = level.getPrice(); if (bookSide.ContainsKey(price)) { MamdaOrderBookPriceLevel fullBookLevel = bookSide[price] as MamdaOrderBookPriceLevel; /*Iterate over the entries in the update and apply them to the * full book level according to action*/ foreach (MamdaOrderBookEntry deltaEntry in level) { switch (deltaEntry.getAction()) { case MamdaOrderBookEntry.Actions.Add: fullBookLevel.addEntry(deltaEntry); break; case MamdaOrderBookEntry.Actions.Update: fullBookLevel.updateEntry(deltaEntry); break; case MamdaOrderBookEntry.Actions.Delete: fullBookLevel.removeEntry(deltaEntry); break; case MamdaOrderBookEntry.Actions.Unknown: /*Do nothing*/ break; default: /*Do nothing*/ break; } } /*Update the details for the level itself*/ fullBookLevel.setDetails(level); } else { bookSide.Add(price, level); // Add it anyway } }
/// <summary> /// Load piece sets from resource /// </summary> /// <returns></returns> public static SortedList<string, PieceSet> LoadPieceSetFromResource() { SortedList<string, PieceSet> arrRetVal; Assembly asm; string strResName; string strKeyName; string strPieceSetName; string[] arrPart; Stream streamResource; ResourceReader resReader; PieceSet pieceSet; arrRetVal = new SortedList<string,PieceSet>(64); asm = typeof(App).Assembly; strResName = asm.GetName().Name + ".g.resources"; streamResource = asm.GetManifestResourceStream(strResName); try { resReader = new System.Resources.ResourceReader(streamResource); streamResource = null; using (resReader) { foreach (DictionaryEntry dictEntry in resReader.Cast<DictionaryEntry>()) { strKeyName = dictEntry.Key as string; if (strKeyName != null) { strKeyName = strKeyName.ToLower(); if (strKeyName.StartsWith("piecesets/") && strKeyName.EndsWith(".baml")) { arrPart = strKeyName.Split('/'); if (arrPart.Length == 3) { strPieceSetName = arrPart[1]; if (!arrRetVal.ContainsKey(strPieceSetName)) { pieceSet = new PieceSetStandard(strPieceSetName, strPieceSetName); arrRetVal.Add(strPieceSetName, pieceSet); } } } } } } } finally { if (streamResource != null) { streamResource.Dispose(); } } return(arrRetVal); }
/// <summary> /// For each entry in the input SortedList (where the keys in the /// list entries are strings, the file paths) add all parent /// directories into the list. So given a list with an entry /// with key "a/b/c", put "a/b" and "a" in the list. /// </summary> /// <remarks>The new entries are string dir name with value null. /// </remarks> /// <param name="list">The SortedList of DictionaryEntry's, with /// string file path keys.</param> /// <returns>true</returns> public static bool AddParents(SortedList list) { ArrayList parents = new ArrayList(); foreach(DictionaryEntry entry in list) { string dir = Path.GetDirectoryName((string)entry.Key); while ((dir != null) && (dir.Length > 1)) { parents.Add(dir); dir = Path.GetDirectoryName(dir); } } foreach(string p in parents) { if (!list.ContainsKey(p)) list.Add(p, null); } return(true); }
private static void GetData(DataSet ds1, SortedList<string, HashSet<string>> nameCodes, List<string> names) { string ckey = ""; foreach (DataRow row in ds1.Tables[0].Rows) { if(row["FF1"]==System.DBNull.Value) { //Console.WriteLine("NA"); } else { string svalue = row["FF1"].ToString(); if (svalue.Contains("计算")) { continue; } if (svalue.Contains("号段")) { continue; } if (!svalue.Trim().StartsWith("1")) { if (!nameCodes.ContainsKey(svalue)) nameCodes.Add(svalue, new HashSet<string>()); names.Add(svalue); ckey = svalue; } else { nameCodes[ckey].Add(svalue); } } } }
protected void CollectParameterNames() { _ParametersSortedByName = new System.Collections.SortedList(); int nameposition = 0; for (int i = 0; i < InnerList.Count; i++) { if (null == this[i].FitFunction) { continue; } IFitFunction func = this[i].FitFunction; FitElement ele = this[i]; for (int k = 0; k < func.NumberOfParameters; k++) { if (!(_ParametersSortedByName.ContainsKey(ele.ParameterName(k)))) { _ParametersSortedByName.Add(ele.ParameterName(k), nameposition++); } } } // now sort the items in the order of the namepositions System.Collections.SortedList sortedbypos = new System.Collections.SortedList(); foreach (DictionaryEntry en in _ParametersSortedByName) { sortedbypos.Add(en.Value, en.Key); } _parameterNames = new string[sortedbypos.Count]; for (int i = 0; i < _parameterNames.Length; i++) { _parameterNames[i] = (string)sortedbypos[i]; } }
public static SortedList<DateTime, double> FillWithPrev(SortedList<DateTime, double> raw, DateTime start, DateTime end, double initValue) { SortedList<DateTime, double> filledList = new SortedList<DateTime, double>(); DateTime cur = start; double curValue = initValue; while (true) { if (cur > end) { break; } if (raw.ContainsKey(cur)) { curValue = raw[cur]; } filledList.Add(cur, curValue); cur = cur.AddDays(1); } return filledList; }
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:visits"; query.Dimensions = "ga:visitorType,ga:date"; query.Sort = "ga:date"; 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 nvsr = new System.Data.DataTable("New vs Returning"); nvsr.Columns.Add("visitorType", typeof(string)); nvsr.Columns.Add("Visits", typeof(int)); System.Collections.SortedList visitors = new System.Collections.SortedList(); System.Data.DataTable nandr = new System.Data.DataTable("New and Returning"); nandr.Columns.Add("Date"); nandr.Columns.Add("New Visitor", typeof(int)); nandr.Columns.Add("Returning Visitor", typeof(int)); System.Collections.SortedList newvisitors = new System.Collections.SortedList(); System.Collections.SortedList returningvisitors = new System.Collections.SortedList(); foreach (DataEntry entry in actual.Entries) { try { int visits = int.Parse(entry.Metrics[0].Value); string visitorType = entry.Dimensions[0].Value.ToString(); DateTime datetime = new DateTime(int.Parse(entry.Dimensions[1].Value.Substring(0, 4)), int.Parse(entry.Dimensions[1].Value.Substring(4, 2)), int.Parse(entry.Dimensions[1].Value.Substring(6, 2))); string date = datetime.ToString("yyyy-MM-dd"); //dt.Rows.Add(new object[] { visitorType,visits }); if (visitorType.StartsWith("New")) { if (newvisitors.ContainsKey(date)) { int current = int.Parse(newvisitors[date].ToString()); current += visits; newvisitors[date] = current; } else { newvisitors.Add(date, visits); } } else { if (returningvisitors.ContainsKey(date)) { int current = int.Parse(returningvisitors[date].ToString()); current += visits; returningvisitors[date] = current; } else { returningvisitors.Add(date, visits); } } if (visitors.ContainsKey(visitorType)) { int current = int.Parse(visitors[visitorType].ToString()); current += visits; visitors[visitorType] = current; } else { visitors.Add(visitorType, visits); } } catch (Exception ex) { Response.Write(ex.ToString()); } } foreach (String key in visitors.Keys) { nvsr.Rows.Add(new object[] { key, int.Parse(visitors[key].ToString()) }); } ArrayList keys = new ArrayList(); keys.AddRange(newvisitors.Keys); keys.AddRange(returningvisitors.Keys); foreach (object key in keys) { int _newvisitors = 0; int _returningvisitors = 0; if (newvisitors.ContainsKey(key)) { _newvisitors = int.Parse(newvisitors[key].ToString()); } if (returningvisitors.ContainsKey(key)) { _returningvisitors = int.Parse(returningvisitors[key].ToString()); } nandr.Rows.Add(new object[] { key, _newvisitors, _returningvisitors }); } this.pie_newvsreturning.GviEnableEvents = true; this.pie_newvsreturning.ChartData(nvsr); this.area_newvsreturning.GviEnableEvents = true; this.area_newvsreturning.ChartData(nandr); }
/// <summary> /// Получить бизнессерве /// </summary> /// <param name="dataObjectType">для объекта типа</param> /// <param name="dsevent">событие</param> /// <returns></returns> static public BusinessServer[] GetBusinessServer(System.Type dataObjectType, DataServiceObjectEvents dsevent, IDataService ds) { //2011-08-04 Братчиков: кешируем с учётом разных строк соединения. Это нужно для того чтобы не переписывать чужому бизнес-серверу датасервис string key = dataObjectType.FullName + "." + dsevent + "." + (ds != null? (ds.CustomizationString ?? "salt"):"tlas").GetHashCode(); lock (cache) { if (cache.ContainsKey(key)) { BusinessServer[] ret_bs = (BusinessServer[])cache[key]; foreach (BusinessServer bsi in ret_bs) { bsi.DataService = ds; } return(ret_bs); } ArrayList bss = new ArrayList(); bool needSort = false; while (dataObjectType != typeof(DataObject) && dataObjectType != typeof(object)) { // TODO: разобраться с логикой выполнения и привести в соответствие со статьёй http://storm:3013/Otrabotka-polzovatelskih-operacii-v-processe-raboty-servisa-dannyh-integraciya-s-biznes-serverom.ashx. //получим сначала бизнес-сервера у самого класса (не может быть больше одного) ArrayList atrs = new ArrayList(dataObjectType.GetCustomAttributes(typeof(BusinessServerAttribute), false)); //добавим бизнес-сервера, которые достались от интерфейсов Type[] interfaces = dataObjectType.GetInterfaces(); List <Type> baseInterfaces = new List <Type>(); if (dataObjectType.BaseType != null) { baseInterfaces.AddRange(dataObjectType.BaseType.GetInterfaces()); } foreach (Type interf in interfaces) { if (!baseInterfaces.Contains(interf)) { atrs.AddRange(interf.GetCustomAttributes(typeof(BusinessServerAttribute), false)); } } //создадим инстанции бизнес-серверов и добавим в итоговый массив foreach (BusinessServerAttribute atr in atrs) { if ((dsevent & atr.ServerEvents) == dsevent) { BusinessServer bs = (BusinessServer)Activator.CreateInstance(atr.BusinessServerType); bs.DataService = ds; bs.SetType(dataObjectType); bss.Insert(0, bs); if (atr.Order != 0) { bs.Order = atr.Order; needSort = true; } } } dataObjectType = dataObjectType.BaseType; } //пересортируем бизнессерверы if (needSort) { //Получим отсортированный список, в котором будет упорядоченная коллекция с допустимыми одинаковыми ключами //bss.Sort(new BusinesServerComparer()); ArrayList sortedArList = new ArrayList(); SortedList sl = new SortedList(); foreach (BusinessServer bs in bss) { if (!sl.ContainsKey(bs.Order)) { sl.Add(bs.Order, new ArrayList()); } ((ArrayList)sl[bs.Order]).Add(bs); } foreach (DictionaryEntry entry in sl) { ArrayList arl = (ArrayList)entry.Value; sortedArList.AddRange(arl); } bss = sortedArList; } BusinessServer[] res = (BusinessServer[])bss.ToArray(typeof(BusinessServer)); cache.Add(key, res); return(res); } }
private SortedList BuildSCCVertexMap( VertexIntDictionary vSccMap ) { // Construct a map of SCC ID as key & IVertexCollection of vertices contained within the SCC as value SortedList h = new SortedList(); VertexCollection vertices = null; foreach( DictionaryEntry de in vSccMap ) { IVertex v = (IVertex) de.Key; int scc_id = (int) de.Value; if( h.ContainsKey(scc_id) ) ((VertexCollection) h[scc_id]).Add(v); else { vertices = new VertexCollection(); vertices.Add(v); h.Add(scc_id, vertices); } } return h; }
/// <summary> /// Re-order the settings items. The reason why this processing is /// necessary is that two settings items may have same order. /// </summary> /// <returns> /// A sorted list. /// </returns> protected virtual SortedList ProcessDataSource() { // Jes1111 -- force the list to obey SettingItem.Order property and divide it into groups // Manu -- a better order system avoiding try and catch. // Now settings with no order have a progressive order number // based on their position on list var settingsOrder = new SortedList(); foreach (var key in this.settings.GetKeyList().Cast<string>().Where(key => this.settings[key] != null)) { //if (!(this.settings[key] is SettingItem<string, TextBox>)) //{ // // TODO: FIX THIS // // ErrorHandler.Publish(Appleseed.Framework.LogLevel.Debug, "Unexpected '" + Settings[key].GetType().FullName + "' in settings table."); //} //else //{ var order = ((ISettingItem)this.settings[key]).Order; while (settingsOrder.ContainsKey(order)) { // be sure do not have duplicate order key or // we get an error order++; } settingsOrder.Add(order, key); //} } return settingsOrder; }
/// <summary> /// Обновить хранилище по объектам (есть параметр, указывающий, всегда ли необходимо взводить ошибку /// и откатывать транзакцию при неудачном запросе в базу данных). Если /// он true, всегда взводится ошибка. Иначе, выполнение продолжается. /// Однако, при этом есть опасность преждевременного окончания транзакции, с переходом для остальных /// запросов режима транзакционности в autocommit. Проявлением проблемы являются ошибки навроде: /// The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION /// </summary> /// <param name="objects">Объекты для обновления.</param> /// <param name="DataObjectCache">Кэш объектов данных.</param> /// <param name="AlwaysThrowException">Если произошла ошибка в базе данных, не пытаться выполнять других запросов, сразу взводить ошибку и откатывать транзакцию.</param> public virtual void UpdateObjects(ref DataObject[] objects, DataObjectCache DataObjectCache, bool AlwaysThrowException) { object id = BusinessTaskMonitor.BeginTask("Update objects"); if (!DoNotChangeCustomizationString && ChangeCustomizationString != null) { var tps = new List <Type>(); foreach (DataObject d in objects) { Type t = d.GetType(); if (!tps.Contains(t)) { tps.Add(t); } } string cs = ChangeCustomizationString(tps.ToArray()); customizationString = string.IsNullOrEmpty(cs) ? customizationString : cs; } // Перенесли этот метод повыше, потому что строка соединения может быть сменена в бизнес-сервере делегатом смены строки соединения (если что-нибудь почитают). IDbConnection conection = GetConnection(); var DeleteQueries = new StringCollection(); var UpdateQueries = new StringCollection(); var UpdateFirstQueries = new StringCollection(); var InsertQueries = new StringCollection(); var DeleteTables = new StringCollection(); var UpdateTables = new StringCollection(); var InsertTables = new StringCollection(); var TableOperations = new SortedList(); var QueryOrder = new StringCollection(); var AllQueriedObjects = new ArrayList(); var auditOperationInfoList = new List <AuditAdditionalInfo>(); var extraProcessingList = new List <DataObject>(); GenerateQueriesForUpdateObjects(DeleteQueries, DeleteTables, UpdateQueries, UpdateFirstQueries, UpdateTables, InsertQueries, InsertTables, TableOperations, QueryOrder, true, AllQueriedObjects, DataObjectCache, extraProcessingList, objects); GenerateAuditForAggregators(AllQueriedObjects, DataObjectCache, ref extraProcessingList); OnBeforeUpdateObjects(AllQueriedObjects); Exception ex = null; /*access checks*/ foreach (DataObject dtob in AllQueriedObjects) { Type dobjType = dtob.GetType(); if (!SecurityManager.AccessObjectCheck(dobjType, tTypeAccess.Full, false)) { switch (dtob.GetStatus(false)) { case ObjectStatus.Created: SecurityManager.AccessObjectCheck(dobjType, tTypeAccess.Insert, true); break; case ObjectStatus.Altered: SecurityManager.AccessObjectCheck(dobjType, tTypeAccess.Update, true); break; case ObjectStatus.Deleted: SecurityManager.AccessObjectCheck(dobjType, tTypeAccess.Delete, true); break; } } } /*access checks*/ if (DeleteQueries.Count > 0 || UpdateQueries.Count > 0 || InsertQueries.Count > 0) { // Порядок выполнения запросов: delete,insert,update if (AuditService.IsAuditEnabled) { /* Аудит проводится именно здесь, поскольку на этот момент все бизнес-сервера на объектах уже выполнились, * объекты находятся именно в том состоянии, в каком должны были пойти в базу + в будущем можно транзакцию передать на исполнение */ AuditOperation(extraProcessingList, auditOperationInfoList); // TODO: подумать, как записывать аудит до OnBeforeUpdateObjects, но уже потенциально с транзакцией } conection.Open(); IDbTransaction trans = null; string query = string.Empty; string prevQueries = string.Empty; object subTask = null; try { trans = CreateTransaction(conection); IDbCommand command = conection.CreateCommand(); command.Transaction = trans; #region прошли вглубь обрабатывая only Update||Insert bool go = true; do { string table = QueryOrder[0]; if (!TableOperations.ContainsKey(table)) { TableOperations.Add(table, OperationType.None); } var ops = (OperationType)TableOperations[table]; if ((ops & OperationType.Delete) != OperationType.Delete) { // Смотрим есть ли Инсерты if ((ops & OperationType.Insert) == OperationType.Insert) { if ( (ex = RunCommands(InsertQueries, InsertTables, table, command, id, AlwaysThrowException)) == null) { ops = Minus(ops, OperationType.Insert); TableOperations[table] = ops; } else { go = false; } } // Смотрим есть ли Update if (go && ((ops & OperationType.Update) == OperationType.Update)) { if ((ex = RunCommands(UpdateQueries, UpdateTables, table, command, id, AlwaysThrowException)) == null) { ops = Minus(ops, OperationType.Update); TableOperations[table] = ops; } else { go = false; } } if (go) { QueryOrder.RemoveAt(0); go = QueryOrder.Count > 0; } } else { go = false; } }while (go); #endregion if (QueryOrder.Count > 0) { #region сзади чистые Update go = true; int queryOrderIndex = QueryOrder.Count - 1; do { string table = QueryOrder[queryOrderIndex]; if (TableOperations.ContainsKey(table)) { var ops = (OperationType)TableOperations[table]; if (ops == OperationType.Update) { if ( (ex = RunCommands(UpdateQueries, UpdateTables, table, command, id, AlwaysThrowException)) == null) { ops = Minus(ops, OperationType.Update); TableOperations[table] = ops; } else { go = false; } if (go) { queryOrderIndex--; go = queryOrderIndex >= 0; } } else { go = false; } } else { queryOrderIndex--; } }while (go); #endregion } foreach (string table in QueryOrder) { if ((ex = RunCommands(UpdateFirstQueries, UpdateTables, table, command, id, AlwaysThrowException)) != null) { throw ex; } } // Удаляем в обратном порядке. for (int i = QueryOrder.Count - 1; i >= 0; i--) { string table = QueryOrder[i]; if ((ex = RunCommands(DeleteQueries, DeleteTables, table, command, id, AlwaysThrowException)) != null) { throw ex; } } // А теперь опять с начала foreach (string table in QueryOrder) { if ((ex = RunCommands(InsertQueries, InsertTables, table, command, id, AlwaysThrowException)) != null) { throw ex; } if ((ex = RunCommands(UpdateQueries, UpdateTables, table, command, id, AlwaysThrowException)) != null) { throw ex; } } if (AuditService.IsAuditEnabled && auditOperationInfoList.Count > 0) { // Нужно зафиксировать операции аудита (то есть сообщить, что всё было корректно выполнено и запомнить время) AuditService.RatifyAuditOperationWithAutoFields( tExecutionVariant.Executed, AuditAdditionalInfo.SetNewFieldValuesForList(trans, this, auditOperationInfoList), this, true); } if (trans != null) { trans.Commit(); } } catch (Exception excpt) { if (trans != null) { trans.Rollback(); } if (AuditService.IsAuditEnabled && auditOperationInfoList.Count > 0) { // Нужно зафиксировать операции аудита (то есть сообщить, что всё было откачено) AuditService.RatifyAuditOperationWithAutoFields(tExecutionVariant.Failed, auditOperationInfoList, this, false); } conection.Close(); BusinessTaskMonitor.EndSubTask(subTask); throw new ExecutingQueryException(query, prevQueries, excpt); } conection.Close(); var res = new ArrayList(); foreach (DataObject changedObject in objects) { changedObject.ClearPrototyping(true); if (changedObject.GetStatus(false) != STORMDO.ObjectStatus.Deleted) { Utils.UpdateInternalDataInObjects(changedObject, true, DataObjectCache); res.Add(changedObject); } } foreach (DataObject dobj in AllQueriedObjects) { if (dobj.GetStatus(false) != STORMDO.ObjectStatus.Deleted && dobj.GetStatus(false) != STORMDO.ObjectStatus.UnAltered) { Utils.UpdateInternalDataInObjects(dobj, true, DataObjectCache); } } objects = new DataObject[res.Count]; res.CopyTo(objects); BusinessTaskMonitor.EndTask(id); } if (AfterUpdateObjects != null) { AfterUpdateObjects(this, new DataObjectsEventArgs(objects)); } }
void UpdateSimList(string household) { SimPe.PackedFiles.Wrapper.ExtSDesc selectedSim = this.SelectedSim; if (household != null && selectedSim != null && selectedSim.HouseholdName != household) { selectedSim = null; } gp.BeginUpdate(); gp.Clear(); lastsel = null; Hashtable ht = FileTable.ProviderRegistry.SimDescriptionProvider.SimInstance; Wait.SubStart(ht.Count); int ct = 0; System.Collections.SortedList map = new System.Collections.SortedList(); foreach (SimPe.PackedFiles.Wrapper.ExtSDesc sdsc in ht.Values) { if (household != null) { if (household != sdsc.HouseholdName) { continue; } } string name = sdsc.SimName + " " + sdsc.SimFamilyName; System.Drawing.Image simimg = gp.GetSimIcon(sdsc, GetBackgroundColor(sdsc)); AddSimToPoolEventArgs ret = DoAddSimToPool(sdsc, name, household, simimg); if (!ret.Cancel) { SteepValley.Windows.Forms.XPListViewItem eip = gp.Add(sdsc, simimg); eip.Tag = sdsc; eip.GroupIndex = ret.GroupIndex; if (map.ContainsKey(name)) { name += " (" + sdsc.FileDescriptor.Instance.ToString() + ")"; } map[name] = eip; Wait.Message = eip.Text; } Wait.Progress = ct++; } SetViewMode(); if (gp.Items.Count > 0) { if (selectedSim != null) { SelectedSim = selectedSim; } else { gp.Items[0].Selected = true; } try { if (SelectedSimChanged != null) { SelectedSimChanged(this, ((SimPe.PackedFiles.Wrapper.ExtSDesc)gp.Items[0].Tag).Image, (Wrapper.SDesc)((SimPe.PackedFiles.Wrapper.ExtSDesc)gp.Items[0].Tag)); } } catch (Exception ex) { Console.WriteLine(ex); } } gp.EndUpdate(); Wait.SubStop(); }
private string CreaCodigoCompleto() { System.Collections.SortedList ColRelaciones = new System.Collections.SortedList(); foreach (System.Data.DataTable tabla in this.DS.Tables) { if (tabla != this.DS.Tables[0]) { ColRelaciones.Add(tabla.Columns[0].ColumnName, tabla.Columns[1].ColumnName); } } string codigo = @" using System; using System.Data; using System.ComponentModel; using System.Reflection; namespace miNamespace { [TypeConverter(typeof(PropertySorter))] public class miClase { private System.Data.DataRow m_Row = null; "; foreach (System.Data.DataTable tabla in this.DS.Tables) { if (tabla != this.DS.Tables[0]) { codigo += "public System.Collections.Hashtable Col" + tabla.Columns[0].ColumnName + " = new System.Collections.Hashtable();\n"; codigo += "public System.Collections.Hashtable _Col" + tabla.Columns[0].ColumnName + " = new System.Collections.Hashtable();\n"; } } codigo += @"public miClase(System.Data.DataRow row) { m_Row = row; "; foreach (System.Data.DataTable tabla in this.DS.Tables) { if (tabla != this.DS.Tables[0]) { codigo += "foreach(System.Data.DataRow fila in row.Table.DataSet.Tables[\"" + tabla.TableName + "\"].Rows)"; codigo += @"{ "; codigo += "Col" + tabla.Columns[0].ColumnName + ".Add(Col" + tabla.Columns[0].ColumnName + ".Count,fila[0]);\n"; codigo += "_Col" + tabla.Columns[0].ColumnName + ".Add(fila[0],_Col" + tabla.Columns[0].ColumnName + ".Count);\n"; codigo += @"} "; } } codigo += "\n"; foreach (System.Data.DataColumn col in this.Tabla.Columns) { if (this.ColCampos.ContainsKey(col.ColumnName)) { if (ColRelaciones.ContainsKey(col.ColumnName)) { codigo += "\t\tif(row[\"" + col.ColumnName + "\"] != DBNull.Value)\n"; codigo += "\t\t{\n"; codigo += "\t\tif(_Col" + col.ColumnName + "[row[\"" + col.ColumnName + "\"]] != null)\n"; codigo += "\t\t{\n"; codigo += "\t\t\tthis." + this.ColNombreCampos[col.ColumnName].ToString() + " = (" + col.ColumnName + "_Enum)_Col" + col.ColumnName + "[row[\"" + col.ColumnName + "\"]];\n"; codigo += "\t\t}\n"; codigo += "\t\t}\n"; } else { codigo += "\t\tif(row[\"" + col.ColumnName + "\"] != DBNull.Value)\n"; codigo += "\t\t{\n"; codigo += "\t\t\tthis." + this.ColNombreCampos[col.ColumnName].ToString() + " = (" + col.DataType.UnderlyingSystemType.ToString() + ")row[\"" + col.ColumnName + "\"];\n"; codigo += "\t\t}\n"; } } } codigo += "}\n"; foreach (System.Data.DataColumn col in this.Tabla.Columns) { if (this.ColCampos.ContainsKey(col.ColumnName)) { if (ColRelaciones.ContainsKey(col.ColumnName)) { string campo = col.ColumnName + "_Enum m_" + ColNombreCampos[col.ColumnName].ToString(); string propiedad = col.ColumnName + "_Enum " + ColNombreCampos[col.ColumnName].ToString(); codigo += "private " + campo + ";\n"; codigo += "[Category(\"" + ColCategorias[col.ColumnName].ToString() + "\"),Description(\"" + ColDescripciones[col.ColumnName].ToString() + "\"),PropertyOrder(" + ColOrden[col.ColumnName].ToString() + "),ReadOnly(" + ColReadOnly[col.ColumnName].ToString().ToLower() + ")]\n"; codigo += "public " + propiedad + @" { get { return m_" + ColNombreCampos[col.ColumnName].ToString() + @"; } set { m_" + ColNombreCampos[col.ColumnName].ToString() + @" = (" + col.ColumnName + "_Enum)value;"; codigo += "m_Row[\"" + col.ColumnName + "\"] = Col" + col.ColumnName + "[(int)value];"; codigo += @" } } " ; } else { string campo = col.DataType.UnderlyingSystemType.ToString() + " m_" + ColNombreCampos[col.ColumnName].ToString(); string propiedad = col.DataType.UnderlyingSystemType.ToString() + " " + ColNombreCampos[col.ColumnName].ToString(); codigo += "private " + campo + ";\n"; codigo += "[Category(\"" + ColCategorias[col.ColumnName].ToString() + "\"),Description(\"" + ColDescripciones[col.ColumnName].ToString() + "\"),PropertyOrder(" + ColOrden[col.ColumnName].ToString() + "),ReadOnly(" + ColReadOnly[col.ColumnName].ToString().ToLower() + ")]\n"; codigo += @" public " + propiedad + @" { get { return m_" + ColNombreCampos[col.ColumnName].ToString() + @"; } set { m_" + ColNombreCampos[col.ColumnName].ToString() + @" = value;"; codigo += "m_Row[\"" + col.ColumnName + "\"] = value;"; codigo += @" } } " ; } } } foreach (System.Data.DataTable tabla in this.DS.Tables) { if (tabla != this.DS.Tables[0]) { codigo += @" public enum " ; codigo += tabla.Columns[0].ColumnName + @"_Enum {" ; int i = 0; foreach (System.Data.DataRow fila in tabla.Rows) { codigo += ObtieneEnumeracion(fila[1].ToString()) + " = " + i + ",\n"; i++; } codigo += "}"; } } codigo += "}}"; return(codigo); }
/// <summary> /// Gets the namespaces from assembly. /// </summary> /// <param name="rep">ReflectionEngine Parameters.</param> /// <param name="assemblyFile">Assembly file name.</param> /// <returns></returns> public SortedList GetNamespacesFromAssembly(ReflectionEngineParameters rep, string assemblyFile) { this.rep = rep; assemblyLoader = SetupAssemblyLoader(); try { Assembly a = assemblyLoader.LoadAssembly(assemblyFile); SortedList namespaces = new SortedList(); foreach (Type t in a.GetTypes()) { string ns = t.Namespace; { if (ns == null) { if ((!namespaces.ContainsKey("(global)"))) namespaces.Add("(global)", null); } else { if ((!namespaces.ContainsKey(ns))) namespaces.Add(ns, null); } } } return namespaces; } catch (ReflectionTypeLoadException rtle) { StringBuilder sb = new StringBuilder(); if (assemblyLoader.UnresolvedAssemblies.Count > 0) { sb.Append("One or more required assemblies could not be located : \n"); foreach (string ass in assemblyLoader.UnresolvedAssemblies) { sb.AppendFormat(" {0}\n", ass); } sb.Append("\nThe following directories were searched, \n"); foreach (string dir in assemblyLoader.SearchedDirectories) { sb.AppendFormat(" {0}\n", dir); } } else { Hashtable fileLoadExceptions = new Hashtable(); foreach (Exception loaderEx in rtle.LoaderExceptions) { System.IO.FileLoadException fileLoadEx = loaderEx as System.IO.FileLoadException; if (fileLoadEx != null) { if (!fileLoadExceptions.ContainsKey(fileLoadEx.FileName)) { fileLoadExceptions.Add(fileLoadEx.FileName, null); sb.Append("Unable to load: " + fileLoadEx.FileName + "\r\n"); } } sb.Append(loaderEx.Message + Environment.NewLine); sb.Append(loaderEx.StackTrace + Environment.NewLine); sb.Append("--------------------" + Environment.NewLine + Environment.NewLine); } } throw new DocumenterException(sb.ToString()); } finally { assemblyLoader.Deinstall(); } }
protected void CollectParameterNames() { _ParametersSortedByName = new System.Collections.SortedList(); int nameposition = 0; for(int i=0;i<InnerList.Count;i++) { if(null==this[i].FitFunction) continue; IFitFunction func = this[i].FitFunction; FitElement ele = this[i]; for(int k=0;k<func.NumberOfParameters;k++) { if(!(_ParametersSortedByName.ContainsKey(ele.ParameterName(k)))) { _ParametersSortedByName.Add(ele.ParameterName(k),nameposition++); } } } // now sort the items in the order of the namepositions System.Collections.SortedList sortedbypos = new System.Collections.SortedList(); foreach(DictionaryEntry en in _ParametersSortedByName) sortedbypos.Add(en.Value,en.Key); _parameterNames = new string[sortedbypos.Count]; for(int i=0;i<_parameterNames.Length;i++) _parameterNames[i] = (string)sortedbypos[i]; }
// *** Start programmer edit section *** (ПроверкаНаличияТоваров CustomMembers) // *** End programmer edit section *** (ПроверкаНаличияТоваров CustomMembers) // *** Start programmer edit section *** (OnUpdateЗаказ CustomAttributes) // *** End programmer edit section *** (OnUpdateЗаказ CustomAttributes) public virtual ICSSoft.STORMNET.DataObject[] OnUpdateЗаказ(АСУ_Склад.Заказ UpdatedObject) { // *** Start programmer edit section *** (OnUpdateЗаказ) // Определим массив, который будем возвращать для обновления. DataObject[] ret = new DataObject[0]; // Проверим на то, что пришедший объект - это именно то, что нам нужно (создан или изменён и статус установлен в Оплачено). if ((UpdatedObject.GetStatus() == ICSSoft.STORMNET.ObjectStatus.Created || UpdatedObject.GetStatus() == ICSSoft.STORMNET.ObjectStatus.Altered) && Array.IndexOf(UpdatedObject.GetAlteredPropertyNames(), "Статус") >= 0 && UpdatedObject.Статус == Состояние_Заказа.Оплаченный) { // Построим ограничение и вычитаем все объекты ТоварНаСкладе, которые нам подходят. Заказ заказ = UpdatedObject; SQLWhereLanguageDef langdef = SQLWhereLanguageDef.LanguageDef; ICSSoft.STORMNET.FunctionalLanguage.Function lf = null; for (int i = 0; i < заказ.Строка_Заказа.Count; i++) { if (lf != null) { if (заказ.Строка_Заказа[i].Товар != null) { lf = langdef.GetFunction(langdef.funcOR, lf, langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, "Товар"), заказ.Строка_Заказа[i].Товар.__PrimaryKey)); } } else { if (заказ.Строка_Заказа[i].Товар != null) { lf = langdef.GetFunction(langdef.funcEQ, new VariableDef(langdef.GuidType, "Товар"), заказ.Строка_Заказа[i].Товар.__PrimaryKey); } } } ICSSoft.STORMNET.Business.LoadingCustomizationStruct lcs = ICSSoft.STORMNET.Business.LoadingCustomizationStruct.GetSimpleStruct(typeof(Товар_на_Складе), "ТоварНаСкладеE"); lcs.LimitFunction = lf; ICSSoft.STORMNET.DataObject[] objs = ICSSoft.STORMNET.Business.DataServiceProvider.DataService.LoadObjects(lcs); // Разместим вычитанные объекты в отсортированном списке для удобного доступа в дальнейшем. System.Collections.SortedList sl = new System.Collections.SortedList(); //for (int i = 0; i < objs.Length; i++) //{ // if (sl.ContainsKey(((Товар_на_Складе)objs[i]).Товар.__PrimaryKey)) // { // ((System.Collections.ArrayList)sl[objs[i].__PrimaryKey]).Add(objs[i]); // } // else // { // System.Collections.ArrayList списокТоваров = new System.Collections.ArrayList(); // списокТоваров.Add(objs[i]); // sl.Add(((Товар_на_Складе)objs[i]).Товар.__PrimaryKey, списокТоваров); // } //} // Определим строчку для сообщения об ошибке. string errStr = string.Empty; ArrayList retObjs = new ArrayList(); // Проверим наличие товара на складах, если не хватает, то выдадим сообщение об ошибке, если хватает, то вычитаем количество. for (int i = 0; i < заказ.Строка_Заказа.Count; i++) { if (sl.ContainsKey(заказ.Строка_Заказа[i].Товар.__PrimaryKey)) { ArrayList arl = ((System.Collections.ArrayList)sl[заказ.Строка_Заказа[i].Товар.__PrimaryKey]); int количествоНаСкладах = 0; for (int j = 0; j < arl.Count; j++) { количествоНаСкладах += ((Товар_на_Складе)arl[j]).Количество; } if (количествоНаСкладах < заказ.Строка_Заказа[i].Количество) { errStr += " Не хватает товара \"" + заказ.Строка_Заказа[i].Товар.Название + "\" в наличии: " + количествоНаСкладах + ", требуется " + заказ.Строка_Заказа[i].Количество + Environment.NewLine; } else { int колич = заказ.Строка_Заказа[i].Количество; for (int j = 0; j < arl.Count; j++) { if (колич > 0 && ((Товар_на_Складе)arl[j]).Количество > колич) { ((Товар_на_Складе)arl[j]).Количество -= колич; колич = 0; retObjs.Add(arl[j]); } else { if (колич > 0) { колич -= ((Товар_на_Складе)arl[j]).Количество; ((Товар_на_Складе)arl[j]).Количество = 0; retObjs.Add(arl[j]); } } } } } else { errStr += "Товар \""+ заказ.Строка_Заказа[i].Товар.Название + "\" в наличии отсутствует." + Environment.NewLine; } } // В случае, если чего-то не хватило, сообщаем об этом пользователю. if (errStr != string.Empty) { throw new Exception(errStr); } // Если всё нормально, то возвращаем массив объектов, которые надо обновить. ret = new DataObject[retObjs.Count]; retObjs.CopyTo(ret, 0); } return(ret); // *** End programmer edit section *** (OnUpdateЗаказ) }
// The following procedure works with the USB device driver; upon finding all instances of USB devices // that match the requested Guid, the procedure checks the corresponding registry keys to find the unique // serial number to show to the user; the serial number is decided by the device driver at installation // time and stored in a registry key whose name is the hash of the laser etched security key of the device private static void EnumeratePorts(Guid guid, SortedList lst) { //string devicePath = null; //(new DeviceManagement()).FindDeviceFromGuid(guid, ref devicePath); //using (WinUsb_AsyncUsbStream s = new WinUsb_AsyncUsbStream(devicePath)) //{ // //const ushort SERIAL_NUMBER_INDEX = 0; // //const ushort MANUFACTURER_NAME_INDEX = 1; // //const ushort PRODUCT_NAME_INDEX = 2; // //const ushort USB_DISPLAY_STRING_INDEX = 4; // //const ushort USB_FRIENDLY_STRING_INDEX = 5; // string displayName = s.RetrieveStringFromDevice(USB_DISPLAY_STRING_INDEX); // string hash = s.RetrieveStringFromDevice(USB_FRIENDLY_STRING_INDEX); // //string operationalPort = s.RetrieveStringFromDevice(IOCTL_WINUSB_PORT_NAME, dmp); // //if ((operationalPort == null) || (displayName == null) || (hash == null)) // if ((displayName == null) || (hash == null)) // { // return; // } // // convert kernel format to user mode format // // kernel : @"\??\USB#Vid_beef&Pid_0009#5&4162af8&0&1#{09343630-a794-10ef-334f-82ea332c49f3}" // // user : @"\\?\usb#vid_beef&pid_0009#5&4162af8&0&1#{09343630-a794-10ef-334f-82ea332c49f3}" // //StringBuilder operationalPortUser = new StringBuilder(); // //operationalPortUser.Append(@"\\?"); // //operationalPortUser.Append(operationalPort.Substring(3)); // // change the display name if there is a collision (otherwise you will only be able to use one of the devices) // displayName += "_" + hash; // if (lst.ContainsKey(displayName)) // { // int i = 2; // while (lst.ContainsKey(displayName + " (" + i + ")")) // { // i++; // } // displayName += " (" + i + ")"; // } // //PortDefinition pd = PortDefinition.CreateInstanceForUsb(displayName, operationalPortUser.ToString()); // PortDefinition pd = PortDefinition.CreateInstanceForWinUsb(displayName, devicePath); // //if (dmp != null) dmp.Dump("[16 == EnumeratePorts]"); // //RetrieveProperties(hash, ref pd, s); // if (!pd.Properties.Contains(DeviceHash)) pd.Properties.Add(DeviceHash, hash); // lst.Add(pd.DisplayName, pd); //} IntPtr devInfo = Native.SetupDiGetClassDevs(ref guid, null, 0, Native.DIGCF_DEVICEINTERFACE | Native.DIGCF_PRESENT); if(devInfo == Native.INVALID_HANDLE_VALUE) { return; } try { Native.SP_DEVICE_INTERFACE_DATA interfaceData = new Native.SP_DEVICE_INTERFACE_DATA(); interfaceData.cbSize = Marshal.SizeOf(interfaceData); int index = 0; while(Native.SetupDiEnumDeviceInterfaces(devInfo, 0, ref guid, index++, ref interfaceData)) { try { Native.SP_DEVICE_INTERFACE_DETAIL_DATA detail = new Native.SP_DEVICE_INTERFACE_DETAIL_DATA(); // explicit size of unmanaged structure must be provided, because it does not include transfer buffer // for whatever reason on 64 bit machines the detail size is 8 rather than 5, likewise the interfaceData.cbSize // is 32 rather than 28 for non 64bit machines, therefore, we make the detemination of the size based // on the interfaceData.cbSize (kind of hacky but it works). if(interfaceData.cbSize == 32) { detail.cbSize = 8; } else { detail.cbSize = 5; } if(Native.SetupDiGetDeviceInterfaceDetail(devInfo, ref interfaceData, ref detail, Marshal.SizeOf(detail) * 2, 0, 0)) { string port = detail.DevicePath.ToLower(); using(WinUsb_AsyncUsbStream s = new WinUsb_AsyncUsbStream(port)) { //const ushort SERIAL_NUMBER_INDEX = 0; //const ushort MANUFACTURER_NAME_INDEX = 1; //const ushort PRODUCT_NAME_INDEX = 2; //const ushort USB_DISPLAY_STRING_INDEX = 4; //const ushort USB_FRIENDLY_STRING_INDEX = 5; string displayName = s.RetrieveStringFromDevice(USB_DISPLAY_STRING_INDEX); string hash = s.RetrieveStringFromDevice(USB_FRIENDLY_STRING_INDEX); //string operationalPort = s.RetrieveStringFromDevice(IOCTL_WINUSB_PORT_NAME, dmp); //if ((operationalPort == null) || (displayName == null) || (hash == null)) if((displayName == null) || (hash == null)) { return; } // change the display name if there is a collision (otherwise you will only be able to use one of the devices) displayName += "_" + hash; if(lst.ContainsKey(displayName)) { int i = 2; while(lst.ContainsKey(displayName + " (" + i + ")")) { i++; } displayName += " (" + i + ")"; } PortDefinition pd = PortDefinition.CreateInstanceForWinUsb(displayName, port); if(!pd.Properties.Contains(DeviceHash)) pd.Properties.Add(DeviceHash, hash); lst.Add(pd.DisplayName, pd); } } } catch { // go to next device } } } finally { Native.SetupDiDestroyDeviceInfoList(devInfo); } }
public override bool ContainsKey(Object key) { lock (_root) { return(_list.ContainsKey(key)); } }
protected void ddlTime_SelectedIndexChanged(object sender, EventArgs e) { DropDownList ddlTime =(DropDownList)sender; Label labArrivalDate = (Label)(ddlTime.Parent.FindControl("labArrivalDate")); Label labRouteNo = (Label)(ddlTime.Parent.FindControl("labRouteNo")); int rowIdx = Convert.ToInt32(labRouteNo.Text) - 1; ListView lvVehicle = (ListView)(this.lvTravelMethod.Items[rowIdx].FindControl("lvVehicle")); UpdatePanel upnlVehicle = (UpdatePanel)(this.lvTravelMethod.Items[rowIdx].FindControl("upnlVehicle")); if (ddlTime.SelectedIndex > 0) { int scheduleId = Convert.ToInt32(ddlTime.SelectedValue); Schedule schedule = new Schedule().GetById(scheduleId, false); labArrivalDate.Text = "Arrival date:" + schedule.ArrivalTime.Value.ToString("ddd dd MMMM yyyy, HH:mm"); lvVehicle.Enabled = true; SortedList<string,string> types = new SortedList<string,string>(); types.Add("", "--select--"); foreach (FareItem fi in schedule.Fare.FareItems) { if (fi.FareType is VehicleType && ((VehicleType)fi.FareType).MinLegth.HasValue && ((VehicleType)fi.FareType).MinLegth.Value>0) if (!types.ContainsKey(fi.FareType.FareTypeName)) types.Add(fi.FareType.FareTypeName, fi.FareType.FareTypeName); } foreach (ListViewDataItem item in lvVehicle.Items) { DropDownList ddlType = (DropDownList)(item.FindControl("ddlType")); ddlType.DataSource = types; ddlType.DataValueField = "Key"; ddlType.DataTextField = "Value"; ddlType.DataBind(); } } else { labArrivalDate.Text = ""; foreach (ListViewDataItem item in lvVehicle.Items) { DropDownList ddlType = (DropDownList)(item.FindControl("ddlType")); ddlType.SelectedIndex = 0; DropDownList ddlHeight = (DropDownList)(item.FindControl("ddlHeight")); ddlHeight.SelectedIndex = 0; DropDownList ddlWidth = (DropDownList)(item.FindControl("ddlWidth")); ddlWidth.SelectedIndex = 0; TextBox txtLength = (TextBox)(item.FindControl("txtLength")); txtLength.Text = ""; } lvVehicle.Enabled = false; } upnlVehicle.Update(); }
private void notifyIcon_MouseClick(object sender, MouseEventArgs e) { TricksterTools.Library.Win32API.SetForegroundWindow(new System.Runtime.InteropServices.HandleRef(this, this.Handle)); Point mp = Control.MousePosition; /** ハッシュテーブルからIDを読み込む **/ // 保存元のファイル名 //string fileName = "config.txt"; //System.Collections.Hashtable accounts = Program.loadConfig(fileName); System.Collections.SortedList links = SettingController.Links; if (e.Button == MouseButtons.Left) { #region 左クリック時 this.contextMenuStrip_Left.Items.Clear(); if (AccountController.AccountData.Count == 0) { this.contextMenuStrip_Left.Items.Add("No Registered ID"); this.contextMenuStrip_Left.Enabled = false; } else { this.contextMenuStrip_Left.Enabled = true; IEnumerator ienum = AccountController.AccountData.GetEnumerator(); while (ienum.MoveNext()) { Accounts.AccountProperties acprop = (Accounts.AccountProperties)ienum.Current; string ID = acprop.ID; string Password = acprop.Password; ToolStripMenuItem items = new ToolStripMenuItem(); items.Text = ID; if (acprop.Site == Accounts.AccountProperties.LoginSite.Official) { items.Image = (Image)Properties.Resources.official.ToBitmap(); } else if (acprop.Site == Accounts.AccountProperties.LoginSite.HanGame) { items.Image = (Image)Properties.Resources.hangame.ToBitmap(); } else if (acprop.Site == Accounts.AccountProperties.LoginSite.AtGames) { items.Image = (Image)Properties.Resources.atgames.ToBitmap(); } else if (acprop.Site == Accounts.AccountProperties.LoginSite.Gamers1) { //items.Image = (Image)Properties.Resources.lievo.ToBitmap(); items.Image = (Image)Properties.Resources.gamers1.ToBitmap(); } else { items.Image = (Image)Properties.Resources.official.ToBitmap(); } items.Click += delegate { if (!Common.isInstalled()) // クライアントがインストールされているか { MessageBox.Show("トリックスター クライアントがインストールされていません。" + Environment.NewLine + "クライアントプログラムをインストールして再度実行してください。", "TSLoginManager", MessageBoxButtons.OK, MessageBoxIcon.Warning); //MessageBox.Show("TRICKSTER client program is not installed in this computer." + Environment.NewLine + // "Please try to install and run.", "TSLoginManager"); } else { SimpleLogger.Write("auto login start..."); //LoginController.startGame(ID, Password); if (acprop.Site == Accounts.AccountProperties.LoginSite.Official) { SimpleLogger.WriteLine("Official"); OfficialLoginController.setPluginHost(this); OfficialLoginController.startGame(ID, Password); } else if (acprop.Site == Accounts.AccountProperties.LoginSite.HanGame) { SimpleLogger.WriteLine("HanGame"); HanGameLoginController.setPluginHost(this); HanGameLoginController.startGame(ID, Password); } else if (acprop.Site == Accounts.AccountProperties.LoginSite.AtGames) { SimpleLogger.WriteLine("AtGames"); AtGamesLoginController.setPluginHost(this); AtGamesLoginController.startGame(ID, Password); } else if (acprop.Site == Accounts.AccountProperties.LoginSite.Gamers1) { SimpleLogger.WriteLine("Lievo"); //LievoLoginController.setPluginHost(this); //LievoLoginController.startGame(ID, Password); GamersOneLoginController.setPluginHost(this); GamersOneLoginController.startGame(ID, Password); } else { OfficialLoginController.setPluginHost(this); OfficialLoginController.startGame(ID, Password); } } }; this.contextMenuStrip_Left.Items.Add(items); } } //this.notifyIcon.ContextMenuStrip = this.contextMenuStrip_Left; //this.contextMenuStrip_Left.Show(mp.X - contextMenuStrip_Left.Width, mp.Y); this.contextMenuStrip_Left.Show(this, PointToClient(Cursor.Position)); #endregion } else if (e.Button == MouseButtons.Right) { #region 右クリック時 //this.ToolStripMenuItem_Right_Edit.DropDownItems.Clear(); //this.ToolStripMenuItem_Right_Edit.DisplayStyle = ToolStripItemDisplayStyle.Text; this.ToolStripMenuItem_Right_Delete.DropDownItems.Clear(); this.ToolStripMenuItem_Right_Delete.DisplayStyle = ToolStripItemDisplayStyle.Text; this.ToolStripMenuItem_Right_Plugins.DropDownItems.Clear(); this.ToolStripMenuItem_Right_Plugins.DisplayStyle = ToolStripItemDisplayStyle.Text; this.ToolStripMenuItem_Right_Links.DropDownItems.Clear(); this.ToolStripMenuItem_Right_Links.DisplayStyle = ToolStripItemDisplayStyle.Text; this.ToolStripMenuItem_Right_Tool_PluginInfo.DropDownItems.Clear(); this.ToolStripMenuItem_Right_Tool_PluginInfo.DisplayStyle = ToolStripItemDisplayStyle.Text; #region アカウント削除用一覧 if (AccountController.AccountData.Count == 0) { //this.ToolStripMenuItem_Right_Edit.DropDownItems.Add("No Registered ID"); //this.ToolStripMenuItem_Right_Edit.Enabled = false; //this.ToolStripMenuItem_Right_Delete.DropDownItems.Add("No Registered ID"); this.ToolStripMenuItem_Right_Delete.Enabled = false; } else { //this.ToolStripMenuItem_Right_Edit.Enabled = true; //this.ToolStripMenuItem_Right_Edit.DropDown.Enabled = true; this.ToolStripMenuItem_Right_Delete.Enabled = true; this.ToolStripMenuItem_Right_Delete.DropDown.Enabled = true; this.contextMenuStrip_Left.Enabled = true; IEnumerator ienum = AccountController.AccountData.GetEnumerator(); while (ienum.MoveNext()) { //ToolStripMenuItem edit_items = new ToolStripMenuItem(); ToolStripMenuItem del_items = new ToolStripMenuItem(); Accounts.AccountProperties acprop = (Accounts.AccountProperties)ienum.Current; string ID = acprop.ID; //string Password = accounts[ID].ToString(); //edit_items.Text = ID; del_items.Text = ID; /* * edit_items.Click += delegate * { * EditForm edtFrm = new EditForm(ID); * edtFrm.Show(); // フォームの表示 * }; * this.ToolStripMenuItem_Right_Edit.DropDownItems.Add(edit_items); */ if (acprop.Site == Accounts.AccountProperties.LoginSite.Official) { del_items.Image = (Image)Properties.Resources.official.ToBitmap(); } else if (acprop.Site == Accounts.AccountProperties.LoginSite.HanGame) { del_items.Image = (Image)Properties.Resources.hangame.ToBitmap(); } else if (acprop.Site == Accounts.AccountProperties.LoginSite.AtGames) { del_items.Image = (Image)Properties.Resources.atgames.ToBitmap(); } else if (acprop.Site == Accounts.AccountProperties.LoginSite.Gamers1) { del_items.Image = (Image)Properties.Resources.lievo.ToBitmap(); } else { del_items.Image = (Image)Properties.Resources.official.ToBitmap(); } del_items.Click += delegate { DialogResult diagres = MessageBox.Show("ID: \" " + ID + " \" を削除しようとしています。" + Environment.NewLine + "よろしいですか?", "TSLoginManager", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2); if (diagres == DialogResult.No) { return; } ProgramController.AController.delete(ID, acprop.Site); /* * この時点でもアカウント情報をファイルに保存する */ string filename = Environment.CurrentDirectory + @"\accounts.dat"; if (AccountController.isLoadedAccount && (AccountController.AccountData.Count > 0)) { ProgramController.AController.saveAccounts(filename, AccountController.MasterKey); } }; this.ToolStripMenuItem_Right_Delete.DropDownItems.Add(del_items); } } #endregion #region プラグイン一覧 if (Program.plugins.Length == 0) { //this.ToolStripMenuItem_Right_Plugins.DropDownItems.Add("No Plugin"); this.ToolStripMenuItem_Right_Plugins.Enabled = false; } else { this.ToolStripMenuItem_Right_Plugins.Enabled = true; this.ToolStripMenuItem_Right_Plugins.DropDown.Enabled = true; foreach (TricksterTools.Plugins.IPlugin plugin in Program.plugins) { ToolStripMenuItem_Plugin PluginItems = new ToolStripMenuItem_Plugin(); PluginItems.setPluginName(plugin.GetType().Name, plugin.Name); PluginItems.Click += delegate { PluginController.PluginRun(Program.plugins, PluginItems.ClassName); }; this.ToolStripMenuItem_Right_Plugins.DropDownItems.Add(PluginItems); } } #endregion #region プラグイン情報 if (Program.plugins.Length == 0) { //this.ToolStripMenuItem_Right_Tool_PluginInfo.DropDownItems.Add("No Plugin"); this.ToolStripMenuItem_Right_Tool_PluginInfo.Enabled = false; } else { this.ToolStripMenuItem_Right_Tool_PluginInfo.Enabled = true; this.ToolStripMenuItem_Right_Tool_PluginInfo.DropDown.Enabled = true; foreach (TricksterTools.Plugins.IPlugin plugin in Program.plugins) { ToolStripMenuItem_Plugin PluginInfoItems = new ToolStripMenuItem_Plugin(); PluginInfoItems.setPluginName(plugin.GetType().Name, plugin.Name); PluginInfoItems.Click += delegate { //PluginInfoForm pluginInfoForm = new PluginInfoForm(plugin); PluginInfoForm pluginInfoForm = new PluginInfoForm(PluginController.getPluginInfo(Program.plugins, PluginInfoItems.ClassName)); pluginInfoForm.Show(); pluginInfoForm.Owner = this; }; this.ToolStripMenuItem_Right_Tool_PluginInfo.DropDownItems.Add(PluginInfoItems); } } #endregion #region リンク一覧 if (links.ContainsKey("__TSLM_NULL__")) { this.ToolStripMenuItem_Right_Links.DropDownItems.Add("No Links"); this.ToolStripMenuItem_Right_Links.Enabled = false; } else { this.ToolStripMenuItem_Right_Links.Enabled = true; this.ToolStripMenuItem_Right_Links.DropDown.Enabled = true; foreach (string key in links.Keys) { ToolStripMenuItem link_items = new ToolStripMenuItem(); string SiteName = key; link_items.Text = SiteName; link_items.Click += delegate { System.Diagnostics.Process.Start(links[SiteName].ToString()); }; this.ToolStripMenuItem_Right_Links.DropDownItems.Add(link_items); } } #endregion #region プラグイン情報 //this.notifyIcon.ContextMenuStrip = this.contextMenuStrip_Right; this.Activate(); this.contextMenuStrip_Right.Show(mp.X, mp.Y + 275); //this.contextMenuStrip_Right.Show(this, Cursor.Position.X - this.Location.X, Cursor.Position.X - this.Location.X); //this.contextMenuStrip_Right.Show(PointToScreen(Cursor.Position)); ToolStripDropDownMenu tsddm_r_del = (ToolStripDropDownMenu)this.ToolStripMenuItem_Right_Delete.DropDown; tsddm_r_del.ShowImageMargin = true; ToolStripDropDownMenu tsddm_r_link = (ToolStripDropDownMenu)this.ToolStripMenuItem_Right_Links.DropDown; tsddm_r_link.ShowImageMargin = false; ToolStripDropDownMenu tsddm_r_plugin = (ToolStripDropDownMenu)this.ToolStripMenuItem_Right_Plugins.DropDown; tsddm_r_plugin.ShowImageMargin = false; ToolStripDropDownMenu tsddm_r_tool = (ToolStripDropDownMenu)this.ToolStripMenuItem_Right_Tool.DropDown; tsddm_r_tool.ShowImageMargin = false; ToolStripDropDownMenu tsddm_r_tool_setting = (ToolStripDropDownMenu)this.ToolStripMenuItem_Right_Tool_Settings.DropDown; tsddm_r_tool_setting.ShowImageMargin = false; ToolStripDropDownMenu tsddm_r_tool_plguininfo = (ToolStripDropDownMenu)this.ToolStripMenuItem_Right_Tool_PluginInfo.DropDown; tsddm_r_tool_plguininfo.ShowImageMargin = false; #endregion #endregion } }