My company has purchased the CoolUtils TotalPDFPrinterX from https://www.coolutils.com/TotalPDFPrinterX
I make an HTTP PUT from Postman to the API and I get “Could not get any response”.
When running on my Windows machine the PDF prints fine however on the server the site crashes and in the event log I get the error "A process serving application pool '[MY_APP_POOL]' failed to respond to a ping. The process id was '[MY_PROCESS_ID]'."
Here is my C# code:
PDFPrinterX ppx = new PDFPrinterX();
ppx.Print(fileName, printerName, "-ap Default");
if (ppx.ErrorMessage != null)
{
WriteToSQL(id, false, ppx.ErrorMessage, 2);
Console.WriteLine(ppx.ErrorMessage);
}
By writing to the event log I know the site crashes on this line: PDFPrinterX ppx = new PDFPrinterX(); I have also surrounded the above code with a try catch and no exception is thrown. The site still crashes.
Things I have tried:
Uninstalling and Reinstalling the CoolUtils software
Giving EVERYONE Full control to the site folder and the CoolUtils program folder
Creating a C# desktop application using the same code. THIS WORKS FINE ON THE SERVER. It's just the ASP site that crashes.
Does anyone know what might be causing this?
The more I research this thing online the more I'm inclined to say that ActiveX which is the X in PDFPrinterX doesn't seem to work well when hosted in IIS.
I've seen a few forums where they say it works fine when they debug on localhost but when deployed to server is crashes.
...works fine when used inside localhost(Visual studio)
One of their feature pages shows that it requires Win 2000/NT/XP/2003/Vista/7
You should look into whether your server supports ActiveX components that can work in conjunction with IIS.
Looking at one of their other products support page: TotalPDFConverterX:
the following note in my opinion may also apply to TotalPDFPrinterX, given its dependency on ActiveX as well.
Note: Pay attention to some details during installation Total PDF Converter X:
Do not forget to register ActiveX in your web-server account.
Total PDF Converter X supports only Internet Explorer, Mozilla and Firefox browsers.
ActiveX works only with 32-bit internet information server. 64-bit server is not supported. Use command line version instead.
Thanks to #Nkosi I was able to find a workaround.
ActiveX works only with 32-bit internet information server. 64-bit server is not supported. Use command line version instead.
Our IIS server is 64 bit so that is what probably caused the site to hang up.
Buttt... the command line still worked in printing the PDFs on the server.
Client side code (makes the HTTP POST):
private void SendToPrinter(string fileName, string printerName, int id, decimal documentSequence)
{
// use http client to make a POST to the print api
using (var client = new HttpClient())
{
// compile the values string to transfer in POST
// should finish to look something like this:
// C:\print.pdf&PRTFTW_OFIT&ValShip-155320-1
var values = new Dictionary<string, string>
{
{ "", fileName + "&" + printerName + "&ValShip-" + id + "-" + documentSequence},
};
// URL encode the values string
var content = new FormUrlEncodedContent(values);
// make the POST
// DEBUG
var response = client.PostAsync("http://localhost:54339/api/print", content);
// retrieve the response
var responseString = response.Result.ToString();
}
}
Server side code (receives the HTTP POST):
using System;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace api.valbruna.print.Controllers
{
public class PrintController : ApiController
{
// POST api/print
public HttpResponseMessage Post(HttpRequestMessage request)
{
try
{
// parse the content recieved from the client
var content = request.Content.ReadAsStringAsync().Result;
// decode the content, certain characters such as
// '&' get encoded to URL lingo such as '%26'
content = HttpUtility.UrlDecode(content);
// split the string into 3 seperate parts
String[] str = content.Split('&');
// remove the equal sign from the first string
str[0] = str[0].Trim('=');
// compile the arguments command line string
// should finish to look something like this:
// "C:\Program Files (x86)\CoolUtils\Total PDF PrinterX\PDFPrinterX.exe" "C:\print.pdf" -p"\\PRINTERS\PRTFTW_OFIT" -ap Default -log "C:\inetpub\logs\CoolUtils\log-ValShip-155320-4.txt" -verbosity detail"
String arguments = "\"" + str[0] + "\" -p\"\\\\PRINTERS\\" + str[1] +
"\" -ap Default -log \"C:\\inetpub\\logs\\CoolUtils\\log-" + str[2] +
".txt\" -verbosity detail";
// file location for PDFPrinterX.exe
String file = #"C:\Program Files (x86)\CoolUtils\Total PDF PrinterX\PDFPrinterX.exe";
// start the process
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = file;
startInfo.Arguments = arguments;
process.StartInfo = startInfo;
process.Start();
return new HttpResponseMessage() { Content = new StringContent(content) };
}
catch (Exception e)
{
return new HttpResponseMessage() { Content = new StringContent(e.Message) };
}
}
}
}
Related
I'm trying to create an application where I have to use WHOIS to get some information I need.
To get the WHOIS information I use this function I found on here and adjusted a little:
string Whois(string domain, string whoisServer = "whois.iana.org")
{
string toReturn = "";
TcpClient tcpClinetWhois = new TcpClient(whoisServer, 43);
MemoryStream memoryStreamWhois = new MemoryStream();
Task copying = tcpClinetWhois.GetStream().CopyToAsync(memoryStreamWhois);
StreamWriter streamWriter = new StreamWriter(tcpClinetWhois.GetStream());
streamWriter.WriteLine(domain);
streamWriter.Flush();
copying.Wait(3000);
toReturn = Encoding.ASCII.GetString(memoryStreamWhois.ToArray());
if (toReturn.Contains("refer:"))
{
toReturn = Whois(domain, toReturn.Split('\n').Where(W => W.StartsWith("refer:")).Select(R => R.Replace("refer:", "").Trim()).First());
}
return toReturn;
}
When I run it, it works for most TLDs like .com or .org but not for .co.uk or .network and probably others too. I have no idea why it wouldn't work because the right WHOIS server gets selected for the TLD. I am also not getting any errors.
I'm using .Net7.0 and my Android 11 phone for testing.
I've tested this exact same function with the exact same domains on the same network but in a Console Application with no problems at all! Everything works fine except when I try this function in a Xamarin Application.
I'm using Linq to Excel library for reading excel tables. Until now, it was working good locally, the method ExcelQueryFactory gets the route of the excel by this way:
var book = new ExcelQueryFactory(#"C:\data.xls");
Now, I would like to use it online on a Rest Api, the POST used for uploading the Excel to the web api is the following:
[HttpPost]
[Route("Upload")]
public Task<HttpResponseMessage> UploadFile() {
List<string> savedFilePath = new List<string>();
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string rootPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
var provider = new MultipartFileStreamProvider(rootPath);
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsCanceled || t.IsFaulted)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
foreach (MultipartFileData item in provider.FileData)
{
try
{
string name = item.Headers.ContentDisposition.FileName.Replace("\"", "");
string newFileName = Guid.NewGuid() + Path.GetExtension(name);
Debug.WriteLine(item.LocalFileName);
File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));
Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty));
//RELATIVE PATH
string fileRelativePath = "~/UploadedFiles/" + newFileName;
//LeerExcel(fileRelativePath);
//ABSOLUTE PATH
Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath));
savedFilePath.Add(fileFullPath.ToString());
//LeerExcel(savedFilePath[0]);
}
catch (Exception ex)
{
string message = ex.Message;
}
}
// string rutaFin = "~" + savedFilePath[0];
// string rest = rutaFin.Replace("http://localhost:56618", "");
// LeerExcel(rest);
return Request.CreateResponse(HttpStatusCode.Created, savedFilePath);
});
return task;
}
So, by choosing the excel manually, neither the absolute path or relative path on the server work for the ExcelQueryFactory string route.
The routes get by this method are the following:
ABSOLUTE:
http://localhost:56618/UploadedFiles/9a27e785-e486-4807-8a80-7abb9b940d8b.xls
And the relative:
/UploadedFiles/9a27e785-e486-4807-8a80-7abb9b940d8b.xls
Is possible to use by the way I want to? During the server is online, the obtained absolute path is accesible, so if I access to that URL, the file is downloaded.
the problem is solved:
As I said, I thought only this library worked locally, but it wasn't.
Since Microsoft has launched a new big update, many people have notice some problems when using Database engine, “Unexpected error from external database driver (1). (Microsoft JET Database Engine)” after applying October security updates.
First, I created a Fake.txt file on /UploadedFiles, folder that is located on the project repository and I give it permission to be always copied, as follows:
Fake.txt properties
With this file, I´m achieving that UploadedFiles folder is copied every time I run the server.
Next step:
Due to Microsoft big update, the recomendation is to "download and install the Microsoft Access Database Engine 2010 Redistributable, and then modify the DB connection strings in Microsoft Excel to use ACE as a provider. Example: Change Provider=Microsoft.Jet.OLEDB.4.0 to Provider=Microsoft.ACE.OLEDB.12.0."
I only have downloaded and install that file, but during this day, 3 new windows updates were installed, so, I dont know if this 3 updates are related with the solution of this problem.
The updates are:
Update 1
Update 2
Update 3
After installing the 2010 database engine version file, I changed the excel extension from .xls to .xlsx and now all work.
I need to download files from opensubtitles.org trough my application which is written in GTK# and C#. The app is based on .NET 4.0 framework.
At first this was the code I was using:
var tZip = new FastZip();
try {
var tRequest = (HttpWebRequest)HttpWebRequest.Create(tDownloadUrl);
var tZipResponse = (HttpWebResponse)tRequest.GetResponse();
using (var tStream = tZipResponse.GetResponseStream()) {
using (var tMemStream = new MemoryStream()) {
tStream.CopyTo(tMemStream);
var tTempPath = Globals.video_location + "OSD";
Directory.CreateDirectory(tTempPath);
tZip.ExtractZip(tMemStream, tTempPath, FastZip.Overwrite.Always, null, #"\.srt$", null, false, true);
var tDirInfo = new DirectoryInfo(tTempPath);
var tFileInfo = new FileInfo(Globals.location_video);
var tSrtFile = tDirInfo.EnumerateFiles().FirstOrDefault();
if (tSrtFile == null) {
writeLog("No .srt file found in zip..");
goto text;
}
writeLog("Downloaded and unpacked: " + tSrtFile.Name);
File.Copy(tSrtFile.FullName, Globals.video_location+Globals.video_name+".srt", true);
Globals.savedTitle = Globals.video_location+Globals.video_name+".srt";
// clean up..
Directory.Delete(tTempPath, true);
writeLog("Deleted temp folder.");
return true;
}
}}
And that worked really well up until few days ago, now it is returning a bunch of html code instead of .zip file. I tried even something like this:
WebClient client = new WebClient();
client.DownloadFile(link, #"OSD\test.zip");
But everything just keeps returning bunch of html code.
The link I am usually trying to download is something like this:
http://dl.opensubtitles.org/en/download/subad/4287952
If you click on the link above it will just redirect you to the opensubtitles.org page of that particular subtitle. But if you right mouse click on that link and then select "open in new tab" or "open in new window" it will automatically start the download. (Tested in Firefox)
Also as soon as I paste that link in "Internet Download Manager" application, it will start the download of the zip file automatically.
If you can help me to resolve this problem I will truly be grateful.
Kind Regards.
I got into this problem because I was filtering the website xml directly. Like from a link such as this one: opensubtitles.org example
And in the beginning it used to work well, but then they changed something on the website and it stopped working. So what I did was build on top of this: OSHandler
That handler library is using XML-RPC so I believe there won't be any problems in the future.
I am building a Windows c# app that needs to upload files to DropBox. Basically I have everything I need for my app(app secret and app key), but I need to have the client tokens saved to my sql DB for future use. According to Dropbox I am unable to save user login info which is good, but finding a good lib is getting tough.I have tried many different DropBox based libraries but run across the following issues:
SharpBox: seems easy enough to use, but need some kind of deserializer to save the client key and client secret anywhere.
OAuth2 Authorizer: Not enough documentation that I can find, in order for me to actually implement this.
DropNet: This is one that looked promising. It's async and looked good, but again I can't find an example of how to perform the auth function and save the variables to a file/DB/Reg/ or anything.
DropBox.API: This is the method that I currently use and it's working. Problem is it's not Async and requires .NET 4.5. I was ok with all the downs but lately found that's it's very touchy about different versions of JSON and other libraries.
I was hoping someone could give me some assistance in getting any of the above OAUTH libs actually working, Just to get the 3 legged auth process working.
UPDATE::
ok so i am going to include some of the code that I am using at the moment, that uses dropbox.api:
// Get Oauth Token
private static OAuthToken GetAccessToken()
{
string consumerKey = "mykey";
string consumerSecret = "myseceret";
var oauth = new OAuth();
var requestToken = oauth.GetRequestToken(new Uri(DropboxRestApi.BaseUri), consumerKey, consumerSecret);
var authorizeUri = oauth.GetAuthorizeUri(new Uri(DropboxRestApi.AuthorizeBaseUri), requestToken);
Process.Start(authorizeUri.AbsoluteUri);
MessageBox.Show("Once Registration is completed Click OK", "Confirmation");
return oauth.GetAccessToken(new Uri(DropboxRestApi.BaseUri), consumerKey, consumerSecret, requestToken);
}
// Complete Oauth function and write to file
private void button5_Click(object sender, EventArgs e)
{
DialogResult result1 = MessageBox.Show("Please register for dropbox before continuing with authentication. The authorization process will take 1 minute to complete. During that time the backup utility window will be unresponsive. Click yes if you are ready to begin the authorization. HAVE YOU REGISTERED FOR DROPBOX YET?", "DO YOU HAVE A DROPBOX ACCOUNT?", MessageBoxButtons.YesNo);
if (result1 == DialogResult.Yes)
{
try
{
u_w.Enabled = false;
var accesstoken = GetAccessToken();
StringBuilder newFile = new StringBuilder();
string temptoken = "";
string tempsecret = "";
string tempprovider = "";
string tempstatus = "";
string[] file = System.IO.File.ReadAllLines(#"C:\cfg\andro_backup.ini");
foreach (string line in file)
{
if (line.Contains("dbkey:"))
{
temptoken = line.Replace("dbkey:", "dbkey:" + accesstoken.Token);
newFile.Append(temptoken + "\r\n");
continue;
}
if (line.Contains("dbsecret:"))
{
tempsecret = line.Replace("dbsecret:", "dbsecret:" + accesstoken.Secret);
newFile.Append(tempsecret + "\r\n");
continue;
}
if (line.Contains("Provider:"))
{
tempprovider = line.Replace("Provider:", "Provider:DropBox");
newFile.Append(tempprovider + "\r\n");
continue;
}
if (line.Contains("Status:"))
{
tempstatus = line.Replace("Status:", "Status:Connected");
newFile.Append(tempstatus + "\r\n");
continue;
}
newFile.Append(line + "\r\n");
}
System.IO.File.WriteAllText(#"C:\cfg\andro_backup.ini", newFile.ToString());
MessageBox.Show("Completed Backup Provider Setup", "Provider Setup Complete");
Configuration.Reload();
The Above works at the moment and I can upload, download files. The issue is it's not Async and I would like to attempt to stay within the .NET 4.0 if possible, this code requires 4.5
Trying to do the same thing with dropnet, I am unable to get it to work at all even using the examples he has given on the page located here https://github.com/dkarzon/DropNet.
I attempted to look at the demos he has on there as well , but they explaing having the user login everytime to perform any functions, where I need the app to be authorized so it can do it's deeds when it needs to. As far as the code I am using for drop net, I literally just copied and pasted what he had there, just to even see if I can get it to connect and still no go.
If you are using DropNet similar to the examples all you need to do is save the return object from the GetAccessToken method. That returns an instance of a UserLogin object which has the Token and secret on it. Or if you are using the async methods for it then the callback parameter.
Checkout the sample here:
https://github.com/dkarzon/DropNet/blob/master/DropNet.Samples/DropNet.Samples.WP7/MainPage.xaml.cs#L69
Post the code you are using for it so I can give you a better explanation for it.
I've been trying for a couple weeks now to run a non-elevated web browser from an elevated process, I have tried various things, duplicating the explorer token, using the WinSafer Apis mentioned here and various other techniques that all failed. Finally I decided to use Microsoft's suggestion of using the Task Scheduler to run the application.
I used the Task Scheduler Managed Wrapper, at first I tried running explorer.exe and passing the url as a command but that did not work so I created a dummy executable that'll launch the site using Process.Start.
Here is how I create the task:
public static void LaunchWin8BrowserThroughTaskScheduler(string sURL)
{
String RunAsUserExecPath = AppDomain.CurrentDomain.BaseDirectory + "URLLaunch.exe";
String Command = string.Format("-w \"{0}\"", sURL);
using (TaskService ts = new TaskService())
{
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "URL Launch";
td.Principal.LogonType = TaskLogonType.InteractiveToken;
TimeTrigger trigger = new TimeTrigger(DateTime.Now.AddSeconds(2))
{
Enabled = true,
EndBoundary = DateTime.Now.AddSeconds(10)
};
td.Triggers.Add(trigger);
td.Actions.Add(new ExecAction( RunAsUserExecPath, Command, null));
td.Settings.StartWhenAvailable = true;
//Delete the task after 30 secs
td.Settings.DeleteExpiredTaskAfter = new TimeSpan(0,0,0,30);
ts.RootFolder.RegisterTaskDefinition("URL Launch", td, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken);
}
}
and this is the code to my dummy executable:
static void Main(string[] args)
{
if(args.Length<=1)
return;
string sCmd = args[0];
string sArg = args[1];
if(string.IsNullOrEmpty(sCmd)||string.IsNullOrEmpty(sArg))
return;
switch (sCmd)
{
case "-w":
{
Process prs = Process.Start(sArg);
}
break;
}
}
This method is working, and the browser is indeed launched non-elevated and I was able to confirm that by checking the Elevated column in Windows 8's task manager.
The only nuance here is that the browser is not launched as the top most window, it is running in the background and I think its got to do with the fact that its being run through task scheduler.
This is causing me problems especially with Modern UI browsers because Windows does not switch to them when a page is launched. I can see that the page has been successfully launched in Chrome, for example, while running in Windows 8 mode, but the fact that it does not switch to the browser just defies the whole purpose of this workaround.
I thought about using SetForegroundWindow but sadly running a URL like the example above or through explorer.exe, Process.Start returns null.
I was wondering if someone can help me fix this and be able to run the browser in foreground.
Regards
I've been able to solve the issue with a very simplistic method.
Just write a shortcut file to somewhere like the TempFolder and execute it through explorer.exe likes so:
public static void GoURL(string url)
{
string sysPath = Environment.GetFolderPath(Environment.SpecialFolder.System);
string ExplorerPath = Path.Combine(Directory.GetParent(sysPath).FullName,
"explorer.exe");
string TempDir = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
string shortcutPath = Path.Combine(TempDir, "Mylink.url");
urlShortcutToTemp(url, shortcutPath);
System.Diagnostics.Process.Start(ExplorerPath, shortcutPath);
}
private static void urlShortcutToTemp(string linkUrl, string shortcutPath)
{
using (StreamWriter writer = new StreamWriter(shortcutPath))
{
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=" + linkUrl);
writer.Flush();
}
}
The same solution can be applied to executables with lnk shortcuts.