I have an Windows Form Application which utilises CefSharp.
A while ago I used a chunk of code that saves the state of the browser such as login details etc so that the user does not have to log in multiple times.
This is the code I used:
private static bool _hasRun;
CefSettings settings = new CefSettings();
if (!_hasRun)
{
Cef.Initialize(new CefSettings { CachePath = "MyCachePath", PersistSessionCookies = true });
}
_hasRun = true;
string cache_dir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + #"\CEF";
settings.CachePath = cache_dir;
settings.CefCommandLineArgs.Add("persist_session_cookies", "1");
string link = Domain;
chrome = new ChromiumWebBrowser(link);
this.tabPage2.Controls.Add(chrome);
chrome.Dock = DockStyle.Fill;
This code runs fine in my old application but when using this on my most recent app I receive this error message:
Any suggestions?
You must provide a full path.
non-absolute: "MyCachepath"
absolute: "C:\users\username\documents\MyCachepath"
why did it work in older projects?
Some project types and versions automaticallly translate an relative path into an absolute path like so:
environment.CurrentDirectory + #"\MyCachepath"
Related
I am trying to incorporate a browser into a console application using CefSharp Offscreen with dotnet core.
Is it possible to view the web page inside the Chromium browser this way?
In the code below (largely taken from their Offscreen github example) I am trying to display a simple HTML page (later it'll be React or Angular but for now HTML is fine).
In their code they l;oad up a webpage in Chromium and take a picture of it, I want to be able to view the webpae that it takes a screenshot of.
public static void Start()
{
//Only required for PlatformTarget of AnyCPU
AppDomain.CurrentDomain.AssemblyResolve += Resolver;
Console.WriteLine("apply cef settings");
CefSettings settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = "localfolder",
SchemeHandlerFactory = new FolderSchemeHandlerFactory(
rootFolder: #"..\..\..\..\html",
defaultPage: "index.html"
)
});
Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null);
CefSharpSettings.ShutdownOnExit = true;
Console.WriteLine("load web page");
ChromeBrowser = new ChromiumWebBrowser("localfolder://cefsharp/");
Console.ReadKey();
Cef.Shutdown();
}
var settings = new CefSettings();
// Initialize cef with the provided settings
settings.CachePath = "C:/Users/Anoni/Source/Repos/WindowsFormsApp1/bin/Debug/Cache";
Cef.Initialize(settings);
// Create a browser component
chromeBrowser = new ChromiumWebBrowser("https://www.reddit.com/r/Turkishleft/");
// Add it to the form and fill it to the form window.
this.Controls.Add(chromeBrowser);
chromeBrowser.Dock = DockStyle.Fill;
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
settings.RemoteDebuggingPort = 8088;
These are my CefSharp settings. As you can see, CefSharp stores my cache in "C:/Users/Anoni/Source/Repos/WindowsFormsApp1/bin/Debug/Cache". But i want it to store cache wherever the application starts from. For example, if app start from "D:/", I want it to save cache in "D:/Cache". How can i make that happen?
Found it. Line of code should be
settings.CachePath = Application.StartupPath + "/Cache";
I am trying to create a torrent file with monotorrent package using C#.
I already created the torrent file with the torrent creator but I want to add some other options that I can't find in the torrent creator methods or properties.
Options that I am looking for :
adding tracking url(S),
Web seed URL(S),
Source,
Optimize alignment.
Here is a snippet of my code:
string filepath = ofd.FileName;
PathDirectoryTxt.Text = filepath;
MonoTorrent.Common.TorrentCreator torrentcreaotr = new MonoTorrent.Common.TorrentCreator();
ITorrentFileSource fileSource = new TorrentFileSource(filepath);
torrentcreaotr.Comment = CommentsRichTxt.Text;
torrentcreaotr.CreatedBy = "Google using " + VersionInfo.ClientVersion;
torrentcreaotr.Publisher = "www.itsitus.com";
if ((PrivateTorrentCheckbox.Checked))
{
torrentcreaotr.Private = true;
}
else if (!PrivateTorrentCheckbox.Checked)
{
torrentcreaotr.Private = false;
}
string savepath = sfd.FileName;
torrentcreaotr.Create(fileSource, savepath);
MessageBox.Show("torrent file has been created successfully !");
Have you tried setting the 'Announce' property with the URL for your tracker, or setting the 'Announces' if you have tracker tiers/fallbacks? Similarly, Webseeds are set using the GetrightHttpSeed property.
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) };
}
}
}
}
I can successfully create an Application Pool and an Application plus link them together.
What I am failing to do however is set the applications Windows Authentication to true and Anonymous Authentication to false.
I patched a hodge podge of examples into one to make this work but I keep getting the following error.
This configuration section cannot be used at this path. This happens
when the section is locked at a parent level. Locking is either by
default (overrideModeDefault="Deny"), or set explicitly by a location
tag with overrideMode="Deny" or the legacy allowOverride="false".
Now barring the obvious that overrideMode needs to likely equal Allow. How do I accomplish this?
public static bool CreateApplication(String websiteName, String applicationName, String appDIR,String appPoolName)
{
try
{
ServerManager iisManager = new ServerManager();
if (!applicationName.Contains("/"))
applicationName = "/" + applicationName;
var app = iisManager.Sites[websiteName].Applications.Add(applicationName, appDIR);
app.ApplicationPoolName = appPoolName;
var config = app.GetWebConfiguration();
var anonsection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication", iisManager.Sites[websiteName].Name + applicationName);
//This is where it fails
anonsection["enabled"] = false;
var winsection = config.GetSection("system.webServer/security/authentication/windowsAuthentication", iisManager.Sites[websiteName].Name + applicationName);
winsection["enabled"] = true;
iisManager.CommitChanges();
return true;
}
catch
{
return false;
}
}
Use the following commands from an admin command prompt
%windir%\system32\inetsrv\appcmd unlock config -section:system.webServer/security/authentication/windowsAuthentication
%windir%\system32\inetsrv\appcmd unlock config -section:system.webServer/security/authentication/anonymousAuthentication
This will unlock those config sections.