Waiting for an Event to Complete - windows-phone-7.1

In Pivot control all Pivot items content is loading at a time in WindowsPhone 7.1 I am developing Cross Platform application.
Issue:
In my application each Pivot Item having WebBrowser control. When loading all Pivot Item's Content at a time java script calls are conflicted.
Requirement:
If Pivot Control having 4 Pivot Items like item1, item2, item3 and item4, then load item2 after the content of item1 load finished.
EDIT 1: I have tried the following code http://www.c-sharpcorner.com/UploadFile/1d42da/synchronization-events-and-wait-handles-in-C-Sharp/
ManualResetEvent mre = new ManualResetEvent(false);
foreach (PivotDetails pivotdetails in pivtdetailslist)
{
PivotItem pivotitem = new PivotItem();
pivotitem.Header = pivotdetails.header;
WebBrowserControl browsercontrol = new WebBrowserControl(this);
browsercontrol.Navigate(pivotdetails.url);
pivotitem.Content = browsercontrol;
mre.Reset();
myPivot.Items.Add(pivotitem);
mre.WaitOne();
}
private void webBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
mre.Set();
}
EDIT1 Issue: Waiting screen only displaying not able to see Design page.

I have used the following code for "Wait to complete the event"
foreach (PivotDetails pivotdetails in pivtdetailslist)
{
PivotItem pivotitem = new PivotItem();
pivotitem.Header = pivotdetails.header;
WebBrowserControl browsercontrol = new WebBrowserControl(this);
pivotitem.Content = browsercontrol;
mre.Reset();
myPivot.Items.Add(pivotitem);
mre.WaitOne();
}
private void webBrowser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
myPivot.isHitTestVisible = true;
}
private void myPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Pivot pivot = sender as Pivot;
PivotItem currentPivot= pivot.SelectedItem as PivotItem;
if (currentPivot.Content is WebBrowserControl)
{
WebBrowserControl bc = currentPivot.Content as WebBrowserControl;
if (bc.getWebView().Source == null)
{
bc.Navigate(pivtdetailslist[pivot.SelectedIndex].url);
bc.getWebView().LoadCompleted += new System.Windows.Navigation.LoadCompletedEventHandler(webBrowser_LoadCompleted);
myPivot.IsHitTestVisible = false;
}
}
}

Related

Update UITableViewController

I have two ViewControllers (ViewController A, ViewController B). Both are UITableviewController.
In ViewController A, I get the data from a database an put it to List<string>, so I can Display it.
I have a Navigationbar-button to go to ViewController B. In ViewController B I have List with additional Items. I can add the additional item to the database with a swipe action. This works.
When I go back to ViewController A I want to update my List, but I don't know how :(
I tried it with ViewDidAppear, but it does not work.
ViewController A:
public override void ViewDidAppear(bool animated)
{
base.ViewDidAppear(animated);
NavigationItem.Title = "Anwendungsfälle";
// Hier geht es zum Hinzufügen der Anwendungsfeleder / -fälle oder Maßnahmen zum bestehenden Katalog
this.NavigationItem.SetRightBarButtonItem(
new UIBarButtonItem(UIBarButtonSystemItem.Add,
(sender, args) =>
{
var alertController = UIAlertController.Create("Anwendungsfeld hinzufügen", "Wählen Sie eine Option aus", UIAlertControllerStyle.ActionSheet);
// Hier geht es zur Vorgefertigten Bibliothek
alertController.AddAction(UIAlertAction.Create("Aus Bibliothek hinzufügen", UIAlertActionStyle.Default, (Action) =>
{
AddAnFaViewController controller = this.Storyboard.InstantiateViewController("AddAnFaViewController") as AddAnFaViewController;
controller.firmabereich = firmabereich;
controller.bereich = bereich;
controller.zieleid = zieleid;
controller.idafe = idafe;
this.NavigationController.PushViewController(controller, true);
}));
// Abbrechen Knopf
alertController.AddAction(UIAlertAction.Create("Abbrechen", UIAlertActionStyle.Cancel, alert => Console.WriteLine("Cancel clicked")));
PresentViewController(alertController, true, null);
}),
true);
var lines = new List<string>();
using (MySqlConnection connection = new MySqlConnection("Server=xxxx;Port=3306;database=xxxxb;User Id=xxxxx;Password=xxxx;charset=utf8"))
{
string query = $"SELECT DISTINCT Anwendungsfall FROM {firmabereich} WHERE IDAFE LIKE '{idafe}' ORDER BY Anwendungsfall ASC";
string query2 = $"SELECT DISTINCT IDAFA FROM {firmabereich} WHERE IDAFE LIKE '{idafe}' ORDER BY Anwendungsfall ASC";
string query3 = $"SELECT DISTINCT PrioAnFa, Anwendungsfall FROM {firmabereich} WHERE IDAFE LIKE '{idafe}' ORDER BY Anwendungsfall ASC";
MySqlCommand command = new MySqlCommand(query, connection);
MySqlCommand command2 = new MySqlCommand(query2, connection);
MySqlCommand command3 = new MySqlCommand(query3, connection);
connection.Open();
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
anwendungsfälle.Add(reader.GetString(0));
}
}
using (MySqlDataReader reader = command2.ExecuteReader())
{
while (reader.Read())
{
anwendungsfälleid.Add(reader.GetString(0));
}
}
using (MySqlDataReader reader = command3.ExecuteReader())
{
while (reader.Read())
{
prio.Add(reader.GetString(0));
}
}
}
TableView.RowHeight = UITableView.AutomaticDimension;
TableView.EstimatedRowHeight = 40f;
TableView.ReloadData();
}
Since reloading data affects the User Interface directly you need to reload data in GCD.
DispatchQueue.main.async {
TableView.ReloadData();
}
GCD is Apple's multi threading concept; so take a time to understand how it works throughout the Application Life Cycle.
This could be the good introduction

Exception in Application start method java.lang.reflect.InvocationTargetException when using parse Double

So, I am attempting to get a GUI working for a programming project. This involved changing it from a simple scanning function to converting the userinput from the text field using parse Double. The program was able to function, but once I made the change it throws the exception in the title and terminates the program every time I run it. Yes, I do have a main method.
Here is the relevant code:
public class TaxProject extends Application implements
EventHandler<ActionEvent>
{
private Stage primaryStage;
private Button button;
public void start(Stage primaryStage)
{
Scanner input = new Scanner(System.in);
TaxInput t1 = new TaxInput();
StateTax s1 = new StateTax(); //Declaring Classes
FedTax f1 = new FedTax();
GridPane pane = new GridPane();
pane.setPadding(new Insets(10, 10, 10, 10));
pane.setVgap(8);
pane.setHgap(10);
TextField tfHrlyWage = new TextField();
TextField tfHrsPerWeek = new TextField();
TextField tfMaritalStatus = new TextField();
TextField tfIncome = new TextField();
Button btCalculate = new Button("Calculate");
pane.add(new Label("Hourly Wage: "), 0, 0);
pane.add(new Label("Hours Per Week: "), 0, 1);
pane.add(new Label("Married or Single? "), 0, 2);
pane.add(btCalculate, 0, 3);
pane.add(tfHrlyWage, 1, 0);
pane.add(tfHrsPerWeek, 1, 1);
pane.add(tfMaritalStatus, 1, 2);
pane.add(tfIncome, 1, 0);
tfHrlyWage.setPrefColumnCount(4);
tfHrsPerWeek.setPrefColumnCount(3);
tfMaritalStatus.setPrefColumnCount(7);
tfIncome.setPrefColumnCount(7);
Scene scene = new Scene(pane, 250,150);
primaryStage.setTitle("Tax Calculator");
primaryStage.setScene(scene);
primaryStage.show();
String MaritalStatus; //Used for deciding federal income tax brackets
//System.out.println("Please Enter your Hourly Wage:");
t1.HrlyWage = Double.parseDouble(tfHrlyWage.getText()); //HourlyWage Input
//System.out.println("Please Enter the hours you work per week:");
t1.HrsPerWeek = Double.parseDouble(tfHrsPerWeek.getText());
MaritalStatus = tfMaritalStatus.getText();
btCalculate.setOnAction(e -> System.out.println("Your Yearly Income After Federal and State Income Taxes is $" + f1.YearlyTakeHome));
The start method is simply setting up the GUI. Nothing makes the code wait for user input the way a console program with a scanner would.
JavaFX is event based and you should find some event/property to add a event handler/listener to and react on events/changes.
This could be a listener to the text property of the TextFields, if you want to automatically update the result on a change of the text field content
//t1.HrlyWage = Double.parseDouble(tfHrlyWage.getText());
//t1.HrsPerWeek = Double.parseDouble(tfHrsPerWeek.getText());
InvalidationListener listener = o -> {
try {
t1.HrlyWage = Double.parseDouble(tfHrlyWage.getText());
t1.HrsPerWeek = Double.parseDouble(tfHrsPerWeek.getText());
// TODO: some output???
} catch (NumberFormatException ex) {
// TODO: output error message???
}
};
tfHrlyWage.textProperty().addListener(listener);
tfHrsPerWeek.textProperty().addListener(listener);
or from the listener to the button event handler:
//t1.HrlyWage = Double.parseDouble(tfHrlyWage.getText());
//t1.HrsPerWeek = Double.parseDouble(tfHrsPerWeek.getText());
btCalculate.setOnAction(e -> {
try {
t1.HrlyWage = Double.parseDouble(tfHrlyWage.getText());
t1.HrsPerWeek = Double.parseDouble(tfHrsPerWeek.getText());
// TODO: use properties for some calculations???
} catch (NumberFormatException ex) {
// TODO: display error message???
}
System.out.println("Your Yearly Income After Federal and State Income Taxes is $" + f1.YearlyTakeHome);
});

Xamarin.Android doesn't create SQLite database

I'm trying to create a database with Xamarin.Android but both on the emulator and on the tablet I do not receive an error but nothing is created, where am I wrong?
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// create variables for our onscreen widgets
var btnCreate = FindViewById<Button>(Resource.Id.btnCreateDB);
// create DB path
var docsFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
var pathToDatabase = System.IO.Path.Combine(docsFolder, "db_sqlnet.db");
// disable the single and list buttons until the database has been created
btnSingle.Enabled = btnList.Enabled = false;
// create events for buttons
btnCreate.Click += delegate
{
var result = createDatabase(pathToDatabase);
txtResult.Text = result + "\n";
// if the database was created ok, then enable the list and single buttons
if (result == "Database created")
btnList.Enabled = btnSingle.Enabled = true;
};
private string createDatabase(string path)
{
try
{
var connection = new SQLiteConnection(path);
connection.CreateTable< Entity.Person>();
return "Database created";
}
catch (SQLiteException ex)
{
return ex.Message;
}
}
In you I would use the folder System.Environment.SpecialFolder.Personal instead of System.Environment.SpecialFolder.MyDocuments.
End when you open the connection with new SQLiteConnection(path) try to add SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create as second parameter.

Printing from Win RT Application (Windows 8.1 App)

I am developing a POS application in windows 8.1 (Universal App).
Order receipt will be printed from the application and even I am able to do so.
Printer - EPSON TM-U220D
Input - A grid is being created pragmatically with dynamic content within the ViewModel. So this grid is the input for printer
Output - In the print preview (Attahced pic 1) all looks good but when the receipt is actually printed then content is cut off from the end (Attahced pic 2)
PIC 1
PIC 2
Observations -
If I print a normal text file manually using print command (Right click file and then print), then all content is printed perfectly.
If I print that SAME content, from the application, by creating Dynamic grid, then with Small font size print is good but with bit bigger font size content again cuts off.
Tried -
Optimized the code for Creating Gird, by specifying height
Questions-
If preview is all good then why not output
Did anyone tried using ePOS-Print_SDK_141020E for Windows Store app?
Generate Dynamic Grid Code
private void AddRows(Grid grid, int count)
{
for (int i = 0; i < count; i++)
{
RowDefinition row = new RowDefinition();
row.Height = GridLength.Auto;
grid.RowDefinitions.Add(row);
}
}
private void AddColumns(Grid grid, int count)
{
for (int i = 0; i < count; i++)
{
grid.ColumnDefinitions.Add(new ColumnDefinition());
}
}
private TextBlock CreateTextBlock(string text, Color color, FontWeight fw, double fs = 10, int thick = 5)
{
if (color == null) color = Colors.Black;
TextBlock txtBlock1 = new TextBlock();
txtBlock1.Text = text;
txtBlock1.FontSize = fs;
txtBlock1.FontWeight = fw;
txtBlock1.Foreground = new SolidColorBrush(color);
txtBlock1.VerticalAlignment = VerticalAlignment.Center;
txtBlock1.Margin = new Thickness(thick);
return txtBlock1;
}
private async Task<Grid> CreateDynamicWPFGrid()
{
Grid ParentGrid = new Grid();
AddRows(ParentGrid, 8);
/* Start First Grid*/
Grid DynamicGrid = new Grid();
DynamicGrid.Width = 230;
DynamicGrid.HorizontalAlignment = HorizontalAlignment.Left;
DynamicGrid.VerticalAlignment = VerticalAlignment.Top;
DynamicGrid.Margin = new Thickness(24, 0, 0, 0);
AddColumns(DynamicGrid, 2);
AddRows(DynamicGrid, 3);
TextBlock txtBlock1 = CreateTextBlock(DateTime.Now.ToString("M/d/yy"), Colors.Black, FontWeights.Normal);
Grid.SetRow(txtBlock1, 0);
Grid.SetColumn(txtBlock1, 1);
.
.
.
.
Return ParentGrid;
}
Printer Events Code
//Register Print Contract
async Task RegisterPrintContract()
{
PrintManager manager = PrintManager.GetForCurrentView();
manager.PrintTaskRequested += OnPrintTaskRequested;
await PrintManager.ShowPrintUIAsync();
}
//Unregister Print Contract
void UnregisterPrintContract()
{
PrintManager printMan = PrintManager.GetForCurrentView();
printMan.PrintTaskRequested -= OnPrintTaskRequested;
}
void OnPrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
// If I need to be asynchronous, I can get a deferral. I don't *need*
// to do this here, I'm just faking it.
var deferral = args.Request.GetDeferral();
PrintTask printTask = args.Request.CreatePrintTask("My Print Job", OnPrintTaskSourceRequestedHandler);
printTask.Completed += OnPrintTaskCompleted;
deferral.Complete();
}
void OnPrintTaskCompleted(PrintTask sender, PrintTaskCompletedEventArgs args)
{
// TODO: Tidy up.
this._document = null;
this._pages = null;
}
async void OnPrintTaskSourceRequestedHandler(PrintTaskSourceRequestedArgs args)
{
var deferral = args.GetDeferral();
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
this._document = new PrintDocument();
this._document.Paginate += OnPaginate;
this._document.GetPreviewPage += OnGetPreviewPage;
this._document.AddPages += OnAddPages;
// Tell the caller about it.
args.SetSource(this._document.DocumentSource);
});
deferral.Complete();
}
void OnAddPages(object sender, AddPagesEventArgs e)
{
// Loop over all of the preview pages and add each one to add each page to be printied
// We should have all pages ready at this point...
foreach (var page in this._pages)
{
//this._pages[page.Key]
this._document.AddPage(this._pages[page.Key]);
}
PrintDocument printDoc = (PrintDocument)sender;
// Indicate that all of the print pages have been provided
printDoc.AddPagesComplete();
}
async void OnGetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
Grid x = await CreateDynamicWPFGrid();
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
// NB: assuming it's ok to keep all these pages in
// memory. might not be the right thing to do
// of course.
if (this._pages == null)
{
this._pages = new Dictionary<int, UIElement>();
}
if (!this._pages.ContainsKey(e.PageNumber))
{
this._pages[e.PageNumber] = x;
}
if (this._document == null)
this._document = new PrintDocument();
this._document.SetPreviewPage(e.PageNumber, this._pages[e.PageNumber]);
}
);
}
async void OnPaginate(object sender, PaginateEventArgs e)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
// I have one page and that's *FINAL* !
this._document.SetPreviewPageCount(e.CurrentPreviewPageNumber, PreviewPageCountType.Final);
});
}

Entity Framework 5 - read a record then delete it in loop

I am having issues with my application. I have a db table for a print queue. When I read from that table in a loop, once I add that record to the view model, I then want to delete it from the database...this would be the most efficient way to do it, but EF barks:
An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
I've tried using multiple contexts... but that didn't seem to work either. I've seen articles like Rick Strahl's, but frankly it was above my level of understanding, and not exactly sure if it helps my issue here and seemed quite an in depth solution for something as simple as this.
Is there a simple way to accomplish what I am trying to achieve here?
Here is my code:
public List<InventoryContainerLabelViewModel> CreateLabelsViewModel(int intFacilityId)
{
var printqRep = new Repository<InventoryContainerPrintQueue>(new InventoryMgmtContext());
var printqRepDelete = new Repository<InventoryContainerPrintQueue>(new InventoryMgmtContext());
IQueryable<InventoryContainerPrintQueue> labels =
printqRep.SearchFor(x => x.FacilityId == intFacilityId);
List<InventoryContainerLabelViewModel> labelsViewModel = new List<InventoryContainerLabelViewModel>();
if (labels.Count() > 0)
{
//Get printq record
foreach (InventoryContainerPrintQueue label in labels)
{
IEnumerable<InventoryContainerDetail> icDtls =
label.InventoryContainerHeader.InventoryContainerDetails;
//Get print details
foreach (InventoryContainerDetail icDtl in icDtls)
{
labelsViewModel.Add(new InventoryContainerLabelViewModel()
{
...
populate view model here
}
);//Add label to view model
} //for each IC detail
//Delete the printq record
printqRepDelete.Delete(label); <======== Error Here
} //foreach label loop
}//label count > 0
return labelsViewModel.ToList();
}
In the end, I added a column to the printq table for status, then in the the loop updated it to processed, then called a separate method to delete it.
public List<InventoryContainerLabelViewModel> CreateLabelsViewModel(int intFacilityId)
{
InventoryMgmtContext dbContext = new InventoryMgmtContext();
var printqRep = new Repository<InventoryContainerPrintQueue>(dbContext);
IEnumerable<InventoryContainerPrintQueue> unprintedPrtqRecs =
printqRep.SearchFor(x => x.FacilityId == intFacilityId && x.Printed == false);
List<InventoryContainerLabelViewModel> labelsViewModel = new List<InventoryContainerLabelViewModel>();
if (unprintedPrtqRecs.Count() > 0)
{
//Get printq record
foreach (InventoryContainerPrintQueue unprintedPrtqRec in unprintedPrtqRecs)
{
IEnumerable<InventoryContainerDetail> icDtls =
unprintedPrtqRec.InventoryContainerHeader.InventoryContainerDetails;
//Get container details to print
foreach (InventoryContainerDetail icDtl in icDtls)
{
labelsViewModel.Add(new InventoryContainerLabelViewModel()
{
...
}
);//Get IC details and create view model
} //for each IC detail
unprintedPrtqRec.Printed = true;
printqRep.Update(unprintedPrtqRec, unprintedPrtqRec, false);
} //foreach label loop
//Commit updated to Printed status to db
dbContext.SaveChanges();
}//label count > 0
return labelsViewModel;
}
public ActionConfirmation<int> DeletePrintQRecs(int intFacilityId)
{
InventoryMgmtContext dbContext = new InventoryMgmtContext();
var printqRep = new Repository<InventoryContainerPrintQueue>(dbContext);
IEnumerable<InventoryContainerPrintQueue> printedPrtqRecs =
printqRep.SearchFor(x => x.FacilityId == intFacilityId && x.Printed == true);
foreach (InventoryContainerPrintQueue printedPrtqRec in printedPrtqRecs)
{
//Delete the printq record
printqRep.Delete(printedPrtqRec, false);
}
//Save Changes on all deletes
ActionConfirmation<int> result;
try
{
dbContext.SaveChanges();
result = ActionConfirmation<int>.CreateSuccessConfirmation(
"All Label Print Q records deleted successfully.",
1);
}
catch (Exception ex)
{
result = ActionConfirmation<int>.CreateFailureConfirmation(
string.Format("An error occured attempting to {0}. The error was: {2}.",
"delete Label Print Q records",
ex.Message),
1
);
}
return result;
}

Resources