Hello.I am currently working on a VS form app with pictureboxes gerating random images.Down below i have posted a simplified version of my programme, where error occurs.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
BackgroundImageLayout = ImageLayout.Stretch;
}
int[] random = new int[16];
public void LoadImages()
{
List<Image> images = new List<Image>();
Random rand = new Random();
images.Add(Properties.strings.firsthero);
images.Add(Properties.strings.secondhero);
images.Add(Properties.strings.thirdhero);
images.Add(Properties.strings.fourthhero);
images.Add(Properties.strings.fifthhero);
images.Add(Properties.strings.sixthhero);
images.Add(Properties.strings.seventhhero);
images.Add(Properties.strings.eighthero);
images.Add(Properties.strings.ninethhero);
images.Add(Properties.strings.tenthhero);
images.Add(Properties.strings.eleventhhero);
images.Add(Properties.strings.twelevethhero);
images.Add(Properties.strings.thirteenthhero);
images.Add(Properties.strings.fourteenthhero);
images.Add(Properties.strings.fifteenthhero);
random[0] = rand.Next(images.Count);
pictureBox1.Image = images[random[0]];
random[1] = rand.Next(images.Count);
pictureBox2.Image = images[random[1]];
random[2] = rand.Next(images.Count);
pictureBox3.Image = images[random[2]];
random[3] = rand.Next(images.Count);
pictureBox4.Image = images[random[3]];
random[4] = rand.Next(images.Count);
pictureBox5.Image = images[random[4]];
random[5] = rand.Next(images.Count);
pictureBox6.Image = images[random[5]];
random[6] = rand.Next(images.Count);
pictureBox7.Image = images[random[6]];
random[7] = rand.Next(images.Count);
pictureBox8.Image = images[random[7]];
random[8] = rand.Next(images.Count);
pictureBox9.Image = images[random[8]];
random[9] = rand.Next(images.Count);
pictureBox10.Image = images[random[9]];
random[10] = rand.Next(images.Count);
pictureBox11.Image = images[random[10]];
random[11] = rand.Next(images.Count);
pictureBox12.Image = images[random[11]];
random[12] = rand.Next(images.Count);
pictureBox13.Image = images[random[12]];
random[13] = rand.Next(images.Count);
pictureBox14.Image = images[random[13]];
random[14] = rand.Next(images.Count);
pictureBox15.Image = images[random[14]];
random[15] = rand.Next(images.Count);
pictureBox16.Image = images[random[15]];
}
private void btnStart_Click(object sender, EventArgs e)
{
LoadImages();
}
private void button2_Click(object sender, EventArgs e)
{
button2.Visible = false;
button2WasClicked = true;
button1Match();
//the same for other buttons
}
public void button1Match()
{
if(button1WasClicked == true)
{
if(button2WasClicked == true)
{
if (random[0] == random[1])
{
winsNumber++;
}
}
else if(button3WasClicked == true)
{
if (random[0] == random[2])
{
winsNumber++;
}
}
else if(button4WasClicked == true)
{
if (random[0] == random[3])
{
winsNumber++;
}
}
else if(button5WasClicked == true)
{
if (random[0] == random[4])
{
winsNumber++;
}
}
else if(button6WasClicked == true)
{
if (random[0] == random[5])
{
winsNumber++;
}
}
else if(button7WasClicked == true)
{
if (random[0] == random[6])
{
winsNumber++;
}
}
else if(button8WasClicked == true)
{
if (random[0] == random[7])
{
winsNumber++;
}
}
else if(button9WasClicked == true)
{
if (random[0] == random[8])
{
winsNumber++;
}
}
else if(button10WasClicked == true)
{
if(random[0] == random[9])
{
winsNumber++;
}
}
else if(button11WasClicked == true)
{
if (random[0] == random[10])
{
winsNumber++;
}
}
else if(button12WasClicked == true)
{
if (random[0] == random[11])
{
winsNumber++;
}
}
else if(button13WasClicked == true)
{
if (random[0] == random[12])
{
winsNumber++;
}
}
else if(button14WasClicked == true)
{
if (random[0] == random[13])
{
winsNumber++;
}
}
else if(button15WasClicked == true)
{
if (random[0] == random[14])
{
winsNumber++;
}
}
else if(button16WasClicked == true)
{
if (random[0] == random[15])
{
winsNumber++;
}
}
}
wins.Text = winsNumber.ToString();
}
So basically I am generatinf random indexes from image list and via them show random images in picture boxes.To find out whether a match between two pictures occurs, I check the indexes of the images in the buttons.
However the problem is that the random[0] = rand.Next(images.Count); only genrates number in the void, and does not assign random[0] value to the global array. Possible solutins?
Related
I have a report viewer in reportviewer.aspx. After I generated the report, I chose Excel format and click Export. I found that in backend, when I press the export button, it goes to load the data again and it make export take 20 minutes or more. I am doubting whether the export is just dumping the already generated report content or will load the functions and do the calculation once again. How can I avoid the export to do the calculation again but just dumping the already generated report?
Here is my code behind the reportviewer.aspx.
public partial class ReportViewer : CustomPage
{
private string _reportSourceFolder = ConfigurationManager.AppSettings["ReportSourceFolder"];
protected void Page_Load(object sender, EventArgs e)
{
try
{
EW_REPORTS, true); // added by HC on 2014-10-21, for permission checking
string reportFileName = Request.QueryString["ReportFileName"];
if (string.IsNullOrEmpty(reportFileName))
{
}
else
{
int? yearInt = null;
string year = Request.QueryString["Year"];
if (string.IsNullOrEmpty(year))
{
yearInt = DateTime.Now.Year;
}
else
{
try
{
yearInt = Convert.ToInt32(year);
}
catch { }
}
string reportFullPath = Path.Combine(_reportSourceFolder, reportFileName);
Telerik.Reporting.UriReportSource uriReportSource = new Telerik.Reporting.UriReportSource();
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("lang", WebUtil.GetLanguage()));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("companyID", WebUtil.GetCompanyID()));
if (yearInt != null)
{
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("year", yearInt));
}
if (
!"AuditReport.trdx".Equals(reportFileName, StringComparison.OrdinalIgnoreCase)
//"Report1.trdx".Equals(reportFileName, StringComparison.OrdinalIgnoreCase)
//|| "ESGSummaryReport.trdx".Equals(reportFileName, StringComparison.OrdinalIgnoreCase)
)
{
int? fromYear = Common.Util.TryToConvertToInt32(Request.QueryString["fromYear"]);
int? fromMonth = Common.Util.TryToConvertToInt32(Request.QueryString["fromMonth"]);
int? toYear = Common.Util.TryToConvertToInt32(Request.QueryString["toYear"]);
int? toMonth = Common.Util.TryToConvertToInt32(Request.QueryString["toMonth"]);
string indicatorIDs = Request.QueryString["indicatorIDs"];
string locationIDs = Request.QueryString["locationIDs"];
if (fromYear == null || fromMonth == null || toYear== null || toMonth == null)
{
try
{
DateTime? fiscalYearStartDate = Util.GetCorporateFiscalYearStartDate();
if (fiscalYearStartDate != null)
{
DateTime now = DateTime.Now;
DateTime startDate = new DateTime(now.Year, fiscalYearStartDate.Value.Month, 1);
if (now < startDate)
{
startDate = startDate.AddYears(-1);
}
DateTime endDate = startDate.AddYears(1).AddMilliseconds(-1d);
if (fromYear == null)
{
fromYear = startDate.Year;
}
if (fromMonth == null)
{
fromMonth = startDate.Month;
}
if (toYear == null)
{
toYear = endDate.Year;
}
if (toMonth == null)
{
toMonth = endDate.Month;
}
}
}
catch { }
}
// prevent incorrect numbers
List<int> indicatorIDsList = new List<int>(1024);
string[] indicatorIDsArr = new string[] { };
if (indicatorIDs != null)
{
indicatorIDsArr = indicatorIDs.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
}
foreach(string indicatorID in indicatorIDsArr)
{
int? temp = Common.Util.TryToConvertToInt32(indicatorID);
if (temp != null && !indicatorIDsList.Contains(temp.Value))
{
indicatorIDsList.Add(temp.Value);
}
}
if (indicatorIDsList.Count > 0)
{
indicatorIDs = string.Join(",", indicatorIDsList);
}
else
{
indicatorIDs = "0";
}
List<int> locationIDsList = new List<int>(1024);
string[] locationIDsArr = new string[] { };
if (locationIDs != null)
{
locationIDsArr = locationIDs.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
}
foreach (string locationID in locationIDsArr)
{
int? temp = Common.Util.TryToConvertToInt32(locationID);
if (temp != null && !locationIDsList.Contains(temp.Value))
{
locationIDsList.Add(temp.Value);
}
}
if (locationIDsList.Count > 0)
{
locationIDs = string.Join(",", locationIDsList);
}
else
{
locationIDs = "0";
}
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("fromYear", fromYear));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("toYear", toYear));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("fromMonth", fromMonth));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("toMonth", toMonth));
//uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("indicatorIDs", indicatorIDs));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("locationIDs", locationIDs));
}
if ("AuditReport.trdx".Equals(reportFileName, StringComparison.OrdinalIgnoreCase))
{
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("performedDateFrom", DateTime.Now.AddDays(-1d)));
uriReportSource.Parameters.Add(new Telerik.Reporting.Parameter("performedDateTo", DateTime.Now));
}
uriReportSource.Uri = reportFullPath;
if (IsPrintPreviewMode())
{
uiReportViewer.ViewMode = Telerik.ReportViewer.WebForms.ViewMode.PrintPreview;
}
uiReportViewer.ReportSource = uriReportSource;
} // end if
}
catch (Exception ex)
{
uiPanel.Alert(Convert.ToString(HttpContext.GetGlobalResourceObject("Resource", "Message_Error_Occurs")));
Logger.Log(string.Format("Error occurs in the '{0}.{1}' method.{2}{3}"
, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString()
, System.Reflection.MethodBase.GetCurrentMethod().Name
, Environment.NewLine
, ex.ToString()));
}
} // end method
private bool IsPrintPreviewMode()
{
bool val = false;
string temp = Request.QueryString["IsPrintPreviewMode"];
if (!string.IsNullOrEmpty(temp))
{
try
{
val = Convert.ToBoolean(temp);
}
catch { }
}
return val;
}
protected void uiBack_Click(object sender, EventArgs e)
{
string reportFileName = Request.QueryString["ReportFileName"];
Response.Redirect(string.Format("~/ReportCriteria.aspx?ReportFileName={0}", reportFileName), false);
Context.ApplicationInstance.CompleteRequest();
}
}
I wrote a custom textbox for a program that is designed to give me database values without a lot of converts or checks and to have custom text input. It had a few different modes, such as an auto formatting date box and SSN. It worked great in VB.NET, but now that I'm learning C# and I'm remaking the program in C# for practice, I'm hitting a snag with the conversion. None of the events will fire.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
public class DBTextBox : TextBox {
private void InitializeComponent() {
SuspendLayout();
Enter += new EventHandler(DBTextBox_Enter);
KeyPress += new KeyPressEventHandler(On_Key_Press);
KeyUp += new KeyEventHandler(On_Key_Up);
Leave += new EventHandler(Control_Leave);
ResumeLayout(false);
}
public enum StyleTypes {
DateBox,
SSNBox,
PhoneBox,
TextBox,
IntegerBox,
DecimalBox
}
private StyleTypes Type { get; set; }
public StyleTypes StyleType {
get { return Type; }
set { Type = value; }
}
private string _Default_Value { get; set; }
public string Default_Value {
get { return _Default_Value; }
set { _Default_Value = value; }
}
private bool _AutoUpperCase = false;
public bool AutoUpperCase {
get { return _AutoUpperCase; }
set { _AutoUpperCase = value; }
}
private bool _AutoUpperCaseFirstCharOnly = false;
public bool AutoUpperCaseFirstCharOnly {
get { return _AutoUpperCaseFirstCharOnly; }
set { _AutoUpperCaseFirstCharOnly = value; }
}
private void On_Key_Up(object sender, KeyEventArgs e) {
if (e.KeyCode != Keys.Back) {
if (Type == StyleTypes.DateBox) {
if (TextLength == 2 && Text.Contains("//") == false) {
Text = Text + "/";
SelectionStart = Text.Length + 1;
}
if (TextLength == 4 && Text.Substring(1, 1) == "//" && Text.Substring(3, 1) != "//" && CharCount('/') <= 1) {
Text = Text + "/";
SelectionStart = Text.Length + 1;
}
if (TextLength == 5 && Text.Substring(2, 1) == "//" && CharCount('/') <= 1) {
Text = Text + "/";
SelectionStart = Text.Length + 1;
}
if (Text.Contains("//")) {
Text = Text.Replace(#"//", #"/");
SelectionStart = Text.Length + 1;
}
}
if (Type == StyleTypes.SSNBox) {
MaxLength = 11;
if (TextLength == 3 || TextLength == 6) {
Text = Text + "-";
SelectionStart = Text.Length + 1;
}
}
if (Type == StyleTypes.PhoneBox) {
MaxLength = 14;
if (TextLength == 3 && Text.Contains('(') == false) {
Text = "(" + Text + ") ";
SelectionStart = Text.Length + 1;
}
if (TextLength == 9) {
Text = Text + "-";
SelectionStart = Text.Length + 1;
}
}
}
}
private void Control_Leave(object sender, EventArgs e) {
if (Type == StyleTypes.DateBox) {
if (DateTime.TryParse(Text, out DateTime i)) {
BackColor = Color.FromKnownColor(KnownColor.Window);
Text = Convert.ToDateTime(Text).ToShortDateString();
} else if (string.IsNullOrWhiteSpace(Text)) {
BackColor = Color.FromKnownColor(KnownColor.Window);
Text = string.Empty;
} else {
BackColor = Color.Salmon;
}
}
}
private void On_Key_Press(object sender, KeyPressEventArgs e) {
if (Type == StyleTypes.DateBox) {
if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false) {
if (e.KeyChar == '/' && CharCount('/') <= 1) { } else { e.Handled = true; }
}
}
if (Type == StyleTypes.PhoneBox) {
if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false && e.KeyChar != '-' && e.KeyChar != '(' && e.KeyChar != ' ') {
e.Handled = true;
}
}
if (Type == StyleTypes.SSNBox) {
if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false && e.KeyChar != '-') {
e.Handled = true;
}
}
if (Type == StyleTypes.DecimalBox) {
if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false) {
if ((e.KeyChar == '.' && CharCount('.') < 1) || (e.KeyChar == '-' && CharCount('-') < 1)) { } else { e.Handled = true; }
}
}
if (Type == StyleTypes.IntegerBox) {
if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false) {
e.Handled = true;
}
}
}
private int CharCount(char Character) {
char[] Chars = Text.ToCharArray();
int Count = 0;
foreach (var Item in Chars) {
if (Item == Character) {
Count += 1;
}
}
return Count;
}
[Description("The Text in the box, returns null if Empty or White spaces")]
public string DBText {
get { if (string.IsNullOrWhiteSpace(Text)) { return null; } else { return Text; } }
set { if (string.IsNullOrWhiteSpace(value)) { Text = null; } else { Text = value; } }
}
[Description("The returned Date if the Text is a date.")]
public DateTime? DBDate {
get { if (DateTime.TryParse(Text, out DateTime i)) { return Convert.ToDateTime(Text); } else { return null; } }
set { Convert.ToDateTime(value).ToShortDateString(); }
}
public decimal? DBDecimal {
get { if (decimal.TryParse(Text, out decimal i)) { return Convert.ToDecimal(Text); } else { return null; } }
set { Text = value.ToString(); }
}
public int? DBInt {
get { if (int.TryParse(Text, out int i) && Convert.ToInt32(Text) > int.MinValue && Convert.ToInt32(Text) < int.MaxValue) { return Convert.ToInt32(Text); } else { return null; } }
set { Text = value.ToString(); }
}
public short? DBShort {
get { if (short.TryParse(Text, out short i)) { return Convert.ToInt16(Text); } else { return null; } }
set { Text = value.ToString(); }
}
private string UppercaseFirstLetter(string Input) {
if (string.IsNullOrEmpty(Input)) { return Input; }
char[] array = Input.ToCharArray();
array[0] = char.ToUpper(array[0]);
bool UpperCaseNextLetter = true;
int LastCharPos = array.Count() - 1;
if (_AutoUpperCaseFirstCharOnly) { LastCharPos = 1; }
for (int i = 0; i <= LastCharPos; i++) {
if (UpperCaseNextLetter == true) {
array[i] = char.ToUpper(array[i]);
UpperCaseNextLetter = false;
} else {
array[i] = char.ToLower(array[i]);
}
if (array[i] == ' ') {
UpperCaseNextLetter = true;
}
}
return new string(array);
}
private void DBTextBox_Enter(object sender, EventArgs e) {
if (Type == StyleTypes.DateBox) {
if (DateTime.TryParse(Text, out DateTime i)) {
SelectionStart = 0;
SelectionLength = Text.Length;
}
}
if (Type == StyleTypes.TextBox && Text.Length > 0 && _Default_Value.Length > 0) {
if (Text == _Default_Value) {
SelectionStart = 0;
SelectionLength = Text.Length;
}
}
}
}
What do I need to do to get the events to fire?
Edit: Here it is on the Debug Form I created to test it;
partial class frmDebug {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.txtDate = new DBTextBox();
this.cmdSet = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// txtDate
//
this.txtDate.AutoUpperCase = false;
this.txtDate.AutoUpperCaseFirstCharOnly = false;
this.txtDate.DBDate = null;
this.txtDate.DBDecimal = null;
this.txtDate.DBInt = null;
this.txtDate.DBShort = null;
this.txtDate.DBText = null;
this.txtDate.Default_Value = null;
this.txtDate.Location = new System.Drawing.Point(72, 52);
this.txtDate.Name = "txtDate";
this.txtDate.Size = new System.Drawing.Size(100, 20);
this.txtDate.StyleType = DBTextBox.StyleTypes.DateBox;
this.txtDate.TabIndex = 0;
//
// cmdSet
//
this.cmdSet.Location = new System.Drawing.Point(68, 128);
this.cmdSet.Name = "cmdSet";
this.cmdSet.Size = new System.Drawing.Size(75, 23);
this.cmdSet.TabIndex = 1;
this.cmdSet.Text = "Set";
this.cmdSet.UseVisualStyleBackColor = true;
this.cmdSet.Click += new System.EventHandler(this.cmdSet_Click);
//
// frmDebug
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.cmdSet);
this.Controls.Add(this.txtDate);
this.Name = "frmDebug";
this.Text = "frmDebug";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button cmdSet;
public DBTextBox txtDate;
}
I don't have any code on the Form so this is what it looks like;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
public partial class frmDebug : Form {
public frmDebug() {
InitializeComponent();
}
}
LarsTech has a better and more correct solution:
You don't call InitializeComponent from inside the TextBox. But a
class doesn't have to listen to their own events. Use the overrides
instead, example: protected override void OnKeyUp(KeyEventArgs e)
{...}
My original answer:
It looks like you'll probably just need to add a constructor for the DBTextBox class that will call your private InitializeComponent() method. It should look something like this:
public DBTextBox()
{
InitializeComponent();
}
I'm attempting to make a google map using Xamarin forms, the pins displays correctly and zooms in onto the user. It displays the inital map when the page starts, but when moving or zooming the map doesn't change and becomes grids if you zoom in enough. I can see my pin on the grid and everything, but I would like the map to load along with the pin.
public partial class IssueMap2 : ContentPage
{
public UIIssueVM Issue { get; set; }
public GeoLocation Location { get; set; }
public bool AllowPinMovment { get; set; }
private ExtendedMap.ExtendedMap map;
public Xamarin.Forms.Maps.Position OrgIssueLocation { get; set; }
bool IsGettingLocation = false;
bool bMapCtrlReady = false;
IGeolocator Locator;
public IssueMap2(UIIssueVM Issue, GeoLocation location)
{
AllowPinMovment = false;
this.Issue = Issue;
this.Location = location;
Title = "Map";
OrgIssueLocation = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
Locator = CrossGeolocator.Current;
if (Locator.DesiredAccuracy != 100)
Locator.DesiredAccuracy = 100;
if (Device.RuntimePlatform != Device.WinPhone)
{
InitializeComponent();
map = new ExtendedMap.ExtendedMap()
{
IsShowingUser = true,
HeightRequest = 100,
WidthRequest = 960,
VerticalOptions = LayoutOptions.FillAndExpand
};
map.LongTap += OnMapLongTap;
map.Ready += MapCtrlReady;
slMap.Children.Add(map);
}
}
public void MapCtrlReady(object sender, EventArgs args)
{
bMapCtrlReady = true;
}
public void OnMapLongTap(object sender, ExtendedMap.TapEventArgs args)
{
if (AllowPinMovment == false)
return;
if (Issue == null)
return;
var pos = args.Position;
// Update Issue
Issue.Latitude = pos.Latitude;
Issue.Longitude = pos.Longitude;
Issue.Changed = true;
// Update Pin
map.Pins.Clear();
AddPin(pos, Issue.Title, Issue.Description);
}
protected void AddPin(Xamarin.Forms.Maps.Position pos, String Title, String Desc)
{
// MAP pin does not like it if labels are empty
if (Title.Length == 0)
Title = "-";
if (Desc.Length == 0)
Desc = "-";
var pin = new Pin
{
Type = PinType.Place,
Position = pos,
Label = Title,
Address = Desc
};
map.Pins.Add(pin);
}
protected override void OnAppearing()
{
if (Device.RuntimePlatform == Device.WinPhone)
{
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
if (Issue.IsNew == false)
{
var position = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
AddPin(position, Issue.Title, Issue.Description);
MoveToPinLocation();
}
else // Issue is new
{
// Move to main location
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromMiles(1)));
// Get current location for new item
OnGetLocation();
}
}
}
protected override async void OnDisappearing()
{
if (Locator.IsListening)
{
await Locator.StopListeningAsync();
}
// Map controller crashes sometimes if we are to quick with exiting
await Task.Delay(500);
while (bMapCtrlReady == false)
{
await Task.Delay(500);
}
}
void OnButtonCenter(object sender, EventArgs args)
{
MoveToPinLocation();
}
void MoveToPinLocation()
{
double KmDistace = 0.5;
if (Issue != null)
{
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude), Distance.FromKilometers(KmDistace)));
}
else
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromKilometers(KmDistace)));
}
void OnButtonMainLocation(object sender, EventArgs args)
{
double KmDistace = 0.5;
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.Maps.Position(Location.Latitude, Location.Longitude), Distance.FromKilometers(KmDistace)));
}
void OnButtonGetLocation(object sender, EventArgs args)
{
OnGetLocation();
}
async void OnGetLocation()
{
if (IsGettingLocation == true)
return; // already getting location
try
{
if (Locator.IsListening == true)
{
await Locator.StopListeningAsync();
}
if (Locator.IsGeolocationAvailable == false)
{
lbPosText.Text = "GeoLocation is not available.";
this.ForceLayout();
return;
}
if (Locator.IsGeolocationEnabled == false)
{
lbPosText.Text = "GeoLocation is not enabled.";
this.ForceLayout();
return;
}
IsGettingLocation = true;
IsBusy = true;
slCommands.IsVisible = false;
aActIndicator.IsVisible = true;
aActIndicator.IsRunning = true;
lbPosText.Text = "Searching for GPS location...";
this.ForceLayout();
TimeSpan timeSpan = TimeSpan.FromTicks(120 * 1000);
var position = await Locator.GetPositionAsync(timeSpan);
// Update Issue Position
Issue.Latitude = position.Latitude;
Issue.Longitude = position.Longitude;
Issue.Changed = true;
// Update Pin Postion
var pos = new Xamarin.Forms.Maps.Position(Issue.Latitude, Issue.Longitude);
map.Pins.Clear();
AddPin(pos, Issue.Title, Issue.Description);
UpdateGPSLocationText();
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
IsGettingLocation = false;
IsBusy = false;
slCommands.IsVisible = true;
this.ForceLayout();
// Center map around pin
MoveToPinLocation();
}
catch (Exception /*ex*/)
{
aActIndicator.IsRunning = false;
aActIndicator.IsVisible = false;
IsGettingLocation = false;
IsBusy = false;
slCommands.IsVisible = true;
lbPosText.Text = "Unable to find position!";
lbPosText.IsVisible = true;
this.ForceLayout();
}
}
void UpdateGPSLocationText()
{
String text = String.Format("{0} x {1}", Issue.Longitude, Issue.Latitude);
lbPosText.Text = text;
}
}
}
Android extended map renderer
[assembly: ExportRenderer(typeof(ExtendedMap.ExtendedMap), typeof(ExtendedMapRenderer))]
namespace ExtendedMap.Android
{
public class ExtendedMapRenderer : MapRenderer, IOnMapReadyCallback
{
private GoogleMap _map;
public ExtendedMapRenderer()
{
}
public ExtendedMapRenderer(IntPtr javaReference, JniHandleOwnership jniHandleOwnership)
{
int x = 0;
x++;
}
private void InvokeOnMapReadyBaseClassHack(GoogleMap googleMap)
{
System.Reflection.MethodInfo onMapReadyMethodInfo = null;
Type baseType = typeof(MapRenderer);
foreach (var currentMethod in baseType.GetMethods(System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.DeclaredOnly))
{
if (currentMethod.IsFinal && currentMethod.IsPrivate)
{
if (string.Equals(currentMethod.Name, "OnMapReady", StringComparison.Ordinal))
{
onMapReadyMethodInfo = currentMethod;
break;
}
if (currentMethod.Name.EndsWith(".OnMapReady", StringComparison.Ordinal))
{
onMapReadyMethodInfo = currentMethod;
break;
}
}
}
if (onMapReadyMethodInfo != null)
{
onMapReadyMethodInfo.Invoke(this, new[] { googleMap });
}
}
void IOnMapReadyCallback.OnMapReady(GoogleMap googleMap)
{
InvokeOnMapReadyBaseClassHack(googleMap);
_map = googleMap;
if (_map != null)
{
_map = googleMap;
this.NativeMap = googleMap;
_map.MapClick += googleMap_MapClick;
_map.MapLongClick += googleMap_MapLongClick;
((ExtendedMap)Element).OnReady();
}
}
protected override void OnElementChanged(ElementChangedEventArgs<Map> e)
{
if (_map != null)
_map.MapClick -= googleMap_MapClick;
base.OnElementChanged(e);
if (Control != null)
((MapView)Control).GetMapAsync(this);
}
private void googleMap_MapClick(object sender, GoogleMap.MapClickEventArgs e)
{
((ExtendedMap)Element).OnTap(new Position(e.Point.Latitude, e.Point.Longitude));
}
private void googleMap_MapLongClick(object sender, GoogleMap.MapLongClickEventArgs e)
{
((ExtendedMap)Element).OnLongTap(new Position(e.Point.Latitude, e.Point.Longitude));
}
}
}
I would double check the Google Maps API key on the manifest of your application!
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzr3yCpVgSOXvTgri29nC6KqFbdO73QmoVQWEw" />
As well as your SHA-1 key of your keystore on the Google API Credential Dashboard.
I am having some problems with my Xamarin XAML page and its viewmodel.
I have written the code with a bunch of methods which are executed via commands from the XAML.
Functionally its all working as desired. However, the view is not refreshing when the methods have finished executing. So despite inserting things and removing things from my observable collections (via an API call update), and having a notifypropertychanged event, the page doesn't reload.
Any ideas?
ViewModel (Some properties omitted to fit the character limit for a post)
namespace TechsportiseApp.ViewModels
{
public class ResultsProcessViewModel : INotifyPropertyChanged
{
public ICommand AddTimingCommand { get; set; }
public ICommand AddScanCommand { get; set; }
public ICommand DeleteTimingCommand { get; set; }
public ICommand DeleteScanCommand { get; set; }
public ICommand PublishCommand { get; set; }
public ICommand LoadResultsCommand { get; set; }
public ICommand MissingFinisherCommand { get; set; }
public ICommand MissingTimingCommand { get; set; }
public int RaceId { get; set; }
public DateTime RaceDate { get; set; }
//public ResultsViewModel(Race race)
public ResultsProcessViewModel(Race race)
{
AddTimingCommand = new Command(AddTiming);
AddScanCommand = new Command(AddScan);
DeleteTimingCommand = new Command<int>(DeleteTiming);
DeleteScanCommand = new Command<int>(DeleteScan);
PublishCommand = new Command<string>(Publish);
LoadResultsCommand = new Command<int>(LoadResults);
MissingFinisherCommand = new Command(MissingFinisher);
MissingTimingCommand = new Command(MissingTiming);
Invalid = false;
AddTimingVisibility = false;
AddScanVisibility = false;
AddVisibility = true;
PublishProvisionalVisibility = false;
PublishFinalVisibility = false;
IsBusy = false;
RaceId = race.Id;
RaceDate = race.RaceDate;
RaceStartTime = Convert.ToDateTime(race.RaceStartTime);
Scans = ScansAPI.GetScans(RaceId);
Timings = TimingsAPI.GetTimings(RaceId);
Entries = EntriesAPI.GetEntries(RaceId);
LoadResults(RaceId);
}
ObservableCollection<Result> _results;
public ObservableCollection<Result> Results
{
get
{
return _results;
}
set
{
if (_results != value)
{
_results = value;
OnPropertyChanged("Results");
}
}
}
ObservableCollection<Scan> _scans;
public ObservableCollection<Scan> Scans
{
get
{
return _scans;
}
set
{
if (_scans != value)
{
_scans = value;
OnPropertyChanged("Scans");
}
}
}
ObservableCollection<Timing> _timings;
public ObservableCollection<Timing> Timings
{
get
{
return _timings;
}
set
{
if (_timings != value)
{
_timings = value;
OnPropertyChanged("Timings");
}
}
}
ObservableCollection<RaceEntry> _entries;
public ObservableCollection<RaceEntry> Entries
{
get
{
return _entries;
}
set
{
if (_entries != value)
{
_entries = value;
OnPropertyChanged("Entries");
}
}
}
ObservableCollection<Race> _races;
public ObservableCollection<Race> Races
{
get
{
try
{
var racelist = RacesAPI.GetRaces();
var sortedracelist = new ObservableCollection<Race>(racelist.OrderBy(c => c.Name));
var racecount = racelist.Count();
if (racecount == 0)
{
RaceCountZero = true;
}
else
{
RaceCountZero = false;
}
return racelist;
}
catch
{
Invalid = true;
ValidationError = "Error getting Race List. No internet connection available.";
}
return _races;
}
set
{
if (_races != value)
{
_races = value;
OnPropertyChanged("Races");
}
}
}
string _aboveBelow;
public string AboveBelow
{
get { return _aboveBelow; }
set
{
if (_aboveBelow == value)
return;
_aboveBelow = value;
OnPropertyChanged("AboveBelow");
}
}
string _aboveBelowPosition;
public string AboveBelowPosition
{
get { return _aboveBelowPosition; }
set
{
if (_aboveBelowPosition == value)
return;
_aboveBelowPosition = value;
OnPropertyChanged("AboveBelowPosition");
}
}
string _addHH;
public string AddHH
{
get { return _addHH; }
set
{
if (_addHH == value)
return;
_addHH = value;
OnPropertyChanged("AddHH");
}
}
string _addMM;
public string AddMM
{
get { return _addMM; }
set
{
if (_addMM == value)
return;
_addMM = value;
OnPropertyChanged("AddMM");
}
}
string _addSS;
public string AddSS
{
get { return _addSS; }
set
{
if (_addSS == value)
return;
_addSS = value;
OnPropertyChanged("AddSS");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var changed = PropertyChanged;
if (changed != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
void AddTiming()
{
AddScanVisibility = false;
AddTimingVisibility = !AddTimingVisibility;
}
void AddScan()
{
AddScanVisibility = !AddScanVisibility;
AddTimingVisibility = false;
}
void MissingFinisher()
{
//Do stuff when deleting a scan. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
var scancount = Scans.Count();
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot add a scan whilst you are offline");
else if (string.IsNullOrEmpty(MissingBib))
throw new Exception("You must enter a bib number");
else if (string.IsNullOrEmpty(AboveBelow))
throw new Exception("You must choose if you are adding the bib above or below");
else if (string.IsNullOrEmpty(AboveBelowPosition))
throw new Exception("You must enter the position you are inserting " + AboveBelow);
else if (Convert.ToInt32(AboveBelowPosition) > scancount)
throw new Exception("The position you have chosen to insert above or below does not exist. Please enter a valid value");
else if (Convert.ToInt32(AboveBelowPosition) < 1)
throw new Exception("The position you have chosen to insert above or below does not exist. Please enter a valid value");
//We are good to go
else
{
var InsertedSequence = new int();
var abovebelow = Scans.SingleOrDefault(i => i.Position == Convert.ToInt32(AboveBelowPosition));
var abposition = Convert.ToInt32(AboveBelowPosition);
if (AboveBelow == "Above")
{
InsertedSequence = abovebelow.Sequence + 5;
}
else if (AboveBelow == "Below")
{
InsertedSequence = abovebelow.Sequence - 5;
}
else
{
return;
}
//Need to add resequencing and reallocation of position numbers
var scan = new ScanPost
{
RaceId = RaceId,
BibNumber = MissingBib,
Sequence = InsertedSequence,
Position = abposition,
Reorder = true,
Status = 0
};
var createscan = ScansAPI.CreateScan(scan);
if (createscan.Code != "Created")
throw new Exception("Error creating scan");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Results");
}
});
}
void MissingTiming()
{
Task.Run(() =>
{
try
{
var timingcount = Timings.Count();
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot add a timing whilst you are offline");
//We are good to go
else
{
if (AddHH == "") { AddHH = "0"; }
if (AddMM == "") { AddMM = "0"; }
if (AddSS == "") { AddSS = "0"; }
var ManualEndTime = RaceStartTime.AddHours(Convert.ToDouble(AddHH))
.AddMinutes(Convert.ToDouble(AddMM))
.AddSeconds(Convert.ToDouble(AddSS));
var timing = new TimingPost
{
RaceId = RaceId,
StartTime = RaceStartTime,
EndTime = ManualEndTime,
Reorder = true,
Position = 0,
Status = 0
};
var createtiming = TimingsAPI.CreateTiming(timing);
if (createtiming.Code != "Created")
throw new Exception("Error creating timing");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
Device.BeginInvokeOnMainThread(() => LoadResults(RaceId));
Device.BeginInvokeOnMainThread(() => OnPropertyChanged("Results"));
}
});
}
void DeleteTiming(int timingid)
{
//Do stuff when deleting a timing. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot delete a timing whilst you are offline");
//We are good to go
else
{
var deletetiming = TimingsAPI.DeleteTiming(timingid);
if (deletetiming.Code != "NoContent")
throw new Exception("Error deleting timing");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Timings");
Device.BeginInvokeOnMainThread(() => LoadResults(RaceId));
Device.BeginInvokeOnMainThread(() => OnPropertyChanged("Timings"));
}
});
}
void DeleteScan(int scanid)
{
//Do stuff when deleting a scan. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot delete a scan whilst you are offline");
//We are good to go
else
{
var deletetiming = TimingsAPI.DeleteTiming(scanid);
if (deletetiming.Code != "NoContent")
throw new Exception("Error deleting scan");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Results");
}
});
}
void Publish(string status)
{
Task.Run(() =>
{
try
{
var publish = new Publish();
publish.RaceId = RaceId;
publish.ResultStatus = status;
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot publish results whilst you are offline");
//We are good to go
else
{
var publishrace = RacesAPI.PublishRace(publish);
if (publishrace.Code != "NoContent")
throw new Exception("Error publishing race");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Results");
}
});
}
void LoadResults(int raceid)
{
var results = new ObservableCollection<Result>();
//Start with the timings
foreach (Timing timing in Timings)
{
var result = new Result();
//Basic details
result.RaceId = RaceId;
result.RaceDate = RaceDate;
result.Status = "Processing";
//Timing Data
result.TimingId = timing.Id;
result.TimingPosition = timing.Position;
result.TimingStatus = timing.Status;
result.StartTime = timing.StartTime;
result.EndTime = timing.EndTime;
var elapsed = result.EndTime - result.StartTime;
string elapsedhours = elapsed.Hours.ToString();
string elapsedminutes = elapsed.Minutes.ToString();
string elapsedseconds = elapsed.Seconds.ToString();
string elapsedmillis;
if (elapsed.Milliseconds.ToString().Length > 2)
{
elapsedmillis = elapsed.Milliseconds.ToString().Substring(0, 2);
}
else
{
elapsedmillis = elapsed.Milliseconds.ToString();
}
if (elapsedhours.Length == 1) { elapsedhours = "0" + elapsedhours; }
if (elapsedminutes.Length == 1) { elapsedminutes = "0" + elapsedminutes; }
if (elapsedseconds.Length == 1) { elapsedseconds = "0" + elapsedseconds; }
if (elapsedmillis.Length == 1) { elapsedmillis = "0" + elapsedmillis; }
if((elapsedhours == "00"))
{
result.Elapsed = elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
else
{
result.Elapsed = elapsedhours + ":" + elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
results.Add(result);
}
//Add in the scans
foreach (Result result1 in results)
{
var scan = Scans.FirstOrDefault(p => p.Position == result1.TimingPosition);
if (scan != null)
{
result1.ScanId = scan.Id;
result1.ScanPosition = scan.Position;
result1.ScanStatus = scan.Status;
result1.ScanBibNumber = scan.BibNumber;
}
else
{
result1.ScanId = 0;
result1.ScanPosition = 0;
result1.ScanStatus = 99;
result1.ScanBibNumber = "UNKNOWN";
}
}
//Add any scans which there are no times for (Higher than count)
var timingscount = Timings.Count();
var notimescans = new ObservableCollection<Scan>();
foreach (Scan scan in Scans)
{
if (scan.Position > timingscount)
{
var newresult = new Result();
newresult.RaceId = RaceId;
newresult.RaceDate = RaceDate;
newresult.Status = "Processing";
newresult.ScanId = scan.Id;
newresult.ScanPosition = scan.Position;
newresult.ScanStatus = scan.Status;
newresult.ScanBibNumber = scan.BibNumber;
newresult.TimingId = 0;
newresult.TimingPosition = 99999;
newresult.TimingStatus = 99;
newresult.StartTime = RaceStartTime;
newresult.EndTime = RaceStartTime;
var elapsed = newresult.EndTime - newresult.StartTime;
string elapsedhours = elapsed.Hours.ToString();
string elapsedminutes = elapsed.Minutes.ToString();
string elapsedseconds = elapsed.Seconds.ToString();
string elapsedmillis = elapsed.Milliseconds.ToString();
if (elapsedhours.Length == 1) { elapsedhours = "0" + elapsedhours; }
if (elapsedminutes.Length == 1) { elapsedminutes = "0" + elapsedminutes; }
if (elapsedseconds.Length == 1) { elapsedseconds = "0" + elapsedseconds; }
if (elapsedmillis.Length == 1) { elapsedmillis = "0" + elapsedmillis; }
if ((elapsedhours == "00"))
{
newresult.Elapsed = elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
else
{
newresult.Elapsed = elapsedhours + ":" + elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
results.Add(newresult);
}
}
//Then add in the entries
foreach (Result result2 in results)
{
var entry = Entries.FirstOrDefault(p => p.BibNumber == result2.ScanBibNumber);
if (entry != null)
{
result2.EntryId = entry.Id;
result2.FirstName = entry.FirstName;
result2.LastName = entry.LastName;
result2.FormattedName = entry.FirstName + " " + entry.LastName.ToUpper();
result2.Gender = entry.Gender;
result2.DateOfBirth = entry.DateOfBirth;
result2.Club = entry.Club;
result2.Team = entry.Team;
result2.EntryBibNumber = entry.BibNumber;
}
else
{
result2.EntryId = 0;
result2.FirstName = "Unknown";
result2.LastName = "ATHLETE";
result2.Gender = "Unknown";
result2.DateOfBirth = DateTime.Now;
result2.Club = "";
result2.Team = "";
result2.EntryBibNumber = "Unknown";
}
}
var sortedresults = new ObservableCollection<Result>(results.OrderBy(c => c.TimingPosition));
Results = sortedresults;
OnPropertyChanged("Results");
}
}
}
is there any way to simplify this code into a few lines, I have a class with string seq(number) has {get;set} functions. I am getting lucio and textValue from another class.
public static void setCategorySeq(string lucio, string textValue)
{
if (lucio == "0") { seq0 = textValue; }
else if (lucio == "1") { seq1 = textValue; }
else if (lucio == "2") { seq2 = textValue; }
else if (lucio == "3") { seq3 = textValue; }
else if (lucio == "4") { seq4 = textValue; }
else if (lucio == "5") { seq5 = textValue; }
else if (lucio == "6") { seq6 = textValue; }
else if (lucio == "7") { seq7 = textValue; }
else if (lucio == "8") { seq8 = textValue; }
else if (lucio == "9") { seq9 = textValue; }
else if (lucio == "10") { seq10 = textValue; }
else if (lucio == "11") { seq11 = textValue; }
else if (lucio == "12") { seq12 = textValue; }
else if (lucio == "13") { seq13 = textValue; }
else if (lucio == "14") { seq14 = textValue; }
else if (lucio == "15") { seq15 = textValue; }
}
May be this could help you reducing the LOC.
public static void setCategorySeq(string lucio, string textValue)
{
string[] seq = new string[16];
for (int i = 0; i <= 15; i++)
{
if (lucio == i.ToString())
seq[i] = textValue;
}
}
Maybe this code will suit you:
static Dictionary<string, string> seq = new Dictionary<string, string>();
public static void setCategorySeq(string lucio, string textValue)
{
seq[lucio] = textValue;
}
public static string setCategorySeq(string lucio)
{
if (seq.ContainsKey(lucio))
return seq[lucio];
return null;
}
Just use a dictionary
var lookup = new Dictionary<string,string>();
then to set an entry in the dictionary
lookup[lucio] = textValue;
and to access it
Console.WriteLine(lookup[lucio])
if you really want to verify that the string is a value between 0 an 15 then parse it first and validate it and use a dictionary with integer as a key
var lookup = new Dictionary<int,string>();
// Using C# 7 notation
if(int.TryParse(lucio, var out lucioInt) && lucionInt > 0 && lucioInt < 16){
lookup[lucioInt] = textValue;
}
I hope this might help
public static void setCategorySeq(string lucio, string textValue)
{
var seq = new string[15];
int noOfsequence=15;
for(int i=0;i<noOfsequence;i++)
{
if(lucio==i.ToString())
{
seq[i] = textValue;
break;
}
}
}