I'm new to repository pattern/unit of work.
I used the GitHub-timschreiber DapperUnitOfWork here and adjust it to my data.
I use WinForms. First I load my Form an load all data to dataGridView. Then I want to use da textBox to filter data. Everything works well.
public Form1()
{
InitializeComponent();
Test();
}
void Test()
{
using (var uow = new UnitOfWork(AppConnection.ConnectionString))
{
dataGridView1.DataSource = uow.ProductRepository.GetAll();
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
using (var uow = new UnitOfWork(AppConnection.ConnectionString))
{
var filteredList = uow.ProductRepository.GetAll().Where(c => c.Ident.Contains(textBox1.Text)).ToList();
dataGridView1.DataSource = filteredList;
}
}
Now my question: Is this the right way to make use of it?
I mean for every action I need a using for the DB.
So is it correct or what is the right way?
Related
My DataGridView sorting method does not work and would not be used wiht the compiler.
Where i use dgv:
public void LoadData(IList conTable)
{
var mtc = new Conversions();
dgvDetailedTable.DataSource = null;
dgvDetailedTable.DataSource = mtc.ToSortableBindingList(conTable);
dgvDetailedTable.RowTemplate.Height = UiConsts.RowHeight;
}
The Sorting event:
private void DgvDetailedTable_Sorted(object sender, EventArgs e)
{
var itemsToSelect = new MisTable[_selectedDetailedItems.Length];
_selectedDetailedItems.CopyTo(itemsToSelect, 0);
DgvOperations.MarkSelectedItems(dgvDetailedTable, itemsToSelect);
}
I hope this help, but I'm not sure you should use Sorted event for it.
You can use this code below at the end of binding and when you add a new item it will sort properly again.
public void LoadData(IList conTable)
{
var mtc = new MisTableConversions();
dgvDetailedTable.DataSource = null;
dgvDetailedTable.DataSource = mtc.ToSortableBindingList(conTable);
dgvDetailedTable.RowTemplate.Height = UiConsts.RowHeight;
// Use sorting here
this.DgvDetailedTable.Sort(this.DgvDetailedTable.Columns["Name"], ListSortDirection.Ascending);
}
I have a simple gridview which I need to bind with a list of users.
In EF.5.0 I could simple write
context.Users.Select(emp => new { Name = emp.FirstName, EmailId = emp.EmailId, UserId = emp.UserId }).ToList();
However, I don't see the .ToList() method anymore in EF6.0
So, I have to write an async query using ToAsyncList(). However, not sure why the below code does not work and system goes in endless execution.
protected void Page_Load(object sender, EventArgs e)
{
var task = LoadData();
task.Wait();
GridView1.DataSource = task.Result;
GridView1.DataBind();
}
private async Task<List<User>> LoadData()
{
List<User> users = null;
using (var context = new BlogEntities())
{
users = await context.Database.SqlQuery<User>("Select * from User", new object[] { }).ToListAsync();
}
return users;
}
Can anyone please let me know, what I am doing wrong here?
Use this code:
var users = context.Users.SqlQuery("SELECT * FROM dbo.User").ToList();
I have this situation I want to synchronize informations in my dataGridView when I insert it on my add form like you can see on this picture.
In my Insert form on insert button I call Add form to pop up like this
private void button1_Click(object sender, EventArgs e)
{
if (addForm==null)
{
addForm = new AddForm();
}
addForm.MdiParent = this.ParentForm;
addForm.FormClosed += AddForm_FormClosed;
addForm.Show();
}
private void AddForm_FormClosed(object sender, FormClosedEventArgs e)
{
addForm = null;
}
On Add form in Accept click I insert informations and call fillDataGrid() method from Insert form to do data sync but nothing is shown data is shown just when I close Insert form and call it again does someone has susggestion how can I do this this is the first time I work with MdiContainer ?
private void buttonAccept_Click(object sender, EventArgs e)
{
if (validation())
{
Proizvod product = new Proizvod();
product.NazivProizvoda = textBoxName.Text;
product.Opis = textBoxDescription.Text;
product.SerijskiBroj = textBoxNumber.Text;
product.ZemljaPorijekla = textBoxCountry.Text;
if (pDal.insertProduct(product)==0)
{
MessageBox.Show("Informations are successfully inserted","Message");
InsertForm inForm = new InsertForm();
inForm.fillDataGrid();
}
}
}
My fillDataGrid() method and Load event of InsertForm:
public void fillDataGrid()
{
dataGridViewProducts.DataSource = null;
dataGridViewProducts.AutoGenerateColumns = false;
dataGridViewProducts.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewProducts.ColumnCount = 3;
dataGridViewProducts.Columns[0].Name = "Product name";
dataGridViewProducts.Columns[0].DataPropertyName = "NazivProizvoda";
dataGridViewProducts.Columns[1].Name = "Country";
dataGridViewProducts.Columns[1].DataPropertyName = "ZemljaPorijekla";
dataGridViewProducts.Columns[2].Name = "Product number";
dataGridViewProducts.Columns[2].DataPropertyName = "SerijskiBroj";
dataGridViewProducts.DataSource = pDal.getAllProducts();
}
private void InsertForm_Load(object sender, EventArgs e)
{
fillDataGrid();
}
private void InsertForm_Shown(object sender, EventArgs e)
{
dataGridViewProducts.CurrentCell = null;
dataGridViewProducts.ClearSelection();
}
Currently in buttonAccept_Click code, you have created a new instance of the list form and called its FillGrid. This way you are manipulating another instance of the list form which is different from the instance which is open and you can see. You are filling a different form which you didn't show it.
Instead of creating a new instance, create a constructor for your second form which accepts a parameter of first form type. Then when you want to create a new instance of seccod form, pass the instance of the first form (this) to second Form. Then in your save button call the FillGrid method of the passed instance.
For more information about how to manipulate another form, read this post. It contains some useful options about:
Pass data to second Form when creating
Manipulate second Form after showing
Manipulate first Form from second Form
Here is some code which belong to the ListForm:
private void ShowAddForm_Click(object sender, EventArgs e)
{
if (addForm == null)
{
addForm = new AddForm(this);
addForm.MdiParent = this.ParentForm;
addForm.FormClosed += AddForm_FormClosed;
}
addForm.Show();
}
private void AddForm_FormClosed(object sender, FormClosedEventArgs e)
{
addForm = null;
}
And here is the code for AddForm
public class AddForm
{
MyListForm listForm;
public AddForm(MyListForm f)
{
InitializeComponent();
listForm = f;
}
private void SaveVutton_Click(object sender, EventArgs e)
{
//perform validation and save data
f.FillGrid();
}
}
Im very new to programing and new to stripe. i am currently trying to create a basic page where i can just create the customers. Im currently using the stripe.net dll and am having a hard time getting this page to work correctly. Here is what i have. I get no errors and no records get created.
Using Stripe;
private StripeCustomer GetCustomer()
{
var mycust = new StripeCustomerCreateOptions();
mycust.Email = "thisisit#overhere.com";
mycust.Description = "One Time";
mycust.CardName = "Full Name";
var customerservice = new StripeCustomerService(System.Web.Configuration.WebConfigurationManager.AppSettings["StripeApiKey"]);
return customerservice.Create(mycust);
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
StripeCustomer current = GetCustomer();
var mycharge = new StripeChargeCreateOptions();
string key = System.Web.Configuration.WebConfigurationManager.AppSettings["StripeApiKey"];
Response.Redirect("/services/donate/thanks.aspx");
}
catch (StripeException ex)
{
//lblerror.Text = (ex.Message);
}
}
Also a little help (as i am lost an nothing i try works) as to how i would go about pulling a list of the current customs i have and display them would be great.
I'm guessing you're using this: https://github.com/jaymedavis/stripe.net#list-all-customers
In your GetCustomer method you are creating a customer, instead, you want to do something like the following:
private IEnumerable<StripeCustomer> GetCustomers()
{
var customerservice = new StripeCustomerService(System.Web.Configuration.WebConfigurationManager.AppSettings["StripeApiKey"]);
return customerservice.List();
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
StripeCustomer list = GetCustomers();
//show this list somewhere
}
catch (StripeException ex)
{
//lblerror.Text = (ex.Message);
}
}
Makre sure StripeApiKey exists in your configuration file.
Having a lot of trouble with this. I'm working on a large project, so there's only a few classes I'm interested in and working on. Basically, these are forms - one is a main editor where a user edits details and the other is used to assign a pin number. In the main editor form, if the user has a pin, they can choose to edit this pin. Here's where my problem lies - if I edit the pin, what I'm doing in the code is deleting the old pin and adding the new one. However, the database doesn't update until AFTER the editor form is closed. Therefore, I'd like to call the method that does change the database on the OKButton click, if I could. The problem I'm facing is I don't know how.
Here is the DB code, we'll say the class is called DetailsConn:
public string editPin(int driverID)
{
if (SchemaChecker.PINAvailable())
{
string sql = "EditPIN";
using (SqlCommand cmd = new SqlCommand(sql, base.connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Remove("#nDriverID");
cmd.Parameters.AddWithValue("#nDriverID", driverID);
cmd.Parameters.Remove("#nPIN");
SqlParameter pinParameter = cmd.Parameters.Add("#nPIN", SqlDbType.Char);
pinParameter.Direction = ParameterDirection.Output;
pinParameter.Size = 32;
cmd.ExecuteNonQuery();
return pinParameter.Value.ToString();
}
}
return "";
}
Here's the code for my edit:
private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.listViewDriverTags.SelectedItems.Count > 0)
{
ListViewItem lvi = this.listViewDriverTags.SelectedItems[0];
DriverTag driverTag = lvi.Tag as DriverTag;
else if (blahTag.blahType == 2)
{
buttonAssignPIN_Click(sender, e);
}
//message stuff and dialog boxes with localization info
if (dr == DialogResult.Yes)
{
this.listViewDriverTags.Items.Remove(lvi);
if (Tag.id != -1)
{
TagsToBeDeleted.Add(driverTag);
}
}
if (dr == DialogResult.No)
{
this.listViewTags.Items.Clear();
this.listViewTags.Items.Add(lvi);
}
}
}
Here's my buttonAssignPIN stuff:
private void buttonAssignPIN_Click(object sender, EventArgs e)
{
using (AssignPINForm form = new AssignPINForm())
{
if (form.ShowDialog(this) == DialogResult.OK)
{
DriverTag PIN = DriverTag.GetNewPIN(form.DriverTag);
ListViewItem lvi = this.listViewTags.Items.Add(PIN.driverTag);
lvi.SubItems.Add(this.TagTypes[PIN.TagType]);
lvi.Tag = PIN;
}
}
}
And finally, here's my AssignPINForm code:
public partial class AssignPINForm : Form
{
public AssignPINForm()
{
InitializeComponent();
this.buttonOK.Click += new EventHandler(buttonOK_Click);
this.buttonCancel.Click += new EventHandler(buttonCancel_Click);
this.buttonOK.Enabled = false;
this.textBoxPin.TextChanged += delegate(object sender, EventArgs e)
{
String pattern = #"^[0-9]{4,20}$";
Regex regex = new Regex(pattern);
buttonOK.Enabled = regex.IsMatch(textBoxPin.Text);
};
LoadStrings();
}
public void LoadStrings()
{
//stome stuff
}
public string DriverTag
{
get { return this.textBoxPin.Text; }
set { this.textBoxPin.Text = value; }
}
private void buttonOK_Click(object sender, EventArgs e)
{
}
private void buttonCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void AssignPINForm_Load(object sender, EventArgs e)
{
}
}
I know it's kind of all over the place but I've provided everything I think is relevant. The middle two snippets are in the same class too, and the DB stuff is the same solution but a different project. I'd be grateful if someone can decipher what I'm after and help me out, it's the only thing I have left to do on this particular bit!
Thanks!
Not sure I fully got what you're after and I agree with some of the comments that this isn't the best of practice but I guess what you're after is to update the buttonOK_Click method to something like this:
private void buttonOK_Click(object sender, EventArgs e)
{
using(DetailsConn connection = new DetailsConn())
{
int driver = -1;
if(int.TryParse(this.DriverTag, out driver)) {
connection.editPin(driver);
}
}
}
Also, you may want to remove any other possible references to the editPin() function.
I actually figured out that even if I got that working correctly, it wasn't going to solve my problem. I've had to call a new procedure and declare that in the database schema - basically it was a lot more complicated than what I was giving it credit for. Thanks for the responses nonetheless.