Zebra Print issue using asp.net with c# - asp.net

I am using the PrintDocument for printing directly to the network printer using asp.net with and C#. The application hosted in IIS with Windows authentication. I am not getting the error and also the PrintStatus is Printing. But we can not see the printed document in the printer and also there is no errors in the printer.
System.Drawing.Printing.PrintDocument printdoc = new System.Drawing.Printing.PrintDocument();
printdoc.DefaultPageSettings.PaperSize = new PaperSize("Custom", 4, 3);
printdoc.OriginAtMargins = true;
// Set the printer name
PrinterSettings printer = new PrinterSettings();
printer.PrinterName = SqlDatabaseUtility.GetZebraPrinterName();
string fullName = CheckPrinterConfiguration(printer.PrinterName);
if (!String.IsNullOrEmpty(fullName))
{
printdoc.PrinterSettings.PrinterName = fullName;
// Handle printing
if (printdoc.PrinterSettings.IsValid)
{
printdoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printdoc_PrintPage);
printdoc.PrinterSettings.Copies = 2;
printdoc.Print();
}
}

Just a theory, but the PrintDocument class is a descendant of Component and so implements IDisposable.
In the same way that you don't leave SqlConnection instances undisposed, you should call Dispose() on your printdoc instance so that any unmanaged resources held by the PrintDocument instance - such as a handle to the printer device, perhaps - get released.
Put a using clause around your printing block as below. It might help with your problem, but even if it does not it is proper practice.
using (System.Drawing.Printing.PrintDocument printdoc = new System.Drawing.Printing.PrintDocument())
{
...
}
The next line of enquiry would be to follow up on the "user permissions" suggestion in the comment. Assuming that your code works if you run it in a test console application, a quick test for this would be to change the user account of your web app's Application Pool to be your own account. If your web app starts printing, then you know that permissions are the problem.

Related

Redirect all ASP.NET Core logging into a single NLog logger

I have an ASP.NET project that sends its logs to NLog.
However in this project, I have my own NLog logger and I would like to know how to route all the logs through it.
I guess I shouldn't add NLog as a logger, but I should find a way to register a method that will get called each time ASP tries to log anything.
How can this be accomplished?
This is the code that creates the logger:
// create the module name
var ProcessName = Process.GetCurrentProcess().ProcessName;
_ModuleName = ProcessName + " (\"" + Oracle.GuessMyName() + "\")";
// create the logger configuration
var Configuration = new LoggingConfiguration();
// create the file target
var FileTarget = new FileTarget ("file")
{
FileName = #"x:\Logs\${processname}.log",
ArchiveFileName = #"x:\Logs\${processname}.{#}.log",
Layout = #"${longdate}|${logger}|${level}|${message}${onexception:|Exception occurred:${exception:format=tostring}${newline}",
ArchiveEvery = FileArchivePeriod.Day,
ArchiveNumbering = ArchiveNumberingMode.Rolling,
MaxArchiveFiles = 7,
ConcurrentWrites = true
};
Configuration.AddTarget(FileTarget);
// create the viewer target
var ViewerTarget = new NLogViewerTarget ("viewer")
{
Layout = #"${message}${onexception:${newline} --> Exception occurred\:${exception:format=tostring}",
IncludeSourceInfo = true,
IncludeCallSite = true,
Address = #"udp://127.0.0.1:9999"
};
Configuration.AddTarget(ViewerTarget);
// set the rules
Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, FileTarget));
Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, ViewerTarget));
// set the configuration
LogManager.Configuration = Configuration;
// create a new logger
_Logger = LogManager.GetLogger(_ModuleName);
and this is also how ASP.net gets attached to nlog:
LoggerFactory.AddNLog();
Application.AddNLogWeb();
Now the current log layout looks like this for two process (the animal names are automatically changing every time the process is restarted)
so both process: shinobi and mouserun here have their own log output, but anything ASP related goes to ASP's nlog instance called Microsoft, regardless of the process.
the goal is to have the ASP output of shinobi to go in the shinobi logger and the mouserun ASP output to go in the mouserun logger.
Look at the code of NLog.Extensions.Logging, where it injects its own custom log-provider.
You can do the same and just wrap your global-logger object:
https://github.com/NLog/NLog.Extensions.Logging/blob/e48d6cc54d9abd70d976066265c7992117cbac5a/src/NLog.Extensions.Logging/NLogLoggerProvider.cs
https://github.com/NLog/NLog.Extensions.Logging/blob/1474ffe5b26d2ac95534ed01ef259133133bfb67/src/NLog.Extensions.Logging/NLogLoggerFactory.cs
https://github.com/NLog/NLog.Extensions.Logging/blob/2c05a4fbdda0fe026e60814d535e164e18786aef/src/NLog.Extensions.Logging/ConfigureExtensions.cs
public static ILoggerFactory AddNLog(this ILoggerFactory factory, NLogProviderOptions options)
{
ConfigureHiddenAssemblies();
using (var provider = new NLogLoggerProvider(options))
{
factory.AddProvider(provider);
}
return factory;
}
You could also create a custom-target, and redirect all non-global-logger messages to this target using NLog rules:
https://github.com/nlog/NLog/wiki/Configuration-file#rules
The custom target can then just forward the log-event to the global-logger:
https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target
You should be careful with cyclic logging. Maybe have a filter in the custom-target to ignore messages from the global-logger.
But I think this is an ugly solution, and I fail to understand the restriction of only one logger-object. Especially when the reason is because it should be named after the application. Why not not a global variable for the name instead of abusing the logger-name?
Alternative you can create a custom target wrapper, that fixes the Logger on LogEventInfo's, so when forwarded to the wrapped target (UDP- / File-target), then it looks like they are all come from the same logger.
Similar to what this guy is trying to do:
https://github.com/NLog/NLog/issues/2352
Again really ugly solution, and should only be used when not able to figure out, how to avoid using the logger-name in the configuration of the wanted Nlog-targets (Ex. configure file-target-filename using something else).

How do I parse specific data from a website within Codename One?

I have run into a road block developing my Codename One app. One of my classes in my project parses 3 specific html "td" elements from a website and saves the text to a string where I then input that text data into a Codename One multibutton. I originally used jSoup for this operation but soon realized that Codename One doesn't support 3rd party jar files so I used this method as shown below.
public void showOilPrice() {
if (current != null) {
current.show();
return;
}
WebBrowser b = new WebBrowser() {
#Override
public void onLoad(String url) {
BrowserComponent c = (BrowserComponent) this.getInternal();
JavascriptContext ctx = new JavascriptContext(c);
String wtiLast = (String) ctx.get("document.getElementById('pair_8849').childNodes[4].innerText");
String wtiPrev = (String) ctx.get("document.getElementById('pair_8849').childNodes[5].innerText");
String wtiChange = (String) ctx.get("document.getElementById('pair_8849').childNodes[8].innerText");
Form op = new Form("Oil Prices", new BoxLayout(BoxLayout.Y_AXIS));
MultiButton wti = new MultiButton("West Texas Intermediate");
Image icon = null;
Image emblem = null;
wti.setEmblem(emblem);
wti.setTextLine2("Current Price: " + wtiLast);
wti.setTextLine3("Previous: " + wtiPrev);
wti.setTextLine4("Change: " + wtiChange);
op.add(wti);
op.show();
}
};
b.setURL("https://sslcomrates.forexprostools.com/index.php?force_lang=1&pairs_ids=8833;8849;954867;8988;8861;8862;&header-text-color=%23FFFFFF&curr-name-color=%230059b0&inner-text-color=%23000000&green-text-color=%232A8215&green-background=%23B7F4C2&red-text-color=%23DC0001&red-background=%23FFE2E2&inner-border-color=%23CBCBCB&border-color=%23cbcbcb&bg1=%23F6F6F6&bg2=%23ffffff&open=show&last_update=show");
}
This method works in the simulator (and gives a "depreciated API" warning), but does not run when I submit my build online after signing. I have imported the parse4cn1 and cn1JSON libraries and have gone through a series of obstacles but I still receive a build error when I submit. I want to start fresh and use an alternative method if one exists. Is there a way that I can rewrite this segment of code without having to use these libraries? Maybe by using the XMLParser class?
The deprecation is for the WebBrowser class. You can use BrowserComponent directly so WebBrowser is redundant in this case.
I used XMLParser for this use case in the past. It should work with HTML as it was originally designed to show HTML.
It might also be possible to port JSoup to Codename One although I'm not sure about the scope of effort involved.
It's very possible that onLoad isn't invoked for a site you don't actually see rendered so the question is what specifically failed on the device?

DotRas unauthorized access exception when adding phonebook an entry

I am devoloping an application with dotras dll. In the application my main goal is to connect to the internet with 3g USB modem. I am adding my code below :
RasPhoneBook book = new RasPhoneBook();
book.Open();
dialer = new RasDialer();
dialer.StateChanged += new EventHandler<StateChangedEventArgs> (dialer_StateChanged);
RasDevice device = RasDevice.GetDeviceByName("ZTE", RasDeviceType.Modem);
RasEntry entry = RasEntry.CreateDialUpEntry("MyEntry", "*99#", device);
entry.EncryptionType = RasEncryptionType.Optional;
entry.Options.ModemLights = true;
entry.NetworkProtocols.IP = true;
entry.NetworkProtocols.Ipx = false;
book.Entries.Add(entry);
dialer.PhoneBookPath = book.Path;
dialer.EntryName = "MyEntry";
dialer.Dial();
When I tried to add the phonebook my entry it's returning an exception :
UnauthorizedAccessException was Unhandled
The caller does not have required permission to perform the action requested.
I'm new about DotRas. So which permissions does it neeeded to add an entry to the phonebook?
Any ideas?
I have found the answer. The reason why I need to elevate privileges for the application is due to the application opening the All User's profile phone book. This is indicated by my call to book.Open()
If you encountered a problem like this remember you can always store the phone book next to your application, which will remove the need to elevate permissions.
The code should be :
RasPhoneBook book = new RasPhoneBook();
book.Open(".\\MyAppPhoneBook.pbk");

asp.net app calling service says its not initialized?

So this code runs in an asp.net app on Linux. The code calls one of my services. (WCF doesn't work on mono currently, that is why I'm using asmx). This code works AS INTENDED when running from Windows (while debugging). As soon as I deploy to Linux, it stops working. I'm definitely baffled. I've tested the service thoroughly and the service is fine.
Here is the code producing an error: (NewVisitor is a void function taking 3 strings in)
//This does not work.
try
{
var client = new Service1SoapClient();
var results = client.NewVisitor(Request.UserHostAddress, Request.UrlReferrer == null ? String.Empty : Request.UrlReferrer.ToString(), Request.UserAgent);
Logger.Debug("Result of client: " + results);
}
Here is the error generated: Object reference not set to an instance of an object
Here is the code that works perfectly:
//This works (from the service)
[WebMethod(CacheDuration = _cacheTime, Description = "Returns a List of Dates", MessageName = "GetDates")]
public List<MySqlDateTime> GetDates()
{
return db.GetDates();
}
//Here is the code for the method above
var client = new Service1Soap12Client();
var dbDates = client.GetDates();
I'd love to figure out why it is saying that the object is not set.
Methods tried:
new soap client.
new soap client with binding and endpoint address specified
Used channel factory to create and open the channel.
If more info is needed I can give more. I'm out of ideas.
It looks like a bug in mono. You should file a bug with a reproducible test case so it can be fixed (and possibly find a workaround you can use).
Unfortunately, I don't have Linux to test it but I'd suggest you put the client variable in an using() statement:
using(var client = new Service1SoapClient())
{
var results = client.NewVisitor(Request.UserHostAddress, Request.UrlReferrer == null ?
String.Empty : Request.UrlReferrer.ToString(), Request.UserAgent);
Logger.Debug("Result of client: " + results);
}
I hope it helps.
RC.

Microsoft Speech Recognition in webservices is not returning the result

Well i'm using Microsoft Speech Platform SDK 10.2.
I made a asp.Net WebService application and most of the WebServices works fine (HelloWorld(), etc...), but I have one service that uses the SpeechRecognitionEngine and when I deploy the application and try to run this webservice I get no result, i.e, I can see through the debug mode that it reaches the return line, but when I call it trought the browser the page keeps loading for ever, without any response.
Here's a sample of the code:
[WebMethod]
public bool voiceRecognition() {
SpeechRecognitionEngine sre = new SpeechRecognitionEngine(new System.Globalization.CultureInfo("pt-PT"));
Choices c = new Choices();
c.Add("test");
GrammarBuilder gb = new GrammarBuilder();
gb.Append(c);
Grammar g = new Grammar(gb);
sre.LoadGrammar(g);
sre.InitialSilenceTimeout = TimeSpan.FromSeconds(5);
//// just for Testing
RecognitionResult result = null;
if (result != null) {
return true;
} else {
return false;
}
}
Note: I'm using IIS to deploy the WebService Application.
If someone have some thoughts please let me know.
I don't know if you've found your answer or not. When trying to solve this myself a couple of days ago, I stumbled across your question and it matched our circumstances to a "T".
In order to fix it all we had to do was put...
sre.RecognizeAsyncStop();
sre.Dispose();
where "sre" is your SpeechRecognitionEngine variable. If you don't stop it and dispose of it at the end of your web service then the web service won't return.
Hope this helps. :)

Resources