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

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();
}
}
} ```

Related

ObjectContext.Translate not working in oracle 19 version

this is my function that translate result from db to object classe.
public static List<T> GetListBySP<T>(string pSPName, params object[] pParamArray)
{
List<T> res = null;
//string connStr = ConfigurationManager.ConnectionStrings[sConnStr].ConnectionString;
string connStr = DbFactory.ConnStr;
using (OracleConnection conn = new OracleConnection(connStr))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandText = pSPName;
cmd.CommandType = CommandType.StoredProcedure;
FillParameters(cmd.Parameters, pParamArray);
cmd.Parameters.Add("pCursor", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
using (var db = DbFactory.CreateRo())
{
try
{
cmd.Connection.Open();
var reader = cmd.ExecuteReader();
res = ((IObjectContextAdapter)db).ObjectContext.Translate<T>(reader).ToList<T>();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Connection.Close();
}
}
}
}
return res;
}
after update oracle version to 19.
exaption throw on line
res = ((IObjectContextAdapter)db).ObjectContext.Translate<T>(reader).ToList<T>();
the exeption is:
An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
the project run on .net framework 4.6.2

C# Azure.Storage.Blobs SDK How to list and zip all files in a container and store the zip in another container

I have around 100 files in a container . I want to call a function to zip all files and send it to another container . I am using the Azure.Storage.Blobs version 12.9.1
var blob = container.GetBlockBlobReference(outputFilename);
using (var stream = await blob.OpenWriteAsync())
using (var zip = new ZipArchive(stream, ZipArchiveMode.Create))
{
for (int i = 0; i < 2000; i++)
{
using (var randomStream = CreateRandomStream(2))
{
var entry = zip.CreateEntry($"{i}.zip", CompressionLevel.Optimal);
using (var innerFile = entry.Open())
{
await randomStream.CopyToAsync(innerFile);
}
}
}
}
This is for the older version . How can we achieve it using the new sdk
Can you please try with this code.
Solution 1: Try this code to generate Zip file. After generating zip file upload it to container
public void ZipFilesToResponse(HttpResponseBase response, IEnumerable<Asset> files, string zipFileName)
{
using (var zipOutputStream = new ZipOutputStream(response.OutputStream))
{
zipOutputStream.SetLevel(0); // 0 - store only to 9 - means best compression
response.BufferOutput = false;
response.AddHeader("Content-Disposition", "attachment; filename=" + zipFileName);
response.ContentType = "application/octet-stream";
foreach (var file in files)
{
var entry = new ZipEntry(file.FilenameSlug())
{
DateTime = DateTime.Now,
Size = file.Filesize
};
zipOutputStream.PutNextEntry(entry);
storageService.ReadToStream(file, zipOutputStream);
response.Flush();
if (!response.IsClientConnected)
{
break;
}
}
zipOutputStream.Finish();
zipOutputStream.Close();
}
response.End();
}
For more details refer this link
Solution 2:Also try with this code
using System;
using System.Threading.Tasks;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;
namespace SO68566758
{
class Program
{
private const string connectionString = "DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key";
private const string sourceContainer = "source-container";
private const string targetContainer = "target-container";
private const string outputBlobName = "backup.zip";
static async Task Main(string[] args)
{
BlobServiceClient serviceClient = new BlobServiceClient(connectionString);
BlobContainerClient sourceContainerClient = serviceClient.GetBlobContainerClient(sourceContainer);
BlobContainerClient targetContainerClient = serviceClient.GetBlobContainerClient(targetContainer);
var blobs = sourceContainerClient.GetBlobsAsync();
using (var fs = new FileStream(outputBlobName, FileMode.OpenOrCreate))
{
using (var zipOutputStream = new ZipOutputStream(fs))
{
await foreach (var blob in blobs)
{
var blobName = blob.Name;
var blobClient = sourceContainerClient.GetBlobClient(blobName);
//var downloadResponse = await blobClient.DownloadAsync();
//var streamContent = downloadResponse.Value.Content;
var entry = new ZipEntry(blobName);
zipOutputStream.PutNextEntry(entry);
await blobClient.DownloadToAsync(zipOutputStream);
}
}
}
BlobClient targetBlob = targetContainerClient.GetBlobClient(outputBlobName);
using (FileStream fs = new FileStream(outputBlobName, FileMode.Open))
{
await targetBlob.UploadAsync(fs);
}
}
}
}

Getting error while consuming Web API in Xamarin forms cross platform

Getting below error while consuming web API in Xamarin forms "Cannot convert from Login to System.Net.Http.HttpCompletionOption"
I'm new to mobile development ,please help me in completing the above code for consuming the API's in Xamarin cross platform.
Below is the code for WEB API
public class DBLoginController : ApiController
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db_test"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = null;
[HttpGet]
[ActionName("getCustomerInfo")]
public DataTable Get()
{
DataTable dt = new DataTable();
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbl_admin";
cmd.Connection = con;
if (con.State == ConnectionState.Open)
{
con.Close();
}
adp = new SqlDataAdapter(cmd);
dt.TableName = "tbl_admin";
adp.Fill(dt);
con.Close();
}
catch
{
}
return dt;
}
[HttpPost]
public int Login([System.Web.Http.FromBody] Login lgn)
{
int ret = 0;
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select count(*) from tbl_admin where username='"+lgn.username+"'username and password='"+ lgn.password + "'";
cmd.Connection = con;
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
ret = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
catch
{
}
return ret;
}
}
Below is the code for consuming API in xamarin form
private async void BtnLogin_Clicked(object sender, EventArgs e)
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://********.com/api/DBLogin/getCustomer");
Login lgn = new Login { username = txtUsername.Text.ToString(), password = txtPassword.Text.ToString() };
var response = client.GetAsync("api/Login/Login").Result;
var a = response.Content.ReadAsStringAsync();
if (a.Result.ToString().Trim() == "0")
{
messageLabel.Text = "Invalid login credentials.";
}
else
{
await Navigation.PushModalAsync(new Page2());
}
}
}
}
please help
Thanks in advance

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

'System.Web.HttpPostedFileBase' does not contain a definition for 'HasFile' and no extension method 'HasFile'

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;

Resources