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();
Related
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?
I want to call a web api method on page load event of my project. But I want to wait for the execution of the function 'GetSelectedTaskDetails' to complete. So that I can manage with the values from DataRow row.
Could you please suggest how can i achieve this?
private DataRow row;
protected void Page_Load(object sender, EventArgs e)
{
GetSelectedTaskDetails(Id);
//other codes
}
private async void GetSelectedTaskDetails(int? selected_task_id)
{
try
{
url = baseUrl + "GetSelectedTaskDetails?task_id=" + selected_task_id;
using (var objClient = new HttpClient())
{
using (var response = await objClient.GetAsync(url))
{
if ((int)response.StatusCode == 401)//unauthorised or token expired
{
Response.Redirect("Default.aspx");
}
if (response.IsSuccessStatusCode)
{
var GetResponse = await response.Content.ReadAsStringAsync();
DataTable dt = JsonConvert.DeserializeObject<DataTable>(GetResponse);
if (dt.Rows.Count == 1)
{
row = dt.Rows[0];
}
}
}
}
}
catch (Exception ex)
{
var message = new JavaScriptSerializer().Serialize(ex.Message.ToString());
var script = string.Format("alert({0});", message);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "", script, true);
}
}
You should avoid async void - it's intended for event handlers. So GetSelectedTaskDetails should be async Task instead of async void. Once GetSelectedTaskDetails is properly returning a Task, you can await it in your Page_Load:
protected async void Page_Load(object sender, EventArgs e)
{
await GetSelectedTaskDetails(Id);
...
}
Note that for async to work properly on ASP.NET pre-Core, you need to set Page.Async to true and ensure httpRuntime#targetFramework is set to 4.5 or newer in your web.config
I have a winform with a SfComboBox. When a selection is made a list of dates is retrieved from a cloud data base, and those dates are used to populated another combobox.
The combobox has .DropDownStyle set to DropDownList and SelectedIndexChanged handled by
private async void Sf_collectionDDL_SelectedIndexChanged(object sender, EventArgs e)
{
var cmb = sender as SfComboBox;
if (cmb.SelectedIndex < 0)
{
sf_datesDDL.SelectedItems.Clear();
return;
}
string collectionName = cmb.SelectedItem.ToString();
await GetCollectionDates(collectionName);
sf_datesDDL.DataSource = CollectionDates;
sf_datesDDL.ValueMember = "Value";
sf_datesDDL.DisplayMember = "Formatted";
sf_datesDDL.MaxDropDownItems = 12;
}
private Task GetCollectionDates(string collectionName)
{
return Task.Run(() =>
{
var builder = Builders<BsonDocument>.Filter;
var filter = builder.Eq("Type", "Header");
var headerDocuments =
Database
.GetCollection<BsonDocument>(collectionName)
.Find(filter)
.ToList()
;
CollectionDates = new SortedSet<ListItem_Date>();
foreach (BsonDocument doc in headerDocuments)
{
DateTime rangeStart = doc["DateStart"].ToUniversalTime().Date;
DateTime rangeEnd = doc["DateEnd"].ToUniversalTime().Date;
for (DateTime dt = rangeStart; dt < rangeEnd; dt = dt.AddDays(1))
{
CollectionDates.Add(new ListItem_Date(dt));
}
}
});
}
Everything works fine when events triggered by person driven UI operations, mouse clicks, etc.
To speed up some debugging (by reaching a specific state of selections and data retrievals) I am trying to make the selections programmatically from inside the form constructor.
private SortedSet<ListItem_Date> CollectionDates { get; set; }
public Form1()
{
InitializeComponent();
WindowState = FormWindowState.Maximized;
sfDataGrid1.EnableDataVirtualization = true;
// host during debugging
sf_hostDDL.DataSource = new List<string>() { "###hidden###" };
sf_hostDDL.SelectedIndex = 0; // loads database names into DDL
sf_databaseDDL.SelectedIndex = 0; // automatically select first database
radioXYZ.Checked = true;
CollectionsDDL_Update(); // do same "DDL_update" UI click on radioXYZ would have done
// Changing the selected index triggers the async/await method
sf_collectionDDL.SelectedIndex = 0; // automatically select first collection
// At this point the CollectionDates property is still null and exception ensues
// The selectedIndex assignment did not 'await' the innards of
// Sf_collectionDDL_SelectedIndexChanged() as I expected.
// Check first three dates
sf_datesDDL.SelectedItems.Add(CollectionDates.Take(3));
}
What is a good strategy to avoid the exception and programmatically achieve the selections I want in order to reach the 'state' I need to be at.
You shouldn't do that on the constructor because events aren't being fired yet.
Try the OnLoad override or the Load event.
The problem is that the event handler is async void.
private async void Sf_collectionDDL_SelectedIndexChanged(object sender, EventArgs e)
An async void method can't be awaited, so you must find some indirect way to await the handler to complete. There must surely exist better ways to do it, but here is a not particularly pretty one. You can declare a TaskCompletionSource member inside the Form, that will represent the asynchronous completion of the event handler:
private TaskCompletionSource<bool> Sf_collectionDDL_SelectedIndexChangedAsync;
private async void Sf_collectionDDL_SelectedIndexChanged(object sender, EventArgs e)
{
Sf_collectionDDL_SelectedIndexChangedAsync = new TaskCompletionSource<bool>();
try
{
var cmb = sender as SfComboBox;
//...
await GetCollectionDates(collectionName);
//...
sf_datesDDL.MaxDropDownItems = 12;
Sf_collectionDDL_SelectedIndexChangedAsync.SetResult(true);
}
catch (Exception ex)
{
Sf_collectionDDL_SelectedIndexChangedAsync.SetException(ex);
}
}
Then in the constructor after changing the SelectedIndex, wait for the completion of the asynchronous operation:
sf_collectionDDL.SelectedIndex = 0;
Sf_collectionDDL_SelectedIndexChangedAsync.Wait();
I created a login page and registration page in windows phone 8.1 app using sqlite database. When I login through the values from database how to create a mail system similar to normal mailing services like gmail using sqlite database.
(or)
How to save particular user data with respect to the user logged in. When the user login to the mainpage his data should be displayed.
Please answer the above both questions.
I successfully created login and registration page and I can insert values to the database. After navigating to the new page what should I code in order to show the data of the logged in user
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/ebook.db";
var con = new SQLiteAsyncConnection(dbpath);
await con.CreateTableAsync<Register>();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/ebook.db";
var con = new SQLiteAsyncConnection(dbpath);
await con.CreateTableAsync<Register>();
Register m = new Register();
m.Name = text_reg.Text;
m.Password = text_password.Password;
string r = "";
if (radio_male.IsChecked == true)
{
r = "Male";
}
else
{
r = "Female";
}
m.Gender = r;
m.State = ((ComboBoxItem)combo_box.SelectedItem).Content.ToString();
await con.InsertAsync(m);
MessageDialog md = new MessageDialog("success");
await md.ShowAsync();
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
Windows.Storage.ApplicationDataContainer data = Windows.Storage.ApplicationData.Current.LocalSettings;
data.Values["check"] = text_reg.Text;
var dbpath = ApplicationData.Current.LocalFolder.Path + "/ebook.db";
var con = new SQLiteAsyncConnection(dbpath);
Register t = new Register();
string query = string.Format("select Name,Password from Register where Name='{0}' and Password='{1}'", text_user.Text, text_pass.Password);
List<Register> mylist = await con.QueryAsync<Register>(query);
if (mylist.Count == 1)
{
t = mylist[0];
}
if (t.Name == text_user.Text && t.Password == text_pass.Password)
{
this.Frame.Navigate(typeof(MainPage));
}
else
{
var messagedialog = new MessageDialog("Unsuccessful").ShowAsync();
}
}
The above code runs successfully. After navigating to next page(i.e MainPage) how to show the particular data
Ok, the mailing system part of your question I couldn't fully understand it.
as for the second part, you have many options.
Use a static property that will hold t and reuse it in every page in your app if you want.
Use a ViewModel to hold any values you want to reuse across your app.
Write whatever values you want to a Temp file within your app scope/domain
The easiest way is option 1.
just add public static Register CurrentUser { get; set; }; to your App.xaml.cs.
and you can access this variable via App.CurrentUser.Name and App.CurrentUser.Password
and don't forget to set CurrentUser before your navigation to main Page.
App.CurrentUser = t;
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.