//Async await is used for heavy db selections and calculations or webservices. //In general tasks which takes time and you want the result returned asyncronuously //because you dont know when the algorithm returns, which run by maybe several threads to execute //async await came in framework 4.5 and there is lots of good examples on the net. //This example is very simple example just to show the idea of async await //In some examples there is used HttpClient... remember to add Reference if you use some of //these examples and methods like GetByteArrayAsync() to load page in bytes //So why use async await??? //The code gets much simpler/prettier where before you needed to handle each thread by f.eks backgoundworker... //Notice: if you have several async await and the first task is done the server will return when all the //tasks are done but the page will load immediately if you are working with web apps...Happy coding...:) protected async void Button1_Click(object sender, EventArgs e) { this.Button1.Enabled = false; var someTask = Task.Factory.StartNew(() => slowFunc(1, 2)); await someTask; this.Label1.Text = "Result: " + someTask.Result.ToString(); this.Button1.Enabled = true; } private int slowFunc(int a, int b) { System.Threading.Thread.Sleep(10000); return a + b; } //mm.Attachments.ToList().ForEach(a => a.Dispose()); //public async void DeleteAllPdfFilesByAccNum(string accNUmber) //huskPage.Async = true //{ // string[] filePaths = Directory.GetFiles(pdfPaths, "*.pdf"); // foreach (string f in filePaths) // { // if (f.Contains("(" + accNUmber + ")")) // { // await Task.Factory.StartNew(() => File.Delete(f)); // } // } //}
public partial class Form1 : Form { public Form1() { InitializeComponent(); pictureBox1.ImageLocation = AppDomain.CurrentDomain.BaseDirectory + "Image/ajax.gif"; } private void button1_Click(object sender, EventArgs e) { byteImageData = ImageToByte(AppDomain.CurrentDomain.BaseDirectory + "Image/ajax.gif", new string[] { ".gif", ".jpg", ".bmp", "png" }); foreach(byte b in byteImageData) textBox1.AppendText(b.ToString()); pictureBox1.Image = null; } private void button2_Click(object sender, EventArgs e) { byteArrayToImage(byteImageData); } private static byte[] byteImageData; # region Converting Image to Byte private static byte[] ImageToByte(string p_postedImageFileName, string[] p_fileType) { bool isValidFileType = false; try { FileInfo file = new FileInfo(p_postedImageFileName); foreach (string strExtensionType in p_fileType) { if (strExtensionType == file.Extension) { isValidFileType = true; break; } } if (isValidFileType) { FileStream fs = new FileStream(p_postedImageFileName, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); byte[] image = br.ReadBytes((int)fs.Length); br.Close(); fs.Close(); return image; } return null; } catch (Exception ex) { throw ex; } } #endregion #region Converting Byte to Image private void byteArrayToImage(byte[] byteArrayIn) { System.Drawing.Image newImage; string strFileName = AppDomain.CurrentDomain.BaseDirectory + "Image/ajaxtemp.gif"; if (byteArrayIn != null) { using (MemoryStream stream = new MemoryStream(byteArrayIn)) { newImage = System.Drawing.Image.FromStream(stream); newImage.Save(strFileName); pictureBox1.ImageLocation = strFileName; } textBox1.Text = "The image conversion was successful."; } else { MessageBox.Show("No image data found!"); } } #endregion private void resizeImg() { byte[] fileBytes = File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + "img.jpg"); Bitmap bm = new Bitmap(232, 154); Graphics g = Graphics.FromImage((Image)bm); g.DrawImage(Image.FromStream(new MemoryStream(fileBytes)), 0, 0, 232, 154); g.Dispose(); pictureBox1.Image = (Image)bm; } }
Download itextsharp.dll associate to it in your project it's open source Create your PDF file and remember to add text fields, these fields are the places you will be able to edit the text. private void DoPDF(string ID, string post) { string pdfTemplate = Server.MapPath("~/bla/bla.pdf"); string newFile = Server.MapPath("~/bla/bla.pdf"); PdfReader pdfReader = new PdfReader(pdfTemplate); PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream( newFile, FileMode.Create)); AcroFields pdfFormFields = pdfStamper.AcroFields; // set form pdfFormFields // The first worksheet and W-4 form pdfFormFields.SetField("ID", "1"); pdfFormFields.SetField("number", "18"); pdfFormFields.SetField("receiver", " simpa.dk"); pdfFormFields.SetField("date", " " + DateTime.Now.AddDays(7.0).ToShortDateString()); pdfFormFields.SetField("post", " " + post); // flatten the form to remove editting options, set it to false // to leave the form open to subsequent manual edits pdfStamper.FormFlattening = false; // close the pdf pdfStamper.Close(); } happy coding... :)
Example with MD5 encrypting/decrypting: class Cryptography { private bool encrypted; public bool Encrypted() { return encrypted; } public void Decrypt(string path, bool useHashing) { encrypted = false; try { byte[] keyArray; //get the byte code of the string TextReader tr = new StreamReader(path); string cipherString = tr.ReadLine(); tr.Close(); byte[] toEncryptArray = Convert.FromBase64String(cipherString); //System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); ////Get your key from config file to open the lock! //string key = (string)settingsReader.GetValue("SecurityKey", typeof(String)); ConfigReaderWriter crf = new ConfigReaderWriter(); string key = crf.ReturnConfigValue(); if (useHashing) { //if hashing was used get the hash code with regards to your key MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); //release any resource held by the MD5CryptoServiceProvider hashmd5.Clear(); } else { //if hashing was not implemented get the byte code of the key keyArray = UTF8Encoding.UTF8.GetBytes(key); } TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); //set the secret key for the tripleDES algorithm tdes.Key = keyArray; //mode of operation. there are other 4 modes. //We choose ECB(Electronic code Book) tdes.Mode = CipherMode.ECB; //padding mode(if any extra byte added) tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateDecryptor(); byte[] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length); //Release resources held by TripleDes Encryptor tdes.Clear(); //return the Clear decrypted TEXT TextWriter tw = new StreamWriter(path); tw.WriteLine(UTF8Encoding.UTF8.GetString(resultArray)); tw.Close(); } catch(Exception e) { MessageBox.Show(e.ToString()); //File.Delete(path); //Application.ExitThread(); } } public void Encrypt(string path, bool useHashing) { encrypted = true; byte[] keyArray; try { TextReader tr = new StreamReader(path); string toEncrypt = tr.ReadLine(); tr.Close(); byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt); System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader(); // Get the key from config file ConfigReaderWriter crf = new ConfigReaderWriter(); string key = crf.ReturnConfigValue(); //System.Windows.Forms.MessageBox.Show(key); //If hashing use get hashcode regards to your key if (useHashing) { MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider(); keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key)); //Always release the resources and flush data //of the Cryptographic service provide. Best Practice hashmd5.Clear(); } else keyArray = UTF8Encoding.UTF8.GetBytes(key); TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider(); //set the secret key for the tripleDES algorithm tdes.Key = keyArray; //mode of operation. there are other 4 modes. We choose ECB(Electronic code Book) tdes.Mode = CipherMode.ECB; //padding mode(if any extra byte added) tdes.Padding = PaddingMode.PKCS7; ICryptoTransform cTransform = tdes.CreateEncryptor(); //transform the specified region of bytes array to resultArray byte[] resultArray = cTransform.TransformFinalBlock (toEncryptArray, 0, toEncryptArray.Length); //Release resources held by TripleDes Encryptor tdes.Clear(); //Return the encrypted data into unreadable string format TextWriter tw = new StreamWriter(path); tw.WriteLine(Convert.ToBase64String(resultArray, 0, resultArray.Length)); tw.Close(); } catch { Application.ExitThread(); } } }
public ArrayList GetConn() { ArrayList list = new ArrayList(); Process p = new Process(); StreamReader sr; ProcessStartInfo startInfo = new ProcessStartInfo("netstat"); startInfo.Arguments = "-ano"; startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; startInfo.CreateNoWindow = true; p.StartInfo = startInfo; p.Start(); sr = p.StandardOutput; while (!sr.EndOfStream) { list.Add(sr.ReadLine()); } return list; }
public Form1{ notifyIcon1 = new NotifyIcon(); notifyIcon1.Icon = new Icon("mail_edit.ico"); notifyIcon1.Visible = true; notifyIcon1.Text = "double click"; notifyIcon1.MouseDoubleClick += new MouseEventHandler(notifyIcon1_MouseDoubleClick); contextMenu1 = new ContextMenu(); MenuItem menuItem1 = new MenuItem("E&xit"); MenuItem menuItem2 = new MenuItem("Minimize"); this.contextMenu1.MenuItems.AddRange( new System.Windows.Forms.MenuItem[] { menuItem1, menuItem2 }); notifyIcon1.ContextMenu = contextMenu1; menuItem1.Click += new EventHandler(menuItem1_Click); menuItem2.Click += new EventHandler(menuItem2_Click); } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { Show(); WindowState = FormWindowState.Normal; } void menuItem1_Click(object sender, EventArgs e) { notifyIcon1.Visible = false; Application.ExitThread(); } void menuItem2_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; this.Hide(); }
C#: How to read: SqlConnection conn = new SqlConnection("127.0.0.1"); SqlCommand command = new SqlCommand("spRead", conn); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("@TelefonNr", SqlDbType.Int).Value = textbox1.Text; if (conn.State == ConnectionState.Closed) conn.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { textbox2.Text = reader["Navn"].ToString(); } if (!reader.HasRows) MessageBox.Show("Does not exist!"); conn.Close(); How to delete: SqlConnection conn = new SqlConnection(db.ConnectionStringAsString()); SqlCommand command = new SqlCommand("spDelete", conn); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("@id", SqlDbType.Int).Value = int.Parse(item); if (conn.State == ConnectionState.Closed) conn.Open(); command.ExecuteNonQuery(); conn.Close(); How to write: SqlConnection conn = new SqlConnection(db.ConnectionStringAsString()); SqlCommand command = new SqlCommand("spWrite", conn); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("@TelefonNr", SqlDbType.Int).Value = textbox1.Text; command.Parameters.Add("@Navn", SqlDbType.VarChar).Value = textbox2.Text; command.Parameters.Add("@Adresse", SqlDbType.VarChar).Value = textbox3.Text; command.Parameters.Add("@PostNr", SqlDbType.VarChar).Value = textbox4.Text; command.Parameters.Add("@ByNavn", SqlDbType.VarChar).Value = textbox5.Text; command.Parameters.Add("@Land", SqlDbType.VarChar).Value = textbox6.Text; command.Parameters.Add("@EMail", SqlDbType.VarChar).Value = textbox7.Text; command.Parameters.Add("@Fax", SqlDbType.Int).Value = 0; command.Parameters.Add("@cvr", SqlDbType.VarChar).Value = ""; command.Parameters.Add("@Kontaktperson", SqlDbType.VarChar).Value = ""; conn.Open(); int rows = command.ExecuteNonQuery(); conn.Close(); SQL: CREATE PROCEDURE [dbo].[spRead] @TelefonNr int WITH ENCRYPTION AS BEGIN SET NOCOUNT ON SELECT [UdlejningId], [Navn], [Udlejning].[TelefonNr], [Dato], [LejeperiodeStart], [LejeperiodeSlut], [Udlejning].[VognID], [Type] FROM [UdlejningDb].[dbo].[Udlejning], [UdlejningDb].[dbo].[Kunde], [UdlejningDB].[dbo].[vogn] WHERE [Kunde].[TelefonNr] = @TelefonNr AND [Vogn].[VognId] = [Udlejning].[VognId] AND [Udlejning].[TelefonNr] = @TelefonNr END GO CREATE PROCEDURE [dbo].[spDelete] @Id int WITH ENCRYPTION AS BEGIN SET NOCOUNT ON UPDATE [UdlejningDb].[dbo].[Vogn] SET [Vogn].[Ledig] = 1 FROM [UdlejningDb].[dbo].[Vogn], [UdlejningDb].[dbo].[Udlejning] WHERE [Vogn].[VognId] = [Udlejning].[VognId] AND [Udlejning].[UdlejningId] = @UdlejningId DELETE FROM [UdlejningDb].[dbo].[Udlejning] WHERE [UdlejningId] = @UdlejningId END GO CREATE PROCEDURE [dbo].[spWrite] @TelefonNr int, @Navn varchar(60), @Adresse varchar(60), @PostNr varchar(15), @EMail varchar(60), @Fax varchar(30), @Kontaktperson varchar(60), @Cvr varchar(30), @ByNavn varchar(60), @Land varchar(30) WITH ENCRYPTION AS BEGIN SET NOCOUNT ON; INSERT INTO [UdlejningDb].[dbo].[Kunde] ([TelefonNr], [Navn], [Adresse], [PostNr], [EMail], [Fax], [Kontaktperson], [Cvr], [AntalUdlejninger]) VALUES (@TelefonNr, @Navn, @Adresse, @PostNr, @EMail, @Fax, @Kontaktperson, @Cvr, 0) IF NOT EXISTS(SELECT * FROM [UdlejningDb].[dbo].[Postnummer] WHERE [PostNr]=@PostNr) BEGIN INSERT INTO [UdlejningDb].[dbo].[Postnummer] ([PostNr], [ByNavn], [Land]) VALUES (@PostNr, @ByNavn, @Land) END END GO
class ConfigReaderWriter { private string connStr; public string ReturnConfigValue() { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "App.config"); XmlNode appSettingsNode = xmlDoc.SelectSingleNode("configuration/appSettings"); foreach (XmlNode node in appSettingsNode.ChildNodes) { ListViewItem lvi = new ListViewItem(); connStr = node.Attributes["value"].Value.ToString(); string keyName = node.Attributes["key"].Value.ToString(); lvi.Text = keyName; lvi.Text = connStr; lvi.SubItems.Add(connStr); } return connStr; } // Updates a key within the App.config public void UpdateKey(string strKey, string newValue) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "App.config"); XmlNode appSettingsNode = xmlDoc.SelectSingleNode("configuration/appSettings"); // Attempt to locate the requested setting. foreach (XmlNode childNode in appSettingsNode) { if (childNode.Attributes["key"].Value == strKey) childNode.Attributes["value"].Value = newValue; } xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "App.config"); xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); } }
public ArrayList Return() { ArrayList list = new ArrayList(); SqlCommand cmd = new SqlCommand("exec spReturn", conn); cmd.Connection = conn; //try //{ conn.Open(); IDataReader reader = cmd.ExecuteReader(); while (reader.Read()) list.Add(reader.GetValue(3).ToString()); conn.Close(); //} //catch (Exception) //{ // MessageBox.Show("Internet connection is required...Please connect and try again..."); //} return list; } public DataSet Return(){ //from here DataSet myDataSet = new DataSet("myDataSet"); DataTable tProc = new DataTable("nc"); DataColumn Nkundenr = new DataColumn("kundenr", typeof(string)); DataColumn Nkundenavn = new DataColumn("kundenavn", typeof(string)); DataColumn Nvognnr = new DataColumn("vognnr", typeof(string)); DataColumn Nvogn = new DataColumn("vogn", typeof(string)); DataColumn Nstartdato = new DataColumn("startdato", typeof(string)); DataColumn Nslutdato = new DataColumn("slutdato", typeof(string)); tProc.Columns.Add(Nkundenr); tProc.Columns.Add(Nkundenavn); tProc.Columns.Add(Nvognnr); tProc.Columns.Add(Nvogn); tProc.Columns.Add(Nstartdato); tProc.Columns.Add(Nslutdato); myDataSet.Tables.Add(tProc); string kundenr = ""; string kundenavn = ""; string vognnr = ""; string vogn = ""; string startdato = ""; string slutdato = ""; DataRow newRow; SqlCommand cmd = new SqlCommand("exec spReturn", conn); cmd.Connection = conn; try { conn.Open(); IDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { kundenr = reader.GetValue(0).ToString(); kundenavn = reader.GetValue(1).ToString(); vognnr = reader.GetValue(2).ToString(); vogn = reader.GetValue(3).ToString(); startdato = reader.GetValue(4).ToString(); slutdato = reader.GetValue(5).ToString(); newRow = tProc.NewRow(); newRow["kundenr"] = kundenr; newRow["kundenavn"] = kundenavn; newRow["vognnr"] = vognnr; newRow["vogn"] = vogn; newRow["startdato"] = startdato; newRow["slutdato"] = slutdato; tProc.Rows.Add(newRow); } conn.Close(); } catch (Exception) { MessageBox.Show("Could not connet to database..."); } return myDataSet; } public static DBManager Instance() { if (db == null) db = new DBManager(); return db; } How to use it in the form adding the values to the list: DBManager db = DBManager.Instance(); listView9.Clear(); listView9.Columns.Add("Vogn", 130, HorizontalAlignment.Left); listView9.Columns.Add("Vognnr", 80, HorizontalAlignment.Left); listView9.Columns.Add("Startdato", 75, HorizontalAlignment.Left); listView9.Columns.Add("Slutdato", 75, HorizontalAlignment.Left); listView9.Columns.Add("Antal Personer", 50, HorizontalAlignment.Left); DataSet tempSet = new DataSet(); tempSet = db.Return(); foreach (DataTable dtable in tempSet.Tables) for (int i = 0; i < dtable.Rows.Count; i) { DataRow drow = dtable.Rows[i]; if (drow.RowState != DataRowState.Deleted) { ListViewItem lvi = new ListViewItem(drow["vogn"].ToString()); lvi.SubItems.Add(drow["vognnr"].ToString()); lvi.SubItems.Add(drow["startdato"].ToString()); lvi.SubItems.Add(drow["slutdato"].ToString()); } } listView9.Items.Add(lvi);
First you need at manifest file wich you can add to the project. Add new file choose manifest file. When you choose the manifest file it is really important to name it <your project name>.exe.manifest example: Project2.exe.manifest. Afterwards add this code: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="Project2" type="win32"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="requireAdministrator"/> </requestedPrivileges> </security> </trustInfo> </assembly> now when you compile there will be showed a shell on the icon. This will request admin rights every time you start your application.
private void button1_Click(object sender, EventArgs e) { Form1 f1 = (Form1)Application.OpenForms["Form1"]; int col = Convert.ToInt32(0) - 1; int colCount = col + 1; bool find = false; colCount = f1.listView1.Columns.Count; col = 0; for (int colAll = col; colAll < colCount; colAll++) { for (int lst12 = lastItm; lst12 < f1.listView1.Items.Count; lst12++) { if (f1.listView1.Items[lst12].SubItems[colAll].Text.LastIndexOf(textBox1.Text) > -1 | f1.listView1.Items[lst12].SubItems[colAll].Text.ToUpper().LastIndexOf(textBox1.Text.ToUpper()) > -1) { f1.listView1.TopItem = f1.listView1.Items[lst12]; if (lastItm > 0) f1.listView1.Items[lastItm - 1].BackColor = Color.Empty; f1.listView1.Items[lst12].BackColor = Color.Aqua; lastItm = lst12 + 1; find = true; break; } } if (find) break; } this.Close(); } Another example: bool exists = false; foreach (ListViewItem lv in this.listView8.Items) { if (lvi.Text == lv.Text) { MessageBox.Show(lv.Text + " is choosen"); exists = true; break; } } if (!exists) { listView8.Items.Add(lvi); }
Make a class with this code: class Sort : IComparer { private int col; private SortOrder order; public Sortering() { col = 0; order = SortOrder.Ascending; } public Sortering(int column, SortOrder order) { col = column; this.order = order; } public int Compare(object x, object y) { String text1 = ((ListViewItem)x).SubItems[col].Text; String text2 = ((ListViewItem)y).SubItems[col].Text; int i1, i2; int returnValue; if (int.TryParse(text1, out i1) && int.TryParse(text2, out i2)) { returnValue = i1 - i2; } else { returnValue = String.Compare(text1, text2); } if (order == SortOrder.Descending) returnValue = -returnValue; return returnValue; } } Now when you need to use it from you form add this code: private int sortColumn = -1; private void listView5_ColumnClick(object sender, ColumnClickEventArgs e) { if (e.Column != sortColumn) { sortColumn = e.Column; listView5.Sorting = System.Windows.Forms.SortOrder.Ascending; } else { if (listView5.Sorting == System.Windows.Forms.SortOrder.Ascending) listView5.Sorting = System.Windows.Forms.SortOrder.Descending; else listView5.Sorting = System.Windows.Forms.SortOrder.Ascending; } this.listView5.ListViewItemSorter = new Sortering(e.Column, listView5.Sorting); listView5.Sort(); } this will sort strings and int.
private void button1_Click(object sender, EventArgs e) { Singelton s = Singelton.instance(); SqlConnection conn = s.conn(); SqlCommand resetCMD = new SqlCommand("SET TRANSACTION ISOLATION LEVEL READ COMMITTED", conn); if (conn.State == ConnectionState.Closed) conn.Open(); resetCMD.ExecuteNonQuery(); //SqlTransaction tempTrans = conn.BeginTransaction(); //tempTrans.Commit(); SqlCommand command = new SqlCommand("spEditMeterReading", conn); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("@newvalue", SqlDbType.Int).Value = textBox1.Text; if (conn.State == ConnectionState.Closed) conn.Open(); int rows = command.ExecuteNonQuery(); conn.Close(); } class Singelton { private static Singelton inst = null; public static Singelton instance() { if (inst == null) inst = new Singelton(); return inst; } public SqlConnection conn() { SqlConnection conn = new SqlConnection(@"Server=localhost\SQLExpress2008; Integrated Security=True; Database=MandatoryDB"); return conn; } } create proc spEditMeterReading @newvalue int as begin begin tran update Readings set value = @newvalue where readingsId = 17988 commit tran end exec [dbo].[spEditMeterReading] 20000
class Idle { private string idle; // Unmanaged function from user32.dll [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); // Struct we'll need to pass to the function internal struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } //Now it's time to double-click the tmrIdle Timer object so that we get to its Tick event. Here comes the main code, which is self-explanatory thanks to the comments: public void tmrIdle_Tick(object sender, EventArgs e) { // Get the system uptime int systemUptime = Environment.TickCount; // The tick at which the last input was recorded int LastInputTicks = 0; // The number of ticks that passed since last input int IdleTicks = 0; // Set the struct LASTINPUTINFO LastInputInfo = new LASTINPUTINFO(); LastInputInfo.cbSize = (uint)Marshal.SizeOf(LastInputInfo); LastInputInfo.dwTime = 0; // If we have a value from the function if (GetLastInputInfo(ref LastInputInfo)) { // Get the number of ticks at the point when the last activity was seen LastInputTicks = (int)LastInputInfo.dwTime; // Number of idle ticks = system uptime ticks - number of ticks at last input IdleTicks = systemUptime - LastInputTicks; } // Set the labels; divide by 1000 to transform the milliseconds to seconds string temp = Convert.ToString(systemUptime / 1000) + " seconds"; idle = Convert.ToString(IdleTicks / 1000);// +" seconds";// IDLE string temp3 = "At second " + Convert.ToString(LastInputTicks / 1000); } public string IdleString(){return idle;} public int IdleInt() { return int.Parse(idle); } }
(Form1) By button click class: public Form1() { InitializeComponent(); } private ContentBasedRouter cbr = new ContentBasedRouter(); private void button4_Click(object sender, EventArgs e) { foreach (string s in cbr.ReturnPayTypeValueDeparture("Coins")) textBox1.Text += s + "\r\n"; } private void button5_Click(object sender, EventArgs e) { foreach (string s in cbr.ReturnPayTypeValueDeparture("SMS")) textBox1.Text += s + "\r\n"; } private void button6_Click(object sender, EventArgs e) { foreach (string s in cbr.ReturnPayTypeValueDeparture("CreditCard")) textBox1.Text += s + "\r\n"; } ContentBasedRouter.cs: class ContentBasedRouter { private string path = @"../../CDM.xml"; protected MessageQueue PBS = new MessageQueue(@".\Private$\PBS"); protected MessageQueue phoneCompany = new MessageQueue(@".\Private$\phoneCompany"); protected MessageQueue coinsqueue = new MessageQueue(@".\Private$\coins"); public List<string> ReturnPayTypeValueDeparture(string type) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(path); XmlNode shared = xmlDoc.SelectSingleNode("Message/D/sharedValues"); List<string> sharedList = new List<string>(); foreach (XmlNode node in shared.ChildNodes) sharedList.Add(node.InnerText.ToString()); if (type == "Coins") { //DEPARTURE if (!MessageQueue.Exists(@".\Private$\coins")) MessageQueue.Create(@".\Private$\coins"); else new MessageQueue(@".\Private$\coins"); XmlNode coins = xmlDoc.SelectSingleNode("Message/D/uniqueValues/" + type); if (coins != null) { List<string> coinsList = new List<string>(); foreach (XmlNode node in coins.ChildNodes) coinsList.Add(node.InnerText.ToString()); //kan laves med 1 foreach men for at forstå koden nemmere har jeg lavet 2 foreach foreach (string s in coinsList) sharedList.Add(s); } this.coinsqueue.Formatter = new XmlMessageFormatter(new String[] { "System.String.mscorlib" }); Message m = new Message(); m.Body += type; m.Label += shared.ParentNode.Name; for (int i = 0; i < sharedList.Count; i++) { m.Body += sharedList[i]; } if (IsSMS(m)) phoneCompany.Send(m); if (IsCoins(m)) coinsqueue.Send(m); if (IsCreditCard(m)) PBS.Send(m); return sharedList; } if (type == "CreditCard") { //DEPARTURE if (!MessageQueue.Exists(@".\Private$\PBS")) MessageQueue.Create(@".\Private$\PBS"); else new MessageQueue(@".\Private$\PBS"); XmlNode creditCard = xmlDoc.SelectSingleNode("Message/D/uniqueValues/" + type); if (creditCard != null) { List<string> creditCardList = new List<string>(); foreach (XmlNode node in creditCard.ChildNodes) creditCardList.Add(node.InnerText.ToString()); //kan laves med 1 foreach men for at forstå koden nemmere har jeg lavet 2 foreach foreach (string s in creditCardList) sharedList.Add(s); } this.PBS.Formatter = new XmlMessageFormatter(new String[] { "System.String.mscorlib" }); Message m = new Message(); m.Label = shared.ParentNode.Name; m.Body += type; for (int i = 0; i < sharedList.Count; i++) { m.Body += sharedList[i]; } if (IsSMS(m)) phoneCompany.Send(m); if (IsCoins(m)) coinsqueue.Send(m); if (IsCreditCard(m)) PBS.Send(m); return sharedList; } if (type == "SMS") { //DEPARTURE if (!MessageQueue.Exists(@".\Private$\phoneCompany")) MessageQueue.Create(@".\Private$\phoneCompany"); else new MessageQueue(@".\Private$\phoneCompany"); XmlNode sms = xmlDoc.SelectSingleNode("Message/D/uniqueValues/" + type); if (sms != null) { List<string> smsList = new List<string>(); foreach (XmlNode node in sms.ChildNodes) smsList.Add(node.InnerText.ToString()); //kan laves med 1 foreach men for at forstå koden nemmere har jeg lavet 2 foreach foreach (string s in smsList) sharedList.Add(s); } this.phoneCompany.Formatter = new XmlMessageFormatter(new String[] { "System.String.mscorlib" }); Message m = new Message(); m.Label = shared.ParentNode.Name; m.Body += type; for (int i = 0; i < sharedList.Count; i++) { m.Body += sharedList[i]; } if (IsSMS(m)) phoneCompany.Send(m); if (IsCoins(m)) coinsqueue.Send(m); if (IsCreditCard(m)) PBS.Send(m); return sharedList; } return null; } protected bool IsSMS(Message m) { string s = (String)m.Body; return (s.StartsWith("SMS")); } protected bool IsCoins(Message m) { string s = (String)m.Body; return (s.StartsWith("Coins")); } protected bool IsCreditCard(Message m) { string s = (String)m.Body; return (s.StartsWith("CreditCard")); } } CDM.xml filen som der læses fra: <!--?xml version="1.0" encoding="utf-8" ?--> <message> <a> <sharedvalues> <datearrival>2010-03-22</datearrival> <timearrival>12:35</timearrival> </sharedvalues> <uniquevalues> <sms> <phonenumber>+4522361258</phonenumber> <status>A</status> <parkingplace>P1</parkingplace> <licenseplate>AB12345</licenseplate> </sms> </uniquevalues> </a> <d> <sharedvalues> <dateexit>2010-03-22</dateexit> <timeexit>15:16</timeexit> </sharedvalues> <uniquevalues> <coins> <amountpayed>120</amountpayed> </coins> <creditcard> <cardnumber>1234123412341234</cardnumber> <expmonth>11</expmonth> <expyear>13</expyear> <controldigit>221</controldigit> </creditcard> <sms> <phonenumber>+4522361258</phonenumber> <status>D</status> <parkingid>id564578</parkingid> </sms> </uniquevalues> </d> </message> </string></string></string></string></string></string></string></string></string>
//Taste of entity framework public static dbModel.Language GetResource(string Value, string CultureName) { using (var contex = new dbModel.dbModel()) { var resource = (from l in contex.Language where l.Value == Value && l.CultureName == CultureName select l).FirstOrDefault(); //contex.Language.Select(p => p.Name == Name && // p.CultureName == CultureName).FirstOrDefault(); return resource; } } public static void InsertCar(dbModel.ForSale car) { using (var context = new dbModel.dbModel()) { context.ForSale.AddObject(car);//AddToCars_User(user); context.SaveChanges(); } } public static void InsertCarPictures(dbModel.Pictures carPictures) { using (var context = new dbModel.dbModel()) { context.Pictures.AddObject(carPictures); context.SaveChanges(); } } public static dbModel.ForSale SelectCarPicture(dbModel.Pictures picture) { using (var context = new dbModel.dbModel()) { var selectedPicture = context.ForSale.Include("Pictures").Where(p => p.id == picture.id).FirstOrDefault(); return selectedPicture; } } public static void InsertBug(dbModel.ToFix bug) { using (var context = new dbModel.dbModel()) { context.ToFix.AddObject(bug); context.SaveChanges(); } } public static List<dbModel.ForSale> SearchCars(string searchValue) { using (var context = new dbModel.dbModel()) { var cars = (from c in context.ForSale where c.CarColor.Contains(searchValue) || c.CarFuel.Contains(searchValue) || c.CarName.Contains(searchValue) || c.CarYear.Contains(searchValue) || c.EngineType.Contains(searchValue) || c.EngineSize.Contains(searchValue) || c.KilometersDriven.Contains(searchValue) || c.Price.Contains(searchValue) select c).ToList(); return cars; } } public static dbModel.ForSale GetCar(int Id) { using (var context = new dbModel.dbModel()) { //var car = (from c in context.ForSale // join cp in context.Pictures on c.id equals cp.ForSale_id // where c.id == Id // select c).DefaultIfEmpty<dbModel.ForSale>().FirstOrDefault(); var car = (from c in context.ForSale.Include("Pictures") where c.id == Id select c).FirstOrDefault(); return car; } } public static dbModel.ForSale GetCar2(int Id) { using (var context = new dbModel.dbModel()) { var car = context.ForSale.Include("Pictures"). Where(c => c.id == Id); //var car = (from c in context.ForSale // from p in c.Pictures // where p.ForSale_id == Id // select new // { // MainPicture = c.MainPicture, // CarName = c.CarName, // EngineSize = c.EngineSize, // EngineType = c.EngineType, // CarYear = c.CarYear, // CarColor = c.CarColor, // CarFuel = c.CarFuel, // KilometerDriven = c.KilometersDriven, // Price = c.Price, // NewsletterSent = c.NewsletterSent, // Picture = p.Picture // }).FirstOrDefault(); //Cars cars = new Cars(); //cars.MainPicture = car.MainPicture; //cars.CarName = car.CarName; //cars.EngineSize = car.EngineSize; //cars.EngineType = car.EngineType; //cars.CarYear = car.CarYear; //cars.CarColor = car.CarColor; //cars.CarFuel = car.CarFuel; //cars.KilometerDriven = car.KilometerDriven; //cars.Price = car.Price; //cars.NewsletterSent = car.NewsletterSent; ////cars.Picture = car.Picture.ToList(); return car.FirstOrDefault(); } } public static List<dbModel.ForSale> GetCars(string sortExpression) { using (var context = new dbModel.dbModel()) { var cars = new List<dbModel.ForSale>(); if (sortExpression.Contains("Asc")) { IQueryable<dbModel.ForSale> source = context.ForSale; source = SortBy(source, sortExpression.Split(' ')[0], SortDirection.Ascending); cars = source.ToList(); } else { IQueryable<dbModel.ForSale> source = context.ForSale; source = SortBy(source, sortExpression.Split(' ')[0], SortDirection.Descending); cars = source.ToList(); } return cars; } } public static int GetCarsCount() { using (var contex = new dbModel.dbModel()) { return contex.ForSale.Count(); } } public static List<int> GetCarsIds() { using (var contex = new dbModel.dbModel()) { var ints = contex.ForSale.Select(s => s.id); List<int> ids = new List<int>(); foreach (int i in ints) { ids.Add(i); } return ids; } } public static int GetCarsPictureCount(int id) { using (var contex = new dbModel.dbModel()) { return contex.Pictures.Count(s => s.ForSale_id == id); } } public static IList<dbModel.Pictures> GetCarsPictureIds(int id) { using (var contex = new dbModel.dbModel()) { var p = contex.Pictures.Where(s => s.ForSale_id == id).ToList(); return p; } } public static void InsertNewsLetterRecipient(dbModel.NewsletterRecipients newsletterRecipient) { using (var contex = new dbModel.dbModel()) { contex.NewsletterRecipients.AddObject(newsletterRecipient); contex.SaveChanges(); } } public static void InsertUser(dbModel.User user) { using (var contex = new dbModel.dbModel()) { contex.User.AddObject(user);//AddToUser(user); contex.SaveChanges(); } } public static void UpdateUser(dbModel.User user) { using (var context = new dbModel.dbModel()) { dbModel.User u = context.User.First(s => s.id == user.id); u = user; context.SaveChanges(); } } public static void DeleteUser(dbModel.User user) { using (var context = new dbModel.dbModel()) { dbModel.User u = context.User.First(s => s.id == user.id); context.User.DeleteObject(user); context.SaveChanges(); } } public static dbModel.User SelectUser(dbModel.User user) { using (var context = new dbModel.dbModel()) { var selectedUser = (from u in context.User where u.id == user.id select u).FirstOrDefault(); return selectedUser; } } public static dbModel.User LoginUser(dbModel.User user) { using (var context = new dbModel.dbModel()) { var selectedUser = (from u in context.User where u.User == user.User && u.Password == user.Password select u).FirstOrDefault(); return selectedUser; } } public static IList<party> PagingParty(int pageIndex, int pagesize, SortDirection sortDirection, string sortOrder) { using (DataClassesDataContext dc = new DataClassesDataContext()) { IQueryable<party> source = dc.parties; //var query = source.Select(p => new //from p in dc.GetTable<party>()//.parties // //select new party // { // id = p.id, // PartyID = p.PartyID, // CanParticipate = p.CanParticipate, // DateParticipate = p.DateParticipate, // LastName = p.LastName, // Name = p.Name, // PhoneOrEmail = p.PhoneOrEmail, // ReasonNotParticipate = p.ReasonNotParticipate, // TimeAdded = p.TimeAdded, // TimeDeleted = p.TimeDeleted, // TimeUpdated = p.TimeUpdated, // }); //IQueryable query = dc.parties.Select(s => new //{ // PartyID = s.PartyID, //IF YOU HAVE SEVERAL PARTYS AT ONCE :) // CanParticipate = s.CanParticipate, // DateParticipate = s.DateParticipate, // LastName = s.LastName, // Name = s.Name, // PhoneOrEmail = s.PhoneOrEmail, // ReasonNotParticipate = s.ReasonNotParticipate, // TimeAdded = s.TimeAdded, // TimeDeleted = s.TimeDeleted, // TimeUpdated = s.TimeUpdated, //}); //query = query.Skip((pageIndex - 1) * pagesize).Take(pagesize); source = source.Skip((pageIndex - 1) * pagesize).Take(pagesize); //query = SortBy(query, sortOrder, sortDirection); source = SortBy(source, sortOrder, sortDirection); //int RecordCount = query.Count(); int RecordCount = source.Count(); return source.ToList(); } } public static IQueryable<T> SortBy<T>(IQueryable<T> source, string sortExpression, SortDirection direction) { if (source == null) { throw new ArgumentNullException("source"); } string methodName = "OrderBy"; if (direction == SortDirection.Descending) { methodName += "Descending"; } var paramExp = Expression.Parameter(typeof(T), String.Empty); var propExp = Expression.PropertyOrField(paramExp, sortExpression); // p => p.sortExpression var sortLambda = Expression.Lambda(propExp, paramExp); var methodCallExp = Expression.Call( typeof(Queryable), methodName, new[] { typeof(T), propExp.Type }, source.Expression, Expression.Quote(sortLambda) ); return (IQueryable<T>)source.Provider.CreateQuery(methodCallExp); } public static List<dbModel.Product> GetProductsByIds(string Ids) { using (var context = new dbModel.dbModel()) { var products = new List<dbModel.Product>(); IQueryable<dbModel.Product> source = context.Products; List<int> ids = new List<int>(); foreach (string id in Ids.Split(',')) { //var p = new dbModel.Product(); int tempId = 0; int.TryParse(id, out tempId); if (tempId != 0) { //p.id = tempId; //products.Add(p); ids.Add(tempId); } } products = source.Where(s => ids.Contains(s.id)).ToList(); return products; } }