|
http://www.devhood.com/tutorials/tutorial_details.aspx?tutorial_id=75 here you go
Best regards
Lasse Espeholt
|
|
|
|
|
Thank You very much espeholt_jr.
|
|
|
|
|
hi,
I am using richtextbox control and in button click this is the code
if (richTextBox1.CanUndo == true)
{
richTextBox1.Undo();
richTextBox1.ClearUndo();
}
This code clearing the entire text in richtextbox in single click.
But I want it should undo chratcer by chracter.
pls help me
with regards
prasad
|
|
|
|
|
Search the articles for "undo"; there are some here on CP that cover the support of undo/redo actions.
"Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning." - Rick Cook www.troschuetz.de
|
|
|
|
|
Hey everyone,
I'm having a hard time getting my program to wait for an acknowledgment from a piece of hardware. An eventhandler in my program sends off a message to the box, and resends until an ack is received. What is the best way to handle this? I'm trying to use threads, which I am unexperienced with. Is there an issue I should be aware of when trying to do this within an eventhandler?
Thanks so much
|
|
|
|
|
Hi,
the user interface is handled by the "UI thread"; it looses good responsiveness
as soon as your UI thread is busy for more than say 100 milliseconds, and
it is completely ruined when the thread is busy for several seconds.
So if your hardware communication typically needs longer than that, you should
use a separate thread for it. Best would be to create a class that models
your hardware and contains all necessary threading stuff, so it remains hidden
from the main app. Of course, using one or more additional threads requires
an asyncrhonous API, i.e. one that splits operations in two parts:
order something (without waiting for it),
then collect results (which may be null since not yet finished).
Try using only one additional thread for your piece of hardware, since having
multiple threads interact with it would complicate matters.
You may want to implement a mutex that prevents your main app from ordering
a second operation before the first operation has finished.
Hope this helps.
|
|
|
|
|
The method to dealing with this problem efficiently is to have a separate thread that waits for responses from your device. When this thread receives the response, its validity can be confirmed, then you can send the data up to the UI (if indeed that is where the data is to go). In the UI code you need to do the invoke on the method that is updating the control.
The method I used in the past to block execution was to put the send command in a separate thread which reset a manual reset event, then make the call, and wait for the receive thread to signal. But this wait was not indefinite. I always put a timeout on the wait so that other sends would not be delayed indefinitely (the case where: what happens when the device is switched off?). In the receive thread, after the reply has been validated, the manual reset event can be signalled (set).
Using the method described above, allows the UI to continue while the threads are waiting for their turn in action.
Phil
|
|
|
|
|
I have an application that is reading thousands of rows form an access database running calculations then updating the data. I'm using an Async. Design pattern that I'd found on MSDN and am getting my butt handed to me.
public void StartRecalculation() {<br />
try {<br />
FillArrayList();<br />
for ( int num = 0; num < m_Manifest.Count; num++ ) {<br />
Guid taskId = Guid.NewGuid();<br />
<br />
this.CalculateStartAsync( Int32.Parse( m_Manifest[ num ].ToString() ), taskId );<br />
}
}
catch ( Exception ex ) {<br />
AddToErrorReport( ex.ToString() );<br />
}
}
<br />
public void CalculateStartAsync( int _ticket, object taskId ) {<br />
AsyncOperation asyncOp = AsyncOperationManager.CreateOperation( taskId );<br />
<br />
lock ( userStateToLifetime.SyncRoot ) {<br />
if ( userStateToLifetime.Contains( taskId ) ) {<br />
throw new ArgumentException( "Task ID parameter must be unique", "taskId" ); <br />
}
<br />
userStateToLifetime[ taskId ] = asyncOp;<br />
}
<br />
WorkerEventHandler workerDelegate = new WorkerEventHandler( CalculateWorker );<br />
workerDelegate.BeginInvoke( _ticket, asyncOp, null, null );<br />
}
My question is when creating the WorkerEventHandler ie..
WorkerEventHandler workerDelegate = new WorkerEventHandler( CalculateWorker );
And then calling the BeginInvoke
workerDelegate.BeginInvoke( _ticket, asyncOp, null, null );
Is this creating a new instance of the CalculateWorker Method and other referenced methods?
Will I need to isolate my tableAdapters to each method and create new each time or will I be able to us a global Dataset to store and manipulate the inforamtion.
I'm having trouble completing anything within my database. I'm getting random rows not found and outOfIndex exceptions. If anyone has any advice on the topic, please help.
thanks.
I'm listening but I only speak GEEK.
|
|
|
|
|
Hi Arejay,
I am not a db specialist at all, but this may help:
your code starts a number of threads each executing the "CalculateWorker" method.
BTW: methods dont get instantiated, they just get executed, using the local context
(e.g. the stack belonging to the executing thread).
So the app has several threads executing the same code, if that code refers
to global data (all your class members) you may get concurrency problems.
If for instance you create and use some object (maybe a table adapter) and
suddenly that object gets manipulated by multiple threads, anything can happen.
Rather than using such shared data (and trying to add all necessary locks), I
would advise to give each thread its own data, i.e. instantiate a "job" object
for each thread you create (better yet, create the thread inside the job object).
Hope this helps.
|
|
|
|
|
Thank you!
So... I've created a worker class and I'm creating multiple instances of the worker. Within the worker class I create an asyn thread using the BeginInvoke. Now I need update the calling form.
public delegate void CalculationCompletedEventHandler( object sender, CalculationCompletedEventArgs e );<br />
In the Worker class:
<br />
public class Worker : Component {<br />
public event CalculationCompletedEventHandler CalculationCompleted;<br />
<br />
private void doCalculationCompleted( object operationState ){<br />
CalculationCompletedEventArgs e = operationState as CalculationCompletedEventArgs;<br />
OnCalculationCompleted( e );<br />
}<br />
<br />
protected void OnCalculationCompleted( CalculationCompletedEventArgs e ){<br />
if ( CalculationCompleted != null ) {<br />
CalculationCompleted( this, e );<br />
}<br />
}
On the form:
internal void OnUpdateProgress( object sender, CalculationCompletedEventArgs e ){<br />
if ( this.InvokeRequired ){<br />
this.Invoke( doProgressUpdate, new object[] { sender, e } );<br />
}else{<br />
lock ( this ){<br />
} <br />
}<br />
}<br />
<br />
Worker w = new Worker(id);<br />
w.CalculationCompleted += OnUpdateProgress;
In the above is the doCalculationCompleted method needed in the Worker Class?
I'll update my code and let you know how it went.
Thanks again.
I'm listening but I only speak GEEK.
|
|
|
|
|
Hi Arejay,
you can do with and without a completion event.
WITH: the callee provides such an event, caller attaches something to it.
WITHOUT: the caller implements some interface (say IDone, with a Done() method),
and the callee's constructor accepts an object argument that implements that
interface; when done the callee just executes the IDone, hence executing
the caller's Done() code.
The advantage of events (being able to attach multiple delegates) typically
is of no value in the given situation...
PS: two remarks about your OnUpdateProgress method:
- it invokes doProgressUpdate, the normal pattern is to invoke itself
- the lock may not be needed, since the else part executes on the UI thread,
hence needs not to be re-entrant. (If other pieces of code contain the same
lock and execute on another thread, net result is such thread may keep
the UI thread from running, which may harm the responsiveness)
Regards.
|
|
|
|
|
I've post a newer version of the application with the connection strings cleaned up and the database has been srunk down. Are Jay's Profile Page[^]
I'm listening but I only speak GEEK.
|
|
|
|
|
Hi,
I have an wierd exception raised in my code when I query the 2003 Acitve Directory for the User information.
I am getting an Exception in the line
'ResultPropertyCollection props = srResult.Properties'
which says 'Object Refernece not set to an instance of an object'
but the same code works fine with a test page what i created...and even the same code works fine with windows 2000 server which is now in Production.
I would really appreciate some kind of help with this..
// constructor
public UserInfo(UserDirectory parentDirectory, String userAttribute, UserSearchType searchType)
{
if (parentDirectory != null)
{
DateTime LDAPStarted = DateTime.Now;
try
{
Directory = parentDirectory;
String filter = "(SAMAccountName=" + userAttribute + ")";
if (searchType == UserSearchType.Email)
filter = "(mail=" + userAttribute + ")";
if (searchType == UserSearchType.LegacyExchangeDN)
filter = "(legacyExchangeDN=" + userAttribute + ")";
if (searchType == UserSearchType.DistinguishedName)
filter = "(distinguishedName=" + userAttribute + ")";
logger.LogDebug(String.Format("UserInfo ({0},{1},{2}). filter={3}", parentDirectory, userAttribute, searchType, filter));
logger.LogDebug(String.Format("LDAP - Server:{0}, Domain:{1}, UserName:{2}", Directory.Configuration.LDAPServer, Directory.Configuration.LDAPDomain, Directory.Configuration.LDAPUsername));
DirectoryEntry deRootDSE;
DirectoryEntry deDomain;
DirectorySearcher dsSearcher;
SearchResult srResult;
deRootDSE = new DirectoryEntry("LDAP://" + Directory.Configuration.LDAPServer + "/RootDSE",
Directory.Configuration.LDAPDomain + "\\" +
Directory.Configuration.LDAPUsername,
Directory.Configuration.LDAPPassword,
AuthenticationTypes.ServerBind);
deDomain = new DirectoryEntry("LDAP://" + Directory.Configuration.LDAPServer + "/" +
deRootDSE.Properties["defaultNamingContext"].Value.ToString(),
Directory.Configuration.LDAPDomain + "\\" +
Directory.Configuration.LDAPUsername,
Directory.Configuration.LDAPPassword,
AuthenticationTypes.ServerBind);
dsSearcher = new DirectorySearcher();
dsSearcher.SearchRoot = deDomain;
dsSearcher.Filter = filter;
dsSearcher.SearchScope = SearchScope.Subtree;
dsSearcher.PropertiesToLoad.Add("cn");
dsSearcher.PropertiesToLoad.Add("sn");
dsSearcher.PropertiesToLoad.Add("canonicalName");
dsSearcher.PropertiesToLoad.Add("displayName");
dsSearcher.PropertiesToLoad.Add("distinguishedName");
dsSearcher.PropertiesToLoad.Add("givenName");
dsSearcher.PropertiesToLoad.Add("name");
dsSearcher.PropertiesToLoad.Add("homeMDB");
dsSearcher.PropertiesToLoad.Add("homeMTA");
dsSearcher.PropertiesToLoad.Add("mail");
dsSearcher.PropertiesToLoad.Add("mailNickname");
dsSearcher.PropertiesToLoad.Add("proxyAddresses");
dsSearcher.PropertiesToLoad.Add("sAMAccountName");
dsSearcher.PropertiesToLoad.Add("userPrincipalName");
dsSearcher.PropertiesToLoad.Add("legacyExchangeDN");
dsSearcher.PropertiesToLoad.Add("objectclass");
dsSearcher.PropertiesToLoad.Add("member");
srResult = dsSearcher.FindOne();
ResultPropertyCollection props = srResult.Properties;
HomeMDB = GetDefaultPropValue(props, "homeMDB", "localhost");
DirectoryEntry deHomeMDB = new DirectoryEntry("LDAP://" + HomeMDB);
SAMAccountName = GetDefaultPropValue(props, "sAMAccountName", PROP_NA);
CN = GetDefaultPropValue(props, "cn", PROP_NA);
SN = GetDefaultPropValue(props, "sn", PROP_NA);
CanonicalName = GetDefaultPropValue(props, "canonicalName", PROP_NA);
DisplayName = GetDefaultPropValue(props, "displayName", PROP_NA);
DistinguishedName = GetDefaultPropValue(props, "distinguishedName", PROP_NA);
GivenName = GetDefaultPropValue(props, "givenName", PROP_NA);
Name = GetDefaultPropValue(props, "name", PROP_NA);
HomeMTA = GetDefaultPropValue(props, "homeMTA", PROP_NA);
Mail = GetDefaultPropValue(props, "mail", PROP_NA);
MailAlias = Mail.Substring(0, Mail.IndexOf("@"));
MailNickname = GetDefaultPropValue(props, "mailNickname", PROP_NA);
ProxyAddresses = GetDefaultPropValue(props, "proxyAddresses", PROP_NA);
UserPrincipalName = GetDefaultPropValue(props, "userPrincipalName", PROP_NA);
LegacyExchangeDN = GetDefaultPropValue(props, "legacyExchangeDN", PROP_NA);
objectClasses = GetPropValues(props, "objectclass");
memberDistinguishedNames = GetPropValues(props, "member");
StoreURL = Directory.Configuration.StoreURI;
StoreURL = StoreURL.Replace("%EXCHANGE_SERVER%", OwningServer);
StoreURL = StoreURL.Replace("%MAILALIAS%", MailAlias);
StoreURL = StoreURL.Replace("%USERNAME%", SAMAccountName);
if (Directory.Configuration.StoreCredentialType.Equals(ConfigInfo.CredentialTypes.Personal))
{
//derive the domain
char[] commadelim = { ',' };
string[] splitPath = DistinguishedName.Split(commadelim);
string domain = null;
foreach (string path in splitPath)
{
char[] eqdelim = { '=' };
string[] splitvalue = path.Split(eqdelim);
if (splitvalue.Length > 1 && splitvalue[0] != null && splitvalue[0].Equals("DC") && splitvalue[1] != null)
{
if (domain != null)
domain += ".";
domain += splitvalue[1];
}
}
authDomain = domain;
DomainPasswordPair dpp = Directory.Credentials.Recall(SAMAccountName);
authUser = SAMAccountName;
authPassword = dpp.Password;
Directory.Credentials.Cache(SAMAccountName, authDomain, authPassword);
}
else
{ // Store Credential Type is Universal - use the common user and password
authDomain = Directory.Configuration.StoreDomain;
authUser = Directory.Configuration.StoreUsername;
authPassword = Directory.Configuration.StorePassword;
}
Statistics.Add(6, Directory.Configuration.ConfigName, LDAPStarted, (DateTime.Now.Ticks - LDAPStarted.Ticks) / 10000, 1, true, "SUCCESS", null);
}
catch (System.Runtime.InteropServices.COMException ce)
{
throw new Exception("FATAL: COM Exception while trying to retrieve User Info from LDAP: {" + ce.Message + "}");
}
}
else
throw new Exception("FATAL: UserInfo requires a valid User Directory instance.");
} // public UserInfo(UserDirectory parentDirectory, String userName, UserSearchType searchType)
Thanks
Zach1983
|
|
|
|
|
Hi,
sounds like dsSearcher.FindOne() is returning null. Does its documentation tell
you anything in that direction ?
I suggest you assert srResult!=null to confirm this.
|
|
|
|
|
Hi,
Thanks for the reply. As u suggested I checked dsSearcher.FindOne() and it is returning a NULL. The trace doesnt sugest me anything other than this
Error: Object reference not set to an instance of an object.. Trace: at UBS.BLISS.UserInfo..ctor(UserDirectory parentDirectory, String userAttribute, UserSearchType searchType) in d:\BLISS\App_Code\UserInfo.cs:line 152
at UBS.BLISS.UserDirectory.GetByLegacyExchangeDN(String legacyExchangeDN) in d:\BLISS\App_Code\UserDirectory.cs:line 101
at UBS.BLISS.MessageReader.GetCapturedMessageItem(IMessage iMsg, MailRetentionType retentionType, MessageType messageType, Boolean hideContent) in d:\BLISS\App_Code\MessageReader.cs:line 395. InnerException: . Source: App_Code.714yokif
I have the same code to do the search based on the LegacyExchangeDN in my test page it works fine but when i do it as a part of the application it throws this exception.
The code also works fine in Production with windows server 2000.
I kinda of struck in this, Please help me
Thanks
Zach1983
|
|
|
|
|
Hi,
since you now realize the FindOne() method may return null, you must include
code to deal with that possibility, how unlikely it may seem (otherwise
it will bomb at an inappropriate point in time)
I dont know enough about Active Directory to pinpoint your problem right away.
Here are some ideas:
- AD not present or not enabled
- some parameter value (maybe the default value of some property) not appropriate
- security problem
Good luck.
|
|
|
|
|
Hi,
I am kinda of struck in this and I found that when I hardcode the legacyExchangeDN string its getting the entry from the Active Directory but when i Parse the string from th email address
say for example Doe, John <ex: o="First" organization="" ou="First" administrative
group="" cn="Recipients/cn=jdoe">.. i parsed the string using this
--------
int startIndex = -1;
int endIndex = -1;
startIndex = inString.IndexOf("<ex:", recindex)="" +="" 4;
="" if="" (startindex=""> recIndex + 4)
endIndex = inString.IndexOf(">", startIndex);
if (endIndex != -1)
lemail = inString.Substring(startIndex, endIndex - startIndex);
-------------
It returning NULL...I dont understand why its not working, what i am doing for Hardcoding is also just outputting the lemail and Coping the same to hard code it...
Any help would be Appreciated... I am struck for more than a week....
Thanks,
Zach1983
|
|
|
|
|
sorry for the junk code
Hi,
I am kinda of struck in this and I found that when I hardcode the legacyExchangeDN string its getting the entry from the Active Directory but when i Parse the string from th email address
say for example Doe, John <EX:/o=First Organization/ou=First Administrative
Group/cn=Recipients/cn=jdoe<...... i parsed the string using this
the code is
--------------
int startIndex = -1;
int endIndex = -1;
startIndex = inString.IndexOf("<EX:", recIndex) + 4;
if (startIndex > recIndex + 4)
endIndex = inString.IndexOf(">", startIndex);
if (endIndex != -1)
lemail = inString.Substring(startIndex, endIndex - startIndex);
int email = lemail.Length;
logger.LogDebug("email " + email);
-------------------
It returning NULL...I dont understand why its not working, what i am doing for Hardcoding is also just outputting the lemail and Coping the same to hard code it...
Any help would be Appreciated... I am struck for more than a week....
Thanks
Zach1983
|
|
|
|
|
Hi,
so you have 10 lines of code that go wrong ?
how about debugging it, this means:
- either you single step through it and look at intermediate results
- or you add output ("log") statements to see intermediate results.
Whatever method you choose, you should soon figure out you made a simple
mistake (that could have been avoided by applying a more defensive
programming style).
Good hunting !
|
|
|
|
|
Hi,
I am suppose to read XML files and extract some data from certain nodes based on its attribute. What I have done is to use XmlTextReader and loop through, using select case and hardcode (inefficient and poor practice) the nodes to be extracted. I have used XmlTextReader instead of XmlDocument initially as I would not be needing Xpath. Now, I would like to know if there are ways to select the nodes based on part of its attribute name like using wildcards. I have tried using Xpath but no success. Essentially, I want to select all the nodes with attributes beginning with a certain string eg) Wanted[…., regardless of the remaining text in the attribute name field.
Can anybody please kindly point to me how to go about doing it if possible? Any advice will be greatly appreciated.
Below are sample of my code and xml file.
reader = new XmlTextReader(link);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.Name == "A") //To select some nodes w/o attributes
{…. }
if (reader.MoveToFirstAttribute()) {
switch (reader.GetAttribute(0)) //To select somes nodes based on attributes.
{
case "Wanted[zxx]":
…
break;
case "Wanted[yyy]":
…
…
default:
break;
….
- <Root>
<A>XXX</A>
….
- <Elements>
<Element name="Num">XXX</Element>
<Element name="xxx">xxx</Element>
<Element name="B1">1424</Element>
<Element name="Unwanted1">xxx</Element>
<Element name="Unwanted2">xxx</Element>
<Element name="Wanted[XXX]">xxx</Element>
<Element name="Wanted[YYY]">xxx</Element>
<Element name="Wanted[ZZZ]">xxx</Element>
</Elements>
</Root>
|
|
|
|
|
drifters wrote: Now, I would like to know if there are ways to select the nodes based on part of its attribute name like using wildcards.
I don't think so.
Christian Graus - Microsoft MVP - C++
Metal Musings - Rex and my new metal blog
"I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )
|
|
|
|
|
Oh no. If that's the case than I'll have to hardcode the cases. Thanks for the help. Any other view or advice will be greatly appreciated.
|
|
|
|
|
Hi!
Im currently playing around with making a Keylogger (nothing malicious, I promise) and ive gotten everything to work properly thus far, but one feature I think would be helpful would be recognizing what window currently has focus for each keystroke, i.e. if "hello" is typed in an internet explorer window, and then "c# programming" is typed in a firefox window, is there any way for my application to both get the kaystrokes, and the window with focus... making me able to do something like this:
Internet Explorer - The Code Project:
hello
Mozilla Firefox - The Code Project:
c# programming
Hopefully ive been clear on what I would like, any help would be much appreciated. Thanks!
Dirk Williams
|
|
|
|
|
Hi,
you can get a window handle and then either get the window's title, or scan the
process list (Process class) to find the process it belongs to. Some PInvoke
would be required:
[DllImport("user32")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern void GetWindowText(IntPtr hWnd, StringBuilder sb, int capacity);
|
|
|
|
|
Hello everyone,
I am using the following code to specify a window to receive mouse and keyboard messages from the video window.
IVideoWindow.put_MessageDrain(this.DvdPanel.Handle);
I was wondering if I can do the following:
1- Can I distinguish between the right and the left mouse click?
2- Can I assign seprerate events to the mouse clicks?
- I would like to have ContextMenu once the right mouse is clicked; and follow the menu available on the Video Window once the left mouse is clicked.
Thank you very much and have a great day.
Khoramdin
|
|
|
|
|