Load file without a button click javascript or jquery - c#

In the next javascript code i have a function to open a file(xml) and then it will search for all the occurences that are between a specific tag(<file>). After using a Regex expression to get the filenames, i need that the dialog can be open, automatically, the same number of times of the files discovered in the xml file. The objective is to force the user to search in their local directory for the files that are in the xml file. After this i will send the strings to the server side.
function fileSelected(evt) {
var files = evt.target.files;
var reader = new FileReader();
var bol;
if (document.getElementById("fileToLoad").value == "") {
alert("Please select a file before submitting.");
bol = 0;
}
else {
ext = document.getElementById("fileToLoad").value;
fpath = ext;
ext = ext.substring(ext.length - 3, ext.length);
ext = ext.toLowerCase();
if (ext == 'xml')
bol = 1;
else if (ext == 'rdf')
bol = 1;
else {
alert("You selected a ." + ext + " file; this is not allowed.");
bol = 0;
}
}
if (bol == 1) {
reader.onload = function (event) {
editor.setValue(event.target.result);
var teste = editor.getValue();
getFileName(teste);
var debug = event.target.files;
document.getElementById("Procura").style.visibility = "visible";
//document.getElementById('<%=hf.ClientID%>').value = editor.getValue();
}
reader.readAsText(files[0], "UTF-8");
}
return false;
}
function getFileName(str) {
var matches = str.match(/<file>(.*)<\/file>/g);
var len = matches.length, i, result;
for (i = 0; i < len; i++) {
matches[i] = matches[i].replace(/<[\/]{0,1}(file|FILE)[^><]*>/g, "");
//need to open dialog for user to search for the same file in matches[i]
//after get file, will save on a string in order to send to server
}
}
I´ve tried many things but this is my first steps in this world(js/jquery/html).

Related

ERR_HTTP2_PROTOCOL_ERROR in a button onClick event when trying to export a DataTable to CSV

I'm getting an error when clicking a button on a page to export data from a DataTable to a CSV file:
ERR_HTTP2_PROTOCOL_ERROR
This error only occurs on the published build. Everything works fine on my local machine in the development environment. It's published to a local machine on the network and then communicates directly with that, rather than over the internet (everything is local and on site, I should say). My assumption is threading being the issue, but I'm not sure how else to display dialog to the user and allow them to specify a path AND filename without SaveFileDialog.
protected void btnExportToCSV_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
try
{
int count = 1;
int totalColumns = dataTable.Columns.Count;
List<string> columnNames = new List<string>();
// add the column names/headers
foreach (DataColumn dr in dataTable.Columns)
{
columnNames.Add(dr.ColumnName);
sb.Append(dr.ColumnName);
if (count != totalColumns)
{
sb.Append(",");
}
count++;
}
sb.AppendLine();
string value = String.Empty;
// add the values for each row in corresponding column
foreach (DataRow dr in dataTable.Rows)
{
for (int x = 0; x < totalColumns; x++)
{
value = dr[x].ToString();
// filter out commas, line breaks, new lines and tabs
if (value.Contains(",") || value.Contains("\"") || value.Contains("<br />") || value.Contains("\t"))
{
value = '"' + value.Replace("\"", "\"\"") + '"';
}
// check that if current column is serial number,
// concat a character string to force it to display as a string
if (columnNames[x] == "SerialNum")
{
value = value.Insert(0, "#");
}
sb.Append(value);
// if not at the final column of a row, go to new column and NOT a new row
if (x != (totalColumns - 1))
{
sb.Append(",");
}
}
sb.AppendLine();
}
}
catch (Exception ex)
{
lblVerify.Text = "There was an issue building the CSV file data; please report the following message to xxxxxxx: " + ex.Message;
lblVerify.ForeColor = System.Drawing.Color.Red;
}
Stream myStream;
// build save dialog window with options
SaveFileDialog saveFileDialog1 = new SaveFileDialog
{
DefaultExt = "txt",
Title = "Save Reports",
Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
RestoreDirectory = true,
};
try
{
// separate thread to open and run save file browser
Thread thread = new Thread(() =>
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// make sure the filename field is not blank
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
myStream.Close();
// write the csv file to disk using the given file name
File.WriteAllText(saveFileDialog1.FileName.ToString(), sb.ToString());
}
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
catch(Exception ee)
{
lblVerify.Text = "There was an issue exporting the data to a CSV file; please report the following message to xxxxxxx: " + ee.Message;
lblVerify.ForeColor = System.Drawing.Color.Red;
}
}

Saving Multiple Files At Once

I've been trying to figure out how to use the SaveFileDialog function in c# to save more than one file at a time.
The basic idea is, after the user has set parameters for a .cfg file, the user types out a set of serial numbers for which to save the configuration as. Then a SaveFileDialog is called allowing the user to save the one .cfg file under the names of the serial numbers the user listed.
Is this possible to do? Do you need to put the function into a loop, or is there another way to achieve this goal?
the .cfg file is set up like:
timezone=1
auto_DST=1
location=0
alarm_time=21
alarm_seconds_P=0
etc.
Here is what I have so far for saving that file:
List<Parameter> _paramList = new List<Parameter>();
List<Information> _infoList = new List<Information>();
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.DefaultExt = ".CFG";
saveFileDialog1.FileName = ( "config_" + txtParamValue.Text);
saveFileDialog1.Filter = "Configuration files (*.CFG)|*.CFG|All files (*.*)|*.*";
if ( saveFileDialog1.ShowDialog( ) == DialogResult.OK )
{
using ( StreamWriter objWriter = new StreamWriter( saveFileDialog1.FileName ) )
{
foreach (Parameter p in _paramList)
{
String name = p.ParameterName.Trim();
String val = p.ParameterValue.Trim();
foreach (Information i in _infoList)
{
if (p.ParameterName.Trim() == i.SimpleName)
{
name = i.InfoName;
if (i.InputChoice == "1")
{
if (p.ParameterValue == "On")
val = "1";
else
val = "0";
}
break;
}
else if (p.ParameterName.Trim() == i.InfoName)
{
if (p.ParameterValue == "On")
val = "1";
else
val = "0";
break;
}
}
if (name == "location" && val != location_update)
{
name = "location_update";
}
objWriter.WriteLine(name + "=" + val);
}
objWriter.Close();
}
}

I want to Optimize upload time of Excel file records saving to Database in asp.net mvc

I want to upload the excel file of record 2500. This process takes time more than 5 minutes approximate. I want to optimize it to less than a minute maximum.
Find the best way of optimization of that code. I am using Dbgeography for location storing. File is uploaded and save the data properly. Everything is working find but I need optimization.
public ActionResult Upload(HttpPostedFileBase FileUpload)
{
if (FileUpload.ContentLength > 0)
{
string fileName = Path.GetFileName(FileUpload.FileName);
string ext = fileName.Substring(fileName.LastIndexOf('.'));
Random r = new Random();
int ran = r.Next(1, 13);
string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), DateTime.Now.Ticks + "_" + ran + ext);
try
{
FileUpload.SaveAs(path);
ProcessCSV(path);
ViewData["Feedback"] = "Upload Complete";
}
catch (Exception ex)
{
ViewData["Feedback"] = ex.Message;
}
}
return View("Upload", ViewData["Feedback"]);
}
Here is other method from where the file is uploaded and save it to the database..
private void ProcessCSV(string filename)
{
Regex r = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
StreamReader sr = new StreamReader(filename);
string line = null;
string[] strArray;
int iteration = 0;
while ((line = sr.ReadLine()) != null)
{
if (iteration == 0)
{
iteration++;
continue; //Because Its Heading
}
strArray = r.Split(line);
StoreLocation store = new StoreLocation();
store.Name = strArray[0];
store.StoreName = strArray[1];
store.Street = strArray[2];
store.Street2 = strArray[3];
store.St_City = strArray[4];
store.St_St = strArray[5];
store.St_Zip = strArray[6];
store.St_Phone = strArray[7];
store.Office_Phone = strArray[8];
store.Fax = strArray[9];
store.Ownership = strArray[10];
store.website = strArray[11];
store.Retailer = check(strArray[12]);
store.WarehouseDistributor = check(strArray[13]);
store.OnlineRetailer = check(strArray[14]);
string temp_Add = store.Street + "," + store.St_City;
try
{
var point = new GoogleLocationService().GetLatLongFromAddress(temp_Add);
string points = string.Format("POINT({0} {1})", point.Latitude, point.Longitude);
store.Location = DbGeography.FromText(points);//lat_long
}
catch (Exception e)
{
continue;
}
db.StoreLocations.Add(store);
db.SaveChanges();
}
The obvious place to start would be your external call to the Geo Location service, which it looks like you are doing for each iteration of the loop. I don't know that service, but is there any way you can build up a list of addresses in memory, and then hit it once with multiple addresses, then go back and amend all the records you need to update?
The call to db.SaveChanges() which updates the database, this is happening for every line.
while (...)
{
...
db.StoreLocations.Add(store);
db.SaveChanges(); // Many database updates
}
Instead, just call it once at the end:
while (...)
{
...
db.StoreLocations.Add(store);
}
db.SaveChanges(); // One combined database update
This should speed up your code nicely.

how to post a file with a paramater in AngularJS and webApi

I want to post a file with a parameter to a web Api function,I am able to save the file to a Directory on the server when I remove the parameter but with the parameter the post the method is not call
this is the angularJs
// this will get the upload from the html
$scope.getFileDetails = function (e)
{
$scope.files = [];
$scope.$apply(function ()
{
// STORE THE FILE OBJECT IN AN ARRAY.
for (var i = 0; i < e.files.length; i++)
{
$scope.files.push(e.files[i])
}
});
};
//the file array
$scope.uploadFiles = function()
{
//FILL FormData WITH FILE DETAILS.
var data = new FormData();
for (var i in $scope.files)
{
data.append("uploadedFile", $scope.files[i]);
}
// ADD LISTENERS.
var objXhr = new XMLHttpRequest();
objXhr.addEventListener("progress", updateProgress, false);
objXhr.addEventListener("load", transferComplete, false);
var empID="PC145"
// SEND FILE DETAILS TO THE API.
objXhr.open("POST", "/api/Logo/"+empID); // this is not working
objXhr.send(data);
}
this is the web Api method
public string UploadFiles(String empid)
{
int iUploadedCnt = 0;
String na = empid;
// DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
string sPath = "";
sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Logo/");
System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
// CHECK THE FILE COUNT.
for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
{
System.Web.HttpPostedFile hpf = hfc[iCnt];
String fileName = sPath + Path.GetFileName(hpf.FileName);
String fileNameDB = Path.GetFileName(hpf.FileName);
this.FileName = fileNameDB;
if (hpf.ContentLength > 0)
{
// CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE)
if (!File.Exists(fileName))
{
// SAVE THE FILES IN THE FOLDER.
hpf.SaveAs(fileName);
insertLogo(fileNameDB);
iUploadedCnt = iUploadedCnt + 1;
}
}
}
// RETURN A MESSAGE (OPTIONAL).
if (iUploadedCnt > 0)
{
return iUploadedCnt + " Files Uploaded Successfully";
}
else
{
return "Upload Failed";
}
}
with the parameter the function is not call, how can post a file with a parameter.

How do I use lucene.net for searching file content?

I am currently using lucene.net to search the content of files for keyword search. I am able to get the results correctly but I have a scenario where I need to display the keywords found in a particular file.
There are two different files containing "karthik" and "steven", and if I search for "karthik and steven" I am able to get both the files displayed. If I search only for "karthik" and "steven" separately, only the respective files are getting displayed.
When I search for "karthik and steven" simultaneously I get both the files in the result as I am displaying the filename alone, and now I need to display the particular keyword found in that particular file as a record in the listview.
Public bool StartSearch()
{
bool bResult = false;
Searcher objSearcher = new IndexSearcher(mstrIndexLocation);
Analyzer objAnalyzer = new StandardAnalyzer();
try
{
//Perform Search
DateTime dteStart = DateTime.Now;
Query objQuery = QueryParser.Parse(mstrSearchFor, "contents", objAnalyzer);
Hits objHits = objSearcher.Search(objQuery, objFilter);
DateTime dteEnd = DateTime.Now;
mlngTotalTime = (Date.GetTime(dteEnd) - Date.GetTime(dteStart));
mlngNumHitsFound = objHits.Length();
//GeneratePreviewText(objQuery, mstrSearchFor,objHits);
//Generate results - convert to XML
mstrResultsXML = "";
if (mlngNumHitsFound > 0)
{
mstrResultsXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Results>";
//Loop through results
for (int i = 0; i < objHits.Length(); i++)
{
try
{
//Get the next result
Document objDocument = objHits.Doc(i);
//Extract the data
string strPath = objDocument.Get("path");
string strFileName = objDocument.Get("name");
if (strPath == null) { strPath = ""; }
string strLastWrite = objDocument.Get("last_write_time");
if (strLastWrite == null)
strLastWrite = "unavailable";
else
{
strLastWrite = DateField.StringToDate(strLastWrite).ToShortDateString();
}
double dblScore = objHits.Score(i) * 100;
string strScore = String.Format("{0:00.00}", dblScore);
//Add results as an XML row
mstrResultsXML += "<Row>";
//mstrResultsXML += "<Sequence>" + (i + 1).ToString() + "</Sequence>";
mstrResultsXML += "<Path>" + strPath + "</Path>";
mstrResultsXML += "<FileName>" + strFileName + "</FileName>";
//mstrResultsXML += "<Score>" + strScore + "%" + "</Score>";
mstrResultsXML += "</Row>";
}
catch
{
break;
}
}
//Finish off XML
mstrResultsXML += "</Results>";
//Build Dataview (to bind to datagrid
DataSet objDS = new DataSet();
StringReader objSR = new StringReader(mstrResultsXML);
objDS.ReadXml(objSR);
objSR = null;
mobjResultsDataView = new DataView();
mobjResultsDataView = objDS.Tables[0].DefaultView;
}
//Finish up
objSearcher.Close();
bResult = true;
}
catch (Exception e)
{
mstrError = "Exception: " + e.Message;
}
finally
{
objSearcher = null;
objAnalyzer = null;
}
return bResult;
}
Above is the code i am using for search and the xml i am binding to the listview, now i need to tag the particular keywords found in the respective document and display it in the listview as recordsss,simlar to the below listview
No FileName KeyWord(s)Found
1 Test.Doc karthik
2 Test2.Doc steven
i hope u guys undesrtood the question,
This depends on how your documents were indexed. You'll need to extract the original content, pass it through the analyzer to get the indexed tokens, and check which matches the generated query.
Just go with the Highlighter.Net package, part of contrib, which does this and more.

Categories