'System.Web.HttpPostedFileBase' does not contain a definition for 'HasFile' and no extension method 'HasFile' - asp.net-mvc-3

I am following http://www.mikesdotnetting.com/Article/125/ASP.NET-MVC-Uploading-and-Downloading-Files. Using VS2010, ASP.NET 4.0, MVC3 in C# with ADO.NET in SQL Server 2008R2. I am getting the following error message...
'System.Web.HttpPostedFileBase' does not contain a definition for 'HasFile' and no extension method 'HasFile' accepting a first argument of type 'System.Web.HttpPostedFileBase' could be found (are you missing a using directive or an assembly reference?)
I searched through Stackflow, there was something about including System.Web.Abstractions. I included this and I still getting the error.
Thanks in advance if anyone can tell me the solution.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Data.SqlClient;
using System.Web.Helpers;
namespace MvcApplication1.Controllers
{
public class MyController : Controller
{
//
// GET: /My/
public ActionResult Index()
{
foreach (string upload in Request.Files)
{
if (!Request.Files[upload].HasFile()) continue;
string mimeType = Request.Files[upload].ContentType;
Stream fileStream = Request.Files[upload].InputStream;
string fileName = Path.GetFileName(Request.Files[upload].FileName);
int fileLength = Request.Files[upload].ContentLength;
byte[] fileData = new byte[fileLength];
fileStream.Read(fileData, 0, fileLength);
const string connect = #"Server=.\SQLExpress;Database=FileTest;Trusted_Connection=True;";
using (var conn = new SqlConnection(connect))
{
var qry = "INSERT INTO FileStore (FileContent, MimeType, FileName) VALUES (#FileContent, #MimeType, #FileName)";
var cmd = new SqlCommand(qry, conn);
cmd.Parameters.AddWithValue("#FileContent", fileData);
cmd.Parameters.AddWithValue("#MimeType", mimeType);
cmd.Parameters.AddWithValue("#FileName", fileName);
conn.Open();
cmd.ExecuteNonQuery();
}
}
return View();
}
public FileContentResult GetFile(int id)
{
SqlDataReader rdr; byte[] fileContent = null;
string mimeType = ""; string fileName = "";
const string connect = #"Server=.\SQLExpress;Database=FileTest;Trusted_Connection=True;";
using (var conn = new SqlConnection(connect))
{
var qry = "SELECT FileContent, MimeType, FileName FROM FileStore WHERE ID = #ID";
var cmd = new SqlCommand(qry, conn);
cmd.Parameters.AddWithValue("#ID", id);
conn.Open();
rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
rdr.Read();
fileContent = (byte[])rdr["FileContent"];
mimeType = rdr["MimeType"].ToString();
fileName = rdr["FileName"].ToString();
}
}
return File(fileContent, mimeType, fileName);
}
}
}
in the Helpers folder I have the Helper class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcApplication1.Models
{
public static class Helper
{
public static bool HasFile(this HttpPostedFileBase file)
{
return (file != null && file.ContentLength > 0) ? true : false;
}
}

You need to add a using statement to your MyController code file, as that is what is required when you want to use an extension method (it needs to be in scope):
using MvcApplication1.Models;

Related

Giving this error XLWorkbook': type used in a using statement must be implicitly convertible to 'System.IDisposable'

This code giving a error XLWorkbook': type used in a using statement must be implicitly convertible to 'System.IDisposable' how to resolve it.
using (XLWorkbook wb = new XLWorkbook()) this line giving the error.
I have also added assembly reference ClosedXML but its not working
Is there any way to resolved this issue?
using System.Web;
using System.Data.SqlClient;
using System.IO;
using ClosedXML.Excel;
using System.Web.Mvc;
using SHIPVICTUAL.Controllers;
namespace SHIPVICTUAL.Controllers
{
public class shipController : Controller
{
// GET: ship
public ActionResult Index()
{
return View();
}
public ActionResult ExportToExcel(FormCollection formCollection)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
try
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings.Get("DBShipVictual"));
cmd = new SqlCommand("Reports_rdlc", con);
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
if (dt.Rows.Count > 0)
{
dt.TableName = "Report";
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-disposition", "attachment;ReportList.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
{
}
}
}
catch
{
}
return View();
}
}
} ```

ASP .NET Core MVC upload text files to an existing db with logged in user foreign key

Now I'm working on my Cloud Storage Project and the main idea of it is to use authorization system provided by Identity Framework and let users upload and download files to an existing table (AspNetFiles - created by me). Moreover, it's important to save all uploaded files to folder in project directory (~/wwwroot/Files/). Now I'm on the way to build upload files system, so:
I made new table AspNetFiles in the direction of other AspNet... tables provided by Identity and Upload-Database NuGet func after creating Migration;
Created new "WorkSpaceController" in "~/Controllers/" for managing files (upload, sort in grid and download) for every logged in user;
Created functions for FileManager view (this is the page for displaying upload, grid and delete files experience) + some other functions for saving files in wwwroot, getting logged in user "Id" and etc.
My dbo.AspNetFiles has the next columns:
FileID (PK, int, not null) with identity (1,1) parameter
FileName (varchar(60), not null)
FileData (varbinary(max), not null) - for store uploaded file data in table
FileExtension (varchar(15), not null)
FileDate (varchar(20), not null)
Id (FK, nvarchar(450), not null) as the primary key of logged in user from dbo.AspNetUsers
After debugging application I get some errors:
InvalidCastException: Object must implement IConvertible. System.Convert.ChangeType(object value, Type conversionType, IFormatProvider provider)
InvalidCastException: Failed to convert parameter value from a FormFile to a Byte[]. Microsoft.Data.SqlClient.SqlParameter.CoerceValue(object value, MetaType destinationType, out bool coercedToDataFeed, out bool typeChanged, bool allowStreaming)
So yeah I know that I use a IFormFile type for "FileData: from "FileDataModel" but it's for saving file locally in project folder as I mentioned previously (~/wwwroot/Files/).
I'm a new user in ASP.NET Core, so I tried many ways from YouTube and articles of how to save files locally and in table of SQL database, but I didn't find any way to do it both and save files with existing Identity Framework with connection to logged in user by foreing key "Id" in table for upload files and download to pc.
Hope u can help me with it. Don't gudge too much :D
This is the code:
FileDataModel (in ~/Models/)
namespace TextCloud.Models
{
public class FileDataModel
{
public string FileName { get; set; }
public IFormFile FileData { get; set; }
public string FileExtension { get; set; }
public string FileDate { get; set; }
public string Id { get; set; }
}
}
WorkSpaceController (in ~/Controllers/)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Configuration;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Protocols;
using System.Data;
using System.Data.SqlClient;
using TextCloud.Models;
using Microsoft.Data.SqlClient;
using Microsoft.AspNetCore.Hosting;
using TextCloud.Areas.Identity.Data;
namespace TextCloud.Controllers
{
public class WorkSpaceController : Controller
{
private readonly IWebHostEnvironment webHostEnvironment;
private readonly UserManager<TextCloudUser> _userManager;
public WorkSpaceController(IWebHostEnvironment webHostEnvironment, UserManager<TextCloudUser> userManager)
{
this.webHostEnvironment = webHostEnvironment;
_userManager = userManager;
}
public IConfigurationRoot GetConnection()
{
var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appSettings.json").Build();
return builder;
}
public IActionResult FileManager()
{
return View();
}
[HttpPost]
public IActionResult FileManager(FileDataModel model)
{
if (ModelState.IsValid)
{
string uniqueFileName = null;
if (model.FileData != null)
{
DateTime FileDate = DateTime.Now;
model.FileDate = FileDate.ToString("dd/MM/yyyy");
model.Id = _userManager.GetUserId(HttpContext.User);
string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Storage");
uniqueFileName = Guid.NewGuid().ToString() + "_" + model.FileData.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
model.FileExtension = Path.GetExtension(model.FileName);
model.FileName = model.FileData.FileName;
if (model.FileDate != null)
{
string connctn = "Server=DESKTOP-LRLFA5K\\SQLEXPRESS;Database=TextCloud;Trusted_Connection=True;MultipleActiveResultSets=true";
SqlConnection con = new SqlConnection(connctn);
con.Open();
string commnd = "insert into AspNetFiles(FileName, FileData, FileExtension, FileDate, Id) values (#FileName, #FileData, #FileExtension, #FileDate, #Id)";
SqlCommand com = new SqlCommand(commnd, con);
com.Parameters.Add("#FileName", SqlDbType.VarChar).Value = model.FileName;
com.Parameters.Add("#FileData", SqlDbType.VarBinary).Value = model.FileData;
com.Parameters.Add("#FileExtension", SqlDbType.VarChar).Value = model.FileExtension;
com.Parameters.Add("#FileDate", SqlDbType.VarChar).Value = model.FileDate;
com.Parameters.Add("#Id", SqlDbType.NVarChar).Value = model.Id;
com.ExecuteScalar();
con.Close();
model.FileData.CopyTo(new FileStream(filePath, FileMode.Create));
}
}
}
return View();
}
}
}
According to your description, I found you directly pass the iformfile to the FileData. You should read the byte array from the iformfile, then store the byte arrary into the database.
More details, you could refer to below codes:
[HttpPost]
public IActionResult FileManager(FileDataModel model)
{
if (ModelState.IsValid)
{
string uniqueFileName = null;
if (model.FileData != null)
{
DateTime FileDate = DateTime.Now;
model.FileDate = FileDate.ToString("dd/MM/yyyy");
model.Id = _userManager.GetUserId(HttpContext.User);
string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Storage");
uniqueFileName = Guid.NewGuid().ToString() + "_" + model.FileData.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
model.FileExtension = Path.GetExtension(model.FileName);
model.FileName = model.FileData.FileName;
if (model.FileDate != null)
{
using (MemoryStream stream = new MemoryStream())
{
model.FileData.OpenReadStream().CopyTo(stream);
string connctn = #"Server=DESKTOP-LRLFA5K\\SQLEXPRESS;Database=TextCloud;Trusted_Connection=True;MultipleActiveResultSets=true";
SqlConnection con = new SqlConnection(connctn);
con.Open();
string commnd = "insert into AspNetFiles(FileName, FileData, FileExtension, FileDate, Id) values (#FileName, #FileData, #FileExtension, #FileDate, #Id)";
SqlCommand com = new SqlCommand(commnd, con);
com.Parameters.Add("#FileName", SqlDbType.VarChar).Value = model.FileName;
com.Parameters.Add("#FileData", SqlDbType.VarBinary).Value = stream.ToArray();
com.Parameters.Add("#FileExtension", SqlDbType.VarChar).Value = model.FileExtension;
com.Parameters.Add("#FileDate", SqlDbType.VarChar).Value = model.FileDate;
com.Parameters.Add("#Id", SqlDbType.NVarChar).Value = model.Id;
com.ExecuteScalar();
con.Close();
stream.CopyTo(new FileStream(filePath, FileMode.Create));
}
}
}
}
return View();
}

Call is not passing from controller to model in web api

I am totally new in web api. I have created web api simply to retrive data from oracle DB with the help of few articles which i found on internet. I am trying to find out error since morning but no success till now. When i try to run the code, it dont give any error or anything. Debugger passed to my DB class and stops. Below is my controller code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.Data.SqlClient;
namespace iLearnWebApi.Controllers
{
public class ValuesController : ApiController
{
DAL.DBAccess dblayer = new DAL.DBAccess();
public DataSet Getrecord(int programid)
{
DataSet ds = dblayer.GetRecordbyid(programid);
return ds;
}
} }
And below is my DBClass code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Configuration;
using System.Data.Odbc;
using Oracle.ManagedDataAccess.Client;
namespace iLearnWebApi.DAL
{
public class DBAccess
{
OracleParameter[] _objOraParam;
OracleConnection con = new OracleConnection();
//--- Get Records By Program ID
public DataSet GetRecordbyid(int progid)
{
DataSet ds = new DataSet();
try
{
_objOraParam = new OracleParameter[2];
_objOraParam[0] = new OracleParameter("p_Program_ID", OracleDbType.Int32);
_objOraParam[0].Direction = ParameterDirection.Input;
_objOraParam[0].Value = progid;
_objOraParam[1] = new OracleParameter("RCT_OUT", OracleDbType.RefCursor);
_objOraParam[1].Direction = ParameterDirection.Output;
ds = ExecuteDataset(con, CommandType.StoredProcedure, "ILS_USP_PROGRAM_DATA", _objOraParam);
}
catch (Exception ex)
{
LogError("GetRecordbyid", ex.Message.ToString());
throw ex;
}
finally
{
con.Close();
}
return ds;
}
// Execute Data
private DataSet ExecuteDataset(OracleConnection con, CommandType procname, string commandText, params OracleParameter[] objOraParam)
{
//create a command and prepare it for execution
OracleCommand cmd = new OracleCommand();
PrepareCommand(cmd, con, (OracleTransaction)null, procname, commandText, objOraParam);
//create the DataAdapter & DataSet
OracleDataAdapter da = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the DataSet using default values for DataTable names, etc.
da.Fill(ds);
cmd.Dispose();
//return the dataset
return ds;
}
//---- Used To Prepare Oracle command
private void PrepareCommand(OracleCommand command, OracleConnection connection, OracleTransaction transaction, CommandType commandType, string commandText, OracleParameter[] commandParameters)
{
//if the provided connection is not open, we will open it
string con_string = ConfigurationManager.ConnectionStrings["OracleConnectionString"].ConnectionString;
if (connection.State != ConnectionState.Open)
{
connection.ConnectionString = DecryptString(con_string, "CFSENC");
connection.Open();
}
//associate the connection with the command
command.Connection = connection;
//set the command text (stored procedure name or Oracle statement)
command.CommandText = commandText;
//if we were provided a transaction, assign it.
if (transaction != null)
{
command.Transaction = transaction;
}
//set the command type
command.CommandType = commandType;
//attach the command parameters if they are provided
if (commandParameters != null)
{
AttachParameters(command, commandParameters);
}
return;
}
// Used For Attaching Parameter To Command
private void AttachParameters(OracleCommand command, OracleParameter[] commandParameters)
{
foreach (OracleParameter p in commandParameters)
{
//check for derived output value with no value assigned
if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
{
p.Value = DBNull.Value;
}
command.Parameters.Add(p);
}
}
// Used For Decryption Of Encrypted String
private string DecryptString(string con_string, string key)
{
byte[] plainBytes = null;
try
{
string passWord = key;
string strInput = con_string;
byte[] encryptBytes = Convert.FromBase64String(strInput);
MemoryStream ms = new MemoryStream(strInput.Length);
//Using triple des for decryption
TripleDESCryptoServiceProvider tDesCsp = new TripleDESCryptoServiceProvider();
// Creating decryption IV and Key using the key supplied by the user
tDesCsp.IV = new byte[8];
PasswordDeriveBytes pdb = new PasswordDeriveBytes(passWord, new byte[0]);
tDesCsp.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
CryptoStream deEnStream = new CryptoStream(ms, tDesCsp.CreateDecryptor(), CryptoStreamMode.Write);
//write the decrypted data to the stream
deEnStream.Write(encryptBytes, 0, encryptBytes.Length);
deEnStream.FlushFinalBlock();
plainBytes = new byte[ms.Length];
ms.Position = 0;
//reading the decrypted stream and write it into the byte array
ms.Read(plainBytes, 0, (int)ms.Length);
deEnStream.Close();
}
catch (Exception err)
{
string sErr = err.ToString();
throw new Exception("Error decrypting string.");
}
return Encoding.UTF8.GetString(plainBytes);
}
// For Writing Log Files
private void LogError(string header, string error)
{
string strPath;
string strActualError;
StreamWriter objErrWriter;
DateTime objDt = DateTime.Now;
string strDate;
strDate = objDt.ToString("ddMMyyyy");
try
{
// Get Actual Path of "Error" stored in Web.config
strPath = ConfigurationManager.AppSettings["sPathErrorLog"];
//Generates Path & LogFile Name of ErrorLog
strPath = strPath + strDate + ".log";
// Generates Error Message
strActualError = DateTime.Now + " : " + header + " : " + error;
// Creation of File.
objErrWriter = new StreamWriter(strPath, true, System.Text.Encoding.ASCII);
objErrWriter.WriteLine("");
objErrWriter.WriteLine(strActualError);
objErrWriter.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}}
Can anyone please tell me what mistake i have done in above code.
This sounds like a routing issue (without seeing your route config).
Try changing: public DataSet Getrecord(int programid)
To: public DataSet Get(int id)
And call: localhost:60908/api/Values/1

Telerik Data Access - Argument Null Exception (ConverterName)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VideoWebsite.DataAccess;
namespace VideoWebsite.Models
{
public class DatabaseModel
{
public int DatabaseID { get; set; }
public string DatabaseName { get; set; }
}
public class DatabaseModelAccess
{
public static IEnumerable<DatabaseModel> All()
{
string queryString = #"SELECT 1 as DatabaseID, 'test' as DatabaseName";
using (EntitiesModelA2 dbContext2 = new EntitiesModelA2())
{
IEnumerable<DatabaseModel> result = dbContext2.ExecuteQuery<DatabaseModel>(queryString); //Exception occurs here
return result;
}
}
}
}
I am trying to materialize the non persistent type.
I am using the postgres database to generate the EntitiesModelA2.
From Telerik Data Access perspective, the error appears because the query does not have a FROM clause (it does not comply to the basic syntax for SELECT statements).
You can execute it like this:
Option 1
using (EntitiesModelA2 dbContext = new EntitiesModelA2())
{
using (IDbConnection connect = dbContext.Connection)
{
using (IDbCommand command = connect.CreateCommand())
{
command.CommandText = "SELECT 1 as DatabaseID, 'test' as DatabaseName FROM ExistingTableName";
using (IDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var result = new DatabaseModel();
result.DatabaseID = reader.GetInt32(0);
result.DatabaseName = reader.GetString(1);
//do something with the result
}
}
}
}
}
Option 2
using (EntitiesModelA2 dbContext = new EntitiesModelA2())
{
var result = dbContext.ExecuteQuery<DatabaseModel>("SELECT 1 as DatabaseID, 'test' as DatabaseName FROM ExistingTableName");
}

The name does not exist in the current context

I'm trying to upload files to Oracle database Using C# vs2012. Its my first time I do so especially with Oracle. I just followed an example I found online but I got some errors before I even run the codes showing me that some of the type or name spaces don't exist.
The example I followed : Blob Example
Here are the codes that are underlined red in my Resources_to_upload.aspx.cs
objCmd
objConn
My code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
public partial class Resources_to_upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void cmdUpload_Click(object sender, EventArgs e)
{
try
{
if (fileUploadDocument.PostedFile.ContentLength > 0)
{
// Get the File name and Extension
string FileName = Path.GetFileName(fileUploadDocument.PostedFile.FileName);
string FileExtension = Path.GetExtension(fileUploadDocument.PostedFile.FileName);
//
// Extract the content of the Document into a Byte array
int intlength = fileUploadDocument.PostedFile.ContentLength;
Byte[] byteData = new Byte[intlength];
fileUploadDocument.PostedFile.InputStream.Read(byteData, 0, intlength);
//
// Save the file to the DB
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
object Conn = new OracleConnection(strConn);
//
StringBuilder strQueryBuilder = new StringBuilder("INSERT INTO RESOURCES(RESOURCES_ID, FILE_NAME, TYPE, RESOURCE_FILE) VALUES (");
strQueryBuilder.Append("'1', ");
strQueryBuilder.Append("'" + FileName + "', ");
strQueryBuilder.Append("'" + FileExtension + "', ");
strQueryBuilder.Append(" :RESOURCE_FILE)");
String strQuery = strQueryBuilder.ToString();
//
OracleParameter blobParameter = new OracleParameter();
blobParameter.ParameterName = "Resources_FILE";
blobParameter.OracleType = OracleType.Blob;
blobParameter.Direction = ParameterDirection.Input;
blobParameter.Value = byteData;
objCmd = new OracleCommand(strQuery, objConn);
objCmd.Parameters.Add(blobParameter);
//
objConn.Open();
objCmd.ExecuteNonQuery();
objConn.Close();
//
lblMsg.Text = "Document Uploaded Succesfully";
}
}
catch (Exception ex)
{
lblMsg.Text = " Error uploading Document: " + ex.Message.ToString();
}
}
}
Please help solve this issue. Thank you
StringBuilder is in the System.Text namespace. So you can either reference it explicitly:
System.Text.StringBuilder strQueryBuilder ...
Or add a using directive to the file:
using System.Text
...
StringBuilder strQueryBuilder ...
As for objCmd and objConn, where do you define those? They're not created in the code you posted. You do create a connection object here:
object Conn = new OracleConnection(strConn);
Maybe you mean to use Conn instead of objConn? But you don't create a command object anywhere. You need to declare and instantiate variables before you can use them.

Resources