Can I implement file download using MVC4's ApiController? - asp.net-mvc-4

Using regular Controller I could do it by returning FileResult. The same doesn't seem to work with ApiController. Can it be done? Is it even a right thing to do?

Try this.
[HttpGet]
public HttpResponseMessage Get()
{
var file = HttpContext.Current.Server.MapPath("~/Images/accent.png");
var stream = new FileStream(file, FileMode.Open);
var content = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
};
content.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return content;
}

I have this working thanks to this question.
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
namespace Web.Controllers
{
//usage: /download/report
[RoutePrefix("download")]
public class DownloadController : ApiController
{
[HttpGet("report")]
public HttpResponseMessage Report()
{
using (var service = new Client())
{
var report = service.BuildReport();
return DownloadResponse(report, "Report.csv");
}
}
private static HttpResponseMessage DownloadResponse(string content, string fileName)
{
var downloadContent = new StringContent(content);
var mediaType = new MediaTypeHeaderValue("application/octet-stream");
var disposition= new ContentDispositionHeaderValue("attachment") { FileName = fileName };
downloadContent.Headers.ContentType = mediaType;
downloadContent.Headers.ContentDisposition = disposition;
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = downloadContent
};
return result;
}
}
}

Related

"Validation failed for one or more entities. ERROR

I am creating web API to save the uploaded file in my local storage. When I testing my code it gives an error as ExceptionMessage": "Validation failed for one or more entities. See EntityValidationErrors' property for more details."
Can anyone help to fix this issue. Thanks in advance.
Controller(FileUploadController)
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Generic;
using System.Web.Http;
using VantageCore.BL;
namespace VantageCoreApi.Controllers.Api
{
public class FileUploadController : ApiController
{
[HttpPost]
[Route("api/FileUpload")]
public async Task<IHttpActionResult> UploadFile(string FileName, int Id)
{
try
{
List<string> ids = new List<string>();
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var referenceId = FileName.Split('_')[0];
foreach (var file in provider.Contents)
{
Guid guid;
ids.Add(Guid.TryParse(await new FileUploadMgt().ReceiveFile(file, FileName, Id), out guid) ? FileName : "Error");
}
return Ok(ids);
}
catch (Exception e)
{
return InternalServerError(e);
}
}
public string SaveFile(byte[] File, string path)
{
string Result = "";
try
{
//LOCAL SERVER PATH
var fs = new BinaryWriter(new FileStream(#"F:\Testfolder" + path, FileMode.Append, FileAccess.Write));
fs.Write(File);
fs.Close();
Result = path;
}
catch (Exception ee)
{
Result = ee.ToString();
}
return Result;
}
}
}
BL (FileUplodMgt.cs)
using System;
using System.Threading.Tasks;
using System.Collections.Specialized;
using System.Configuration;
using System.IO;
using System.Net.Http;
using VantageCore.Entity.Model;
using File = VantageCore.Entity.Model.File;
namespace VantageCore.BL
{
public class FileUploadMgt
{
public async Task<string> ReceiveFile(HttpContent receivedFile, string receivedFileName, int Id)
{
if (receivedFile != null)
{
var fileId = Guid.NewGuid();
using (var c = new DBEntities())
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
string folder = appSettings["TestPath"];
var fileName = fileId.ToString() + Path.GetExtension(receivedFileName).ToLower();
var file = Path.Combine(folder, fileName);
bool exists = Directory.Exists(folder);
if (!exists) Directory.CreateDirectory(folder);
using (var fs = new BinaryWriter(new FileStream(file, FileMode.Create, FileAccess.Write)))
{
fs.Write(await receivedFile.ReadAsByteArrayAsync());
}
string extention = Path.GetExtension(file);
receivedFileName = Path.GetFileNameWithoutExtension(receivedFileName).Length <= 32
? Path.GetFileNameWithoutExtension(receivedFileName)
: Path.GetFileNameWithoutExtension(receivedFileName).Substring(0, 31) + "~";
var newFile = new File
{
Uid = fileId,
FileExtention = extention,
FileName = receivedFileName,
FileSize = (int)(receivedFile.Headers.ContentLength / 1024),
CreatedDate = DateTime.UtcNow
};
c.Files.Add(newFile);
c.SaveChanges();
}
return fileId.ToString();
}
else
{
return "Error,Invalid file Or file size exceeded";
}
}
}
}
You could try as below to observe the error message when you debug and share it;
try
{
c.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
}
}

Simple serialize ODataQueryOptions

I'm trying to:
[EnableQuery]
[HttpGet]
[ODataRoute("")]
public IHttpActionResult Get(ODataQueryOptions<UserODataModel> options)
{
var users = _repository.RetrieveOData();
var serialQuery = JsonConvert.SerializeObject(options, jsonOptions);
//save serialQuery somewhere
return Ok(users);
}
But got
Newtonsoft.Json.JsonSerializationException: 'Error getting value from 'ReadTimeout' on 'Microsoft.Owin.Host.SystemWeb.CallStreams.InputStream'.'
"Timeouts are not supported on this stream."
I know there is already a question about serialize Stream:
Newtonsoft Json.net - how to serialize content of a stream?
But in this case i can't "extract stream value" from ODataQueryOptions, or can I?
Some ideia?
Since we work on the same company, if anyone is interested, we found a way, maybe not the pretty way, to serialize an ODataQueryOptions:
public static ODataQueryOptions DeserializeQueryOptions(SerializedQueryOptions options)
{
var uri = new Uri(teste.OriginalUri);
var model = ODataConfig.Model; //GetEdmModel
var segment = model.EntityContainer.FindEntitySet(options.EdmType);
var newPath = new Microsoft.AspNet.OData.Routing.ODataPath(new EntitySetSegment(segment));
var httpConfiguration = new HttpConfiguration();
httpConfiguration.EnableDependencyInjection();
var request = new HttpRequestMessage(HttpMethod.Get, uri)
{
Properties =
{
{ HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },
}
};
var context = new ODataQueryContext(model, options.EntityType, newPath);
var oDataQueryOptions = new ODataQueryOptions(context, request);
return oDataQueryOptions;
}
public static SerializedQueryOptions SerializeQueryOptions(ODataQueryOptions options)
{
return new SerializedQueryOptions
{
OriginalUri = options.Request.RequestUri.AbsoluteUri,
EdmType = options.Context.NavigationSource.Name,
EntityType = options.Context.ElementClrType
};
}
After you serialize it to an object you can serialize it to a JSON string:
var queryOptionsSerialized = new SerializedQueryOptions()
{
OriginalUri = "http://localhost:25723/odata/users?$skip=0&$top=2&$orderby=fullName&$count=true",
EdmType = "users",
EntityType = typeof(UserODataModel)
};
var json = JsonConvert.SerializeObject(queryOptionsSerialized);
var deserialized = JsonConvert.DeserializeObject<SerializedQueryOptions>(json);
var options = ODataQueryOptionsHelper.DeserializeQueryOptions(deserialized);
In case One is not using OData routing or using an ApiController (not ODataController),
modify the way of Obtaining ODataPath to:
ODataUriParser parser = new ODataUriParser(model, serviceRoot, requestUri);
ODataPath path = parser.ParsePath();
//var newPath = new Microsoft.AspNet.OData.Routing.ODataPath(new EntitySetSegment(segment));
Microsoft.AspNet.OData.Routing.ODataPath newPath = new Microsoft.AspNet.OData.Routing.ODataPath(path.FirstOrDefault());
where the serviceRoot is the Url part other that the path defined in the model.

ASP.NET CORE using ADO.NET with AutoMapper

What is the proper way of using AutoMapper with ADO.NET in ASP.NET Core in generic way?
Also the SQL query has the same column names as in class of <T>
In specified example variable result is always empty list, so automapper could not map object properties to DbDataReader columns.
public class CustomDbContext : BaseRepository
{
readonly DbConnection dbConn;
public CustomDbContext(RepoDbContext context) : base(context)
{
dbConn = context.Database.GetDbConnection();
}
public async Task<List<T>> Get<T>(string sql) where T : class
{
var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.CreateMap<DbDataReader, List<T>>();
});
var mapper = config.CreateMapper();
await dbConn.OpenAsync();
using (var command = dbConn.CreateCommand())
{
command.CommandText = sql;
var reader = await command.ExecuteReaderAsync();
var result = new List<T>();
if (reader.HasRows)
{
await reader.ReadAsync();
result = mapper.Map<DbDataReader, List<T>>(reader);
}
reader.Dispose();
return result;
}
}
}
Should I specify more detailed AutoMapper configuration or it can't be done this way?
Try using interfaces as IDataReader and IEnumerable instead of classes DbDataReader and List.
public async Task<List<T>> Get<T>(string sql) where T : class
{
var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.CreateMap<IDataReader, IEnumerable<T>>();
});
var mapper = config.CreateMapper();
await dbConn.OpenAsync();
using (var command = dbConn.CreateCommand())
{
command.CommandText = sql;
var reader = await command.ExecuteReaderAsync();
var result = new List<T>();
if (reader.HasRows)
{
await reader.ReadAsync();
result = mapper.Map<IDataReader, IEnumerable<T>>(reader).ToList();
}
reader.Dispose();
return result;
}
}

TwitterSettings.OAuthVersion

i don't understand that : GetRequestToken is not working in TweetSharp on Windows Phone
My code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp2.Resources;
using TweetSharp;
namespace PhoneApp2
{
public partial class MainPage : PhoneApplicationPage
{
private const string consumerKey = "zvBvaKjEQRwGqu9ECaNfop0pr";
private const string consumerSecret = "SgEqsMRcIrEYNrtXhvtYdnx7qBA9EITzswneyjf8wRorDvSAvn";
private TwitterService myclient;
private OAuthRequestToken requestToken;
private bool userAuthenticated = false;
// Constructeur
public MainPage()
{
InitializeComponent();
myclient = new TwitterService(consumerKey, consumerSecret);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//If user is already logged in, just send the tweet, otherwise get the RequestToken
if (userAuthenticated)
//send the Tweet, this is just a placeholder, we will add the actual code later
Dispatcher.BeginInvoke(() => { MessageBox.Show("Placeholder for tweet sending"); });
else
myclient.GetRequestToken(processRequestToken);
}
private void processRequestToken(OAuthRequestToken token, TwitterResponse response)
{
if (token == null)
Dispatcher.BeginInvoke(() => { MessageBox.Show("Error getting request token"); });
else
{
requestToken = token;
Dispatcher.BeginInvoke(() =>
{
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(myclient.GetAuthorizationUri(requestToken));
});
}
}
}
}
and visual studio 2013 create an error on myclient.GetRequestToken(processRequestToken); ...
how can incorporate your solution with hammock on my code?
I had this identical error last week (doing this app) The solution was to implement the Hammock Library instead of tweet sharp. Also in the post tweet example change the version from 1 to 1.1
This is the Nokia Developer Documentation I followed to implement logging in
This is the Nokia Developer Documentation I followed to implement posting a tweet
REMEMBER CHANGE THE VERSION TO 1.1 LIKE THIS
From this
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
};
var restClient = new RestClient
{
Authority = "http://api.twitter.com",
HasElevatedPermissions = true
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = "/1/statuses/update.json",
Method = WebMethod.Post
};
restRequest.AddParameter("status", txtTweetContent.Text);
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
To This
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
};
var restClient = new RestClient
{
Authority = "http://api.twitter.com",
HasElevatedPermissions = true
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = "/1.1/statuses/update.json",
Method = WebMethod.Post
};
restRequest.AddParameter("status", txtTweetContent.Text);
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));

VCR for ServiceStack's JsonServiceClient

The Ruby VCR library enables you to "Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests."
I'd like to create something similar using ServiceStack's JsonServiceClient, but I can't get it to work. My most recent failed attempt follows. I'd like to either make my current attempt work, or suggestions on another approach that will work.
public static class Memoization
{
public static Func<T, TResult> AsCached<T, TResult>(this Func<T, TResult> function)
{
var cachedResults = new Dictionary<T, TResult>();
string filename = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + (typeof(TResult)).Name + ".jsv";
var serializer = MessagePackSerializer.Create<Dictionary<T, TResult>>();
if (cachedResults.Count == 0)
{
////// load cache from file
using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
cachedResults = serializer.Unpack(fs);
}
}
return (argument) =>
{
TResult result;
lock (cachedResults)
{
if (!cachedResults.TryGetValue(argument, out result))
{
result = function(argument);
cachedResults.Add(argument, result);
////// update cache file
using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
serializer.Pack(fs, cachedResults);
}
}
}
return result;
};
}
}
class MemoizeJsonClient<TResponse> : JsonServiceClient, IServiceClient, IRestClient
{
private Func<IReturn<TResponse>, TResponse> _getCached;
private JsonServiceClient client;
public TResponse Get(IReturn<TResponse> request)
{
if (_getCached == null)
{
Func<IReturn<TResponse>, TResponse> func = GetImpl;
_getCached = func.AsCached();
}
return _getCached(request);
}
private TResponse GetImpl(IReturn<TResponse> request)
{
return client.Get(request);
}
public MemoizeJsonClient(string BaseUri) {
client = new JsonServiceClient(BaseUri);
}
}
Called like this:
[Test]
public void TestReports2()
{
string Host = "http://localhost:1337";
string BaseUri = Host + "/";
List<Options> testcases = new List<Options>();
testcases.Add(new Options("Name", "20130815", "20130815"));
foreach (Options options in testcases)
{
TransactionsReq transRequest = new TransactionsReq();
transRequest.source = "Source";
transRequest.name = new List<String>(new string[] { options.Name });
transRequest.startDate = options.StartDate;
transRequest.endDate = options.EndDate;
MemoizeJsonClient<TransactionsReqResponse> client = new MemoizeJsonClient<TransactionsReqResponse>(BaseUri);
List<Transaction> transactions;
TransactionsReqResponse transResponse = client.Get(transRequest);
transactions = transResponse.data;
}
}
But I get the following error:
System.Runtime.Serialization.SerializationException occurred
HResult=-2146233076
Message=Cannot serialize type 'ServiceStack.ServiceHost.IReturn`1[ImagineServerWrapper.DTO.TransactionsReqResponse]' because it does not have any serializable fields nor properties.
Source=MsgPack
StackTrace:
at MsgPack.Serialization.SerializerBuilder`1.CreateSerializer()
InnerException: