i'm working on Linq To Sql,WPF and i have a database now i need to save some picture in the database but i don't know which is the correct datatype to save the pictures Database(this database would be connect from 10 users in the same time).
Can you point me in the right way to overcome this step?
If i didn't wrong it is not a good idea to save pictures in the database but if you can advice me a better method i will apply it.
Thanks so much for your time.
Nice Regards
You can use a 'varbinary(MAX)' or 'image' column type. Linq2Sql will auto-generate a class that uses a Binary object to wrap your image. The Binary object is just a wrapper around a byte[].
myObject.Image = new Binary(imageByteArray);
Store your picture as a blob, the variable defined in your class containing the image could be a byte[] stream. Alternatively you just store a reference to the picture in the database and store the image on a file server.
Typically you will use a varbinary(max) -or less than max- on the database side and you will use a byte[] type in your class.
There's a lot of heated debates that occur when people talk about this, I would like to note that you might want to consider storing that path to a network folder in the database.
The disadvantage of storing the actual image in the database is that all those bytes have to get sent back and forth through a sql query and if those images are large you will be increasing the size of your db substantially. along with the weird things that were mentioned above.
Anyways I don't want to open up a can of worms, just wanted to show an alternative.
UPDATE:
Something like this:
public partial class LinqClass
{
public string ImagePath { get; set; }
public System.Drawing.Image Picture
{
get
{
return System.Drawing.Image.FromFile(ImagePath);
}
}
}
where ImagePath is the actual column in the db that you are saving the file path to. This doesn't have the code to save the file (something like File.Save(ImagePath) etc. but it's a start.
I've never done it with Linq, but we used a b64 conversion for the image, then a clob datatype. Then reverse the b64 when you want to view the image.
Related
I have followed tutorial on how to write content part in Orchard CMS.
http://docs.orchardproject.net/Documentation/Writing-a-content-part
So, my content part writes the data from the backend to the record table that I wanted to, but the backend isn't reading saved custom content from the same table, i.e. when I manually change the record value in the database and refresh orchard admin, I don't see it changed.
How to change this?
That documentation article is slightly misleading because while the code it provides does store your data in the table you created in the database, it also stores the data within Orchards document storage (xml stored in the ContentVersionRecord table, column called data I believe). So basically for fetching data it will use the document storage, for any querying/filtering it will use the data stored in your record. You can change your code so it will only store it in your table if you'd prefer.
public double Latitude
{
get { return Record.Latitude; }
set { Record.Latitude = value; }
}
So yeah, I shall try to update the documentation tonight because that article is particularly confusing. Have a look at Bertrand's article on Orchard's document storage model: The Shift. Useful read
And I know it's annoying to hear this, but when you are playing with Orchard, it's best to play by its rules. Is there a particular reason you need to modify data directly in the db? Or just playing around?
I have some simple entity which now needs to have a Profile image. What is the proper way to do this? So, it is 1 to 1 relationship, one image is related only to one entity and vice versa. This image should be uploaded through webform together with inserting related entity.
If anyone can point me to the right direction how to persist images to the db and related entity will be great.
Just a side comment: I think is not a good idea to store images in db.
In general is not a good idea store images in db as dbs are designed to store text not big binary chunks. Is much better to store paths for images and have images in a folder. If you want to get sure of 1 to 1 relationship name image with ID of entity (1323.jpg).
If you want to have image paths you should follow some guidelines (In general code defensively):
On upload of image check that image is valid (even made a binary check of image header)
Don't allow to overwrite an existing image in case of a INSERT of a new entity.
Name images as primary key (1.jpg, 2.jpg)
On load of image don't assume that image is going to be there.
Do not allow (if possible) manual interaction with images (No remoting in machine and copying images from one place to other). Manual interaction can cause inconsistencies.
But I assume that for some reason you should do it. So in order to achieve what you want:
DB design
Create a binary column (binary or varbinary) in your table
It is better if you create it in a different table with 1-1 relationship. However the idea is avoiding to load image when hydrating entity. Use a lazy load approach to load your image only when you want.
You have to avoid to load images when you make a big select (for example if you want to load all your entities in a combo avoid SELECT * From whatever) as it will load thousands of images for nothing. As I said this can be done by having images in a different table, or loading only proper columns in SELECT or by making lazy load. (Or even better by NOT having images in DB, only paths)
C# Code
Use BynaryReader to read it
User Byte array to store it
Check this link for code example: http://www.codeproject.com/Articles/21208/Store-or-Save-images-in-SQL-Server
The code is trivial but why the DB?
If this is a website why not save it to a location on disk where you can easily reference it?
Databases are optimised to store data of a known size and relatively small size. Youre image will most likely be more than 8KB in length (mearning its a MAX datatype).
The image will be stored on a separate row/page from your "profile".
Personally I'd save the images in a known folder and use the id for the image name. For profiles that don't have an image and use a standard gif or similar, probably keep it simple / trim by having simlinks/hardlinks of the profile id to the common gif.
public class Profile
{
public int Id {get;}
public string Name {get; private set;}
public Image Picture {get; private set;}
public void Save()
{
using (var connection = new SqlConnection("myconnectionstring"))
using (var command = new SqlCommand("", connection))
{
command.CommandText =
"UPDATE dbo.TblProfile " +
"SET " +
"Name = #name, " +
"Picture = #picture " +
"WHERE ID = #id";
command.Parameters.AddWithValue("#name", Name);
command.Parameters.AddWithValue("#picture", Picture);
command.Parameters.AddWithValue("#id", Id);
command.ExecuteNonQuery();
}
}
}
I think following link would give you the solution,
Upload Image and Save in DB
I am working on a website and I want a drop-down to display the list of cities. Where should I store the list of cities for faster access? I do not want to store this data in DB.
Is it a good idea to store it in XML file?
I would store it in Cache, possibly with a Sql Dependency or File Dependency.
public DataTable GetCities(bool BypassCache)
{
string cacheKey = "CitiesDataTable";
object cacheItem = Cache[cacheKey] as DataTable;
if((BypassCache) || (cacheItem == null))
{
cacheItem = GetCitiesFromDataSource();
Cache.Insert(cacheKey, cacheItem, null,
DateTime.Now.AddSeconds(GetCacheSecondsFromConfig(cacheKey),
TimeSpan.Zero);
}
return (DataTable)cacheItem;
}
If you want to store it in XML, that's fine too but you'll have to publish the file to all servers in the farm each time there is a change.
Store it in a text file. This avoids the overhead of XML parsing. Load using File.ReadAllLines().
You can store the list in an XML file or other flat file format, but I guess it depends on what your reasons are for not wanting to store it in the database.
You mentioned faster access, but you might want to expound on that. If you mean you don't want the overhead of accessing the database on every request, then have you thought about storing it in the database and caching the list on application start-up instead? This way, you get the benefits of a database, yet only pay the overhead once.
For small applications, however, an XML file would be just fine.
If the list will never change, then just declare it as a const array of strings in your code.
If it may change occasionally, then put it in an xml file or a database table, but cache it when you have read it so it only needs to be read once in any session.
I believe XML is the best solution, and it would be better to use DOM parser rather than SAX.
You can also load the file into the session whenever it is not loaded to decrease the number of reads of the XML, but this will use more RAM on the server, be sure not to load unnecessary data because it will be loaded into the server's RAM for each session. You can load it only for logged in users if it makes sense.
What I'm about to suggest is HORID style, but I think the quickest you can get and with the smallest "footprint":
public static readonly string [] CityList = new string []
{
"Sydney",
"New York",
"London"
};
Now, I hope you don't like the solution, and can give us all a little more context so that we might be able to offer an elegant and maintainable solution to your problem; but if all your after is speed...
i need to get an image from client and displayed(preview) before saving it into database..and then should be saved in database after getting preview..?
Is is possible in Asp.net using c#... ?
Yes, it's possible.
If you are using MS SQL Server, declare a field in your table as type "image" or "varbinary". Varbinary limits the number of bytes stored depending on your version of SQL Server, so "image" is the way to go. After all, you are storing an image ;)
Then store your image as a byte array in that field.
Without seeing some code, it's hard to give code samples. Are you using SqlCommand directly, Linq2Sql, Entity framework or NHibernate to communicate with your database?
[Edit: Linq2Sql sample]
On your linq object you will have a propery called Image, if that's what you named your image/varbinary column. To assign it do this:
// assign data
byte[] imageByteArray = ...some byte data...;
myObject.Image = new Binary(imageByteArray);
// save to db
dataContext.YourTable.InsertOnSubmit(myObject); //YourTable is the name of your actual table class
dataContext.SubmitChanges();
where imageByteArray is a byte[] holding your image.
The Binary object is a wrapper around a byte[].
Does any one know of an example on how to store an image in a SQL Server CE database?
What data type should the column be? (I am guessing binary.)
I use Linq-To-Datasets. Is it possible using that to put the image into the database and pull it out again later?
Thanks for any advice.
Here is how I did it:
MemoryStream stream = new MemoryStream();
myBitmapImage.Save(stream, ImageFormat.Png);
myInsertLinqToDataSetRow.IMAGE_COLUMN = stream.ToArray();
To load it back out again I did this:
MemoryStream stream = new MemoryStream(myLinqToDataSetRow.IMAGE_COLUMN);
myBitmapImage.SignatureImage = new Bitmap(stream);
I found a page on MSDN that said that the Image column type is going away and that you should use varbinary(MAX). Max is not supported on SQL Server CE so I did varbinary(8000).
LATER NOTE: while varbinary(max) is not supported on SQL Server CE. Varbinary(8000) is not big enough for many images. I did end up using the Image type even though it is planned to be deprecated. Once ms offers a resonable alternitive on the mobile platform I will consider switching.
Here is an MSDN article explaining how:
http://support.microsoft.com/kb/318639
Unfortunately, the example is in VB, but I am sure that you can get the idea of how to do it.
I would say the binary datatype would be fine for storing the images.
Why aren't you using the Image type? Here is a description of types, supported by the sql server ce.
Image - Variable-length binary data with a maximum length of 2^30 – 1 (1,073,741,823) bytes.
This is not a direct answer to your question, but I've had good success storing the image's filepath (example: C:\images\image1.png) as a string value in the database instead of the raw image.
One advantage to this is that it keeps the database size smaller.
Another is that multiple tables can point to the images without storing multiple copies of the image.