|
What I was trying to do is to have my software to connect up to 4 USB Communication Box. This box would communicate with RFID tag. In some cases, the USB box would somehow loses connection and the software would detect the loss of communication to the box. Also that when the USB box is reconnected, the software would re-connect and re-communicate again. This software would ensure that the "address" would be unique from other 3 USB devices.
here's my sample code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using HID_API_Library;
using System.Security.Permissions;
namespace USB_Device_Connect_Disconnect_Test
{
public partial class Form1 : Form
{
public enum WM : uint
{
WM_DEVICECHANGE = 0x0219,
WM_PARENTNOTIFY = 0x0210,
DBT_DEVTYP_DEVICEINTERFACE = 5,
DBT_DEVTYP_HANDLE = 6,
DBT_DEVICEARRIVAL = 0x8000,
DBT_DEVICEQUERYREMOVE = 0x8001,
DBT_DEVICEREMOVECOMPLETE = 0x8004,
DBT_DEVTYP_VOLUME = 0x00000002,
DBT_DEVNODES_CHANGED = 7,
BROADCAST_QUERY_DENY = 0x424D5144,
}
byte[] Read_Input = new byte[9];
byte[] DeviceFirmwareVersion = new byte[9];
byte[] inputReport = new byte[9];
HID_API[] hid = new HID_API[4];
GroupBox[] gbDevice = new GroupBox[4];
List<string> usbDevices;
public Form1()
{
InitializeComponent();
MonitorUSBDevices();
}
int ReadPort(int deviceID, ref byte data)
{
int status = hid[deviceID].ExchangeInputAndOutputReports(ref Read_Input, ref inputReport, deviceID);
if (status == 1)
{
data = inputReport[1];
}
else
status = -530;
return status;
}
int GetDeviceFirmwareVersion(int deviceID, ref byte versionDeviceFirmware)
{
byte[] result = new byte[9];
int status = hid[deviceID].ExchangeInputAndOutputReports(ref DeviceFirmwareVersion, ref result, deviceID);
if (status == 1)
versionDeviceFirmware = result[0];
else
{
versionDeviceFirmware = 0x00;
status = -510;
}
return status;
}
int GetBoxID(int deviceID, ref byte boxId)
{
int status = ReadPort(deviceID, ref boxId);
if (status == 1)
{
boxId = (byte)~boxId;
boxId &= 0x0F;
if ((boxId & 0x08) == 0x08)
{
boxId &= 0x06;
boxId >>= 1;
boxId += 1;
}
else
{
boxId = 0;
status = -520;
}
}
else
status = -521;
return status;
}
void CreateGroupBoxes()
{
int yLoc = 12;
for (int i = 0; i < 4; i++)
{
gbDevice[i] = gb_Device0;
gbDevice[i].Location = new Point(218, yLoc);
yLoc += 106;
}
this.Controls.AddRange(gbDevice);
}
List<string> SeekHIDDevices()
{
HID_API hid_api = new HID_API();
return hid_api.EnumerateUSBDevices(0x0003, 0x0483);
}
private void MonitorUSBDevices()
{
usbDevices = SeekHIDDevices();
byte boxID = 0x00;
for (int i = 0; i < usbDevices.Count; i++)
{
hid[i] = new HID_API();
hid[i].OpenUSBDrive(usbDevices[i]);
hid[i].RegisterHidNotification(this.Handle);
}
if (usbDevices.Count >= 1)
{
GetBoxID(0, ref boxID);
lbl_BoxID0.Text = boxID.ToString("X2");
if (usbDevices.Count >= 2)
{
GetBoxID(1, ref boxID);
lbl_BoxID1.Text = boxID.ToString("X2");
if (usbDevices.Count >= 3)
{
GetBoxID(2, ref boxID);
lbl_BoxID2.Text = boxID.ToString("X2");
if (usbDevices.Count == 4)
{
GetBoxID(3, ref boxID);
lbl_BoxID3.Text = boxID.ToString("X2");
}
}
}
}
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
int devType = 0;
switch ((WM)m.Msg)
{
case WM.WM_DEVICECHANGE:
{
switch ((WM)m.WParam)
{
case WM.DBT_DEVICEARRIVAL:
{
break;
}
case WM.DBT_DEVICEREMOVECOMPLETE:
{
break;
}
case WM.DBT_DEVNODES_CHANGED:
{
HID_API hid_api = new HID_API();
List<string> usbPath = hid_api.EnumerateUSBDevices(0x0003, 0x0483);
break;
}
}
break;
}
}
base.WndProc(ref m);
}
}
}
|
|
|
|
|
try
{
con1.ConnectionString = SQLConnectionString;
if (con1.State == ConnectionState.Closed)
{
con1.Open();
}
trans = con1.BeginTransaction();
SqlCommand cmd1 = new SqlCommand(“select name from testinfo WITH(XLOCK) where ID=’” + textBox1.Text + “‘”, con1,trans);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.HasRows)
{
while (dr1.Read())
{
label1.Text = dr1["name"].ToString();
}
}
catch (Exception ee)
{
trans.Commit();
con1.Close();
MessageBox.Show(“Access By Other User “);
}
}
this is working properly ,it generate an exception which is correct , gives an message “access by another user ” ,but this system define exception required lot of time min 10 sec it take , so i want to find any other condition which will show that this row is access by another user.is there is any other parameter so i can identify that this row is exclusive lock by other user.
|
|
|
|
|
From the docs; "Specifies that exclusive locks are to be taken and held until the transaction completes." What did you lock? A row, a page or the entire table?
One doesn't need a transaction to select data; there's also nothing to commit.
GauravSatpute wrote: but this system define exception required lot of time min 10 sec it take , so i want to find any other condition which will show that this row is access by another user.is there is any other parameter so i can identify that this row is exclusive lock by other user. The default method provided by the software will be the most efficient one, I'd presume.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
The reason why it needs a few seconds is because the SqlServer tries to also complete subsequent request on the (locked) table. However, you can specify a Timeout for the SqlCommand (for example 1 Second).
Have a look at this MSDN Page (including an example): System.Data.Sqlclient.Sqlcommand.CommandTimeout.aspx[^]
|
|
|
|
|
GauravSatpute wrote: so i want to find any other condition which will show that this row is access by
another user
Which is probably a very bad idea.
What exactly is your BUSINESS case where all of the following are true
- There are two users
- They are acting on the data at the same time.
- They are modifying the data with different values.
- The above is correct behavior (thus the valid business case.)
|
|
|
|
|
I was just confusing How it works ?
|
|
|
|
|
|
Here you go[^]
The concept of recursion is pretty much that a method keeps calling itself, in c# this is can be summed up with:
public void MyMethod()
{
MyMethod();
}
Note that this will cause an exception because, for practical purposes, the program cannot execute an infinite number of methods without the method ending (technically, there is a stack which monitors method calls, by recursing you add to the stack without removing. As this has limited space, you eventually cause the stack to overflow). So you need to make sure there is an end condition that will always break the loop:
public void MyMethod(int i)
{
if(i < 10)
{
i++;
MyMethod(i)
}
}
looks reasonable. But it will get stack overflow if you start with values of i >= 10. This brings in one of the disadvantages of recursion, that sometimes getting the end condition can be hard. For a simple example it is easy, but for more complicated stuff it isn't.
The final thing to remember is, just because you can, it doesn't mean you should. Aside from performance concerns, recursive algorithms can be harder to understand than plain loops (and you can always write a loop as a recursion, and always write a recursion as a loop) so you need to decide whether the recursive solution is neater than a looping one. As an example, I'd loop across a list, but recursively traverse a tree (which can be seen as a recursive data structure).
“Education is not the piling on of learning, information, data, facts, skills, or abilities - that's training or instruction - but is rather making visible what is hidden as a seed” “One of the greatest problems of our time is that many are schooled but few are educated”
Sir Thomas More (1478 – 1535)
|
|
|
|
|
|
Recursion ->
CallMethod()
{
while (IsTrue())
{
Console.Write("Recursing...");
CallMethod();
}
Console.Write("Done");
}
|
|
|
|
|
Definition of recursion (n)
re·cur·sion
[ ri kúrzh'n ]
[See recursion]
|
|
|
|
|
I'd google recursion if I were you.
“Education is not the piling on of learning, information, data, facts, skills, or abilities - that's training or instruction - but is rather making visible what is hidden as a seed” “One of the greatest problems of our time is that many are schooled but few are educated”
Sir Thomas More (1478 – 1535)
|
|
|
|
|
On the CS106b[^] page, you'll find a Course Reader. This Reader has two chapters exclusively for Recursion, explained very well.
|
|
|
|
|
|
any one plz help me to upload xml file into the SQLServer2008
|
|
|
|
|
The Microsoft Windows search "textbox" on the top-right corner of the Window Explorer is not too efficient when searching for files. So, I thought I should write something that would provide an easily way of searching for files in your Windows directories.
There is a small application written to do a quick and smart search of files in a directory. It's still under development and your comments and contributions would be appreciated.
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.Data.OleDb;
using System.Data.SqlClient;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
FolderBrowserDialog openDir = new FolderBrowserDialog();
if (openDir.ShowDialog() == DialogResult.OK)
txtBxDir.Text = openDir.SelectedPath;
else
MessageBox.Show("Make sure you have selected a valid path name");
}
public void searchDirectory()
{
if (cmbBx.Text == "") MessageBox.Show("Input a valid file type format");
else if (txtBxDir.Text == "") MessageBox.Show("Input a valid directory pathname");
try
{
String[] arrayFileList = Directory.GetFiles(txtBxDir.Text, cmbBx.Text, SearchOption.AllDirectories);
foreach (string file in arrayFileList)
{
string fileName = file.Substring(file.LastIndexOf("\\") + 1);
txtBxResult.Text += fileName + "\r\n";
}
}
catch (IOException)
{
MessageBox.Show("Choose the correct file type");
}
}
private string getTextBoxNoFiles()
{
string noFiles = txtBxResult.Lines.Length.ToString();
return txtBxNoFiles.Text = noFiles;
}
private void btnSearch_Click(object sender, EventArgs e)
{
if (txtBxResult.Text != "")
MessageBox.Show("The Result Field is not empty");
else if (txtBxResult.Text == "")
{
searchDirectory();
getTextBoxNoFiles();
}
else
MessageBox.Show("Make sure the Result field is Empty");
}
private void saveMtd()
{
string fNames;
FileStream fStream;
SaveFileDialog saveFiles = new SaveFileDialog();
DialogResult btnClicked = saveFiles.ShowDialog();
string fileType = "Text file (*.txt)|*.txt| All files (*.*)|*.*";
fNames = saveFiles.FileName;
saveFiles.Filter = fileType;
saveFiles.FilterIndex = 2;
saveFiles.CheckPathExists = true;
saveFiles.CreatePrompt = true;
saveFiles.DefaultExt = ".txt";
saveFiles.CheckFileExists = false;
if (btnClicked == DialogResult.Cancel)
return;
if (fNames == "" || fNames == null)
MessageBox.Show("Invalid filename", "File Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
else
{
try
{
fStream = new FileStream(fNames, FileMode.Create, FileAccess.Write);
string[] fileContent = txtBxResult.Lines;
BinaryWriter fbinContent = new BinaryWriter(fStream);
for (int i = 0; i < fileContent.Length; i++)
{
fbinContent.Write(fileContent[i] + "\r\n");
}
if (fbinContent == null)
fbinContent.Close();
if (fStream == null)
fStream.Close();
}
catch (IOException)
{
MessageBox.Show("Error: File cannot be written or not found", "File Error");
}
}
}
private void button1_Click(object sender, EventArgs e)
{
saveMtd();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtBxResult.Clear();
}
private void load()
{
String[] txtBxArr = txtBxResult.Lines;
string txtcombo = cmbBx.Text;
for (int i = 0; i < txtBxArr.Length; i++)
{
string cmdLoad = null;
switch (txtcombo)
{
case "*.pdf":
cmdLoad = "INSERT INTO tblFileType (AcrobatReader)" +
"VALUES ('" + txtBxArr[i] + "')";
break;
case "*.txt":
cmdLoad = "INSERT INTO tblFileType (TextDocuments)" +
"VALUES ('" + txtBxArr[i] + "')";
break;
case "*.doc":
cmdLoad = "INSERT INTO tblFileType (MicrosoftWord)" +
"VALUES ('" + txtBxArr[i] + "')";
break;
case "*.mp3":
cmdLoad = "INSERT INTO tblFileType (Musical)" +
"VALUES ('" + txtBxArr[i] + "')";
break;
default:
break;
}
try
{
OleDbConnection loadCon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=myFilesdb.mdb;");
loadCon.Open();
OleDbCommand dbcom = new OleDbCommand(cmdLoad, loadCon);
OleDbDataAdapter dbAdap = new OleDbDataAdapter();
dbAdap.InsertCommand = dbcom;
dbAdap.SelectCommand = dbcom;
DataSet myFiledbDataSet = new DataSet();
dbAdap.Fill(myFiledbDataSet);
loadCon.Close();
}
catch
{
MessageBox.Show("Click the LOAD button again");
}
}
return;
}
private void btnLoad_Click(object sender, EventArgs e)
{
load();
}
private void button3_Click(object sender, EventArgs e)
{
Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void txtBxSearch_TextChanged(object sender, EventArgs e)
{
}
private void find()
{
try
{
string[] result = txtBxResult.Lines;
int j = txtBxResult.Lines.Length;
for (int i = 0; i < txtBxResult.Lines.Length; i++)
{
string found = result[i];
bool files = found.Contains(txtBxSearch.Text);
if (files)
{
i++;
MessageBox.Show("This book " + found + " is available" + " at position " + i);
txtBxResult.ScrollToCaret();
int index = found.IndexOf(txtBxSearch.Text, found.Length - txtBxSearch.Text.Length, txtBxSearch.Text.Length);
txtBxResult.Select(txtBxSearch.Text.Length + index, txtBxSearch.Text.Length);
i--;
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
private void txtBxNoFiles_TextChanged(object sender, EventArgs e)
{
}
private void btnFind_Click(object sender, EventArgs e)
{
find();
}
}
}
The "find" method should search within the ResultTextBox then select and highlight it.
modified 3-Jun-13 6:59am.
|
|
|
|
|
If you have a question then please edit the above and add it to your post. If this is your suggested improvement for Windows Explorer, then write an article or Tip and post it in the article submission section[^].
Use the best guess
|
|
|
|
|
This is C# *discussions* so I think it's ok if he doesn't have a question and is just looking for general advice. Right? Probably not gonna get it, but I think it's a valid post for this section, and shouldn't the "questions" really be going to the quick answers section or on Stack Overflow?
This is the kind of thing I'd love to see here, or anywhere really... code discussions and critique is much more fun than answering dumb questions.
|
|
|
|
|
Jasmine2501 wrote: This is C# *discussions* so I think it's ok if he doesn't have a question Not according to http://www.codeproject.com/Messages/1278604/How-to-get-an-answer-to-your-question.aspx[^].
Jasmine2501 wrote: and shouldn't the "questions" really be going to the quick answers section or on Stack Overflow? No.
Jasmine2501 wrote: This is the kind of thing I'd love to see here, or anywhere really... code discussions and critique is much more fun than answering dumb questions. Then I suspect you are at the wrong place.
Use the best guess
|
|
|
|
|
Yeah I read that, but it doesn't really make sense to have a forum if that's what it is. QA is done on Stack Overflow. This site has no purpose if it doesn't allow discussion. I think it's a good post.
|
|
|
|
|
Jasmine2501 wrote: Yeah I read that, but it doesn't really make sense to have a forum if that's what it is. Well it's been like that since Chris set it up, and everyone seems happy that it is. I don't think changing it now would go down well with the membership.
Use the best guess
|
|
|
|
|
But I take that as a "sticky" with just plain good advice. It doesn't say anywhere that "this is the only thing you're allowed to do here" it's just information about how to ask good questions. I've been here many years, and we used to have good discussions, back when Chris set it up, and everyone was happy, yes, you're right about that. I clicked on a tab that says "discussions" to get here. Should be orange at the top of the page right now.
|
|
|
|
|
Jasmine2501 wrote: I clicked on a tab that says "discussions" to get here. Should be orange at the top of the page right now. Big deal, it is titled "discussions", but everyone (apart from you) seems to accept that it actually means question and answer type discussions about technical problems, in fact the readmes at the top make it reasonably clear what the forum is used for.
OK, you don't like that, so post a request in Bugs & Sugs, write a paper on it, or create a survey, because in a day or so this thread will disappear off the front page and be lost forever.
Use the best guess
|
|
|
|
|
I think that is because people don't care about learning and exploring, they just want someone else to do their job. I don't see anywhere that it's a rule.
|
|
|
|
|
Jasmine2501 wrote: I don't see anywhere that it's a rule. You also don't see anyone supporting your view.
Use the best guess
|
|
|
|
|