Listbox move items - listbox

// Users
IEnumerable<String> selected_user_ids = from ListItem item in SelectedUsersListBox.Items select item.Value;
IEnumerable<RuleUser> existing_rule_users = dc.RuleUsers.Where(ru => ru.RuleID == ruleId && selected_user_ids.Contains(ru.MFAUserID.ToString()));
IEnumerable<String> existing_user_ids = existing_rule_users.Select(ru => ru.MFAUserID.ToString());
IEnumerable<RuleUser> delete_rule_users = dc.RuleUsers.Where(ru => ru.RuleID == ruleId).Except(existing_rule_users);
IEnumerable<String> new_user_ids = selected_user_ids.Except(existing_user_ids);
dc.RuleUsers.DeleteAllOnSubmit(delete_rule_users);
foreach (String userid in new_user_ids)
{
RuleUser rule_user = new RuleUser();
rule_user.MFAUserID = new Guid(userid);
rule_user.RuleID = ruleId;
dc.RuleUsers.InsertOnSubmit(rule_user);
}
protected void AddUserButton_Click(object sender, EventArgs e)
{
ListItem item;
while ((item = UnselectedUsersListBox.SelectedItem) != null)
{
SelectedUsersListBox.Items.Add(item);
UnselectedUsersListBox.Items.Remove(item);
}
}
protected void RemoveUserButton_Click(object sender, EventArgs e)
{
ListItem item;
while ((item = SelectedUsersListBox.SelectedItem) != null)
{
UnselectedUsersListBox.Items.Add(item);
SelectedUsersListBox.Items.Remove(item);
}
}

Related

asp.net mvc core A second operation was started on the context before the first operation is completed

I am using this code for authorization on controllers.
with [Authorize(Policy = "CustomRole")]
The thing happened that after 3 or 4 request it fails with
A second operation started on this context before a previous operation completed
public class CustomRoleRequirement : AuthorizationHandler<CustomRoleRequirement>, IAuthorizationRequirement
{
public CMSContext _context = new CMSContext();
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRoleRequirement requirement)
{
var routeobj = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;
var c = routeobj.RouteData.Values.Values.ToList();
var keys = routeobj.RouteData.Values.Keys.ToList();
string area = "";
string id = "";
string controller = "";
string action = "";
string module = "";
foreach (var item in keys)
{
if (item=="area")
{
int indexs = keys.FindIndex(cc => cc == "area");
area = c[indexs].ToString();
}
else if (item == "id")
{
int indexs = keys.FindIndex(cc => cc == "id");
id = c[indexs].ToString();
}
else if (item == "controller")
{
int indexs = keys.FindIndex(cc => cc == "controller");
controller = c[indexs].ToString();
}
else if (item == "module")
{
int indexs = keys.FindIndex(cc => cc == "module");
module = c[indexs].ToString();
}
else if (item == "action")
{
int indexs = keys.FindIndex(cc => cc == "action");
action = c[indexs].ToString();
}
}
string modulelink = controller;
if (!string.IsNullOrEmpty(module))
{
modulelink = modulelink + "/" + module;
}
List<string> Roles = new List<string>();
int UserId = Auth.UserID;
string UserName = Auth.UserName;
if (UserName == "superadmin")
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
// apparently the error occurred here
var moduleobj = _context.AppModules.FirstOrDefault(q => q.Link == modulelink);
if (moduleobj != null)
{ // 69 role is assessing news module
//60 role is accessing page module
var RolesModulesobj = _context.AppRolesModules.FirstOrDefault(q => q.ModuleId == moduleobj.ModuleId && q.RolesId == Auth.RoleId);
if (RolesModulesobj != null)
{
string permissionsobj = RolesModulesobj.Permissions;
List<string> PermissionsListobj = permissionsobj.Split(',').Select(x => x.Trim()).ToList();
var FindFullAccess = PermissionsListobj.FirstOrDefault(q => q.Contains("FullAccess:true"));
if (FindFullAccess != null)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
var abc = PermissionsListobj.FirstOrDefault(q => q.Contains(action + ":true"));
if (abc != null)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
context.Fail();
return Task.CompletedTask;
}
}
}
}
}
The error occurred at this line above
var moduleobj = _context.AppModules.FirstOrDefault(q => q.Link == modulelink);
How can I make task wait before the second operation started in the method above?
You can't use a singleton DB context. You either create one each time you need one or you pool them.

how to use CRUD operation in MVC using class library and Entityframework

My Controller in which there are different actions for different views
// GET: Employee
public ActionResult Index)
{
List<EmployeeViewModel> Employees = null;
Employees = _DaoEmployee.FindAll();
ViewData["model"] = Employees;
return View(Employees);
}
public ActionResult Details(int id)
{
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
employee emp = _DaoEmployee.ViewEmployee(id);
return View(emp);
}
[HttpGet]
public ActionResult Create()
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
return View();
}
// POST: Employee
[HttpPost]
// public async Task<ActionResult> Create(employee emp, HttpPostedFileBase file)
// public ActionResult Create(employee emp, HttpPostedFileBase file)
public async Task<ActionResult> Create(employee emp, HttpPostedFileBase file)
{
string path = null;
emp.createdby = Convert.ToInt32(Sessions.GetSession()[0]);
emp.createddate = DateTime.Now;
emp.updatedby = Convert.ToInt32(Sessions.GetSession()[0]);
emp.updateddate = DateTime.Now;
int empid = _DaoEmployee.AddEmployee(emp);
if (empid == -1)
{
return HttpNotFound();
}
if (empid >= 1)
{
//Insert User
// string image = System.IO.Path.GetFileName(file.FileName);
if (file != null)
{
var newPath = DateTime.Now.ToString("yyyymmddMMss") + file.FileName;
path = Server.MapPath("~/Content/images/" + newPath);
file.SaveAs(path);
}
string sub = "Your Password";
cms_user u = new cms_user();
u.user_name = emp.emp_name;
u.user_image = path;
u.user_email = emp.email;
u.user_password = RandomPassword.CreatePassword();
u.entity_id = empid;
u.entity_type = "Employee";
u.user_description = emp.comment;
var pass = "Your Password is " + u.user_password;
bool result = _DaoUser.AddUser(u);
if (result == true)
{
emp_performance ep = new emp_performance();
var designation = _DaoEmployee.GetEmployeeDesignationName(emp.desig_id);
ep.emp_perf_des = "Start Working As " + designation;
ep.emp_perf_date = DateTime.Now;
ep.emp_id = empid;
bool res = _DaoEmployee.AddEmployeePerformance(ep);
if (res == true)
{
await Email.sendEmail(u.user_name, u.user_email, pass, sub);
TempData["add"] = emp.emp_name + " is Added and Email Sent Succesfully !!!";
return RedirectToAction("Index", "Employee");
}
else
{
TempData["add"] = emp.emp_name + " is Added Succesfully But Email Not Sent !!!";
return RedirectToAction("Index", "Employee");
}
}
else
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
TempData["error"] = "Error !!! Employee is not Added";
return View();
}
}
else
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
TempData["error"] = "Error !!! Employee is not Added";
return View();
}
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
TempData["error"] = "Error !!! Employee is not Added";
return View();
}
//Get
[HttpGet]
public ActionResult Edit(int id)
{
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
employee emp = _DaoEmployee.FindEmployee(id);
if (emp != null)
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name", _db.employees.FirstOrDefault(q => q.emp_id == id).desig_id);
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_status_id);
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_alternative_relationship);
return View(emp);
}
else
return HttpNotFound();
}
// POST: Employee
[HttpPost]
public ActionResult Edit(employee emp)
{
var id = emp.emp_id;
emp.email = "example#gmail.com";
emp.updatedby = emp.createdby = Convert.ToInt32(Sessions.GetSession()[0]);
emp.updateddate = DateTime.Now;
bool result = _DaoEmployee.EditEmployee(emp);
if (result == true)
{
TempData["update"] = emp.emp_name + " is Updated Succesfully !!!";
return RedirectToAction("Index", "Employee");
}
else
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name", _db.employees.FirstOrDefault(q => q.emp_id == id).desig_id);
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_status_id);
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_alternative_relationship);
TempData["error"] = "Error !!! Employee is not Updated";
return View();
}
}
// DELETE: Employee
public ActionResult Delete(int id)
{
var name = _db.employees.FirstOrDefault(q => q.emp_id == id).emp_name;
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
else
{
if (id != 0)
{
bool result = _DaoEmployee.DeleteEmployee(id);
if (result == true)
{
TempData["delete"] = name + " is Deleted Succesfully !!!";
return RedirectToAction("Index", "Employee");
}
}
}
TempData["error"] = "Error !!! User is not Deleted";
return RedirectToAction("Index", "Employee");
}
//protected override void Dispose(bool disposing)
//{
// if (disposing)
// {
// _db.Dispose();
// }
// base.Dispose(disposing);
//}
public ActionResult Profile()
{
if (!Sessions.IsEmployeeLoggedIn())
{
return View();
}
int user_id = Convert.ToInt32(Sessions.GetSession()[0]);
int id = Convert.ToInt32(Sessions.GetSession()[5]);
ViewBag.user_password = _db.cms_user.FirstOrDefault(q => q.user_id == user_id).user_password;
cms_user user = _DaoUser.FindUser(id);
//Get employee perfomance history from tbl performance
List<emp_performance> emp_his = _DaoEmployee.FindHistory(id);
ViewData["JoBHistory"] = emp_his;
//Attendance Of Employee
List<attendance> att = _DaoAttendance.FindById(id);
ViewData["attendance"] = att;
//Projects on which employee working
List<ProjectTeamModel> team = _DaoProject.FindProjectById(id);
ViewData["projteam"] = team;
//Get Employee Designation from tbl emp
int designation = _DaoEmployee.GetEmployeeDesignation(id);
ViewBag.EmployeeDesignation = _DaoEmployee.GetEmployeeDesignationName(designation);
employee emp = _db.employees.Where(e => e.emp_id == id).FirstOrDefault();
return View(emp);
}
public ActionResult Dashboard()
{
if (!Sessions.IsAdminLoggedIn())
{
return View();
}
ViewBag.image = Sessions.GetSession()[2];
int id = Convert.ToInt32(Sessions.GetSession()[5]);
employee emp = _db.employees.Where(e => e.emp_id == id).FirstOrDefault();
return View(emp);
}
public ActionResult ViewAttendance(int id)
{
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
List<attendance> att = _DaoAttendance.FindById(id);
if (att != null)
{
return View(att);
}
else
return HttpNotFound();
}
public ActionResult ViewProjects(int id)
{
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
List<ProjectTeamModel> team = _DaoProject.FindProjectById(id);
ViewData["projteam"] = team;
if (team != null)
{
return View();
}
else
return HttpNotFound();
return View();
}
public ActionResult JobHistory(int id)
{
List<emp_performance> emp_his = _DaoEmployee.FindHistory(id);
ViewData["model"] = emp_his;
return View(emp_his);
}
public ActionResult AddDesignation()
{
string desg = Request.Form["emp_desg"];
bool result = _DaoEmployee.AddDesignation(desg);
if (result == true)
{
return RedirectToAction("Dashboard", "Employee");
}
else
return HttpNotFound();
}
public ActionResult DesignationList(int Id)
{
if (Id == 1)
{
IEnumerable<emp_status> status = _db.emp_status.ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
status,
"emp_status_id",
"emp_status_name"), JsonRequestBehavior.AllowGet
);
return View(status);
}
if (Id == 2)
{
IEnumerable<designation> status = _db.designations.ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
status,
"desg_id",
"desg_name"), JsonRequestBehavior.AllowGet
);
return View(status);
}
return View("Index");
}
[HttpPost]
public ActionResult MarkAttendance(attendance att)
{
att.Date = DateTime.Now;
int Id = Convert.ToInt32(Sessions.GetSession()[5]);
att.emp_id = Id;
bool result = _DaoAttendance.AddEmployeeAttendance(att);
if (result == true)
{
return RedirectToAction("Profile", "Employee");
}
else
{
return RedirectToAction("Profile", "Employee");
}
}
public ActionResult EditUser(cms_user user, HttpPostedFileBase file)
{
string path = Sessions.GetSession()[3];
if (file != null)
{
var newPath = DateTime.Now.ToString("yyyymmddMMss") + file.FileName;
path = Server.MapPath("~/Content/images/" + newPath);
file.SaveAs(path);
}
user.user_image = path;
user.user_id = Convert.ToInt32(Sessions.GetSession()[0]);
user.entity_id = Convert.ToInt32(Sessions.GetSession()[5]);
user.entity_type = Sessions.GetSession()[4];
//user.user_description = Request.Form["user_description"];
bool result = _DaoUser.EditUser(user);
if (result == true)
{
return RedirectToAction("Profile", "Employee");
}
else
{
return RedirectToAction("Profile", "Employee");
}
}
public ActionResult AddPerformance(emp_performance ep)
{
var name = _db.employees.FirstOrDefault(q => q.emp_id == ep.emp_id).emp_name;
ep.emp_perf_date = DateTime.Now;
bool result = _DaoEmployee.AddEmployeePerformance(ep);
if (result == true)
{
TempData["add"] = "Perfomnace of " + name + " Added Successfully !!!";
return RedirectToAction("Index", "Employee");
}
else
{
TempData["error"] = "Error !!! Employee Performance is not Added";
return RedirectToAction("Index", "Employee");
}
}
}
Class Libraray Class
public class DaoEmployee
{
CmsdbEntities _db = new CmsdbEntities();
public List<EntityFramework.employee> FindAllEmployee()
{
try
{
var records = from r in _db.employees
select r;
return records.ToList();
}
catch (Exception ex)
{
return new List<EntityFramework.employee>();
}
}
public List<EmployeeViewModel> FindAll()
{
try
{
// Should be check by directly assigning
// the List<employeeV> or IEnumerable<employeeV>
var records = (from r in _db.employees
select new
{
r.emp_id,
r.emp_name,
r.emp_contactno,
r.emp_dob,
r.emp_salary,
r.emp_joindate,
r.emp_address,
emp_designation = _db.designations.FirstOrDefault(q => q.desg_id == r.desig_id).desg_name,
emp_status = _db.emp_status.FirstOrDefault(q => q.emp_status_id == r.emp_status_id).emp_status_name,
createdbyName = _db.cms_user.FirstOrDefault(q => q.user_id == r.createdby).user_name,
r.createddate,
updateddbyName = _db.cms_user.FirstOrDefault(q => q.user_id == r.updatedby).user_name,
r.updateddate
}).ToList();
List<EmployeeViewModel> employees = new List<EmployeeViewModel>();
foreach (var record in records)
{
EmployeeViewModel employee = new EmployeeViewModel();
employee.emp_id = record.emp_id;
employee.emp_name = record.emp_name;
employee.emp_contactno = record.emp_contactno;
employee.emp_dob = record.emp_dob;
employee.emp_salary = record.emp_salary;
employee.emp_joindate = record.emp_joindate;
employee.emp_address = record.emp_address;
employee.emp_designation = record.emp_designation;
employee.emp_status = record.emp_status;
employee.createdbyName = record.createdbyName;
employee.createddate = record.createddate;
employee.updatedbyName = record.updateddbyName;
employee.updateddate = record.updateddate;
employees.Add(employee);
}
return employees;
}
catch (Exception ex)
{
return new List<EmployeeViewModel>();
}
}
public List<ProjectViewModel> FindProjectsByStatus(int j)
{
throw new NotImplementedException();
}
public bool CheckEmployeePerformance(int empid, int projid)
{
try
{
var record = from r in _db.emp_performance
where r.emp_id == empid && r.proj_id == projid
select r;
if (record != null)
return true;
else
return false;
}
catch (Exception ex)
{
return false;
}
}
public object GetEmployeeDesignationName(int? desig_id)
{
return _db.designations.FirstOrDefault(a => a.desg_id == desig_id).desg_name;
}
public employee FindEmployee(int id)
{
return _db.employees.Find(id);
}
public bool EditEmployee(employee emp)
{
try
{
_db.Entry(emp).State = EntityState.Modified;
_db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public int AddEmployee(employee emp)
{
try
{
_db.Entry(emp).State = EntityState.Added;
_db.SaveChanges();
return emp.emp_id;
}
catch (Exception ex)
{
return -1;
}
}
public employee ViewEmployee(int id)
{
return _db.employees.Find(id);
}
public bool DeleteEmployee(int id)
{
try
{
employee emp = _db.employees.Find(id);
_db.employees.Remove(emp);
_db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool AddEmployeePerformance(emp_performance ep)
{
try
{
_db.Entry(ep).State = EntityState.Added;
_db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public List<emp_performance> FindHistory(int id)
{
try
{
var records = from r in _db.emp_performance
where r.emp_id == id
select r;
return records.ToList();
}
catch (Exception ex)
{
return new List<emp_performance>();
}
}
public bool AddDesignation(string desg)
{
designation d = new designation();
d.desg_name = desg;
try
{
_db.Entry(d).State = EntityState.Added;
_db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public dynamic GetEmployeeDesignation(int id)
{
int? desig = _db.employees.FirstOrDefault(u => u.emp_id == id).desig_id;
return desig;
}
public dynamic GetEmployeeDesignationName(int designation)
{
string desig = _db.designations.Where(u => u.desg_id == designation).FirstOrDefault().desg_name;
return desig;
}
}
What is the benefits of using class library classes, Can anyone explain?

MvvmCross: Binding warning on iOS device

I´ve created my bindings like Stuart told in this Post: MvvmCross - How to bind UIView.Layer.AnyProperty (Xamarin.iOS) to a property on a viewmodel?
This works well on simulator, but not on a iOS device. I already added LinkerPleaseInclude.cs but this changed nothing.
Binding to BorderWidth works perfectly, binding to BorderColor shows a warning.
LinkerPleaseInclude.cs:
public class LinkerPleaseInclude
{
public void Include(UIButton uiButton)
{
uiButton.TouchUpInside += (s, e) =>
uiButton.SetTitle(uiButton.Title(UIControlState.Normal), UIControlState.Normal);
}
public void Include(UIBarButtonItem barButton)
{
barButton.Clicked += (s, e) =>
barButton.Title = barButton.Title + "";
}
public void Include(UITextField textField)
{
textField.Text = textField.Text + "";
textField.EditingChanged += (sender, args) => { textField.Text = ""; };
}
public void Include(UITextView textView)
{
textView.Text = textView.Text + "";
textView.Changed += (sender, args) => { textView.Text = ""; };
}
public void Include(UILabel label)
{
label.Text = label.Text + "";
}
public void Include(UIImageView imageView)
{
imageView.Image = new UIImage();
}
public void Include(UIDatePicker date)
{
date.Date = date.Date.AddSeconds(1);
date.ValueChanged += (sender, args) => { date.Date = DateTime.MaxValue.ToNSDate(); };
}
public void Include(UISlider slider)
{
slider.Value = slider.Value + 1;
slider.ValueChanged += (sender, args) => { slider.Value = 1; };
}
public void Include(UISwitch sw)
{
sw.On = !sw.On;
sw.ValueChanged += (sender, args) => { sw.On = false; };
}
public void Include(INotifyCollectionChanged changed)
{
changed.CollectionChanged += (s,e) => { var test = string.Format("{0}{1}{2}{3}{4}", e.Action,e.NewItems, e.NewStartingIndex, e.OldItems, e.OldStartingIndex); } ;
}
}
My code for binding:
bindingSet.Bind(this.MyUITextField.Layer)
.For(x => x.BorderColor)
.To(x => x.MyViewModelProperty.IsValid)
.WithConversion("ValidationStyleBorderColor");
bindingSet.Bind(this.MyUITextField.Layer)
.For(x => x.BorderWidth)
.To(x => x.MyViewModelProperty.IsValid)
.WithConversion("ValidationStyleBorderWidth");
bindingSet.Apply();
My converter:
public class ValidationStyleBorderColorValueConverter : MvxValueConverter<bool, CGColor>
{
protected override CGColor Convert(bool value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value == true ? Themes.Default.HighlightColor.CGColor : Themes.Default.ErrorColor.CGColor;
}
}
And the warning: MvxBind: Warning: 22,91 Failed to create target binding for binding BorderColor for MyViewModelProperty.IsValid
What am I doing wrong?
As Stuart told, including the Border properties in LinkerPleaseInclude made it.

Updating image control in Windows Phone 8

I have a HTML5 web app I can view through my mobile devices.
I have an img control that would download an image using an ashx asp.net handler.
I updated via a timer.
I am trying to port this over to a Windows Phone 8.1 app instead.
The image seems to take ages to update (if at all). This is my code:
long tick = DateTime.Now.Ticks;
BitmapImage bmp =new BitmapImage(new Uri("http://my url/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick));
imgFrame1.Source = bmp;
Is this the correct way?
this is the full code:
private async void LogIn()
{
using (var client = new HttpClient())
{
var resp = await client.PostAsJsonAsync("http://my url/UserManagement/Login.aspx/Test",
new { username = "", password = "", hubuserid = hubuserid });
var str = await resp.Content.ReadAsStringAsync();
var jsonObj = JsonConvert.DeserializeObject<UserLogIn>(str);
if (jsonObj.d.Success)
{
UpdateConnectionState("Logged In");
}
else
{
UpdateConnectionState("Not Logged In");
}
}
}
public class D
{
public string __type { get; set; }
public bool Success { get; set; }
}
public class UserLogIn
{
public D d { get; set; }
}
private string hubuserid = "";
public string Uptime { get; set; }
private byte ImageIsLoaded = 1;
private async void UpdateTime(int data)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try
{
txtInfo.Text = data.ToString();
if (ImageIsLoaded == 1)
{
ImageIsLoaded = 0;
long tick = DateTime.Now.Ticks;
BitmapImage bi = new BitmapImage(new Uri("http://www.informedmotion.co.uk/Mobile/NewFrame.ashx?b=1a=9A5C3-E1945-3D315-BB43C&c=3&m=1&t=" + tick, UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened; }
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
//throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
imgFrame1.Source = (BitmapImage)sender;
}
private void imgFrame1_ImageOpened(object sender, RoutedEventArgs e)
{
ImageIsLoaded = 1;
}
private void imgFrame1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
ImageIsLoaded = 1;
}
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
imgFrame1.ImageFailed += imgFrame1_ImageFailed;
imgFrame1.ImageOpened += imgFrame1_ImageOpened;
ConnectToHub();
}
private void ConnectToHub()
{
proxy.On<int>("broadcastMessage", data =>
{
UpdateTime(data);
});
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
UpdateConnectionState("Not Connected");
ConnectToHub();
}
else
{
UpdateConnectionState(string.Format("Success! Connected with client connection id {0}", connection.ConnectionId));
hubuserid = connection.ConnectionId;
LogIn();
}
});
connection.Error += ex =>
{
UpdateConnectionState(string.Format("An error occurred {0}", ex.Message));
};
connection.Closed += () =>
{
UpdateConnectionState(string.Format("Connection with client id {0} closed", connection.ConnectionId));
ConnectToHub();
};
connection.Reconnected += () =>
{
//LogIn();
UpdateConnectionState("The connection was re-established");
};
}
Windows.UI.Core.CoreDispatcher dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
async void UpdateConnectionState(string state)
{
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
try{
txtInfo.Text = state;
}
catch (Exception ex)
{
txtInfo.Text = ex.ToString();
}
});
}
static HubConnection connection = new HubConnection("http://www.informedmotion.co.uk/");
IHubProxy proxy = connection.CreateHubProxy("ChatHub");
If you're going to download the image, then you probably want to hooked the
Image.DownloadProgress event
Image.ImageOpened event
ImageOpened will fire once the download is complete, so at that moment you can set the .Source to it.
While it is downloading (if it's a huge image) you can either show the previous image or a place holder image (with progress bar maybe?)
BitmapImage bi = new BitmapImage(new Uri("http://www.google.com/myimage.bmp", UriKind.Absolute));
bi.DownloadProgress += bi_DownloadProgress;
bi.ImageOpened += bi_ImageOpened;
hiddenImage.Source = bi; // we need to set it to an element in the visual tree so the
// events will fire, we're going to use the hiddenImage
void bi_DownloadProgress(object sender, DownloadProgressEventArgs e)
{
throw new NotImplementedException();
}
void bi_ImageOpened(object sender, RoutedEventArgs e)
{
throw new NotImplementedException();
}
<!-- myImage is your image that you use to show stuff -->
<!-- hiddenImage is the image we use to fire the event -->
<Image x:Name="myImage"></Image>
<Image x:Name="hiddenImage" Visibility="Collapsed"></Image>

Clickhandler to delete an tablerow

I'm building an app were i add tablerows to a view programmatically. I add a deletebutton to every row that is an ImageButton. Now i have a few questions.
Can i use an ImageButton for this?
How do i get the tablerow id
where the deletebutton was clicked?
How can i convert the eventargs
from a clickhandler into MenuItemOnMenuItemClickEventArgs or vice
versa?
How should my clickhandler look like?
Here is my sourcecode:
public class CalculatorSide2 : Activity
{
private Button stepButton;
private IntentHelper intentHelper = new IntentHelper();
private string age;
private string estLife;
private string estPens;
private string[] pensions;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
intentHelper.IntentSide2(Intent, out age, out estLife,out estPens);
SetContentView(Resource.Layout.calculatorside2);
TableLayout tl_layout = FindViewById<TableLayout>(Resource.Id.tableLayout1);
ImageView plusButton = FindViewById<ImageView>(Resource.Id.plusButton);
stepButton = FindViewById<Button>(Resource.Id.cside2stepButton);
plusButton.Click += (sender, e) =>
{
PopupMenu popupMenu = new PopupMenu(this, plusButton);
popupMenu.Inflate(Resource.Menu.popupmenu);
fillPopupMenu(popupMenu);
popupMenu.Show();
popupMenu.MenuItemClick += (s1, arg) =>
{
string info = arg.Item.TitleFormatted.ToString();
string id = arg.Item.ItemId.ToString();
var inputDialog = new AlertDialog.Builder(this);
EditText userInput = new EditText(this);
userInput.InputType = (Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber);
inputDialog.SetTitle(info);
inputDialog.SetView(userInput);
inputDialog.SetPositiveButton("Ok", (ss, ee) =>
{
TextView rowInfo = new TextView(this);
rowInfo.SetLines(2);
rowInfo.TextSize = 20;
rowInfo.SetTextColor(Android.Graphics.Color.Black);
rowInfo.Text = info + ": \n" + userInput.Text + "€";
ImageButton delete = new ImageButton(this);
delete.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.delete_icon));
TableRow row = new TableRow(this);
row.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
row.SetBackgroundColor(Android.Graphics.Color.Rgb(255, 153, 0));
row.SetPadding(0, 0, 0, 30);
row.AddView(rowInfo);
row.AddView(delete);
tl_layout.AddView(row);
});
inputDialog.SetNegativeButton("Cancel", (se, es) => { });
inputDialog.Show();
};
};
stepButton.Click += (object sender, EventArgs e) =>
{
var step = new Intent(this, typeof(CalculatorSide3));
step.PutExtra("Age", age);
step.PutExtra("EstPens", estPens);
step.PutExtra("EstLife", estLife);
step.PutStringArrayListExtra("Pensions", pensions);
StartActivity(step);
};
}
private void fillPopupMenu(PopupMenu menu)
{
int groupId = 0;
int i = 0;
int menuItemId = Android.Views.Menu.First;
int menuItemOrder = Android.Views.Menu.None;
foreach (var item in Enum.GetNames(typeof(PopupMenuItems)))
{
string itemString = item.ToString();
menu.Menu.Add(groupId, menuItemId + i, menuItemOrder + i, itemString.Replace("_", " "));
i++;
}
}
}
I hope someone understands what i mean, bc english is not my native language.
public class CalculatorSide2 : Activity
{
private Button stepButton;
private IntentHelper intentHelper = new IntentHelper();
private string age;
private string estLife;
private string estPens;
private string[] pensions;
private Dictionary<int,string> temp;
private TableLayout tl_layout;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
intentHelper.IntentSide2(Intent, out age, out estLife,out estPens);
SetContentView(Resource.Layout.calculatorside2);
tl_layout = FindViewById<TableLayout>(Resource.Id.tableLayout1);
ImageView plusButton = FindViewById<ImageView>(Resource.Id.plusButton);
stepButton = FindViewById<Button>(Resource.Id.cside2stepButton);
temp = new Dictionary<int,string>();
int i = 0;
plusButton.Click += (sender, e) =>
{
PopupMenu popupMenu = new PopupMenu(this, plusButton);
popupMenu.Inflate(Resource.Menu.popupmenu);
fillPopupMenu(popupMenu);
popupMenu.Show();
popupMenu.MenuItemClick += (s1, arg) =>
{
string info = arg.Item.TitleFormatted.ToString();
string id = arg.Item.ItemId.ToString();
var inputDialog = new AlertDialog.Builder(this);
EditText userInput = new EditText(this);
userInput.InputType = (Android.Text.InputTypes.NumberFlagDecimal | Android.Text.InputTypes.ClassNumber);
inputDialog.SetTitle(info);
inputDialog.SetView(userInput);
inputDialog.SetPositiveButton("Ok", (ss, ee) =>
{
TextView rowInfo = new TextView(this);
rowInfo.SetLines(2);
rowInfo.TextSize = 20;
rowInfo.SetTextColor(Android.Graphics.Color.Black);
rowInfo.Text = info + ": \n" + userInput.Text + "€";
ImageButton delete = new ImageButton(this);
delete.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.delete_icon));
delete.Focusable = false;
delete.Clickable = false;
TableRow row = new TableRow(this);
row.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
row.SetBackgroundColor(Android.Graphics.Color.Rgb(255, 153, 0));
row.SetPadding(0, 0, 0, 30);
row.Id = 10 + i;
row.Click += new EventHandler(HandleClick);
row.AddView(rowInfo);
row.AddView(delete);
tl_layout.AddView(row);
temp.Add(row.Id,userInput.Text);
i++;
});
inputDialog.SetNegativeButton("Cancel", (se, es) => { });
inputDialog.Show();
};
};
stepButton.Click += (object sender, EventArgs e) =>
{
if (temp.Count != 0)
{
pensions = new string[temp.Count];
var j = 0;
foreach (KeyValuePair<int, string> pair in temp)
{
pensions[j] = pair.Value;
j++;
}
}
else
{
pensions = new string[0];
}
var step = new Intent(this, typeof(CalculatorSide3));
step.PutExtra("Age", age);
step.PutExtra("EstPens", estPens);
step.PutExtra("EstLife", estLife);
step.PutStringArrayListExtra("Pensions", pensions);
StartActivity(step);
};
}
private void fillPopupMenu(PopupMenu menu)
{
int groupId = 0;
int i = 0;
int menuItemId = Android.Views.Menu.First;
int menuItemOrder = Android.Views.Menu.None;
foreach (var item in Enum.GetNames(typeof(PopupMenuItems)))
{
string itemString = item.ToString();
menu.Menu.Add(groupId, menuItemId + i, menuItemOrder + i, itemString.Replace("_", " "));
i++;
}
}
public void HandleClick(object sender, EventArgs e)
{
var clickedTR = sender as TableRow;
int trId = clickedTR.Id;
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Löschen");
builder.SetMessage("Möchten Sie den Eintrag wirklich löschen?");
builder.SetPositiveButton("Ja", (ssr,args) => {
temp.Remove(trId);
tl_layout.RemoveView(clickedTR);
});
builder.SetNegativeButton("Nein",(sse,arge) => { });
builder.SetCancelable(false);
builder.Show();
}
}

Resources