Unable to evaluate the expression - c#

I'm unable to debug the the SaveFileToDisk method. Please me help me out how to resolve the issue. Thanks in advance.
private void Download_TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
try
{
PortalTeacherDairyAttachmentList attachment = ((TappedEventArgs)e).Parameter as PortalTeacherDairyAttachmentList;
byte[] attachmentbyte = attachment.Attachment;
DependencyService.Get<IDownloadManager>().SaveFileToDisk(attachment.FileName,attachmentbyte);
}
catch (Exception ex)
{
}
}
SaveFileToDiskCode:
{
Toast.MakeText(Android.App.Application.Context, "Downloading started...", ToastLength.Long).Show();
var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
var absolutepath = dir.AbsolutePath;
string name = filename;
string filePath = System.IO.Path.Combine(absolutepath, name);
try
{
System.IO.File.WriteAllBytes(filePath, data);
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Uri.FromFile(new File(filePath)));
Xamarin.Forms.Forms.Context.SendBroadcast(mediaScanIntent);
OpenFile(filePath, filename);
Toast.MakeText(Android.App.Application.Context, "File downloaded at" + filePath, ToastLength.Long).Show();
CreateNotificationChannel(name);
}
catch (System.Exception e)
{
System.Console.WriteLine(e.ToString());
Toast.MakeText(Android.App.Application.Context, "Error occured", ToastLength.Long).Show();
}
}

Related

Application inexplicably failing capturing screenshots

I have an odd issue that I have been trying to pin down for awhile. Essentially my application opens up various URL's using chrome (data from an array), takes a picture of them, saves them, and continues on looping through the array. The application successfully launches and runs, but variably it fails (usually between 2-5 days). When it fails, chrome no longer appears to open but the application continues to 'run'. Here is the error that is being produced from my try/catches:
at System.Drawing.Graphics.CopyFromScreen(Int32 sourceX, Int32 sourceY, Int32 destinationX, Int32 destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
at Command_Center_Screen_Capture_Agent.Form1.Capture(String name)
My only working theory right now is that there might be an issue with the memory since it's failing to take the picture and failing to open the browser, but I'm not sure how to test that theory.
{UPDATE} Going through the logs on all of my servers, I noticed that while only some had the error above, all of them had the following error:
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(String filename, ImageFormat format)
at Command_Center_Screen_Capture_Agent.Form1.Capture(String name) in SERVER REDACTED\Visual Studio 2012\Projects\Command Center Screen Capture Agent\Command Center Screen Capture Agent\Form1.cs:line 170
This error appears to always be the last error before the system stopped logging and (theoretically) failed.
The code in question is:
try
{
GFX.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
}
catch (Exception e)
{
//Noticed without this if the program was running before skyvision was opened an occasional error popped up
error_logging(e.StackTrace);
}
// Save the screenshot to the specified path
try
{
String filePath = #"\" + pictureNames[count] + ".png";
// MessageBox.Show("Saving file to: " + FILEPATH_LOCATION + forTesting);
BIT.Save(#FILEPATH_LOCATION + #filePath, ImageFormat.Png);
System.Threading.Thread.Sleep(2000);
count++;
_capture.Enabled = true;
}
catch (Exception e)
{
error_logging(e.StackTrace);
//Save error without breaking in case issue with path
//MessageBox.Show("CAPTURE ERROR: \n\n" + e.StackTrace);
}
The full source code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.IO;
using System.Configuration;
namespace Command_Center_Screen_Capture_Agent
{
public partial class Form1 : MaterialSkin.Controls.MaterialForm
{
public Form1()
{
InitializeComponent();
}
//Array storage for URLs and pic names
public static String[] URLS;
public static String[] pictureNames; //Used to save picture by name
//Data
static List<String> URL_LIST = new List<String>();
static List<String> URL_DESC = new List<String>();
static String base_url_1 = "URL_OMITTED";
static String base_url_2 = "URL_OMITTED";
static Configuration configManager = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
int count = 0;
//Create a new bitmap.
static Image BIT = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
Graphics GFX = Graphics.FromImage(BIT);
string FILEPATH_LOCATION = (#"FILEPATH_OMITTED");
string ERROR_LOGGING = Path.Combine(Application.StartupPath, "Error Logs");
private void error_logging(string line)
{
try
{
Guid filename = Guid.NewGuid();
string targetPath = Path.Combine(ERROR_LOGGING, filename + ".txt");
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(targetPath))
{
file.WriteLine(line);
}
}
catch (Exception E)
{
MessageBox.Show("Failure Writing Error log. " + E.StackTrace);
}
}
private void load_data()
{
//Attempt to load data
try
{
string line;
System.IO.StreamReader file =
new System.IO.StreamReader(AppDomain.CurrentDomain.BaseDirectory + "data.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("SERVERS:"))
{
URL_LIST = line.Substring(8).Split(',').ToList();
}
if (line.Contains("DESC:"))
{
URL_DESC = line.Substring(5).Split(',').ToList();
}
}
file.Close();
}
catch (Exception criticalError)
{
MessageBox.Show("Critical Error. Could not access data file. Closing application. \n\n" + criticalError.StackTrace);
Application.Exit();
}
}
private void build_error_log()
{
if (!Directory.Exists(ERROR_LOGGING))
{
Directory.CreateDirectory(ERROR_LOGGING);
}
}
private void Form1_Load(object sender, EventArgs e)
{
build_error_log();
load_data();
Checkpath();
cycleTimeTxtBx.Text = Properties.Settings.Default.TimeToLoadPage.ToString();
}
private bool Checkpath()
{
this.Hide();
if (Directory.Exists(FILEPATH_LOCATION))
{
return (true);
}
else
{
DirectoryInfo dir = Directory.CreateDirectory(FILEPATH_LOCATION);
return false;
}
}
private void Capture(string name)
{
try
{
if (!Checkpath())
{
System.Threading.Thread.Sleep(1000);
}
}
catch (Exception whoops)
{
error_logging(whoops.StackTrace);
//Console.WriteLine(whoops);
}
// Take the screenshot from the upper left corner to the right bottom corner.
try
{
GFX.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
}
catch (Exception e)
{
error_logging(e.StackTrace);
}
// Save the screenshot to the specified path
try
{
String filePath = #"\" + pictureNames[count] + ".png";
BIT.Save(#FILEPATH_LOCATION + #filePath, ImageFormat.Png);
System.Threading.Thread.Sleep(2000);
count++;
_capture.Enabled = true;
}
catch (Exception e)
{
error_logging(e.StackTrace);
//Save error without breaking in case issue with path
//MessageBox.Show("CAPTURE ERROR: \n\n" + e.StackTrace);
}
KillChrome();
}
private void KillChrome()
{
try
{
Process[] procsChrome = Process.GetProcessesByName("chrome");
foreach (Process pro in procsChrome)
{
pro.Kill();
}
}
catch (Exception e)
{
error_logging(e.StackTrace);
Console.WriteLine(e);
}
}
private void _capture_Tick(object sender, EventArgs e)
{
//Assume that the URL array hasn't been setup
if (URLS == null || URLS.Length < 1)
{
URLS = URL_LIST.ToArray();
pictureNames = URL_DESC.ToArray();
}
try
{
Process process = new Process();
process.StartInfo.FileName = "chrome.exe";
if (count < URLS.Length)
{
string sysCode = URLS[count];
string market;
int delimIndex = sysCode.IndexOf("|");
market = sysCode.Substring(delimIndex + 1);
sysCode = sysCode.Substring(0, delimIndex);
string useable_url = base_url_1 + sysCode + base_url_2 + market;
process.StartInfo.Arguments = useable_url + " --start-maximized --incognito --new-window";
}
else
{
count = 0;
string sysCode = URLS[count];
string market;
int delimIndex = sysCode.IndexOf("|");
market = sysCode.Substring(delimIndex + 1);
sysCode = sysCode.Substring(0, delimIndex);
string useable_url = base_url_1 + sysCode + base_url_2 + market;
process.StartInfo.Arguments = useable_url + " --start-maximized --incognito --new-window";
}
process.Start();
_capture.Enabled = false;
System.Threading.Thread.Sleep(Properties.Settings.Default.TimeToLoadPage * 1000);
Capture("no");
}
catch (Exception error)
{
error_logging(error.StackTrace);
//MessageBox.Show(error.StackTrace);
}
}
private void startBTN_Click(object sender, EventArgs e)
{
_capture.Enabled = true;
this.Hide();
notifyIcon1.Visible = true;
}
private void saveBtn_Click(object sender, EventArgs e)
{
try
{
Properties.Settings.Default.TimeToLoadPage = Convert.ToInt32(cycleTimeTxtBx.Text);
Properties.Settings.Default.Save();
}
catch (Exception error)
{
MessageBox.Show("Error: Unable to parse cycle timer. Please only use integers when setting the cycle time.", "Parsing Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
cycleTimeTxtBx.Text = Properties.Settings.Default.TimeToLoadPage.ToString();
}
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
Console.WriteLine("Clicked");
Show();
_capture.Enabled = false;
this.WindowState = FormWindowState.Normal;
notifyIcon1.Visible = false;
}
}
}

BackgroundDownloader The system cannot find the file specified

I'm using C# and Windows Phone 8.1 as Universal.
I Have an issue with BackgroundDownloader. when I start a downloader, it gave me an exception:
Downloading http://localhost/MySong.mp3 to MySong.mp3 with Default priority, a95c00db-738d-4e22-a456-dc30d49b0a3b
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Exception: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
here is my code:
private void downladButton_Tapped(object sender, TappedRoutedEventArgs e)
{
PumpUrl(txtUrl.Text);
}
async void PumpUrl(string url)
{
if (!string.IsNullOrEmpty(url) && CheckUrl(url))
StartDownloadMethod(url);
else
await new MessageDialog("Looks like URL is invalid.\r\nPlease check your URL and try again"").ShowAsync();
}
public bool CheckUrl(string URL)
{
Uri source;
if (Uri.TryCreate(URL, UriKind.RelativeOrAbsolute, out source))
return true;
else
return false;
}
public void StartDownloadMethod(string url, string fileName = null)
{
StartDownload(url, BackgroundTransferPriority.Default, false, fileName);
}
private async void StartDownload(string url, BackgroundTransferPriority priority, bool requestUnconstrainedDownload, string fileName = null)
{
Uri source;
if (!Uri.TryCreate(url.Trim(), UriKind.RelativeOrAbsolute, out source))
{
Debug.WriteLine("Invalid URI.");
return;
}
string destination = null;
if (string.IsNullOrEmpty(fileName))
try
{
destination = System.IO.Path.GetFileName(Uri.UnescapeDataString(url)).Trim();
}
catch { }
else
destination = Uri.UnescapeDataString(fileName).Trim();
if (string.IsNullOrWhiteSpace(destination))
{
Debug.WriteLine("A local file name is required.");
return;
}
StorageFile destinationFile = null;
try
{
if (vars.localType == LocalType.SDCard)
destinationFile = await KnownFolders.RemovableDevices.CreateFileAsync(
"Downloads\\Test App\\" + destination, CreationCollisionOption.GenerateUniqueName);
else
destinationFile = await KnownFolders.MusicLibrary.CreateFileAsync(
"Test App\\" + destination, CreationCollisionOption.GenerateUniqueName);
}
catch (FileNotFoundException ex)
{
Debug.WriteLine("Error while creating file: " + ex.Message);
return;
}
catch (Exception ex) { Debug.WriteLine("Error while creating file: " + ex.Message); }
if (destinationFile == null)
return;
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(source, destinationFile);
Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}",
source.AbsoluteUri, destinationFile.Name, priority, download.Guid));
download.Priority = priority;
Add(url, destination, download);
if (!requestUnconstrainedDownload)
{
// Attach progress and completion handlers.
await HandleDownloadAsync(download, true);
return;
}
List<DownloadOperation> requestOperations = new List<DownloadOperation>();
requestOperations.Add(download);
UnconstrainedTransferRequestResult result;
try
{
result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations);
}
catch (NotImplementedException)
{
Debug.WriteLine(
"BackgroundDownloader.RequestUnconstrainedDownloadsAsync is not supported in Windows Phone.");
return;
}
Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Request for unconstrained downloads has been {0}",
(result.IsUnconstrained ? "granted" : "denied")));
await HandleDownloadAsync(download, true);
}
private async Task HandleDownloadAsync(DownloadOperation download, bool start)
{
try
{
Debug.WriteLine("Running: " + download.Guid);
bool bb = false;
foreach (DownloadOperation item in DownloadDB.activeDownloads)
{
if (item != null && item.Guid == download.Guid)
{
bb = true;
break;
}
}
if (!bb)
DownloadDB.activeDownloads.Add(download);
Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
CancellationTokenSource cts = new CancellationTokenSource();
AppendCancellationTokenSource(download, cts);
if (start)
await download.StartAsync().AsTask(cts.Token, progressCallback);
else
await download.AttachAsync().AsTask(cts.Token, progressCallback);
ResponseInformation response = download.GetResponseInformation();
DownloadDB.RemoveChildByGuid(download.Guid.ToString());
DownloadDB.SaveDB();
Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}",
download.Guid, response.StatusCode));
}
catch (TaskCanceledException taskCanceled)
{
Debug.WriteLine("TaskCanceledException: " + download.Guid + "\t" + taskCanceled.Message);
DownloadDB.RemoveChildByGuid(download.Guid.ToString());
}
catch (Exception ex)
{
Debug.WriteLine("Exception: " + ex.Message);
}
finally
{
DownloadDB.RemoveChildByGuid(download.Guid.ToString());
DownloadDB.activeDownloads.Remove(download);
}
}
I used my code in other application 3 month ago and it works fine but in this application dosent work. Where I wrong?
Thanks

Upload a file using file upload in ASP.net

I wrote the code to upload the file and save in project root directory. How can I change this to save the path into database and the files into a separate folder from project?
protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile) {
try {
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
saveImgPathToDB(filename, 3);
StatusLabel.Text = "Upload status: File uploaded!";
} catch (Exception ex) {
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
private void saveImgPathToDB(string path, int recordID)
{
using (sqlconnection db = new sqlconnection("your_connection_string")) {
using (sqlcommand cmd = new sqlcommand("INSERT INTO photo_table (PhotoPath) VALUES (#path) WHERE someId=#someid", cn)) {
cmd.parameters.addwithvalue("#path", path);
cmd.parameters.addwithvalue("someid", recordID);
cmd.connection.open();
try {
cmd.executenonquery();
}
}
}
}

How to Transfer Files in different Threads with FileWatcher

I have a form with a File Watcher to which he transfers to multiple addresses all video files placed in a folder. What is the best option so that when multiple files are added to even be able to perform each transfer in a thread. Here's an example of my code:
DockingBarTransferEntities context = new DockingBarTransferEntities();
private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
{
IEnumerable<Diretorios> directories = context.Diretorios.ToList();
foreach (var destino in directories)
{
try
{
Transfere(e.FullPath,Path.GetFileName(e.FullPath),destino);
}
catch (Exception ex)
{
textBox1.Text += "Error: " + ex.Message;
}
}
}
public void Transfere(string fullPath, string name, Diretorios diretorio)
{
try
{
if (Directory.Exists(diretorio.Caminho))
{
string fileName = Path.GetFileName(fullPath);
fileName = String.Format("{0}\\{1}", diretorio.Caminho, fileName);
FileInfo arquivo = new FileInfo(fullPath);
arquivo.CopyTo(fileName, true);
}
}
catch (Exception ex)
{
}
}
It should be as simple as this:
Task.Factory.StartNew(() => Transfere(e.FullPath, Path.GetFileName(e.FullPath), destino));
instead of calling Transfere directly.

error in C# project

here are my two functions:
public void SetCompanies()
//set the Companies table from Shret.net DataBase
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://api.sherut.net/?method=Company");
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
try
{
webClient.OpenReadAsync(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void webClient_OpenReadCompleted(object sender, OpenWriteCompletedEventArgs e)
{
try
{
DataContractJsonSerializer serializer = null;
var companies = (Companies)serializer.ReadObject(e.Result);
foreach (Company c in companies.data)
{
MessageBox.Show(c.Name + " " + c.CompanyID);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
and this is the error i get:
"No overload for 'webClient_OpenReadCompleted' matches delegate
'System.Net.OpenReadCompletedEventHandler'"
i dont understand why, because i wrote the handler after this function......
Thanks in advance!
OpenReadCompleted doesn't take OpenWriteCompletedEventArgs.

Categories