I write a program to execute and send msg using windows net send command.Its working fine for single receptor.But the problem happen when i want to send message in many receptors. i use a for loop to take receptor name from a list box. Here all message go to the first receptor.The problem happen on process execution.So far i guess the process is not clear or dead on the time.
Can any body guide me how i can send the msg to multiple users at a time?
my code below:
string sendingMessage = messageRichTextBox.Text;
string[] recepentAddressArray = new string[recepentAddressListBox.Items.Count];
for (int j = 0; j < recepentAddressListBox.Items.Count; j++) // Getting address from list box
{
recepentAddressArray[j] = recepentAddressListBox.Items[j].ToString();
string recepantAddress = recepentAddressArray[j];
try
{
string strLine = "net send " + recepantAddress + " " + sendingMessage + " >C:netsend.log";
FileStream fs = new FileStream("c:netsend.bat", FileMode.Create, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.BaseStream.Seek(0, SeekOrigin.End);
streamWriter.Write(strLine);
streamWriter.Flush();
streamWriter.Close();
fs.Close();
Process p = new Process();
p.StartInfo.FileName = "C:netsend.bat";
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
p.WaitForExit();
p.Close();
FileStream fsOutput = new FileStream("C:netsend.log", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fsOutput);
reader.BaseStream.Seek(0, SeekOrigin.Begin);
string strOut = reader.ReadLine();
reader.Close();
fsOutput.Close();
}
catch (Exception)
{
MessageBox.Show("ERROR");
}
}
Related
I am writing a sample pdf signer using itextsharp.dll n the digital signature is on a usb device.
it's working nicely only problem is that some times the signing gets completely stops for hours together.
I have found that the signing process goes to digital issuer site to get CRL to embed in the signed document increasing it's size from 100kb to 1300kb+ and also signs document very slow due to getting CRL from issuer site.
but if I disable internet the file gets signed very fast and size increase is just 5-10kb.
So my question precisely is how can I instruct the signing process not to go online to get CRL n simply sign the document fast with less size increase in original document.
public void Sign(ICollection<X509Certificate> chain, X509Certificate2 pk,
String digestAlgorithm, CryptoStandard subfilter,
String reason, String location,
int estimatedSize)
{
IList<ICrlClient> crlList = new List<ICrlClient>();
crlList.Add(new CrlClientOnline(chain));
// Creating the reader and the stamper
PdfReader reader = null;
PdfStamper stamper = null;
FileStream os = null;
//int noofpdfs = 0;
var watch = Stopwatch.StartNew();
try
{
string[] srcfiles;
if (lblSplitedFilePath.Text.Equals("Split By Page Directory"))
srcfiles = Directory.GetFiles(tbsrcpath.Text, "*.pdf");
else
if (tbsrcpath.Text.ToUpper().Contains(#"\SPLIT"))
srcfiles = Directory.GetFiles(tbsrcpath.Text, "*.pdf");
else
srcfiles = Directory.GetFiles(tbsrcpath.Text + #"\split\", "*.pdf");
//int noofpdfs = srcfilePaths.Count();
for (int i = 0; i < srcfiles.Count(); i++)
{
// Get FileName
lblOutputFile.Text = tbtgtpath.Text + #"\" + Path.GetFileName(srcfiles[i]);
lblOutputFile.Refresh();
os = new FileStream(lblOutputFile.Text, FileMode.Create);
reader = new PdfReader(srcfiles[i]);
iTextSharp.text.Rectangle pdfbox = reader.GetPageSize(1);
stamper = PdfStamper.CreateSignature(reader, os, '\0');
// Creating the appearance
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
if (!string.IsNullOrWhiteSpace(tbContact.Text))
{
appearance.ReasonCaption = "Contact:";
appearance.Reason = tbContact.Text;// reason;
}
appearance.Location = location;
//Adding Image to Sign
if (cbAddImageSign.Checked)
{
var image = iTextSharp.text.Image.GetInstance(tbSignImage.Text);
appearance.Acro6Layers = true;
appearance.SignatureGraphic = image;
appearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION;
}
int llx, lly, urx, ury;
int.TryParse(Tbllx.Text, out llx);
int.TryParse(tblly.Text, out lly);
int.TryParse(tburx.Text, out urx);
int.TryParse(tbury.Text, out ury);
pdfSigning.Properties.Settings.Default.llx = llx;
pdfSigning.Properties.Settings.Default.lly = lly;
pdfSigning.Properties.Settings.Default.urx = urx;
pdfSigning.Properties.Settings.Default.ury = ury;
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(llx, lly, urx, ury), 1, "sig");
//Add Water mark
if (!lblWaterMarkImagePath.Text.Equals("Pdf Water Mark Image Path"))
{
var wmimage = iTextSharp.text.Image.GetInstance(lblWaterMarkImagePath.Text);
wmimage.SetAbsolutePosition(0, 0);
wmimage.ScaleToFit(100, 100);
for (var j = 0; j < reader.NumberOfPages; j++)
{
var content = stamper.GetUnderContent(j + 1);
content.AddImage(wmimage);
}
}
//appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
// Creating the signature
try
{
IExternalSignature pks = new X509Certificate2Signature(pk, digestAlgorithm);
MakeSignature.SignDetached(appearance, pks, chain, crlList, null, null, estimatedSize,
subfilter);
}
catch (CryptographicException ex)
{
MessageBox.Show(ex.ToString());
}
//noofpdfs++;
if (cbPrintOnSign.Checked)
{
switch (tbPrintMethod.Text)
{
case "2":
SendFileToPrinter(lblOutputFile.Text, printpdf2printer);
break;
default:
SendToPrinter(lblOutputFile.Text);
break;
}
}
if (cbDeletePdfPostSign.Checked)
{
File.Delete(srcfiles[i]);
}
dgvPrintFiles.Rows.Add(srcfiles[i].ToString());
}
lblOutputFile.Text += #" Siging Over:Signed " + srcfiles.Count().ToString() + " Files";
}
finally
{
if (reader != null)
reader.Close();
if (stamper != null)
stamper.Close();
if (os != null)
os.Close();
}
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
MessageBox.Show("Signing Time:" + elapsedMs / 1000 + " Second");
}
I have a method which has served me well, but now the queries have changed and I need to add a CommandTimeout to allow for the fact that some of the client machines on which this is executed are a little under-powered. The issue I'm having is the using lines as adding a CommandTimeout doesn't work.
The program itself pulls queries down from an SFTP server each night and then executes the queries against the client DB, writes the results to file then sends the results back to the SFTP server.
I can't improve the efficiency of the query (read only access) on the client machines, so I'm stuck with this method.
public void DumpTableToFile(string connection, string destinationFile, string QueryToExec)
{
string logDirectory = VariableStorage.logDirectory;
string Practice = VariableStorage.Practice;
try
{
SqlConnection conn = new SqlConnection(connection);
conn.Open();
using (var command = new SqlCommand(QueryToExec, conn))
using (var reader = command.ExecuteReader())
using (var outFile = File.CreateText(destinationFile))
{
string[] columnNames = GetColumnNames(reader).ToArray();
int numFields = columnNames.Length;
outFile.WriteLine(string.Join("\t", columnNames));
if (reader.HasRows)
{
while (reader.Read())
{
string[] columnValues =
Enumerable.Range(0, numFields)
.Select(i => reader.GetValue(i).ToString())
.Select(field => string.Concat("", field.Replace("\"", "\"\""), ""))
.ToArray();
outFile.WriteLine(string.Join("\t", columnValues));
}
}
}
}
catch (Exception e)
{
Program log = new Program();
log.WriteToLog(" Error: " + e);
SendEmailReport(Practice + " - Data Collection Error", " Error: " + e);
}
}
OK, found the answer. I had to remove the Using statements.
var command = new SqlCommand(QueryToExec, conn);
command.CommandTimeout = 300;
var reader = command.ExecuteReader();
var outFile = File.CreateText(destinationFile);
I need some help with my project.
I have a main method which start a cmd process and redirects output onto event handler.
private void RunBTN_Click(object sender, EventArgs e)
{
this.process.StartInfo.FileName = sMasterBATname;
this.process.StartInfo.UseShellExecute = false;
this.process.StartInfo.CreateNoWindow = true;
this.process.StartInfo.RedirectStandardOutput = true;
this.process.OutputDataReceived += new DataReceivedEventHandler(StandardOutputHandler);
this.process.StartInfo.RedirectStandardInput = true;
this.process.Start();
this.process.BeginOutputReadLine();
}
CMD process runs number of exe files and everything would be fine but some of the exe output is redirected onto a text file(">>" command) and therefore is not handled by my event.
public void StandardOutputHandler(object sender, DataReceivedEventArgs outLine)
{
if (outLine.Data != null && !String.IsNullOrWhiteSpace(outLine.Data))
{
if (outLine.Data.Contains(">>"))
{
string[] commandLine = outLine.Data.Split('>');
this.logFileFullPath = commandLine[1];
this.logFileFullPath = this.logFileFullPath.Replace('"', ' ').Trim();
string[] split = logFileFullPath.Split('\\');
this.logFileName = split[6];
this.path = split[0] + "\\" + split[1] + "\\" + split[2] + "\\" + split[3] + "\\" + split[4] + "\\" + split[5];
BatchRun.LogMonitor(this.logFileName,this.path) //this class will run on different thread
else
{
//validate content of received data
}
}
}
}
Both methods above are located in partial class.
Log Monitor which will run on separate thread and will perform a loop to check for any updates to the text/log file as per below which is based on Tail like program:
public class Monitor
{
public LogMonitor(string LogName, string LogPath)
{
using (StreamReader reader = new StreamReader(new FileStream(LogName,
FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
//start at the end of the file
long lastMaxOffset = reader.BaseStream.Length;
while (true)
{
System.Threading.Thread.Sleep(100);
//if the file size has not changed, idle
if (reader.BaseStream.Length == lastMaxOffset)
continue;
//seek to the last max offset
reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin);
//read out of the file until the EOF
string line = "";
while ((line = reader.ReadLine()) != null)
Console.WriteLine(line);
//update the last max offset
lastMaxOffset = reader.BaseStream.Position;
}
}
}
My issue is that I have no idea how to pass a line variable, each time a new line has been appended to the log, from LogMonitor method onto StandardOutputHandler so I can validate content of the log file the same way and act accordingly.
If someone could use my code and paste an answer that would be awesome. OR maybe someone can suggest a better way of achieving my goal?
I have only been using C# for 2 months so don't have great understanding of the evens etc...
I want to send DataSet data with email excel file attachment in C# but I don't want to create Excel file physically. It can be do with MemoryStream but I couldn't.
Another problem I want to set Excel file's encoding type because data may be Russian or Turkish special character.
Please help me...
Here is my sample code...
<!-- language: c# -->
var response = HttpContext.Response;
response.Clear();
response.Charset = "utf-8";
response.ContentEncoding = System.Text.Encoding.Default;
GridView excelGridView = new GridView();
excelGridView.DataSource = InfoDataSet;
excelGridView.DataBind();
excelStringWriter = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(excelStringWriter);
excelGridView.RenderControl(htw);
byte[] ExcelData = emailEncoding.GetBytes(excelStringWriter.ToString());
MemoryStream ms = new MemoryStream(ExcelData);
mailMessage.Attachments.Add(new Attachment(ms, excelFileName, "application/ms-excel"));
<!-- language: c# -->
here is another one simple and easy with excel attchment
public string SendMail(string LastId)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_GetMailData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#LastID", LastId);
con.Open();
string result = "0";
string temptext = "";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
//ExportToSpreadsheet(dt,"My sheet");
GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();
AttachandSend(gv);
con.Close();
return result.ToString();
}
public void AttachandSend(GridView gv)
{
StringWriter stw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(stw);
gv.RenderControl(hw);
System.Text.Encoding Enc = System.Text.Encoding.ASCII;
byte[] mBArray = Enc.GetBytes(stw.ToString());
System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
MailAddress address = new
MailAddress("xxxxxxxxxxxxx", "Admin");
mailMessage.Attachments.Add(new Attachment(mAtt, "sales.xls"));
mailMessage.Body = "Hi PFA";
mailMessage.From = address;
mailMessage.To.Add("xxxxxxxxxxxx");
mailMessage.Subject = "xxxxxxxxxxxxxx";
mailMessage.IsBodyHtml = true;
var smtp = new SmtpClient();
smtp.Send(mailMessage);
}
Here is your solution
private static Stream DataTableToStream(DataTable table)
{
const string semiColon = ";";
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
foreach (DataColumn column in table.Columns)
{
sw.Write(column.ColumnName);
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
sw.Write(row[i].ToString().Replace(semiColon, string.Empty));
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
}
return ms;
}
private static MailMessage CreateMail(string from,
string to,
string subject,
string body,
string attname,
Stream tableStream)
{
// using System.Net.Mail
var mailMsg = new MailMessage(from, to, subject, body);
tableStream.Position = 0;
mailMsg.Attachments.Add(
new Attachment(tableStream, attname, CsvContentType));
return mailMsg;
}
private const string CsvContentType = "application/ms-excel";
private static void ExportToSpreadsheetInternal(Stream tableStream, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = CsvContentType;
context.Response.AppendHeader(
"Content-Disposition"
, "attachment; filename=" + name + ".xls");
tableStream.Position = 0;
tableStream.CopyTo(context.Response.OutputStream);
context.Response.End();
}
public static void ExportToSpreadsheet(DataTable table, string name)
{
var stream = DataTableToStream(table);
var mailMsg = CreateMail("from#ddd.com",
"to#ddd.com",
"spread",
"the spread",
name,
stream);
//ExportToSpreadsheetInternal(stream, name);
// send the mailMsg with SmtpClient (config in your web.config)
var smtp = new SmtpClient();
smtp.Send(mailMsg);
}
Call this method
ExportToSpreadsheet(DataTable table, string name)
I have a problem in API Management, I want to create images in item 1 item, but I still can not do it forever. I use c # language, I feel depressed
i want to create a resource in catchoom.
can you help me
byte[] buffer = null;
byte[] data = null;
byte[] data1 = null;
HttpWebRequest request = null;
int bytesRead = 0;
long length = 0;
string boundary = DateTime.Now.Ticks.ToString("x");
// string boundary = "AaB03x";
StringBuilder sb = null;
// Create the HttpWebRequest object
request = (HttpWebRequest)HttpWebRequest.Create("https://crs.catchoom.com/api/v0/image/?api_key=5aba12ba6974c04ebc95da45ba1597d27d75238f");
// Specify the ContentType
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
// Specify the Method
request.Method = "POST";
request.KeepAlive = false;
// Create the StringBuilder object
sb = new StringBuilder();
// Constrcut the POST header message
sb.AppendLine("");
sb.AppendLine("--" + boundary);
sb.AppendLine("Content-Disposition: form-data; name=\"anh\"");
sb.AppendLine("");
sb.AppendLine("/api/v0/item/aee726ff67274fcb80f4c24f27861c1e/");
sb.AppendLine("--" + boundary);
sb.AppendLine("Content-Disposition: file; name=\"anh\"; filename=\"anh\"");
sb.AppendLine("Content-Type: image/jpg");
sb.AppendLine("");
StringBuilder sb1 = new StringBuilder();
sb1.AppendLine("");
sb1.AppendLine("--" + boundary + "--");
// Convert the StringBuilder into a string
data = Encoding.UTF8.GetBytes(sb.ToString());
data1 = Encoding.UTF8.GetBytes(sb1.ToString());
//
using (FileStream fs = new FileStream(#"D:\17. NHATLINH\ToolKit_Catchoom\ToolKit_Catchoom\bin\Debug\aa.jpg", FileMode.Open, FileAccess.Read))
{
length = data.Length + fs.Length + data1.Length;
// đưa thông tin chiều dài của gói gửi đi vào
request.ContentLength = length;
//
using (Stream stream = request.GetRequestStream())
{
// ghi header vào gói gửi đi
stream.Write(data, 0, data.Length);
//
buffer = new Byte[checked((uint)Math.Min(4096, (int)fs.Length))];
// buffer = new Byte[fs.Length];
// Write the file contents
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
stream.Write(data1, 0, data1.Length);
//
try
{
Console.WriteLine(request.ContentType);
Console.WriteLine(sb.ToString() + sb1.ToString());
WebResponse responce = request.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
MessageBox.Show(sr.ReadToEnd());
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
}
}
Building a multipart-encoded request is an error-prone task ( it is normal if you feel frustrated trying ), I recommend you to use a library to handle this kind of things, no point in reinventing the wheel :)
If you are using the Microsoft .NET Framework >= 4.5, you may use the HttpClient class as this answer explains.
Hope this help you ;)