|
give me better suggetions
|
|
|
|
|
Make a .CS file with name of ImportExcel.CS
:----
public class FileExt : ValidationAttribute
{
public string Allow;
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
string extension = ((System.Web.HttpPostedFileBase)value).FileName.Split('.')[1];
if (Allow.Contains(extension))
return ValidationResult.Success;
else
return new ValidationResult(ErrorMessage);
}
else
return ValidationResult.Success;
}
}
public class ImportExcel
{
[Required(ErrorMessage = "Please select file")]
[FileExt(Allow = ".xls,.xlsx", ErrorMessage = "Only excel file")]
public HttpPostedFileBase file { get; set; }
}
And Add this code to your controller
:-----
public ActionResult ImportExcel()
{
return View();
}
[HttpPost]
public ActionResult importexcel(ImportExcel importExcel)
{
if (ModelState.IsValid)
{
string path = Server.MapPath("~/library/ExcelFile/" + importExcel.file.FileName);
importExcel.file.SaveAs(path);
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" + path + "';Extended Properties='Excel 12.0;'";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
string tableName = excelConnection.GetSchema("Tables").Rows[0]["TABLE_NAME"].ToString();
excelConnection.Close();
OleDbCommand cmd = new OleDbCommand("Select * from [" + tableName + "]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
sqlBulk.DestinationTableName = "ExcelFile";
sqlBulk.ColumnMappings.Add("Userid", "Userid");
sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.ColumnMappings.Add("TelephoneNo", "TelephoneNo");
sqlBulk.ColumnMappings.Add("Address", "Address");
sqlBulk.ColumnMappings.Add("EmailAddress", "EmailAddress");
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
ViewBag.Result = "Successfully Imported";
}
return View();
}
And create view page of ImportExcel method with name of ImportExcel.cshtml and add this code
:-----
@model Models.GeneralModel.ImportExcel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>ImportExcel</title>
</head>
<body>
<div style="float:right">
<h4>@ViewBag.Result</h4>
@using (Html.BeginForm("ImportExcel", "NewCustomer", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.TextBoxFor(m => m.file, new { type = "file" })
<button id="submitButton" type="submit">Submit</button>
@Html.ValidationMessageFor(model => model.file)
}
</div>
</body>
</html>
|
|
|
|
|
You do realise we can all see you talking to yourself, don't you?
Quote:
string extension = ((System.Web.HttpPostedFileBase)value).FileName.Split('.')[1];
Lots of problems with that line. For example, what if the uploaded file doesn't contain an extension? What if it contains multiple "." characters? What if the extension is .lsx ? Etc.
Try:
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var file = value as System.Web.HttpPostedFileBase;
if (file != null)
{
string extension = System.IO.Path.GetExtension(file.FileName);
string[] allowedExtensions = Allow.Split(',');
if (!Array.Exists(allowedExtensions, ext => string.Equals(ext, extension, StringComparison.OrdinalIgnoreCase)))
{
return new ValidationResult(ErrorMessage);
}
}
return ValidationResult.Success;
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
i have been trying to get my program to start but it keeps refusing to.can anyone help me find a solution to the error below.thanks
This site can’t be reached localhost refused to connect.
Search Google for localhost 58962
ERR_CONNECTION_REFUSED
|
|
|
|
|
You're trying to access a web server running on port 58962 of your local machine, but there is on web server running there. We can't access your machine so we can't tell you why that is. Typically you only use non-standard ports when running the site in debug mode from Visual Studio. So either you are trying to access your site outside of VS, or VS's internal web server isn't working for some reason.
|
|
|
|
|
I am new to ASP.NET MVC, getting error at below code :
<div id="wrapper" style="background-color:#fff;">
<nav class="navbar navbar-default navbar-cls-top " role="navigation" style="margin-bottom: 0">
<div class="navbar-header">
<a class="navbar-brand" href="/Home/EmployeeDashboard" target="_blank">
@{
string comnameup = "";
using (PMEntities dc = new PMEntities())
{
var data = dc.tblGenerals.SingleOrDefault();
comnameup = data.CompanyName;
@comnameup
}
}
</a>
</div>
also adding connection string :
<connectionStrings>
<add name="PMEntities" connectionString="metadata=res://*/PMData.csdl|res://*/PMData.ssdl|res://*/PMData.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost\SQLEXPRESS;initial catalog=eee;integrated security=SSPI;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
|
|
|
|
|
You need to look at the full details of the exception, including the InnerException , to see what the error is.
NB: SingleOrDefault will return null if there are no records. When you try to read the property on the next line, you could potentially get a NullReferenceException . It would be better to use Single in this instance.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Is anyone help me out for import tables data from PDF file and show them on front using C#,.Net ,please suggest me a piece of code for random column and row and also recommend library OR 3RD party such as RadDocumentProcessing,telerikdocument processing ,Itextsharp etc .
|
|
|
|
|
You already have the names of 3rd party libraries. If you go and study them you should be able to decide which one suits your needs.
|
|
|
|
|
yes ok but i need a piece of code to extract tables from pdf and show on datatable in c#.
|
|
|
|
|
Yes, but you need to write the code first.
|
|
|
|
|
checkout their documentation
=====================================================
The grass is always greener on the other side of the fence
|
|
|
|
|
Problem
What layers required for make asp.net core 2 project for prevent repeat data ?
I need to make new project with asp.net core 2.1 using Generics and i have more questions
How many layers used ?
which layer must have initialize of connections ?
|
|
|
|
|
|
Anything related to data and database connection should be placed inside your Data Access layer. Anything related to Business rules and validation should be placed inside your Business Layer or whatever you want to call it.
|
|
|
|
|
In most of our web services I use the repository pattern. Isolating data access from business rules from controller/services.
Here is a link to some docs on Microsoft. This isn't specific to Dotnet Core, but the same pattern can still be applied.
|
|
|
|
|
I want c# code for image compression. Which can compress image without quality loss. I want to implement it in asp.net. Can you give me the code for compression
|
|
|
|
|
Google will find you samples.
|
|
|
|
|
Hi,
I have the following Web Api methods, I want to call and test my methods from a mocking application, if possible any code, following are my Web api methods:
[Produces("application/json")]
[Route("api/Employee")]
public class EmployeeController : Controller
{
EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();
[HttpGet("[action]")]
public IEnumerable<TblEmployee> Index()
{
return objemployee.GetAllEmployees();
}
[HttpPost]
public int Create(TblEmployee employee)
{
return objemployee.AddEmployee(employee);
}
[HttpGet("{id}")]
public TblEmployee Details(int id)
{
return objemployee.GetEmployeeData(id);
}
[HttpPut("{id}")]
public int Edit(int id, TblEmployee employee)
{
return objemployee.UpdateEmployee(employee);
}
[HttpDelete("{id}")]
public int Delete(int id)
{
return objemployee.DeleteEmployee(id);
}
[HttpGet("[action]")]
public IEnumerable<TblCities> GetCityList()
{
return objemployee.GetCities();
}
}
|
|
|
|
|
Mocking in tests is to replace the access of external resources with other things like hard-coded values so that you can test the business logic in your app independent of other things. So the short answer is that you would probably mock the entire web EmployeeController so that any code that calls the webapi would call your mocked controller instead.
If it is the controller itself you want to test then you would mock out the data access, in this case your EmployeeDataAccessLayer, so you could call the methods on your controller from a unit test without needing database access. However your controller methods don't really do anything, there is no logic in them, they just act as an interface to calls on the data access layer. So long story short, there is nothing here worth testing.
|
|
|
|
|
xUnit unit testing framework has the ability to use external data sources for unit testing.
For example you could create a spreadsheet or a database table will a randomized set of data that can be used as the mocked source data for your unit testing.
Here is a link to a blog post discussing it.
|
|
|
|
|
When we are using Microsoft Test runner we use Moq to build out our mock data layer. We recently have been switching to xUnit, I haven't tried using Moq with it yet.
Here is the link to the Moq GitHub repo, there's good info here.
|
|
|
|
|
Hi,
I am trying to learn React.Js, I am trying to start with a small Hello World application, the problem is, I am not able to integrate React.Js with with MVC that I have or even MVVM, what I want is, I write some jsx file I want to execute it part of my MVC application. Just like I used to write code for my previous applications and just execute them when I press F5, am I doing anything wrong here? Can't I write jsx files as part of my MVC application and call them and execute them just by pressing F5?
Any guide for me for integrating my MVC or Web Api application with React.Js or Angular 2.0 anything is fine, I am getting very frustrated because there very less help for executing React or Angular as part of Visual Studio, I am searching a lot, but I couldn't execute even a single link successfully.
Need some help, if anything that can explain me those basic things to execute at least one application successfully - please.
I put some money in Udemy for react that guy is teaching more of Passport than react and ASP.Net MVC full stack - very sad.
Any help a link or a suggestion anything helps me, because even the errors are not descriptive they are not explaining me why something is failing - frustrated, please any help.
|
|
|
|
|
Have you created your project type as a Web Application type? Other types won't fire up the internal IIS Express server. This is moot if you're rolling with a stand-alone web server, but that doesn't sound like the case.
If you're using MVC, is your base jsx being served by your home controller? If not, that would be a problem, but I frankly wouldn't use MVC.NET for this, I would use WebAPI with a static files section.
You might get some ideas for URL management at:
Serving URLs with File Extensions in an ASP.NET MVC Application - Rick Strahl's Web Log
"Never attribute to malice that which can be explained by stupidity."
- Hanlon's Razor
|
|
|
|
|
I applaud your ambition on learning React or Angular, a path I took last year and started out integrating my learning with a MVC project which was quite a steep learning curve. Yes you can integrate ReactJs and Angular into a MVC project, and even a .Net Core project, but you have to change the way you think about programming and .Net.
Keep in mind that ReactJs and Angular doesn't require a .Net environment. .Net is just used as a back end to feed data to the client script pages. In hindsight, I found using .Net for the back end much harder to deal with than using say pure Java or Typescript for the whole thing.
I would like to seed your ambition with some files and code, but It's just too large to post here.
I actually build a large project that uses ReactJs both client and server side and works great.
But rendering ReactJs on the server side requires a library of JavaScriptEngines which gets complicated.
Start with the client side first, then work your way to the server side.
But this is where I started.
React integration for ASP.NET MVC | ReactJS.NET
Follow the tutorial
If it ain't broke don't fix it
Discover my world at jkirkerx.com
|
|
|
|