ASP.NET DynamicData Import Datas from Excel - asp.net-dynamic-data

I am using ASP.NET DynamicData v4.5 to allow admin to insert/update the records in the database.
My requirement is, -- Allow admin to import records for table from EXCEL file.
Source for the table may be available in excel files also. so i want admin to import data from file.
Is there any way i can achieve this in DynamicData ?

Yes you can do it, I've done it many times.
There is no built-in feature in Dynamic Data doing this but that's not a problem since it's pretty easy to implement.
The fact that you use ASP.NET Dynamic Data (like I do) is not really important for this task. As you probably know, you can create a regular ASP.NET form within a Dynamic Data project. You can also use a folder named /DynamicData/CustomPages to customize a Dynamic Data page. I suggest creating a new regular ASP.NET form called ImportingTool.aspx where your users will be able to import spreadsheets into your database. Once imported, they can use other dynamic data pages to edit the data.
Here is what you will need :
1- You need the user to upload a file, you will need
asp:fileupload or ajaxToolkit:AjaxFileUpload
2- You need to open that file, it will look like :
public void Import(FileUpload fileUpload)
{
if (fileUpload.HasFile)
{
string FileName = Path.GetFileName(fileUpload.PostedFile.FileName);
string Extension = Path.GetExtension(fileUpload.PostedFile.FileName);
string FilePath = HttpRuntime.AppDomainAppPath + "/Uploaded/" + FileName;
fileUpload.SaveAs(FilePath);
Import(FilePath, Extension);
}
}
3- You will need to import that file in your database, it will look like :
public Boolean Import(string FilePath, string Extension)
{
if (String.IsNullOrEmpty(FilePath) || String.IsNullOrEmpty(Extension))
{
return false;
}
string conStr;
string conStrNoHDR;
GetConnectionString(FilePath, Extension, out conStr, out conStrNoHDR);
OleDbConnection connection = new OleDbConnection(conStr);
OleDbConnection connectionNoHDR = new OleDbConnection(conStrNoHDR);
// depending on file extension, you might want to use connectionNoHDR
Import(connection);
connection.Close();
connectionNoHDR.Close();
}
private static void GetConnectionString(string FilePath, string Extension, out string conStr, out string conStrNoHDR)
{
conStr = "";
conStrNoHDR = "";
switch (Extension)
{
case ".xls": //Excel 97-03
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 8.0;HDR=YES\"";
conStrNoHDR = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 8.0;HDR=NO\"";
break;
case ".xlsx": //Excel 07
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=Excel 12.0 ";
conStrNoHDR = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 12.0;HDR=NO\"";
break;
case ".csv":
conStr = "Provider=Microsoft.Jet.OleDb.4.0; Data Source=" + Path.GetDirectoryName(FilePath) + ";Extended Properties=\"Text;FMT=Delimited;HDR=NO\"";
break;
}
}
public static void Import(OleDbConnection connection)
{
String query = "SELECT * From [Report-LANG_VOCALLS$]";
DataTable dt = ImportUtils.GetData(connection, query);
string table = "Dialer";
string conn = ConfigurationManager.ConnectionStrings["Telecom"].ConnectionString;
SqlBulkCopy bulkCopy = new SqlBulkCopy(conn);
bulkCopy.ColumnMappings.Add("Phone", "Phone");
bulkCopy.ColumnMappings.Add("portfolio", "Portfolio_eng");
bulkCopy.ColumnMappings.Add("dept", "Department_eng");
ImportUtils.BulkCopy(dt, table, bulkCopy);
}
public static DataTable GetData(OleDbConnection connection, String query)
{
DataTable dt = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter();
OleDbCommand cmdExcel = new OleDbCommand();
cmdExcel.CommandText = query;
cmdExcel.Connection = connection;
connection.Open();
adapter.SelectCommand = cmdExcel;
adapter.Fill(dt);
Debug.WriteLine(dt.Rows.Count);
connection.Close();
return dt;
}

Related

Access to wwwroot - Asp.Net Core MVC working well on local host but not in published app

I'm having a lot of trouble trying to get my App to work when
published. Basically, the code is supposed to create a doc from
template using Open XML sdk, then save to wwwroot and then upload to
blob storage.
It's working fine using local host. Have read and tried some stuff re
accessing static files - but nothing seems to work. Any help would be
very much appreciated. Relevant code is below:
[HttpGet]
public IActionResult GenerateDocxBrowser(MemoryStream mem, string filepath, string inputLastName, string inputTitle, string requestID, string dateReceived, string complaintType, string complaintDetails, string nameString, string no, string street, string town, string postcode)
{
var list = _context.Complaints.Where(s => s.ComplaintId.ToString().Contains(requestID)).ToList();
using (mem = new MemoryStream())
{
filepath = #"wwwroot\RequestTemplate.docx";
nameString = list.Select(s => s.NameString).FirstOrDefault();
complaintDetails = list.Select(s => s.Complaint).FirstOrDefault();
street = list.Select(s => s.AddressStreet).FirstOrDefault();
town = list.Select(s => s.AddressTown).FirstOrDefault();
using (WordprocessingDocument document = WordprocessingDocument.Open(filepath,true))
{
document.GetMergeFields("LastName").ReplaceWithText(inputLastName);
document.GetMergeFields("Title").ReplaceWithText(inputTitle);
document.GetMergeFields("ComplaintID").ReplaceWithText(requestID);
document.GetMergeFields("DateReceived").ReplaceWithText(dateReceived);
document.GetMergeFields("ComplaintType").ReplaceWithText(complaintType);
document.GetMergeFields("ComplaintDetails").ReplaceWithText(complaintDetails);
document.GetMergeFields("NameString").ReplaceWithText(nameString);
document.GetMergeFields("AddressLn1").ReplaceWithText(no + " " + street);
document.GetMergeFields("AddressLn2").ReplaceWithText(town + " TAS " + postcode);
document.SaveAs(#"wwwroot\" + requestID + ".docx");
document.MainDocumentPart.Document.Save();
document.Close();
}
}
const string StorageAccountName = "xxx";
const string StorageAccountKey = "xxxxxx";
var storageAccount = new CloudStorageAccount(
new StorageCredentials(StorageAccountName, StorageAccountKey), true);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("tasman/Request Images");
CloudBlockBlob blockBlob = container.GetBlockBlobReference(requestID + ".docx");
blockBlob.UploadFromFileAsync(#"wwwroot\" + requestID + ".docx");
return View();
}
Your .SaveAs() field should be relative, currently its literally saving to wwwroot somewhere on the drive. You can specify the relative path a few different ways - one of them is below:
var saveToFolder = Path.Combine(Environment.CurrentDirectory, $"/wwwroot/{requestID}.docx");

xxxxxx is not a valid path. Make sure that the path name is

I have windows application that can access files from setting.ini file I modified it and get access to them from my code. but still getting this error like 'C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
here is my setting.ini file code :
[UserDetail]
UserID=xxxxxxx
PassWord=xxxxxxxx
[Connection]
contact=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls
DebitISE=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE 1.xls
DebitLKP=C:\Users\infinity\Desktop\aadinathfiles\ALL EVENT FILE FORMAT\TRADING MASTER FILE\ISE CLEINT MASTER.xls
[FilePath]
DebitISEClient=C:
[FileName]
DebitISEClient=Contact_06-07-2015.txt
and here my code for accessing this files from ini file :
private void button1_Click(object sender, EventArgs e)
{
string filepath = txtpayoutfile.Text;
string message = "";
string mobileno = "";
string name = "";
DataSet dsmaster = new DataSet();
string filepathc = ini.IniReadValue("Connection", "contact");
if (filepath == "")
{
MessageBox.Show("Import Contact File");
this.Show();
}
if (Path.GetExtension(filepath) == ".xls")
{
oledbConn1 = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepathc + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(filepath) == ".xlsx")
{
oledbConn1 = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepathc + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
oledbConn1.Open(); ////exception occurs here
if (Path.GetExtension(filepath) == ".xls")
{
oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(filepath) == ".xlsx")
{
oledbConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
OleDbCommand cmdoledb = new OleDbCommand("Select * from [Sheet1$3:3000]", oledbConn);
OleDbDataAdapter daoledb = new OleDbDataAdapter(cmdoledb);
DataTable dt = new DataTable();
daoledb.Fill(dt);
}

Using Dapper QueryMultiple in Oracle

I´m trying to use dapper with Oracle (ODP.NET) and I would like to use the "QueryMultiple" functionality.
Passing this string to the QueryMultiple method:
var query = "Select CUST_ID CustId from Customer_info WHERE CUST_ID=:custId;" +
"Select CUST_ID CustId from BCR WHERE CUST_ID=:custId";
I´m getting a ORA-00911: invalid character error
Is there any way to do this or it´s not possible?
Tks
The OP has probably long since solved the issue by now, but as of the time of writing, this question has only one answer and it doesn't really solve the problem of using Dapper's QueryMultiple() method with Oracle. As #Kamolas81 correctly states, by using the syntax from the official examples, one will indeed get the ORA-00933: SQL command not properly ended error message. I spent a while searching for some sort of documentation about how to do QueryMultiple() with Oracle, but I was surprised that there wasn't really one place that had an answer. I would have thought this to be a fairly common task. I thought that I'd post an answer here to save me :) someone some time in the future just in case anybody happens to have this same problem.
Dapper seems to just pass the SQL command straight along to ADO.NET and whatever db provider is executing the command. In the syntax from the examples, where each command is separated by a line break, SQL server will interpret that as multiple queries to run against the database and it will run each of the queries and return the results into separate outputs. I'm not an ADO.NET expert, so I might be messing up the terminology, but the end effect is that Dapper gets the multiple query outputs and then works its magic.
Oracle, though, doesn't recognize the multiple queries; it thinks that the SQL command is malformed and returns the ORA-00933 message. The solution is to use cursors and return the output in a DynamicParameters collection. For example, whereas the SQL Server version would look like this:
var sql =
#"
select * from Customers where CustomerId = #id
select * from Orders where CustomerId = #id
select * from Returns where CustomerId = #id";
the Oracle version of the query would need to look like this:
var sql = "BEGIN OPEN :rslt1 FOR SELECT * FROM customers WHERE customerid = :id; " +
"OPEN :rslt2 FOR SELECT * FROM orders WHERE customerid = :id; " +
"OPEN :rslt3 FOR SELECT * FROM returns Where customerid = :id; " +
"END;";
For queries run against SQL Server, Dapper can handle it from there. However, because we're returning the result sets into cursor parameters, we'll need to use an IDynamicParameters collection to specify parameters for the command. To add an extra wrinkle, the normal DynamicParameters.Add() method in Dapper uses a System.Data.DbType for the optional dbType parameter, but the cursor parameters for the query need to be of type Oracle.ManagedDataAccess.Client.OracleDbType.RefCursor. To solve this, I used the solution which #Daniel Smith proposed in this answer and created a custom implementation of the IDynamicParameters interface:
using Dapper;
using Oracle.ManagedDataAccess.Client;
using System.Data;
public class OracleDynamicParameters : SqlMapper.IDynamicParameters
{
private readonly DynamicParameters dynamicParameters = new DynamicParameters();
private readonly List<OracleParameter> oracleParameters = new List<OracleParameter>();
public void Add(string name, OracleDbType oracleDbType, ParameterDirection direction, object value = null, int? size = null)
{
OracleParameter oracleParameter;
if (size.HasValue)
{
oracleParameter = new OracleParameter(name, oracleDbType, size.Value, value, direction);
}
else
{
oracleParameter = new OracleParameter(name, oracleDbType, value, direction);
}
oracleParameters.Add(oracleParameter);
}
public void Add(string name, OracleDbType oracleDbType, ParameterDirection direction)
{
var oracleParameter = new OracleParameter(name, oracleDbType, direction);
oracleParameters.Add(oracleParameter);
}
public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
{
((SqlMapper.IDynamicParameters)dynamicParameters).AddParameters(command, identity);
var oracleCommand = command as OracleCommand;
if (oracleCommand != null)
{
oracleCommand.Parameters.AddRange(oracleParameters.ToArray());
}
}
}
So all of the code together goes something like this:
using Dapper;
using Oracle.ManagedDataAccess.Client;
using System.Data;
int selectedId = 1;
var sql = "BEGIN OPEN :rslt1 FOR SELECT * FROM customers WHERE customerid = :id; " +
"OPEN :rslt2 FOR SELECT * FROM orders WHERE customerid = :id; " +
"OPEN :rslt3 FOR SELECT * FROM returns Where customerid = :id; " +
"END;";
OracleDynamicParameters dynParams = new OracleDynamicParameters();
dynParams.Add(":rslt1", OracleDbType.RefCursor, ParameterDirection.Output);
dynParams.Add(":rslt2", OracleDbType.RefCursor, ParameterDirection.Output);
dynParams.Add(":rslt3", OracleDbType.RefCursor, ParameterDirection.Output);
dynParams.Add(":id", OracleDbType.Int32, ParameterDirection.Input, selectedId);
using (IDbConnection dbConn = new OracleConnection("<conn string here>"))
{
dbConn.Open();
var multi = dbConn.QueryMultiple(sql, param: dynParams);
var customer = multi.Read<Customer>().Single();
var orders = multi.Read<Order>().ToList();
var returns = multi.Read<Return>().ToList();
...
dbConn.Close();
}
Building on greyseal96's helpful answer, I created this implementation of IDynamicParameters:
public class OracleDynamicParameters : SqlMapper.IDynamicParameters
{
private readonly DynamicParameters dynamicParameters;
private readonly List<OracleParameter> oracleParameters = new List<OracleParameter>();
public OracleDynamicParameters(params string[] refCursorNames) {
dynamicParameters = new DynamicParameters();
AddRefCursorParameters(refCursorNames);
}
public OracleDynamicParameters(object template, params string[] refCursorNames) {
dynamicParameters = new DynamicParameters(template);
AddRefCursorParameters(refCursorNames);
}
private void AddRefCursorParameters(params string[] refCursorNames)
{
foreach (string refCursorName in refCursorNames)
{
var oracleParameter = new OracleParameter(refCursorName, OracleDbType.RefCursor, ParameterDirection.Output);
oracleParameters.Add(oracleParameter);
}
}
public void AddParameters(IDbCommand command, SqlMapper.Identity identity)
{
((SqlMapper.IDynamicParameters)dynamicParameters).AddParameters(command, identity);
var oracleCommand = command as OracleCommand;
if (oracleCommand != null)
{
oracleCommand.Parameters.AddRange(oracleParameters.ToArray());
}
}
}
Assuming the same query, it can be used so:
var queryParams = new { id };
string[] refCursorNames = { "rslt1", "rslt2", "rslt3" };
var dynParams = new OracleDynamicParameters(queryParams, refCursorNames);
...
var multi = dbConn.QueryMultiple(sql, param: dynParams);
I suspect this is two or three separate things:
Your first query should not have a semi-colon
There is no new-line character between the queries
The usage notes imply that the bind character is # not : (no idea if this depends on the RDBMS being used).
If you look at the Dapper Google Code page the example given for QueryMultiple() is:
var sql =
#"
select * from Customers where CustomerId = #id
select * from Orders where CustomerId = #id
select * from Returns where CustomerId = #id";
using (var multi = connection.QueryMultiple(sql, new {id=selectedId}))
{
var customer = multi.Read<Customer>().Single();
var orders = multi.Read<Order>().ToList();
var returns = multi.Read<Return>().ToList();
...
}
Remove the semi-colon; add a new line and if you still have issues change the bind character.

How to want to move my DAL to separate project in my MVC3 solution?

I have MVC 3 application that uses a DAL (ADO.NET) that communicates to a set of tsql stored procedures? I want to add a new MVC project to my current solution. I need to have DAL in a separate project that the 2 MVC project ("Monitor" and "Audit") can share.
Here's the current DAL (which sits in a folder of the "Monitor" MVC project) code below. My issue is I have signature like IEnumerable located in the Monitor.Models and IEnumerable located in the Audit.Models. Do I need to make the DAL generic to avoid needing to make references to the models in the DAL?
Ex:
**//Is this bad practice?**
using Monitor.Models;
using Adit.Models;
namespace Monitor.DAL
{
public class QuestionDAL
{
static ILog log = log4net.LogManager.GetLogger(typeof(QuestionDAL));
private string _connectionString = WebConfigurationManager.ConnectionStrings["NexGenContext"].ToString();
public IEnumerable<AgencyTerm> SearchAgencies(string ori, string name)
{
log.Debug("Executing: SearchAgencies(string ori, string name)");
List<AgencyTerm> agencies = new List<AgencyTerm>();
using (var conn = new SqlConnection(_connectionString))
{
var com = new SqlCommand();
com.Connection = conn;
com.CommandType = CommandType.StoredProcedure;
string term = "Ori";
if (!String.IsNullOrEmpty(ori))
{
term = "Ori";
com.Parameters.Add(new SqlParameter
{
ParameterName = "#ORI",
Value = ori
});
}
if (!String.IsNullOrEmpty(name))
{
term = "legal_name";
com.Parameters.Add(new SqlParameter
{
ParameterName = "#Name",
Value = name
});
}
com.CommandText = "Review_Get_Agency_List";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
agencies = (from c in dataset.Tables[0].AsEnumerable()
select new AgencyTerm()
{
label = c[term].ToString(),
id = c["Agency_Id"].ToString()
}).ToList<AgencyTerm>();
return agencies;
}
}
public IEnumerable<User> GetUsers()
{
log.Debug("Executing: GetUsers()");
List<User> users = new List<User>();
using (var conn = new SqlConnection(_connectionString))
{
var com = new SqlCommand();
com.Connection = conn;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "Review_Get_Users";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);
users = (from c in dataset.Tables[0].AsEnumerable()
select new User()
{
User_ID = Convert.ToInt32(c["User_ID"]),
Department = c["Department"].ToString(),
Enabled = Convert.ToBoolean(c["Enabled"]),
Email = c["Email"].ToString(),
User_First_Name = c["User_First_Name"].ToString(),
User_Last_Name = c["User_Last_Name"].ToString(),
Location = c["Location"].ToString(),
User_Name = c["User_Name"].ToString()
}).ToList<User>();
return users;
}
}
You have two possibilities:
Either move your model into a separate library as well and then reference it from your MVC project and your DAL
Make your DAL completely generic and just push the values inside. I don't see an easy way here though since you have a lot of information in your DAL
I would go with the first option. Just extract your models to a different project and then reuse that library in both DAL and MVC-projects

How to add image dynamically in the jasper reports in java

Hii Guys !!!
I designed a jasper report to export into pdf which contains image that is stored in my local machine.Now As per my need i need to add the image dynamically from the projects classpath .Below I am posting my code.plz guys help me how to add image dynamically ...
File tempFile = File.createTempFile(getClass().getName(), ".pdf");
try {
FileOutputStream fos = new FileOutputStream(tempFile);
try {
ServletOutputStream servletOutputStream = response.getOutputStream();
InputStream reportStream = getServletConfig().getServletContext().getResourceAsStream("jasperpdf.jasper");
try {
String datum1 = request.getParameter("fromdate");
String datum2 = request.getParameter("todate");
SimpleDateFormat sdfSource = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdfSource.parse(datum1);
Date date2 = sdfSource.parse(datum2);
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd");
datum1 = sdfDestination.format(date);
System.out.println(datum1);
datum2 = sdfDestination.format(date2);
System.out.println(datum2);
String strQuery = "";
ResultSet rs = null;
conexion conexiondb = new conexion();
conexiondb.Conectar();
strQuery = "Select calldate,src,dst,duration,disposition,cdrcost from cdrcost where date(calldate) between '" + datum1 + "' and '" + datum2 + "'";
rs = conexiondb.Consulta(strQuery);
JRResultSetDataSource resultSetDataSource = new JRResultSetDataSource(rs);
JasperRunManager.runReportToPdfStream(reportStream, fos, new HashMap(), resultSetDataSource);
rs.close();
Is it working when you have provided the relative path of the image? i.e. images/image.jpg You should have a folder named images in your project and inside that there should be the file image.jpg ..
i'm newbie for jasper report, may be this code useful for you
private static JRDesignImage getImage(int x_postion, int y_position, int width, int height,ScaleImageEnum scale_type, HorizontalAlignEnum align_type,
JRDesignExpression expression) {
JRDesignImage image = new JRDesignImage(null);
image.setX(0);
image.setY(8);
image.setWidth(97);
image.setHeight(50);
image.setScaleImage(ScaleImageEnum.RETAIN_SHAPE);
image.setHorizontalAlignment(HorizontalAlignEnum.LEFT);
image.setExpression(expression);
// TODO Auto-generated method stub
return image;
}
then add
band = new JRDesignBand();
band.setHeight(73);
expression = new JRDesignExpression();
expression.setValueClass(java.lang.String.class);
expression.setText("$P{imagePath}");
// jasperDesign.addField();
band.addElement(getImage(0,8,97,50,ScaleImageEnum.RETAIN_SHAPE,HorizontalAlignEnum.LEFT,expression));

Resources