19
PHIL’S SAMPLE PROGRAMS Samples include Asp.Net MVC, Javascript, jQuery, Google Charts, WinForms, and WPF/XAML

Phil’s Sample Programs

Embed Size (px)

Citation preview

Page 1: Phil’s Sample Programs

PHIL’S SAMPLE PROGRAMS

Samples include Asp.Net MVC, Javascript, jQuery, Google Charts,

WinForms, and WPF/XAML

Page 2: Phil’s Sample Programs

Asp.Net MVC This website provides information about

Canadian business metrics This website supports English and French The following pages show results of

selecting ‘absenteeism’ rates Since Javascript was enabled on the

browser, the initial screen shows column charts.

Page 3: Phil’s Sample Programs

Top of Page

Page 4: Phil’s Sample Programs

Same webpage, move down

Page 5: Phil’s Sample Programs

Same webpage, move bottom

Page 6: Phil’s Sample Programs

User pressed ‘Line Charts’ button

Page 7: Phil’s Sample Programs

User pressed ‘Data Tables’ button

Page 8: Phil’s Sample Programs

Razor View Code Behind Excerpt@model Opal1.Models.Absenteeism @Scripts.Render("~/bundles/jquery")<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>@Scripts.Render("~/bundles/Phil_Bundle") <h2 class="center">@Opal1.Resources.AbsenteeismAge</h2><br /> @using (Html.BeginForm("ShowReport_ByAgeGroups", "Absenteeism", FormMethod.Post, new { @class = "center" })){ <div class="text-center"> @Html.AntiForgeryToken()  @* Remember some fields here. *@ @Html.HiddenFor(m => m.SelectedCategoryID, new { id = "CategoryID" }) @Html.HiddenFor(m => m.CategoryInProgress) @Html.HiddenFor(m => m.SummaryTableWords_forJS, new { id = "SummaryTableWords" }) @Html.HiddenFor(m => m.DetailTableWords1_forJS, new { id = "DetailTableWords1_forJS" }) @Html.HiddenFor(m => m.DetailTableWords2_MaleForJS, new { id = "DetailTableWords2_MaleForJS" }) @Html.HiddenFor(m => m.DetailTableWords2_FemaleForJS, new { id = "DetailTableWords2_FemaleForJS" })  @* Next provides max values for the detail charts per age group*@ @Html.HiddenFor(m => m.DataMaximum[0], new { id = "DataMaximum0" }) @Html.HiddenFor(m => m.DataMaximum[1], new { id = "DataMaximum1" }) @Html.HiddenFor(m => m.DataMaximum[2], new { id = "DataMaximum2" }) @Html.HiddenFor(m => m.DataMaximum[3], new { id = "DataMaximum3" }) @Html.HiddenFor(m => m.DataMaximum[4], new { id = "DataMaximum4" }) @Html.HiddenFor(m => m.DataMaximum[5], new { id = "DataMaximum5" }) @Html.HiddenFor(m => m.DataMaximum[6], new { id = "DataMaximum6" })  @Html.HiddenFor(m => m.Culture_forJS, new { id = "Culture_forJS" })  <div> @*@Html.Label(Opal1.Resources.StatOption)*@ <h4>@Opal1.Resources.StatOption</h4>  <br /> @* Place the selected item in SelectedOptionID. *@ @Html.DropDownListFor(m => m.SelectedOptionID, Model.Options) </div> <br /> <div> <input class="btn btn-primary" type="submit" value="@Opal1.Resources.Submit" /> <br /> <br /> </div> </div>}

Page 9: Phil’s Sample Programs

Model ‘Absenteeism’ Class Excerptnamespace Opal1.Models{ public class Absenteeism : BaseModel { private readonly ErrorHandling errorHandler = new ErrorHandling();  #region Constructors public Absenteeism() { mCategories = GetCategoriesForSelectList(); } #endregion  #region Properties  private SelectList mCategories; public SelectList Categories { get { return mCategories; } }  public string CategoryInProgress { get; set; }  public SelectList Options { get; private set; }  public string SelectedCategoryID { get; set; } public string SelectedOptionID { get; set; }  public Dictionary<short, List<LocalAbsenceByAge>> AbsenceByAgeData_Male { get; set; } public Dictionary<short, List<LocalAbsenceByAge>> AbsenceByAgeData_Female { get; set; }  public List<SummaryAbsenceByAge> SummaryByAge { get; set; } private SummaryAbsenceByAge SummaryByAgeRow = null;  public string SummaryTableWords_forJS { get; set; } public string DetailTableWords1_forJS { get; set; } public string DetailTableWords2_MaleForJS { get; set; } public string DetailTableWords2_FemaleForJS { get; set; } public string Culture_forJS { get; set; }  public double[] DataMaximum { get; set; }  // Arrays are needed because we'll be showing tables by age group public double[] DataAverage_Male { get; set; } public double[] DataMaximum_Male { get; set; }  // Arrays are needed because we'll be showing tables by age group public double[] DataAverage_Female { get; set; } public double[] DataMaximum_Female { get; set; }

Etc…

Page 10: Phil’s Sample Programs

Javascript / jQuery Excerpt$(function () { if (window.jQuery !== undefined) { $("#WaitForLoad").removeClass("hidden");  // Show buttons showing options for showing the data. $("#GraphButtons").removeClass("hidden");  // Hide the data tables. $("#DataTables").hide();  // Assign 'on click' functions. $("#DataTablesButton").click(ShowDataTables); $("#ColumnChartsButton").click(ShowColumnCharts); $("#LineChartsButton").click(ShowLineCharts);  // Get current culture to pass to google load so numbers format for that culture. var culture = $("#Culture_forJS").val();  google.charts.load('45', { packages: ['corechart'], language: culture }); google.charts.setOnLoadCallback(DrawCharts); }}); // User clicked the Data Tables button.function ShowDataTables() { $("#DataTables").show(1000); $("#ColumnCharts").hide(1000); $("#LineCharts").hide(1000);  DeactivateButtons(); $("#DataTablesButton").addClass("active");} // User clicked the column charts button.function ShowColumnCharts() { $("#DataTables").hide(1000); $("#ColumnCharts").show(1000); $("#LineCharts").hide(1000);  DeactivateButtons(); $("#ColumnChartsButton").addClass("active");} // User clicked the line charts button.function ShowLineCharts() { $("#DataTables").hide(1000); $("#ColumnCharts").hide(1000); $("#LineCharts").show(1000); Etc…

Page 11: Phil’s Sample Programs

WinForms Memory Management

I wrote this application to highlight bad and good methods of dealing with large datasets.

The following UI screenshot shows results of reading a large XML file and inserting the resulting data into a SQL DB table.

Processing involved deleting and inserting 1 million rows of data.

Page 12: Phil’s Sample Programs

The UI

Page 13: Phil’s Sample Programs

Main ‘Good XML to DB’ Processing

private void btnGoodXMLtoDB_Click(object sender, EventArgs e) { btnGoodXMLtoDB.Enabled = false; txtGoodResults.Text = "Started...";  Thread aThread = new Thread(GoodXMLtoDB); aThread.Start(uiContext); }  private void GoodXMLtoDB(object inContext) { Results _results = new Results(true); SynchronizationContext _localUIContext = inContext as SynchronizationContext;  // Delete all rows first - we'll add new rows below. using (var db = new BigDBDataContext()) { // Delete rows via a stored procedure. _results.DbRowsDeleted = (int)(db.DeleteAllRows("PhoneLogDupe").FirstOrDefault()).Column1; }  // Create an in-memory array (batches of 100) of phone log items from the XML file.  PhoneLogDupe _loggedCall = null; int _logListSize = 100; PhoneLogDupe[] _logList = new PhoneLogDupe[_logListSize]; int _logListIndex = 0;  XmlReaderSettings xs = new XmlReaderSettings() { IgnoreComments = true, IgnoreWhitespace = true }; string _source = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "xPhoneLog_Good.xml");  using (FileStream fs = File.OpenRead(_source)) using (XmlReader xmlReader = XmlReader.Create(fs, xs)) { while (xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element) { switch (xmlReader.Name) // switch on 'name' of node {Continued …

Page 14: Phil’s Sample Programs

‘Good XML to DB’ Continued

switch (xmlReader.Name) // switch on 'name' of node { // When a batch of calls is ready, insert the batch into the DB. case "Call": _loggedCall = new PhoneLogDupe();  _loggedCall.LogRecorded = DateTime.Parse(xmlReader.GetAttribute("Time")); _loggedCall.PhoneNumberCalled = xmlReader.GetAttribute("PhoneNumberCalled"); _loggedCall.CallDurationSec = int.Parse(xmlReader.GetAttribute("CallDuration"));  _logList[_logListIndex] = _loggedCall; ++_logListIndex;  if (_logListIndex == _logListSize) { _logListIndex = 0;  // Insert list of phone log items to the DB. using (var db = new BigDBDataContext()) { db.PhoneLogDupes.InsertAllOnSubmit(_logList); db.SubmitChanges(); } } break; } } } } // Insert possible remaining items and get final count of rows inserted to the DB. using (var db = new BigDBDataContext()) { if (_logListIndex > 0) { db.PhoneLogDupes.InsertAllOnSubmit(_logList); db.SubmitChanges(); _logList = null; } // Get count of rows via a stored procedure. _results.DbRowsInserted = (int)(db.CountRows("PhoneLogDupe")).FirstOrDefault().Column1; }  // Show processing results to the UI. _results.FinalizeResults(); _localUIContext.Send(ReportResultsToUI, _results); }END

Page 15: Phil’s Sample Programs

WPF / XAML Image Application

This application allows a user to:

create new images from scratch incorporate existing image files (e.g. jpg,

png, etc.) into a new custom image option to save work to XML so one can

open the XML later to resume editing / creating

options to save the final work to various image formats and sizes

Page 16: Phil’s Sample Programs

The UI

Page 17: Phil’s Sample Programs

Code Sample The following shows part of the

‘ChangeableStar’ class This class was used several times to

create the image above

Page 18: Phil’s Sample Programs

ChangeableStar Class public class ChangeableStar : ChangeableGraphic, IXmlSerializable { Polygon mStar; TransformGroup mTransGroup = new TransformGroup(); RotateTransform mTransRotate = new RotateTransform(); ScaleTransform mTransScale = new ScaleTransform(); SkewTransform mTransSkew = new SkewTransform();  #region Constructors  // Constructor 1 - normal public ChangeableStar(int inKey, Point inPoint, double inWidth, double inHeight) : base(inKey) { CommonConstruct(inKey, inPoint, inWidth, inHeight); }  // Constructor 2 - Create via Xml data public ChangeableStar(int inKey, XmlReader r) : base(inKey) { GraphicType = GraphicTypes.Star; mStar = new Polygon() { Stroke = (SolidColorBrush)OurApp.Resources["GraphicBrush"], StrokeThickness = 2, Tag = inKey }; base.MainElement = mStar;  mTransGroup.Children.Add(mTransRotate); mTransGroup.Children.Add(mTransScale); mTransGroup.Children.Add(mTransSkew); mStar.RenderTransform = mTransGroup;  GraphicComplete = true;  ReadXml(r); }Continued…

Page 19: Phil’s Sample Programs

ChangeableStar Class /// <summary> /// Create the points for a star shape /// </summary> /// <param name="inPoint">Point where the user clicked</param> /// <param name="inPoints">Number of points for the star</param> internal void CreateStar(Point inPoint, int inPoints) { mStar.Points.Clear();  // Include both the outer points and valley points int NumStarPoints = inPoints * 2; double AngleDelta = 360.0 / NumStarPoints; double Angle = 0; double PointX = 0; double PointY = 0;  for (int Index = 0; Index != NumStarPoints; ++Index, Angle += AngleDelta) { // If even number, use the OuterRadius if (Index % 2 == 0) { PointX = inPoint.X + Math.Cos(Angle * Math.PI / 180.0) * ChangeableOuterRadius; PointY = inPoint.Y + Math.Sin(Angle * Math.PI / 180.0) * ChangeableOuterRadius; } // Else use the ShortRadius for a valley point of the star else { PointX = inPoint.X + Math.Cos(Angle * Math.PI / 180.0) * ChangeableInnerRadius; PointY = inPoint.Y + Math.Sin(Angle * Math.PI / 180.0) * ChangeableInnerRadius; } Point mPoint = new Point(PointX, PointY); AddPoint(mPoint); } }