Search Results

Search found 923 results on 37 pages for 'messagebox'.

Page 9/37 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • How to backup database (MS SQl Server 2008) in C# without using SMO (having proplems) ?

    - by SzamDev
    Hi I have this code and it is not working but I don't why? try { saveFileDialog1.Filter = "SQL Server database backup files|*.bak"; saveFileDialog1.Title = "Database Backup"; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { SqlCommand bu2 = new SqlCommand(); SqlConnection s = new SqlConnection("Data Source=M1-PC;Initial Catalog=master;Integrated Security=True;Pooling=False"); bu2.CommandText = String.Format("BACKUP DATABASE LA TO DISK='{0}'", saveFileDialog1.FileName); s.Open(); bu2.ExecuteNonQuery(); s.Close(); MessageBox.Show("ok"); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } and I get this error : What is the proplem?

    Read the article

  • Why are there connections open to my databases?

    - by Everett
    I have a program that stores user projects as databases. Naturally, the program should allow the user to create and delete the databases as they need to. When the program boots up, it looks for all the databases in a specific SQLServer instance that have the structure the program is expecting. These database are then loaded into a listbox so the user can pick one to open as a project to work on. When I try to delete a database from the program, I always get an SQL error saying that the database is currently open and the operation fails. I've determined that the code that checks for the databases to load is causing the problem. I'm not sure why though, because I'm quite sure that all the connections are being properly closed. Here are all the relevant functions. After calling BuildProjectList, running "DROP DATABASE database_name" from ExecuteSQL fails with the message: "Cannot drop database because it is currently in use". I'm using SQLServer 2005. private SqlConnection databaseConnection; private string connectionString; private ArrayList databases; public ArrayList BuildProjectList() { //databases is an ArrayList of all the databases in an instance if (databases.Count <= 0) { return null; } ArrayList databaseNames = new ArrayList(); for (int i = 0; i < databases.Count; i++) { string db = databases[i].ToString(); connectionString = "Server=localhost\\SQLExpress;Trusted_Connection=True;Database=" + db + ";"; //Check if the database has the table required for the project string sql = "select * from TableExpectedToExist"; if (ExecuteSQL(sql)) { databaseNames.Add(db); } } return databaseNames; } private bool ExecuteSQL(string sql) { bool success = false; openConnection(); SqlCommand cmd = new SqlCommand(sql, databaseConnection); try { cmd.ExecuteNonQuery(); success = true; } catch (SqlException ae) { MessageBox.Show(ae.Message.ToString()); } closeConnection(); return success; } public void openConnection() { databaseConnection = new SqlConnection(connectionString); try { databaseConnection.Open(); } catch(Exception e) { MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void closeConnection() { if (databaseConnection != null) { try { databaseConnection.Close(); } catch (Exception e) { MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }

    Read the article

  • SQL-Calculate percentages from database table values

    - by Howard
    Hi, Im trying to calculate the percentages of selected fields from tables. Within the fields that data is numeric but I want to show the percentage value. Please help. private void btnpics_Click(object sender, EventArgs e) { try { myCon.Open(); string queryString = "SELECT FoodType.Description,FoodType.Calories, FoodType.Carbohydrate, FoodType.Fat, FoodType.Protein FROM [FoodType], [Meal] WHERE (Meal.UserID =" + userid.Text + ") AND (Meal.MealDate =" + date.Text + ");"; MessageBox.Show(queryString); loadDataGrid(queryString); } catch (Exception ex) { MessageBox.Show(ex.Message); } }

    Read the article

  • Serialization problem

    - by Falcon eyes
    Hi Every body I have a problem and want help. I have created a phonebook application and it works fine after a awhile i liked to make an upgrade for my application and i started from scratch i didn't inherit it from my old class,and i successes too ,my request "I want to migrate my contacts from the old application to the new one" ,so i made an adapter class for this reason in my new application with the following code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Windows.Forms; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; namespace PhoneBook { class Adapter { PhoneRecord PhRecord; //the new application object CTeleRecord TelRecord; //the old application object string fileName; public Adapter(string filename) { fileName = filename; } public void convert() { PhRecord = new PhoneRecord(); TelRecord = new CTeleRecord(); FileStream OpFileSt = new FileStream(fileName, FileMode.Open,FileAccess.Read); BinaryFormatter readBin = new BinaryFormatter(); for (; ; ) { try { TelRecord.ResetTheObject(); TelRecord = (CTeleRecord)readBin.Deserialize(OpFileSt); PhRecord.SetName = TelRecord.GetName; PhRecord.SetHomeNumber = TelRecord.GetHomeNumber; PhRecord.SetMobileNumber = TelRecord.GetMobileNumber; PhRecord.SetWorkNumber = TelRecord.GetWorkNumber; PhRecord.SetSpecialNumber = TelRecord.GetSpecialNumber; PhRecord.SetEmail = TelRecord.GetEmail; PhRecord.SetNotes = TelRecord.GetNotes; PhBookContainer.phBookItems.Add(PhRecord); } catch (IOException xxx) { MessageBox.Show(xxx.Message); } catch (ArgumentException tt) { MessageBox.Show(tt.Message); } //if end of file is reached catch (SerializationException x) { MessageBox.Show(x.Message + x.Source); break; } } OpFileSt.Close(); PhBookContainer.Save(@"d:\MyPhBook.pbf"); } } } the problem is when i try to read the file ctreated by my old application i receive serialization exception with this message "Unabel to find assembly 'PhoneBook,Version=1.0.0.0,Culture=neutral,PublicK eyToken=null" and the source of exceptionis mscorlib. when i read the same file with my old application(Which is the origin of the file)i have no problem and idon't know what to do to make my adapter class work.so can somebody help please.

    Read the article

  • Why the current working directory changes when use the Open file dialog in XP?

    - by RRUZ
    I have found an strange behavior when use the open file dialog in c#. If use this code in Windows XP the current working directory changes to the path of the selected file, however if you run this code in windows 7 the current working directory does not change. private void button1_Click(object sender, EventArgs e) { MessageBox.Show(string.Format("Current Directory {0}",Directory.GetCurrentDirectory()), "My Application",MessageBoxButtons.OK, MessageBoxIcon.Asterisk); DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog and get result. if (result == DialogResult.OK) { } MessageBox.Show(string.Format("Current Directory {0}", Directory.GetCurrentDirectory()), "My Application", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } Anybody know the reason for this behavior? Why the current directoiry changes in XP and not in windows 7?

    Read the article

  • Email goes to spam

    - by VICKY Shastri
    i am creating an simple mail sending application in c# windows form application. My application works well but when i send email to my yahoo account it goes to spam not in inbox but if i send email to gmail it goes to inbox. please tell me what i need to do to send email in inbox below is my code: try { // setup mail message MailMessage message = new MailMessage(); message.From = new MailAddress(textBox1.Text); message.To.Add(new MailAddress(textBox2.Text)); message.Subject = textBox3.Text; message.Body = richTextBox1.Text; // setup mail client SmtpClient mailClient = new SmtpClient("smtp.mail.yahoo.com"); mailClient.Credentials = new NetworkCredential(textBox1.Text, "password"); // send message mailClient.Send(message); MessageBox.Show("Sent"); } catch(Exception) { MessageBox.Show("Error"); }

    Read the article

  • Running Network Application on port Server side give me error how can i solve it?

    - by Phsika
    if i run Server App. Exception occurs: on Dinle.Start() System.Net.SocketException - Only one usage of each socket address (protocol/network address/port) is normally permitted How can i solve this error? Server.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; namespace Server { public partial class Server : Form { Thread kanal; public Server() { InitializeComponent(); try { kanal = new Thread(new ThreadStart(Dinle)); kanal.Start(); kanal.Priority = ThreadPriority.Normal; this.Text = "Kanla Çalisti"; } catch (Exception ex) { this.Text = "kanal çalismadi"; MessageBox.Show("hata:" + ex.ToString()); kanal.Abort(); throw; } } private void Server_Load(object sender, EventArgs e) { Dinle(); } private void btn_Listen_Click(object sender, EventArgs e) { Dinle(); } void Dinle() { // IPAddress localAddr = IPAddress.Parse("localhost"); // TcpListener server = new TcpListener(port); // server = new TcpListener(localAddr, port); //TcpListener Dinle = new TcpListener(localAddr,51124); TcpListener Dinle = new TcpListener(51124); try { while (true) { Dinle.Start(); Exception is occured. Socket Baglanti = Dinle.AcceptSocket(); if (!Baglanti.Connected) { MessageBox.Show("Baglanti Yok"); } else { TcpClient tcpClient = Dinle.AcceptTcpClient(); if (tcpClient.ReceiveBufferSize 0) { byte[] Dizi = new byte[250000]; Baglanti.Receive(Dizi, Dizi.Length, 0); string Yol; saveFileDialog1.Title = "Dosyayi kaydet"; saveFileDialog1.ShowDialog(); Yol = saveFileDialog1.FileName; FileStream Dosya = new FileStream(Yol, FileMode.Create); Dosya.Write(Dizi, 0, Dizi.Length - 20); Dosya.Close(); listBox1.Items.Add("dosya indirildi"); listBox1.Items.Add("Dosya Boyutu=" + Dizi.Length.ToString()); listBox1.Items.Add("Indirilme Tarihi=" + DateTime.Now); listBox1.Items.Add("--------------------------------"); } } } } catch (Exception ex) { MessageBox.Show("hata:" + ex.ToString()); } } } }

    Read the article

  • Problem using pantheios file stock back end

    - by Tanuj
    I am trying to use pantheios file stock back end to log from my dll in c++. The file gets created but nothing gets written to the file. Here is a snippet of my code if (pantheios::pantheios_init() < 0) { MessageBox(NULL, "Init Failed", "fvm", MB_OK); }else { MessageBox(NULL, "Init Passed", "fvm", MB_OK); pantheios::log_INFORMATIONAL("Logger enabled!"); } DWORD pid = GetCurrentProcessId(); sprintf_s(moduleName, sizeof(moduleName), "C:\\%d.log", pid); pantheios_be_file_setFilePath(moduleName, PANTHEIOS_BE_FILE_F_TRUNCATE,PANTHEIOS_BE_FILE_F_TRUNCATE, PANTHEIOS_BEID_LOCAL); pantheios::log(pantheios::debug, "Entering main"); I get the Init Passed message box but no log statements are dumped in the file.

    Read the article

  • Refresh databases data

    - by Simon
    How can i refresh the data from my database(ms access) in c# using windows form aplication? part of the code where i insert the data : insertCommand.Parameters.Add("@ID_uporabnika", OleDbType.Integer).Value = Convert.ToInt32(textBox6.Text); insertCommand.Parameters.Add("@datum", OleDbType.DBDate).Value = DateTime.Now.ToShortDateString(); insertCommand.Parameters.Add("@ID_zivila", OleDbType.Integer).Value = Convert.ToInt32(iDTextBox.Text); insertCommand.Parameters.Add("@skupaj_kalorij", OleDbType.Double).Value = Convert.ToDouble(textBox1.Text); empConnection.Open(); try { int count = insertCommand.ExecuteNonQuery(); } catch (OleDbException ex) { MessageBox.Show(ex.Message); } finally { empConnection.Close(); MessageBox.Show("zauižiti obrok je bil shranjen"); textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); textBox4.Clear(); textBox5.Clear(); } }

    Read the article

  • How to implement an EventHandler to update controls

    - by Bill
    May I ask for help with the following? I am attempting to connect and control three pieces of household electronic equipment by computer through a GlobalCache GC-100 and iTach. As you will see in the following code, I created a class-instance of GlobalCacheAdapter that communicates with each piece of equipment. Although the code seems to work well in controlling the equipment, I am having trouble updating controls with the feedback from the equipment. The procedure "ReaderThreadProc" captures the feedback; however I don't know how to update the associated TextBox with the feedback. I believe that I need to create an EventHandler to notify the TextBox of the available update; however I am uncertain as to how an EventHandler like this would be implemented. Any help wold be greatly appreciated. using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { // Create three new instances of GlobalCacheAdaptor and connect. // GC-100 (Elan) 192.168.1.70 4998 // GC-100 (TuneSuite) 192.168.1.70 5000 // GC iTach (Lighting) 192.168.1.71 4999 private GlobalCacheAdaptor elanGlobalCacheAdaptor; private GlobalCacheAdaptor tuneSuiteGlobalCacheAdaptor; private GlobalCacheAdaptor lutronGlobalCacheAdaptor; public Form1() { InitializeComponent(); elanGlobalCacheAdaptor = new GlobalCacheAdaptor(); elanGlobalCacheAdaptor.ConnectToDevice(IPAddress.Parse("192.168.1.70"), 4998); tuneSuiteGlobalCacheAdaptor = new GlobalCacheAdaptor(); tuneSuiteGlobalCacheAdaptor.ConnectToDevice(IPAddress.Parse("192.168.1.70"), 5000); lutronGlobalCacheAdaptor = new GlobalCacheAdaptor(); lutronGlobalCacheAdaptor.ConnectToDevice(IPAddress.Parse("192.168.1.71"), 4999); elanTextBox.Text = elanGlobalCacheAdaptor._line; tuneSuiteTextBox.Text = tuneSuiteGlobalCacheAdaptor._line; lutronTextBox.Text = lutronGlobalCacheAdaptor._line; } private void btnZoneOnOff_Click(object sender, EventArgs e) { elanGlobalCacheAdaptor.SendMessage("sendir,4:3,1,40000,4,1,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,181,21,800" + Environment.NewLine); } private void btnSourceInput1_Click(object sender, EventArgs e) { elanGlobalCacheAdaptor.SendMessage("sendir,4:3,1,40000,1,1,20,179,20,179,20,179,20,179,20,179,20,179,20,179,20,278,20,179,20,179,20,179,20,780" + Environment.NewLine); } private void btnSystemOff_Click(object sender, EventArgs e) { elanGlobalCacheAdaptor.SendMessage("sendir,4:3,1,40000,1,1,20,184,20,184,20,184,20,184,20,184,20,286,20,286,20,286,20,184,20,184,20,184,20,820" + Environment.NewLine); } private void btnLightOff_Click(object sender, EventArgs e) { lutronGlobalCacheAdaptor.SendMessage("sdl,14,0,0,S2\x0d"); } private void btnLightOn_Click(object sender, EventArgs e) { lutronGlobalCacheAdaptor.SendMessage("sdl,14,100,0,S2\x0d"); } private void btnChannel31_Click(object sender, EventArgs e) { tuneSuiteGlobalCacheAdaptor.SendMessage("\xB8\x4D\xB5\x33\x31\x00\x30\x21\xB8\x0D"); } private void btnChannel30_Click(object sender, EventArgs e) { tuneSuiteGlobalCacheAdaptor.SendMessage("\xB8\x4D\xB5\x33\x30\x00\x30\x21\xB8\x0D"); } } } public class GlobalCacheAdaptor { public Socket _multicastListener; public string _preferredDeviceID; public IPAddress _deviceAddress; public Socket _deviceSocket; public StreamWriter _deviceWriter; public bool _isConnected; public int _port; public IPAddress _address; public string _line; public GlobalCacheAdaptor() { } public static readonly GlobalCacheAdaptor Instance = new GlobalCacheAdaptor(); public bool IsListening { get { return _multicastListener != null; } } public GlobalCacheAdaptor ConnectToDevice(IPAddress address, int port) { if (_deviceSocket != null) _deviceSocket.Close(); try { _port = port; _address = address; _deviceSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _deviceSocket.Connect(new IPEndPoint(address, port)); ; _deviceAddress = address; var stream = new NetworkStream(_deviceSocket); var reader = new StreamReader(stream); var writer = new StreamWriter(stream) { NewLine = "\r", AutoFlush = true }; _deviceWriter = writer; writer.WriteLine("getdevices"); var readerThread = new Thread(ReaderThreadProc) { IsBackground = true }; readerThread.Start(reader); _isConnected = true; return Instance; } catch { DisconnectFromDevice(); MessageBox.Show("ConnectToDevice Error."); throw; } } public void SendMessage(string message) { try { var stream = new NetworkStream(_deviceSocket); var reader = new StreamReader(stream); var writer = new StreamWriter(stream) { NewLine = "\r", AutoFlush = true }; _deviceWriter = writer; writer.WriteLine(message); var readerThread = new Thread(ReaderThreadProc) { IsBackground = true }; readerThread.Start(reader); } catch { MessageBox.Show("SendMessage() Error."); } } public void DisconnectFromDevice() { if (_deviceSocket != null) { try { _deviceSocket.Close(); _isConnected = false; } catch { MessageBox.Show("DisconnectFromDevice Error."); } _deviceSocket = null; } _deviceWriter = null; _deviceAddress = null; } private void ReaderThreadProc(object state) { var reader = (StreamReader)state; try { while (true) { var line = reader.ReadLine(); if (line == null) break; _line = _line + line + Environment.NewLine; } // Need to create EventHandler to notify the TextBoxes to update with _line } catch { MessageBox.Show("ReaderThreadProc Error."); } } }

    Read the article

  • ShowDialog returns immediately after a handled exception in .net compact framework

    - by leiz
    The problem I am having is that for some reason ShowDialog returns immediately after handle an exception. However, it works for MessageBox.Show() or at the second time I call ShowDialog. What is the best workaround for this problem? I was only able to find this. And I cannot believe that no one else has this issue. I am using .net compact framework 3.5. Sample code: try { using(SomeForm f = new SomeForm()) { f.ShowDialog(); } } catch(SomeException) { using(SomeOtherForm f = new SomeOtherForm()) { f.ShowDialog(); // this returns immediately // if this is MessageBox.Show(), it works correctly. f.ShowDialog(); // then this works fine } }

    Read the article

  • Add / Remove the default documents of IIS7 using vb.net 2.0 windows application

    - by Senthil S R
    Hai, I wrote the coding for add / remove the default documents of IIS7 in vb.net 2.0 windows application using Microsoft.Web.Administration.dll. The coding is working fine. After adding a new document, the messagebox showing that newly added document name. Simillarly if I remove any document, the messagebox not showing that document name. So that I am saying, the coding is working fine. Now the problem is, I can't see the newly added document name in II7 Manager GUI. The next proplem is, my website not access that newly added document. Please can any body suggest for these problems. What the mistake I did the vb.net 2.0 windows application coding and what are the modifications I need to do? Thanks in advance.

    Read the article

  • Using events in threads between processes - C

    - by Jamie Keeling
    Hello all! I have an application consisting of two windows, one communicates to the other and sends it a struct constaining two integers (In this case two rolls of a dice). I will be using events for the following circumstances: Process a sends data to process b, process b displays data Process a closes, in turn closing process b Process b closes a, in turn closing process a I have noticed that if the second process is constantly waiting for the first process to send data then the program will be just sat waiting, which is where the idea of implementing threads on each process occurred and I have started to implement this already. The problem i'm having is that I don't exactly have a lot of experience with threads and events so I'm not sure of the best way to actually implement what I want to do. Following is a small snippet of what I have so far in the producer application; Create thread: case IDM_FILE_ROLLDICE: { hDiceRoll = CreateThread( NULL, // lpThreadAttributes (default) 0, // dwStackSize (default) ThreadFunc(hMainWindow), // lpStartAddress NULL, // lpParameter 0, // dwCreationFlags &hDiceID // lpThreadId (returned by function) ); } break; The data being sent to the other process: DWORD WINAPI ThreadFunc(LPVOID passedHandle) { HANDLE hMainHandle = *((HANDLE*)passedHandle); WCHAR buffer[256]; LPCTSTR pBuf; LPVOID lpMsgBuf; LPVOID lpDisplayBuf; struct diceData storage; HANDLE hMapFile; DWORD dw; //Roll dice and store results in variable storage = RollDice(); hMapFile = CreateFileMapping( (HANDLE)0xFFFFFFFF, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) BUF_SIZE, // maximum object size (low-order DWORD) szName); // name of mapping object if (hMapFile == NULL) { dw = GetLastError(); MessageBox(hMainHandle,L"Could not create file mapping object",L"Error",MB_OK); return 1; } pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUF_SIZE); if (pBuf == NULL) { MessageBox(hMainHandle,L"Could not map view of file",L"Error",MB_OK); CloseHandle(hMapFile); return 1; } CopyMemory((PVOID)pBuf, &storage, (_tcslen(szMsg) * sizeof(TCHAR))); //_getch(); MessageBox(hMainHandle,L"Completed!",L"Success",MB_OK); UnmapViewOfFile(pBuf); return 0; } I'm trying to find out how I would integrate an event with the threaded code to signify to the other process that something has happened, I've seen an MSDN article on using events but it's just confused me if anything, I'm coming up on empty whilst searching on the internet too. Thanks for any help Edit: I can only use the Create/Set/Open methods for events, sorry for not mentioning it earlier.

    Read the article

  • Implementing events to communicate between two processes - C

    - by Jamie Keeling
    Hello all! I have an application consisting of two windows, one communicates to the other and sends it a struct constaining two integers (In this case two rolls of a dice). I will be using events for the following circumstances: Process a sends data to process b, process b displays data Process a closes, in turn closing process b Process b closes a, in turn closing process a I have noticed that if the second process is constantly waiting for the first process to send data then the program will be just sat waiting, which is where the idea of implementing threads on each process occurred and I have started to implement this already. The problem i'm having is that I don't exactly have a lot of experience with threads and events so I'm not sure of the best way to actually implement what I want to do. Following is a small snippet of what I have so far in the producer application; Create thread: case IDM_FILE_ROLLDICE: { hDiceRoll = CreateThread( NULL, // lpThreadAttributes (default) 0, // dwStackSize (default) ThreadFunc(hMainWindow), // lpStartAddress NULL, // lpParameter 0, // dwCreationFlags &hDiceID // lpThreadId (returned by function) ); } break; The data being sent to the other process: DWORD WINAPI ThreadFunc(LPVOID passedHandle) { HANDLE hMainHandle = *((HANDLE*)passedHandle); WCHAR buffer[256]; LPCTSTR pBuf; LPVOID lpMsgBuf; LPVOID lpDisplayBuf; struct diceData storage; HANDLE hMapFile; DWORD dw; //Roll dice and store results in variable storage = RollDice(); hMapFile = CreateFileMapping( (HANDLE)0xFFFFFFFF, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) BUF_SIZE, // maximum object size (low-order DWORD) szName); // name of mapping object if (hMapFile == NULL) { dw = GetLastError(); MessageBox(hMainHandle,L"Could not create file mapping object",L"Error",MB_OK); return 1; } pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUF_SIZE); if (pBuf == NULL) { MessageBox(hMainHandle,L"Could not map view of file",L"Error",MB_OK); CloseHandle(hMapFile); return 1; } CopyMemory((PVOID)pBuf, &storage, (_tcslen(szMsg) * sizeof(TCHAR))); //_getch(); MessageBox(hMainHandle,L"Completed!",L"Success",MB_OK); UnmapViewOfFile(pBuf); return 0; } I'm trying to find out how I would integrate an event with the threaded code to signify to the other process that something has happened, I've seen an MSDN article on using events but it's just confused me if anything, I'm coming up on empty whilst searching on the internet too. Thanks for any help Edit: I can only use the Create/Set/Open methods for events, sorry for not mentioning it earlier.

    Read the article

  • How to Convert Date(from date time input field) to another date format in C#?

    - by Saeed Khan
    I have Date time input field from where I am taking date and converting it to another format, my code for that try { DateTime dt = dtiFrom.Value.Date; string format = "DD-MM-YYYY"; // Use this format MessageBox.Show(dt.ToString(format)); // here its shows result as DD-10-YYYY DateTime dt1 = Convert.ToDateTime(dt.ToString(format)); // here Error "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0." } catch (Exception ee) { MessageBox.Show(ee.Message, "Error Message!"); } I am not able to convert date according to my format. please could any body help me in code or suggest me some code. thanks in advance

    Read the article

  • how to stop this message on pressing CTRL + ALT + DEL?

    - by moon
    i have the following code to disable task manager of windows xp but it still displays a message the "task manager is disabled" and we have to press ok how can i disable even this message ; i want that when any one presses ALT+CLRT+ DEL nothing happens even no message dialog. HKEY hMykey; DWORD pDWDisp; unsigned char cData[1]; cData[0]='1'; LONG lRes = RegCreateKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\system", 0,"DisableTaskMgr",REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS, NULL,&hMykey,&pDWDisp); // Open a key for edit if(lRes != ERROR_SUCCESS) { MessageBox(0,"Error opening key","",MB_OK); exit(0);// Shutdown on fail }//End if lRes = RegSetValueEx(hMykey,"DisableTaskMgr",0,REG_DWORD, (LPBYTE)cData,sizeof(cData));// Add your key value if(lRes != ERROR_SUCCESS) { MessageBox(0,"Error saving record","",MB_OK); RegCloseKey(hMykey); exit(0);// Shutdown on fail }//End if

    Read the article

  • Ideas on implementing threads and cross process communication. - C

    - by Jamie Keeling
    Hello all! I have an application consisting of two windows, one communicates to the other and sends it a struct constaining two integers (In this case two rolls of a dice). I will be using events for the following circumstances: Process a sends data to process b, process b displays data Process a closes, in turn closing process b Process b closes a, in turn closing process a I have noticed that if the second process is constantly waiting for the first process to send data then the program will be just sat waiting, which is where the idea of implementing threads on each process occured. I have already implemented a thread on the first process which currently creates the data to send to the second process and makes it available to the second process. The problem i'm having is that I don't exactly have a lot of experience with threads and events so I'm not sure of the best way to actually implement what I want to do. Following is a small snippet of what I have so far in the producer application; Rolling the dice and sending the data: case IDM_FILE_ROLLDICE: { hDiceRoll = CreateThread( NULL, // lpThreadAttributes (default) 0, // dwStackSize (default) ThreadFunc(hMainWindow), // lpStartAddress NULL, // lpParameter 0, // dwCreationFlags &hDiceID // lpThreadId (returned by function) ); } break; The data being sent to the other process: DWORD WINAPI ThreadFunc(LPVOID passedHandle) { HANDLE hMainHandle = *((HANDLE*)passedHandle); WCHAR buffer[256]; LPCTSTR pBuf; LPVOID lpMsgBuf; LPVOID lpDisplayBuf; struct diceData storage; HANDLE hMapFile; DWORD dw; //Roll dice and store results in variable storage = RollDice(); hMapFile = CreateFileMapping( (HANDLE)0xFFFFFFFF, // use paging file NULL, // default security PAGE_READWRITE, // read/write access 0, // maximum object size (high-order DWORD) BUF_SIZE, // maximum object size (low-order DWORD) szName); // name of mapping object if (hMapFile == NULL) { dw = GetLastError(); MessageBox(hMainHandle,L"Could not create file mapping object",L"Error",MB_OK); return 1; } pBuf = (LPTSTR) MapViewOfFile(hMapFile, // handle to map object FILE_MAP_ALL_ACCESS, // read/write permission 0, 0, BUF_SIZE); if (pBuf == NULL) { MessageBox(hMainHandle,L"Could not map view of file",L"Error",MB_OK); CloseHandle(hMapFile); return 1; } CopyMemory((PVOID)pBuf, &storage, (_tcslen(szMsg) * sizeof(TCHAR))); //_getch(); MessageBox(hMainHandle,L"Completed!",L"Success",MB_OK); UnmapViewOfFile(pBuf); return 0; } I'd like to think I am at least on the right lines, although for some reason when the application finishes creating the thread it hits the return DefWindowProc(hMainWindow, message, wParam, lParam); it crashes saying there's no more source code for the current location. I know there are certain ways to implement things but as I've mentioned I'm not sure if i'm doing this the right way, has anybody else tried to do the same thing? Thanks!

    Read the article

  • What common routines do you put in your Program.cs for C#

    - by Rick
    I'm interested in any common routine/procedures/methods that you might use in you Program.cs when creating a .NET project. For instance I commonly use the following code in my desktop applications to allow easy upgrades, single instance execution and friendly and simple reporting of uncaught system application errors. using System; using System.Diagnostics; using System.Threading; using System.Windows.Forms; namespace NameoftheAssembly { internal static class Program { /// <summary> /// The main entry point for the application. Modified to check for another running instance on the same computer and to catch and report any errors not explicitly checked for. /// </summary> [STAThread] private static void Main() { //for upgrading and installing newer versions string[] arguments = Environment.GetCommandLineArgs(); if (arguments.GetUpperBound(0) > 0) { foreach (string argument in arguments) { if (argument.Split('=')[0].ToLower().Equals("/u")) { string guid = argument.Split('=')[1]; string path = Environment.GetFolderPath(Environment.SpecialFolder.System); var si = new ProcessStartInfo(path + "\\msiexec.exe", "/x" + guid); Process.Start(si); Application.Exit(); } } //end of upgrade } else { bool onlyInstance = false; var mutex = new Mutex(true, Application.ProductName, out onlyInstance); if (!onlyInstance) { MessageBox.Show("Another copy of this running"); return; } AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Application.ThreadException += ApplicationThreadException; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { try { var ex = (Exception) e.ExceptionObject; MessageBox.Show("Whoops! Please contact the developers with the following" + " information:\n\n" + ex.Message + ex.StackTrace, " Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } catch (Exception) { //do nothing - Another Exception! Wow not a good thing. } finally { Application.Exit(); } } public static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e) { try { MessageBox.Show("Whoops! Please contact the developers with the following" + " information:\n\n" + e.Exception.Message + e.Exception.StackTrace, " Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } catch (Exception) { //do nothing - Another Exception! Wow not a good thing. } } } } I find these routines to be very helpful. What methods have you found helpful in Program.cs?

    Read the article

  • GetdataBy date doesn't work Why?

    - by vp789
    I am trying to pull the data by date in vb.net. It is not throwing the error nor giving any result. Whereas It shows the results in table adapter configuration wizard when I try through query builder. I am using date time picker in the form. But I have formatted the date in the database as date.I am puzzled. Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click Try Dim dt As Date = CDate(tspTextDate.Text) Me.Bank_transactionsTableAdapter.GetDataByDate(dt) 'Catch ex As Exception Catch ex As FormatException MessageBox.Show("date is wrong", "Entry Error") Catch ex As SqlException MessageBox.Show("SQL Server error#" & ex.Number _ & ":" & ex.Message, ex.GetType.ToString) End Try End Sub rows of data BT102 4/5/2010 BKS 200.00 1200.00 1400.00 BT103 4/5/2010 BKS 200.00 1400.00 1600.00 BT105 4/6/2010 BKS 200.00 1800.00 1800.00

    Read the article

  • How to resolve error "Run-Time Check Failure #3"?

    - by karikari
    I am working on MS Visual Studio. I keep on getting this error: "Run-Time Check Failure #3 - The variable 'test' is being used without being initialized." I don't have any idea how to solve this. Here is the code that I'm currently tries to modify: STDMETHODIMP CButtonDemoBHO::Exec(const GUID*, DWORD nCmdID, DWORD d, VARIANTARG*, VARIANTARG* pvaOut) { CRebarHandler *test; switch (nCmdID){ case BUTTON_PRESSED: MessageBox(m_hWnd, L"You have pressed the button", L"Button Pressed", MB_OK); test->findButton(m_hWnd); test->setmenu(); break; case MENU_ITEM_SELECT: MessageBox(m_hWnd, L"You have simulated a button press with the menu ", L"Menu Pressed", MB_OK); break; } return S_OK; }

    Read the article

  • No matter what, I can't get this stupid progress bar to update from a thread!

    - by Synthetix
    I have a Windows app written in C (using gcc/MinGW) that works pretty well except for a few UI problems. One, I simply cannot get the progress bar to update from a thread. In fact, I probably can't get ANY UI stuff to update. Basically, I have a spawned thread that does some processing, and from that thread I attempt to update the progress bar in the main thread. I tried this by using PostMessage() to the main hwnd, but no luck even though I can do other things like open message boxes. However, it's unclear whether the message box is getting called within the thread or on the main thread. Here's some code: //in header/globally accessible HWND wnd; //main application window HWND progress_bar; //progress bar typedef struct { //to pass to thread DWORD mainThreadId; HWND mainHwnd; char *filename; } THREADSTUFF; //callback function LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){ switch(msg){ case WM_CREATE:{ //create progress bar progress_bar = CreateWindowEx( 0, PROGRESS_CLASS, (LPCTSTR)NULL, WS_CHILD | WS_VISIBLE, 79,164,455,15, hwnd, (HMENU)20, NULL, NULL); break; } case WM_COMMAND:{ if(LOWORD(wParam)==2){ //do some processing in a thread //struct of stuff I need to pass to thread THREADSTUFF *threadStuff; threadStuff = (THREADSTUFF*)malloc(sizeof(*threadStuff)); threadStuff->mainThreadId = GetCurrentThreadId(); threadStuff->mainHwnd = hwnd; threadStuff->filename = (void*)&filename; hThread1 = CreateThread(NULL,0,convertFile (LPVOID)threadStuff,0,NULL); }else if(LOWORD(wParam)==5){ //update progress bar MessageBox(hwnd,"I got a message!", "Message", MB_OK | MB_ICONINFORMATION); PostMessage(progress_bar,PBM_STEPIT,0,CLR_DEFAULT); } break; } } } This all seems to work okay. The problem is in the thread: DWORD WINAPI convertFile(LPVOID params){ //get passed params, this works perfectly fine THREADSTUFF *tData = (THREADSTUFF*)params; MessageBox(tData->mainHwnd,tData->filename,"File name",MB_OK | MB_ICONINFORMATION); //yep PostThreadMessage(tData->mainThreadId,WM_COMMAND,5,0); //only shows message PostMessage(tData->mainHwnd,WM_COMMAND,5,0); //only shows message } When I say, "only shows message," that means the MessageBox() function in the callback works, but not the PostMessage() to update the position of the progress bar. What am I missing?

    Read the article

  • WP7 databinding displays int but not string?

    - by user1794106
    Whenever I test my app.. it binds the data from Note class and displays it if it isn't a string. But for the string variables it wont bind. What am I doing wrong? Inside my main: <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <ListBox x:Name="Listbox" SelectionChanged="listbox_SelectionChanged" ItemsSource="{Binding}"> <ListBox.ItemTemplate> <DataTemplate> <Border Width="800" MinHeight="60"> <StackPanel> <TextBlock x:Name="Title" VerticalAlignment="Center" FontSize="{Binding TextSize}" Text="{Binding Name}"/> <TextBlock x:Name="Date" VerticalAlignment="Center" FontSize="{Binding TextSize}" Text="{Binding Modified}"/> </StackPanel> </Border> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </Grid> in code behind: protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { MessageBox.Show("enters onNav Main"); DataContext = null; DataContext = Settings.NotesList; Settings.CurrentNoteIndex = -1; Listbox.SelectedIndex = -1; if (Settings.NotesList != null) { if (Settings.NotesList.Count == 0) { Notes.Text = "No Notes"; } else { Notes.Text = ""; } } } and public static class Settings { public static ObservableCollection<Note> NotesList; static IsolatedStorageSettings settings; private static int currentNoteIndex; static Settings() { NotesList = new ObservableCollection<Note>(); settings = IsolatedStorageSettings.ApplicationSettings; MessageBox.Show("enters constructor settings"); } notes class: public class Note { public DateTimeOffset Modified { get; set; } public string Title { get; set; } public string Content { get; set; } public int TextSize { get; set; } public Note() { MessageBox.Show("enters Note Constructor"); Modified = DateTimeOffset.Now; Title = "test"; Content = "test"; TextSize = 32; } }

    Read the article

  • FILE_NOT_FOUND when trying to open COM port C++

    - by Moutabreath
    I am trying to open a com port for reading and writing using C++ but I can't seem to pass the first stage of actually opening it. I get an INVALID_HANDLE_VALUE on the handle with GetLastError FILE_NOT_FOUND. I have searched around the web for a couple of days I'm fresh out of ideas. I have searched through all the questions regarding COM on this website too. I have scanned through the existing ports (or so I believe) to get the name of the port right. I also tried combinations of _T("COM1") with the slashes, without the slashes, with colon, without colon and without the _T I'm using windows 7 on 64 bit machine. this is the code i got I'll be glad for any input on this void SendToCom(char* data, int len) { DWORD cbNeeded = 0; DWORD dwPorts = 0; EnumPorts(NULL, 1, NULL, 0, &cbNeeded, &dwPorts); //What will be the return value BOOL bSuccess = FALSE; LPCSTR COM1 ; BYTE* pPorts = static_cast<BYTE*>(malloc(cbNeeded)); bSuccess = EnumPorts(NULL, 1, pPorts, cbNeeded, &cbNeeded, &dwPorts); if (bSuccess){ PORT_INFO_1* pPortInfo = reinterpret_cast<PORT_INFO_1*>(pPorts); for (DWORD i=0; i<dwPorts; i++) { //If it looks like "COMX" then size_t nLen = _tcslen(pPortInfo->pName); if (nLen > 3) { if ((_tcsnicmp(pPortInfo->pName, _T("COM"), 3) == 0) ){ COM1 =pPortInfo->pName; //COM1 ="\\\\.\\COM1"; HANDLE m_hCommPort = CreateFile( COM1 , GENERIC_READ|GENERIC_WRITE, // access ( read and write) 0, // (share) 0:cannot share the COM port NULL, // security (None) OPEN_EXISTING, // creation : open_existing FILE_FLAG_OVERLAPPED, // we want overlapped operation NULL // no templates file for COM port... ); if (m_hCommPort==INVALID_HANDLE_VALUE) { DWORD err = GetLastError(); if (err == ERROR_FILE_NOT_FOUND) { MessageBox(hWnd,"ERROR_FILE_NOT_FOUND",NULL,MB_ABORTRETRYIGNORE); } else if(err == ERROR_INVALID_NAME) { MessageBox(hWnd,"ERROR_INVALID_NAME",NULL,MB_ABORTRETRYIGNORE); } else { MessageBox(hWnd,"unkown error",NULL,MB_ABORTRETRYIGNORE); } } else{ WriteAndReadPort(m_hCommPort,data); } } pPortInfo++; } } } }

    Read the article

  • Why do I get a WCF timeout even though my service call and callback are successful?

    - by KallDrexx
    I'm playing around with hooking up an in-game console to a WCF interface, so an external application can send console commands and receive console output. To accomplish this I created the following service contracts: public interface IConsoleNetworkCallbacks { [OperationContract(IsOneWay = true)] void NewOutput(IEnumerable<string> text, string category); } [ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IConsoleNetworkCallbacks))] public interface IConsoleInterface { [OperationContract] void ProcessInput(string input); [OperationContract] void ChangeCategory(string category); } On the server I implemented it with: public class ConsoleNetworkInterface : IConsoleInterface, IDisposable { public ConsoleNetworkInterface() { ConsoleManager.Instance.RegisterOutputUpdateHandler(OutputHandler); } public void Dispose() { ConsoleManager.Instance.UnregisterOutputHandler(OutputHandler); } public void ProcessInput(string input) { ConsoleManager.Instance.ProcessInput(input); } public void ChangeCategory(string category) { ConsoleManager.Instance.UnregisterOutputHandler(OutputHandler); ConsoleManager.Instance.RegisterOutputUpdateHandler(OutputHandler, category); } protected void OutputHandler(IEnumerable<string> text, string category) { var callbacks = OperationContext.Current.GetCallbackChannel<IConsoleNetworkCallbacks>(); callbacks.NewOutput(text, category); } } On the client I implemented the callback with: public class Callbacks : IConsoleNetworkCallbacks { public void NewOutput(IEnumerable<string> text, string category) { MessageBox.Show(string.Format("{0} lines received for '{1}' category", text.Count(), category)); } } Finally, I establish the service host with the following class: public class ConsoleServiceHost : IDisposable { protected ServiceHost _host; public ConsoleServiceHost() { _host = new ServiceHost(typeof(ConsoleNetworkInterface), new Uri[] { new Uri("net.pipe://localhost") }); _host.AddServiceEndpoint(typeof(IConsoleInterface), new NetNamedPipeBinding(), "FrbConsolePipe"); _host.Open(); } public void Dispose() { _host.Close(); } } and use the following code on my client to establish the connection: protected Callbacks _callbacks; protected IConsoleInterface _proxy; protected void ConnectToConsoleServer() { _callbacks = new Callbacks(); var factory = new DuplexChannelFactory<IConsoleInterface>(_callbacks, new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/FrbConsolePipe")); _proxy = factory.CreateChannel(); _proxy.ProcessInput("Connected"); } So what happens is that my ConnectToConsoleServer() is called and then it gets all the way to _proxy.ProcessInput("Connected");. In my game (on the server) I immediately see the output caused by the ProcessInput call, but the client is still stalled on the _proxy.ProcessInput() call. After a minute my client gets a JIT TimeoutException however at the same time my MessageBox message appears. So obviously not only is my command being sent immediately, my callback is being correctly called. So why am I getting a timeout exception? Note: Even removing the MessageBox call, I still have this issue, so it's not an issue of the GUI blocking the callback response.

    Read the article

  • Problem with anonymouse delegate within foreach

    - by geting
    public Form1() { InitializeComponent(); Collection<Test> tests = new Collection<Test>(); tests.Add(new Test("test1")); tests.Add(new Test("test2")); foreach (Test test in tests) { Button button = new Button(); button.Text = test.name; button.Click+=new EventHandler((object obj, EventArgs arg)=>{ this.CreateTest(test); }); this.flowLayoutPanel1.Controls.Add(button); } } public void CreateTest(Test test) { MessageBox.Show(test.name); } } when i click the button witch text is 'test1', the messagebox will show 'test2',but my expect is 'test1'. So ,would anyone please tell me why or what`s wrong with my code.

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >