Note 1: Check if current user is administrator
WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); Console.WriteLine("Programm wird unter dem Usercontext ausgeführt: {0}", principal.Identity.Name); Console.WriteLine("Adminrechte vorhanden: {0}", principal.IsInRole(WindowsBuiltInRole.Administrator) ? "Ja" : "Nein");
Note 2: ContextMenuStrip at selected row open and Index in DataTable localize.
private void dgv_MouseUp(object sender, MouseEventArgs e) { DataGridView.HitTestInfo hitTest = ((DataGridView)sender).HitTest(e.X, e.Y); if (hitTest .Type == DataGridViewHitTestType.Cell) { dgv.CurrentCell = dgv.Rows[hTest.RowIndex].Cells[hTest.ColumnIndex]; } }
Note 3: SQL Query for clustering
Source:
KeywordId (int) | Zugriffe (int) ============================== 1 | 10 2 | 5 3 | 25 4 | 45 5 | 10 6 | 1 ===============================
Destination: (1,2,3) (4,5,6) clustered to be (3,4) with summing.
KeywordId (int) | Zugriffe (int) ============================== 3 | 40 4 | 56 ===============================
Solution 1:
SELECT SUM(CASE WHEN KeyWordId IN (1,2,3) THEN Zugriffe ELSE 0 END) AS Cluster123, SUM(CASE WHEN KeyWordId IN (4,5,6) THEN Zugriffe ELSE 0 END) AS Cluster456 FROM <Tablename>
Solution 2:
SELECT 'Cluster123' AS KeyWordIdCluster, SUM(Zugriffe) AS Zugriffe FROM <Tablename> WHERE KeyWordId IN (1,2,3) UNION ALL SELECT 'Cluster456' AS KeyWordIdCluster, SUM(Zugriffe) AS Zugriffe FROM <Tablename> WHERE KeyWordId IN (4,5,6)
Solution 3:
SELECT CASE WHEN Keyword IN(1,2,3) THEN 'A' WHEN Keyword IN(4,5,6) THEN 'B' END as 'Keyword', SUM(Zugriffe) as 'Zugriffe' FROM data GROUP BY CASE WHEN Keyword IN(1,2,3) THEN 'A' WHEN Keyword IN(4,5,6) THEN 'B' END
Note 4: ASP.NET and database connection
– ASP.NET (HTTP protocol), is a stateless protocol. This means that a browser never logs off the server. The browser sends only one request to the server, “wants to see page X” and then the server sends the page back.
Building a database connection as late as possible, and terminate the connection as soon as possible. At best pack the code in Using query, then the CLR takes care of the necessary Close command.
– Application_End event is usually fired when the application is unloaded to exit from IIS, or from the application pool. There are also events that are fired after processing a single request. But should still open the database connection only when needed and close again. Whether a browser window is still open, can not get reliably with – should never try at web applications to respond to determine the server side. It is in many cases, hardly any difference between “window is still open” and “cookie is still there, window will be opened with previous URL again.”
Note 5: SelectMany LINQ Distinct
var portal = "portal1"; var kunde1 = new Kunde(); kunde1.Portale.Add(portal); var kunde2 = new Kunde(); kunde2.Portale.Add(portal); kunde2.Portale.Add("portal2"); var monat = new Monat(); monat.Kunden.Add(kunde1); monat.Kunden.Add(kunde2); var monatList = new List<Monat>(); monatList.Add(monat); var distinctPortals = monatList.SelectMany(f => f.Kunden.SelectMany(x => x.Portale)).Distinct().ToList();
Note 6: Wait until Thread finishes
public class A { private AutoResetEvent ev = new AutoResetEvent(false); private List<object> bList; public A() { // Threads ThreadPool...(callback_methode); } void callback_methode() { bList = ... ev.Set(); } public List<object> Bs { get { ev.WaitOne(); return bList; } } }
Note 7: Enumerate all pairs of numbers, but without (i, i) and without (i, j) if (j, i) is already available
int Number = 4; for(int a = 0; a < Number; a++) for(int b = a +1 ; b < Number; b++) Console.WriteLine("{0};{1}",a,b);
Note 8: Select what not in other table
Kunde "Mustermann", id=1 Kunde "Meier", id=2 Produkt "Nudeln", id=99, KundenId=1, SparteId=8 Produkt "Erbsen", id=100, KundenId=1, SparteId=10 Produkt "Linsen", id=101, KundenId=2, SparteId=15
Task: Only give “Meier” as result back because he has SparteId = 10.
SQL
SELECT k.* FROM Kunden k WHERE NOT EXISTS ( SELECT * FROM Produkte p WHERE k.Id = p.KundenId AND p.Sparte = 10);
or
SELECT Kunde.* FROM ( SELECT 1 as ID, 'Mustermann' as Kunde UNION SELECT 2 as ID, 'Meier' as Kunde ) Kunde LEFT JOIN ( SELECT * FROM ( SELECT 99 as ID, 'Nudeln' as Produkt, 8 as Sparte_ID, 1 as Kunde_ID UNION SELECT 100 as ID, 'Erbsen' as Produkt, 10 as Sparte_ID, 1 as Kunde_ID UNION SELECT 101 as ID, 'Linsen' as Produkt, 15 as Sparte_ID, 2 as Kunde_ID ) Data ) Produkt ON Kunde.ID = Produkt.Kunde_ID AND Produkt.Sparte_ID = 10 WHERE Produkt.Sparte_ID is null
Note 9 : Select items with Count() = 1
List<int> l = new List<int>(){1,1,1,2,3,4,5,6}; var v = l.Where(item => l.Count(i => item == i) == 1).ToList(); //oder var vv = l.GroupBy(item => item).Where(g=> g.Count() == 1).Select(item=>item.Key).ToList();
Note 10: Read user comment from EXIF
EXIF Specification : http://www.exif.org/Exif2-2.PDF
public static string ReadComment(Image image) { PropertyItem[] items = image.PropertyItems; foreach (PropertyItem pi in items) { if (pi.Id == 0x9286) { string characterCode = System.Text.Encoding.ASCII.GetString(pi.Value, 0, 8).TrimEnd('\0');; switch (characterCode) { case "UNICODE": return System.Text.Encoding.Unicode.GetString(pi.Value, 8, pi.Len-8); case "ASCII": return System.Text.Encoding.ASCII.GetString(pi.Value, 8, pi.Len-8); default: throw new NotSupportedException(characterCode + " Encoding not Supported!"); } } } return string.Empty; }
Note 11: Insert Excel table to Word document
using System; using System.Collections.Generic; using System.Linq; using System.Text; using wd = Microsoft.Office.Interop.Word; using xl = Microsoft.Office.Interop.Excel; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { // Word starten wd.Application wdApp = new wd.Application(); // sichtbar machen wdApp.Visible = true; object shType = "Excel.Sheet.12"; //14 geht nicht (warum auch immer...) object misssing = Type.Missing; object comFalse = false; // Neues Dokument öffnen wdApp.Documents.Add(); // excel-tabelle in's dokument einfügen wd.InlineShape shape = wdApp.Selection.InlineShapes.AddOLEObject(ref shType, ref misssing, ref comFalse, ref comFalse, ref misssing, ref misssing, ref misssing, ref misssing); // Format wird benötigt, um an das eigentliche Objekt zu kommen wd.OLEFormat format = shape.OLEFormat; //format.Objekt kann wie Excel.Application verwendet werden, casten geht bei mir nicht. Console.WriteLine(format.Object.ActiveSheet.Name); Console.ReadLine(); } } }
Note 12: How to disable network interface
ConnectionOptions oConn = new ConnectionOptions(); oConn.Username = @"MaxMustermann"; oConn.Password = "PW_Mustermann"; int[] arr_status = new int[2]; ManagementScope oMs = new ManagementScope("\\\\Mustermanns_Rechner\\root\\cimv2"); oMs.Connect(); if (oMs.IsConnected) { System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("Select * From Win32_NetworkAdapter WHERE NetConnectionID = 'Local Area Connection'"); //Execute the query ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery); ManagementOperationObserver observer = new ManagementOperationObserver(); //Get the results ManagementObjectCollection oReturnCollection = oSearcher.Get(); foreach (ManagementObject oReturn in oReturnCollection) { try { NetworkAdapter NW = new NetworkAdapter(oReturn); oReturn.InvokeMethod("disable", null); lbl_nw.Text = "Deaktiviert"; break; } catch (Exception ex) { lbl_info.Text = ex.ToString(); } } }
Note 13: Event fired when new monitor is plugged in
SystemEvents.DisplaySettingsChanging += new EventHandler(SystemEvents_DisplaySettingsChanging);
Note 14: How to debug Stored Procedure
USE [docmaDB_INT] GO DECLARE @return_value int EXEC @return_value = [P3907].[GetMainNodeID] @ProjectID = 561 SELECT 'Return Value' = @return_value GO
Note 15 : DataTable Sort
public static void Main(string[] args) { DataTable table = new DataTable(); table.Columns.Add("Col1", Type.GetType("System.Boolean")); table.Columns.Add("Col2", Type.GetType("System.DateTime")); table.Columns.Add("Col3", Type.GetType("System.DateTime")); table.Columns.Add("Col4", Type.GetType("System.Double")); table.Columns.Add("Col5", Type.GetType("System.Double")); table.Rows.Add(true, new DateTime(2011, 10, 3), new DateTime(2011, 10, 3), 0.00065432, 0.125432); table.Rows.Add(true, new DateTime(2011, 10, 3), new DateTime(2011, 10, 3), 0.00065432, 0.125432); table.Rows.Add(true, new DateTime(2011, 10, 5), new DateTime(2011, 10, 5), 0.00065432, 0.125432); table.Rows.Add(true, new DateTime(2012, 11, 3), new DateTime(2012, 11, 3), 2.2345, 0.61232); table.Rows.Add(true, new DateTime(2012, 11, 4), new DateTime(2012, 11, 4), 2.2345, 0.61232); DataTable dt = SortSourceTable(table); for (int i = 0; i < dt.Rows.Count; i++) { DataRow row = dt.Rows[i]; Console.WriteLine(row["Col2"]); } Console.Read(); } public static DataTable SortSourceTable(DataTable table) { DataView dv = table.DefaultView; dv.Sort = "Col2"; return dv.ToTable(); }