I have this button which opens a window with a canvas. When I click on the canvas an event starts which should go to my first form look into 2 listboxes for the selecteditems and sends the color and shape so I can draw it in my canvas. I'm making my own custom event class.
public class MyEventArgs
{
}
I was wondering what I should write there for constructor or the items of my listbox.
like in example
public class MyEventArgs
{
public DateTime EventDateTime { get; private set; }
public MyEventArgs(DateTime eventDateTime)
{
EventDateTime = eventDateTime;
}
}
The only problem I have is to create the custom eventargs.
All the next steps I can do.
Main window
public delegate void listboxEventHandler(object sender, MyEventArgs myEventArgs);
public partial class MainWindow : Window
{
tblColorke kleur = new tblColorke();
tblVorm vorm = new tblVorm();
tblType type = new tblType();
LinqSanderDataContext db = new LinqSanderDataContext();
public event listboxEventHandler ListboxEvent;
public MainWindow()
{
InitializeComponent();
foreach (tblColorke kleur in db.tblColorkes)
{
ColorItem ci = new ColorItem
{
ColorId = kleur.ColourID,
Fill = new SolidColorBrush(Color.FromArgb(255,
Convert.ToByte(kleur.ColorR), Convert.ToByte(kleur.ColorG), Convert.ToByte(kleur.ColorB)))
};
lsbColor.Items.Add(ci);
}
foreach (tblType type in db.tblTypes)
{
lsbType.Items.Add(type);
}
foreach (tblVorm vorm in db.tblVorms)
{
lsbVorm.Items.Add(vorm);
}
foreach (tblCanvaske canvaske in db.tblCanvaskes)
{
dgCanvas.Items.Add(canvas);
}
}
void On_MyObjProperty_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
lsbColor.Items.Refresh();
}
private void canvas1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
try
{
ColorItem John = lsbColor.SelectedItem as ColorItem;
if (lsbVorm.SelectedItem == null)
throw new Exception("Please select a shape before drawing!");
Point mouseLocation = e.GetPosition(this.canvas);
tblVorm vrm = lsbVorm.SelectedItem as tblVorm;
switch (vrm.TypeID)
{
case 1:
Circle ci = new Circle(vrm.Hoogte, vrm.Breedte);
if (ci != null)
{
ci.Draw(canvas, (int)mouseLocation.X, (int)mouseLocation.Y);
ci.Paint(John.Fill);
}
break;
case 2:
Ellipse1 el = new Ellipse1(vrm.Hoogte, vrm.Breedte);
if (el != null)
{
el.Draw(canvas, (int)mouseLocation.X, (int)mouseLocation.Y);
el.Paint(John.Fill);
}
break;
case 3:
Rectangle1 re = new Rectangle1(vrm.Hoogte, vrm.Breedte);
if (re != null)
{
re.Draw(canvas, (int)mouseLocation.X, (int)mouseLocation.Y);
re.Paint(John.Fill);
}
break;
case 4:
Square sq = new Square(vrm.Hoogte, vrm.Breedte);
if (sq != null)
{
sq.Draw(canvas, (int)mouseLocation.X, (int)mouseLocation.Y);
sq.Paint(John.Fill);
}
break;
default:
break;
}
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
private void btnToevoegenKleur_Click(object sender, RoutedEventArgs e)
{
try
{
tblColorke kleur = new tblColorke();
kleur.ColorR = System.Convert.ToInt32(txtR.Text);
kleur.ColorG = System.Convert.ToInt32(txtG.Text);
kleur.ColorB = System.Convert.ToInt32(txtB.Text);
db.tblColorkes.InsertOnSubmit(kleur);
db.SubmitChanges();
txtR.Clear();
txtG.Clear();
txtB.Clear();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
private void btnToevoegenVorm_Click(object sender, RoutedEventArgs e)
{
try
{
tblVorm vorm = new tblVorm();
vorm.TypeID = ((tblType)lsbType.SelectedItem).TypeID;
vorm.Hoogte = System.Convert.ToInt32(txtHeight.Text);
vorm.Breedte = System.Convert.ToInt32(txtWidth.Text);
db.tblVorms.InsertOnSubmit(vorm);
db.SubmitChanges();
txtHeight.Clear();
txtWidth.Clear();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
private void btnCOpslaan_Click(object sender, RoutedEventArgs e)
{
try
{
LinqSanderDataContext ctx = new LinqSanderDataContext();
tblCanvaske canvasken = new tblCanvaske
{
Naam = txtNaam.ToString(),
Aangemaakt = DateTime.Now,
Aangepast = DateTime.Now
};
foreach (DrawableShape ds in canvas.Children)
{
tblTekeningening tekeningening = new tblTekeningening
{
MouseLocationX = (int)Canvas.GetLeft(ds),
MouseLocationY = (int)Canvas.GetTop(ds),
Vorm = ((tblVorm)lsbVorm.SelectedItem).VormID,
Kleur = ((ColorItem)lsbColor.SelectedItem).ColorId,
tblCanvaske = canvasken
};
ctx.tblTekeningenings.InsertOnSubmit(tekeningening);
}
ctx.SubmitChanges();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
}
protected void onListboxEvent(MyEventArgs myEventArgs)
{
if (ListboxEvent != null)
{
ListboxEvent(this, myEventArgs);
}
}
private void btnNewScrean_Click(object sender, RoutedEventArgs e)
{
}
}
}
Related
I create a class that I define some variables with their properties.
also I have two class "Form1" and "Form2".
I assign values to this variables in "Form1" but when I want to use the values in "Form2" after I assigned them and show them through MessageBox.Show(), I find out the variables are empty.
class Property
{
private string a_username;
private string a_email;
public string username
{
get { return a_username; }
set { a_username = value; }
}
public string email
{
get { return a_email; }
set { a_email = value; }
}
public string password { get; set; } = "88306540";
}
the assignment: (this function is in "Form1")
Property pro = new Property();
private void CreateUserInform()
{
userid = File.ReadLines(filePath).Skip(idx).Take(1).First();
// MessageBox.Show(userid);
HtmlElementCollection elemcol = webBrowser2.Document.GetElementsByTagName("option");
int i = 0;
string[] mailservices = new string[elemcol.Count];
foreach (HtmlElement elem in elemcol)
{
mailservices[i] = elem.InnerText;
i += 1;
}
pro.username = userid;
Random rand = new Random();
mailservice = mailservices[rand.Next(10)];
pro.email = pro.username + mailservice;
wb2func_create_mail();
}
call function: (this function is in "Form2" and it called after previous function.)
Property pro = new Property();
public void signup_fill()
{
HtmlElementCollection elemcol = site.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elemcol)
{
if (elem.Name == "login")
elem.SetAttribute("value", pro.username);
if (elem.Name == "remail")
elem.SetAttribute("value", pro.email);
if (elem.Name == "password")
elem.SetAttribute("value", pro.password);
if (elem.Name == "password2")
elem.SetAttribute("value", pro.password);
}
MessageBox.Show(pro.username);
}
I should mention that the "password" variable was shown pretty good but the others were shown empty.
also when I call them in "Form1" that I used to define them, it works just fine and shows the correct assignment.
the completely Form2 codes:
namespace Bypassing
{
public partial class Form2 : Form
{
string referal_link;
Property pro = new Property();
public Form2(Property form1Property)
{
InitializeComponent();
pro = form1Property;
}
public void signup_fill()
{
HtmlElementCollection elemcol = site.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elemcol)
{
if (elem.Name == "login")
elem.SetAttribute("value", pro.username);
if (elem.Name == "remail")
elem.SetAttribute("value", pro.email);
if (elem.Name == "password")
elem.SetAttribute("value", pro.password);
if (elem.Name == "password2")
elem.SetAttribute("value", pro.password);
}
MessageBox.Show(pro.username);
}
private void btn_fill_Click(object sender, EventArgs e)
{
signup_fill();
}
private void btn_logout_Click(object sender, EventArgs e)
{
HtmlElementCollection elemcol = site.Document.GetElementsByTagName("a");
foreach (HtmlElement elem in elemcol)
{
if (elem.InnerText == " Log out ")
elem.InvokeMember("click");
}
}
private void btn_next_link_Click(object sender, EventArgs e)
{
}
public bool btn_fill_enabled
{
get { return btn_fill.Enabled; }
set { btn_fill.Enabled = value; }
}
public bool btn_logout_enabled
{
get { return btn_logout.Enabled; }
set { btn_logout.Enabled = value; }
}
public bool btn_next_link_enabled
{
get { return btn_next_link.Enabled; }
set { btn_next_link.Enabled = value; }
}
private void avelon_site_Completed(object sender, WebBrowserNavigatedEventArgs e)
{
Form1 main_win = new Form1();
main_win.text_edit();
}
}
}
Form1 codes:
namespace BitcoinCloudMiningBypassApp
{
public partial class Form1 : Form
{
private string mailservice;
private string userid;
int idx = 29;
bool wb1flag = true;
bool wb2flag = true;
bool wb1ready = false;
bool wb2ready = false;
bool workflag = false;
bool start = false;
string filePath;
//StreamWriter file2 = new StreamWriter("avelon_users_email.txt", true);
//StreamWriter file = new StreamWriter("avelon_referal_links.txt", true);
Property pro = new Property();
private void OpenFileDialogForImportingUserId()
{
//var fileContent = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "C:\\";
openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog.FilterIndex = 1;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
filePath = openFileDialog.FileName;
btn_start.Enabled = true;
////Read the contents of the file into a stream
//var fileStream = openFileDialog.OpenFile();
//using (StreamReader reader = new StreamReader(fileStream))
//{
// fileContent = reader.ReadToEnd();
//}
}
}
}
private void CreateUserInform()
{
userid = File.ReadLines(filePath).Skip(idx).Take(1).First();
// MessageBox.Show(userid);
HtmlElementCollection elemcol = webBrowser2.Document.GetElementsByTagName("option");
int i = 0;
string[] mailservices = new string[elemcol.Count];
foreach (HtmlElement elem in elemcol)
{
mailservices[i] = elem.InnerText;
i += 1;
}
pro.username = userid;
Random rand = new Random();
mailservice = mailservices[rand.Next(10)];
pro.email = pro.username + mailservice;
//MessageBox.Show(avelon_email);
wb2func_create_mail();
}
public Form1()
{
InitializeComponent();
webBrowser2.Navigate("https://temp-mail.org/en/option/change/");
}
private void btn_start_Click(object sender, EventArgs e)
{
Form2 avelon = new Form2(pro);
avelon.Show();
//VPN vpn = new VPN();
// MessageBox.Show(vpn.ConnectVPN(vpn.SetServer(0)).ToString());
CreateAvelonUserInform();
start = true;
btn_load.Enabled = false;
btn_start.Enabled = false;
avelon.btn_logout_enabled = true;
btn_refresh.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
btn_load.Enabled = false;
btn_start.Enabled = false;
btn_next.Enabled = false;
//Process.Start("cmd.exe", "taskkill / F / im notepad.exe");
}
private void webBrowser2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (wb2flag)
{
wb2flag = false;
wb2ready = true;
if (!start)
btn_load.Enabled = wb2ready;
}
else
{
text_edit();
}
}
private void wb2func_create_mail()
{
HtmlElementCollection elemcol = webBrowser2.Document.GetElementsByTagName("option");
foreach (HtmlElement elem in elemcol)
{
if (elem.InnerText == mailservice)
elem.SetAttribute("selected", "selected");
}
HtmlElementCollection elemcol2 = webBrowser2.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elemcol2)
if (elem.GetAttribute("name") == "mail")
elem.SetAttribute("value", pro.username);
//wb2flag = true;
//workflag = true;
webBrowser2.Document.GetElementById("postbut").InvokeMember("click");
}
private void btn_load_Click(object sender, EventArgs e)
{
//OpenFileDialogForImportingUserId();
VPN vpn = new VPN();
MessageBox.Show(vpn.ConnectVPN(vpn.SetServer(0)).ToString());
//Process.Start("C:\\Users\\Hossein\\Desktop\\output.bat");
//MessageBox.Show(Environment.GetEnvironmentVariable("a", EnvironmentVariableTarget.Process));
//MessageBox.Show(Environment.GetEnvironmentVariable("a", EnvironmentVariableTarget.User));
//MessageBox.Show(Environment.GetEnvironmentVariable("a", EnvironmentVariableTarget.Machine));
}
public void text_edit()
{
txt_username.TextChanged += new EventHandler(text_change);
txt_username.Text = pro.username;
txt_email.Text = pro.email;
}
private void btn_next_Click(object sender, EventArgs e)
{
}
private void btn_refresh_Click(object sender, EventArgs e)
{
webBrowser2.Navigate("https://temp-mail.org/en/option/change/");
}
private void text_change(object s , EventArgs e)
{
Form2 avelon = new Form2(pro);
avelon.btn_fill_enabled = true;
}
}
}
Seems that password is showing fine as it's defined at the Property class itself so, each time you create a new object of that class, it will be setted by default untill you change it.
The reason you don't see the data from Form 1 at Form 2 seems to be that you aren't passing the Property object from Form 1 to Form 2, so you have a Property object filled with data at Form 1 but at Form 2 you remain with a newly created Property object. Just modify the Form 2 constructor so it accepts a Property parameter and pass it from Form 1.
Example (this goes on your Form2's code):
public Form2 (Property form1Property){
InitializeComponent();
pro = form1Property;
}
That creates a code that executes each time you create a new Form2 and requires you to pass a Property object to create it (new Form2(pro); in Form1) so it assigns Form2's Property object to the one you passed when creating it's object on Form1.
Also make your Property class public, so you can use it as a parameter at Form2's constructor.
More info about constructors here
Hope this helps you!
P.S: Looking at your code I see that you're creating a global Form2 object. You should create it at btn_start_Click before you are showing it, so data is filled up correctly (when you show it your Form1's Property object is filled, now when you create it it's not filled)
I have coded my behind code logic in xaml.cs file and now i want to move my code from code behind to ViewModel. How can this be done apart from code refactoring.
I am new to xamarin
Here is my Code behind
namespace _somename
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CareingtonFeeSchedule : ContentPage
{
private OneDentalFeeScheduleService oneDentalFeeScheduleService;
private ObservableCollection<ProviderSearchViewModel> _allGroups;
private ObservableCollection<ProviderSearchViewModel> _expandedGroups;
protected ObservableCollection<Grouping<string, FeeScheduleItem>> feeScheduleGroups;
protected ObservableCollection<FeeScheduleItem> feeScheduleItems;
private readonly AppViewModel AppViewModelInstance;
private Plugin.Geolocator.Abstractions.Position currentPosition;
private FeeScheduleModel feeScheduleDataResult;
public CareingtonFeeSchedule(AppViewModel appViewModel)
{
InitializeComponent();
AppViewModelInstance = appViewModel;
BindingContext = AppViewModelInstance;
AppViewModelInstance.IsActivityLoading = true;
LoadFeeeSchedule();
}
private void HeaderTapped(object sender, EventArgs args)
{
int selectedIndex = _expandedGroups.IndexOf(
((ProviderSearchViewModel)((Button)sender).CommandParameter));
_allGroups[selectedIndex].Expanded = !_allGroups[selectedIndex].Expanded;
UpdateListContent();
}
async Task OnHomeFeeScheduleTapped_TappedAsync(object sender, EventArgs args)
{
await Navigation.PushAsync(new AccLandPage(AppViewModelInstance));
}
private void ProviderBar_TextChanged(object sender, TextChangedEventArgs e)
{
var keyword = ProviderSearchBar.Text;
GroupedView.ItemsSource =
_expandedGroups.Where(s =>
s.Title.ToLower().Contains(keyword.ToLower()));
}
private void UpdateListContent()
{
_expandedGroups = new ObservableCollection<ProviderSearchViewModel>();
foreach (ProviderSearchViewModel group in _allGroups)
{
ProviderSearchViewModel newGroup = new ProviderSearchViewModel(group.Title, group.ShortName, group.Expanded);
if (group.Expanded)
{
foreach (Plan plan in group)
{
newGroup.Add(plan);
}
}
_expandedGroups.Add(newGroup);
}
GroupedView.ItemsSource = _expandedGroups;
}
public FeeScheduleModel FeeScheduleDataResult
{
protected set
{
feeScheduleDataResult = value;
OnPropertyChanged(nameof(FeeScheduleDataResult));
}
get => feeScheduleDataResult;
}
protected int feeScheduleCount;
public int FeeScheduleCount => feeScheduleCount;
private async Task<bool> LoadFeeeSchedule()
{
try
{
if (oneDentalFeeScheduleService == null)
{
oneDentalFeeScheduleService = new OneDentalFeeScheduleService("1dental.com");
}
var feeSchedRes = await oneDentalFeeScheduleService.GetFeeScheduleAsync(AppViewModelInstance.ZipCode, string.Empty, CancellationToken.None);
if (feeSchedRes?.Schedule?.Count > 0)
{
ConvertFeeScheuleDict(feeSchedRes.Schedule);
}
else FeeScheduleDataResult = null;
return true;
}
catch (Exception eX)
{
with the fee schedule lookup: \n{eX.Message}", "OK");
return false;
}
finally
{
AppViewModelInstance.IsActivityLoading = false;
actInd.IsRunning = false;
}
}
private void ConvertFeeScheuleDict(Dictionary<string, List<FeeScheduleItem>> feesche)
{
ObservableCollection<ProviderSearchViewModel> list = new ObservableCollection<ProviderSearchViewModel>();
ProviderSearchViewModel psm = null;
foreach (var item in feesche)
{
psm = new ProviderSearchViewModel(item.Key, "");
foreach (var valitem in item.Value)
{
Plan p = new Plan();
p.Code = valitem.Code;
p.CostDisplay = valitem.CostDisplay;
p.Description = valitem.ProcedureSecondary;
p.Name = valitem.Procedure;
psm.Add(p);
}
list.Add(psm);
}
_allGroups = list;
UpdateListContent();
}
private async void GetZipCode()
{
try
{
if (AppViewModelInstance.UserPosition == null)
{
try
{
var hasPermission = await Utils.CheckPermissions(Permission.Location);
if (!hasPermission)
{
await Navigation.PushAsync(new MainScreen());
return;
}
}
catch (Exception ex)
{
Debug.WriteLine($"Exception occurred while looking permission during Appearing event: {ex}");
}
var locator = CrossGeolocator.Current;
currentPosition = await locator.GetPositionAsync(new TimeSpan(0, 0, 0, 10, 0));
var addressList = await locator.GetAddressesForPositionAsync(currentPosition, null);
AppViewModelInstance.UserPosition = currentPosition;
foreach (var item in addressList)
{
AppViewModelInstance.ZipCode = item.PostalCode;
ZipCodeEntry.Text = item.PostalCode;
break;
}
}
else
{
var locator = CrossGeolocator.Current;
currentPosition = AppViewModelInstance.UserPosition;
var addressList = await locator.GetAddressesForPositionAsync(currentPosition, null);
foreach (var item in addressList)
{
AppViewModelInstance.ZipCode = item.PostalCode;
ZipCodeEntry.Text = item.PostalCode;
break;
}
}
LoadFeeeSchedule();
}
catch (Exception ex)
{
Debug.WriteLine($"Exception occurred while looking up location during Appearing event: {ex}");
}
}
private void ZipCodeEntry_Complete(object sender, EventArgs e)
{
if (sender != null)
{
AppViewModelInstance.ZipCode = ((Entry)sender).Text;
}
}
private void ZipCodeEntry_Changed(object sender, EventArgs e)
{
if (sender != null)
{
string _text = ((Entry)sender).Text; //Get Current Text
if (_text.Length > 5) //If it is more than your character restriction
{
_text = _text.Remove(_text.Length - 1); // Remove Last character
ZipCodeEntry.Text = _text; //Set the Old value
}
if (_text.Length == 5)
{
AppViewModelInstance.ZipCode = _text;
LoadFeeeSchedule();
}
}
}
public bool CanRefreshExecute(string tempVal = null)
{
if (AppViewModelInstance.IsRefreshing) return false;
var valToCheck = tempVal ?? AppViewModelInstance.ZipCode;
if (string.IsNullOrEmpty(valToCheck) || string.IsNullOrWhiteSpace(valToCheck)) return false;
bool isDigitString = true;
foreach (var c in valToCheck)
{
if (char.IsDigit(c)) continue;
isDigitString = false;
}
if (isDigitString) AppViewModelInstance.ZipCode = valToCheck;
return isDigitString;
}
private void GroupedView_ItemTapped(object sender, ItemTappedEventArgs e)
{
}
}
}
just export your code to the view model and set the view model as binding context of the Page. For example in the constructor:
//In the code behind
PageViewModel viewModel;
public Page()
{
this.BindingContext = viewModel = new PageViewModel();
//...
}
The ViewModel should implement INotifyPropertyChanged.
(Functions which are triggered by events have to stay in the code behind and access the view model through the ViewModel Property)
I am building a Xamarin.Android application for a Zebra TC-70 Android device. My main activity runs the scanner just fine the first time through. It gets the data from the scanner and then passes data to another activity just fine. If I cancel the new activity or complete my work and return to the first activity, the scanner does not re-initialize. Here is my code:
[Activity(Label = "MyApp", MainLauncher = true, Icon = "#mipmap/icon",
ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : AppCompatActivity, EMDKManager.IEMDKListener
{
//EMDK
private BarcodeManager _barcodeManager;
private EMDKManager _emdkManager;
private EditText _scanBarcodeEditText;
private Scanner _scanner;
void EMDKManager.IEMDKListener.OnClosed()
{
if(_emdkManager != null)
{
_emdkManager.Release();
_emdkManager = null;
}
}
void EMDKManager.IEMDKListener.OnOpened(EMDKManager p0)
{
_emdkManager = p0;
InitScanner();
}
protected override void OnResume()
{
base.OnResume();
var intent = new Intent(this, typeof(FpmsDataService));
BindService(intent, _dataServiceConnection, Bind.AutoCreate);
_scanBarcodeEditText.Text = string.Empty;
InitScanner();
}
protected override void OnPause()
{
base.OnPause();
UnbindService(_dataServiceConnection);
DeinitScanner();
if (_emdkManager != null)
{
_emdkManager.Release();
_emdkManager = null;
}
}
protected override void OnDestroy()
{
base.OnDestroy();
DeinitScanner();
if(_emdkManager != null)
{
_emdkManager.Release();
_emdkManager = null;
}
Log.Information("Destroyed FirePMS MainActivity");
Log.CloseAndFlush();
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Window.SetFlags(WindowManagerFlags.KeepScreenOn, WindowManagerFlags.KeepScreenOn);
SetContentView(Resource.Layout.Main);
_scanBarcodeEditText = FindViewById<EditText>(Resource.Id.MaintenanceScanBarcode_EditText);
//Initialize Scanner
var results = EMDKManager.GetEMDKManager(Application.Context, this);
}
private void InitScanner()
{
if(_emdkManager != null)
{
if(_barcodeManager == null)
{
try
{
//Get the feature object such as BarcodeManager object for accessing the feature.
_barcodeManager = (BarcodeManager)_emdkManager.GetInstance(EMDKManager.FEATURE_TYPE.Barcode);
_scanner = _barcodeManager.GetDevice(BarcodeManager.DeviceIdentifier.Default);
if (_scanner != null)
{
//Attach the Data Event handler to get the data callbacks.
_scanner.Data += Scanner_Data;
_scanner.Status += Scanner_Status;
_scanner.Enable();
}
else
{
Log.Error("Failed to enable scanner");
}
}
catch (ScannerException e)
{
Log.Error(e.Message);
}
catch (Exception ex)
{
Log.Error(ex.Message);
}
}
}
}
private void Scanner_Status(object sender, Scanner.StatusEventArgs e)
{
var state = e.P0.State;
if(state == StatusData.ScannerStates.Idle)
{
try
{
if (_scanner.IsEnabled &&
!_scanner.IsReadPending)
{
SetScannerConfig();
_scanner.Read();
}
}
catch (ScannerException e1)
{
Log.Error(e1.Message);
}
}
}
private void DeinitScanner()
{
if(_emdkManager != null)
{
if(_scanner != null)
{
try
{
_scanner.CancelRead();
_scanner.Disable();
_scanner.Data -= Scanner_Data;
_scanner.Status -= Scanner_Status;
_scanner.Release();
}
catch (ScannerException e)
{
Log.Error(e.Result.Description);
}
}
}
if (_barcodeManager != null)
{
_emdkManager.Release(EMDKManager.FEATURE_TYPE.Barcode);
}
_barcodeManager = null;
_scanner = null;
}
private void SetScannerConfig()
{
var config = _scanner.GetConfig();
config.SkipOnUnsupported = ScannerConfig.SkipOnUnSupported.None;
config.ScanParams.DecodeLEDFeedback = true;
config.ReaderParams.ReaderSpecific.ImagerSpecific.PicklistEx = ScannerConfig.PicklistEx.Hardware;
config.DecoderParams.Code39.Enabled = true;
config.DecoderParams.Code128.Enabled = false;
_scanner.SetConfig(config);
}
private void Scanner_Data(object sender, Scanner.DataEventArgs e)
{
var scanDataCollection = e.P0;
if((scanDataCollection != null) && (scanDataCollection.Result == ScannerResults.Success))
{
var scanData = scanDataCollection.GetScanData();
if (scanData[0].Data == null)
{
return;
}
RunOnUiThread(() => _scanBarcodeEditText.Text = scanData[0].Data);
RunOnUiThread(ProcessScan);
}
}
private void ProcessScan()
{
if (string.IsNullOrEmpty(_scanBarcodeEditText.Text))
{
Toast.MakeText(this, "You must scan or enter a barcode to begin", ToastLength.Long).Show();
return;
}
else
{
var intent = new Intent(this, typeof(SecondActivity));
intent.PutExtra("ScannedData",_scanBarcodeEditText.Text);
StartActivity(intent)
}
}
}
Any suggestions would be greatly appreciated. As I indicated, the process works just fine the first time, it's when I return to this activity that the scanner is no longer initialized and doesn't come back.
I suspect the EMDK is not being properly released before the activity is restarted. If you take a look at the following article, though using Java the principle is the same and the advice there is to release the EMDK in onStop(). See the note about managing the EMDK instance about half way down.
I'm trying to change TextBox_Drukarki_Model background from class after PING. Code:
MainWindow : MetroWindow
private void Button_Drukarki_Sprawdz_Click(object sender, RoutedEventArgs e)
{
DrukarkaPing test = new DrukarkaPing(TextBox_Drukarki_IPNS.Text);
test.CheckPing();
}
Another class outside MainForm
class DrukarkaPing
{
private string adresip;
private MainWindow _form;
public DrukarkaPing(MainWindow MetroWindow)
{
_form = MetroWindow;
}
public DrukarkaPing(string adresip)
{
this.adresip = adresip;
}
public async void CheckPing()
{
try
{
Ping PingZapytanie = new Ping();
PingReply PingOdp = PingZapytanie.Send(adresip);
if (PingOdp.Status == IPStatus.Success)
{
_form.TextBox_Drukarki_Model.Background = new SolidColorBrush(Colors.Green);
}
else
{
var window = Application.Current.Windows.OfType<MetroWindow>().FirstOrDefault();
if (window != null)
await window.ShowMessageAsync("Błąd!", "Błędny adres IP lub Netbios.");
}
}
catch (Exception e)
{
var window = Application.Current.Windows.OfType<MetroWindow>().FirstOrDefault();
if (window != null)
await window.ShowMessageAsync("Błąd!", e.Message);
}
}
}
It's almost working but when IPStatus.Success, catch shows me Exception:
"Object reference not set to an instance of an object".
I have no idea what to change.I tried various combinations with MetroWindow, MainWindow or TextBox_Drukarki_Model in constructors.
Update Work now.
Main:
DrukarkaPing Sprawdznext = new DrukarkaPing(TextBox_Drukarki_IP.Text, TextBox_Drukarki_IPNS.Text);
Sprawdznext.CheckPing(TextBox_Drukarki_IP);
CS:
private string adresip;
private string test;
public TextBox TextBox_Drukarki_IP { get; set; }
public TextBox TextBox_Drukarki_IPNS { get; set; }
public DrukarkaPing(string adresip, string test)
{
this.adresip = adresip;
this.test = test;
}
public async void CheckPing(TextBox TextBox_Drukarki_IP)
{
try
{
if (test == "" || test == " ")
{
return;
}
else
{
Ping PingZapytanie = new Ping();
PingReply PingOdp = PingZapytanie.Send(adresip);
if (PingOdp.Status == IPStatus.Success)
{
TextBox_Drukarki_IP.Background = new SolidColorBrush(Colors.Green);
}
else
{
TextBox_Drukarki_IP.Background = new SolidColorBrush(Colors.Red);
}
}
}
catch (Exception e)
{
var window = Application.Current.Windows.OfType<MetroWindow>().FirstOrDefault();
if (window != null)
await window.ShowMessageAsync("Błąd!", e.Message);
}
}
I am working on a WPF web application with a MainPage which is using ninject to load pages.
Basically I am woundering if there is a way to tell NavigationService that an Id has changed because a user updated a value in a composite key.
I'll do my best to explain a little more. My MultiTagPage has a MultiTagViewModel and it shows a multitagvalue consisting of (MultiTagDef, Key, Value). There is also a DataGrid with other values with the same key and MultiTagDef. If you dubble click on one of those values the corresponding multitagvalue is showed instead.
In the database the multitagvalues are stored with composite keys (Multitagdef.Name, key, value). So if somebody updates a multitagvalue the Id is changed (say from (A, B, C) to (A, B, D)) and saved, then if the user proceeds to another multitagvalue in the datagrid (A, B, E) and perhaps deletes that object then the navigationservice try to load (A, B, C) instead of (A, B, D).
The architecture is designed for objects which has an ID column which, of course, never changes. Unfortunately adding an ID column is not an option in this case. So does anyone have a suggestion of how to solve this? Should I try to reload the page everytime somebody saves or could I tell the NavigationService that the current object now has changed ID?
Now, code:
From MainPage:
public partial class MainPage : IUIService
{
public static readonly DependencyProperty MainModelProperty = PropertyHelper.Register<MainPage>(x => x.MainModel);
public MainModel MainModel
{
get { return (MainModel)GetValue(MainModelProperty); }
set { SetValue(MainModelProperty, value); }
}
private static readonly ILog log = LogManager.GetLogger(typeof(MainPage));
public MainPage()
{
// Make doubly sure...
ShowsNavigationUI = false;
InitializeComponent();
App.Kernel.Rebind<IUIService>().ToConstant(this);
MainModel = App.Kernel.Get<MainModel>();
WindowTitle = MainModel.Title;
ContentFrame.Navigating += Navigating;
ContentFrame.Navigated += Navigated;
ContentFrame.NavigationFailed += NavigationFailed;
}
private void Navigating(object sender, NavigatingCancelEventArgs args)
{
object dataContext = null;
if(ContentFrame.Content is FrameworkElement) {
dataContext = ((FrameworkElement)ContentFrame.Content).DataContext;
} else if(ContentFrame.Content is FrameworkContentElement) {
dataContext = ((FrameworkContentElement)ContentFrame.Content).DataContext;
}
if(dataContext is ISaveable && ((ISaveable)dataContext).NeedsSave) {
if(MessageControl.UnsavedSync() != MessageControl.Button.Yes) {
args.Cancel = true;
}
}
}
private void Navigated(object sender, NavigationEventArgs e)
{
var mi = e.ExtraData as MenuItemModel;
if(mi == null) {
var page = e.Content as IMenuItemPage;
if(page != null) {
mi = page.MenuItem;
}
if(mi == null) {
log.DebugFormat("Navigated to {0} ({1}) without menu item", e.Content, e.Uri);
return;
}
}
MainModel.CurrentMenuItem = mi;
if(mi.Type != MenuItemType.Folder) {
Settings.Default.AddRecentMenuItem(new RecentMenuItem(mi.MenuItem));
}
}
#region Generic Edit command
private void EditCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.Handled = true;
e.CanExecute = false;
var param = Unwrap(e.Parameter);
var paramType = GetEditType(param);
if(paramType == null || !editPages.ContainsKey(paramType)) {
return;
}
e.CanExecute = ToConstructorArgument(param) != null;
}
private void EditExecuted(object sender, ExecutedRoutedEventArgs e)
{
Edit(e.Parameter);
}
private void Edit(object param)
{
var paramType = GetEditType(param);
if(paramType == null || !editPages.ContainsKey(paramType)) {
log.WarnFormat("Page for param {0} (type {1}) not found", param, paramType);
return;
}
if(param is IList) {
var list = (IList)param;
if(list.Count > 1000) {
Show("Too many items selected", "Please select no more than 1000 items at a time", messageTheme: MessageTheme.Warning);
return;
}
}
var arg = ToConstructorArgument(param);
if(arg == null) {
log.Warn("Unexpected parameter " + param + " supplied to EditExecuted");
return;
}
var pageType = editPages[paramType];
try {
log.DebugFormat("Got a parameter of type {0}, navigating to edit page {1}", param.GetType(), pageType);
Navigate(MakePage(pageType, arg));
} catch(Exception ex) {
log.Error("Unable to load edit page for parameter " + param, ex);
}
}
private static Page MakePage(Type pageType, params IParameter[] p)
{
var page = (Page)App.Kernel.Get(pageType, p);
var dp = ClientUtil.GetViewModelProperty(page.GetType());
if(dp != null) {
page.Loaded += (o, args) => {
var skrap = App.Kernel.Get(dp.PropertyType, p);
page.SetValue(dp, App.Kernel.Get(dp.PropertyType, p));
};
page.Unloaded += (o, args) => {
try {
page.ClearValue(dp);
} catch(Exception e) {
// Often happens when datagrid is in edit mode when navigating away from page:
// http://connect.microsoft.com/VisualStudio/feedback/details/571967/wpf-datagrid-causes-crash-with-sorting-is-not-allowed-during-an-addnew-or-edititem-transaction
log.Warn("Error while unloading page", e);
}
};
ViewModelBehavior.SetUpdateUIError(page, true);
}
return page;
}
#endregion
#region Navigate command
private void NavigateCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = e.Parameter is Type;
e.Handled = true;
}
private void NavigateExecuted(object sender, ExecutedRoutedEventArgs e)
{
var type = e.Parameter as Type;
if(type == null) {
return;
}
Navigate(MakePage(type));
e.Handled = true;
}
#endregion
#region IUIService implementation
public void Navigate(Type type, params Tuple<string, object>[] parameters)
{
Navigate(MakePage(type, parameters.Select(x => new ConstructorArgument(x.Item1, x.Item2)).ToArray()));
}
public void Navigate(Type type, MenuItemModel menuItem, params Tuple<string, object>[] parameters)
{
Navigate(MakePage(type, parameters.Select(x => new ConstructorArgument(x.Item1, x.Item2))
.Prepend(new ConstructorArgument("menuItem", menuItem))
.Prepend(new ConstructorArgument("props", menuItem.Params))
.ToArray()),
menuItem);
}
public void Navigate(Page content, object extraData = null)
{
if(ContentFrame != null) {
if(ContentFrame.Content is DependencyObject) {
foreach(var dg in WpfUtil.FindDescendants<DataGrid>((DependencyObject)ContentFrame.Content)) {
while(!dg.CommitEdit()) { /* Keep committing */ }
}
}
ContentFrame.Navigate(content, extraData);
}
}
public bool NavigateBack()
{
if(ContentFrame != null && ContentFrame.CanGoBack) {
ContentFrame.GoBack();
return true;
}
if(NavigationService != null && NavigationService.CanGoBack) {
NavigationService.GoBack();
return true;
}
return false;
}
}
Please tell me if you need more information.