Convert image To Bytes in Asp.Net Mvc 6 - c#

In Asp.Net Mvc 6, I am trying to convert image to bytes for adding the picture into database. I cannot find the way to use the right method of encoding. Can someone help me to correct this below code, the mistake is at encoding: UInt32 which is not valid in the given context.
private readonly ApplicationDbContext _context = new ApplicationDbContext();
public int UploadImageInDataBase(IFormFile file, PublisherInfos publisherInfos)
{
publisherInfos.CoverImage = ConvertToBytes(file);
var pubInfos = new PublisherInfos
{
ImageSize = publisherInfos.ImageSize,
FileName = publisherInfos.FileName,
CoverImage = publisherInfos.CoverImage
};
_context.PublisherInfos.Add(pubInfos);
int i = _context.SaveChanges();
if (i == 1)
{
return 1;
}
else
{
return 0;
}
}
// ConvertToBytes
private byte[] ConvertToBytes(IFormFile image)
{
byte[] CoverImageBytes = null;
var _reader = new StreamReader(image.OpenReadStream());
BinaryReader reader = new BinaryReader(_reader.ReadToEndAsync, encoding: UInt32);
CoverImageBytes = reader.ReadBytes((int)image.Length);
return CoverImageBytes;
}
// Controller
public IActionResult Create(PublisherInfos publisherInfos)
{
if (ModelState.IsValid)
{
IFormFile file = Request.Form.Files["CoverImage"];
PublisherInfosRepository service = new PublisherInfosRepository();
int i = service.UploadImageInDataBase(file, publisherInfos);
if (i == 1)
{
// Add file size and file name into Database
_context.PublisherInfos.Add(publisherInfos);
_context.SaveChanges();
return RedirectToAction("Index", new { Message = PublisherInfoMessageId.DataloadSuccess });
}
}
return View(publisherInfos);
}

You Controller Action will be like this
[HttpPost]
public virtual ActionResult Index(HttpPostedFileBase file)
{
.....
.....
byte[] m_Bytes = ReadToEnd (file.InputStream);
....
...
}
The Helper Method
public static byte[] ReadToEnd(System.IO.Stream stream)
{
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
If you are using MVC 5
use this
private byte[] ConvertToBytes(IFormFile file)
{
Stream stream= file.OpenReadStream();
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}

try this
private byte[] ConvertToBytes(IFormFile image)
{
byte[] CoverImageBytes = null;
BinaryReader reader = new BinaryReader(image.OpenReadStream());
CoverImageBytes = reader.ReadBytes((int)image.Length);
return CoverImageBytes;
}

Related

How to resolve an append issue to a csv file in ASP.net?

I have an issue with adding some text to a csv file, my text is appending but it is appending to the previous line and not a new line. I also get a type error saying System.FormatException: Input string was not in a correct format. This is obviously to do with the append issue but I can't figure out what I'm doing wrong here. Any ideas?
here is the output in the csv file
University,0
Groceries,1
Other,2
Gaming,3Pets,4
Thanks in advance :)
Controller
// GET: Category/Create
public ActionResult Create()
{
return View();
}
// POST: Category/Create
[HttpPost]
public ActionResult Create(Category category)
{
try
{
TodolistRepository.AddCategory(category.Name);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
.cs file
public static bool AddCategory(string category, int catId = 0)
{
int newIdentifier = catId;
if (newIdentifier == 0)
{
int maxIdentifier = _listOfCategories.Max(x => x.Identifier);
newIdentifier = ++maxIdentifier;
}
try
{
using (FileStream fs = new FileStream(_categoriesfile, FileMode.Append, FileAccess.Write))
{
using (var writer = new StreamWriter(fs))
{
var line = $"{category},{newIdentifier.ToString()}";
writer.WriteLine(line);
writer.Flush();
}
}
return true;
}
catch (Exception)
{
return false;
}
}
public static void ReadCategoriesFromFile()
{
using (StreamReader reader = new StreamReader(_categoriesfile))
{
while (!reader.EndOfStream)
{
string[] fields = reader.ReadLine().Split(',');
_listOfCategories.Add(new Category
{
Name = fields[0],
Identifier = Int32.Parse(fields[1])
});
}
}
}
//Gets all the categories in the List
public static List<Category> GetCategories()
{
ReadCategoriesFromFile();
_listOfCategories = _listOfCategories.OrderBy(x => x.Identifier).ToList();
return _listOfCategories;
}
Add newLine"\r\n" character end of line where you addCategory. if you want to check if there is a line without newLine character read line first.

Loacl PDF not opening in cefsharp 71

I am trying to open pdf in the cefsharp browser itself. But nothing is getting displayed when I open the pdf. I have set the logs to error level but there are no errors in it.
This is how I am registering the CefCustomScheme :
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CefSharpSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CefSharpSchemeHandlerFactory(),
IsCSPBypassing = true,
});
This is my CefSharpSchemeHandlerFactory :
public class CefSharpSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "local";
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
if (schemeName == SchemeName && request.Url.EndsWith("CefSharp.Core.xml", System.StringComparison.OrdinalIgnoreCase))
{
//Convenient helper method to lookup the mimeType
var mimeType = ResourceHandler.GetMimeType(".xml");
//Load a resource handler for CefSharp.Core.xml
//mimeType is optional and will default to text/html
return ResourceHandler.FromFilePath("CefSharp.Core.xml", mimeType);
}
return new CefSharpSchemeHandler();
}
}
This is my CefSharpSchemeHandler :
internal class CefSharpSchemeHandler : IResourceHandler
{
private static readonly IDictionary<string, string> ResourceDictionary;
private string mimeType;
private MemoryStream stream;
static CefSharpSchemeHandler()
{
}
bool IResourceHandler.ProcessRequest(IRequest request, ICallback callback)
{
// The 'host' portion is entirely ignored by this scheme handler.
var uri = new Uri(request.Url);
var fileName = uri.AbsolutePath;
string resource;
if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource))
{
Task.Run(() =>
{
using (callback)
{
var bytes = Encoding.UTF8.GetBytes(resource);
stream = new MemoryStream(bytes);
var fileExtension = Path.GetExtension(fileName);
mimeType = ResourceHandler.GetMimeType(fileExtension);
callback.Continue();
}
});
return true;
}
else
{
callback.Dispose();
}
return false;
}
void IResourceHandler.GetResponseHeaders(IResponse response, out long responseLength, out string redirectUrl)
{
responseLength = stream == null ? 0 : stream.Length;
redirectUrl = null;
response.StatusCode = (int)HttpStatusCode.OK;
response.StatusText = "OK";
response.MimeType = mimeType;
}
bool IResourceHandler.ReadResponse(Stream dataOut, out int bytesRead, ICallback callback)
{
callback.Dispose();
if(stream == null)
{
bytesRead = 0;
return false;
}
//Data out represents an underlying buffer (typically 32kb in size).
var buffer = new byte[dataOut.Length];
bytesRead = stream.Read(buffer, 0, buffer.Length);
dataOut.Write(buffer, 0, buffer.Length);
return bytesRead > 0;
}
bool IResourceHandler.CanGetCookie(Cookie cookie)
{
return true;
}
bool IResourceHandler.CanSetCookie(Cookie cookie)
{
return true;
}
void IResourceHandler.Cancel()
{
}
void IDisposable.Dispose()
{
}
}
And this how I am opening My pdf file from some other class :
string pdfPath = #"D:\Magic\10774.pdf";
var mimeType = ResourceHandler.GetMimeType(".pdf");
ResourceHandler.FromFilePath(pdfPath, mimeType);
I am not getting a hit at CefSharpSchemeHandlerFactory create method.

C# how to handle multipart file uploaded from android to C#

I'm uploading excel file from android to C# the request from android is arriving to c# server(I don't want to use asp.net).
I've built from scratch a simple HTTPServe, I do't how to handle multipart data upload in c# that's my code :
Request.cs:
class Request
{
public String type { get; set; }
public String url { get; set; }
public String host { get; set; }
private Request(String type,String url,String host)
{
this.type = type;
this.url = url;
this.host = host;
}
public static Request GetRequest(String request)
{
if (String.IsNullOrEmpty(request))
return null;
String[] tokens = request.Split(' ');
String type = tokens[0];
String url = tokens[1];
String host = tokens[4];
return new Request(type, url, host);
}
}
Response.cs:
class Response
{
private Byte[] data = null;
private String status;
private String mime;
private Response(String status,String mime,Byte[] data)
{
this.status = status;
this.data = data;
this.mime = mime;
}
public static Response From(Request request)
{
Console.WriteLine(request.type);
if (request == null)
return MakeNullRequest();
if (request.type.Equals("POST"))
{
return UploadCompleteResponse(request);
}
return MakeFromExcel();
}
private static Response UploadCompleteResponse(Request request)
{ //Handling the multipart request here but I don't know how that is a simple example
Console.WriteLine("uploaded!!");
byte[] bytes = Encoding.ASCII.GetBytes("uploaded!!");
return new Response("ok 200","text/plain",bytes);
}
//private static Response MakeFromFile(FileInfo f)
//{
// // to do later
// //return new Response("200 ok", "text/html", d);
//}
//Retruning an excel file response
private static Response MakeFromExcel()
{
String file = Environment.CurrentDirectory + HTTPServer.EXCEL_DIR+"brains.xlsx";
Console.WriteLine(file);
FileInfo info = new FileInfo(file);
if (info.Exists)
{
FileStream fs = info.OpenRead();
BinaryReader read = new BinaryReader(fs);
Byte[] d = new Byte[fs.Length];
read.Read(d, 0, d.Length);
fs.Close();
return new Response("200 ok", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", d);
}
return PageNotFound();
}
private static Response MakeNullRequest()
{
String file = Environment.CurrentDirectory+HTTPServer.MSG_DIR +"400.html";
Console.WriteLine(file);
FileInfo info = new FileInfo(file);
FileStream fs=info.OpenRead();
BinaryReader read=new BinaryReader(fs);
Byte[] d = new Byte[fs.Length];
read.Read(d, 0, d.Length);
fs.Close();
return new Response("400 Bad Request", "text/html", d);
}
private static Response PageNotFound()
{
String file = Environment.CurrentDirectory + HTTPServer.MSG_DIR + "400.html";
FileInfo info = new FileInfo(file);
FileStream fs = info.OpenRead();
BinaryReader read = new BinaryReader(fs);
Byte[] d = new Byte[fs.Length];
read.Read(d, 0, d.Length);
return new Response("404 Not Found", "text/html", d);
}
public void Post(NetworkStream stream)
{
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(String.Format("{0} {1}\r\nServer: {2}\r\nContent-Type: {3}\r\nAccept-Ranges: 255 bytes\r\nContent-Length: {4}\r\n", HTTPServer.VERSION
, status, HTTPServer.NAME, mime, data.Length));
writer.Flush();
stream.Write(data, 0, data.Length);
stream.Flush();
stream.Close();
}
}
In the above code I used more than one type of response You can access and the request fields by increasing the size of the token array.
HTTServer.cs:
class HTTPServer
{
public const String MSG_DIR = "\\root\\msg\\";
public const String EXCEL_DIR = "\\root\\excel\\";
public const String WEB_DIR = "\\root\\web\\";
public const String VERSION = "HTTP/1.1";
public const String NAME = "Thecode007 HTTP SERVER v 1.0";
private bool running = false;
private TcpListener listener;
public HTTPServer(int port)
{
listener = new TcpListener(IPAddress.Any,port);
}
public void Start() {
Thread serverThread = new Thread(new ThreadStart(Run));
serverThread.Start();
}
private void Run()
{
running = true;
listener.Start();
while (running)
{
Console.WriteLine("Waiting for connection...");
TcpClient client = listener.AcceptTcpClient();
HandleClient(client);
Console.WriteLine("Client connected!");
}
running = false;
listener.Stop();
}
private void HandleClient(TcpClient client)
{
StreamReader reader = new StreamReader(client.GetStream());
String msg = "";
while (reader.Peek() != -1)
{
msg += reader.ReadLine()+"\n";
}
Console.WriteLine(msg);
Request req = Request.GetRequest(msg);
Response resp = Response.From(req);
resp.Post(client.GetStream());
}
}
And here is the main method:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting Serving on port 9000");
HTTPServer server = new HTTPServer(9000);
server.Start();
Console.ReadLine();
}
}
Disclaimer: You should never write a HTTP server directly with TcpClient for any production work. There are far too many specifications to be accounted for and C# has these built in to any Asp.Net web server you use.
That being said, for an exercise this is a matter of parsing the request in a specific way. You should be able to reference these questions to learn more about the details of multipart boundary:
What is http multipart request?
What should a Multipart HTTP request with multiple files look like?
Essentially, you will have to read a header from the http headers (Content-Type), and parse the value of boundary= to determine what is separating the key/value pairs of the multipart form in the request body. Once you've got the boundary you will have to parse the body of the request into the real key/value pairs of the form. From there, the contents of the uploaded file will be the value of whatever key the form submits it as.
Read more on the official W3 spec
Response.cs:
class Response
{
private Byte[] data = null;
private String status;
private String mime;
private Response(String status,String mime,Byte[] data)
{
this.status = status;
this.data = data;
this.mime = mime;
}
public static Response From(Request request)
{
if (request == null)
return MakeNullRequest();
if (request.type.Equals("POST"))
{
return UploadCompleteResponse(request);
}
return MakeFromExcel();
}
private static Response UploadCompleteResponse(Request request)
{ //I added on the rquest array the datapart which contains data
String data=request.data;
byte[] bytes = Encoding.ASCII.GetBytes("uploaded!!");
return new Response("ok 200","text/plain",bytes);
}
//private static Response MakeFromFile(FileInfo f)
//{
// // to do later
// //return new Response("200 ok", "text/html", d);
//}
//Retruning an excel file response
private static Response MakeFromExcel()
{
String file = Environment.CurrentDirectory + HTTPServer.EXCEL_DIR+"brains.xlsx";
Console.WriteLine(file);
FileInfo info = new FileInfo(file);
if (info.Exists)
{
FileStream fs = info.OpenRead();
BinaryReader read = new BinaryReader(fs);
Byte[] d = new Byte[fs.Length];
read.Read(d, 0, d.Length);
fs.Close();
return new Response("200 ok", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", d);
}
return PageNotFound();
}
private static Response MakeNullRequest()
{
String file = Environment.CurrentDirectory+HTTPServer.MSG_DIR +"400.html";
Console.WriteLine(file);
FileInfo info = new FileInfo(file);
FileStream fs=info.OpenRead();
BinaryReader read=new BinaryReader(fs);
Byte[] d = new Byte[fs.Length];
read.Read(d, 0, d.Length);
fs.Close();
return new Response("400 Bad Request", "text/html", d);
}
private static Response PageNotFound()
{
String file = Environment.CurrentDirectory + HTTPServer.MSG_DIR + "400.html";
FileInfo info = new FileInfo(file);
FileStream fs = info.OpenRead();
BinaryReader read = new BinaryReader(fs);
Byte[] d = new Byte[fs.Length];
read.Read(d, 0, d.Length);
return new Response("404 Not Found", "text/html", d);
}
public void Post(NetworkStream stream)
{
try
{
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(String.Format("{0} {1}\r\nServer: {2}\r\nContent-Type: {3}\r\nAccept-Ranges: 255 bytes\r\nContent-Length: {4}\r\n", HTTPServer.VERSION
, status, HTTPServer.NAME, mime, data.Length));
writer.Flush();
stream.Write(data, 0, data.Length);
stream.Flush();
stream.Close();
}catch(Exception ex){
}
}
}
Request.cs:
class Request
{
public String type { get; set; }
public String url { get; set; }
public String host { get; set; }
public String data { get; set; }
private Request(String type,String url,String host)
{
this.type = type;
this.url = url;
this.host = host;
}
private Request(String type, String url, String host,String data)
{
this.type = type;
this.url = url;
this.host = host;
this.data = data;
}
public static Request GetRequest(String request)
{
if (String.IsNullOrEmpty(request))
return null;
String[] tokens = request.Split(' ');
String type = tokens[0];
String url = tokens[1];
String host = tokens[4];
String data = "N/A";
if (tokens.Length >= 9)
{
data = tokens[8];
}
return new Request(type, url, host, data);
}
}
Secondly my android client was excpecting a response which is responsbody type not a plain text thats why the data was never sent....

CefSharp custom SchemeHandler

Iam using CefSharp's SchemeHandler in order to grab resources from my C# project like .css, .js or .png files using a custom url for example custom://cefsharp/assets/css/style.css
I've 2 custom classes in order to archive this.
First class, MyCustomSchemeHandlerFactory will be the one that handles the custom Scheme and it looks like this, where "custom" will be the custom scheme:
internal class MyCustomSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "custom";
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
return new MyCustomSchemeHandler();
}
}
The next class I've implemented is MyCustomSchemeHandler which will receive the call and output a response and it looks like this:
internal class MyCustomSchemeHandler : IResourceHandler
{
private static readonly IDictionary<string, string> ResourceDictionary;
private string mimeType;
private MemoryStream stream;
static MyCustomSchemeHandler()
{
ResourceDictionary = new Dictionary<string, string>
{
{ "/home.html", Properties.Resources.index},
{ "/assets/css/style.css", Properties.Resources.style}
};
}
public Stream Stream { get; set; }
public int StatusCode { get; set; }
public string StatusText { get; set; }
public string MimeType { get; set; }
public NameValueCollection Headers { get; private set; }
public Stream GetResponse(IResponse response, out long responseLength, out string redirectUrl)
{
redirectUrl = null;
responseLength = -1;
response.MimeType = MimeType;
response.StatusCode = StatusCode;
response.StatusText = StatusText;
response.ResponseHeaders = Headers;
var memoryStream = Stream as MemoryStream;
if (memoryStream != null)
{
responseLength = memoryStream.Length;
}
return Stream;
}
public bool ProcessRequestAsync(IRequest request, ICallback callback)
{
// The 'host' portion is entirely ignored by this scheme handler.
var uri = new Uri(request.Url);
var fileName = uri.AbsolutePath;
string resource;
if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource))
{
var resourceHandler = ResourceHandler.FromString(resource);
stream = (MemoryStream)resourceHandler.Stream;
var fileExtension = Path.GetExtension(fileName);
mimeType = ResourceHandler.GetMimeType(fileExtension);
callback.Continue();
return true;
}
else
{
callback.Dispose();
}
return false;
}
void GetResponseHeaders(IResponse response, out long responseLength, out string redirectUrl)
{
responseLength = stream == null ? 0 : stream.Length;
redirectUrl = null;
response.StatusCode = (int)HttpStatusCode.OK;
response.StatusText = "OK";
response.MimeType = mimeType;
}
bool ReadResponse(Stream dataOut, out int bytesRead, ICallback callback)
{
//Dispose the callback as it's an unmanaged resource, we don't need it in this case
callback.Dispose();
if (stream == null)
{
bytesRead = 0;
return false;
}
//Data out represents an underlying buffer (typically 32kb in size).
var buffer = new byte[dataOut.Length];
bytesRead = stream.Read(buffer, 0, buffer.Length);
dataOut.Write(buffer, 0, buffer.Length);
return bytesRead > 0;
}
bool CanGetCookie(Cookie cookie)
{
return true;
}
bool CanSetCookie(Cookie cookie)
{
return true;
}
void Cancel()
{
}
}
Inside this class I've defined a custom resource dictionary which will dictate what file from the resources will be used, so as I stated in the first example, custom://cefsharp/assets/css/style.css should load the resource Properties.Resources.style, the problem is that nothing gets loaded once I enter to the specific url, I've tried to output the mimeType and It works but somehow the file itself won't output correctly. Is there something wrong with my implementation?
Additionaly I've tried to output the raw file in the form of:
if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource))
{
MessageBox.Show(resource);
}
And it outputs the correct file without any problems.
To load the custom Scheme I use the following code before initializing CefSharp:
var settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = MyCustomSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new MyCustomSchemeHandlerFactory()
});
The above classes were based on the following links:
MyCustomSchemeHandlerFactory: FlashResourceHandlerFactory.cs
MyCustomSchemeHandler: CefSharpSchemeHandler.cs and ResourceHandler.cs
Since Cefsharp changed a bit in last few months here is an updated and easier way of handling 'file' protocol. I wrote blog post on this matter.
What you want to add is your scheme handler and its factory:
using System;
using System.IO;
using CefSharp;
namespace MyProject.CustomProtocol
{
public class CustomProtocolSchemeHandler : ResourceHandler
{
// Specifies where you bundled app resides.
// Basically path to your index.html
private string frontendFolderPath;
public CustomProtocolSchemeHandler()
{
frontendFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "./bundle/");
}
// Process request and craft response.
public override bool ProcessRequestAsync(IRequest request, ICallback callback)
{
var uri = new Uri(request.Url);
var fileName = uri.AbsolutePath;
var requestedFilePath = frontendFolderPath + fileName;
if (File.Exists(requestedFilePath))
{
byte[] bytes = File.ReadAllBytes(requestedFilePath);
Stream = new MemoryStream(bytes);
var fileExtension = Path.GetExtension(fileName);
MimeType = GetMimeType(fileExtension);
callback.Continue();
return true;
}
callback.Dispose();
return false;
}
}
public class CustomProtocolSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "customFileProtocol";
public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
return new CustomProtocolSchemeHandler();
}
}
}
And then register it before calling Cef.Initialize:
var settings = new CefSettings
{
BrowserSubprocessPath = GetCefExecutablePath()
};
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CustomProtocolSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CustomProtocolSchemeHandlerFactory()
});
If you simply need to return a string, then you can use ResourceHandler.FromString(html, mimeType). For this you just need to implement the ISchemeHandlerFactory.
https://github.com/cefsharp/CefSharp/blob/cefsharp/47/CefSharp/ResourceHandler.cs#L98
Example reading from a file https://github.com/cefsharp/CefSharp/blob/cefsharp/47/CefSharp.Example/CefSharpSchemeHandlerFactory.cs#L17 which can be translated to reading from a string quite simply.

Creating an instance of HttpPostedFileBase for unit testing

I need to create an instance of HttpPostedFileBase class object and pass it to a method, but I cannot find any way to instantiate it. I am creating a test case to test my fileupload method.
This is my method which takes an HttpPostedFileBase object. I need to call it from my test case class. I am not using any mock library.
Is there a simple way to do this?
[HttpPost]
public JsonResult AddVariation(HttpPostedFileBase file, string name, string comment, string description, decimal amount, string accountLineTypeID)
{
var accountLineType = _fileService.GetAccountLineType(AccountLineType.Debit);
if (Guid.Parse(accountLineTypeID) == _fileService.GetAccountLineType(AccountLineType.Credit).AccountLineTypeID)
{
amount = 0 - amount;
}
var info = new File()
{
FileID = Guid.NewGuid(),
Name = name,
Description = description,
FileName = file.FileName,
BuildID = Guid.Parse(SelectedBuildID),
MimeType = file.ContentType,
CreatedUserID = CurrentUser.UserID,
UpdatedUserID = CurrentUser.UserID,
Amount = amount,
};
var cmmnt = new Comment()
{
CommentDate = DateTime.Now,
CommentText = comment,
FileID = info.FileID,
UserID = CurrentUser.UserID
};
_variationService.AddVariation(info, file.InputStream);
_variationService.AddComment(cmmnt);
return Json("Variation Added Sucessfully", JsonRequestBehavior.AllowGet);
}
HttpPostedFileBase is an abstract class so therefore it cannot be directly instantiated.
Create a class that derives from HttpPostedFileBase and returns the values you are looking for.
class MyTestPostedFileBase : HttpPostedFileBase
{
Stream stream;
string contentType;
string fileName;
public MyTestPostedFileBase(Stream stream, string contentType, string fileName)
{
this.stream = stream;
this.contentType = contentType;
this.fileName = fileName;
}
public override int ContentLength
{
get { return (int)stream.Length; }
}
public override string ContentType
{
get { return contentType; }
}
public override string FileName
{
get { return fileName; }
}
public override Stream InputStream
{
get { return stream; }
}
public override void SaveAs(string filename)
{
throw new NotImplementedException();
}
}
I think that #BenjaminPaul has the best answer - but wanted to add this in case anyone else is looking to test the content length on the MyTestPostedFileBase object.
I created the class as is outlined above and then passing a stream that is filled with random bytes - this allows the `MyTestPostedFileBase.ContentLength to return a testable value that I needed.
byte[] byteBuffer = new Byte[10];
Random rnd = new Random();
rnd.NextBytes(byteBuffer);
System.IO.MemoryStream testStream = new System.IO.MemoryStream(byteBuffer);
and then instantiate it:
var TestImageFile = new MyTestPostedFileBase(testStream, "test/content", "test-file.png");

Categories

Resources