Fileupload to server and saving his id to database as guid - asp.net-mvc

A client of mine came with the following demand:
Add the option to upload a file to the server
Save the file id as a guid in database
I followed this answer- so the file upload is working(to a specific location on the server)
http://stackoverflow.com/questions/5193842/file-upload-asp-net-mvc-3-0
What i don't familiar with is his second demand:
Save the file id as a guid in database
What does it mean?
Why does the file need a guid id in the database?
What should I do in extra to the post I linked to?(security check, extension check?)

guid = globaly unique identifier.
Why does a file need a guid in database ? well because its your client's requirement its not required by the database.
And finally how to do it? is simple when you will be saving a filename to database generate a guid and save it to the database you can generate a guid like this Guid id = Guid.NewGuid(); and you can create a separate column in the database for saving file's guids.

Related

How to Upload json file in mvc4 to enter data in tables

I have json file generated from my database in the following format
[{"UserInfoID":"57adb1e8-27ab-e311-afb2-eca86bf5549a","DbType":"OFFLINE","UserID":"d3f3b6a6-77aa-436a-a73c-d6655566888b","GraphID":"56adb1e8-27ab-e311-afb2-eca86bf5549a","UserLevelEnumId":"00000000-0000-0000-0000-000000000000","Title":"Mr/Mrs","FirstName":"Neeraj","MiddleName":null,"LastName":"Mehta","Birthdate":"\/Date(699388200000)\/","Gender":"Male","Email":"neer.srmiet#gmail.com","MobileNo":"+918950333123","Country":"India","Zipcode":133201,"UserLevel":999,"CountFollowers":0,"CountFollows":0,"CountFiles":0,"CountPhotos":0,"Quote":"Empowering Education","AvatarURL":"/UserFiles/Images/X50/IMAG1289_1vv4djTgspjjsl87fquality_50.jpg","PosterURL":null,"isVerified":true,"VerificationCount":0,"UserEnumType":"USER","UserCreatorId":"d3f3b6a6-77aa-436a-a73c-d6655566888b"}
and i have downloaded this data in a file and now i want to upload this data in other database having same structure and same attribute
How can i upload this from a file and suggestion?
Create a class that match this object if you don't have it yet (lets call this class 'user').
If you want to upload this json data using ajax create the following action:
[HttpPost]
public ActionResult(User user) {
// Add input validation here.
// Add the user entity to the database.
UsersContext context = new UsersContext();
context.Users.Add(user);
context.SaveChanges();
}

User profile image asp.net mvc identity

I'm creating a web application using MVC 5 and Identity. I have so far created a registration system, but I would like to allow users to upload a profile when they register.
I was wondering if it is possible to implement profile pictures with asp.net identity?
Yes. Assuming you're using the default Entity Framework implementation, you can extend the ApplicationUser in a file called Models/IdentityModels.cs.
You can store the image in the database or elsewhere on the file system.
One way to store it in the database is using a byte array in the model (which I believe maps to varbinary(max))...
public class ApplicationUser : IdentityUser
{
public byte[] Image { get; set; }
}
Details on how to save upload an image and save in the database via EF can be found here...
Entity Framework 5 Code first adding an image
Or you can simply save the uploaded file to the file system or to blob storage, then store the path or URL to the image...
public class ApplicationUser : IdentityUser
{
public string ImagePath { get; set; }
}
Best thing todo is to create a second table (or add a column to the current table), add a file upload feature to the registration form. When registration is successful add the picture to the db with EntityFramework. Create a page to return the picture by the userid so you can include it in a page somewhere.
Something like this http://blogs.msdn.com/b/webdev/archive/2013/10/16/customizing-profile-information-in-asp-net-identity-in-vs-2013-templates.aspx but with a profile picture

Asp mvc 3 noobie: Why is the code-first method not building my DB on sql server?

I am an ASP MVC 3 noobie who has done a few tutorials. Now I'm trying to build a site. All of the tutorials on the microsoft website emphasize the code-first approach: you define your model with code and then create a datacontext and then the entity framework creates/manages the DB based on your code.
I set up an Employees class and a DataBaseContext class that inherits from DbContext. I added a connection string to Web.config connection string that successfully links DataBaseContext to an already existing empty DB on SQL server. EDIT= That was the problem. See my answer below
But when I try to run the Employees controller created thru scaffolding, I get this error
Invalid object name 'dbo.Employees'.
Description: An unhandled exception occurred during the execution of...
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.Employees'.
I followed this post SqlException (0x80131904): Invalid object name 'dbo.Categories' and realized that if I create an employees table on the DB, this excpetion goes away (I get a new one saying that the column names are invalid).
But I thought the whole point of MVC 3 is that the framework will make the DB for you based on the code.
Maybe I need a line of code in the Global.asax Application_start() to create the database? Here is my application_start method:
Sub Application_Start()
AreaRegistration.RegisterAllAreas()
RegisterGlobalFilters(GlobalFilters.Filters)
RegisterRoutes(RouteTable.Routes)
End Sub
Here is the code for Employee:
Public Class Employee
Property EmployeeID As Integer
Property First As String
Property Last As String
Property StartDate As DateTime
Property VacationHours As Integer
Property DateOfBirth As DateTime 'in case two employees have the same name
End Class
Here is the code for the DB context:
Imports System.Data.Entity
Public Class DatabaseContext
Inherits DbContext
Public Property Employee As DbSet(Of Employee)
Public Property AnnualLeave As DbSet(Of AnnualLeave)
End Class
What am I missing?
By default EF uses DropCreateDatabaseIfModelChanges<TContext> database initializer. Accordingly to the MSDN:
An implementation of IDatabaseInitializer<TContext> that will delete, recreate, and optionally re-seed the database with data only if the model has changed since the database was created. This is achieved by writing a hash of the store model to the database when it is created and then comparing that hash with one generated from the current model.
Since the database was created manually, EF can't find the hash and decides do not perform any further initialization logic.
You might want to look into this article, same question successfully answered already.
Or it can be this (also resolved successfully)
Answer to your problem is most likely one of the two.
Hope this will help you
Does the name you're specifying for your connection string match the name of your database context?
For example:
Context
var myDbContext = new MyDbContext();
Connection string
<connectionStrings>
<add name="MyDbContext" connectionString="YOUR.CONNECTION.STRING" providerName="System.Data.SqlServer" />
</connectionStrings>
Try and see if this post I wrote about DbContext with MVC works for you: Code-First
Not a lot to be done to get this to work, but there are a few things that are easily missed that will cause a bunch of head aches.
hope this helps
I had already created a database with that name on SQL server. Once I deleted the existing database, the code first framework created the tables for me like it was supposed to. It seems like if the database already exists, the framework won't set up the tables for you. It wants to create the whole DB from scratch.
You were using AdventureWorks Database?
It has it's own schema assigned to the employees table. HumanResources.Employees and not the default dbo.Employees.
Even though I've identified the problem, I don't know the solution to using the database as configured with the HumanResources schema.
Anybody know?

Saving Id in Raven Document

New to Raven. I have an MVC page that saves data to a Raven document. I am able to save all fields as expected. I have noticed the Id (field/attribute of the table/class structure in my project) is null and it does not get saved into the document. There is a Raven system generated Id in the title of the document (like DocName/123 etc...). How can I get that DocName/123 or 123 or some other auto generated Id field save into the raven document? Please help..Thank you
Raven will Automatically generate the Id if it is not specified. If you don't want Raven to generate this key then you need to specify public string Id {get; set;}
property in your class.`

Change model after database is created on EF4 code only

Hey, sorry for my bad english...
Using EF4 code-only, I have created some POCO classes and my database was generated from that. All worked fine, I inserted some data on the tables but now I need to create a new property on one of my classes. If i just create it, the application give me the exception:
{"The model backing the 'TestContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."}
I tried to create manually the field on the table, but it is still complaining... does someone know if there is a way and if so how can I manually update the database schema (i don't want to recreate it because i already have data) to match the model?
It should work if you make sure that your new column match exactly your new property.
For example, if you add a property NewProp
public class MyEntity
{
[Key]
public int Id;
public string PropA;
public int PropB;
public int NewProp;
}
then in your database table MyEntities, you would add a column NewProp of type int not null.
What you can do to check if the column you add is correct, is to rename your database, then let Code-First recreate the database and see what's different between the original and new databases.
EF generates partial classes. So you can add new properties(fields) in another partial class.

Resources