I cannot save or load the cache data from my CefSharp browser application.
I tried adding cefSet.CefCommandLineArgs.Add("renderer-process-limit", "1"); after seeing it got suggested alot, same with cefSet.CachePath = //cache directory as string non of them worked, i personally believe that it might be connected to another problem im having which is cef always thinking that its already initialized even after i just open the computer and program can't start without i put this part to the code:
if (Cef.IsInitialized == false)
{
Cef.Initialize(cefSet, performDependencyCheck: true, browserProcessHandler: null);
}
Which means its possibly never initialising, but at the same logically it can't open without initialising when the pc just got open. But since there is no confirmation on initialising being the the exact problem i wanted to ask in a rather open way.
//created chromiumWebBrowser1 on the form
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
private void Form2_Load(object sender, EventArgs e)
{
CefSettings cefSet = new CefSettings();
cefSet.CachePath = curDir + #"\cch";
cefSet.CefCommandLineArgs.Add("renderer-process-limit", "1");
if (Cef.IsInitialized == false)
{
Cef.Initialize(cefSet, performDependencyCheck: true, browserProcessHandler: null);
}
chromiumWebBrowser1.Controls.Add(browser);
}
public static string curDir = Directory.GetCurrentDirectory();
public static string gameLoc = "file:///" + curDir + "/test.html";
public static ChromiumWebBrowser browser = new ChromiumWebBrowser(gameLoc,new RequestContext());
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
Cef.Shutdown();
}
I expected some cache files in my folder as im using the application and after using it. tried with few sites and nothing on cache so far.
Related
I have code that was using the windows FolderPicker. After updating to Windows version 10.0.18362, my use of the FoldePicker has stopped working.
I have attached some code that I used in order to get the access to file is denied result.
using System;
using System.IO;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.Storage.AccessCache;
namespace FolderPickerTest
{
public sealed partial class MainPage : Page
{
private static string path = #"filepath";
string[] lines;
public MainPage()
{
this.InitializeComponent();
test();
}
public async void test()
{
var folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
}
}
private void open_click(object sender, RoutedEventArgs e)
{
lines = new string[2];
try
{
lines = File.ReadAllLines(path);
}
catch(Exception ex)
{
errorText.Text = ($"Error: {ex.Message.ToString()}");
}
}
}
}
The error message that I am currently getting is:
Access to the path 'filepath' is denied
The problem here is that you are trying to read an arbitrary path using System.IO APIs. In one of the releases this was actually working when you declared the broadFileSystemAccess capability, but this is no longer the case. You now must use the StorageFile APIs to achieve your goal.
If you pick a folder with FolderPicker, you get a StorageFolder instance back. You can call GetFileAsync method on this instance to get a file by name. This is an instance of StorageFile which you can read using FileIO.ReadLinesAsync method.
To explain better the answer of Martin Zikmund, in Win 10 1803 (april 2018), broadFileSystemAccess capability was set automatically to ON in the user Settings.
Starting from Win 10 1809 (October 2018), this System setting is set to OFF by default.
You need to ask the user to explicitly set the setting ON in the Settings app, even by referencing the specific setting page directly.
I need to create an Windows Service that will capture images from camera. After serching the internet, i do not find any similar project. I decided to use Aforge.net but got stuck in how to capture image because the Bitmap is not supported in windows Service.
here is my code so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Deployment;
using System.Runtime.InteropServices;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Imaging;
namespace PCSecurityCamera
{
partial class PCSecurityCamera : ServiceBase
{
System.Timers.Timer timeDelay;
string pixDrive = "", journalLoc = "", txnDate = "", txnTime = "", txnDate1 = "";
int retVal, timeFrame = 0, count = 0, txn_count = 0, retention = 0;
string picdirectory;
int i = 0;
string[] availableCameras = new string[5];
private FilterInfoCollection VideoCaptureDevices; //stores all available camera
private VideoCaptureDevice FinalVideoSource; //stores camera to be used
public PCSecurityCamera()
{
InitializeComponent();
timeDelay = new System.Timers.Timer();
timeDelay.Elapsed += new System.Timers.ElapsedEventHandler(WorkProcess);
}
public void WorkProcess(object sender, System.Timers.ElapsedEventArgs e)
{
}
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
LogService("PCSecuritycamera Service is Started");
try
{
int camCount = 0;
Array.Clear(availableCameras,0,availableCameras.Length);
VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach(FilterInfo VideoCaptureDevice in VideoCaptureDevices)
{
availableCameras[camCount] = VideoCaptureDevice.Name.ToString();
LogService(availableCameras[camCount]);
camCount++;
}
if (availableCameras[0] == "")
{
LogService("No Available Camera");
}
else
{
FinalVideoSource = new VideoCaptureDevice(VideoCaptureDevices[0].MonikerString);
LogService("Camera Selected: " + FinalVideoSource.ToString());
FinalVideoSource.NewFrame +=FinalVideoSource_NewFrame;
}
}
catch (Exception e)
{
LogService(e.ToString());
}
timeDelay.Enabled = true;
}
private void FinalVideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
}
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
LogService("Service Stoped");
timeDelay.Enabled = false;
}
private void LogService(string content)
{
FileStream fs = new FileStream(#"C:\Users\talatj\Desktop\Me\ServiceLog.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine(content);
sw.Flush();
sw.Close();
}
}
}
my problem is how to capture the image in windows service.
Please help
System.Drawing Namespace
Classes within the System.Drawing namespace are not supported for use
within a Windows or ASP.NET service. Attempting to use these classes
from within one of these application types may produce unexpected
problems, such as diminished service performance and run-time
exceptions. For a supported alternative, see Windows Imaging
Components.
GDI+
GDI+ functions and classes are not supported for use within a Windows
service. Attempting to use these functions and classes from a Windows
service may produce unexpected problems, such as diminished service
performance and run-time exceptions or errors
HOWEVER!
System.Drawing does work in Services, it's just not supported. There can be issues with high load (running out of unmanaged resources), memory or resource leaks (badly implemented or called dispose patterns)
My suspicions is you have just not referenced the System.Drawing.dll
Note : You will just have to be wary and do this on a trial and error basis, though IMO saving bitmaps should be fine
I'm trying to generate a screenshot from a html page on windows Azure.
This is the code I was using on my personal IIS and I know it works on every test machine.
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
class Program
{
static void Main(string[] args)
{
new WebsiteToImage("http://www.google.com", "C:\\screenshot.jpg");
}
// Define other methods and classes here
public class WebsiteToImage
{
internal string _url;
internal string _fileName;
public WebsiteToImage(string url, string fileName)
{
_url = url;
_fileName = fileName;
// Thread
var thread = new Thread(Generate);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
private void Generate()
{
using (var browser = new WebBrowser { ScrollBarsEnabled = false })
{
browser.Navigate(_url);
browser.DocumentCompleted += WebBrowser_DocumentCompleted;
while (browser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
browser.Dispose();
}
}
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Capture
using (var bmp = new Bitmap(1280, 800))
{
var browser = (WebBrowser)sender;
browser.ClientSize = new Size(1280, 800);
browser.ScrollBarsEnabled = false;
browser.BringToFront();
browser.DrawToBitmap(bmp, browser.Bounds);
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
bmp.Save(_fileName, ImageCodecInfo.GetImageDecoders().FirstOrDefault(c => c.FormatID.Equals(ImageFormat.Jpeg.Guid)), encoderParameters);
}
}
}
}
Now, on Azure I know I can't use GDI+ and I'm pretty sure I can't also use WebBrowser.
Any idea or alternative solution? Even third part component.
You haven't said whether you're using Azure Web Sites or Azure Cloud Services, but from what you say about not being able to use GDI+, I'm guessing Web Sites?
You should certainly be able to run your code in a Cloud Service, either a Web or Worker role. If the code is part of a web application hosted on Web Sites, you can use an Azure Storage Queue to add the URL to be snap-shotted, then poll that queue on a worker role, run your code, and store the resulting file into Blob storage.
If your expected load on the screen-shot server is low, you could probably get away with an Extra-Small instance, which would cost very little.
Update: Awesomium should be an option in this case.
I found Is there a webservice/API to grab a screenshot of another website? and from there this service that do the task with an open source code. For the light use we're planning to do, this is better than a custom implemented solution.
I am making a program updater / launcher that can be used for any program.
I have a config file on the client and a config file on a http server. I get version numbers from both of them and compare them and if they are are not = then update the client.
I have everything working except for when the update starts. What I need is say if someone downloaded my application and do not use if for say a month and in between that time I have 5 or so updates.
The problem is how to I get my program to download the first update , install it and then download the next update untill they have all been downloaded?
I am new to programming and this is the only kind of app I can think of to work on to learn.
Thanks
My settings.conf on http server XML File.
<Table>
<Product>
<Product_id>1</Product_id>
<Product_name>Infected</Product_name>
<Product_version>1.0.0.1</Product_version>
<Product_Url>http://localhost/update/v1.0.0.1.exe</Product_Url>
<Product_id>2</Product_id>
<Product_name>Infected</Product_name>
<Product_version>1.0.0.2</Product_version>
<Product_Url>http://localhost/update/v1.0.0.2.exe</Product_Url>
<Product_id>3</Product_id>
<Product_name>Infected</Product_name>
<Product_version>1.0.0.3</Product_version>
<Product_Url>http://localhost/update/v1.0.0.3.exe</Product_Url>
<Product_id>4</Product_id>
<Product_name>Infected</Product_name>
<Product_version>1.0.0.4</Product_version>
<Product_Url>http://localhost/update/v1.0.0.4.exe</Product_Url>
<Product_id>5</Product_id>
<Product_name>Infected</Product_name>
<Product_version>1.0.0.5</Product_version>
<Product_Url>http://localhost/update/v1.0.0.5.exe</Product_Url>
</Product>
</Table>
My Client Config XML file.
<Table>
<Product>
<Product_id>1</Product_id>
<Product_name>Infected</Product_name>
<Product_version>1.0.0.0</Product_version>
<Product_Url>http://localhost/update/v1.0.0.1.exe</Product_Url>
</Product>
</Table>
My C# Form.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Runtime.Remoting;
namespace Launcher
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string localversion { get; set; }
public string remoteversion { get; set; }
public string UpdateURL { get; set; }
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("http://www.kceoc.com/");
webBrowser2.Navigate("http://www.kceoc.com/");
button1.Enabled = false; // Disable the launch button untill all updates are completed.
GetLocalXMLFile(); //Run first xml function to start everything off.
}
private void GetLocalXMLFile()
{
try //Start error checking.
{
using (XmlTextReader localxml = new XmlTextReader("settings.conf")) //Load xml file in same folder as launcher.exe
{
while (localxml.Read()) // Start reading the settings.conf file
{
switch (localxml.NodeType) //Get the Node that we will use.
{
case XmlNodeType.Text:
label1.Text = localxml.Value; //Change the text of label1 to value of Node.
string localversion = localxml.Value; // Store Node Value in string localversion for latter use.
GetRemoteXMLFile(localversion, remoteversion); //Everything went ok and got a value from Node so pass this all to our next function witch is get remote xml.
break;
}
}
}
}
catch (FileNotFoundException)
{
label1.Text = "Local Config not found. Reinstall the application"; // Catch error incase file is not there.
}
}
private void GetRemoteXMLFile(string localversion, string remoteversion)
{
try //Start error checking
{
using (XmlTextReader remotexml = new XmlTextReader("http://localhost/update/settings.conf")) //Load up remote xml on web server
{
while (remotexml.Read()) //Start reading xml file from server.
{
switch (remotexml.NodeType)
{
case XmlNodeType.Text:
label2.Text = remotexml.Value; // Change value of label2 to remote xml node value
remoteversion = remotexml.Value; // Set the remoteversion string to remotexml.value
CompareXMLFileVersions(localversion, remoteversion); // Everything went ok so send localversion string and remoteversion string to compare function.
break;
}
}
}
}
catch (FileNotFoundException)
{
label1.Text = "Remote config not found. Maby website id down?"; // Catch error incase file is not there.
}
}
private void CompareXMLFileVersions(string localversion, string remoteversion)
{
label1.Text = localversion; // Just so we can see the value in the lables to konw if they have value or not.
label2.Text = remoteversion; // Just so we can see the value in the lables to konw if they have value or not.
if (localversion == remoteversion) // Comparing the values of localversion and remoteversion and if they have same value then
{ // change label3 to You have latest version.
label3.Text = "You have the latest version";
}
else
{
label3.Text = "There is a new version. Starting update process here"; // If localversion and remoteversion are diffrent then let user know the files are out of date and start the updating process..
GetListOfUpdates(remoteversion); // Starting the updating process function..
}
}
private void GetListOfUpdates(string remoteversion)
{
//WebClient webClient = new WebClient();
//webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
//webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
//webClient.DownloadFileAsync(new Uri(remoteversion), #"v1.0.0.1.exe");
string url = "http://localhost/update/v1.0.0.1.exe";
WebClient downloader = new WebClient();
downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(downloader_DownloadFileCompleted);
downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged);
downloader.DownloadFileAsync(new Uri(url), "temp.exe");
}
void downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
label1.Text = e.BytesReceived + " " + e.ProgressPercentage;
}
void downloader_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
//if (e.Error != null)
// MessageBox.Show(e.Error.Message);
//else
// MessageBox.Show("Completed!!!");
}
}
}
Thanks
Welcome to SO!
I am new to programming and this is the only kind of app I can think of to work on to learn. Thanks
Depending on how new you are, I'd really recommend you start with something a little easier. Otherwise, the first thing I'd recommend you do is to actually draw a flowchart. Your logic looks a little off, and it looks as if you're huffing it trying to design this system as you write it, which is something you never want to be doing.
There are a lot of solutions for this that provide a better, more reliable systems then anything you can make yourself, but I can understand the educational value of this sort of project. I made my own 'auto-update/launcher' recently for just that reason, and it works reasonably well, albeit on a free webserver with myself an some friends as the only users.
Here's the flowchart I made for it:
Large:http://i.imgur.com/qS1U8.png
This is actually the second iteration of my little project, with the first being less then overwhelming and somewhat disastrous in uncommon circumstances, but it's a good learning experiance. This one also has goofy command files that I can define things like showing messages to the user during an update, which is nice.
If you don't mind looking at terrible and messy code, you can look through the code repo here, although it's not documented and a few part's aren't actually used but haven't been removed from source control. An example application that uses it is here (source, also messy).
Sorry for what looks like a shameless self-plug, but I can't really answer your question directly and hope that you might be able to make use of some of this as an indication of how you should go about doing this, since it's actually a pretty fun project.
When I start my .net console application from a bat file e.g. start myapp.exe
myapp.exe then tries to write a file to its current directory, although I get a .net runtime error claiming that the file is in use by another application (there is nothing else running)
http://i.stack.imgur.com/XLmnR.png
Although when I launch it normally with out a batch file e.g. double click on it, it functions fine and outputs the file fine. I thought it might be something to do with privilages, although tried running the batch file as an administrator and I got the same error "File is in use..."
Could anyone shed any light on this?
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileSearcher
{
class Program
{
static void Main(string[] args)
{
string dirPath = "C:\\";
FileSystemWatcher fileWatcher = new FileSystemWatcher(dirPath);
fileWatcher.IncludeSubdirectories = true;
fileWatcher.Filter = "*.exe";
// fileWatcher.Filter = "C:\\$Recycle.Bin";
// fileWatcher.Changed += new FileSystemEventHandler(FileWatcher_Changed);
fileWatcher.Created += new FileSystemEventHandler(FileWatcher_Created);
// fileWatcher.Deleted += new FileSystemEventHandler(FileWatcher_Deleted);
// fileWatcher.Renamed += new RenamedEventHandler(FileWatcher_Renamed);
fileWatcher.EnableRaisingEvents = true;
// updated code
Console.ReadKey();
}
static void FileWatcher_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine(e.OldName + " was renamed to " + e.Name);
}
static void FileWatcher_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + " was deleted");
}
static void FileWatcher_Created(object sender, FileSystemEventArgs e)
{
using (StreamWriter fileWriter = new StreamWriter("process.lst", true))
{
var data = true;
fileWriter.Write("C:\\" + e.Name + Environment.NewLine);
}
}
static void FileWatcher_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine(e.Name + "");
}
}
}
It looks like from your batch file that you are sending stdout (1>) to the same file (process.lst) that you are writing to within your application. You can do one or the other, not both.
For example, this application works fine when run by itself:
static void Main(string[] args)
{
StreamWriter writer = File.CreateText("process.lst");
Console.WriteLine("Writing to the file.");
writer.Write("Testing 1.2.3.4");
Console.WriteLine("Finished.");
}
But, when run from the command line like myTestApp.exe 1> process.lst yields the same exception that you have:
The process cannot access the file 'process.lst' because it is being used by another process.
Try doing your process after the OnCreated event has finished. Maybe starting a short timer and writing the file when the timer ticks (remember to stop the timer)
The event that a file has been created is fired immediately, even if the file is not written yet. You should always try to open the file and wait a little bit, when you get the IOException. You can find a solution here: http://bloggingabout.net/blogs/jschreuder/archive/2006/07/06/12886.aspx