Browse a file from my pc using web application in asp.net - asp.net

I have a web application which I uploaded using IIS. I want the users using the application would be able to select a file located on their (the user) computer and read its contents.
The code is:
TextReader trs = new StreamReader(faFile.Value);
DataAccessLayer.clearFA();
string line = trs.ReadLine();
// Read all unneeded data
while (line != "** Start Data **")
{
line = trs.ReadLine();
}
line = trs.ReadLine();
while (line != null)
{
string[] words = line.Split('*');
// There is no message
if (words[4] == "")
{
DataAccessLayer.insertIntoFA(Int32.Parse(words[1]), words[3].Replace("'", ""));
}
else
{
DataAccessLayer.insertIntoFA(Int32.Parse(words[1]), words[4].Replace("'", ""));
}
line = trs.ReadLine();
}
}
When I run it from my pc it works. But when I try to run it from the IIS it gives me the following error:
Could not find a part of the path 'C:\Documents and Settings\myUser\Desktop\file.txt'.
I understand that the application cant read the file from the user pc. Any idea how can I make it work?
Thanks!
Greg

This is done for security reasons - a browser does not have access to the filesystem of the user.
There is no way to work around this, as all other technologies running inside a browser are sandboxed and limited (again, for security reasons).
The closest you can get is to use an <input type="file"> that lets the user to select a file for upload.

The upload file's path in IE 8 is a full path. You can obtain filename from the full name. Combine server path and filename before saving file

Related

How to open a database in Sql Browser which is encrypted by sqlCipher?

I apologize for the duplicate question if it is. I almost searched everywhere but couldn't find any solution.
see this and this picture. To mention that I used the latest version of the SQLite browser on Windows.
Any help would be appreciated.
Ok first you need to create the database as non encrypted
then open Android Studio and run the emulator with the code I will give you below
Now minimize every thing Emulator and Android Studio BUT BEFORE YOU DO THAT LOOK IN your logcat you will see the path to your DB Highlight and COPY that
Now find adb.exe folder it will be on C drive under where ever you installed AS. OR just do a search on C drive OK when you get to where that folder is HOLD DOWN the SHIFT KEY and RIGHT CLICK any where in the white SELECT "Open command Window here"
now in the command window type this
adb pull (do a right click and paste that path you coppied C:\name of folder on your C Drive Best to create one and name it AASafe
bingo your data base is now on your PC in the folder AASafe HERE IS RHE CODE it is a method that needs to be called under onCreate
// Is External Storage Avaiable if so use it and find the path for DBHelper
public void onAvail() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED) && (!state.equals(Environment.MEDIA_MOUNTED_READ_ONLY))) {
File removable = ContextCompat.getExternalFilesDirs(this, null)[1];
THE_PATH = String.valueOf(removable) + "/Documents/";
System.out.println("SD Card Path ==> " + THE_PATH);
} else {// if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
THE_PATH = "";
System.out.println("Internal Path ==> "+ THE_PATH);
}
}

Understanding the JIT; slow website

First off, this question has been covered a few times (I've done my research), and, for example, on the right side of the SO webpage is a list of related items... I have been through them all (or as many as I could find).
When I publish my pre-compiled .NET web application, it is very slow to load the first time.
I've read up on this, it's the JIT which I understand (sort of).
The problem is, after the home page loads (up to 20 seconds), many other pages load very fast.
However, it would appear that the only reason they load is because the resources have been loaded (or that they share the same compiled dlls). However, some pages still take a long time.
This indicates that maybe the JIT needs to compile different pages in different ways? If so, and using a contact form as an example (where the Thank You page needs to be compiled by the JIT and first time is slow), the user may hit the send button multiple times whilst waiting for the page to be shown.
After I load all these pages which use different models or different shared HTML content, the site loads quickly as expected. I assume this issue is a common problem?
Please note, I'm using .NET 4.0 but, there is no database, XML files etc. The only IO is if an email doesn't send and it writes the error to a log.
So, assuming my understanding is correct, what is the approach to not have to manually go through the website and load every page?
If the above is a little too broad, then can this be resolved in the settings/configuration in Visual Studio (2012) or the web.config file (excluding adding compilation debug=false)?
In this case, there are 2 problems
As per rene's comments, review this http://msdn.microsoft.com/en-us/library/ms972959.aspx... The helpful part was to add the following code to the global.asax file
const string sourceName = ".NET Runtime";
const string serverName = ".";
const string logName = "Application";
const string uriFormat = "\r\n\r\nURI: {0}\r\n\r\n";
const string exceptionFormat = "{0}: \"{1}\"\r\n{2}\r\n\r\n";
void Application_Error(Object sender, EventArgs ea) {
StringBuilder message = new StringBuilder();
if (Request != null) {
message.AppendFormat(uriFormat, Request.Path);
}
if (Server != null) {
Exception e;
for (e = Server.GetLastError(); e != null; e = e.InnerException) {
message.AppendFormat(exceptionFormat,
e.GetType().Name,
e.Message,
e.StackTrace);
}
}
if (!EventLog.SourceExists(sourceName)) {
EventLog.CreateEventSource(sourceName, logName);
}
EventLog Log = new EventLog(logName, serverName, sourceName);
Log.WriteEntry(message.ToString(), EventLogEntryType.Error);
//Server.ClearError(); // uncomment this to cancel the error
}
The server was maxing out during sending of the email! My code was fine, but, viewing Task Scheduler showed it was hitting 100% memory...
The solution was to monitor the errors shown by point 1 and fix it. Then, find out why the server was being throttled when sending an email!

Download a file with Tidesdk

How can I download a file and store it locally? I've searched the doc and google and couldn't find an example of it.
I tried this:
this.copyRemote = function(path,path2){
reader = Ti.Network.createHTTPClient();
writer = Ti.Filesystem.getFile(path2);
reader.open('GET',path);
reader.receive(writer);
}
But Tidesdk crashes while trying to download the file, the last messages on console are:
[12:42:39:647] [Ti.Network.HTTPClient] [Debug] Changing readyState from 0 to 1 for url:https://buttonpublish.com/api/images/7/image257189x142.jpg
[12:42:39:671] [Ti.Proxy] [Debug] Looking up proxy information for: https://buttonpublish.com/api/images/7/image257189x142.jpg
[12:
Seems like there has been success on the TideSDK Google Group using the code below:
var httpClient = Ti.Network.createHTTPClient();
httpClient.open('GET', path);
httpClient.receive(function(data) {
var file = Ti.Filesystem.getFile(path2);
var fileStream = file.open(Ti.Filesystem.MODE_APPEND);
fileStream.write(data);
fileStream.close();
});
Hope that helps, at least to point in the right direction.
I found that this works for my needs, which are just to get the file onto the machine:
function downloadFile( url ){
Ti.Platform.openApplication( url );
}
This opens the URL using the machine's default browser. One downside to this approach is that the user is normally prompted to confirm the download. I use the downloadFile function in case I want to change how this works in the future.

How to store translations in a phonegap application and save the user preferences?

I'm developing a Phonegap application using jQuery Mobile. It's a very basic application, its purpose is to show information about a big organization in Spanish and English. On the first page the application shows 2 options, Spanish and English. If the user selects Spanish, the information displayed must be Spanish and vice versa.
Using SQLite DB will probably give some problems on Windows Phones since it is not yet supported (see Phonegap Storage).
There is the File Storage option too. And raw JSON files, as well.
The way I do it is to create a language specific json file to hold all my strings. In this case english.json and spanish.json. Structure the json like:
{
help: "Help",
ok: "Okay"
}
On the first page of your app when the user clicks the Spanish button for instance it should set a value in localStorage.
localStorage.setItem("lang", "spanish");
Then in the second page once you get the "deviceready" event you should load the correct json file using XHR.
var request = new XMLHttpRequest();
request.open("GET", localStorage.getItem("lang") + ".json", true);
request.onreadystatechange = function(){//Call a function when the state changes.
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
langStrings = JSON.parse(request.responseText);
}
}
}
request.send();
Now whenever you want to use a translated string you get it from langStrings.
langStrings.ok;
Make sense?
For persistance I successfully used Html5 Local Storage.
It works on Android, iOS and Windows Phone 7(I tried it on these platforms).
I use it like this.
For i18n you can use any javascript i18n library. I created own simple solution.

Lucene.NET --> access denied to segments

I have a problem with Lucene.NET. During an index, I receive the error 'Access to the path segments is denied'. Or sometimes 'Access to the path deletable is denied'. I eventually gave 'Everyone' full security rights to the index directory, but the problem still existed.
I then found out that during the index run, lucene renames the segments file to 'segments.new', and then this error happens. I guess some process still tries to read from the old segments file after it has been renamed? I have no clue as to why this happens, or how to fix this. Strangely enough, my co-developers can run the index on their computer without a problem.
The error happens at happens in Lucene.Net.Index.IndexModifier.AddDocument(Document).
Any ideas would be much appreciated.
I suspect that your IndexModifier is in contention with a Searcher.
Here's how I use Lucene.Net in my bug tracking app, BugTracker.NET, which seems to be working ok.
I create the index at app startup.
I create a searcher and keep it around so that the index isn't reloaded with each search. All threads share the same searcher. When the searcher searches, it grabs a lock, searches, then releases the lock, so that another thread can search. Forces the searches into single file is doable in my app because Lucene.NET is quick and a bug tracking system isn't THAT busy.
Meanwhile, I have an IndexWriter that updates the index when there is a data change. It is just changing a little bit so it does its task quick too. When it needs to run, it grabs the same lock, destroys the searcher, updates the index, and the re-recreates the searcher. The new searcher stays around until the next update of the index. The searcher always is working with an up-to-date index.
You can get the BugTracker.NET source and look at the files my_lucene.cs and search_text.aspx. It's all in those two files, and there isn't that much code.
This problem is caused by an online virus scanner locking the segments(.new) file. I have had to write a custom Lucene Directory implementation to work around this.
I think i found a solution.. well at least it worked for me..
I was testing for the "segments.new" problem and below you have the code .. so as you can see in a loop i created thousands of lucene documents (6000).. At about 1360 document an error appears saying that he couldn´t rename blablabla.. The code is written in c#.. basically you just have to insert a try catch (inside the loop) for the error and when the error pops up you just try again subtracting the int loop nunmber(y) by one (y = y - 1) ..
//-----------------Problem -------------------------------------
for (int y = 0; y < 6000; y++)
{
Document doc = new Document();
doc.Add(new Field("URL", "C:/Users/blabla/(convert-csharp)/IMssg", Field.Store.YES, Field.Index.TOKENIZED));
writer.AddDocument(doc);
}
//--------------------Solution----------------------------------------
IndexWriter writer = new IndexWriter("C:/Users/blabla/(convert-csharp)/IMssg", new StandardAnalyzer(), false);
for (int y = 0; y < 6000; y++)
{
try
{
Document doc = new Document();
doc.Add(new Field("URL", "C:/Users/blabla/(convert-csharp)/IMssg", Field.Store.YES, Field.Index.TOKENIZED));
writer.AddDocument(doc);
}
catch (Exception t)
{
y = (y < 0) ? 0 : y - 1;
string gfff = t.Message.ToString();
}
}
writer.Close();
Im not a english guy so im sory if there´s any error in some word...
by now
regards immanouel
I second Imma's solution. I had this problem also. The fix for me was to put the try/catch around IndexWriter.AddDocument(doc):
int attemptNo = 0;
while (attemptNo < 2)
{
try
{
writer.AddDocument(doc);
break;
}
catch (Exception e)
{
String ErrMsg = String.Format("{0} ({1}): While adding Document {2}/{3}, caught {4}", DateTime.Now, attemptNo, doc.GetField("kanji").StringValue(), doc.GetField("kana").StringValue(), e.Message);
attemptNo++;
System.Threading.Thread.Sleep(30);
Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate()
{
ViewModel.Log.Add(ErrMsg);
});
}
reference: http://issues.apache.org/jira/browse/LUCENE-665:
"The gist of the issue is: on Windows, you sometimes see intermittant
"Access Denied" errors in renaming segments.new to segments or
deletable.new to deletable, etc. Lucene typically writes files first
to X.new and then renames then to X."
I read about this. However, I do not have any virus scanners running. I also disabled Vista Search Index for the index directory, killed the search index process from the task manager, to make sure no other process is locking the file. Unfortunately, to no avail. Moreover, the problem seems more to be that the 'segments' file it tries to access, is gone (since lucene renamed it to segments.new). I'm not sure if they are the same problems...

Resources