|
First you have to find all installed printers, and then implement your code logic for selecting appropriate one's for printing the documents.
using System.Drawing.Printing;
// Loop through the string collection of printers
foreach (string strPrinter in PrinterSettings.InstalledPrinters)
{
// Show the name of the printer
MessageBox.Show(strPrinter);
}
By this you will have access to all installed printers. Implement your logic for selecting printer to do the job.
|
|
|
|
|
Hello to every body.
My name is Christian and i´m not a c# developer (I´m a VFP developer) but some how i manage to built a little UDP server listener app in c#.
I needed to do this becouse I will have several vehicles that send a data via GPRS to the server each minute and the server should be listening and decode the data to store in the database (MySql). There will be hundreds of entries per minute. I Hope that somebady can tell me if my code is multithread or not and if it´s not, how can i implement it. Also, if i need multithread in the database part. The code is this:
using System;
using System.IO;
using System.Net.Sockets;
using System.Net;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Threading;
namespace httprequest
{
public partial class udp : Form
{
private delegate void SetTextCallback(string text);
private delegate void SetValCallback(int val);
public udp()
{
InitializeComponent();
}
int i;
Socket soc;
const int bufsize = 1024;
byte[] buf = new byte[bufsize];
string szData;
private void button1_Click(object sender, EventArgs e)
{
try
{
i = 0;
IPEndPoint localIP = new IPEndPoint(IPAddress.Parse(this.textBox2.Text),Convert.ToInt32(this.textBox1.Text));
EndPoint epSender = (EndPoint)localIP;
soc = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
soc.Bind(localIP);
soc.BeginReceiveFrom(buf, 0, buf.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
this.button1.Enabled = false;
this.richTextBox1.Text = "Waiting for DataPacket...";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void SetText(string text)
{
if(i == 0)
{
this.richTextBox1.Clear();
i = 1;
}
this.richTextBox1.Text += text;
this.richTextBox1.Text += Environment.NewLine;
this.richTextBox1.SelectionStart = richTextBox1.Text.Length - 1;
//this.richTextBox1.ScrollToCaret();
if (text != null)
{
string[] geoValues = text.Split(new char[] { ',' });
if (geoValues.Length > 0 && geoValues.Length == 36)
{
string GeoResponse = geoValues[0].Substring(1, 4);
if (GeoResponse == "unit")
{
string unit = geoValues[0].Substring(6);
string reason = geoValues[7].Substring(7);
string eventid = geoValues[8].Substring(8);
string longitude = geoValues[11].Substring(10);
string latitude = geoValues[12].Substring(9);
string gps_valid = geoValues[14].Substring(10);
string gps_connected = geoValues[15].Substring(14);
string velocity = geoValues[17].Substring(9);
string emergency = geoValues[19].Substring(10);
string door = geoValues[21].Substring(5);
string datetime_actual = geoValues[34].Substring(16);
DateTime UTC = Convert.ToDateTime(datetime_actual);
DateTime LOCAL = UTC.ToLocalTime();
string datetime_actual1 = LOCAL.ToString("yyyy/MM/dd HH:mm:ss");
if (eventid != "0" && reason == "4")
{
conexion con = new conexion();
con.InsertRow(unit, reason, eventid, longitude, latitude, gps_valid, gps_connected, velocity, emergency, door, datetime_actual1);
con.closingcon();
}
}
}
}
}
private void WaitForData()
{
IPEndPoint localIP = new IPEndPoint(IPAddress.Parse(this.textBox2.Text), Convert.ToInt32(this.textBox1.Text));
EndPoint epSender = (EndPoint)localIP;
soc.BeginReceiveFrom(buf, 0, buf.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
}
private void OnReceive(IAsyncResult ar)
{
try
{
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
EndPoint epSender = (EndPoint)ipeSender;
int iRx = 0 ;
iRx = soc.EndReceiveFrom(ar,ref epSender);
char[] chars = new char[iRx+1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buf, 0, iRx, chars, 0);
szData = Encoding.Default.GetString(buf, 0, buf.Length);
string text = szData;
if (this.richTextBox1.InvokeRequired)
{
SetTextCallback f = new SetTextCallback(SetText);
this.Invoke(f, new object[] { text });
}
WaitForData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void udp_Load(object sender, EventArgs e)
{
String strHostName = "";
strHostName = Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostByName(strHostName);
IPAddress[] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
this.textBox2.Text = addr[i].ToString();
}
}
private void button3_Click(object sender, EventArgs e)
{
this.richTextBox1.Clear();
}
}
}
|
|
|
|
|
this is codes from web:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace BroadcastExample
{
public partial class Form1 : Form
{
delegate void AppendStringCallback(string text);
AppendStringCallback appendstringcallback;
//Port 51008
/// <summary>
///
/// </summary>
private int port = 51008;
/// <summary>
///
/// </summary>
private UdpClient udpclient;
public Form1()
{
InitializeComponent();
appendstringcallback = new AppendStringCallback(AppendString);
}
/// <summary>
///
/// </summary>
/// <param name="text"></param>
private void AppendString(string text)
{
if (richtextBox2.InvokeRequired == true)
{
this.Invoke(appendstringcallback, text);
}
else
{
richtextBox2.AppendText(text + "\r\n");
}
}
/// <summary>
///
/// </summary>
private void RecData()
{
udpclient = new UdpClient(port);
IPEndPoint remote = null;
while (true)
{
try
{
byte[] bytes = udpclient.Receive(ref remote);
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
AppendString(string.Format("From{0}:{1}", remote, str));
}
catch
{
break;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Thread mythread = new Thread(new ThreadStart(RecData));
mythread.IsBackground = true;
mythread.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
udpclient.Close();
}
private void button1_Click(object sender, EventArgs e)
{
UdpClient myUdpclient = new UdpClient();
try
{
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, port);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(textBox1.Text);
myUdpclient.Send(bytes, bytes.Length, iep);
textBox1.Clear();
myUdpclient.Close();
textBox1.Focus();
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Failed");
}
finally
{
myUdpclient.Close();
}
}
}
}
modified 27-May-14 5:31am.
|
|
|
|
|
|
Hi.
Is it possible to change content of a WebBrowser object in C# without using HTML files ?
I mean :
For example we have following XHTML code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<style type="text/css">
<!--
body,td,th {
color: #000;
}
body {
background-color: #990;
}
-->
</style></head>
<body>
<table width="100%" border="1">
<tr>
<td align="center">TEST01</td>
<td align="center">test02</td>
</tr>
<tr>
<td><p>test03</p></td>
<td align="center">test04</td>
</tr>
</table>
</body>
</html>
Now , I wanna show the design in WebBrowser => http://img143.imageshack.us/img143/6855/50068901.png[^]
I would be appreciate if you guide me !
|
|
|
|
|
I do believe you can set the HTML of the control. If you can't, you can always save this HTML locally and point the control to it.
Christian Graus
Driven to the arms of OSX by Vista.
Read my blog to find out how I've worked around bugs in Microsoft tools and frameworks.
|
|
|
|
|
Christian Graus wrote: I do believe you can set the HTML of the control.
Could you please guide me , which method or property do it in WebBrowser ?
|
|
|
|
|
Try DocumentText[^]
(Try having a look at the documentation some time - it realy is quicker than asking here...)
No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced.
This message is made of fully recyclable Zeros and Ones
|
|
|
|
|
|
it's possible to change content of a webbrowser object in c# by using a string;
for example :
private void WriteHtml(string s){
//stream to string
MemoryStream ms = new MemoryStream();
try{
byte[] htmlcode = System.Text.Encoding.Default.GetBytes(s);
ms.Write(htmlcode,0,htmlcode.Length);
Stream dataStream = ms;
//Position
dataStream.Seek(0,0);
if(axWb.Document!=null){
//to IStream
(axWb.Document as UnsafeNativeMethods.IPersistStreamInit).Load(new UnsafeNativeMethods.ComStreamFromDataStream(dataStream));
}
}finally{
ms.Close();
}
}
modified 27-May-14 5:30am.
|
|
|
|
|
I have the following code snippet in a C# console application and am getting the following error in VS2008 on the last line (bool recExists = myReader.HasRows):
Error 2 Use of unassigned local variable 'myReader'
Here's the code:
string sResponse;<br />
SqlDataReader myReader;<br />
<br />
<br />
sQuery = "Select * from tracking where shipper_id = '" + sShipperId +<br />
"' AND shipper_ack = '" + sShipperAck + "'";<br />
<br />
myCommand1 = new SqlCommand(sQuery, conn);<br />
<br />
try<br />
{<br />
myReader = myCommand1.ExecuteReader();<br />
}<br />
catch (Exception e2)<br />
{<br />
conn.Close();<br />
conn.Dispose();<br />
<br />
sResponse = e2.GetBaseException().ToString() + " " + sQuery;<br />
<br />
}<br />
<br />
bool recExists = myReader.HasRows;
I use this same identical code in a Windows Client app with no problems.
What am I missing????
Thanks,
Dave
|
|
|
|
|
If that's a copy and paste of the code, it should work fine. I'm assuming there's something else that's not clear from what you copied and pasted. Is all of this an exact copy and paste of the whole function ?
Of course, it's not good code. You should check if myreader is null, because if execute reader blows up, it could well be.
Christian Graus
Driven to the arms of OSX by Vista.
Read my blog to find out how I've worked around bugs in Microsoft tools and frameworks.
|
|
|
|
|
Change SqlDataReader myReader; to SqlDataReader myReader = null; and you should be fine
|
|
|
|
|
Excellent....
That worked great, but why do I need to set the value to null in the console app and not in the Windows Forms app????
|
|
|
|
|
(Just a guess since I don't know all your code) Maybe the SqlDataReader used to be a field instead of a local? Fields are initialized automatically whereas locals aren't so they often need explicit initialization
|
|
|
|
|
Oh - yeah, I see the issue now. That is really dumb, IMO, I've had that happen too.
Christian Graus
Driven to the arms of OSX by Vista.
Read my blog to find out how I've worked around bugs in Microsoft tools and frameworks.
|
|
|
|
|
Try your code like this:
string sResponse;
SqlDataReader myReader;
bool recExists = false;
// Check existence of tracking record
sQuery = "Select * from tracking where shipper_id = '" + sShipperId +
"' AND shipper_ack = '" + sShipperAck + "'";
myCommand1 = new SqlCommand(sQuery, conn);
try
{
myReader = myCommand1.ExecuteReader();
bool recExists = myReader.HasRows;
}
catch (Exception e2)
{
conn.Close();
conn.Dispose();
sResponse = e2.GetBaseException().ToString() + " " + sQuery;
}
// for example
return recExists;
Hope this helps
|
|
|
|
|
change "SqlDataReader myReader;" to "SqlDataReader myReader = null;"
and try again.
modified 27-May-14 5:30am.
|
|
|
|
|
Hai friends I am facing some problems while operating powerpoint using c# application. The problem is I was able to operate the powerpoint only when I am opening it or creating it by c# application. Does any of you have ideas on how to operate the powerpoint, which is already opened in the system.
|
|
|
|
|
vijay_varma86 wrote: Does any of you have ideas on how to operate the powerpoint, which is already opened in the system.
What do you mean by operating?
Manas Bhardwaj
Please remember to rate helpful or unhelpful answers, it lets us and people reading the forums know if our answers are any good.
|
|
|
|
|
OOPS! I mean moving the powerpoint slideshow back and forth
|
|
|
|
|
I am not sure that's possible. I know you can work with powerpoint using the office toolkit, in .NET, but I don't know if Office allows an external program to find instances already running, and control them.
Christian Graus
Driven to the arms of OSX by Vista.
Read my blog to find out how I've worked around bugs in Microsoft tools and frameworks.
|
|
|
|
|
This is the first time i've used a FileSystemWatcher, so i might well be doing something very basic wrong. The code below is what i use to start the FileSystemWatcher.
_fileSystemWatcher = new FileSystemWatcher(path, "*.sql");
_fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite;
_fileSystemWatcher.Created += new FileSystemEventHandler(FileSystemWatcher_Created);
_fileSystemWatcher.Error += new ErrorEventHandler(FileSystemWatcher_Error);
_fileSystemWatcher.EnableRaisingEvents = true;
But, i never seem to get an events raised. The path is set to the correct folder and i am creating files with an sql extension when my program runs, so i thought i would see some info.
I am running Win7, if thats any help...
Regards,
Gareth.
(FKA gareth111)
|
|
|
|
|
I just try your code, it works if you remove the line with "NotifyFilter".
|
|
|
|
|
Cheers.
I changed it to "NotifyFilters.FileName", as i am only interested in new files being created.
Regards,
Gareth.
(FKA gareth111)
|
|
|
|
|