|
An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in system.windows.forms.dll<br />
<br />
Additional information: Unable to get the window handle for the 'AxWebBrowser' control. Windowless ActiveX controls are not supported.
This happens whenever the application terminates.
Sammy
"A good friend, is like a good book: the inside is better than the cover..."
|
|
|
|
|
The only instance I can find of something like this has a bit of a weird solution.
Try putting the WebBrowser control in a Panel control.
RageInTheMachine9532
|
|
|
|
|
In your container, override Dispose(bool) (if it isn't already, which VS.NET does automatically when you create a new class from the appropriate templates) and be sure to call AxWebBrowser.Dispose . This typically helps.
The problem is basically a race condition. The window gets destroyed (hence, no window handle) before the control itself is cleaned-up.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
I am getting a runtime exception when i register a remote client for receving events from the server.
I have 3 main components in my solution
an interface to be shared between client and server
using System;
namespace ItfDelegate
{
public delegate void RemoteCall(string p);
public interface IDelegateHandler
{
void HandleRemote(string p);
event RemoteCall GetStock;
}
}
The server (registered as single call)
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using ItfDelegate;
namespace cbConsoleServer
{
class ClsServer:MarshalByRefObject,IDelegateHandler
{
public event RemoteCall GetStock;
public void HandleRemote(string p)
{
GetStock(p);
}
[STAThread]
static void Main(string[] args)
{
......standard single call registration code
}
}
}
And the remote client that registers for callbacks
using ItfDelegate;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
namespace RemoteDelegateClient
{
[Serializable]
class ClsClientHandler
{
string strinit;
public void Getmystats(string s)
{
strinit=s;
}
[STAThread]
static void Main(string[] args)
{
..gettting server proxy through activator.getobject
ClsClientHandler cs = new ClsClientHandler();
IDelegateHandler svr=(IDelegateHandler)o;
svr.GetStock += new RemoteCall(cs.Getmystats);
svr.HandleRemote(cs.ToString());
Console.WriteLine(cs.strinit);
}
}
}
I get an exception while registering the client with the event.What do i need to do?THe stack trace is as follows
Unhandled Exception:
System.Runtime.Serialization.SerializationException: Parse
Error, no assembly associated with Xml key a2:http://schemas.microsoft.com/clr/n
sassem/RemoteDelegateClient/RemoteDelegateClient%2C%20Version%3D1.0.1545.32282%2
C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull ClsClientHandler
Server stack trace:
at System.Runtime.Serialization.Formatters.Soap.SoapHandler.ProcessGetType(St
ring value, String xmlKey, String& assemblyString)
at System.Runtime.Serialization.Formatters.Soap.SoapHandler.ProcessType(Parse
Record pr, ParseRecord objectPr)
at System.Runtime.Serialization.Formatters.Soap.SoapHandler.ProcessAttributes
(ParseRecord pr, ParseRecord objectPr)
at System.Runtime.Serialization.Formatters.Soap.SoapHandler.StartChildren()
at System.Runtime.Serialization.Formatters.Soap.SoapParser.ParseXml()
at System.Runtime.Serialization.Formatters.Soap.SoapParser.Run()
at System.Runtime.Serialization.Formatters.Soap.ObjectReader.Deserialize(Head
erHandler handler, ISerParser serParser)
at System.Runtime.Serialization.Formatters.Soap.SoapFormatter.Deserialize(Str
eam serializationStream, HeaderHandler handler)
at System.Runtime.Remoting.Channels.SoapServerFormatterSink.ProcessMessage(IS
erverChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestH
eaders, Stream requestStream, IMessage& responseMsg, ITransportHeaders& response
Headers, Stream& responseStream)
Exception rethrown at [0]:
|
|
|
|
|
The exception states that the assembly to which the callback points cannot be found, which means that the server doesn't know how to deserialize that type since it doesn't exist in a resolvable path on the server (i.e., in the same directory as the remoting server, in the GAC, or in a number of other places that the .config file can also specify). You need to provide that client assembly to the server. Typically, though, just use a shared assembly with an interface that would have the callback method, which should do the trick since the server shouldn't care about the implementation so long as you pass the interface's implementation of the callback method declared using the interface itself.
Also, if the remoting object is registered as single call, the may not work depending on how you call it. The remoting object would be instantiated only for that single method call, so unless you invoke the callback within that call it won't work because the object would be disposed after completing the method call.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Both my client and server use asynchronous network read and file reads.
the procedure is:
my client sends a string(latitude and longitude) and the server reads from the network stream.
the server uses the latitude and longitude and plots it in a map and send the length of the block first and then the block(2048 byte blocks).
in the first round all fine.
but when the second round starts that is when the client sends latitude/longitude and when the server sends the length,we get binary and the prog hangs.
code for server is
[CODE]
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Data.SqlClient;
namespace AsyncServer1
{
///
/// Summary description for Form1.
///
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
///
/// Required designer variable.
///
///
// Bitmap b1;
public Thread t1;
private System.ComponentModel.IContainer components;
private System.Windows.Forms.Button button3;
private System.Data.SqlClient.SqlConnection sqlConnection1;
private System.Windows.Forms.Button button2;
int bytesRead;
//static int zoom=2;
//float la,lo,la1,lo1;
// Graphics g;
//int id;
float x1=(float)49,x2=(float)141.1297,y1=(float)46,y2=(float)344.8689;
float la,lo,p1=0,p2=0;
static string st;
float xb1,xb2,yb1,yb2,lab1,lab2,lob1,lob2;
float m,c;
Graphics g;
static int zoom=2;
int flag=0;
int count=0;
int id,id1=-1;
Bitmap bmp1,nw1;
string latu;
int bytesRead1;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label2;
//byte[] len=new byte[8];
byte[] len=new byte[8];
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
///
/// Clean up any resources being used.
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.sqlConnection1 = new System.Data.SqlClient.SqlConnection();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.tabPage3 = new System.Windows.Forms.TabPage();
this.label2 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.tabControl1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.tabPage3.SuspendLayout();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(176, 192);
this.button1.Name = "button1";
this.button1.TabIndex = 0;
this.button1.Text = "Start";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(88, 192);
this.button2.Name = "button2";
this.button2.TabIndex = 1;
this.button2.Text = "Hello";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(8, 192);
this.button3.Name = "button3";
this.button3.TabIndex = 3;
this.button3.Text = "Stop";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// sqlConnection1
//
this.sqlConnection1.ConnectionString = "workstation id=C8A2;packet size=4096;integrated security=SSPI;data source=\"C8A2\\V" +
"SDOTNET\";persist security info=False;initial catalog=Project";
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Controls.Add(this.tabPage3);
this.tabControl1.Location = new System.Drawing.Point(16, 24);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(280, 248);
this.tabControl1.TabIndex = 4;
//
// tabPage2
//
this.tabPage2.Controls.Add(this.button3);
this.tabPage2.Controls.Add(this.button2);
this.tabPage2.Controls.Add(this.button1);
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Size = new System.Drawing.Size(272, 222);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Main";
//
// tabPage3
//
this.tabPage3.Controls.Add(this.label2);
this.tabPage3.Controls.Add(this.textBox2);
this.tabPage3.Controls.Add(this.label1);
this.tabPage3.Controls.Add(this.textBox1);
this.tabPage3.Location = new System.Drawing.Point(4, 22);
this.tabPage3.Name = "tabPage3";
this.tabPage3.Size = new System.Drawing.Size(272, 222);
this.tabPage3.TabIndex = 2;
this.tabPage3.Text = "Settings";
//
// label2
//
this.label2.Location = new System.Drawing.Point(24, 80);
this.label2.Name = "label2";
this.label2.TabIndex = 3;
this.label2.Text = "Port";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(128, 80);
this.textBox2.Name = "textBox2";
this.textBox2.TabIndex = 2;
this.textBox2.Text = "65000";
//
// label1
//
this.label1.Location = new System.Drawing.Point(24, 40);
this.label1.Name = "label1";
this.label1.TabIndex = 1;
this.label1.Text = "IP Address";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(128, 40);
this.textBox1.Name = "textBox1";
this.textBox1.TabIndex = 0;
this.textBox1.Text = "192.168.0.2";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(304, 293);
this.Controls.Add(this.tabControl1);
this.Name = "Form1";
this.Text = "Form1";
this.tabControl1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.tabPage3.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
void hee()
{
IPAddress localAddr=IPAddress.Parse(textBox1.Text);
int port=System.Convert.ToInt32(textBox2.Text);
TcpListener tcpListener=new TcpListener(localAddr,port);
tcpListener.Start();
for(;;)
{
Socket socketForClient=tcpListener.AcceptSocket();
if(socketForClient.Connected)
{
Console.WriteLine("Client connected");
// MessageBox.Show("Client Connected");
ClientHandler handler=new ClientHandler(socketForClient);
handler.StartRead();
}
}
}
private void button1_Click(object sender, System.EventArgs e)
{
t1=new Thread(new ThreadStart(hee));
t1.Start();
}
private void button2_Click(object sender, System.EventArgs e)
{
MessageBox.Show("Hello World");
}
private void pictureBox1_Click(object sender, System.EventArgs e)
{
}
private void button3_Click(object sender, System.EventArgs e)
{
t1.Abort();
}
class ClientHandler : Form1
{
private const int BufferSize=2048;
private byte[] buffer;
private Socket socket;
private static NetworkStream networkStream;
private Stream inputStream;
StreamWriter writer1;
StreamReader read1;
byte[] latarray=new byte[2048];
private AsyncCallback callbackRead;
private AsyncCallback callbackWrite;
private AsyncCallback myFileCallBack;
private AsyncCallback latCallback;
private AsyncCallback StartReadCallback;
System.Threading.ManualResetEvent m1;
int temphandle;
public ClientHandler(Socket socketForClient)
{
socket=socketForClient;
buffer=new byte[2048];
networkStream=new NetworkStream(socket);
read1=new StreamReader(networkStream);
myFileCallBack=new AsyncCallback(this.OnFileCompletedRead);
temphandle=this.Handle.ToInt32();
callbackWrite=new AsyncCallback(this.OnWriteComplete);
latCallback=new AsyncCallback(this.OnLatComplete);
StartReadCallback=new AsyncCallback(this.StartRead1);
}
public void StartRead()
{
m1=new System.Threading.ManualResetEvent(false);
for(;;)
{
networkStream.BeginRead(latarray,0,2048,latCallback,null);
m1.WaitOne();
m1.Reset();
}
}
public void StartRead1(IAsyncResult ar)
{
StartReadCallback.EndInvoke(ar);
networkStream.BeginRead(latarray,0,2048,latCallback,null);
}
void OnLatComplete(IAsyncResult ar)
{
networkStream.EndRead(ar);
OnReadComplete();
}
private void OnReadComplete()
{
string fileName=System.Text.Encoding.Unicode.GetString(latarray);
Console.WriteLine("latitude/longi {0} lat/long",fileName);
int r=fileName.IndexOf('|');
int l1=fileName.Length-r;
string lon=fileName.Substring(r+1,l1-1);
string lat=fileName.Substring(0,r);
Console.WriteLine("lat is {0} lon is {1}",lat,lon);
la=System.Convert.ToSingle(lat);
lo=System.Convert.ToSingle(lon);
map();
inputStream=File.OpenRead(@"c:\tmp"+temphandle.ToString()+".jpg");
inputStream.BeginRead(buffer,8,buffer.Length-8,myFileCallBack,null);
}
void map()
{
float lax1,lax2,lox1,lox2;
int zoom1;
if(sqlConnection1.State==ConnectionState.Closed)
sqlConnection1.Open();
SqlCommand cmd=sqlConnection1.CreateCommand();
cmd.CommandText="SELECT id,lax1,lox1,lax2,lox2,zoom FROM Table1";
SqlDataReader r=cmd.ExecuteReader();
while(r.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",r["id"],r["lax1"],r["lox1"]);
if((int)r["id"]==2)
Console.WriteLine("ha");
lax1=System.Convert.ToSingle(r["lax1"]);
lox1=System.Convert.ToSingle(r["lox1"]);
lax2=System.Convert.ToSingle(r["lax2"]);
lox2=System.Convert.ToSingle(r["lox2"]);
zoom1=(int)r["zoom"];
id=(int)r["id"];
Console.WriteLine("la is {0} lax1 is {1} lax2 is {2}",la,lax1,lax2);
Console.WriteLine("lo is {0} lax1 is {1} lox2 is {2}",lo,lox1,lox2);
if(lo<=lox2&&la>=lax2&&lo>lox1&&la<lax1&&zoom1==zoom)
{
="" break;
="" }
=""
="" }
="" console.writeline("id="" is="" {0}",id);
="" r.close();
="" sqlcommand="" r1="sqlConnection1.CreateCommand();
" r1.commandtext="SELECT map FROM Table1 WHERE id=" +id;
="" byte[]="" b="(byte[])r1.ExecuteScalar();
" if(b.length="">0)
{
MemoryStream m=new MemoryStream(b,true);
m.Write(b,0,b.Length);
bmp1=new Bitmap(m);
g=Graphics.FromImage(bmp1);
r1.Dispose();
SqlCommand r2=sqlConnection1.CreateCommand();
r2.CommandText="SELECT x1,y1,x2,y2,la1,la2,lo1,lo2 FROM Table1 WHERE id="+id;
SqlDataReader ha=r2.ExecuteReader();
ha.Read();
xb1=System.Convert.ToSingle(ha["x1"]);
xb2=System.Convert.ToSingle(ha["x2"]);
yb1=System.Convert.ToSingle(ha["y1"]);
yb2=System.Convert.ToSingle(ha["y2"]);
lab1=System.Convert.ToSingle(ha["la1"]);
lob1=System.Convert.ToSingle(ha["lo1"]);
lab2=System.Convert.ToSingle(ha["la2"]);
lob2=System.Convert.ToSingle(ha["lo2"]);
ha.Close();
r2.Dispose();
}
getcoord(xb1,yb1,lab1,lob1,xb2,yb2,lab2,lob2,(float)10,(float)11,(float)12,(float)13);
SolidBrush s=new SolidBrush(Color.Blue);
Console.WriteLine("he p1 is {0},p2 is {1}",p1,p2);
g.FillEllipse(s,p1-(float)2.54,p2-(float)2.54,5,5);
bmp1.Save(@"c:\tmp"+temphandle.ToString()+".jpg");
if(sqlConnection1.State==ConnectionState.Open)
sqlConnection1.Close();
id1=id;
}
void getcoord(float x1,float y1,float la1,float lo1,float x2,float y2,float la2,float lo2,float x3,float y3,float la3,float lo3)
{
float x,y,t1,t2;
float xa1,ya1,xa2,ya2,xa3,ya3;
x=(x1-x2)/(lo1-lo2);
y=(y1-y2)/(la1-la2);
t1=x*(lo-lo1);
t2=y*(la-la1);
xa1=x1+t1;
ya1=y1+t2;
x=(x2-x3)/(lo2-lo3);
y=(y2-y3)/(la2-la3);
t1=x*(lo-lo2);
t2=y*(la-la2);
xa2=x2+t1;
ya2=y2+t2;
x=(x1-x3)/(lo1-lo3);
y=(y1-y3)/(la1-la3);
t1=x*(lo-lo1);
t2=y*(la-la1);
xa3=x1+t1;
ya3=y1+t2;
p1=xa1;
p2=ya1;
Console.WriteLine("t1 is{0},t2 is {1}",t1,t2);
Console.WriteLine("p1 is{0},p2 is {1}",p1,p2);
}
void OnLengthComplete(IAsyncResult asyncResult)
{
networkStream.EndRead(asyncResult);
}
void OnFileCompletedRead(IAsyncResult asyncResult)
{
byte[] len1;
bytesRead=inputStream.EndRead(asyncResult);
Console.WriteLine("length is {0}",bytesRead);
len1=Encoding.Unicode.GetBytes(bytesRead.ToString());
for(int i=0;i<=len1.Length-1;i++)
len[i]=len1[i];
for(int i=len1.Length;i<=7;i++)
len[i]=0;
if(bytesRead>0)
{
for(int i=0;i<=7;i++)
buffer[i]=len[i];
string test=Encoding.Unicode.GetString(len);
Console.WriteLine("test string is {0}",test);
networkStream.BeginWrite(buffer,0,bytesRead+8,callbackWrite,null);
}
else
{
Console.WriteLine("Finished");
inputStream.Close();
File.Delete(@"c:\tmp"+temphandle.ToString()+".jpg");
Console.WriteLine("everything over");
//networkStream.Flush();
m1.Set();
//System.AsyncCallback.
//networkStream.BeginWrite(buffer,0,0,
// StartRead();
// StartReadCallback.BeginInvoke(asyncResult,StartReadCallback,null);
}
}
private void OnWriteComplete(IAsyncResult ar)
{
networkStream.EndWrite(ar);
Console.WriteLine("Write complete p1 is {0}",p1);
if(bytesRead==2040)
inputStream.BeginRead(buffer,8,buffer.Length-8,myFileCallBack,null);
else
{
Console.WriteLine("Finished");
inputStream.Close();
File.Delete(@"c:\tmp"+temphandle.ToString()+".jpg");
Console.WriteLine("everything over");
//networkStream.Flush();
m1.Set();
}
}
}
}
}
[/CODE]
code for the client is
[CODE]
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace AsyncClient2
{
///
/// Summary description for Form1.
///
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private const int BufferSize=2048;
private static NetworkStream streamToServer;
private StreamReader reader2;
private AsyncCallback callbackRead;
private AsyncCallback myFileCallBack;
private AsyncCallback lengthCallback;
private AsyncCallback latCallback;
private AsyncCallback ha1Callback;
System.Threading.ManualResetEvent m1;
StreamReader reader1;
static int count=0;
Bitmap b;
int bytesRead;
int readlength;
byte[] latarray=new byte[2048];
//char[] buffer=new char[BufferSize];
byte[] buffer=new byte[2048];
// FileStream fs = new FileStream(@"sibi.jpg", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
private Stream outputStream;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox textBox1;
string length;
byte[] len=new byte[8];
static string hello;
TcpClient tcpSocket;
private System.ComponentModel.IContainer components;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
callbackRead=new AsyncCallback(this.OnReadComplete);
myFileCallBack=new AsyncCallback(this.OnFileCompletedWrite);
lengthCallback=new AsyncCallback(this.OnLengthComplete);
latCallback=new AsyncCallback(this.OnLatComplete);
ha1Callback=new AsyncCallback(this.ha1);
reader1=File.OpenText(@"c:\6.txt");
}
///
/// Clean up any resources being used.
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.button2 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(168, 264);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(64, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Connect";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// pictureBox1
//
this.pictureBox1.Location = new System.Drawing.Point(4, 8);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(232, 248);
this.pictureBox1.TabIndex = 1;
this.pictureBox1.TabStop = false;
//this.pictureBox1.Click += new System.EventHandler(this.pictureBox1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(8, 264);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(64, 23);
this.button2.TabIndex = 2;
this.button2.Text = "Icon";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(80, 264);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(72, 20);
this.textBox1.TabIndex = 3;
this.textBox1.Text = "C8A2";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(240, 293);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button2);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
void ha()
{
string serverName=textBox1.Text;
Console.WriteLine("Connecting to {0}",serverName);
tcpSocket=new TcpClient(serverName,65000);
streamToServer=tcpSocket.GetStream();
reader2=new StreamReader(streamToServer);
string message=reader1.ReadLine();
m1=new System.Threading.ManualResetEvent(false);
Console.WriteLine("Sending {0} to server.",message);
byte[] latarray1=System.Text.Encoding.Unicode.GetBytes(message);
for(int i=0;i<=latarray1.Length-1;i++)
latarray[i]=latarray1[i];
for(int i=latarray1.Length;i<=2047;i++)
latarray[i]=0;
for(;;)
{
streamToServer.BeginWrite(latarray,0,2048,latCallback,null);
m1.WaitOne();
m1.Reset();
}
//streamToServer.BeginWrite(latarray,0,2048,latCallback,null);
}
void OnLatComplete(IAsyncResult ar)
{
streamToServer.EndRead(ar);
//streamToServer.Flush();
streamToServer.BeginRead(len,0,8,lengthCallback,null);
}
void ha1(IAsyncResult ar)
{
string message=reader1.ReadLine();
Console.WriteLine("Sending {0} to server.",message);
byte[] latarray1=System.Text.Encoding.Unicode.GetBytes(message);
for(int i=0;i<=latarray1.Length-1;i++)
latarray[i]=latarray1[i];
for(int i=latarray1.Length;i<=2047;i++)
latarray[i]=0;
}
private void button1_Click(object sender, System.EventArgs e)
{
ha();
}
private void OnLengthComplete(IAsyncResult ar)
{
int l=streamToServer.EndRead(ar);
hello=System.Text.Encoding.Unicode.GetString(len);
Console.WriteLine("hello is {0}",hello);
readlength=Convert.ToInt16(hello);
Console.WriteLine("readlength is {0}",readlength);
streamToServer.BeginRead(buffer,0,readlength,callbackRead,null);
}
private void OnReadComplete(IAsyncResult ar)
{
bytesRead=streamToServer.EndRead(ar);
Console.WriteLine("bytesRead is {0}",bytesRead);
if(bytesRead>0)
{
if(count==0)
outputStream=File.Open(@"sibi.jpg",FileMode.OpenOrCreate,FileAccess.ReadWrite);
outputStream.BeginWrite(buffer,0,bytesRead,myFileCallBack,null);
if(count==0)
count=1;
}
else
{
Bitmap b=new Bitmap(outputStream);
pictureBox1.Image=b;
count=0;
}
}
void OnFileCompletedWrite(IAsyncResult asyncResult)
{
outputStream.EndWrite(asyncResult);
streamToServer.BeginRead(len,0,8,lengthCallback,null);
}
private void button2_Click(object sender, System.EventArgs e)
{
Bitmap b=new Bitmap(@"c:\new-11.png");
pictureBox1.Image=b;
System.Drawing.Icon ic=new System.Drawing.Icon(@"c:\1.ico");
Graphics g=Graphics.FromImage(b);
g.DrawIcon(ic,100,100);
}
}
}
[/CODE]
i am using a database.
u can replace it by a file.
can u please help me out
sibish
|
|
|
|
|
Hi,
I have been searching in the web for algorightms or tips about generating diagrams from a database automatically.
I know it's not an easy task, graph theory, exponential algorithms, but I'm searching some starting point, do you know some place / web where I can get that info ( if it has some examples in C# that would be even better ).
Thanks in advance, greetings
Braulio
|
|
|
|
|
Is there an easy method, in c#, to change a form? For instance, in MFC I wrote an application where I had the frame, and then form was shown inside the frame. In this method, I was able to create many forms (CFormView in MFC) and then I could change the forms while keeping the same frame. I'm trying to write this same application using c#, because I find that the controls (windows) are MUCH better! I'm sure it's possible to do this, but how much a pain in the butt is it? Thanks for you help!
|
|
|
|
|
In a very simplistic manner, assume two control classes (or even two instances of the same control class): UserControl1 and UserControl2 , both to be exclusively hosted by MainForm :
public class MainForm : Form
{
private UserControl1 uc1;
private UserControl2 uc2;
private void Next()
{
Controls.Remove(uc1);
Controls.Add(uc2);
}
} Remove one and add the other. This won't create or dispose the instances, just remove them from the collection of child controls for that container (and they can be parented only to one container as with all windows).
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
I understand your example about creating either multiple controls, or else multiple instances of the same control. My biggest problem now is that I have data that I will load from a file at startup. How is it possible for each of my controls to be able to access this data?
Thanks for your previous help, it was very useful!
|
|
|
|
|
See the documentation for the ConfigurationSettings class. .NET applications typically use .config files (XML files) which have different sections (like AppSettings ), of which you can create your own. Search CodeProject for "configuration settings" as well for more examples and articles.
Since I'm guessing you deleted your other post that I got notification of, I would also suggestion that you skim through the articles in the .NET Framework SDK, under "Programming with the .NET Framework". Reviewing the classes in the System.Windows.Forms namespace would also be beneficial.
Above all, keep in mind there's no magic here. Just like MFC wraps the native Win32 functions for common controls and windows management, so does Windows Forms. In a pinch, you can always override Control.WndProc and handle notification messages like you're probably used in with MFC, but you'll have to P/Invoke (declare external, native functions in C#) native functions like SendMessage , re-create necessary structs (like LVITEM for a ListView or something), and define (if you desire, which is handy) the constants (like private const int WM_HSCROLL = 0x0114 ).
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
How can i convert Links into Images using Rich Text Box in Visual c#.Net
This is Jitendra
|
|
|
|
|
You need to find the images :
Regex r = new Regex("<[^>]*\\n?.*=(\"|')?(?<imog>.*\\.jpg)(\"|')?.*?\\n?[^<]*>");
MatchCollection Matches = r.Matches(rtb.Text);
and then replace them with an image
foreach (Match m in Matches)
{
string imageName = m.Groups["imog"].Value;
Image img = Image.FromFile(imageName);
rtb.SelectionStart = m.Index;
rtb.SelectionLength = m.Length;
Clipboard.SetDataObject(img);
rtb.Paste();
}
Warning though this code does not work properly. Problem one is the regular expression which I found off the web doesn't handle img tags very well.
Problem two is find the SelectionStart once you've started replacing the text.
I know this sucks but i thought it would give you a start.
HTH
Circumstances have overtaken man. His old languages are not sufficient to describe what is happening, and what is about to happen. To think in terms of a millennium or such tame concepts as the 'eleventh hour' is ridiculous.
Better that he should realize that he is in an era which might be accurately described as the 'eighth
day of the week'. Idries Shah
|
|
|
|
|
Thanks .
This is Jitendra
|
|
|
|
|
How can i convert Links into Images using Rich Text Box
This is Jitendra
|
|
|
|
|
Everytime I open up a C# project and click build, a new assembly gets created even if none of the source files and references are modified. However, once I build once, then for that session, any further build will not create a new assembly (unless I change something of course). How to make the first build after opening the project to also not build if nothing has changed?
|
|
|
|
|
Opening VS.NET treats the project like its new/modified. There's no documented way to change this that I've ever seen.
If you're concerned about versioning problems, first don't use automatic version incrementing in larger projects with multiple assemblies. Not only does it create problems like this, but it makes deployment and tracking a pain in the arse. You can also facilitate better builds by using project references for projects in your solution instead of assembly references if you're not already. This keep dependencies in sync and keeps the build configuration constant for all projects.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Thanks for the info.
The problem I have is that I have a library project which gets referenced (yes, project reference) by some exe projects. Everytime I compile one exe project, the library project also gets compiled too. Isn't it better to use assembly references in this case? That way, I only build the library project whenever I change it?
|
|
|
|
|
I wouldn't say it's "better", but you sure could. Just make sure that when switching between build configurations you update the assembly reference (if you use pre-proc conditions to change any of the code, for example).
The nice thing about project references is that is how VS.NET sets up dependencies (it's odd you can't do this manually like with VC++ projects, though). If your library project changes (and I understand that it will appear to at startup and that's annoying), your apps should recompile it if the recompile is necessary. It will only get built once until the library project changes again (or you restart VS.NET).
Again, it's up to you and really doesn't matter, but this is just something to consider.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
I'm making the switch from MFC to C#, or at least attempting, so here's an opportunity for a couple of you to get points for posting an answer to what is probably an easy question (keep looking for my name, more will be coming.) At any rate, I want to be able to use a DataGrid object on my form. I have read through countless articles, but I'm just not getting it. All I want is 8 columns, each of a primitive type (int, string, double). I just want the grid to be blank, with the first row showing, then when the user puts information into the first row, the next row shows up, etc. Is this really that hard to do? I'm using Visual Studios .NET, fyi.
Please only point me to an article if it answers my question...so far all of the articles I've found just bind the grid to a pre-existing data source...that's not what I have here. Thanks a ton...and for those using c# for a while...don't bash me too hard!
|
|
|
|
|
Just create a new DataTable, add a few columns of the appropriate type, and set the grid data source to the new table You have to make sure the grid allows new:
DataTable t = new DataTable();
t.TableName = "test";
t.Columns.AddRange(
new DataColumn[] {
new DataColumn("one", typeof(string)),
new DataColumn("two", typeof(int)),
new DataColumn("three", typeof(DateTime)),
new DataColumn("four", typeof(string)),
new DataColumn("five", typeof(bool)),
new DataColumn("six", typeof(double))
});
dataGrid1.DataSource = t;
The above code in my small test app was in the constructor of a form after the InitializeComponent() call. I created a C# Windows Forms project, added a DataGrid, then added the above code.
It should be a simple starting point.
|
|
|
|
|
The code that uses pre-existing data sources is what you need. The DataGrid - without overriding practically everything about it - is a data-bound control. If you use it for data entry, you must get the data from it somehow. You can do this by retrieving the DataSource value, which can be anything that implements IList or IListSource (like a DataSet , ArrayList , etc.).
Nothing says that data has to contain data initially, though. The easiest example is to use a DataSet , which you can - through code or by creating a typed DataSet - define a table and columns. In your DataGrid , set the DataSource to the empty DataSet instance, the DataMember to the name of the DataTable within the DataSet and you're basically done. You'll find that you'll have more control over the layout if you use the DataGrid.TableStyles property to add a corresponding DataGridTableStyle with various (8 in your case) DataGridColumnStyle s. The documentation in the .NET Framework SDK for any one of those 3 aforementioned properties and classes will have an example (same example, IIRC).
You could also use an ArrayList or any other type of list with a list of classes that define properties and bind your DataGrid in the same way. The problem is this can be difficult if you have no initial data since the DataGrid wouldn't know how to construct your data source.
When the DataGrid is bound - even to an empty data source - rows can be added like you want. With a data source, the DataGrid can't add rows to anything because it has nothing to add them to. Give it a data source (again, I recommend a DataSet ) and now it has something to modify since it's just a view on the data source.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
hi,
I want to ask, how can I get mouse position in realtime except getting it inside MouseEvent Handler?
The Idea is, I have one context menu, after I clicked the menu button, I want to show one dialog at the mouse location immediately.
Thanks for help
|
|
|
|
|
You can get the mouse position at any time - in screen coordinates - using the static Control.MousePosition method which returns a Point . To convert these coordinates to form coordinates, call PointToClient with the Point on the control that you want to the relative coordinates for (relative to the upper-left corner).
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Hello,
In my app a user chooses an icon. I want to save that icon to a file. However, no matter what I try, the image is saved incorrectly. I did some searching and found that there may be some troubles with saving the alpha channel info. I am no expert on images so I have no idea.
All I want to do is save the icon to a file. I tried
<br />
using (StreamWriter swI = new StreamWriter(Application.StartupPath + "/TestI.ico")) <br />
{<br />
ico.Save(swI.BaseStream);<br />
}<br />
However, the icon is saved in poor quality and when I load it, it looks pretty bad.
Can someone please help me? I just want to save an icon and be able to load it when I need it.
P.S. Is it possible for me to save multiple icons in one file and extract the icons one at a time?
Thanx for the help,
-Flack
|
|
|
|
|