How to retrieve stored image in sql database in asp.net mvc3? - sql

I have a table in my database and one of its columns is in Image data type. I can store Image in database but I can't retrieve it. I want to retrive Image for each logged in user. I used this code:
public ActionResult ShowImage()
{
var userID = GetUserID();
var advert = from ad in StoreDb.Ads where ad.UserId == userID select ad.AdImage;
return File(advert, "Image");
}
But got this error:
Error 2 Argument 1: cannot convert from 'System.Linq.IQueryable' to 'string' C:\Users\Tena\Documents\Visual Studio 2010\Projects\MvcApplication6\MvcApplication6\Controllers\Default3Controller.cs 92 25 MvcApplication6
The problem is that advert is in
System.Linq.IQueryable<>byte[]
format but File needs byte[] format. What should I do now? Any answer is helpful.
Thanks

The problem is that the LINQ query isn't being evaluated and the query as it stands could theoretically return more than one result (hence it's an IQueryable).
In fact the query doesn't look right as presumably there will be more than one advert for a particular user and I wouldn't expect the adverts to be stored according to user in any case, but I don't know anything about your data structure, so I'll just try to help you make the query work and you can refine it later.
Try changing this line:
var advert = from ad in StoreDb.Ads where ad.UserId == userID select ad.AdImage;
to this:
var advert = (from ad in StoreDb.Ads where ad.UserId == userID select ad.AdImage).FirstOrDefault();
I could give you other tips around how to do this, but try that first and see what happens.

I'not sure, this is the way to go for this problem. I usually implement a custom http handler, which expects some id (e.g. userid), connects to the database, fetches the picture and returns a stream of bytes with the correct mime type of the picture.
In the "view" i just create an image tag with the url of the http handler as image source.

Related

How to create several new records in another SQL table from one button-click

I'm new here. Thanks in advance for your advice.
I’m working on an app which will ask the user how many items they made.
The user will enter a number. My app should then create that many new records in a table called 'Items_Made'.
E.g. The app asks “How many items did you make?”, the user enters “19”, the app then creates 19 new records in the 'Items_Made' table.
I've managed to pull together some code (shown below) that creates ONE new record, but I would like it to create several. I probably need some kind of loop or 'while' function but am unsure how to do so.
var ceateDatasource = app.datasources.Items_Made.modes.create;
var newItem = ceateDatasource.item;
ceateDatasource.createItem();
This code successfully creates 1 record. I would like it to be able to create several.
Creating a lot of records via client script is not recommended, especially if you loose connection or the app gets closed by mistake. In my opinion, the best way to handle this would be via server script for two things: First, It's more reliable and second, it's faster. As in the example from the official documentation, to create a record you need to do something like this:
// Assume a model called "Fruits" with a string field called "Name".
var newRecord = app.models.Fruits.newRecord();
newRecord.Name = "Kiwi"; // properties/fields can be read and written.
app.saveRecords([newRecord]); // save changes to database.
The example above is a clear example on how to create only one record. To create several records at once, you can use a for statement like this:
function createRecordsInBulk(){
var newRecords = [];
for(var i=0; i<19; i++){
var newRecord = app.models.Fruits.newRecord();
newRecord.Name = "Kiwi " + i;
newRecords.push(newRecord);
}
app.saveRecords(newRecords);
}
In the example above, you initiate newRecords, an empty array that will be responsible for holding all the new records to create at once. Then using a for statement, you generate 19 new records and push them into the newRecords. Finally, once the loop is finished, you save all the records at once by using app.saveRecords and passing the newRecords array as an argument.
Now, all this is happening on the server side. Obviously you need a way to call this from the client side. For that, you need to use the google.script.run method. So from the client side you need to do the following:
google.script.run.withSuccessHandler(function(result) {
app.datasources.Fruits.load();
}).createRecordsInBulk();
All this information is clearly documented on the app maker official documentation site. I strongly suggest you to always check there first as I believe you can get a faster resolution by reading the documentation.
I'd suggest making a dropdown or textbox where the user can select/enter the number of items they want to create and then attach the following code to your 'Create' button:
var createDatasource = app.datasources.Items_Made.modes.create;
var userinput = Number(widget.root.descendants.YourTextboxOrDropdown.value);
for (var i = 0; i <= userinput; i++) {
var newItem = createDatasource.item;
createDatasource.createItem();
}
Simple loop with your user input should get this accomplished.

Preserving the value of ViewData MVC 4

I am working on MVC 4 where i have "ActionResult" method which is of login page, username and password are entered in textbox, based on the username(which is billnumber) after login it should pull the data of that respective billnumber(username), so currently everything is working fine, I am able to get the username from one view and send it to another for further verification, I have stored "username" and "usertypeID" in Viewdata and that value is passed to next view, but the data on ViewData will not stand for longer time, and even if we try to refresh the page multiple times(10 to 20 times), below are the code which i Have used to store and to access
this is where i store the value
public ActionResult ValidateLogIn(FormCollection postedFormData)
{
// codes
TempData["UsrName"] = LoginViewModel.LoginDataModel.UserName;
// codes
}
public ActionResult LandingPage()
{
ViewData["message"] = TempData["UsrName"].ToString();
ViewData["person"] =Convert.ToInt32(TempData["UserTypeID"]);
TempData.Keep();
PatientDetailsViewModel PatientDetailsViewModel = new PatientDetailsViewModel();
String PatID = Convert.ToString(ViewData["message"].ToString());
int PersonType = Convert.ToInt32(ViewData["person"]);
PatientUnderDoctorDetailsViewModel = PatientUnderDoctorDataAccessService.PatientUnderDocLogInEnquiry(PatID);
}
this is where i store it on viewdata
ViewData["message"] = TempData["UsrName"].ToString();
ViewData["person"] =Convert.ToInt32(TempData["UserTypeID"]);
TempData.Keep();
AND HERE IS WHERE I GET VALUES FROM VIEWDATA
String PatID = Convert.ToString(ViewData["message"].ToString());
int PersonType = Convert.ToInt32(ViewData["person"]);
I am passing PatID and PersonType as parameter to next method,
at beginning I wasn't using TempData.keep(); so when I refresh the page atleast once used to get error, tried searching and found TempData but i believe it is not much efficient for longer time, if I left application idle for 5 mins and then refreshes the page once , it generates error message since tempdata is empty(null)
WHAT I NEED
let me know is there any mistake i have done, or is there any better way to fix this issue, where data can be stored in variable until I quit the application
I hope this link will help you State Management In MVC
Don't use Temp data for this. it will be lost when the app pool refreshes or if you use another process (web garden).
User.Identity.Name will return the name of a validated user.
If you are passing data around you should be using Models and not ViewData or TempData or ViewBag.

MVC 4 Lookup UserName Based on UserId

I'm using the MVC 4 template with VS 2012. I have enabled a comments section which stores the logged in user's UserId to a table. When I display the comments I want to display the user's user name and email from the UserProfiles table.
I've tried the following code:
public static string GetUserName(int userId)
{
using (var db = new UsersContext())
{
return db.UserProfiles.Single(x => x.UserId == userId).UserName;
}
}
But I get an exception:
The model backing the 'UsersContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
Any suggestions?
The exception is pretty descriptive. Your model does not reflect what your database look like. I recommend you to read this about code first migrations, basically what migrations mean is that you update your database to match your models, its done with one line of command in VS.
Hope this helps
Also I would recommend you to use .Find() or .First() instead of .Single()

Checking if certain key exists in database

I have saved certain MDX query and I run them using ADOMD.NET. I get CellSet back which I convert into dataset. All this is working fine. Now the DB team has changed the cube structure. They have updated the DimesnionName, Attribute Name etc. Some dimensions got renamed and some got deleted. Becuase of this I am unable to run my saved queries. I want to create a console application, which will take list of keys ([DimensionName].[AttributeName] or [DimensionName].[AttributeName].[MemeberName] format) and it will tell me following keys does not exists.
Please let me know if this is possible programatically. I dont want to check it manually.
Kindly share a link or code which will help me acheive this.
Thank you.
If you're using ADOMD already this should be no problem, just use the metadata queries:
http://msdn.microsoft.com/en-us/library/ms123485.aspx
Alternatively, AMO is nice http://msdn.microsoft.com/en-us/library/microsoft.analysisservices.aspx
I use it in SSIS for processing, you could easily use it in .Net to test existence of elements:
using Microsoft.AnalysisServices;
...
Server server = new Server();
server.Connect(cubeConnectionString);
Database database = server.Databases.FindByName(databaseName);
Cube cube = database.Cubes.FindByName(cubeName);
foreach (MeasureGroup measureGroup in cube.MeasureGroups)
{
foreach (Partition partition in measureGroup.Partitions)
{
...
}
}
foreach (CubeDimension cubeDimension in cube.Dimensions)
{
Dimension dimension = cubeDimension.Dimension;
var dimName = dimension.Name;
...
}
Finding the names in advance for all the elements you need is probably the hard part (And keeping it all up-to-date).
Would it not be easier to fire all the queries at the cube and try to trap the "no such thing" response?

Use an AppReceiptId to verify a user's identity in a Windows Store App?

I want to be able to use the AppReceiptId from the result of CurrentApp.GetAppReceiptAsync() and tie it to a username in my backend service, to verify that the user has actually purchased the app.
I know I'm supposed to use CurrentAppSimulator in place of CurrentApp, but CurrentAppSimulator.GetAppReceiptAsync() always returns a different, random value for AppReceiptId. This makes it difficult to test with my service.
Is there a way to make it always return the same value, other than just using a hardcoded one? I'm worried that when I replace CurrentAppSimulator with CurrentApp and submit it to the store, it won't behave the way I expect it to. In the real world, the AppReceiptId won't ever change, right?
The Code I use to get AppReceiptId:
var receiptString = await CurrentAppSimulator.GetAppReceiptAsync();
XmlDocument doc = new XmlDocument();
doc.LoadXml(receiptString);
var ReceiptNode = (from s in doc.ChildNodes
where s.NodeName == "Receipt"
select s).Single();
var AppReceiptNode = (from s in ReceiptNode.ChildNodes
where s.NodeName == "AppReceipt"
select s).Single();
var idNode = (from s in AppReceiptNode.Attributes
where s.NodeName == "Id"
select s).Single();
string id = idNode.NodeValue.ToString();
id will always be some random Guid.
CurrentApp.GetAppReceiptAsync().Id is a unique ID for the actual purchase. Although it does technically represent a unique purchase made by a single Windows ID, it doesn't represent the user themselves and I don't think there's any guarantee on the durability of that ID.
Would you be better suited using the Windows Live SDK to track the actual user identity across devices?
At any rate, to answer your original question, no I don't believe there's any way to make it return the same ID all the time. The only logical place for that functionality would be in the WindowsStoreProxy.xml file, and I don't see anything in the schema that would allow you to specify this information.