Print to a network printer in C# - visual-studio-2010

I am attempting to print to a network servia via C# in VS2010 but have run into difficulties getting it to work. If I use the "print" Verb insted it prints fine but only to the default printer. I am using the PrintTo Verb to try and specify a printer. In my case using print verb I successfully can print to the same network printer that I am trying to print to using the printto verb after I change my default printer to a different printer. Here is the code I am currently using. Any help would be greatly appreciated.
private string FindPrinter(string printerName)
{
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection printers = searcher.Get();
foreach (ManagementObject printer in printers)
{
if (!String.IsNullOrEmpty(printer.Properties["PortName"].Value.ToString()))
{
return printerName = string.Format(#"\\{0}\{1}", printer.Properties["PortName"].Value.ToString(), printerName);
}
}
return printerName;
}
private void Print(string fileName, string printerName)
{
PrinterSettings ps = new PrinterSettings();
ps.PrinterName = printerName;
if (ps.IsValid)
{
try
{
ProcessStartInfo processStartInfo = new ProcessStartInfo(fileName);
using (PrintDialog pd = new PrintDialog())
{
pd.ShowDialog();
printerName = this.FindPrinter(pd.PrinterSettings.PrinterName);
if (printerName.IndexOf(#"\\") == 0)
{
processStartInfo.Verb = "PrintTo";
processStartInfo.Arguments = printerName;
}
else
{
processStartInfo.Verb = "print";
}
}
processStartInfo.CreateNoWindow = true;
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process printProcess = new Process();
printProcess.StartInfo = processStartInfo;
bool printStarted = printProcess.Start();
MessageBox.Show(string.Format("{0} printed to {1}", fileName, printerName), "Report Print", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Report Print", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show(string.Format("{0} printer does not exist. Please contact technical support.", printerName), "Report Print", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

only use verb PrintTo and
use the double quotes to quote the printerName
processStartInfo.Verb = "PrintTo";
processStartInfo.Arguments = "\"" + printerName + "\"";

Related

Brother Printer SDK in Xamarin.Android Printing Issue

I'm Working on Brother Label Printer QL-710W using Xamarin.Android.
I have created a Android bindings project and Added jar files and .so files as shown below.
I'm using Visual Studio.
Jars >
BrotherPrintLibrary.jar; BuildAction: EmbeddedJar
MobilePrintLib.jar; BuildAction: ReferenceJar
NativeLibraries > armeabi >
libAndrJFPDFEMB.so; BuildAction: EmbeddedNativeLibrary
libcreatedata.so; BuildAction: EmbeddedNativeLibrary
Additions
ClassTest.cs
public bool PrintFile(string fileurl, NetPrinter printer)
{
Task <bool> printTask = new Task<bool>(() => {
bool success = true;
try
{
Printer myPrinter = new Printer();
PrinterInfo myPrinterInfo = new PrinterInfo();
PrinterStatus status = new PrinterStatus();
LabelInfo mLabelInfo = new LabelInfo();
myPrinterInfo.PrinterModel = PrinterInfo.Model.Ql710w;
myPrinterInfo.IpAddress = printer.IpAddress;
myPrinterInfo.MacAddress = printer.MacAddress;
myPrinterInfo.Port = PrinterInfo.PortEnum.Net;
myPrinterInfo.PrintMode=PrinterInfo.PrintModeEnum.FitToPage;
myPrinterInfo.PaperSize = PrinterInfo.PaperSizeEnum.Custom;
myPrinterInfo.Orientation = PrinterInfo.OrientationEnum.Portrait;
myPrinterInfo.LabelNameIndex = LabelInfo.QL700.W62.Ordinal();
myPrinterInfo.ScaleValue = 1;
mLabelInfo.LabelNameIndex = LabelInfo.QL700.ValueOf("W62").Ordinal();
mLabelInfo.IsAutoCut = true;
mLabelInfo.IsEndCut = true;
myPrinter.SetPrinterInfo(myPrinterInfo);
myPrinter.SetLabelInfo(mLabelInfo);
myPrinter.StartCommunication();
status = myPrinter.PrintFile(fileurl);
if (status.ErrorCode != PrinterInfo.ErrorCode.ErrorNone)
success = false;
myPrinter.EndCommunication();
}catch(Exception ex)
{
Console.WriteLine("ERROR : {0}",ex.Message);
success = false;
}
return success;
});
printTask.Start();
var isSuccess = printTask.Result;
return isSuccess;
}
I'm getting printers list successfully from network. But when I'm calling above method it is getting exception at myPrinter.SetPrinterInfo(myPrinterInfo); as "Couldn't load createdata from loader dalvik.system.PathClassLoader[DexPathList[[zip file \"/data/app/PocAndroidArchieve.PocAndroidArchieve-2.apk\"],nativeLibraryDirectories=[/data/app-lib/PocAndroidArchieve.PocAndroidArchieve-2, /vendor/lib, /system/lib]]]: findLibrary returned null"
Please suggest me if any one has idea to work with jar's and dependent .so files.
Thanks in advance.

Catch incoming emails and send them to a web service (rather than just to a mail server)

I would like to catch incoming emails and send them a web service (rather than just to a mail server).
--
After some searching I found a way of getting new emails via polling - see below: This may be of some help to others. Is there a way to receive messages by SMTP? Perhaps by ISAPI ???
using Limilabs.Mail;
using Limilabs.Client.IMAP;
public ActionResult checkIMAPmail()
{
string rval = "not a sausage";
using (Imap imap = new Imap())
{
imap.Connect(<mail server>);
imap.Login(<username>, <password>);
imap.SelectInbox();
List<long> uids = imap.Search(Flag.Unseen);
foreach (long uid in uids)
{
byte[] ourBytes = imap.GetMessageByUID(uid);
IMail email = new MailBuilder().CreateFromEml(ourBytes);
rval = email.Subject + " [" + email.From + "][" + email.Text + "]";
}
imap.Close();
}
return Content(rval, "text/html");
}
See also http://stackoverflow.com/questions/670183/accessing-imap-in-c-sharp
for other IMAP packages, although note the change to using byte[], above.
Given that Limilabs.Mail is a paid service, I finally used MailKit:
using MailKit;
public int checkIMAPmail()
{
int numEmails = 0;
try {
using (var client = new MailKit.Net.Imap.ImapClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect(ourSmtpClient);
// disable the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate(ourSmtpAdminUser, ourSmtpAdminUserPwd);
// The Inbox folder is always available on all IMAP servers...
var inboxFolder = client.Inbox;
var savedFolder = client.GetFolder("saved");
inboxFolder.Open(FolderAccess.ReadWrite);
for (int ii = 0; ii < inboxFolder.Count; ii++)
{
var query = MailKit.Search.SearchQuery.NotSeen;
foreach (var uid in inboxFolder.Search(query))
{
var thisMsg = inboxFolder.GetMessage(uid);
string thisDate = notNullString(thisMsg.Date);
string thisSubject = notNullString( thisMsg.Subject);
string thisBody = notNullString(thisMsg.GetTextBody(0)); // plain text
string thisFromName = "";
string thisFromEmail = "";
if ( thisMsg.From != null)
{
// just get the first
foreach( var mb in thisMsg.From.Mailboxes)
{
thisFromName = notNullString( mb.Name);
thisFromEmail = notNullString( mb.Address);
break;
}
}
numEmails += 1;
// move email to saved
inboxFolder.MoveTo(uid, savedFolder);
}
}
client.Disconnect(true);
}
}
catch (Exception exc)
{
log2file("checkIMAPmail Error: " + exc.ToString());
}
return numEmails;
}

CKEditor file upload doesn't work properly with mvc 6

I'm trying to use the built in upload file of CKEditor, it works with my MVC5 project, but it doesn't work with my MVC6 project, the code for uploading the file is correct, I've tested it, and it actually upload the file to the server, but it doesn't populate the form with the URL and image information, here's the code for my MVC5 project that works:
public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor,
string langCode)
{
string vImagePath = String.Empty;
string vMessage = String.Empty;
string vFilePath = String.Empty;
string vOutput = String.Empty;
try
{
if (upload != null && upload.ContentLength > 0)
{
var vFileName = DateTime.Now.ToString("yyyyMMdd-HHMMssff") + " - " + Path.GetFileName(upload.FileName);
var vFolderPath = Server.MapPath("/Upload/");
if (!Directory.Exists(vFolderPath))
{
Directory.CreateDirectory(vFolderPath);
}
vFilePath = Path.Combine(vFolderPath, vFileName);
upload.SaveAs(vFilePath);
vImagePath = Url.Content("/Upload/" + vFileName);
vMessage = "The file uploaded successfully.";
}
}
catch(Exception e)
{
vMessage = "There was an issue uploading:" + e.Message;
}
vOutput = #"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + vImagePath + "\", \"" + vMessage + "\");</script></body></html>";
return Content(vOutput);
}
And here is the code for MVC6 project that doesn't work:
public async Task<ActionResult> UploadImage(IFormFile upload, string CKEditorFuncNum, string CKEditor,
string langCode)
{
string vImagePath = String.Empty;
string vMessage = String.Empty;
string vFilePath = String.Empty;
string vOutput = String.Empty;
try
{
if (upload != null && upload.Length > 0)
{
var vFileName = DateTime.Now.ToString("yyyyMMdd-HHMMssff") + " - " + ContentDispositionHeaderValue.Parse(upload.ContentDisposition).FileName.Trim('"');
var vFolderPath = Path.Combine(_environment.WebRootPath, "Files", "ArticleUploads");
if (!Directory.Exists(vFolderPath))
{
Directory.CreateDirectory(vFolderPath);
}
vFilePath = Path.Combine(vFolderPath, vFileName);
await upload.SaveAsAsync(vFilePath);
vImagePath = Url.Content("/Files/ArticleUploads/" + vFileName);
vMessage = "The file uploaded successfully.";
}
}
catch (Exception e)
{
vMessage = "There was an issue uploading:" + e.Message;
}
vOutput = #"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + vImagePath + "\", \"" + vMessage + "\");</script></body></html>";
return Content(vOutput);
}
And in CKEditor config file I have:
config.filebrowserImageUploadUrl = '/Admin/Article/UploadImage';
I've inspected the variables, and they send the same value, also worth to note that I'm using the same version of CKEditor, so that can't be the problem, I'd appreciate any help on this.
If the file gets uploaded and you don't see the image gets populated, I guess there should be some problem with the way you return your content, since you are returning html, try to specify your content type, like so:
return Content(vOutput, "text/html");
If that didn't solve your problem, you need to provide more information, tell us what exactly you get from this action in JavaScript side.

How to record echo mssage displayed on command prompt using C#?

I am using below function to call EAR_Encrypt_FTP.bat in C#. Is there any way to trace the echo messages dispayed in cmd.exe while running the batch file??
I need to process echo messages displayed on command prompt screen log the process.
private static short batchfileInvoke(string ftpFileName, string headerFile)
{
short value = 0;
Process p = null;
try
{
p = new Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "cmd.exe";
string argument1 = "EAR_Encrypt_FTP.bat";
string test = "\"" + ftpFileName + "\"";
string argument2 = test;
string test1 = "\"" + headerFile + "\"";
string argument3 = test1;
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(argument1);
startInfo.Arguments = "/C EAREncryptFTP.bat " + argument2 + " " + argument3;
p.StartInfo = startInfo;
p.Start();
p.WaitForExit();
int value2 = p.ExitCode;
value = (short)value2;
if(value==0)
{
Console.WriteLine("Encryption process is done");
}
}
catch (Exception ex)
{
Console.WriteLine("Exception Occurred :{0},{1}",
ex.Message, ex.StackTrace.ToString());
value = -4;
}
return value;
}

Exception raised while connecting remotely to Exchange only in IIS hosted application

I hope somebody can help me, I have the following function to do remote calls to a powershell server:
private static string DoCall()
{
string resultPs = string.Empty;
string serverName = "myserver.com";
string SHELL_URI = "http://schemas.microsoft.com/powershell/Microsoft.Exchange";
System.Uri serverUri = new Uri(String.Format("http://{0}/powershell?serializationLevel=Full", serverName));
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(serverUri, SHELL_URI, (PSCredential)null);
//connectionInfo = new WSManConnectionInfo(serverUri, SHELL_URI, PSCredential.Empty);
//connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Kerberos;
try
{
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
PowerShell powershell = PowerShell.Create();
powershell.Runspace = runspace;
runspace.Open();
powershell.AddScript("Get-DatabaseAvailabilityGroup");
Collection<PSObject> results = powershell.Invoke();
if (powershell.Streams.Error.Count > 0)
{
foreach (ErrorRecord err in powershell.Streams.Error)
{
resultPs += (err.ErrorDetails.Message != null ? err.ErrorDetails.Message : "");
}
}
foreach (PSObject result in results)
{
foreach (PSPropertyInfo propertyInfo in result.Properties)
{
resultPs += "Property:" + propertyInfo.Name + " Value:" + propertyInfo.Value;
}
}
powershell.Runspace.Close();
}
}
catch (Exception ex)
{
resultPs = ex.Message + " " + ex.StackTrace + " innerException: " + (ex.InnerException != null ? (ex.InnerException.Message ?? "") : "");
}
return resultPs;
}
}
If I run this code within Visual Studio in a console application, my credentials are used and the exchange call is done as expected, however, if I publish this code in a WCF service and set the application pool to use my credentials I receive the following exception
"An internal error occurred. \0 at System.Management.Automation.Remoting.Client.WSManClientSessionTransportManager.Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo)\r\n at System.Management.Automation.Remoting.Client.WSManClientSessionTransportManager..ctor(Guid runspacePoolInstanceId, WSManConnectionInfo connectionInfo, PSRemotingCryptoHelper cryptoHelper)\r\n at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerImpl..ctor(ClientRemoteSession session, PSRemotingCryptoHelper cryptoHelper, RunspaceConnectionInfo connectionInfo, URIDirectionReported uriRedirectionHandler)\r\n at System.Management.Automation.Remoting.ClientRemoteSessionImpl..ctor(RemoteRunspacePoolInternal rsPool, URIDirectionReported uriRedirectionHandler)\r\n at System.Management.Automation.Internal.ClientRunspacePoolDataStructureHandler..ctor(RemoteRunspacePoolInternal clientRunspacePool, TypeTable typeTable)\r\n at System.Management.Automation.Runspaces.Internal.RemoteRunspacePoolInternal..ctor(Int32 minRunspaces, Int32 maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo)\r\n at System.Management.Automation.Runspaces.RunspacePool..ctor(Int32 minRunspaces, Int32 maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo)\r\n at System.Management.Automation.RemoteRunspace..ctor(TypeTable typeTable, RunspaceConnectionInfo connectionInfo, PSHost host, PSPrimitiveDictionary applicationArguments)\r\n at System.Management.Automation.Runspaces.RunspaceFactory.CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments)\r\n at TestingRemote.Service.DoCall() in "
I have checked several blogs about passing the credentials but I haven't found someone with the same exact issue and that has solved mine. I know I can use an overloaded method for initializing the Credentials, but I want to use the ones in the app pool.

Resources