ado.net query removes file exention when adding string filename to the database - asp.net

I am using the code below for saving uploaded picture and makigna thumbnail but it saves a filename without the extension to the database, therefore, I get broken links. How can I stop a strongly typed dataset and dataadapter to stop removing the file extension? my nvarchar field has nvarchar(max) so problem is not string length.
I realized my problem was the maxsize in the dataset column, not sql statement parameter, so I fixed it. You may vote to close on this question.
hasTableAdapters.has_actorTableAdapter adp1 = new hasTableAdapters.has_actorTableAdapter();
if (Convert.ToInt16(adp1.UsernameExists(username.Text)) == 0)
{
adp1.Register(username.Text, password.Text,
ishairdresser.Checked, city.Text, address.Text);
string originalfilename = Server.MapPath(" ") + "\\pictures\\" + actorimage.PostedFile.FileName;
string originalrelative = "\\pictures\\" + actorimage.FileName;
actorimage.SaveAs(originalfilename);
string thumbfilename = Server.MapPath(" ") + "\\pictures\\t_" + actorimage.PostedFile.FileName;
string thumbrelative = "\\pictures\\t_" + actorimage.FileName;
Bitmap original = new Bitmap(originalfilename);
Bitmap thumb=(Bitmap)original.GetThumbnailImage(100, 100,
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),
IntPtr.Zero);
thumb=(Bitmap)original.Clone(
new Rectangle(new Point(original.Width/2,original.Height/2), new Size(100,100)),
System.Drawing.Imaging.PixelFormat.DontCare);
/*
bmpImage.Clone(cropArea,bmpImage.PixelFormat);
*/
thumb.Save(thumbfilename);
adp1.UpdatePicture(originalrelative, thumbrelative, username.Text);
LoginActor();
Response.Redirect("Default.aspx");
}
}

Looks like the problem is you are using HttpPostedFile.FileName property, which returns fully-qualified file name on the client. So, this code string originalfilename = Server.MapPath(" ") + "\\pictures\\" + actorimage.PostedFile.FileName; generates something like this:
c:\inetpub\pictures\c:\Users\Username\Pictures\image1.jpg
Use FileUpload.FileName property everywhere and you will probably get what you want.

Use this to get Image or file extension :
string Extension = System.IO.Path.GetExtension(FileUpload.FileName);

Related

SQLite connection string cannot contain a comma?

I'm getting an error from SQLite when the connection string contains a comma. I don't have full control over where the database will end up, so it's possible a user will place it into a directory containing arbitrary characters. In this case, it appears that the presence of a comma (,) in the path causes an error when connecting. Here is the connection string:
Data Source=C:/Users/Dan/AppData/LocalLow/Gravia Software, LLC/Gravia/exampleDatabase.db;
This results in the following exception when trying to connect:
ArgumentException: Invalid ConnectionString format for parameter "LLC/Gravia/exampleDatabase.db"
It appears that the presence of the comma in the connection string is the issue. I've tried escaping the command (\,), wrapping the whole thing in quotes, but it doesn't seem to matter. Any ideas?
Edit:
The actual code I was executing comes from this page: https://ornithoptergames.com/how-to-set-up-sqlite-for-unity/
var dbPath = "URI=file:" + Application.persistentDataPath + "/exampleDatabase.db";
using (var conn = new SqliteConnection(dbPath)) {
conn.Open(); // Error occurs here
// etc
}
I tried changing out URI=file: for Data Source=, as the result was the same.
Try this ?
"Data Source=" + "C:/Users/Dan/AppData/LocalLow/Gravia Software," + "LLC/Gravia/exampleDatabase.db";
I solved this way:
var currDir = Directory.GetCurrentDirectory();
Directory.SetCurrentDirectory(Path.GetDirectoryName(Application.streamingAssetsPath + "/DB/"));
SqliteConnection dbcon = null;
try
{
dbcon = new SqliteConnection(_Connection);
dbcon.Open();
}
catch (Exception e)
{
Debug.Log(e.Message);
return null;
}
finally
{
Directory.SetCurrentDirectory(currDir);
}
You can escape unsupported characters in ODBC connection variables using curly-brackets ({}).
So wrap your variable, like below
Data Source={C:/Users/Dan/AppData/LocalLow/Gravia Software, LLC/Gravia/exampleDatabase.db};
Source

Check if Image Exists on Remote Site ASP.NET VB

I'm trying to get my website to detect if an image exists on the server, display if it does, if it doesn't display another image (which is just called blank.png).
I have tried to use Server.MapPath with relative pathings but havent been able to get it to work. When using Server.MapPath and checking in the broswer after the page has loaded i uses the full path of the file (eg G:\domain\path\blank.png).
If i use The normal path (Dim sImagePath As String = "\Images\DriversNew\"'). The image will display, but the check for whether the image exists or not always returns false. I'm assuming its to do with the physical location of the file.
'Dim sImagePath As String = Server.MapPath("Images/DriversNew/")
Dim sImagePath As String = "\Images\DriversNew\"
Dim sHeadshot As String = sImagePath & dsDriver.Tables("Driver").Rows(0).Item("Name") & ".png"
If File.Exists(sHeadshot) Then
imgDriver.ImageUrl = sHeadshot
Else
imgDriver.ImageUrl = sImagePath & "Blank.png"
End If
Any advice? I know its something simple, but with the reading ive been doing it hasnt been able to get it working on the site.
Thanks, much appreciated!
Assuming that your database column Name contains only the short filename (i.e. no directory path information or folder names) then you can do this:
String nameFromDatabase = (String)dsDriver.Tables("Driver").Rows[0]["Name"] + ".png";
String appRootRelativeHttpResourcePath = "~/Images/DriversNew/" + nameFromDatabase;
String localFileSystemPath = Server.MapPath( appRootRelativeHttpResourcePath );
if( File.Exists( localFileSystemPath ) ) {
imgDriver.ImageUrl = appRootRelativeHttpResourcePath; // you can specify app-root-relative URLs ("~/...") here
}
else {
imgDriver.ImageUrl = "~/Images/DriversNew/Blank.png";
}

bulk insertion in MS SQL from a text file

I have a text file that contains around 21 lac entries and I want to insert all these entries into a table. Initially I have created one function in c# that read line by line and insert into table but it takes too much time. Please suggest an efficient way to insert these bulk data and that file is containing TAB(4 spaces) as delimiter.
And that text file also containing some duplicate entries and I don't want to insert those entries.
Load all of your data into a DataTable object and then use SqlBulkCopy to bulk insert them:
DataTable dtData = new DataTable("Data");
// load your data here
using (SqlConnection dbConn = new SqlConnection("db conn string"))
{
dbConn.Open();
using (SqlTransaction dbTrans = dbConn.BeginTransaction())
{
try
{
using (SqlBulkCopy dbBulkCopy = new SqlBulkCopy(dbConn, SqlBulkCopyOptions.Default, dbTrans))
{
dbBulkCopy.DestinationTableName = "intended SQL table name";
dbBulkCopy.WriteToServer(dtData );
}
dbTrans.Commit();
}
catch
{
dbTrans.Rollback();
throw;
}
}
dbConn.Close();
}
I've included the example to wrap this into a SqlTransaction so there will be a full rollback if there's a failure along the way. To get you started, here's a good CodeProject article on loading the delimited data into a DataSet object.
Sanitizing the data before loading
OK, here's how I think your data looks:
CC_FIPS FULL_NAME_ND
AN Xixerella
AN Vila
AN Sornas
AN Soldeu
AN Sispony
... (cut down for brevity)
In this instance you want to create your DataTable like this:
DataTable dtData = new DataTable("Data");
dtData.Columns.Add("CC_FIPS");
dtData.Columns.Add("FULL_NAME_ND");
Then you want to iterate each row (assuming your tab delimited data is separated row-by-row by carriage returns) and check whether this data already exists in the DataTable using the .Select method and if there is a match (i'm checking for BOTH values, it's up to you whether you want to do something else) then don't add it thereby preventing duplicates.
using (FileStream fs = new FileStream("path to your file", FileMode.Open, FileAccess.Read))
{
int rowIndex = 0;
using (StreamReader sr = new StreamReader(fs))
{
string line = string.Empty;
while (!sr.EndOfStream)
{
line = sr.ReadLine();
// use a row index to skip the header row as you don't want to insert CC_FIPS and FULL_NAME_ND
if (rowIndex > 0)
{
// split your data up into a 2-d array tab delimited
string[] parts = line.Split('\t');
// now check whether this data has already been added to the datatable
DataRow[] rows = dtData.Select("CC_FIPS = '" + parts[0] + "' and FULL_NAME_ND = '" + parts[1] + "'");
if (rows.Length == 0)
{
// if there're no rows, then the data doesn't exist so add it
DataRow nr = dtData.NewRow();
nr["CC_FIPS"] = parts[0];
nr["FULL_NAME_ND"] = parts[1];
dtData.Rows.Add(nr);
}
}
rowIndex++;
}
}
}
At the end of this you should have a sanitized DataTable that you can bulk insert. Please note that this code isn't tested, but it's a best guess as to how you should do it. There are many ways this can be done, and probably a lot better than this method (specifically LINQ) - but it's a starting point.

How to replace the file name(particular specific folder) using Asp.net?

i can replace the file name in particular folder , i wrote like this
FileInfo fsource = new FileInfo(Server.MapPath("~/PurchaseOrder/" + lblhideid.Text));
if (fsource.Exists)
{
string[] file = lblhideid.Text.Split('.');
string fName="Z-"+System.DateTime.Now.ToString("MM-dd-yyyy")+"-"+saveConsultantID+"."+file[1];
fsource.Name.Replace(lblhideid.Text, fName);
}
lblhideid.Text=image.jpeg , so i can replace the my own name like fName , how to replace the name pls give me any suggestion.
Thank u
Hemanth
I suspect you want that last line to be:
fsource.MoveTo(Server.MapPath("~/PuchaseOrder/" + fName));
You current code is only getting the filename as a string and manipulate that string. You want to manipulate the file itself.
EDIT:
Are you sure that ~/PurchaseOrder/ exists?
Try:
string originalPath = Server.MapPath("~/PurchaseOrder/" + lblhideid.Text);
FileInfo fsource = new FileInfo(originalPath);
if (fsource.Exists)
{
string newName = string.Format("Z-{0:MM-dd-yyyy}-{1}.{2}",
System.DateTime.Now,
saveConsultantID,
fsource.Extension);
string newPath = Path.Combine(fsource.DirectoryName, newName);
fsource.MoveTo(newPath);
}
Try this, what if they put a filename like file.tar.gz ?
string extension = Path.GetExtension("~/PurchaseOrder/" + lblhideid.Text);
string newName = "MYFILE." + extension
File.Move(
"~/PurchaseOrder/" + lblhideid.Text,
"~/PurchaseOrder/" + newName );

java.io.FileNotFoundException?

i have written the code of jsp,servlet for uploading the Doc file in database.
here is my code,but i am getting the error like this==java.io.FileNotFoundException: insert into resume(resume) values(?) (The filename, directory name, or volume label syntax is incorrect) .please help me how to remove this error???
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:jtds:sqlserver://W2K8SERVER:1433/career","sa","Alpha#123" );
pst = con.prepareStatement("select * from data1 where email=? and password=?");
pst = con.prepareStatement
("insert into resume(resume) "+ "values(?)");
File re = new File("" + pst);
fis = new FileInputStream(re);
pst.setBinaryStream(3, (InputStream)fis, (int)(re.length()));
pst.setString (1,upload);
//rs = pst.executeQuery();
while (rs.next())
cnt ++;
int s = pst.executeUpdate();
if(s>0) {
System.out.println("Uploaded successfully !");
}
else {
System.out.println("unsucessfull to upload image.");
}
rs.close();
pst.close();
con.close();
}
It is because insert into resume(resume) values(?) is probably not the name of a file on your disk.
pst = con.prepareStatement ("insert into resume(resume) "+ "values(?)");
File re = new File("" + pst);
You are creating a File from ""+ pst, which is the result of toString() being called on a PreparedStatement. Did you put in the "" to get rid of the informative compilation error?
You probably have the real filename in some other variable.
File re = new File(theRealFileNameVariable);
File re = new File("" + pst);
please make sure the "pst" value is a valid file path, apparently the value "insert into resume(resume) values(?)" is not a valid file path
The java.io.File class has four (4) constructors
File(File parent, String child)
File(String pathname)
File(String parent, String child)
File(URI uri)
In your case you are trying to pass to the constructor an object or type java.sql.PreparedStatement that you trying to cast into a String. I don't see how (even if you arrived to convert pst into a string) pst will reference a path to a file. Please go back and read a little bit about java.io.
.

Resources