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();
}
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 have a "Player" class, which is supposed to manage my global music player.
This also works so far. The class is at the bottom, if you have any suggestions for improvement, feel free to give it to us.
I want to start a second song while the current song ends.
So a FadeIn into the next song and a FadeOut from the current song, which makes the song quieter.
My approach at the moment is that one song is running in the "waveOutDevice1" object and the second one is waiting in the second object. And as soon as the current song is about to end, the second WavePlayer starts. But I don't know how I can react to it, as soon as the current song is about to end.
Do you have an idea or suggestions?
With kind regards
my Player class:
public class Player
{
#region Properties, Fields
private IWavePlayer waveOutDevice1;
private IWavePlayer waveOutDevice2;
private AudioFileReader fileReader1;
private AudioFileReader fileReader2;
public AudioFile CurrentSong { get; private set; }
public Playlist CurrentPlaylist { get; private set; }
public List<AudioFile> lstPastSongs { get; private set; }
public List<AudioFile> lstNextSongs { get; set; }
public PlaybackState PlaybackState { get; private set; }
public bool Muted { get; private set; }
private float OldVolume = 0.0f;
#endregion
public Player()
{
this.lstNextSongs = new List<AudioFile>();
this.lstPastSongs = new List<AudioFile>();
}
#region Methods
public void Play(int index)
{
if (this.lstNextSongs.Count > 0 && index >= 0 && index < this.lstNextSongs.Count)
{
this.ResetFileReader();
this.CurrentSong = this.lstNextSongs[index];
this.CurrentPlaylist = this.CurrentSong.Playlist;
this.lstNextSongs.RemoveAt(index);
this.fileReader1 = new AudioFileReader(this.CurrentSong.Path);
this.waveOutDevice1 = new WaveOut();
this.waveOutDevice1.PlaybackStopped += WaveOutDevice1_PlaybackStopped;
this.waveOutDevice1.Init(this.fileReader1);
this.PlaybackState = PlaybackState.Playing;
this.waveOutDevice1.Play();
}
}
private void WaveOutDevice1_PlaybackStopped(object sender, StoppedEventArgs e)
{
this.Next();
}
private void ResetFileReader()
{
if (this.fileReader1 != null)
{
this.fileReader1.Dispose();
this.fileReader1 = null;
}
if (this.fileReader2 != null)
{
this.fileReader2.Dispose();
this.fileReader2 = null;
}
if(this.waveOutDevice1 != null)
{
this.waveOutDevice1.Dispose();
this.waveOutDevice1 = null;
}
if(this.waveOutDevice2 != null)
{
this.waveOutDevice2.Dispose();
this.waveOutDevice2 = null;
}
}
public void Pause()
{
if(this.waveOutDevice1 != null)
if (this.waveOutDevice1.PlaybackState == PlaybackState.Playing)
this.waveOutDevice1.Pause();
if(this.waveOutDevice2 != null)
if (this.waveOutDevice2.PlaybackState == PlaybackState.Playing)
this.waveOutDevice2.Pause();
this.PlaybackState = PlaybackState.Paused;
}
public void Continue()
{
if (this.waveOutDevice1 != null)
if (this.waveOutDevice1.PlaybackState == PlaybackState.Paused)
this.waveOutDevice1.Play();
if (this.waveOutDevice2 != null)
if (this.waveOutDevice2.PlaybackState == PlaybackState.Paused)
this.waveOutDevice2.Play();
this.PlaybackState = PlaybackState.Playing;
}
public void Next()
{
if(this.lstNextSongs.Count > 0)
{
if (this.CurrentSong != null)
this.lstPastSongs.Add(this.CurrentSong);
if (GlobalSettings.Shuffle)
{
System.Random random = new System.Random();
int randomNumber = random.Next(0, this.lstNextSongs.Count - 1);
this.Play(randomNumber);
}
else
this.Play(0);
}
else
{
if(GlobalSettings.Replay)
if(GlobalSettings.CurrentPlaylist != null)
for (int i = 0; i < GlobalSettings.CurrentPlaylist.panPlaylist.SongPlaylist.NumberOfSongs; i++)
this.lstNextSongs.AddRange(GlobalSettings.CurrentPlaylist.panPlaylist.SongPlaylist.AllSongs);
}
}
public void Previous()
{
if(this.CurrentSong == null)
{
if(this.lstPastSongs.Count > 0)
{
this.lstNextSongs.Insert(0, this.lstPastSongs[this.lstPastSongs.Count - 1]);
this.lstPastSongs.RemoveAt(this.lstPastSongs.Count - 1);
this.Play(0);
}
}
else
{
if(this.fileReader1 != null)
this._Previous(this.waveOutDevice1, this.fileReader1);
else if(this.fileReader2 != null)
this._Previous(this.waveOutDevice2, this.fileReader2);
}
}
private void _Previous(IWavePlayer waveOutDevice, AudioFileReader fileReader)
{
if (fileReader.CurrentTime.Seconds >= 10 || this.lstPastSongs.Count == 0)
{
waveOutDevice.Pause();
fileReader.CurrentTime = new System.TimeSpan(0, 0, 0);
waveOutDevice.Play();
}
else
{
this.lstNextSongs.Insert(0, this.CurrentSong);
this.lstNextSongs.Insert(0, this.lstPastSongs[this.lstPastSongs.Count - 1]);
this.lstPastSongs.RemoveAt(this.lstPastSongs.Count - 1);
this.Play(0);
}
}
public void SetVolume(int Volume)
{
if (Volume > -1 && Volume < 101)
{
float vol = (float)Volume / 100;
if (this.fileReader1 != null)
this.fileReader1.Volume = vol;
if (this.fileReader2 != null)
this.fileReader2.Volume = vol;
this.Muted = false;
}
}
public void Mute()
{
if(this.Muted)
{
if(this.fileReader1 != null)
{
this.fileReader1.Volume = this.OldVolume;
this.Muted = false;
}
else if(this.fileReader2 != null)
{
this.fileReader2.Volume = this.OldVolume;
this.Muted = false;
}
}
else
{
this.Muted = true;
if(this.fileReader1 != null)
{
this.OldVolume = this.fileReader1.Volume;
this.fileReader1.Volume = 0;
}
else if(this.fileReader2 != null)
{
this.OldVolume = this.fileReader2.Volume;
this.fileReader2.Volume = 0;
}
}
}
#endregion
}
If you can get the duration of the song when it starts playing, you can set a timer for duration - fadeInTime and start your fade when the timer fires.
Another approach is to use a single wave out device and MixingSampleProvider to add in the second song as a new input to the mixer as the first one is ending. You can do this by creating your own wrapper ISampleProvider whose Read method can keep accurate track of where you are up to.
I am using https://courses.cs.washington.edu/courses/cse326/07su/prj2/kruskal.html psuedocode as reference when writing my code.
Code is in C#, and my code can only generate mazes up to 11x11, anything more than than it will run, seemingly, forever (e.g. 12x11 or 12x12 won't work)
Grid Properties are just storing the dimension of the size of the maze
public class GridProperties
{
private int xLength;
private int yLength;
public GridProperties(int xlength, int ylength)
{
xLength = xlength;
yLength = ylength;
}
public int getXLength()
{
return this.xLength;
}
public int getYLength()
{
return this.yLength;
}
}
Cell Properties generates the grid
public class CellProperties
{
private GridProperties Grid;
private bool topWall, bottomWall, rightWall, leftWall;
private int? xCoord, yCoord;
private CellProperties topCell, bottomCell, rightCell, leftCell;
private CellProperties topParentCell, bottomParentCell, rightParentCell, leftParentCell;
private HashSet<String> passageID = new HashSet<String>();
public CellProperties(GridProperties grid = null, int? targetXCoord = null, int? targetYCoord = null,
CellProperties tpCell = null, CellProperties bpCell = null,
CellProperties rpCell = null, CellProperties lpCell = null)
{
this.Grid = grid;
this.xCoord = targetXCoord;
this.yCoord = targetYCoord;
this.updatePassageID(this.xCoord.ToString() + this.yCoord.ToString());
this.topWall = true;
this.bottomWall = true;
this.rightWall = true;
this.leftWall = true;
this.topParentCell = tpCell;
this.bottomParentCell = bpCell;
this.rightParentCell = rpCell;
this.leftParentCell = lpCell;
this.topCell = this.setTopCell();
this.bottomCell = this.setBottomCell();
if (this.yCoord == 0)
{
this.rightCell = this.setRightCell();
}
this.leftCell = this.setLeftCell();
}
public CellProperties setTopCell()
{
if (this.Grid == null)
{
return null;
}
if (this.yCoord == this.Grid.getYLength() - 1)
{
return new CellProperties();
}
else
{
return new CellProperties(this.Grid, this.xCoord, this.yCoord + 1, null, this, null, null);
}
}
public CellProperties setBottomCell()
{
if (this.yCoord == 0)
{
return new CellProperties();
}
else
{
return this.bottomParentCell;
}
}
public CellProperties setRightCell()
{
if (this.Grid == null)
{
return null;
}
if (this.xCoord == this.Grid.getXLength() - 1)
{
return new CellProperties();
}
else
{
return new CellProperties(this.Grid, this.xCoord + 1, this.yCoord, null, null, null, this);
}
}
public CellProperties setLeftCell( )
{
if (this.xCoord == 0)
{
return new CellProperties();
}
else
{
if (this.Grid == null)
{
return null;
}
if (this.yCoord == 0)
{
return this.leftParentCell;
}
else
{
CellProperties buffer = this.bottomCell;
for (int depth = 0; depth < this.yCoord - 1; depth++)
{
buffer = buffer.bottomParentCell;
}
buffer = buffer.leftParentCell.topCell;
for (int depth = 0; depth < this.yCoord - 1; depth++)
{
buffer = buffer.topCell;
}
buffer.rightCell = this;
return buffer;
}
}
}
public GridProperties getGrid()
{
return this.Grid;
}
public CellProperties getBottomCell()
{
return this.bottomCell;
}
public CellProperties getTopCell()
{
return this.topCell;
}
public CellProperties getLeftCell()
{
return this.leftCell;
}
public CellProperties getRightCell()
{
return this.rightCell;
}
public void setBottomWall(Boolean newBottomWall)
{
this.bottomWall = newBottomWall;
}
public void setTopWall(Boolean newTopWall)
{
this.topWall = newTopWall;
}
public void setLeftWall(Boolean newLeftWall)
{
this.leftWall = newLeftWall;
}
public void setRightWall(Boolean newRightWall)
{
this.rightWall = newRightWall;
}
public Boolean getBottomWall()
{
return this.bottomWall;
}
public Boolean getTopWall()
{
return this.topWall;
}
public Boolean getLeftWall()
{
return this.leftWall;
}
public Boolean getRightWall()
{
return this.rightWall;
}
public void updatePassageID(String newPassageID)
{
this.passageID.Add(newPassageID);
}
public void setPassageID(HashSet<String> newPassageID)
{
this.passageID = new HashSet<string>(newPassageID);
}
public HashSet<String> getPassageID()
{
return this.passageID;
}
}
This class is where the magic happens ... or suppose to happen.
public class KruskalMazeGenerator
{
private CellProperties Cell0x0;
private CellProperties CurrentCell;
private CellProperties NeighbourCell;
private int WallsDown;
private int TotalNumberOfCells;
private Random rnd = new Random();
private int rndXCoord, rndYCoord;
private String rndSide;
public KruskalMazeGenerator(CellProperties cell0x0)
{
Cell0x0 = cell0x0;
WallsDown = 0;
TotalNumberOfCells = Cell0x0.getGrid().getXLength() * Cell0x0.getGrid().getYLength();
}
public void selectRandomCellCoords()
{
this.rndXCoord = rnd.Next(0, this.Cell0x0.getGrid().getXLength());
this.rndYCoord = rnd.Next(0, this.Cell0x0.getGrid().getYLength());
}
public void selectRandomSide(String[] possibleSides)
{
if (possibleSides.Length != 0)
{
this.rndSide = possibleSides[rnd.Next(0, possibleSides.Length)];
}
}
public void selectRandomCurrentCell()
{
this.selectRandomCellCoords();
this.CurrentCell = this.Cell0x0;
for (int xWalk = 0; xWalk < this.rndXCoord; xWalk++)
{
this.CurrentCell = this.CurrentCell.getRightCell();
}
for (int xWalk = 0; xWalk < this.rndYCoord; xWalk++)
{
this.CurrentCell = this.CurrentCell.getTopCell();
}
}
public CellProperties checkWallBetweenCurrentAndNeighbour(List<String> possibleSides)
{
if (this.rndSide == "top")
{
if (this.CurrentCell.getTopCell() == null || this.CurrentCell.getTopCell().getGrid() == null)
{
possibleSides.Remove("top");
this.selectRandomSide(possibleSides.ToArray());
return this.checkWallBetweenCurrentAndNeighbour(possibleSides);
}
return this.CurrentCell.getTopCell();
}
else if (this.rndSide == "bottom")
{
if (this.CurrentCell.getBottomCell() == null || this.CurrentCell.getBottomCell().getGrid() == null)
{
possibleSides.Remove("bottom");
this.selectRandomSide(possibleSides.ToArray());
return this.checkWallBetweenCurrentAndNeighbour(possibleSides);
}
return this.CurrentCell.getBottomCell();
}
else if (this.rndSide == "left")
{
if (this.CurrentCell.getLeftCell() == null || this.CurrentCell.getLeftCell().getGrid() == null)
{
possibleSides.Remove("left");
this.selectRandomSide(possibleSides.ToArray());
return this.checkWallBetweenCurrentAndNeighbour(possibleSides);
}
return this.CurrentCell.getLeftCell();
}
else if (this.rndSide == "right")
{
if (this.CurrentCell.getRightCell() == null || this.CurrentCell.getRightCell().getGrid() == null)
{
possibleSides.Remove("right");
this.selectRandomSide(possibleSides.ToArray());
return this.checkWallBetweenCurrentAndNeighbour(possibleSides);
}
return this.CurrentCell.getRightCell();
}
return null;
}
public void selectRandomNeigbhourCell()
{
this.selectRandomSide(new String[4] { "top", "bottom", "left", "right" });
this.NeighbourCell = this.checkWallBetweenCurrentAndNeighbour(new List<String>(new String[4] { "top", "bottom", "left", "right" }));
}
public void checkForDifferentPassageID()
{
if (!this.CurrentCell.getPassageID().SetEquals(this.NeighbourCell.getPassageID()))
{
if (this.rndSide == "top")
{
this.CurrentCell.setTopWall(false);
this.NeighbourCell.setBottomWall(false);
this.unionAndResetPassageID();
this.WallsDown += 1;
}
else if (this.rndSide == "bottom")
{
this.CurrentCell.setBottomWall(false);
this.NeighbourCell.setTopWall(false);
this.unionAndResetPassageID();
this.WallsDown += 1;
}
else if (this.rndSide == "left")
{
this.CurrentCell.setLeftWall(false);
this.NeighbourCell.setRightWall(false);
this.unionAndResetPassageID();
this.WallsDown += 1;
}
else if (this.rndSide == "right")
{
this.CurrentCell.setRightWall(false);
this.NeighbourCell.setLeftWall(false);
this.unionAndResetPassageID();
this.WallsDown += 1;
}
}
}
public void unionAndResetPassageID()
{
HashSet<String> oldCurrentPassageID = new HashSet<String>(this.CurrentCell.getPassageID());
HashSet<String> oldNeighbourPassageID = new HashSet<String>(this.NeighbourCell.getPassageID());
HashSet <String> newPassageID = new HashSet<String>();
newPassageID = this.CurrentCell.getPassageID();
newPassageID.UnionWith(this.NeighbourCell.getPassageID());
CellProperties xwalkCell = new CellProperties();
CellProperties ywalkCell = new CellProperties();
for (int xWalk = 0; xWalk < this.Cell0x0.getGrid().getXLength(); xWalk++)
{
xwalkCell = xWalk == 0 ? this.Cell0x0 : xwalkCell.getRightCell();
for (int yWalk = 0; yWalk < this.Cell0x0.getGrid().getYLength(); yWalk++)
{
xwalkCell.setBottomWall(xWalk == 0 && yWalk == 0 ? false : xwalkCell.getBottomWall());
xwalkCell.setBottomWall(xWalk == this.Cell0x0.getGrid().getXLength() - 1 && yWalk == this.Cell0x0.getGrid().getYLength() - 1 ? false : xwalkCell.getBottomWall());
ywalkCell = yWalk == 0 ? xwalkCell : ywalkCell.getTopCell();
if (ywalkCell.getPassageID().SetEquals(oldCurrentPassageID) ||
ywalkCell.getPassageID().SetEquals(oldNeighbourPassageID))
{
ywalkCell.setPassageID(newPassageID);
}
}
}
}
public CellProperties createMaze()
{
while (this.WallsDown < this.TotalNumberOfCells - 1)
{
this.selectRandomCurrentCell();
this.selectRandomNeigbhourCell();
if (this.NeighbourCell != null)
{
this.checkForDifferentPassageID();
}
}
return this.Cell0x0;
}
}
then this is my visual representation class
public class drawGrid : CellProperties
{
private CellProperties Cell0x0 = new CellProperties();
private CellProperties yWalkBuffer = new CellProperties();
private CellProperties xWalkBuffer = new CellProperties();
private String bottomWall = "";
private String topWall = "";
private String leftAndrightWalls = "";
public drawGrid(CellProperties cell0x0)
{
Cell0x0 = cell0x0;
}
private void WallDrawingReset()
{
this.bottomWall = "\n";
this.topWall = "\n";
this.leftAndrightWalls = "\n";
}
private void Draw()
{
// draw bottom wall
{
if (this.bottomWall == "\n")
{
Console.Write("");
}
else
{
Console.Write(this.bottomWall);
}
}
Console.Write(this.leftAndrightWalls);
// draw top wall
{
if (topWall == "\n")
{
Console.Write("");
}
else
{
Console.Write(this.topWall);
}
}
}
public void yWalk()
{
for (int yWalk = 0; yWalk < this.Cell0x0.getGrid().getYLength(); yWalk++)
{
this.yWalkBuffer = yWalk == 0 ? this.Cell0x0 : this.yWalkBuffer.getTopCell();
this.WallDrawingReset();
this.xWalk(yWalk);
this.Draw();
}
}
private void xWalk(int yWalk)
{
for (int xWalk = 0; xWalk < this.Cell0x0.getGrid().getXLength(); xWalk++)
{
this.xWalkBuffer = xWalk == 0 ? this.yWalkBuffer : this.xWalkBuffer.getRightCell();
if (yWalk == 0)
{
this.bottomWall = xWalkBuffer.getBottomWall() ? this.bottomWall + "----" : this.bottomWall + " ";
this.topWall = xWalkBuffer.getTopWall() ? this.topWall + "----" : this.topWall + " ";
}
else
{
this.topWall = this.xWalkBuffer.getTopWall() ? this.topWall + "----" : this.topWall + " ";
}
if (xWalk == 0)
{
leftAndrightWalls = this.xWalkBuffer.getLeftWall() ? this.leftAndrightWalls + "| " : this.leftAndrightWalls + " ";
leftAndrightWalls = this.xWalkBuffer.getRightWall() ? this.leftAndrightWalls + "| " : this.leftAndrightWalls + " ";
}
else
{
leftAndrightWalls = this.xWalkBuffer.getRightWall() ? this.leftAndrightWalls + "| " : this.leftAndrightWalls + " ";
}
}
}
}
this is how i call them
class Program
{
static void Main(string[] args)
{
{
CellProperties cell = new CellProperties(new GridProperties(12, 11), 0, 0, null, null, null, null);
drawGrid draw = new drawGrid(cell);
draw.yWalk();
KruskalMazeGenerator kmaze = new KruskalMazeGenerator(cell);
cell = kmaze.createMaze();
Console.WriteLine("Final");
draw = new drawGrid(cell);
draw.yWalk();
}
Console.ReadKey();
}
}
Since I got you guys here, please don't mind pitching in what I can improve on as in coding style and other things that you are displeased with.
Thanks in advance.
Error seems to be here:
this.updatePassageID(this.xCoord.ToString() + this.yCoord.ToString());
Image those two scenarios:
xCoord = 1 and yCoord = 11.
xCoord = 11 and yCoord = 1.
both those result in newPassageID of 111.
So simply change the line to
this.updatePassageID(this.xCoord.ToString() + "|" + this.yCoord.ToString());
or written more sexy:
this.updatePassageID($"{xCoord}|{yCoord}");
With this you will receive
1|11 for the first scenario and 11|1 for the second which differs.
Edit based on comments:
I saw that your code is looping endlessly in the method createMaze. This method calls a method called checkForDifferentPassageID in there you check if two collections are equal or not. Once I saw that those collections are of type HashSet<string>, I thought that maybe your strings you put into the HashSet arent as unique as you think they are and there we go. So overall it took me like 10 minutes.
When i check via debug, i can see the methods and variables but no matter what solution i have tried posted on stackoverflow failed
Here how i can see the methods with debug
Here the class
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PlayerStats : pb::IMessage<PlayerStats>
{
/// <summary>Field number for the "level" field.</summary>
public const int LevelFieldNumber = 1;
/// <summary>Field number for the "experience" field.</summary>
public const int ExperienceFieldNumber = 2;
/// <summary>Field number for the "prev_level_xp" field.</summary>
public const int PrevLevelXpFieldNumber = 3;
/// <summary>Field number for the "next_level_xp" field.</summary>
public const int NextLevelXpFieldNumber = 4;
/// <summary>Field number for the "km_walked" field.</summary>
public const int KmWalkedFieldNumber = 5;
/// <summary>Field number for the "pokemons_encountered" field.</summary>
public const int PokemonsEncounteredFieldNumber = 6;
/// <summary>Field number for the "unique_pokedex_entries" field.</summary>
public const int UniquePokedexEntriesFieldNumber = 7;
/// <summary>Field number for the "pokemons_captured" field.</summary>
public const int PokemonsCapturedFieldNumber = 8;
/// <summary>Field number for the "evolutions" field.</summary>
public const int EvolutionsFieldNumber = 9;
/// <summary>Field number for the "poke_stop_visits" field.</summary>
public const int PokeStopVisitsFieldNumber = 10;
/// <summary>Field number for the "pokeballs_thrown" field.</summary>
public const int PokeballsThrownFieldNumber = 11;
/// <summary>Field number for the "eggs_hatched" field.</summary>
public const int EggsHatchedFieldNumber = 12;
/// <summary>Field number for the "big_magikarp_caught" field.</summary>
public const int BigMagikarpCaughtFieldNumber = 13;
/// <summary>Field number for the "battle_attack_won" field.</summary>
public const int BattleAttackWonFieldNumber = 14;
/// <summary>Field number for the "battle_attack_total" field.</summary>
public const int BattleAttackTotalFieldNumber = 15;
/// <summary>Field number for the "battle_defended_won" field.</summary>
public const int BattleDefendedWonFieldNumber = 16;
/// <summary>Field number for the "battle_training_won" field.</summary>
public const int BattleTrainingWonFieldNumber = 17;
/// <summary>Field number for the "battle_training_total" field.</summary>
public const int BattleTrainingTotalFieldNumber = 18;
/// <summary>Field number for the "prestige_raised_total" field.</summary>
public const int PrestigeRaisedTotalFieldNumber = 19;
/// <summary>Field number for the "prestige_dropped_total" field.</summary>
public const int PrestigeDroppedTotalFieldNumber = 20;
/// <summary>Field number for the "pokemon_deployed" field.</summary>
public const int PokemonDeployedFieldNumber = 21;
/// <summary>Field number for the "pokemon_caught_by_type" field.</summary>
public const int PokemonCaughtByTypeFieldNumber = 22;
/// <summary>Field number for the "small_rattata_caught" field.</summary>
public const int SmallRattataCaughtFieldNumber = 23;
private static readonly pb::MessageParser<PlayerStats> _parser =
new pb::MessageParser<PlayerStats>(() => new PlayerStats());
private int battleAttackTotal_;
private int battleAttackWon_;
private int battleDefendedWon_;
private int battleTrainingTotal_;
private int battleTrainingWon_;
private int bigMagikarpCaught_;
private int eggsHatched_;
private int evolutions_;
private long experience_;
private float kmWalked_;
private int level_;
private long nextLevelXp_;
private int pokeballsThrown_;
private pb::ByteString pokemonCaughtByType_ = pb::ByteString.Empty;
private int pokemonDeployed_;
private int pokemonsCaptured_;
private int pokemonsEncountered_;
private int pokeStopVisits_;
private int prestigeDroppedTotal_;
private int prestigeRaisedTotal_;
private long prevLevelXp_;
private int smallRattataCaught_;
private int uniquePokedexEntries_;
public PlayerStats()
{
OnConstruction();
}
public PlayerStats(PlayerStats other) : this()
{
level_ = other.level_;
experience_ = other.experience_;
prevLevelXp_ = other.prevLevelXp_;
nextLevelXp_ = other.nextLevelXp_;
kmWalked_ = other.kmWalked_;
pokemonsEncountered_ = other.pokemonsEncountered_;
uniquePokedexEntries_ = other.uniquePokedexEntries_;
pokemonsCaptured_ = other.pokemonsCaptured_;
evolutions_ = other.evolutions_;
pokeStopVisits_ = other.pokeStopVisits_;
pokeballsThrown_ = other.pokeballsThrown_;
eggsHatched_ = other.eggsHatched_;
bigMagikarpCaught_ = other.bigMagikarpCaught_;
battleAttackWon_ = other.battleAttackWon_;
battleAttackTotal_ = other.battleAttackTotal_;
battleDefendedWon_ = other.battleDefendedWon_;
battleTrainingWon_ = other.battleTrainingWon_;
battleTrainingTotal_ = other.battleTrainingTotal_;
prestigeRaisedTotal_ = other.prestigeRaisedTotal_;
prestigeDroppedTotal_ = other.prestigeDroppedTotal_;
pokemonDeployed_ = other.pokemonDeployed_;
pokemonCaughtByType_ = other.pokemonCaughtByType_;
smallRattataCaught_ = other.smallRattataCaught_;
}
public static pb::MessageParser<PlayerStats> Parser
{
get { return _parser; }
}
public static pbr::MessageDescriptor Descriptor
{
get { return global::PokemonGo.RocketAPI.GeneratedCode.PayloadsReflection.Descriptor.MessageTypes[14]; }
}
public int Level
{
get { return level_; }
set { level_ = value; }
}
public long Experience
{
get { return experience_; }
set { experience_ = value; }
}
public long PrevLevelXp
{
get { return prevLevelXp_; }
set { prevLevelXp_ = value; }
}
public long NextLevelXp
{
get { return nextLevelXp_; }
set { nextLevelXp_ = value; }
}
public float KmWalked
{
get { return kmWalked_; }
set { kmWalked_ = value; }
}
public int PokemonsEncountered
{
get { return pokemonsEncountered_; }
set { pokemonsEncountered_ = value; }
}
public int UniquePokedexEntries
{
get { return uniquePokedexEntries_; }
set { uniquePokedexEntries_ = value; }
}
public int PokemonsCaptured
{
get { return pokemonsCaptured_; }
set { pokemonsCaptured_ = value; }
}
public int Evolutions
{
get { return evolutions_; }
set { evolutions_ = value; }
}
public int PokeStopVisits
{
get { return pokeStopVisits_; }
set { pokeStopVisits_ = value; }
}
public int PokeballsThrown
{
get { return pokeballsThrown_; }
set { pokeballsThrown_ = value; }
}
public int EggsHatched
{
get { return eggsHatched_; }
set { eggsHatched_ = value; }
}
public int BigMagikarpCaught
{
get { return bigMagikarpCaught_; }
set { bigMagikarpCaught_ = value; }
}
public int BattleAttackWon
{
get { return battleAttackWon_; }
set { battleAttackWon_ = value; }
}
public int BattleAttackTotal
{
get { return battleAttackTotal_; }
set { battleAttackTotal_ = value; }
}
public int BattleDefendedWon
{
get { return battleDefendedWon_; }
set { battleDefendedWon_ = value; }
}
public int BattleTrainingWon
{
get { return battleTrainingWon_; }
set { battleTrainingWon_ = value; }
}
public int BattleTrainingTotal
{
get { return battleTrainingTotal_; }
set { battleTrainingTotal_ = value; }
}
public int PrestigeRaisedTotal
{
get { return prestigeRaisedTotal_; }
set { prestigeRaisedTotal_ = value; }
}
public int PrestigeDroppedTotal
{
get { return prestigeDroppedTotal_; }
set { prestigeDroppedTotal_ = value; }
}
public int PokemonDeployed
{
get { return pokemonDeployed_; }
set { pokemonDeployed_ = value; }
}
/// <summary>
/// TODO: repeated PokemonType ??
/// </summary>
public pb::ByteString PokemonCaughtByType
{
get { return pokemonCaughtByType_; }
set { pokemonCaughtByType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); }
}
public int SmallRattataCaught
{
get { return smallRattataCaught_; }
set { smallRattataCaught_ = value; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor
{
get { return Descriptor; }
}
public PlayerStats Clone()
{
return new PlayerStats(this);
}
public bool Equals(PlayerStats other)
{
if (ReferenceEquals(other, null))
{
return false;
}
if (ReferenceEquals(other, this))
{
return true;
}
if (Level != other.Level) return false;
if (Experience != other.Experience) return false;
if (PrevLevelXp != other.PrevLevelXp) return false;
if (NextLevelXp != other.NextLevelXp) return false;
if (KmWalked != other.KmWalked) return false;
if (PokemonsEncountered != other.PokemonsEncountered) return false;
if (UniquePokedexEntries != other.UniquePokedexEntries) return false;
if (PokemonsCaptured != other.PokemonsCaptured) return false;
if (Evolutions != other.Evolutions) return false;
if (PokeStopVisits != other.PokeStopVisits) return false;
if (PokeballsThrown != other.PokeballsThrown) return false;
if (EggsHatched != other.EggsHatched) return false;
if (BigMagikarpCaught != other.BigMagikarpCaught) return false;
if (BattleAttackWon != other.BattleAttackWon) return false;
if (BattleAttackTotal != other.BattleAttackTotal) return false;
if (BattleDefendedWon != other.BattleDefendedWon) return false;
if (BattleTrainingWon != other.BattleTrainingWon) return false;
if (BattleTrainingTotal != other.BattleTrainingTotal) return false;
if (PrestigeRaisedTotal != other.PrestigeRaisedTotal) return false;
if (PrestigeDroppedTotal != other.PrestigeDroppedTotal) return false;
if (PokemonDeployed != other.PokemonDeployed) return false;
if (PokemonCaughtByType != other.PokemonCaughtByType) return false;
if (SmallRattataCaught != other.SmallRattataCaught) return false;
return true;
}
public void WriteTo(pb::CodedOutputStream output)
{
if (Level != 0)
{
output.WriteRawTag(8);
output.WriteInt32(Level);
}
if (Experience != 0L)
{
output.WriteRawTag(16);
output.WriteInt64(Experience);
}
if (PrevLevelXp != 0L)
{
output.WriteRawTag(24);
output.WriteInt64(PrevLevelXp);
}
if (NextLevelXp != 0L)
{
output.WriteRawTag(32);
output.WriteInt64(NextLevelXp);
}
if (KmWalked != 0F)
{
output.WriteRawTag(45);
output.WriteFloat(KmWalked);
}
if (PokemonsEncountered != 0)
{
output.WriteRawTag(48);
output.WriteInt32(PokemonsEncountered);
}
if (UniquePokedexEntries != 0)
{
output.WriteRawTag(56);
output.WriteInt32(UniquePokedexEntries);
}
if (PokemonsCaptured != 0)
{
output.WriteRawTag(64);
output.WriteInt32(PokemonsCaptured);
}
if (Evolutions != 0)
{
output.WriteRawTag(72);
output.WriteInt32(Evolutions);
}
if (PokeStopVisits != 0)
{
output.WriteRawTag(80);
output.WriteInt32(PokeStopVisits);
}
if (PokeballsThrown != 0)
{
output.WriteRawTag(88);
output.WriteInt32(PokeballsThrown);
}
if (EggsHatched != 0)
{
output.WriteRawTag(96);
output.WriteInt32(EggsHatched);
}
if (BigMagikarpCaught != 0)
{
output.WriteRawTag(104);
output.WriteInt32(BigMagikarpCaught);
}
if (BattleAttackWon != 0)
{
output.WriteRawTag(112);
output.WriteInt32(BattleAttackWon);
}
if (BattleAttackTotal != 0)
{
output.WriteRawTag(120);
output.WriteInt32(BattleAttackTotal);
}
if (BattleDefendedWon != 0)
{
output.WriteRawTag(128, 1);
output.WriteInt32(BattleDefendedWon);
}
if (BattleTrainingWon != 0)
{
output.WriteRawTag(136, 1);
output.WriteInt32(BattleTrainingWon);
}
if (BattleTrainingTotal != 0)
{
output.WriteRawTag(144, 1);
output.WriteInt32(BattleTrainingTotal);
}
if (PrestigeRaisedTotal != 0)
{
output.WriteRawTag(152, 1);
output.WriteInt32(PrestigeRaisedTotal);
}
if (PrestigeDroppedTotal != 0)
{
output.WriteRawTag(160, 1);
output.WriteInt32(PrestigeDroppedTotal);
}
if (PokemonDeployed != 0)
{
output.WriteRawTag(168, 1);
output.WriteInt32(PokemonDeployed);
}
if (PokemonCaughtByType.Length != 0)
{
output.WriteRawTag(178, 1);
output.WriteBytes(PokemonCaughtByType);
}
if (SmallRattataCaught != 0)
{
output.WriteRawTag(184, 1);
output.WriteInt32(SmallRattataCaught);
}
}
public int CalculateSize()
{
var size = 0;
if (Level != 0)
{
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Level);
}
if (Experience != 0L)
{
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Experience);
}
if (PrevLevelXp != 0L)
{
size += 1 + pb::CodedOutputStream.ComputeInt64Size(PrevLevelXp);
}
if (NextLevelXp != 0L)
{
size += 1 + pb::CodedOutputStream.ComputeInt64Size(NextLevelXp);
}
if (KmWalked != 0F)
{
size += 1 + 4;
}
if (PokemonsEncountered != 0)
{
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PokemonsEncountered);
}
if (UniquePokedexEntries != 0)
{
size += 1 + pb::CodedOutputStream.ComputeInt32Size(UniquePokedexEntries);
}
if (PokemonsCaptured != 0)
{
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PokemonsCaptured);
}
if (Evolutions != 0)
{
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Evolutions);
}
if (PokeStopVisits != 0)
{
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PokeStopVisits);
}
if (PokeballsThrown != 0)
{
size += 1 + pb::CodedOutputStream.ComputeInt32Size(PokeballsThrown);
}
if (EggsHatched != 0)
{
size += 1 + pb::CodedOutputStream.ComputeInt32Size(EggsHatched);
}
if (BigMagikarpCaught != 0)
{
size += 1 + pb::CodedOutputStream.ComputeInt32Size(BigMagikarpCaught);
}
if (BattleAttackWon != 0)
{
size += 1 + pb::CodedOutputStream.ComputeInt32Size(BattleAttackWon);
}
if (BattleAttackTotal != 0)
{
size += 1 + pb::CodedOutputStream.ComputeInt32Size(BattleAttackTotal);
}
if (BattleDefendedWon != 0)
{
size += 2 + pb::CodedOutputStream.ComputeInt32Size(BattleDefendedWon);
}
if (BattleTrainingWon != 0)
{
size += 2 + pb::CodedOutputStream.ComputeInt32Size(BattleTrainingWon);
}
if (BattleTrainingTotal != 0)
{
size += 2 + pb::CodedOutputStream.ComputeInt32Size(BattleTrainingTotal);
}
if (PrestigeRaisedTotal != 0)
{
size += 2 + pb::CodedOutputStream.ComputeInt32Size(PrestigeRaisedTotal);
}
if (PrestigeDroppedTotal != 0)
{
size += 2 + pb::CodedOutputStream.ComputeInt32Size(PrestigeDroppedTotal);
}
if (PokemonDeployed != 0)
{
size += 2 + pb::CodedOutputStream.ComputeInt32Size(PokemonDeployed);
}
if (PokemonCaughtByType.Length != 0)
{
size += 2 + pb::CodedOutputStream.ComputeBytesSize(PokemonCaughtByType);
}
if (SmallRattataCaught != 0)
{
size += 2 + pb::CodedOutputStream.ComputeInt32Size(SmallRattataCaught);
}
return size;
}
public void MergeFrom(PlayerStats other)
{
if (other == null)
{
return;
}
if (other.Level != 0)
{
Level = other.Level;
}
if (other.Experience != 0L)
{
Experience = other.Experience;
}
if (other.PrevLevelXp != 0L)
{
PrevLevelXp = other.PrevLevelXp;
}
if (other.NextLevelXp != 0L)
{
NextLevelXp = other.NextLevelXp;
}
if (other.KmWalked != 0F)
{
KmWalked = other.KmWalked;
}
if (other.PokemonsEncountered != 0)
{
PokemonsEncountered = other.PokemonsEncountered;
}
if (other.UniquePokedexEntries != 0)
{
UniquePokedexEntries = other.UniquePokedexEntries;
}
if (other.PokemonsCaptured != 0)
{
PokemonsCaptured = other.PokemonsCaptured;
}
if (other.Evolutions != 0)
{
Evolutions = other.Evolutions;
}
if (other.PokeStopVisits != 0)
{
PokeStopVisits = other.PokeStopVisits;
}
if (other.PokeballsThrown != 0)
{
PokeballsThrown = other.PokeballsThrown;
}
if (other.EggsHatched != 0)
{
EggsHatched = other.EggsHatched;
}
if (other.BigMagikarpCaught != 0)
{
BigMagikarpCaught = other.BigMagikarpCaught;
}
if (other.BattleAttackWon != 0)
{
BattleAttackWon = other.BattleAttackWon;
}
if (other.BattleAttackTotal != 0)
{
BattleAttackTotal = other.BattleAttackTotal;
}
if (other.BattleDefendedWon != 0)
{
BattleDefendedWon = other.BattleDefendedWon;
}
if (other.BattleTrainingWon != 0)
{
BattleTrainingWon = other.BattleTrainingWon;
}
if (other.BattleTrainingTotal != 0)
{
BattleTrainingTotal = other.BattleTrainingTotal;
}
if (other.PrestigeRaisedTotal != 0)
{
PrestigeRaisedTotal = other.PrestigeRaisedTotal;
}
if (other.PrestigeDroppedTotal != 0)
{
PrestigeDroppedTotal = other.PrestigeDroppedTotal;
}
if (other.PokemonDeployed != 0)
{
PokemonDeployed = other.PokemonDeployed;
}
if (other.PokemonCaughtByType.Length != 0)
{
PokemonCaughtByType = other.PokemonCaughtByType;
}
if (other.SmallRattataCaught != 0)
{
SmallRattataCaught = other.SmallRattataCaught;
}
}
public void MergeFrom(pb::CodedInputStream input)
{
uint tag;
while ((tag = input.ReadTag()) != 0)
{
switch (tag)
{
default:
input.SkipLastField();
break;
case 8:
{
Level = input.ReadInt32();
break;
}
case 16:
{
Experience = input.ReadInt64();
break;
}
case 24:
{
PrevLevelXp = input.ReadInt64();
break;
}
case 32:
{
NextLevelXp = input.ReadInt64();
break;
}
case 45:
{
KmWalked = input.ReadFloat();
break;
}
case 48:
{
PokemonsEncountered = input.ReadInt32();
break;
}
case 56:
{
UniquePokedexEntries = input.ReadInt32();
break;
}
case 64:
{
PokemonsCaptured = input.ReadInt32();
break;
}
case 72:
{
Evolutions = input.ReadInt32();
break;
}
case 80:
{
PokeStopVisits = input.ReadInt32();
break;
}
case 88:
{
PokeballsThrown = input.ReadInt32();
break;
}
case 96:
{
EggsHatched = input.ReadInt32();
break;
}
case 104:
{
BigMagikarpCaught = input.ReadInt32();
break;
}
case 112:
{
BattleAttackWon = input.ReadInt32();
break;
}
case 120:
{
BattleAttackTotal = input.ReadInt32();
break;
}
case 128:
{
BattleDefendedWon = input.ReadInt32();
break;
}
case 136:
{
BattleTrainingWon = input.ReadInt32();
break;
}
case 144:
{
BattleTrainingTotal = input.ReadInt32();
break;
}
case 152:
{
PrestigeRaisedTotal = input.ReadInt32();
break;
}
case 160:
{
PrestigeDroppedTotal = input.ReadInt32();
break;
}
case 168:
{
PokemonDeployed = input.ReadInt32();
break;
}
case 178:
{
PokemonCaughtByType = input.ReadBytes();
break;
}
case 184:
{
SmallRattataCaught = input.ReadInt32();
break;
}
}
}
}
public override bool Equals(object other)
{
return Equals(other as PlayerStats);
}
public override int GetHashCode()
{
var hash = 1;
if (Level != 0) hash ^= Level.GetHashCode();
if (Experience != 0L) hash ^= Experience.GetHashCode();
if (PrevLevelXp != 0L) hash ^= PrevLevelXp.GetHashCode();
if (NextLevelXp != 0L) hash ^= NextLevelXp.GetHashCode();
if (KmWalked != 0F) hash ^= KmWalked.GetHashCode();
if (PokemonsEncountered != 0) hash ^= PokemonsEncountered.GetHashCode();
if (UniquePokedexEntries != 0) hash ^= UniquePokedexEntries.GetHashCode();
if (PokemonsCaptured != 0) hash ^= PokemonsCaptured.GetHashCode();
if (Evolutions != 0) hash ^= Evolutions.GetHashCode();
if (PokeStopVisits != 0) hash ^= PokeStopVisits.GetHashCode();
if (PokeballsThrown != 0) hash ^= PokeballsThrown.GetHashCode();
if (EggsHatched != 0) hash ^= EggsHatched.GetHashCode();
if (BigMagikarpCaught != 0) hash ^= BigMagikarpCaught.GetHashCode();
if (BattleAttackWon != 0) hash ^= BattleAttackWon.GetHashCode();
if (BattleAttackTotal != 0) hash ^= BattleAttackTotal.GetHashCode();
if (BattleDefendedWon != 0) hash ^= BattleDefendedWon.GetHashCode();
if (BattleTrainingWon != 0) hash ^= BattleTrainingWon.GetHashCode();
if (BattleTrainingTotal != 0) hash ^= BattleTrainingTotal.GetHashCode();
if (PrestigeRaisedTotal != 0) hash ^= PrestigeRaisedTotal.GetHashCode();
if (PrestigeDroppedTotal != 0) hash ^= PrestigeDroppedTotal.GetHashCode();
if (PokemonDeployed != 0) hash ^= PokemonDeployed.GetHashCode();
if (PokemonCaughtByType.Length != 0) hash ^= PokemonCaughtByType.GetHashCode();
if (SmallRattataCaught != 0) hash ^= SmallRattataCaught.GetHashCode();
return hash;
}
partial void OnConstruction();
public override string ToString()
{
return pb::JsonFormatter.ToDiagnosticString(this);
}
}
You can't see methods in the Auto and Locals View. Methods can have side effects when they get evaluated (properties are ought to have no side effects), so to prevent your application to end up corrupted it doesn't show them.
Only properties and fields are shown. You can call methods yourself in the Watch View.
I am trying to access data store in ResultID from the following code:
public class ResultPanelEventArgs : EventArgs
{
private string stringResultId = string.Empty;
private int intRowIndex = -1;
private string stringAnalysisName = string.Empty;
private DateTime dateTimeAnalysisDateTime;
/// <summary>
/// Gets or sets the row index of selected result.
/// </summary>
public int RowIndex
{
get { return intRowIndex; }
set { intRowIndex = value; }
}
/// <summary>
/// Gets or sets the result id of selected result.
/// </summary>
public string ResultId
{
get { return stringResultId; }
set { stringResultId = value; }
}
/// <summary>
/// Gets or sets the date and time of the selected result.
/// </summary>
public DateTime AnalysisDateTime
{
get { return dateTimeAnalysisDateTime; }
set { dateTimeAnalysisDateTime = value; }
}
/// <summary>
/// Gets or sets the name of the sample as Analysis name.
/// </summary>
public string AnalysisName
{
get { return stringAnalysisName; }
set { stringAnalysisName = value; }
}
};
I have a method to pull the info:
private string GetResultID(object sender, ResultPanelEventArgs e)
{
string resultID = string.Empty;
resultID = e.ResultId.ToString();
return resultID;
}
but cannot seem to call that method (I get Argument errors). I am somewhat new to c# and have never worked with EventArgs so I don't even know if this is possible. Any advice on how to access the data stored here?
Per request here are three methods that appear to populate ResultId:
private ResultPanelEventArgs GetDataForTheGivenRowIndex(int intRowIndex)
{
ResultPanelEventArgs resultPanelEventArgs = new ResultPanelEventArgs();
resultPanelEventArgs.RowIndex = intRowIndex;
try
{
if (intRowIndex >= 0 && intRowIndex < dataGridViewResultView.Rows.Count)
{
object objectResultId = null;
if (dataGridViewResultView.Columns.Contains("ColumnResultId") == true)
{
objectResultId = dataGridViewResultView.Rows[intRowIndex].Cells["ColumnResultId"].Value;
}
else
{
objectResultId = dataGridViewResultView.Rows[intRowIndex].Tag;
}
if (objectResultId != null)
{
resultPanelEventArgs.ResultId = objectResultId.ToString();
}
object objectAnalysisName = null;
if (dataGridViewResultView.Columns.Contains("ColumnAnalysis") == true)
{
objectAnalysisName = dataGridViewResultView.Rows[intRowIndex].Cells["ColumnAnalysis"].Value;
}
else
{
objectAnalysisName = dataGridViewResultView.Rows[intRowIndex].Tag;
}
if (objectAnalysisName != null)
{
resultPanelEventArgs.AnalysisName = objectAnalysisName.ToString();
}
object objectAnalysisDateTime = null;
if (dataGridViewResultView.Columns.Contains("ColumnDate") == true)
{
objectAnalysisDateTime = dataGridViewResultView.Rows[intRowIndex].Cells["ColumnDate"].Value;
}
else
{
objectAnalysisDateTime = dataGridViewResultView.Rows[intRowIndex].Tag;
}
if (objectAnalysisDateTime != null)
{
resultPanelEventArgs.AnalysisDateTime =
Utilities.ConvertStringToDateTime(objectAnalysisDateTime.ToString());
}
}
}
catch
{
resultPanelEventArgs = null;
//Nothing to do
}
return resultPanelEventArgs;
}
and
private ResultPanelEventArgs GetDataForTheGivenResultID(string stringResultId)
{
ResultPanelEventArgs resultPanelEventArgs = null;
try
{
foreach (DataGridViewRow dataGridViewRow in dataGridViewResultView.Rows)
{
if (dataGridViewRow != null)
{
if (dataGridViewRow.Index >= 0)
{
if (dataGridViewRow.Cells["ColumnResultId"] != null)
{
if (dataGridViewRow.Cells["ColumnResultId"].Value.ToString() == stringResultId)
{
//Create the ResultPanelEventArgs
object objectResultId = dataGridViewRow.Cells["ColumnResultId"].Value;
object objectAnalysisName = dataGridViewRow.Cells["ColumnAnalysis"].Value;
object objectAnalysisDateTime = dataGridViewRow.Cells["ColumnDate"].Tag;
resultPanelEventArgs = new ResultPanelEventArgs();
if (objectResultId != null)
{
resultPanelEventArgs.RowIndex = dataGridViewRow.Index;
resultPanelEventArgs.ResultId = objectResultId.ToString();
resultPanelEventArgs.AnalysisName = objectAnalysisName.ToString();
resultPanelEventArgs.AnalysisDateTime = (DateTime)objectAnalysisDateTime;
}
dataGridViewRow.Selected = true;
break;
}
}
}
}
}
}
catch
{
resultPanelEventArgs = null;
//Nothing to do
}
return resultPanelEventArgs;
}
and
private void dataGridViewResultList_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
try
{
if (e.RowIndex >= 0)
{
this.result = this.GetResult(e.RowIndex);
ResultPanelEventArgs resultPanelEventArgs = new ResultPanelEventArgs();
resultPanelEventArgs.ResultId = this.result.Id.ToString();
resultPanelEventArgs.RowIndex = this.dataGridViewResultList.SelectedRows[0].Index;
if (this.DoubleClicked != null)
{
this.DoubleClicked(sender, resultPanelEventArgs);
}
this.DialogResult = DialogResult.OK;
}
}
catch (Exception ex)
{
UICommon.LogError(ex);
}
}
I assume this is an event handler. If you are using an event that uses the standard base class, but triggering it with the ResultPanelEventArgs, you will need to handle it with the base class EventArgs then cast them to the correct type.
private void HandleResultID(object sender, EventArgs args)
{
var e = (ResultPanelEventArgs) args;
var resultID = e.ResultId.ToString();
// Now do something with the ID. You cannot return it, because this is handling the click event.
}
Update: To subscribe to an event (add an event handler to an event):
this.DoubleClicked += new EventHandler(HandleResultID);