|
That XAML makes my brain hurt. Maybe you should use the PRE tag on it rather than the CODE tag. The PRE tag maintains the indentation.
|
|
|
|
|
Hi aspodotnetdev,
i tried to modify it but i can not fix it well i don't know why, i will try again.
Thanks
Edit... i tried to use PRE tag but when i post the code many lines of code disappear ,i am so sorry if it is not fix well.
|
|
|
|
|
VisualLive wrote: i tried to use PRE tag but when i post the code many lines of code disappear
Hmmm, maybe that's related to a bug I reported here.
|
|
|
|
|
You needed to HTML encode your XML. I've fixed it
cheers,
Chris Maunder
The Code Project | Co-founder
Microsoft C++ MVP
|
|
|
|
|
Hi Chris,
you are so kind to do that,i will remind for the next time i post a code.
Thanks so much .
Have a nice day.
|
|
|
|
|
You may get a better reponse to your query in the WPF forum.
Just say 'NO' to evaluated arguments for diadic functions! Ash
|
|
|
|
|
Hi Richard,
truly i believed it was the WPF Forum ,so it was my mistake .
Thanks for your suggest,i moved this question to the WPF Forum.
Have a nice day.
|
|
|
|
|
I have a template StartPage.xaml file, and I understand XAML well enough.
What I don't understand is how/where the page is getting it's data.
In addition, there's no .CS file ain this project. Where do you put the code behind?
Anyone have any experience with this?
Thanks
Everything makes sense in someone's mind
|
|
|
|
|
|
Nishant Sivakumar wrote: See http://msdn.microsoft.com/en-us/library/ee663382(v=VS.100).aspx[^]
Ya useful link.
Take 5
|
|
|
|
|
hi!
My query is that, If i enter some text in textbox the matching record from the database column display.
I am using windows application
e.g.: google, if we enter some text related text displayed.
thanx
|
|
|
|
|
|
|
Hi Guys,
I'm working on a windows service which runs under a given service account. It writes files to shared areas on other machines, but needs to change the owner of these files to a different account. I can do this using the SetAccessControl as below:
public static void SetOwner(string uri, string account)
{
System.Security.AccessControl.FileSecurity security = File.GetAccessControl(uri);
IdentityReference owner = new NTAccount(account);
security.SetOwner(owner);
File.SetAccessControl(uri, security);
}
However, this only works if the service account which I'm using is an administrator or backup operator on the remote machine (unless it's setting the owner to itself). I'd like to avoid giving this service account rights to too many machines, since that puts too much power in the hands of one account. Instead, I'd like to provide a username and password for the account which will be the owner of the file, and have the service impersonate this account when assigning ownership (e.g. in a similar way to how you could have credentials in a connection string for a database connection which didn't use trusted authentication). I'm looking for something like the code below, but have so far been unable to find an understandable example to work from.
public static void SetOwner(string uri, string account)
{
StartImpersonating(account);
System.Security.AccessControl.FileSecurity security = File.GetAccessControl(uri);
IdentityReference owner = new NTAccount(account);
security.SetOwner(owner);
File.SetAccessControl(uri, security);
StopImpersonating();
}
static void StartImpersonating(string account, string password)
{
System.Security.Principal.WindowsIdentity.Impersonate(account, password);
}
static void StartImpersonating(string account)
{
string password = GetPasswordFromSecureStore(account);
StartImpersonating(account, password);
}
static void StartImpersonating(string domain, string username)
{
StartImpersonating(string.Format("{0}\\{1}",domain,username));
}
static void StopImpersonating()
{
StartImpersonating(System.Environment.UserDomainName,System.Environment.UserName);
}
NB: the above code is just for illustrative purposes to show the sort of thing I'm looking for; I've no idea whether what's there is even close to what's required to acheive this.
Any advice, pointers, or intPtrs appreciated.
Thanks in advance,
JB
|
|
|
|
|
Seek and ye shall find Windows Impersonation using C#[^].
It's from '03 but im sure the pricipals are still the same, you are going to have to call the Windows API to get done but the above link should help you out.
Don't comment your code - it was hard to write, it should be hard to read!
|
|
|
|
|
Hi JB,
I used this in a small test I composed on impersonation:
static void TestProcessLogs(string path)
{
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
IntPtr token;
#region User / Password
String user = "xxxxxx";
String domain = "xxxxx";
String pass = "xxxxxxx";
#endregion
if (LogonUser(user, domain, pass, 9, 0, out token))
{
WindowsIdentity fromIdentity = new WindowsIdentity(token);
WindowsImpersonationContext context = fromIdentity.Impersonate();
ProcessLog(@"\\xxxxxxx.xxxxxxx.xxxxxx\f$\Connector\LNWorkerDir\705-SORL9002-PGBU-WEC-US-productn-octtic\peqdLN02\all.log");
context.Undo();
}
}
and here comes the definition of LogonUser. Place this within a class definition:
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
Best regards
Manfred
|
|
|
|
|
That's perfect. Thanks to both of you for the link & code sample; very much appreciated.
I've put this code into a disposable object, so that you can easily swap contexts, using the using statement to control when you impersonate another account. Hopefully this will be of use to anyone following this thread in future.
e.g.
class Program
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<demo />");
doc.Save(@"\\server\share\demo1.xml");
using (Impersonator impersonate = new Impersonator(@"domain\user"))
{
doc.Save(@"\\server\share\xjbdemo2.xml");
}
doc.Save(@"\\server\share\xjbdemo3.xml");
Console.WriteLine("Done");
Console.ReadKey();
}
}
public class Impersonator: IDisposable
{
#region windows api reference
#region enums
public enum LogonType
{
LOGON32_LOGON_INTERACTIVE = 2,
LOGON32_LOGON_NETWORK = 3,
LOGON32_LOGON_BATCH = 4,
LOGON32_LOGON_SERVICE = 5,
LOGON32_LOGON_UNLOCK = 7,
LOGON32_LOGON_NETWORK_CLEARTEXT = 8,
LOGON32_LOGON_NEW_CREDENTIALS = 9,
}
public enum LogonProvider
{
LOGON32_PROVIDER_DEFAULT = 0,
}
#endregion enums
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
void Impersonate(string account)
{
Impersonate(account, GetPassword(account));
}
void Impersonate(string account, string pass)
{
string[] accountSplit = SplitAccount(account);
Impersonate(accountSplit[0], accountSplit[1], pass);
}
void Impersonate(string domain, string user, string pass)
{
IntPtr token;
AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
if (LogonUser(user, domain, pass, (int)LogonType.LOGON32_LOGON_NEW_CREDENTIALS, (int)LogonProvider.LOGON32_PROVIDER_DEFAULT, out token))
{
WindowsIdentity fromIdentity = new WindowsIdentity(token);
this.context = fromIdentity.Impersonate();
}
else
{
throw new NotImplementedException("Logon Issue");
}
}
#endregion windows api reference
#region fields
const string DOMAIN_USER_SEPARATOR = @"\";
WindowsImpersonationContext context;
#endregion fields
#region constructor
public Impersonator(string account)
{
Impersonate(account);
}
public Impersonator(string account, string pass)
{
Impersonate(account, pass);
}
public Impersonator(string domain, string user, string pass)
{
Impersonate(domain, user, pass);
}
#endregion constructor
#region helper methods
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;
}
string[] SplitAccount (string account)
{
string[] accountSplit = account.Split(DOMAIN_USER_SEPARATOR.ToCharArray(), 2);
return accountSplit;
}
#endregion helper methods
#region disposal pattern
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
}
this.context.Undo();
this.context.Dispose();
disposed = true;
}
}
~Impersonator()
{
Dispose (false);
}
#endregion disposal pattern
}
Thanks again,
JB
|
|
|
|
|
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
|
|
|
|
|