|
Hi JB,
thanks for sharing your class with us.
I have some issues with your design though:
1. In the constructor I would not call Impersonate(...) straight away.
There are two reasons for this:
a.) Code in a constructor that will likely cause an exception
is a real pain in the a**e.
b.) Let the user of your library decide when Impersonation starts
and ends.
Store user account and domain in instance variables. Password should not be stored in
the class (as you have already done) but could be retrieved via GetPassword() (see 2.).
I would make an additional overload Impersonate() a public function and add another function
like Revert() that will call context.Undo() and set context = null. bool IsImpersonating()
would be nifty (context != null) too.
2. Move the function GetPassword to a separate class that implements an interface say
IStringPasswordProvider. Have a property that allows the user of your library to inject
an instance of his or her own implementation of IPasswordProvider.
public interface IStringPasswordProvider
{
String GetPassword(String account);
String GetPassword(String account, String domain);
}
public class DefaultPasswordProvider : IStringPasswordProvider
{
string GetPassword(string account)
{
string[] accountSplit = SplitAccount(account);
return GetPassword(accountSplit[0], accountSplit[1]);
}
string GetPassword(string domain, string user)
{
string pass = string.Empty;
pass = "todo";
return pass;
}
}
A password provider might read passwords from a DB or may be the app.config (web.config) file.
Please let me know what you think of these changes.
Best Regards
Manfred
|
|
|
|
|
Hi All
I have a server that starts up as part of my application (when the application InitializeComponent()), as below:
<br />
public Window1()<br />
{<br />
InitializeComponent();<br />
<br />
<br />
...other code<br />
connectionAccept();<br />
<br />
}<br />
This calls the below code:
<br />
private void connectionAccept()<br />
{<br />
try<br />
{<br />
listener = new Socket(AddressFamily.InterNetwork,<br />
SocketType.Stream,<br />
ProtocolType.Tcp);<br />
<br />
IPEndPoint LocalIP = new IPEndPoint(IPAddress.Any, 2112);<br />
<br />
listener.Bind(LocalIP);<br />
<br />
listener.Listen(0);<br />
<br />
listener.BeginAccept(new AsyncCallback(OnClientConnect), null);<br />
<br />
}
<br />
catch (SocketException se)<br />
{<br />
MessageBox.Show(se.Message);<br />
}
<br />
}
<br />
public void OnClientConnect(IAsyncResult asyn)<br />
{<br />
try<br />
{<br />
otherListener[numberOfClients] = listener.EndAccept(asyn);<br />
<br />
WaitForData(otherListener[numberOfClients]);<br />
<br />
++numberOfClients;<br />
<br />
String strData = Convert.ToString(numberOfClients);<br />
MessageBox.Show(strData);<br />
<br />
listener.BeginAccept(new AsyncCallback(OnClientConnect), null);<br />
}<br />
catch (ObjectDisposedException)<br />
{<br />
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");<br />
}
<br />
catch (SocketException se)<br />
{<br />
MessageBox.Show(se.Message);<br />
<br />
}
<br />
}
<br />
public class SocketPacket<br />
{<br />
public System.Net.Sockets.Socket currentSoc;<br />
public byte[] dataBuffer = new byte[0];<br />
<br />
}
<br />
public void WaitForData(System.Net.Sockets.Socket soc)<br />
{<br />
try<br />
{<br />
<br />
if (pfnListnerCallBack == null)<br />
{<br />
pfnListnerCallBack = new AsyncCallback(OnDataReceived);<br />
<br />
<br />
SocketPacket socPkt = new SocketPacket();<br />
socPkt.currentSoc = soc;<br />
<br />
<br />
soc.BeginReceive(socPkt.dataBuffer, 0,<br />
socPkt.dataBuffer.Length,<br />
SocketFlags.None,<br />
pfnListnerCallBack,<br />
socPkt);<br />
<br />
<br />
}
<br />
}
<br />
catch (SocketException se)<br />
{<br />
MessageBox.Show(se.Message);<br />
<br />
}
<br />
}
<br />
public void OnDataReceived(IAsyncResult asyn)<br />
{<br />
try<br />
{<br />
SocketPacket socketData = (SocketPacket)asyn.AsyncState;<br />
string receivedValue = string.Empty;<br />
<br />
byte[] receivedBytes = new byte[1024];<br />
int numBytes = socketData.currentSoc.Receive(receivedBytes);<br />
<br />
receivedValue = Encoding.ASCII.GetString(receivedBytes); <br />
<br />
MessageBox.Show(receivedValue); <br />
WaitForData(socketData.currentSoc); <br />
<br />
}
<br />
catch (ObjectDisposedException)<br />
{<br />
System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");<br />
<br />
}
<br />
catch (SocketException se)<br />
{<br />
MessageBox.Show(se.Message);<br />
}
<br />
}
<br />
}<br />
<br />
Ok so the server works, but it seems to only work once. When I send a string in bytes across to it, it shows you that one client has connected and the message recieved. Then if I try doing the same thing again, it only shows the another client has connected but does not show the second message MessageBox.Show(receivedValue); . I want it to always show the message from the client. Where am I going wrong??? Oh by the way I got some of the code for the server from
Codeguru.com
|
|
|
|
|
You need to call BeginReceive() in your OnDataReceived() method.
You do that to reset it. You will need to also consider if you don't want to do that, such as when the app is exiting.
|
|
|
|
|
It’s always pleasing when a piece of software works the way you want to, but as long as I don’t understand precisely why (or how) it works I consider that a big problem. I made an ICMP listener to compensate for a flaw in the ’UdpClient’ class, that will not return appropriate ICMP messages resulting from requests made when unexpectedly the remote host becomes unavailable. (ICMP Type 3, any Code). Instead of replying with an ICMP code, it simply throws an error: (WSACONNRESET) and ‘Cannot access a disposed object’.
The code as I have it running now uses ManualResetEvents as signaling, which is acceptable. The resulting data has been carefully checked, even at time-slot and sequence number level, and all is well. I just don’t understand why a new ‘StateObject’ is required for every iteration of the loop.
There is no reason that I am aware of that states that the current buffer cannot be re-used. Nevertheless, if I don’t use a new one every iteration, the buffer returned is invalid (no errors though); the buffer then refers to a packet from my host to an external destination instead of a buffer from a remote host. Therefore, I see my system’s reply to an echo (Type 0) request, instead of the actual echo request (Type 8) received (as seen in Wireshark). As soon as I change the loop to use a new ‘StateObject’, all is well again. The examples of Microsoft did not include a disposable ‘StateObject’, so I made a new class that inherits from IDisposable for that purpose.
Furthermore, when switching from ManualResetEvent signaling to ‘AsyncWaitHandle’ signaling, the process only works when using a recursive call to the callback delegate. If I don’t, the ’IASyncResult’ ‘IsCompleted’ is not always set (even though all buffers are the same 60 bytes), so it will wait indefinitely on the handle.
A long story (and a lot of code) but I hope someone will be able to shed some light on these issues.
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System.Text;
using System.Threading;
using log4net;
namespace ICMPTest
{
public class ICMPCheck
{
private static ManualResetEvent gotMessage;
private static IPAddress ipAddress;
private static IntPtr stateHandle;
private static ICMP.Disposables.StateObject so = null;
private static Socket icmpClient;
private static EndPoint remoteRawEndPoint = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
public static Queue<byte[]> m_icmpQueue = new Queue<byte[]>();
public static object m_syncLock = new object();
private static IPEndPoint NIC = null;
private static int Queued = 0;
private static int DeQueued = 0;
private static int CallCount = 0;
public static IAsyncResult iar;
public static void Start()
{
try
{
using (icmpClient = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp))
{
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
IPHostEntry hostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress[] address = hostInfo.AddressList;
ipAddress = address[0];
NIC = new IPEndPoint(ipAddress, 0);
icmpClient.Bind(NIC);
byte[] inBytes = new byte[] { 1, 0, 0, 0 };
byte[] outBytes = new byte[] { 0, 0, 0, 0 };
icmpClient.IOControl(IOControlCode.ReceiveAll, inBytes, outBytes);
icmpClient.ReceiveBufferSize = 1024;
while (true)
{
using (so = new ICMP.Disposables.StateObject(stateHandle))
{
so.workSocket = icmpClient;
iar = icmpClient.BeginReceiveFrom(so.buffer, 0, ICMP.Disposables.StateObject.BUFFER_SIZE, 0, ref remoteRawEndPoint, new AsyncCallback(ReceiveFromCallback), so);
iar.AsyncWaitHandle.WaitOne();
for (int i = DeQueued; i < Queued; i++)
{
Interlocked.Increment(ref DeQueued);
ICMP.ICMPProgram.logger.Debug("ICMPCheck-0: Signal + Message received: " + remoteRawEndPoint.ToString() + " Queue: " + m_icmpQueue.Count.ToString() + " " + Queued.ToString() + " " + DeQueued.ToString());
}
}
}
}
}
catch (Exception excp)
{
ICMP.ICMPProgram.logger.Error("ICMPCheck: Exception Mainblock. " + excp.Message);
}
return;
}
private static void ReceiveFromCallback(IAsyncResult iar)
{
Interlocked.Increment(ref CallCount);
try
{
ICMP.Disposables.StateObject state = (ICMP.Disposables.StateObject)iar.AsyncState;
Socket client = ((ICMP.Disposables.StateObject)iar.AsyncState).workSocket;
EndPoint tempRemoteEP = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
int bytesRead = client.EndReceiveFrom(iar, ref tempRemoteEP);
if (bytesRead > 0)
{
if (!(((IPEndPoint)tempRemoteEP).Address).Equals(NIC.Address))
{
byte[] _icmpData = new byte[bytesRead];
byte[] icmpType = new byte[1];
Buffer.BlockCopy(state.buffer, 20, icmpType, 0, 1);
if (true)
{
Buffer.BlockCopy(state.buffer, 0, _icmpData, 0, bytesRead);
lock (m_syncLock)
{
m_icmpQueue.Enqueue(_icmpData);
Interlocked.Increment(ref Queued);
}
}
client.BeginReceiveFrom(state.buffer, 0, ICMP.Disposables.StateObject.BUFFER_SIZE, 0, ref tempRemoteEP, new AsyncCallback(ReceiveFromCallback), state);
remoteRawEndPoint = tempRemoteEP;
ICMP.ICMPProgram.logger.Debug("ICMPCheck: Bytes: " + bytesRead.ToString() + ", Type: " + icmpType[0].ToString() + " " + tempRemoteEP.ToString() + " " + m_icmpQueue.Count.ToString() + " " + Queued.ToString() + " " + CallCount.ToString() + " " + iar.IsCompleted.ToString());
}
}
else
{
ICMP.ICMPProgram.logger.Debug("ICMPCheck: bytesRead = 0 ");
}
}
catch (Exception excp)
{
ICMP.ICMPProgram.logger.Debug("ICMPCheck:ReceiveFromCallback main " + excp.Message);
}
finally
{
}
}
}
}
StateObject:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Net.Sockets;
namespace ICMP
{
public class Disposables
{
public class StateObject : IDisposable
{
public Socket workSocket = null;
public const int BUFFER_SIZE = 1024;
public byte[] buffer = new byte[BUFFER_SIZE];
public StringBuilder sb = new StringBuilder();
private IntPtr handle;
private Component component = new Component();
private bool disposed = false;
public StateObject(IntPtr handle)
{
this.handle = handle;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
component.Dispose();
}
CloseHandle(handle);
handle = IntPtr.Zero;
disposed = true;
}
}
[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle);
~StateObject()
{
Dispose(false);
}
}
}
}
|
|
|
|
|
Hi Guys
Need Help. I am using a dynamic created Textbox in code behind
However when i wanna retrieve the value from the Textbox which i have created, I always seem to hit an error and stuck at the part of retrieving value
Any sample or advise will be a blessing to me
Thanks A Millions
KaKaShi HaTaKe
|
|
|
|
|
You add the textbox using Controls.Add() . When creating the textbox from codebehind, you can assign it an ID say, tbDynamicId.
TextBox tb = new TextBox();
tb.ID = "tbDynamicId";
this.Controls.Add(tb);
Then you can get the textbox like:
TextBox tbDynamic = (TextBox)FindControl("tbDynamicId");
And then retrive the value normally,
String value = tbDynamic.Text;
|
|
|
|
|
string text = ((TextBox)this.Controls["ControlName"]).Text;
|
|
|
|
|
suppose i have form where toolstrip is there and that toolstrip contain many toolstrip button and other control. how can i find is there any toolstrip button exist or not on the form just by name. can i write any function like findcontrol where i pass the control name means toolstrip button name as string to that function and that function will iterate in all the controls on the form and check any toolstrip button exist having that name which i pass to that function. please help me with sample code.
i have written a code snippet which is not able to find out the toolstrip button. my code as follows
<br />
public static System.Windows.Forms.Control FindControl(string id, System.Windows.Forms.Form.ControlCollection col)<br />
{<br />
System.Windows.Forms.Control child = null;<br />
child = FindControlRecursive(c, id);<br />
if (child != null)<br />
return child;<br />
<br />
return null;<br />
}<br />
<br />
private static System.Windows.Forms.Control FindControlRecursive(System.Windows.Forms.Control root, string id)<br />
{<br />
if (root.Name != null && root.Name == id)<br />
return root;<br />
<br />
foreach (System.Windows.Forms.Control c in root.Controls)<br />
{<br />
System.Windows.Forms.Control rc = FindControlRecursive(c, id);<br />
if (rc != null)<br />
return rc;<br />
}<br />
return null;<br />
}<br />
plzzzz help
tbhattacharjee
|
|
|
|
|
A ToolStripButton [^] inherits from Component , not Control .
Good luck
--edit
The same answer has been given here[^]. I think the answer will stay the same, no matter how often you're going to post your question.
It's not going to work using the "FindControl" method. How about searching the items [^] collection of the ToolStrip ?
I are Troll
modified on Thursday, November 4, 2010 4:47 AM
|
|
|
|
|
As Eddy has told you, ToolStripButton is not a Control, so it is not added to any Controls collection.
If you want to find a ToolStripButton by name among several ToolStrip controls (ToolStrip does inherit from Control), you should first find the ToolStrip objects, using something similar to what you have done, and then use the string indexer of the Items property of these ToolStrip controls. I mean, if "ts" is a ToolStrip, and you want to see if a ToolStripButton named "tsbtn" is in that ToolStrip, you just have to try this:
ToolStripItem itm = ts.Items["tsbtn"];
If itm is null, the ToolStrip does not contain that item.
|
|
|
|
|
I want to add a custom toolbar to VS. This toolbar would have a combo on it and some buttons. Can someone point me in the right direction on how to do this?
Thanks
Everything makes sense in someone's mind
|
|
|
|
|
Take a look at the links in the answers on this thread[^].
Henry Minute
Do not read medical books! You could die of a misprint. - Mark Twain
Girl: (staring) "Why do you need an icy cucumber?"
“I want to report a fraud. The government is lying to us all.”
|
|
|
|
|
Has anyone had problems with their final build not functioning the same as when in debug? I have a procedure that finds the selected item in a listbox and updates its associated data in the database. Basically, the listbox gets disabled during the update and re-enable when complete. Upon re-enabling, I set the selected item to the item that was just updated. This works fine in debug, but when I build the project and run the executable, the recently update item does not get selected, the first item in the list always gets selected. I know you can't diagnose my exact problem without looking at the code, but I thought it strange that the final build is not working as I expected after testing. I was wondering if anyone had some ideas of what to look for?
|
|
|
|
|
Are you updating your database on a background thread? If so, are you using Invoke to reenable the ListBox and select the item when the database update finishes?
|
|
|
|
|
No, I'm not running a background thread. I have an "edit" button that allows the user to edit the info in a series of textboxes that are linked to the values in the listbox. When the "edit" button is pressed, the listbox is disable to prevent the user from changing the selection. When the user is done, a "save" button is pressed, a SQL Update statement is run and the listbox is enabled. I stored the original selected item index, so I can return the selection to the same value.
|
|
|
|
|
Then I need to see the code. Otherwise I can't figure out what is going on.
|
|
|
|
|
kruegs35 wrote: I was wondering if anyone had some ideas of what to look for?
#IF DEBUG
Another thing to check would be the projects' properties; you might be using different path's, and thus, be including different things in the debug/compile versions.
I are Troll
|
|
|
|
|
I define new bitmap in my code
Bitmap image = new Bitmap( width, height, PixelFormat.Format8bppIndexed);
==> that mean that this bitmap is gray scale color.
Now, i want to define what color will be at place (i, j) so i usually use ( on 24 color bit ) the method 'SetPixel( i, j, Color.FromRGB( ... ) )'
But in this case that the bitmap is on gray scale i cant do it because i have only one value of the color ... and the application crash all the time when i try to
call Color.FromRGB(theOneColorIhave)
Someone know other way to do set the pixel values - some way that can be use with 8 bit format ?
Thanks
modified on Wednesday, November 3, 2010 10:36 AM
|
|
|
|
|
Try this function to get a color supported by your currently selected palette.
Greetings
Covean
|
|
|
|
|
You cannot use SetPixel if your bitmap pixel format is indexed, so you will have to use the BitmapData object returned by LockBits[^] method.
Edit
Ok, this is a little tricky, so I will give a little sample on how to do this before you have to ask again:
unsafe Bitmap ToGrayScale(Bitmap bmp)
{
Bitmap grayBmp = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format8bppIndexed);
ColorPalette pal = grayBmp.Palette;
for (int i = 0; i < 256; i++)
pal.Entries[i] = Color.FromArgb(i, i, i);
grayBmp.Palette = pal;
BitmapData bd = grayBmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.ReadWrite,
PixelFormat.Format8bppIndexed);
byte* ptr = (byte*)bd.Scan0.ToPointer();
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
Color c = bmp.GetPixel(i, j);
ptr[j * bd.Stride + i] = (byte)((c.R + c.G + c.B) / 3);
}
}
grayBmp.UnlockBits(bd);
return grayBmp;
}
Sure I should have locked bits also for bmp, becouse GetPixel performance is really bad but, hey, I feel a little lazy today...
modified on Wednesday, November 3, 2010 12:01 PM
|
|
|
|
|
hello !
i making a remote support app and i trying to get the screen image when the computer is in lock mode or in log off mode and i can't.. i only get a black screen !!! can somebody help me ?
thx
|
|
|
|
|
Think about what state the system will be in if it is locked or if no user is logged on.
Just say 'NO' to evaluated arguments for diadic functions! Ash
|
|
|
|
|
You're getting a black screen because the image you're capturing is on a Desktop that is no longer visible. When the workstation is locked, the user see a different Desktop. Whatever you're using to capture the screen isn't written to handle multiple Desktops.
|
|
|
|
|
public static System.Windows.Forms.Control FindControl(string id, System.Windows.Forms.Form.ControlCollection col)
{
System.Windows.Forms.Control child = null;
foreach (System.Windows.Forms.Control c in col)
{
if (c.GetType().Name.ToUpper() == "TOOLSTRIP")
{
foreach (System.Windows.Forms.ToolStripItem item in ((System.Windows.Forms.ToolStrip)c).Items)
{
switch (item.GetType().Name)
{
case "ToolStripButton":
child = ((Control)((ToolStripButton)item));
break;
case "ToolStripComboBox":
break;
case "ToolStripLabel":
break;
case "ToolStripMenuItem":
break;
case "ToolStripProgressBar":
break;
case "ToolStripStatusLabel":
break;
case "ToolStripTextBox":
break;
}
}
}
else
{
child = FindControlRecursive(c, id);
}
if (child != null)
return child;
}
return null;
}
tbhattacharjee
|
|
|
|
|
Format your code using the pre tags, i.e. use the "code block" menu item.
Ask a question, the subject is not the question
I know the language. I've read a book. - _Madmatt
|
|
|
|
|