|
Try reading on "non-blocking server socket" in the MSDN.
The thing is: if you have a "server loop" which waits on data to arrive on any of these ports, then does some manipulation and loops, you will always have poor performance, as your application will block until you are done with one of the requests.
If you decided to use 10 ports in order to offer "10 parallel connections", you totally misunderstood the concept (sorry ).
You should only use different ports for different services (e.g. FTP Control connection on Port 21, HTTP on Port 80, ...) or to seperate user-groups (e.g. Customer1 connects to FTP on port 21, Customer2 uses Port 23, ...).
Specifically, you might want to read into Delegates, Callbacks, etc. These are, IMHO, the easiest way to create socket-using apps without doing manual multithreading.
Cheers
Sid
|
|
|
|
|
I have a web form, which has a place holder named Example when, Page_Load happens in my web form. I’m creating dynamically a WUC named WebUserControl3 into my place holder.
WebUserControl3 has several text boxes, a button and a label, when user click button I’m executing some calculation which result I’m placing into label. But when user click button occurs Page_Load in web form that contains my place holder and I need recreate my WUC plus data was contained therein, I have tried with ViewState and Session variables but still I can’t pass data from WUC to web form to recreate WUC and its data. Obviously WUC is created again without data. Notwithstanding if I re-enter data in WUC and click button again data are displayed OK.
Why first time it isn’t working and begin second try it’s working fine?
My code is:
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
}
else
{
Example.Controls.Clear();
Control control = this.Page.LoadControl("WebUserControl3.ascx");
Example.Controls.Add(control);
}
}
Thanks in advance
A.L.
El hombre que tiene amigos debe mostrarse amigo...
|
|
|
|
|
Does somebody know about this topic?
El hombre que tiene amigos debe mostrarse amigo...
|
|
|
|
|
Hello:
At last I found a solution.
For some reason the page does not create it with the same control Id. the first time as every other time.
To solve it I inserted this line:
control.ID="WebUserCotrol3"; as it shows:
Example.Controls.Clear();
Control control = this.Page.LoadControl("WebUserControl3.ascx");
control.ID="WebUserCotrol3";
Example.Controls.Add(control);
I hope this be useful for newbie person as I am.
Greetings.
A.L.
El hombre que tiene amigos debe mostrarse amigo...
|
|
|
|
|
How can I inside Windows Form code determine if there has been key strokes or mouse move outside of the Form.
e.g. To make a Sys Tray application that can determine if the user has left the pc compliatly
(If there has been no mousemove or key strokes for a period)
|
|
|
|
|
|
I'm attempting to send Keyboard and Mouse events to windows other than my own using the SendMessage and/or PostMessage APIs. I've looked pretty closely at the messageboards here and am still having a hell of a time getting it to work.
[DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr FindWindow(string winClass, string WinName);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
private const uint WM_ACTIVATEAPP=0x001C;
private const uint WM_KEYDOWN= 0x0100;
private const uint WM_KEYUP=0x0101;
private const uint WM_SETFOCUS=0x0007;
private void CheckWindows()
{
IntPtr WinHandle=IntPtr.Zero;
WinHandle = FindWindow(null,"Untitled - Notepad");
if(WinHandle!=IntPtr.Zero)
{
SendMessage(WinHandle,WM_ACTIVATEAPP,(IntPtr)1,IntPtr.Zero);
SendMessage(WinHandle,WM_SETFOCUS,IntPtr.Zero,IntPtr.Zero);
SendMessage(WinHandle,WM_KEYDOWN,(IntPtr)0x31,(IntPtr)1);
SendMessage(WinHandle,WM_KEYUP,(IntPtr)0x31,(IntPtr)1);
}
}
At this point I assume I'm not sending the correct messages, but I was hoping someone could point me in the right direction.
|
|
|
|
|
First, make sure you're using the correct signatures (it looks like you are already, but just in case, use pinvoke.net)
Also, use the Spy++ tool bundled with Visual Studio to see correct messages to send to the app. For example, use Spy++ to view the incoming messages when you type some text in Notepad. After logging the necessary messages, you should be able to send the same messages using your app.
I just tried this and it looks like a key press in notepad generates:
WM_KEYDOWN
WM_CHAR
EM_GETSEL
EM_GETSEL
EM_LINEFROMCHAR
EM_LINEFROMCHAR
EM_LINEINDEX
EM_LINEINDEX
WM_KEYUP
You might want to try those messages, in that order, to send text to Notepad.
Tech, life, family, faith: Give me a visit.
I'm currently blogging about: Lies of Our Fathers: A Must-Know About Lent
Judah Himango
|
|
|
|
|
I did already use Spy++ to log the messages. I just didn't know if all these messages needed to be sent or if some are generated as a result of initial messages...ie. WM_ACTIVATEAPP. I also could not tell what message were generated by NOTEPAD as a result of the WM_KEYDOWN and WM_CHAR messages that most likely were generated by the keyboard. Thanks for the input though.
|
|
|
|
|
If you don't want to mess with sending each message/character separately or have problems getting it to work, you could take a look at the SendKeys class in the FCL.
It has easy to use static methods for this.
Regards,
mav
|
|
|
|
|
Right, but you must make sure the window is topmost and has the focus. I chose the SendMessage to avaoid this.
|
|
|
|
|
I'm trying to load an assembly dynamically (IE. extracting it as an embedded resource, and then using Assembly.Load() to load it) and then use the types and functions that are built into it, but I can't figure out how to get access to them, nor could I find any good tutorials.
Any hints, or am I trying the impossible?
|
|
|
|
|
You can use Assembly.Load or Assembly.LoadFrom(). Those function will return you an Assembly object. You can then call GetTypes() on that object to get the list of all types. For each Type object, you can then call Activator.CreateInstance() to create an instance and then Type's InvokeMember() to call methods. Something like
<br />
Assembly assembly = Assembly.Load("...");<br />
foreach(Type t in assembly.GetTypes())<br />
{<br />
Object obj = Activator.CreateInstance(t);<br />
t.InvokeMember("MyMethod", BindingFlags.Instance, null, obj, null);<br />
}<br />
Hope this helps.
Regards
Senthil
My Blog
|
|
|
|
|
I wrote a FTP program that would download files from a ftp server and store it on my machine.
Then on my other pc, I mapped the location of that program and run it (2 pcs are on the same network)
I got this error message:
Unhandled Exception: System.Security.SecurityException: Request for the permissi
on of type System.Security.Permissions.FileIOPermission, mscorlib, Version=1.0.5
000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed.
at System.Security.CodeAccessSecurityEngine.CheckTokenBasedSetHelper(Boolean
ignoreGrants, TokenBasedSet grants, TokenBasedSet denied, TokenBasedSet demands)
at System.Security.CodeAccessSecurityEngine.CheckSetHelper(PermissionSet gran
ts, PermissionSet denied, PermissionSet demands)
at tieFtpv2.CExecute..ctor(Boolean display, String command, CXmlDoc myProfile
, Int32 myIndex)
at tieFtpv2.CTieFTP.Main(String[] args)
The state of the failed permission was:
<ipermission class="System.Security.Permissions.FileIOPermission, mscorlib, Vers
ion=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
="" version="1" unrestricted="true">
Could anyone please help me out?
What do i need to do with the Security to be able to run the program on a network?
Thank you so much in advance.
|
|
|
|
|
Thats caused by CAS (Code Access Security). You need to change the policy for the appropiate zone to allow this. This can be achieved by using the wizard in administrative tools, or by the command line tool caspol. More details can be found by googling.
--
Joel Lucsy
|
|
|
|
|
Hi,
I need to install services dynamically at runtime, without using InstallUtil.exe or a setup project. Do I have to use the "old" Win32 service APIs like CreateService or is there a way to do this natively in the framework?
If a train station is where the train stops, what's a workstation...?
|
|
|
|
|
i use sendto and receivefrom functions to ping a host
ex:
sendto(host)
timestart = datetime.now
receivefrom(buf,edp)
timestop = datetime.now - timestart
but the time was too long ,when i ping localhost the time is 56ms
how can reduce the time?
|
|
|
|
|
Since we know nothing of how you're using the SendTo and RecieveFrom functions, and what class is supplying them, there's nothing anyone can tell you. There are a bunch of factors that will affect this, starting with the time source your using, which is terrible for the timing resolution your looking for, what size packets your sending, how name resolution is taking place, ...
RageInTheMachine9532
"...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome
|
|
|
|
|
the code:
namespace mPing
{
using System;
using System.Net;
using System.Net.Sockets;
///
/// The Main Ping Class
///
class Ping
{
//Declare some Constant Variables
const int SOCKET_ERROR = -1;
const int ICMP_ECHO = 8;
///
/// The Starting Point of the Class
/// It Takes the Hostname parameter
///
public static void Main(string[] argv)
{
if(argv.Length==0)
{
//If user did not enter any Parameter inform him
Console.WriteLine("Usage:Ping <hostname> /r") ;
Console.WriteLine("<hostname> The name of the Host who you want to ping");
Console.WriteLine("/r Optional Switch to Ping the host continuously") ;
}
else if(argv.Length==1)
{
//Just the hostname provided by the user
//call the method "PingHost" and pass the HostName as a parameter
PingHost(argv[0]) ;
}
else if(argv.Length==2)
{
//the user provided the hostname and the switch
if(argv[1]=="/r")
{
//loop the ping program
while(true)
{
//call the method "PingHost" and pass the HostName as a parameter
PingHost(argv[0]) ;
}
}
else
{
//if the user provided some other switch
PingHost(argv[0]) ;
}
}
else
{
//Some error occured
Console.WriteLine("Error in Arguments") ;
}
}
///
/// This method takes the "hostname" of the server
/// and then it ping's it and shows the response time
///
public static void PingHost(string host)
{
//Declare the IPHostEntry
IPHostEntry serverHE, fromHE;
int nBytes = 0;
int dwStart = 0, dwStop = 0;
//Initilize a Socket of the Type ICMP
Socket socket = new Socket(AddressFamily.AfINet, SocketType.SockRaw, ProtocolType.ProtICMP);
// Get the server endpoint
try
{
serverHE = DNS.GetHostByName(host);
}
catch(Exception)
{
Console.WriteLine("Host not found"); // fail
return ;
}
// Convert the server IP_EndPoint to an EndPoint
IPEndPoint ipepServer = new IPEndPoint(serverHE.AddressList[0], 0);
EndPoint epServer = (ipepServer);
// Set the receiving endpoint to the client machine
fromHE = DNS.GetHostByName(DNS.GetHostName());
IPEndPoint ipEndPointFrom = new IPEndPoint(fromHE.AddressList[0], 0);
EndPoint EndPointFrom = (ipEndPointFrom);
int PacketSize = 0;
IcmpPacket packet = new IcmpPacket();
// Construct the packet to send
packet.Type = ICMP_ECHO; //8
packet.SubCode = 0;
packet.CheckSum = UInt16.Parse("0");
packet.Identifier = UInt16.Parse("45");
packet.SequenceNumber = UInt16.Parse("0");
int PingData = 32; // sizeof(IcmpPacket) - 8;
packet.Data = new Byte[PingData];
//Initilize the Packet.Data
for (int i = 0; i < PingData; i++)
{
packet.Data[i] = (byte)'#';
}
//Variable to hold the total Packet size
PacketSize = PingData + 8;
Byte [] icmp_pkt_buffer = new Byte[ PacketSize ];
Int32 Index = 0;
//Call a Methos Serialize which counts
//The total number of Bytes in the Packet
Index = Serialize(
packet,
icmp_pkt_buffer,
PacketSize,
PingData );
//Error in Packet Size
if( Index == -1 )
{
Console.WriteLine("Error in Making Packet");
return ;
}
// now get this critter into a UInt16 array
//Get the Half size of the Packet
Double double_length = Convert.ToDouble(Index);
Double dtemp = Math.Ceil( double_length / 2);
int cksum_buffer_length = Convert.ToInt32(dtemp);
//Create a Byte Array
UInt16 [] cksum_buffer = new UInt16[cksum_buffer_length];
//Code to initilize the Uint16 array
int icmp_header_buffer_index = 0;
for( int i = 0; i < cksum_buffer_length; i++ ) {
cksum_buffer[i] =
BitConverter.ToUInt16(icmp_pkt_buffer,icmp_header_buffer_index);
icmp_header_buffer_index += 2;
}
//Call a method which will return a checksum
UInt16 u_cksum = checksum(cksum_buffer, cksum_buffer_length);
//Save the checksum to the Packet
packet.CheckSum = u_cksum;
// Now that we have the checksum, serialize the packet again
Byte [] sendbuf = new Byte[ PacketSize ];
//again check the packet size
Index = Serialize(
packet,
sendbuf,
PacketSize,
PingData );
//if there is a error report it
if( Index == -1 )
{
Console.WriteLine("Error in Making Packet");
return ;
}
dwStart = System.Environment.TickCount; // Start timing
//send the Pack over the socket
if ((nBytes = socket.SendTo(sendbuf, PacketSize, 0, epServer)) == SOCKET_ERROR)
{
Console.WriteLine("Socket Error cannot Send Packet");
}
// Initialize the buffers. The receive buffer is the size of the
// ICMP header plus the IP header (20 bytes)
Byte [] ReceiveBuffer = new Byte[256];
nBytes = 0;
//Receive the bytes
bool recd =false ;
int timeout=0 ;
//loop for checking the time of the server responding
while(!recd)
{
nBytes = socket.ReceiveFrom(ReceiveBuffer, 256, 0, ref EndPointFrom);
if (nBytes == SOCKET_ERROR)
{
Console.WriteLine("Host not Responding") ;
recd=true ;
break;
}
else if(nBytes>0)
{
dwStop = System.Environment.TickCount - dwStart; // stop timing
Console.WriteLine("Reply from "+epServer.ToString()+" in "+dwStop+"MS :Bytes Received"+nBytes);
recd=true;
break;
}
timeout=System.Environment.TickCount - dwStart;
if(timeout>1000)
{
Console.WriteLine("Time Out") ;
recd=true;
}
}
//close the socket
socket.Close();
}
///
/// This method get the Packet and calculates the total size
/// of the Pack by converting it to byte array
///
public static Int32 Serialize( IcmpPacket packet, Byte [] Buffer, Int32 PacketSize, Int32 PingData )
{
Int32 cbReturn = 0;
// serialize the struct into the array
int Index=0;
Byte [] b_type = new Byte[1];
b_type[0] = (packet.Type);
Byte [] b_code = new Byte[1];
b_code[0] = (packet.SubCode);
Byte [] b_cksum = BitConverter.GetBytes(packet.CheckSum);
Byte [] b_id = BitConverter.GetBytes(packet.Identifier);
Byte [] b_seq = BitConverter.GetBytes(packet.SequenceNumber);
// Console.WriteLine("Serialize type ");
Array.Copy( b_type, 0, Buffer, Index, b_type.Length );
Index += b_type.Length;
// Console.WriteLine("Serialize code ");
Array.Copy( b_code, 0, Buffer, Index, b_code.Length );
Index += b_code.Length;
// Console.WriteLine("Serialize cksum ");
Array.Copy( b_cksum, 0, Buffer, Index, b_cksum.Length );
Index += b_cksum.Length;
// Console.WriteLine("Serialize id ");
Array.Copy( b_id, 0, Buffer, Index, b_id.Length );
Index += b_id.Length;
Array.Copy( b_seq, 0, Buffer, Index, b_seq.Length );
Index += b_seq.Length;
// copy the data
Array.Copy( packet.Data, 0, Buffer, Index, PingData );
Index += PingData;
if( Index != PacketSize/* sizeof(IcmpPacket) */) {
cbReturn = -1;
return cbReturn;
}
cbReturn = Index;
return cbReturn;
}
///
/// This Method has the algorithm to make a checksum
///
public static UInt16 checksum( UInt16[] buffer, int size )
{
Int32 cksum = 0;
int counter;
counter = 0;
while ( size > 0 ) {
UInt16 val = buffer[counter];
cksum += Convert.ToInt32( buffer[counter] );
counter += 1;
size -= 1;
}
cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >> 16);
return (UInt16)(~cksum);
}
} // class ping
///
/// Class that holds the Pack information
///
public class IcmpPacket
{
public Byte Type; // type of message
public Byte SubCode; // type of sub code
public UInt16 CheckSum; // ones complement checksum of struct
public UInt16 Identifier; // identifier
public UInt16 SequenceNumber; // sequence number
public Byte [] Data;
} // class IcmpPacket
}
|
|
|
|
|
the end i use two threads to ping more hosts.
one thread calls sendto function,the other calls receivefrom.
if i ping one host twice in one cycle,and the first time it costs 56ms,and the second time costs 1ms,why?
|
|
|
|
|
Look at what your timing! THe code as you wrote it, will time the DNS lookup of the host, the building of the ICMP Packet, opening the socket connection, sending the echo packet, ...
You're not timing the packet travel time, you're timing nearly your entire application from the time you hit enter to the time it takes for the first echo packet to come back. The only thing you weren't timing was how long it took to parse the command line parameters.
RageInTheMachine9532
"...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome
|
|
|
|
|
i have correct it,record the time just before sending the packet,
but the time costed is 56ms too
|
|
|
|
|
Somehow, I doubt it. On top of that, unless you rewrite this code so you setup EVERYTHING you need to send and receive the packet, without doing anything in between the two, your still timing code to setup the receive.
The only thing that'll get the timing down to <10ms on loopback, is to rewrite the code so it's far more efficient. And from what I've seen, you've got a bunch of work to do.
RageInTheMachine9532
"...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome
|
|
|
|
|
Hi
I am looking for a new way to licence our products. We currently ask the user to enter a company name, plus a load of parameters (such as package limits, number of users, expiry date, etc) which are then validated against an authorisation code we provide.
Each of our products have different parameters that relate to the functionality of that product, and as functionality increases, the number of parameters is also increasing.
Therefore, i am attempting to come up with a system that allows the user to enter just two bits of information, the Company Name and an Authorisation Code. The authorisation code is validated against the compan name and then the licence information is extracted out of the authorisation code.
It sounds great in principle, but i've no idea where to start on this, or if it is at all possible.
Any ideas or suggestions would be greatly appreciated.
Thanks
Tom
|
|
|
|
|
hi
i have a sqldb with unicode data column.(nvarchar)
i search the user data entry in textbox in webpage , in database.
please tell me how to convert string to utf8 charset?
thanks
|
|
|
|
|