45
1-day .NET C# Programming Crash Course for Engineers By LIEW YONG SEONG Advance Contech (Singapore) Pte. Ltd.

1-day C# Introductory Workshop for Engineers

Embed Size (px)

Citation preview

1-day .NET C# Programming Crash Course for Engineers

By LIEW YONG SEONG

Advance Contech (Singapore) Pte. Ltd.

Objective

u  Exposing engineers to programming modern desktop application using Microsoft .Net Framework

u  Enabling engineers make efficient use of computer to solve complex engineering problems with computer codes

u  Empowering engineers to simplify workflow by automating piece-wise design processes with computer codes

u  At the end of the course, trainees will be exposed to various programming concepts and technics in writing a Windows Desktop software to process structural analysis output results and  design a rectangular beam section.

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 2

Final “Product”

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 3

Targeted Audience

u  Graduating and practicing structural engineers with basic programming concept

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 4

1. Why .Net Framework ?

u  Developed, maintained and advocated by Microsoft.

u  Built into Window XP, Vista, 7, 8 and 10

u  Used in almost all modern application running on Windows machines

u  Defines common data types

u  Provides rich set of library for modern software development for both desktop and web applications

u  AutoDesk Revit SDK (and many others) is based on .NET

u  … any program that can interface with Revit likely to be communicate with any other .NET library/API

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 5

C#, the modern programming language

u  Modern C-like programming language

u  Object oriented, borrowed and extended many good concepts from Java.

u  Created by Microsoft

u  Promoted as 1st-class citizen in .Net application development.

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 6

Timeline    Morning:     0. Computer Setup (Software Installation)

                       1. Introduction to Microsoft .Net Framework

                       2. Quick Tour of .NET APIs

                       3. Hello World WinForm Program

                       4. File I/O

    Afternoon:

                       5. Variables and Arithmetic

                       6. Graphical API

                       7. A simple Beam Section design utility

                       8. Q&A.

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 7

1. .Net Framework u  Common Language Runtime (CLR)

u  Common Type System (CTS)

u  Base Class Library (BCL)

u  Common Language Specification (CLS)

u  Programming Language Neutral

u  Desktop (WinForm etc.) and Web (ASP.Net etc.)

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 8

What does the word “common” means?

u  .Net program are compiled to “intermedia code”, and further translated to machine upon running.

u  Mix and use different programming language to produce one executable is possible.

u  It is cross-language “decompilable”.

u  Code in C#, decompiled and shown as Visual Basic code, and vice-versa

u  Demo

u  Code-reuse (in the form of 3rd-party callable library, API) is possible.

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 9

2. Lesson 0 - API Quick Tour (BCL) with Visual Studio orientation

u  Console Application o  Console.WriteLine(…) o  Console.ReadLine(…)

u  Data manipulations o  String functions

o  String.format(…)

o  Number functions o  int.TryParse(…)

o  DateTime functions o  DateTime.Now – (new DateTime(…))

u  File I/O u  StreamReader, StreamWrite, WriteLine(…)

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 10

// 0. Wait for key press Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey();

// 1. String Console.WriteLine("## String ##"); Console.WriteLine("What's your name ?"); String name = Console.ReadLine(); Console.WriteLine("Hello, " + name);

Snippet 2

Snippet 1

[F5] – Build and Run

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 11

// 2. Number Console.WriteLine(); Console.WriteLine("## Number ##"); Console.WriteLine("Which year you were born? "); string year_as_string = Console.ReadLine(); Console.WriteLine("Which month you were born? "); string month_as_string = Console.ReadLine(); Console.WriteLine("Which day you were born? "); string day_as_string = Console.ReadLine(); int year = 0, month = 0, day = 0; int.TryParse(year_as_string, out year); int.TryParse(month_as_string, out month); int.TryParse(day_as_string, out day);

Snippet 3

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 12

// 3. DateTime Console.WriteLine(); Console.WriteLine("## Date/Time ##"); DateTime dob = new DateTime(year, month, day); DateTime today = DateTime.Now; int totaldays = (int) (today-dob).TotalDays; Console.WriteLine("Total days on earth : " + totaldays);

Snippet 4

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 13

// 4. File I/O Console.WriteLine(); Console.WriteLine("## File I/O ##"); string filename = "myrecord.txt"; StreamWriter sw = new StreamWriter(filename); sw.WriteLine(

string.Format( "Name: {0}, DOB: {1}/{2}/{3}, Total Days: {4}", name, day, month, year, totaldays )

); sw.Close(); Console.WriteLine("Record saved to '" + filename + "'" );

Snippet 5

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 14

Lesson 1

u  Familiar with Visual Studio.

u  Create Solution.

u  Drag-and-Drop visual controls on WinForm.

u  Label Control [Hellow world!]

u  Button Control [Close]

u  Configure visual controls’ properties.

u  Font of the Label Control

u  Wire-up event handler to visual controls event.

u  Button -> Close the form and terminate the program.

u  Build and Run Solution.

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 15

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 16

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 17

this.Close();

Snippet 1

[F5] – Build and Run

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 18

Lesson 2

u  Add new project to Solution

u  Set Start-up Project

u  Textbox Control (to accept user input)

u  Access properties of Textbox Control

u  MessageBox.Show(…)

u  Present information and wait for user response

u  Revisit

u  String.format(…) vs “abc” + variable

u  Commment/uncomment statements with ‘//’

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 19

MessageBox.Show("Hello " + this.txtUsername.Text);

Snippet 1

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 20

Lesson 3

u  Convert string to number (double)

u  double.Tryparse(…)

u  Perform arithmetic

u  Display results

u  Quiz

u  Add a new button to calculate the power of Value1 to the order of Value2

u  Hint: Math.Pow(…)

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 21

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 22

double value1 = getValue(this.txtValue1.Text); double value2 = getValue(this.txtValue2.Text); MessageBox.Show(

string.Format("{0} + {1} = {2}", value1, value2, value1+value2) );

Snippet 1

double value1 = getValue(this.txtValue1.Text); double value2 = getValue(this.txtValue2.Text); MessageBox.Show(

string.Format("{0} + {1} = {2}", value1, value2, value1-value2) );

Snippet 2

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 23

private double getValue(string value_as_string) {

double returned_value = 0.0;

double.TryParse(value_as_string, out returned_value);

return returned_value;

}

Snippet 3

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 24

Lesson 4 u  Beam Section Design subroutine

u  Procedural way

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 25

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 26

public double design( double fck, double fyk, double b, double h, double c, double m_kNm ) { double d = h - c; double m_Nmm = m_kNm * 10e5; double K = m_Nmm / b / d / d / fck; double z = Math.Ceiling(d * (0.5 + Math.Sqrt(0.25 - K / 1.134))); double As = Math.Floor(m_Nmm / 0.87 / fyk / z); return As; }

Snippet 1

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 27

double fck = 0; double fyk = 0; double b = 0; double h = 0; double c = 0; double moment = 0; double.TryParse(txtFck.Text, out fck); double.TryParse(txtFyk.Text, out fyk); double.TryParse(txtB.Text, out b); double.TryParse(txtH.Text, out h); double.TryParse(txtCover.Text, out c); double.TryParse(txtMoment.Text, out moment); double As = design(fck, fyk, b, h, c, moment); txtAs.Text = As.ToString();

Snippet 2

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 28

Lesson 4 b

u  Import and use 3rd party component/library/API

u  Make this into an API / component for other to re-use

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 29

Add an external reference

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 30

BeamSectionVisualizer API ======================== [A] Properties: // View zoom factor float _zoomScale ; [B] Methods: // Set the dimension of beam section and rebars to be displayed void setParams( float width, float height, float cover, float rebar_diameter, float required_area); // Get the thumbnail Image getImage(); // Refresh the image void Invalidate();

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 31

this.beamSectionVisualizer1._zoomScale = 0.35f; this.beamSectionVisualizer1.Invalidate();

Snippet 1

Snippet 2

// Calling external API this.beamSectionVisualizer1.setParams(b, h, c, 16, As); this.beamSectionVisualizer1.Invalidate(); // API return value when acting as callee this._As = As;

Snippet 3

public double _As { get; set; }

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 32

Demo

integrating Lesson 4b component into other

software

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 33

Lesson 4c

u  Add Load/Save feature

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 34

OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Beam Section Designer (*.beam)|*.beam"; var result = dialog.ShowDialog(); if (result == DialogResult.OK) {

loadFromDisk(dialog.FileName); }

Snippet 1

private void loadFromDisk(string filename) { if (File.Exists(filename)) { StreamReader sr = new StreamReader(filename); this.txtFck.Text = sr.ReadLine(); this.txtFyk.Text = sr.ReadLine(); this.txtB.Text = sr.ReadLine(); this.txtH.Text = sr.ReadLine(); this.txtCover.Text = sr.ReadLine(); this.txtMoment.Text = sr.ReadLine(); sr.Close(); }

}

Snippet 2

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 35

Snippet 3

SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "Beam Section Designer (*.beam)|*.beam"; var result = dialog.ShowDialog(); if (result == DialogResult.OK) {

saveToDisk(dialog.FileName); }

Snippet 4

private void saveToDisk(string filename) { StreamWriter sw = new StreamWriter(filename); sw.WriteLine("{0}", this.txtFck.Text); sw.WriteLine("{0}", this.txtFyk.Text); sw.WriteLine("{0}", this.txtB.Text); sw.WriteLine("{0}", this.txtH.Text); sw.WriteLine("{0}", this.txtCover.Text); sw.WriteLine("{0}", this.txtMoment.Text); sw.Close();

} © 2013~2015. LIEW YONG SEONG. All Rights Reserved. 36

Lesson 4d

u  Add reporting features

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 37

Snippet 1

this.webBrowser1.ShowPrintDialog();

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 38

Preview_Report_Form previewReportForm = new Preview_Report_Form(); string content = ""; content += "<html>"; content +="<body>"; content += "<h1>Beam Section Design</h1><br>"; // Input parameters content += string.Format("<p>fck, MPa = {0}</p>", this.txtFck.Text); content += string.Format("<p>fyk, MPa = {0}</p>", this.txtFyk.Text); content += string.Format("<p>b, mm: {0} </p>", this.txtB.Text); content += string.Format("<p>h, mm: {0} </p>", this.txtH.Text); content += string.Format("<p>cover, mm: {0} </p>", this.txtCover.Text); content += string.Format("<p>design moment, kNm: {0} </p>", this.txtMoment.Text);

var image = this.beamSectionVisualizer1.getImage(); // The image var imageString = ""; using (MemoryStream m = new MemoryStream()) {

image.Save(m, ImageFormat.Png); byte[] imageBytes = m.ToArray(); string base64String = Convert.ToBase64String(imageBytes); imageString = base64String;

} // As content += string.Format("<img alt='Embedded Image' src='data:image/png;base64,{0}'/>", imageString); content += string.Format("<p>As, mm^2: {0} </p>", this.txtAs.Text); content += "</body>"; content += "</html>"; // Load the content previewReportForm.webBrowser1.DocumentText = content; // Show the preview form previewReportForm.Show();

Snippet 2

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 39

Flash back

u  Data Type

u  Visual Design of WinForm

u  Hook up control event with code

u  Create function

u  Import 3rd party library

u  Expose API for 3rd party software

u  File I/O

u  Printing

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 40

What’s next?

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 41

More data-type (bool, decimal, etc.) Flow control statements (if…else, while, switch, do…while) Class (object oriented programming) Event driven programming Database programming Web programming … The sky is the limit!

Recommended Reading

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 42

Online Resources

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 43

http://it-ebooks.info/

C#

.Net

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 44

Thank you! LIEW YONG SEONG

Cell +65.9276.0058

Email [email protected]

© 2013~2015. LIEW YONG SEONG. All Rights Reserved. 45