I am making a module that shows the tree view of documents that are stores on my drive in a folder. It is retrieving well. But the problem is that the documents are in different format like(.pdf, .docx etc). That are not opening in browser on click. There it shows a 404.4 error. So Tell me how can I download/open different format files through button click? The following is my code:
protected void Page_Load(System.Object sender, System.EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
if (Settings["DirectoryPath"] != null)
{
BindDirectory(Settings["DirectoryPath"].ToString());
}
else
{
BindDirectory(Server.MapPath("~/"));
}
}
}
catch (DirectoryNotFoundException DNEx)
{
try
{
System.IO.Directory.CreateDirectory("XIBDir");
BindDirectory(Server.MapPath("XIBDir"));
}
catch (AccessViolationException AVEx)
{
Response.Write("<!--" + AVEx.Message + "-->");
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
#endregion
#region Optional Interfaces
/// -----------------------------------------------------------------------------
/// <summary>
/// Registers the module actions required for interfacing with the portal framework
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <history>
/// </history>
/// -----------------------------------------------------------------------------
public ModuleActionCollection ModuleActions
{
get
{
ModuleActionCollection Actions = new ModuleActionCollection();
Actions.Add(this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl(), false, SecurityAccessLevel.Edit, true, false);
return Actions;
}
}
#endregion
private void BindDirectory(string Path)
{
try
{
System.IO.DirectoryInfo dirRoot = new System.IO.DirectoryInfo(Path);
TreeNode tnRoot = new TreeNode(Path);
tvDirectory.Nodes.Add(tnRoot);
BindSubDirectory(dirRoot, tnRoot);
tvDirectory.CollapseAll();
}
catch (UnauthorizedAccessException Ex)
{
TreeNode tnRoot = new TreeNode("Access Denied");
tvDirectory.Nodes.Add(tnRoot);
}
}
private void BindSubDirectory(System.IO.DirectoryInfo dirParent, TreeNode tnParent)
{
try
{
foreach (System.IO.DirectoryInfo dirChild in dirParent.GetDirectories())
{
//TreeNode tnChild = new TreeNode(dirChild.Name);
TreeNode tnChild = new TreeNode(dirChild.Name, dirChild.FullName);
tnParent.ChildNodes.Add(tnChild);
BindSubDirectory(dirChild, tnChild);
}
}
catch (UnauthorizedAccessException Ex)
{
TreeNode tnChild = new TreeNode("Access Denied");
tnParent.ChildNodes.Add(tnChild);
}
}
private void BindFiles(string Path)
{
try
{
tvFile.Nodes.Clear();
System.IO.DirectoryInfo dirFile = new System.IO.DirectoryInfo(Path);
foreach (System.IO.FileInfo fiFile in dirFile.GetFiles("*.*"))
{
string strFilePath = Server.MapPath(fiFile.Name);
string strFilePaths = "~/" + fiFile.FullName.Substring(15);
TreeNode tnFile = new TreeNode(fiFile.Name, fiFile.FullName, "", strFilePaths, "_blank");
tvFile.Nodes.Add(tnFile);
}
}
catch (Exception Ex)
{
Response.Write("<!--" + Ex.Message + "-->");
}
}
protected void tvDirectory_SelectedNodeChanged(object sender, EventArgs e)
{
try
{
string strFilePath = tvDirectory.SelectedNode.Value;
BindFiles(tvDirectory.SelectedNode.Value);
}
catch (Exception Ex)
{
Response.Write("<!--" + Ex.Message + "-->");
}
}
}
}
404.4 means that the web server (IIS presumably) does not now how to serve the file (based on extension). If your code is serving other files correctly, this is a web server configuration issue. Check your servers documentation for adding the appropriate handlers for the file extensions that aren't working.
I would use a hyperlink in your treeview that opens the link: openfile.ashx?path=[insertpathhere] (make sure that your link opens in target="_blank")
within your Generic Handler (ASHX) you have access to load a file from Disk, and stream its bytes into the responseStream. and that will cause the file to download at the browser. You should also set the content-type where applicable.
Code Sample Requested...
Preface: There are some "extra" things going on here... I base64 Encoded the path in my example because I didnt want the path to be 'human-readable'. Also, when I handed it off to the browser I am pre-pending 'export-' plus a timestamp... but you get the idea...
public class getfile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var targetId = context.Request.QueryString["target"];
if (string.IsNullOrWhiteSpace(targetId))
{
context.Response.ContentType = "text/plain";
context.Response.Write("Fail: Target was expected in querystring.");
return;
}
try
{
var url = new String(Encoding.UTF8.GetChars(Convert.FromBase64String(targetId)));
var filename = url.Substring(url.LastIndexOf('\\') + 1);
filename = "export-" + DateTime.Now.ToString("yyyy-MM-dd-HHmm") + filename.Substring(filename.Length - 4);
context.Response.ContentType = "application/octet-stream";
context.Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", filename));
var data = File.ReadAllBytes(url);
File.Delete(url);
context.Response.BinaryWrite(data);
}
catch (Exception ex)
{
context.Response.Clear();
context.Response.Write("Error occurred: " + ex.Message);
context.Response.ContentType = "text/plain";
context.Response.End();
}
}
public bool IsReusable { get { return false; } }
}
Related
I'm developing a web form where I wish to upload a document related to a particular user into a folder and make a respective entry for the same in MySql server database. Now whenever I submit my details of my document, it uploads the document just fine but at times it skips the entry into the data base.
Code Segment 1
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
String path = Server.MapPath("~/AdminUploads/");
if (FileUpload1.HasFile)
{
Response.Write(FileUpload1.FileName);
try
{
FileUpload1.SaveAs(path + FileUpload1.FileName);
DOCUPLOADED doc = new DOCUPLOADED();
doc.DOCTYPE = Int32.Parse(DropDownList2.SelectedValue);
doc.DOCID = TextBox4.Text;
doc.FILEPATH = path + FileUpload1.FileName;
doc.FORUSER = Int64.Parse(TextBox5.Text);
doc.FILENAME = TextBox6.Text;
uploaddoc ud = new uploaddoc(doc);
if (ud.upload())
{
Response.Write("<script>alert('Addition succesfull');<script>");
}
else
{
Response.Write("<script>alert('Fatal error : addition unsuccesfull');</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('Error : File was not uploaded ');</script>");
}
}
Code Segment 2
public class uploaddoc
{
private DOCUPLOADED doc;
public uploaddoc(DOCUPLOADED doc)
{
this.doc = doc;
}
public bool upload()
{
if (doc != null)
{
dbcfDataContext dc = new dbcfDataContext();
dc.DOCUPLOADEDs.InsertOnSubmit(doc);
try
{
dc.SubmitChanges();
}
catch (Exception ex)
{
//
}
return true;
}
else
return false;
}
}
ID is supposed to be autoincremented, you can see 1-6 are absent,so are 9 10 etc.
dbcfdatacontext is the connection to database done by creating a dbml file and dragging the tables on to it.
I have fixed your code:
public class uploaddoc
{
private DOCUPLOADED doc;
public uploaddoc(DOCUPLOADED doc)
{
this.doc = doc;
}
public bool upload()
{
if (doc != null)
{
dbcfDataContext dc = new dbcfDataContext();
dc.DOCUPLOADEDs.InsertOnSubmit(doc);
//try
//{
dc.SubmitChanges();
//}
//catch (Exception ex)
//{
//
//}
return true;
}
else
return false;
}
}
But in all seriousness, empty catch blocks are the equivalent of shooting yourself in the foot. Don't do that.
I want to create a C# application using windows forms that let me upload files to a webserver, i have seen a lot of tutorial and everyone of them prove to be useless to solve my problem.
and with my project i have the next code in the button for upload
WebClient client = new WebClient();
client.UploadFile("http://localhost:8080/", location);
from here i had have several errors, an try multiple ideas, some of my more common errors are 404 not found or innaccessible path, also sometimes it doenst display me an error and works but the file doesn't save in the indicated path.
some of the links i use to solve the problem are the next ones:
http://www.c-sharpcorner.com/UploadFile/scottlysle/UploadwithCSharpWS05032007121259PM/UploadwithCSharpWS.aspx
http://www.c-sharpcorner.com/Blogs/8180/
How to upload a file in window forms?
upload a file to FTP server using C# from our local hard disk.
private void UploadFileToFTP()
{
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/sample.txt");
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential("user", "pass");
byte[] b = File.ReadAllBytes(#"E:\sample.txt");
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
if (ftpResp != null)
{
if(ftpResp.StatusDescription.StartsWith("226"))
{
Console.WriteLine("File Uploaded.");
}
}
}
In windows:
private void uploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) return;
Upload(openFileDialog.FileName);
}
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("http://www.yoursite.com/UploadMethod/");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
var data = System.IO.File.ReadAllBytes(fileName);
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In server:
[HttpPost]
public async Task<object> UploadMethod()
{
var file = await Request.Content.ReadAsByteArrayAsync();
var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
var filePath = "/upload/files/";
try
{
File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);
}
catch (Exception ex)
{
// ignored
}
return null;
}
winform
string fullUploadFilePath = #"C:\Users\cc\Desktop\files\test.txt";
string uploadWebUrl = "http://localhost:8080/upload.aspx";
client.UploadFile(uploadWebUrl , fullUploadFilePath );
asp.net create upload.aspx as below
<%# Import Namespace="System"%>
<%# Import Namespace="System.IO"%>
<%# Import Namespace="System.Net"%>
<%# Import NameSpace="System.Web"%>
<Script language="C#" runat=server>
void Page_Load(object sender, EventArgs e) {
foreach(string f in Request.Files.AllKeys) {
HttpPostedFile file = Request.Files[f];
file.SaveAs(Server.MapPath("~/Uploads/" + file.FileName));
}
}
</Script>
<html>
<body>
<p> Upload complete. </p>
</body>
</html>
you should set in win app
WebClient myWebClient = new WebClient();
string fileName = "File Address";
Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);
// Upload the file to the URI.
// The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
byte[] responseArray = myWebClient.UploadFile(uriString,fileName);
then set read and write permission for SubDir
create a simple API Controller file in the Controllers folder and name it UploadController.
Let’s modify that file by adding a new action that will be responsible for the upload logic:
[HttpPost, DisableRequestSizeLimit]
public IActionResult UploadFile()
{
try
{
var file = Request.Form.Files[0];
string folderName = "Upload";
string webRootPath = _host.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
string ext = Path.GetExtension(file.FileName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string fileName = "";
string name = Path.GetFileNameWithoutExtension(file.FileName);
string fullPath = Path.Combine(newPath, name + ext);
int counter = 2;
while (System.IO.File.Exists(fullPath))
{
fileName = name + "(" + counter + ")" + ext;
fullPath = Path.Combine(newPath, fileName);
counter++;
}
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
return Ok();
}
return Ok();
}
catch (System.Exception ex)
{
return BadRequest();
}
}
We are using a POST action for the upload-related logic and disabling the request size limit as well.
and use code below in Winform
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("https://localhost/api/upload");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
client.UploadFileAsync(uri, directoryfile);
client.UploadFileCompleted += Client_UploadFileCompleted;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
{
MessageBox.Show("done");
}
Goodluck
I'm developing an application to control cafeteria consumption for my company. Basically each employee has a badge id with a barcode, and they are entitled to a free meal every day. The application will scan the badge and log each employees' meals. It will run on a Motorola MK4000 device, which has an integrated scanner and runs on Windows CE.
I've got an issue with the device scanner. I can get it to run and scan fine, but if it stays idle for a few minutes, it goes to "Waiting" status, the laser turns off, and doesn't come back on. I've tried monitoring the status and starting a new read when it changes to that status, but then it just keeps scanning false reads indefinitely.
Can you guys help me figure out what im doing wrong?
This is the class I'm using for the scanner functionality. It wasn't developed by me, but its begin used for other applications on the same device (I made a few changes to it, mostly on the error messages).
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace MK4000
{
class BarCode
{
#region Fields
private Symbol.Barcode.Reader myReader = null;
private Symbol.Barcode.ReaderData myReaderData = null;
private System.EventHandler myReadNotifyHandler = null;
private System.EventHandler myStatusNotifyHandler = null;
#endregion Fields
#region Properties
/// <summary>
/// Provides the access to the Symbol.Barcode.Reader reference.
/// The user can use this reference for his additional Reader - related operations.
/// </summary>
public Symbol.Barcode.Reader Reader
{
get
{
return myReader;
}
}
public String ErrorMessage
{
get
{
return "Error";
}
}
#endregion Properties
#region Methods
/// <summary>
/// Attach a ReadNotify handler.
/// </summary>
public void AttachReadNotify(System.EventHandler ReadNotifyHandler)
{
// If we have a reader
if (myReader != null)
{
// Attach the read notification handler.
myReader.ReadNotify += ReadNotifyHandler;
myReadNotifyHandler = ReadNotifyHandler;
}
}
/// <summary>
/// Attach a StatusNotify handler.
/// </summary>
public void AttachStatusNotify(System.EventHandler StatusNotifyHandler)
{
// If we have a reader
if (myReader != null)
{
// Attach status notification handler.
myReader.StatusNotify += StatusNotifyHandler;
myStatusNotifyHandler = StatusNotifyHandler;
}
}
/// <summary>
/// Detach the ReadNotify handler.
/// </summary>
public void DetachReadNotify()
{
if ((myReader != null) && (myReadNotifyHandler != null))
{
// Detach the read notification handler.
myReader.ReadNotify -= myReadNotifyHandler;
myReadNotifyHandler = null;
}
}
/// <summary>
/// Detach a StatusNotify handler.
/// </summary>
public void DetachStatusNotify()
{
// If we have a reader registered for receiving the status notifications
if ((myReader != null) && (myStatusNotifyHandler != null))
{
// Detach the status notification handler.
myReader.StatusNotify -= myStatusNotifyHandler;
myStatusNotifyHandler = null;
}
}
/// <summary>
/// Initialize the reader.
/// </summary>
public bool InitReader()
{
// If the reader is already initialized then fail the initialization.
if (myReader != null)
{
return false;
}
else // Else initialize the reader.
{
try
{
// Get the device selected by the user.
Symbol.Generic.Device MyDevice =
Symbol.StandardForms.SelectDevice.Select(
Symbol.Barcode.Device.Title,
Symbol.Barcode.Device.AvailableDevices);
if (MyDevice == null)
{
MessageBox.Show(ErrorMessage);
return false;
}
// Create the reader, based on selected device.
myReader = new Symbol.Barcode.Reader(MyDevice);
// Create the reader data.
myReaderData = new Symbol.Barcode.ReaderData(
Symbol.Barcode.ReaderDataTypes.Text,
Symbol.Barcode.ReaderDataLengths.MaximumLabel);
// Enable the Reader.
myReader.Actions.Enable();
// In this sample, we are setting the aim type to trigger.
switch (myReader.ReaderParameters.ReaderType)
{
case Symbol.Barcode.READER_TYPE.READER_TYPE_IMAGER:
myReader.ReaderParameters.ReaderSpecific.ImagerSpecific.AimType = Symbol.Barcode.AIM_TYPE.AIM_TYPE_TRIGGER;
//myReader.Parameters.Feedback.Success.BeepTime = 0;
break;
case Symbol.Barcode.READER_TYPE.READER_TYPE_LASER:
myReader.ReaderParameters.ReaderSpecific.LaserSpecific.AimType = Symbol.Barcode.AIM_TYPE.AIM_TYPE_TRIGGER;
break;
case Symbol.Barcode.READER_TYPE.READER_TYPE_CONTACT:
// AimType is not supported by the contact readers.
break;
}
myReader.Actions.SetParameters();
}
catch (Symbol.Exceptions.OperationFailureException ex)
{
MessageBox.Show(ex.Message);
return false;
}
catch (Symbol.Exceptions.InvalidRequestException ex)
{
MessageBox.Show(ex.Message);
return false;
}
catch (Symbol.Exceptions.InvalidIndexerException ex)
{
MessageBox.Show(ex.Message);
return false;
};
return true;
}
}
/// <summary>
/// Start a read on the reader.
/// </summary>
public void StartRead(bool toggleSoftTrigger)
{
// If we have both a reader and a reader data
if ((myReader != null) &&
(myReaderData != null))
try
{
if (!myReaderData.IsPending)
{
// Submit a read.
myReader.Actions.Read(myReaderData);
if (toggleSoftTrigger && myReader.Info.SoftTrigger == false)
{
myReader.Info.SoftTrigger = true;
}
}
}
catch (Symbol.Exceptions.OperationFailureException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidRequestException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidIndexerException ex)
{
MessageBox.Show(ex.Message);
};
}
/// <summary>
/// Stop all reads on the reader.
/// </summary>
public void StopRead()
{
//If we have a reader
if (myReader != null)
{
try
{
// Flush (Cancel all pending reads).
if (myReader.Info.SoftTrigger == true)
{
myReader.Info.SoftTrigger = false;
}
myReader.Actions.Flush();
}
catch (Symbol.Exceptions.OperationFailureException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidRequestException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidIndexerException ex)
{
MessageBox.Show(ex.Message);
};
}
}
/// <summary>
/// Stop reading and disable/close the reader.
/// </summary>
public void TermReader()
{
// If we have a reader
if (myReader != null)
{
try
{
// stop all the notifications.
StopRead();
//Detach all the notification handler if the user has not done it already.
DetachReadNotify();
DetachStatusNotify();
// Disable the reader.
myReader.Actions.Disable();
// Free it up.
myReader.Dispose();
// Make the reference null.
myReader = null;
}
catch (Symbol.Exceptions.OperationFailureException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidRequestException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidIndexerException ex)
{
MessageBox.Show(ex.Message);
};
}
// After disposing the reader, dispose the reader data.
if (myReaderData != null)
{
try
{
// Free it up.
myReaderData.Dispose();
// Make the reference null.
myReaderData = null;
}
catch (Symbol.Exceptions.OperationFailureException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidRequestException ex)
{
MessageBox.Show(ex.Message);
}
catch (Symbol.Exceptions.InvalidIndexerException ex)
{
MessageBox.Show(ex.Message);
};
}
}
#endregion Methods
}
}
And this is the code for the actual form:
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace MK4000
{
public partial class Form1 : Form
{
private bool isReaderInitiated;
private BarCode myScanner;
private EventHandler myStatusNotifyHandler = null;
private EventHandler myReadNotifyHandler = null;
private String MacAddress = "00-00-00-00-00-00";
private String strIPAddress = "000.000.000.000";
private String version = "0.0.0.1";
public static int TaskbarHeight = Screen.PrimaryScreen.Bounds.Height - Screen.PrimaryScreen.WorkingArea.Height;
private int counter = 0;
private int itemLimit = 10;
public String ErrorMessage
{
get
{
return "Error";
}
}
public Form1()
{
InitializeComponent();
this.Width = Screen.PrimaryScreen.Bounds.Width;
this.Height = Screen.PrimaryScreen.Bounds.Height - TaskbarHeight;
this.FormBorderStyle = FormBorderStyle.None;
this.ControlBox = false;
this.MinimizeBox = false;
this.EmpID.Visible = false;
this.EmpName.Visible = false;
this.messageLabel.Visible = false;
this.lblCounter.Text = counter.ToString();
this.lblCounter.Visible = false;
this.statusBar1.Text = "Initializing.. Reticulating Splines " + MacAddress + " | " + strIPAddress + " | " + version;
this.listView1.View = View.Details;
this.listView1.Columns.Add("EmployeeID", 150, HorizontalAlignment.Left);
this.listView1.Columns.Add("EmployeeName", 330, HorizontalAlignment.Left);
this.listView1.Columns.Add("Time", 250, HorizontalAlignment.Left);
this.Closing += new CancelEventHandler(Form1_OnClosing);
this.myScanner = new BarCode();
this.isReaderInitiated = this.myScanner.InitReader();
if (!(this.isReaderInitiated))// If the reader has not been initialized
{
// Display a message & exit the application.
MessageBox.Show(ErrorMessage);
Application.Exit();
}
else // If the reader has been initialized
{
// Attach a status natification handler.
myScanner.AttachStatusNotify(myScanner_StatusNotify);
// Start a read operation & attach a handler.
myScanner.StartRead(true);
myScanner.AttachReadNotify(myScanner_ReadNotify);
}
}
private void myScanner_ReadNotify(object Sender, EventArgs e)
{
// Get ReaderData
Symbol.Barcode.ReaderData TheReaderData = this.myScanner.Reader.GetNextReaderData();
processData(TheReaderData.ToString());
this.myScanner.StopRead();
System.Threading.Thread.Sleep(1000);
this.myScanner.StartRead(true);
}
private void processData(string readerData)
{
string EmployeeName = "";
string EmployeeID = readerData;
hideMessage();
//This will query the employee database and proceed if employee exists, right now i just give it a random name
EmployeeName = "John Doe";
if (EmployeeName != "")
{
addToList(EmployeeID, EmployeeName);
counter += 1;
this.lblCounter.Text = counter.ToString();
this.EmpID.Visible = true
this.EmpName.Visible = true
this.lblCounter.Visible = true;
showMessage("Thank You!", System.Drawing.Color.LimeGreen);
}
}
private void showMessage(string messageText, System.Drawing.Color messageColor)
{
this.messageLabel.Text = messageText;
this.messageLabel.BackColor = messageColor;
this.messageLabel.Visible = true;
}
private void hideMessage()
{
this.messageLabel.Text = "";
this.messageLabel.BackColor = System.Drawing.Color.Black;
this.messageLabel.Visible = false;
}
private void addToList(string EmployeeID, string EmployeeName)
{
if (this.listView1.Items.Count >= itemLimit)
{
this.listView1.Items.RemoveAt(0);
}
ListViewItem item = new ListViewItem(EmployeeID);
//item.Text = EmployeeID;
item.SubItems.Add(EmployeeName);
item.SubItems.Add(DateTime.Now.ToString());
this.listView1.Items.Add(item);
this.listView1.Refresh();
}
private void myScanner_StatusNotify(object Sender, EventArgs e)
{
// Get ReaderData
Symbol.Barcode.BarcodeStatus TheStatusData = this.myScanner.Reader.GetNextStatus();
switch (TheStatusData.State)
{
case Symbol.Barcode.States.IDLE:
this.statusBar1.Text = "Idle - Scan ID Barcode " + MacAddress + " | " + strIPAddress + " | " + version;
break;
case Symbol.Barcode.States.READY:
this.statusBar1.Text = "Ready - Scan ID Barcode " + MacAddress + " | " + strIPAddress + " | " + version;
break;
case Symbol.Barcode.States.WAITING:
//this.myScanner.StopRead();
//this.myScanner.StartRead(true);
this.statusBar1.Text = "Waiting- Scan ID Barcode " + MacAddress + " | " + strIPAddress + " | " + version;
break;
default:
this.statusBar1.Text = TheStatusData.Text + " " + MacAddress + " | " + strIPAddress + " | " + version;
break;
}
}
private void Form1_OnClosing(object Sender, EventArgs e)
{
if (isReaderInitiated)
{
myScanner.DetachReadNotify();
myScanner.DetachStatusNotify();
myScanner.TermReader();
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
this.Close();
}
private void pictureBox2_Click(object sender, EventArgs e)
{
this.myScanner.StopRead();
this.myScanner.StartRead(true);
}
}
}
This is still a work in progress, mind you, so there is some functionality missing, but I want to have the scanner workingfull before moving forward. Any help will be greatly appreciated, thank you.
Ok, I figured out that the scanner goes into a cycle of switching between Idle and Waiting status, this is why my StatusNotify event handler was making the scanner laser turn on and off repeatedly.
I solved it by saving the previous status, and only restarting the scanner when the previous status is not one of those two.
case Symbol.Barcode.States.WAITING:
if (lastScannerStatus != "WAITING" && lastScannerStatus != "INIT" && lastScannerStatus != "IDLE")
{
this.myScanner.StopRead();
this.myScanner.StartRead(true);
}
this.statusBar1.Text = "Waiting- Scan ID Barcode " + MacAddress + " | " + strIPAddress + " | " + version;
break;
i'm new here,
help me out here please,
i am working with web service and doing upload file.
here's my code for uploading file
private void Button_Click(object sender, RoutedEventArgs e)
{
testServiceClient = new TestServiceClient();
var uploadFile = "C:\\Computer1\\Sample.csv";
try
{
var dir = #"\\Computer2\UploadedFile\";
string myUploadPath = dir;
var myFileName = Path.GetFileName(uploadFile);
var client = new WebClient { Credentials = CredentialCache.DefaultNetworkCredentials };
client.UploadFile(myUploadPath + myFileName, "PUT", uploadFile);
client.Dispose();
MessageBox.Show("ok");
testServiceClient.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
i can upload file in the same network, but my question is this,
how can i upload file when the two computer is not in the same network?
i've tried changing the
var dir = #"\\Computer2\UploadedFile\";
to
var dir = #"https://Computer2/UploadedFile/";
but i'm getting an error 'unable to connect to remote server'
help me out here pls.
In windows:
private void uploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) return;
Upload(openFileDialog.FileName);
}
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("https://Computer2/UploadedFile/");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
var data = System.IO.File.ReadAllBytes(fileName);
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In server:
[HttpPost]
public async Task<object> UploadedFile()
{
var file = await Request.Content.ReadAsByteArrayAsync();
var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
var filePath = "/upload/files/";
try
{
File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);
}
catch (Exception ex)
{
// ignored
}
return null;
}
I think the problem is that you are not actually sending the file with your UploadFile() method, you are just sending the file path. you should be sending the file bytes.
This link is quite usefull: http://www.codeproject.com/Articles/22985/Upload-Any-File-Type-through-a-Web-Service
i try whithout success to delete a file in my local storage. Exactly, i took a photo and i want to delete it later with a button for exemple. But when i click on the button, the app bugs and i have : "access denied".
I sude a simple Delet.Async() after i get the file in a StorageFile.
private async void delete_click(object sender, RoutedEventArgs e)
{
StorageFile filed = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filed != null)
{
await filed.DeleteAsync();
}
}
Try the code below to see if it works for you.
private async void takephoto_click(object sender, RoutedEventArgs e)
{
var ui = new CameraCaptureUI();
ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);
var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
// store the file
var myFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("myImg.jpg");
await file.MoveAndReplaceAsync(myFile);
// display the file
var bitmap = new BitmapImage();
bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read));
Photo.Source = bitmap;
}
}
private async void delete_click(object sender, RoutedEventArgs e)
{
StorageFile filed = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filed != null)
{
await filed.DeleteAsync();
}
StorageFile filefound = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filefound != null)
{
// do something here
}
}
i am having same problem in deleting file from local storage. there are many files stored in the local storage with different names so how to delete other files. in the above case you have hard coded the file name to delete.
StorageFile filefound = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
instead of myImg.jpg user want to delte other file then how user will delete
/// <summary>
/// Delete the indicated application file
/// </summary>
/// <param name="strFilePathName">The file path name to delete</param>
/// <returns>True, if successful; else false</returns>
public async static Task<bool> DeleteAppFile(string strFilePathName)
{
try
{
StorageFile fDelete = null;
if (!strFilePathName.Equals(""))
{
fDelete = await ApplicationData.Current.LocalFolder.GetFileAsync(strFilePathName);
if (fDelete != null)
{
try
{
await fDelete.DeleteAsync();
}
catch (Exception ex)
{
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile {" + strFilePathName + "}", ex.Message);
return false;
}
return true;
}
}
else
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile", "File path name is empty.");
}
catch (Exception ex)
{
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile {" + strFilePathName + "}", ex.Message);
}
return false;
}