how to store dbcontext.emps.ToList() data in a data table - entity-framework

how to store the dbcontext.emp.tolist(); data in datatable to perform sorting using entity frame database first approach and linq .
here i am uploading my code.
please help.
how to perform soting operation for grid using entity frame work and linq.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace sortingby_crud
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//this.BindGrid();
GridView1.DataSource = BindGrid();
GridView1.DataBind();
}
}
private DataTable BindGrid()
{
using (dbEntities db = new dbEntities())
{
//GridView1.DataSource = db.emps.ToList();
//GridView1.DataBind();
DataTable dt = new DataTable();
dt= db.emps.ToList();
return dt;
}
}
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortingDirection = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
dir = SortDirection.Ascending;
sortingDirection = "Asc";
}
DataView sortedView = new DataView(BindGrid());
sortedView.Sort = e.SortExpression + " " + sortingDirection;
GridView1.DataSource = sortedView;
GridView1.DataBind();
}
}
}

public DataTable data() // or keep return type is also
as void .
/convert db.context in data table.
{
DataTable table = new DataTable();
var list = db.SupplierAssignmentones.ToList();
//Defining the header for the datatable.
table.Columns.Add("VendorId", typeof(int));
table.Columns.Add("VendorName", typeof(string));
table.Columns.Add("VendorDescription", typeof(string));
table.Columns.Add("SupHie1_CD", typeof(string));
table.Columns.Add("SupHie2_CD", typeof(string));
table.Columns.Add("SupHie3_CD", typeof(string));
table.Columns.Add("Is_Active", typeof(string));
//assigning the data for data table rows.
foreach (var data in list)
{
table.Rows.Add(data.VendorId, data.VendorName, data.VendorDescription, data.SupHie1_CD, data.SupHie2_CD, data.SupHie3_CD, data.Is_Active);
}
return table;
}

Related

Npgsql Performance

I am trying to implement Npgsql in our DAL and running into issues under heavy load. the following sample application is a decent representation of just a simple query that under heavy load, throws a 'A command is already in progress' exception. I am assuming this is due to the lack of MARS support so I also tried creating a connection each time with a using statement around each command only to have the performance become unusable. I checked that the username is indexed so that shouldn't be an issue.
Not sure what I am doing wrong here but I need some advice on how to get this performing well.
OS: Docker Container: microsoft/dotnet:2.1.301-sdk
using Npgsql;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Threading.Tasks;
namespace npgsqlTest
{
class Program
{
static async Task Main(string[] args)
{
DAL dal = new DAL();
dal.Prepare();
var tasks = dal.Users.Select(async user =>
{
Console.WriteLine(await dal.RunTest(user));
});
await Task.WhenAll(tasks);
}
}
public class DAL
{
private static string _ConnectionString;
private NpgsqlConnection _Connection;
public List<string> Users { get; set; } = new List<string>();
public DAL()
{
_ConnectionString = $"Host=192.168.1.1;Username=admin;Port=5432;Password=password;Database=BigDB;";
_Connection = new NpgsqlConnection(_ConnectionString);
_Connection.Open();
}
public void Prepare()
{
string query = "SELECT username FROM usertable;";
using (var cmd = new NpgsqlCommand(query, _Connection))
{
var reader = cmd.ExecuteReader();
using (reader)
{
while (reader.Read())
{
Users.Add(reader[0].ToString());
}
}
}
}
public async Task<string> RunTest(string user)
{
var parameters = new Dictionary<string, Object> { { "username", user } };
var query = $"SELECT name FROM usertable WHERE username = (#username);";
var reader = await QueryAsync(query, parameters);
using (reader)
{
if (reader.HasRows)
{
while (await reader.ReadAsync())
{
var name = reader["name"];
if (!(hash is DBNull))
return (string)name;
}
}
}
return String.Empty;
}
public async Task<DbDataReader> QueryAsync(string query, Dictionary<string, Object> parameters)
{
using (var cmd = new NpgsqlCommand(query, _Connection))
{
foreach (var parameter in parameters)
{
cmd.Parameters.AddWithValue(parameter.Key, parameter.Value == null ? DBNull.Value : parameter.Value);
}
cmd.Prepare();
return await cmd.ExecuteReaderAsync();
}
}
}
}

Maximum Report Processing has been reached for crystal report

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Xml;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.ReportSource;
using CrystalDecisions.Reporting;
using CrystalDecisions.Shared;
using CrystalDecisions.Web;
public partial class Schools : System.Web.UI.Page
{
ReportDocument crystalReport = new ReportDocument();
protected void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
string query = "select * from School Where Designation = 'Public' Order by School ASC";
crystalReport.Load(Server.MapPath("ReportPrimary.rpt"));
MPrimary dsCustomers = GetData(query);
crystalReport.SetDataSource(dsCustomers);
crystalReport.SetDatabaseLogon("username", "password.34", "mssql.webaddress.net,4118", "dataDB");
SchReport.ReportSource = crystalReport;
Session["ReportDocument"] = crystalReport;
}
catch (LogOnException ex)
{
//Throws an exception if an error is encountered on retrieval
}
}
else
{
string query = "select * from School Where Designation = " + "'" + drpSchoolDesignation.SelectedValue + "'" + " Order by School ASC";
// ReportDocument crystalReport = new ReportDocument();
crystalReport.Load(Server.MapPath("ReportPrimary.rpt"));
TextObject to = (TextObject)crystalReport.ReportDefinition.Sections["Section2"].ReportObjects["Text3"];
to.Text = drpSchoolDesignation.SelectedValue.ToUpper() + " SCHOOLS";
MPrimary dsCustomers = GetData(query);
crystalReport.SetDataSource(dsCustomers);
SchReport.FindControl("Text3");
crystalReport.SetDatabaseLogon("username", "password.34", "mssql.webaddress.net,4118", "dataDB");
ReportDocument doc = (ReportDocument)Session["ReportDocument"];
SchReport.ReportSource = doc;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
private void OpenNewWindow(string url, string windowName, string windowParams)
{
if (url == null)
throw new ArgumentNullException("url");
if (windowName == null)
windowName = "";
if (windowParams == null)
windowParams = "";
string scriptCode =
string.Format(
"<script>window.open('{0}','{1}','{2}');</script>",
url, windowName, windowParams);
//write the script out to HTTP Response stream
Response.Write(scriptCode);
}
private MPrimary GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["DBConnectionString1"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (MPrimary dsCustomers = new MPrimary())
{
sda.Fill(dsCustomers, "School");
return dsCustomers;
}
}
}
}
protected void drpSchoolDesignation_SelectedIndexChanged(object sender, EventArgs e)
{
drpDisplay.SelectedIndex = 0;
drpSort.SelectedIndex = 0;
string query = "select * from School Where Designation = " + "'" + drpSchoolDesignation.SelectedValue + "'" + " Order by School ASC";
crystalReport.Load(Server.MapPath("ReportPrimary.rpt"));
TextObject to = (TextObject)crystalReport.ReportDefinition.Sections["Section2"].ReportObjects["Text3"];
to.Text = drpSchoolDesignation.SelectedValue.ToUpper() + " SCHOOLS";
MPrimary dsCustomers = GetData(query);
crystalReport.SetDataSource(dsCustomers);
crystalReport.SetDatabaseLogon("username", "password.34", "mssql.webaddress.net,4118", "dataDB");
Session["ReportDocument"] = crystalReport;
SchReport.ReportSource = crystalReport;
}
protected void CrystalReportViewer1_Unload(object sender, EventArgs e)
{
crystalReport.Close();
crystalReport.Dispose();
}
protected void Button1_Click(object sender, EventArgs e)
{
//Select data from DB
//Action to be added later
}
}
This code is supposed to retrieve and display info using crystal reports.
It seems my object is not been properly disposed. Modifying this code disables the user from ever getting to page 3 of the document. Any help would be appreciated. Thanks guys in advance.

Libusbdotnet HID Read (Event Driven) Error

I used LibUSbDotNet for read USB data from my Hardware using Event Driven operation. My hardware pumps out data at two different intervals. (2000 ms and 300 ms). The buffer size is 7 bytes.
The code works fine for sometimes afterwards the reading is slowed. instead of 2000 and 300 ms the data receives at 4000 and 2000 ms.
Please help me resolve this issue guys...
regards
John
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LibUsbDotNet;
using LibUsbDotNet.DeviceNotify;
using LibUsbDotNet.Main;
namespace ATE_BackEnd
{
public partial class Main_Form : Form
{
public static IDeviceNotifier UsbDeviceNotifier = DeviceNotifier.OpenDeviceNotifier();
UsbDeviceFinder MyUsbFinder;
UsbDevice MyUsbDevice;
UsbEndpointReader EPReader;
UsbEndpointWriter EPWriter;
int bytesWritten;
public DateTime LastDataEventDate = DateTime.Now;
public Main_Form()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
UsbDeviceNotifier.OnDeviceNotify += OnDeviceNotifyEvent;
}
void OpenUSB(int VendorID, int ProductID)
{
toolStripStatusLabel.Text = "Opening USB";
MyUsbFinder = new UsbDeviceFinder(VendorID, ProductID);
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
if (MyUsbDevice == null) { USBConnection_label.Text = "USB Not Connected"; CloseUSB(); }
else
{
USBConnection_label.Text = "USB Connected";
USBInfo_label.Text = "VID = " + MyUsbDevice.Info.Descriptor.VendorID.ToString() +
", PID = " + MyUsbDevice.Info.Descriptor.ProductID.ToString();
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
wholeUsbDevice.SetConfiguration(1);
wholeUsbDevice.ClaimInterface(0);
}
EPReader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01, 7);
EPWriter = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
EPReader.DataReceived += OnUsbDataReceived;
EPReader.DataReceivedEnabled = true;
}
}
void WriteUSB(int Site)
{
toolStripStatusLabel.Text = "Writing Data...";
ErrorCode ECWriter = EPWriter.Write(Encoding.Default.GetBytes(Site.ToString()), 100, out bytesWritten);
if (ECWriter != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);
}
void CloseUSB()
{
toolStripStatusLabel.Text = "Closing USB";
if (MyUsbDevice != null)
{
if (MyUsbDevice.IsOpen)
{
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
wholeUsbDevice.ReleaseInterface(0);
}
MyUsbDevice.Close();
}
EPReader.DataReceived -= OnUsbDataReceived;
EPReader.DataReceivedEnabled = false;
EPReader.Dispose();
EPWriter.Dispose();
}
MyUsbDevice = null;
UsbDevice.Exit();
}
void OnDeviceNotifyEvent(object sender, DeviceNotifyEventArgs e)
{
toolStripStatusLabel.Text = "Device Notify Message: " + e.EventType.ToString();
if (e.EventType.ToString() == "DeviceRemoveComplete") { USBConnection_label.Text = "USB Disconnected"; CloseUSB(); }
else if (e.EventType.ToString() == "DeviceArrival") { USBConnection_label.Text = "USB Connected"; OpenUSB(4660, 1); }
}
void OnUsbDataReceived(object sender, EndpointDataEventArgs e)
{
toolStripStatusLabel.Text = "Receiving Data!!!";
byte[] s1stat = e.Buffer;
S1SOT_textBox.Text = s1stat[0].ToString();
S2SOT_textBox.Text = s1stat[1].ToString();
S1EOT_textBox.Text = s1stat[2].ToString();
S2EOT_textBox.Text = s1stat[3].ToString();
S1BIN_textBox.Text = s1stat[4].ToString();
S2BIN_textBox.Text = s1stat[5].ToString();
TowerLamp_textBox.Text = s1stat[6].ToString();
Time_label.Text = (DateTime.Now - LastDataEventDate).TotalMilliseconds.ToString();
LastDataEventDate = DateTime.Now;
}
private void Main_Form_FormClosing(object sender, FormClosingEventArgs e)
{
toolStripStatusLabel.Text = "Closing App";
CloseUSB();
}
private void Main_Form_Load(object sender, EventArgs e)
{
toolStripStatusLabel.Text = "Opening App";
OpenUSB(4660, 1);
}
private void Write_button_Click(object sender, EventArgs e)
{
CloseUSB();
OpenUSB(4660, 1);
WriteUSB(Write_comboBox.SelectedIndex+1);
}
}
}

Execute stored procedure in Entity Framework, return List<DataTable> or DataSet

How do I modify the below method to return a List< DataTable> or a DataSet? I want to make it generic so it can return multiple resultsets from the database.
public static DataTable ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
{
var entityConnection = (EntityConnection) db.Connection;
var conn = entityConnection.StoreConnection;
var initialState = conn.State;
var dt = new DataTable();
try
{
if (initialState != ConnectionState.Open)
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = storedProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
reader.Close();
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close();
}
return dt;
}
I ended up doing it like this -
public static DataSet ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
{
var connectionString = ((EntityConnection)db.Connection).StoreConnection.ConnectionString;
var ds = new DataSet();
using (var conn = new SqlConnection(connectionString))
{
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = storedProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
using (var adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
}
}
}
return ds;
}
reader.NextResult() should technically work. Here is the modified version:
public static DataSet ExecuteStoredProcedure(ObjectContext db, string storedProcedureName, IEnumerable<SqlParameter> parameters)
{
var entityConnection = (EntityConnection) db.Connection;
var conn = entityConnection.StoreConnection;
var initialState = conn.State;
DataSet dataSet = new DataSet();
try
{
if (initialState != ConnectionState.Open)
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = storedProcedureName;
cmd.CommandType = CommandType.StoredProcedure;
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
using (var reader = cmd.ExecuteReader())
{
do
{
DataTable dt = new DataTable();
dt.Load(reader);
dataSet.Tables.Add(dt);
}
while (reader.NextResult());
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close();
}
return dataSet;
}

StackoverflowException while using SqlDependencies with Ef Framework

I would like to get some feedback about using SqlDependencies with EF Framework 4.0. I have currently implemented a scenario using ObjectQuery in combination with toStraceString() to generate SqlDependency.
Im getting a StackoverflowException somewhere in Entity Framework source code when doing refresh store wins. I thought this error would somewhere in my code, but i cannot find it.
I made up a small example of what i want to do:
public partial class MainWindow : Window
{
private SqlDependency _sqldep;
public delegate void DataChanged(string test);
TestEntities m = new TestEntities();
SqlCommand _cmd;
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
//m.Connection.Open();
SqlDependency.Start(((System.Data.EntityClient.EntityConnection)m.Connection).StoreConnection.ConnectionString);
var query = m.User.AsQueryable<User>();
string query_str = m.User.ToTraceString();
SqlConnection con = new SqlConnection(((System.Data.EntityClient.EntityConnection)m.Connection).StoreConnection.ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(query_str, con);
_cmd = cmd;
_sqldep = new SqlDependency(cmd);
_sqldep.OnChange += dependency_OnChange;
cmd.ExecuteReader();
this.Users = m.User;
}
SqlDependency dependency;
// Bei Ă„nderung am gegebenen SQL-Statement
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
dependency = (SqlDependency)sender;
dependency.OnChange -= dependency_OnChange;
NotifierOnDataChanged(string.Empty);
dependency.OnChange += dependency_OnChange;
}
private void NotifierOnDataChanged(string bla)
{
try
{
m.Refresh(System.Data.Objects.RefreshMode.StoreWins, m.User);
}
catch (System.Exception ex)
{
System.Windows.MessageBox.Show(ex.Message, "Fehler");
}
}
private IEnumerable<User> _users;
public IEnumerable<User> Users
{
get { return _users; }
set { _users = value; }
}
}
I'm getting my StackoverflowException at NotifierOnDataChanged -> Refresh