This is a very simple text for C#. Remember it is just a summary.
Machine Language
0011 1001 1101
Assembly Language
Mor R1,M27
Add R1,R2,R3
High Level Language
C, C++, Java, Fortran, Cobol, Lisp, Pascal, Haskell, Perl, ...., C#
statement z = Math.Sin(x*y)+37;
iteration for, while, ..
recursion if (n==0) return 1;
else return n*Fac(n-1);
using System;
using System.Drawing;
using System.Collections;
using
System.ComponentModel;
using System.Windows.Forms;
using
System.Data;
using System.IO;
namespace CompPhysics
{
///
<summary>
/// Form1.cs is written in resulting from the lecture
"Physics using Computer".
/// </summary>
public class Form1 :
System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox
textBox1;
private System.Windows.Forms.Button button1;
private
System.Windows.Forms.TextBox textBox2;
/// <summary>
/// textBox1 is
input, button1 is to run, and textBox2 is output.
///
</summary>
private System.ComponentModel.Container components =
null;
public Form1()
{
InitializeComponent();
}
///
<summary>
/// We have only a Form1.
///
</summary>
protected override void Dispose( bool disposing
)
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing
);
}
#region Windows Form Designer generated code
///
<summary>
/// InitializeComponent is generated automatically.
///
</summary>
private void InitializeComponent()
{
this.textBox1 =
new System.Windows.Forms.TextBox();
this.button1 = new
System.Windows.Forms.Button();
this.textBox2 = new
System.Windows.Forms.TextBox();
this.SuspendLayout();
//
//
textBox1
//
this.textBox1.Location = new System.Drawing.Point(16,
128);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new
System.Drawing.Size(128, 20);
this.textBox1.TabIndex =
0;
this.textBox1.Text = "";
//
// button1
//
this.button1.Location = new System.Drawing.Point(240,
72);
this.button1.Name = "button1";
this.button1.Size = new
System.Drawing.Size(112, 40);
this.button1.TabIndex = 1;
this.button1.Text
= "Click to Run";
this.button1.Click += new
System.EventHandler(this.button1_Click);
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(32,
160);
this.textBox2.Multiline = true;
this.textBox2.Name =
"textBox2";
this.textBox2.ScrollBars =
System.Windows.Forms.ScrollBars.Vertical;
this.textBox2.Size = new
System.Drawing.Size(408, 184);
this.textBox2.TabIndex =
2;
this.textBox2.Text = "output";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize
= new System.Drawing.Size(488, 366);
this.Controls.AddRange(new
System.Windows.Forms.Control[]
{
this.textBox2,
this.button1,
this.textBox1});
this.Name =
"Form1";
this.Text =
"Form1";
this.ResumeLayout(false);
}
#endregion
///
<summary>
/// Change only the part of button1_Click.
///
</summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void
button1_Click(object sender, System.EventArgs e)
{
}
}
}
TextBox is one of classes in .NET framework. We use two TextBox objects. One of them is for input and the other is for output. When we try to see results, we simply click Button objects. Also Button is one of classes in .NET framework. Each component has a property, which contains Back Ground Color, etc. When you make a textbox or a button, you can use Tool Box, which you can find in the left part of Visual Studio .NET IDE.
this.textBox1.Text = "Yahoo!";
this.textBox2.Text = this.textBox1.Text;
- Graphical User Interface (GUI)
- Console Application
using System;
namespace HelloWorld
{
class Hello
{
public Hello( )
{
}
}
}
/* This is the answer to the question.
there are many lines in codes
So we use as */
Code:
int x; // first integer
int y; // second integer
int z; // third integer // This three statements become a single as int x,y,z;
.....
x = 7; // x variable, 7 value
.....
x=y+10;
.....
x="Hello" // It makes an error, because x is an integer.
x=x - 1; // Good Expression.
x+y*z; // the same as math x+yz
x+(y*z); // this is different from (x+y)*z
"abc", "good bye \n", "abc\tdef", "abc"+"def"="abcdef",...
Code:
double i = 1.0;
double k = 8.0;
k =
Convert.ToDouble(textBox1.Text);
double j = i+k;
int i1 = 5, k1=
3;
int j1 = i1%k1;
bool tf = false;
string str = "this is a
string.";
if(tf) textBox2.Text = Convert.ToString(tf);
else textBox2.Text
= "false";
textBox2.Text += "\r\n";
textBox2.Text += str+"\r\n";
- Problem
specified informally or formally ( i.e. mathematically)
- Algorithm
abstract solution to a problem, expressed formally or informally.
Mathematics - formal
English - informal
pseudo-code
- Program
concrete solution to a problem, i.e. a concrete instantiation of an algorithm.
2. There may be more than one program to realize a given algorithm.
get ten numbers
add numbers all together
divide sum by ten
- if
- if / else
- switch
- while
- do / while
- for
- foreach
bool foo = false;
bool foo2 = true;
if(foo)
{
textBox2.Text +=
"if is running"+"\r\n";
textBox2.Text += "\t more";
}
else
if(foo2)
{
textBox2.Text +="foo2 is
true";
}
else
{
textBox2.Text += " foo is
false";
}
textBox2.Text += " the end";
217.345e5 float - 32 bit, double - 64 bit
conversion x = (float) n / (float) y;
1byte = 8 bit , ASCII = 7 bit, Unicode = 16 bit, MIME = 6 bit
To terminate running code, control <cmd>.
// for
int sum = 0;
for(int a = 10; a >= 0; a -=
2)
{
textBox2.Text += Convert.ToString(a)+"\r\n";
sum += a; // sum =
sum + a;
}
// while
int k = 0;
while(k <
10)
{
textBox2.Text +="kkkk"+"\r\n";
k++;
}
// switch
string
k = textBox1.Text;
switch(k)
{
case "yes":
case "YES":
case
"Yes":
textBox2.Text = " k is yes";
break;
case "no":
textBox2.Text
= " k is no";
break;
default:
textBox2.Text = " k is not 1 nor
2";
break;
}
x = x+1; x+= 1; x++; ++x;
x = x+7; x+=7;
+= -= /= *= %=
x=2; y=x++ + 7; => y=9 and x=3; "after add".
x=2; y=++x + 7; => y=10 and x=3; "before add".
// ++a, a++;
int a = 10;
a++;
++a;
int b = a +
1;
a++;
textBox2.Text += " b is "+Convert.ToString(b);
Examples: Console.WriteLine()
Console.ReadLine()
Int32.Parse()
MessageBox.Show()
Syntex: <class name>.<method name> for static method.
<object name>.<method name> for dynamic method.
using System; => We do not need to write a long commend as System.Console.WriteLine();
Method call or invocation:
Syntex: <method name>(<argument list>)
ex) Int32.Parse("123");
Method definition:
Syntex: <return type> <method name>(<parameter list>) { <body>}
Example:
Method Code:
private void button1_Click(object sender, System.EventArgs
e)
{
double c = -100.0;
a =
Convert.ToInt32(textBox1.Text);
textBox2.Text = Convert.ToString(c);
c =
Square(5.2);
textBox2.Text +=" "+ Convert.ToString(c);
}
int
a;
int c; // think about shadow
private void Square()
{
c =
a*a;
}
Another Example:
char[] c;
private void button1_Click(object sender, System.EventArgs
e)
{
c = textBox1.Text.ToCharArray();
textBox2.Text =
Convert.ToString(c[3]);
}
We can use the same names for Method with different input types.
private int Square(int a)
{
return a*a;
}
private
double Square(double a)
{
return a*a;
}
private int Square(double a) // it
can not be distinguished by double Square(double a), thus, it makes an error.
The type of return is irrelevant.
{
return a*a;
}
To make a method to be an independent code, the rule of shadow is adopted.
int a = 10;
public int ShadowTest(int x)
{
int a = 23;
return a;
}
As we can see in the above code, the return value will be 23.
Data Structure:
structured value (or objects)
whose components are other values (or data structures)
Examples: Lists, Trees, Pairs, Tuples, Stacks, Queues, ... and Arrays.
Array: Fixed-sized set of continuous memory locations.
n elements
0 | First |
1 | Second |
2 | Third |
3 | Fourth |
n-1 | n-th |
Data structures are characterized by three kinds of operations on them.
a.Length => length (size) of a
Code:
// Array
int[] a = new int[6];
a[0] = 8;
a[1] = 2;
a[2] =
6;
a[3] = a[0] + a[2];
a[4] = 7;
a[5] = 6;
// Multiple Array
double[,,] a = new double[2,3,2]; //
first 0,1 second 0,1,2, third 0,1
a[1,1,0] = 10.678;
a[1,2,1] =
12.9;
textBox2.Text = Convert.ToString(a[1,1,1]);
Called by Value: Make copy of argument before passing ( int, float, bool, char, double) to method.
Called by Reference: A reference to value is passed to method. (arrays, objects, strings,...).
If arrays were immutable, no difference between CBV and CBR (except in efficiency).
If arrays are mutable, results can be different.
As pointer in C, the keywork "ref" is used in C#.
Code:
private void
button1_Click(object sender, System.EventArgs e)
{
a[0] =
2.0;
Replace(a);
b = 4.0;
Replace(b);
textBox2.Text =
Convert.ToString(b);
}
double[] a = new double[2];
double
b;
private void Replace(double[] c)
{
c[0] = 5.0;
}
private void
Replace(double c)
{
c = 5.0;
}
When a method is executed, all local variables are disappeared except return variables or global variables.
private
void button1_Click(object sender, System.EventArgs e){
ff(x);
textBox1.Text += x[0] + "\r\n";
textBox1.Text += x[1] + "\r\n";
}
double[] x = { 1.5, 2.9 };
private void ff(double[] x)
{
double[] xx;
double[] y = { 2.4, 1.6 };
xx = y; // compare x = y;
x[1] = xx[1];
}
foreach is useful when we do not know the exact Length of array.
Of course, it is possible to change foreach to for.
Code:
private void button1_Click(object sender, System.EventArgs
e)
{
// Student[] y;
double[,,] x = new double[2,4,3];
x[0,0,0] =
2.8;
x[0,1,0] = 1.1;
foreach(double k in x)
{
textBox2.Text +=
Convert.ToString(k)+"\r\n";
}
// for(int i =0; i<2; i++)
// for(int
j =0; j<4; j++)
// textBox2.Text +=
Convert.ToString(x[i,j])+"\r\n";
}
In order to distinguish variables inside class and the same name variables inside a method,
we use the keywork "this". In consequence, this is used to overcome shadow.
Code:
private int x = 1;
// private int y =
x;
private void button1_Click(object sender, System.EventArgs
e)
{
int x = 7;
int y = this.x;
textBox2.Text =
Convert.ToString(y);
}
To access private members which have index, we use indexer using the keyword "this".
Code:
private double[,] el;
public double this[int a, int b]
{
get{return el[a,b];}
set{el[a,b]=value;}
}
It is useful to use keyword operator to see our usual operator.
Code:
public static Matrix operator *(Matrix a, Matrix b) // This
code must locate at Matrix.
{
Matrix b = new
Matrix();
b.SetSize(a.SizeOfRow,c.SizeOfColumn);
double
sum;
for(int
k = 0; k < b.SizeOfRow; k++) {
for(int
j = 0; j < b.SizeOfColumn; j++) {
sum = 0.0;
for(int
s = 0; s < a.SizeOfColumn; s++) sum += a.Element[k,s]*c.Element[s,j];
"To iterate is human, to re-curse is divine."
Example: Factorial n! = n*(n-1)*(n-2)....(2)(1)
fac(n) = | 1 if n=0 |
n*fac(n-1) if n > 0 |
Code for Recursive:
private void button1_Click(object sender, System.EventArgs
e)
{
int a = Convert.ToInt32(textBox1.Text);
textBox2.Text =
Convert.ToString(Factorial(a));
}
private int Factorial(int
n)
{
if( n == 0) return 1;
else return
n*Factorial(n-1); // or: return (n <= 1) ? 1 :
n*Factorial(n-1);
}
Example 2:
private int Fib(int n)
{
if(n=0) return 0;
else if (n=1) return 1;
else return Fib(n-1)+Fib(n-2);
}
Example 3:
private int GCD(int x, int y)
{
if(x==y) return x;
else return GCD(y,x%y);
}
A class is a template for an object.
An object encapsulates states and methods.
class is used to achieve ADT (Abstract Data Type).
Code:
private void button1_Click(object sender, System.EventArgs
e)
{
Student a = new Student("chung");
Student
b = new Student("kim",345);
b.Number = 346;
textBox2.Text = b.Name+"
"+Convert.ToString(b.NumberAdd(20));
}
public class Student
{
private
string n; // private objects
private int num;
// private objects
public Student() //
Constructor
{
n = "ftfttt";
num = 0;
}
public Student(string
name) // overload Constructor
{
n = name;
num = 0;
}
public Student(string
name, int a) // Constructor
{
n = name;
num = a;
}
public string
Name // Property
{
get{return n;}
}
public int Number //
Property
{
get{return num;}
set{num=value;}
}
public int
NumberAdd(int a) // public Method
{
return
PrivateNumberAdd(a);
}
private int PrivateNumberAdd(int a) // private
Method
{
num = num + 2*a;
return num;
}
}
// end of class
Another code:
public
class Coin{
private int val; private string state = "Head"; // private object public Coin(){
}
public Coin(int price) // constructor{
val = price;
}
public int Value // property{
get{return val;} set{val=value;}}
public string State // property{
get{return state;}}
private bool front = true; public void Flip() // method{
if(front) {state = "Tail";front=false;} else {state = "Head";front=true;}}
}
To reuse classes, we have to consider inheritance.
As an example for inheritance, we
consider three classes.
Point
|
Circle
|
Cylinder
Code:
private
void button1_Click(object sender, System.EventArgs e)
{
Cylinder cy =
new Cylinder(2.3,5.6,1.0,1.0);
cy.h = 2.0;
Circle c = new
Circle(2.1,4.5,6.7);
Cylinder cy1 = new
Cylinder(2.3,5.6,1.0,3.0);
textBox2.Text = Convert.ToString(cy1.Volume());
// Circle cir = new Circle(2.3,5.6,1.0,1.0);
// cir = new Cylinder(2.3,2.3,1.0,4.3);
// textBox2.Text = Convert.ToString(cir.Area());
} // Main Code
public class Point
{
protected double x, y;
public
Point() // Constructor
{
x = 0.0;
y = 0.0;
}
public Point(double a, double
b) // Constructor Overloading
{
x = a;
y = b;
}
public double X
{
get{return
x;}
}
public double Y
{
get{return y;}
}
}
public class
Circle : Point // Circle is inherited from Point
{
protected double r;
public Circle() :
base()
{
}
public Circle(double a, double b, double c) :
base(a,b)
{
r = c;
}
/* public Circle(double a, double b,
double c)
{
x = a;
y = b;
r = c;
}
*/
public
virtual double
Area()
{
return r*r*Math.PI;
}
}
public class Cylinder :
Circle
{
public double h;
public Cylinder(double a, double b, double c,
double d) : base(a,b,c)
{
h = d;
}
public override double
Area()
{
return base.Area()*2.0+h*2.0*Math.PI*r;
}
public double
Volume()
{
return r*r*Math.PI*h;
}
}
When we make derived classes, we use keyword "base" to avoid duplication of making constructors.
Code:
public ClassConstructor(int a, int b, int c) : base(a, b)
{
k = c;
}
public void Method2(int x)
{
base.Method1(x);
}
"public" methods can be called outside class, while "private" methods or variables can be called only inside the corresponding class.
"protected" methods or variables can be called in derived classes.
Shapes
| \
2D 3D
|
Rectangular
|
Square
When we make all classes, we write new Shape(..) however this Constructor has no sense.
We use keyword abstract - override or virtual - override. It is not needed to override for virtual.
If at least one abstract is used in a class, then the class is abstract.
Code:
public abstract class Point
{
protected double
x, y;
public Point()
{
x = 0.0;
y = 0.0;
}
public Point(double
a, double b)
{
x = a;
y = b;
}
public double X
{
get{return
x;}
}
public double Y
{
get{return y;}
}
public abstract int
Meth();
{
return 3;
}
}
public class Circle :
Point
{
protected double r;
public Circle() : base()
{
}
//
public Circle(double a, double b, double c) : base(a,b)
// {
// r =
c;
// }
public Circle(double a, double b, double c)
{
x = a;
y =
b;
r = c;
}
public double Area()
{
return
r*r*Math.PI;
}
public override int Meth()
{
return
4;
}
}
public class Cylinder : Circle
{
public double
h;
public Cylinder(double a, double b, double c, double d) :
base(a,b,c)
{
h = d;
}
public new double Area()
{
return
r*r*Math.PI*2.0+h*2.0*Math.PI*r;
}
public double Volume()
{
return
r*r*Math.PI*h;
}
// public override int Meth()
// {
// return
5;
// }
}
When a programmer wants to use a method as an argument in a method, he have to use "delegate".
For example, EventHandler is a delegate name.
Code:
private void button1_Click(object sender, System.EventArgs
e)
{
D4 kk = new D4(Mul);
// D4 is delegate name, and method "Mul" is delivered.
textBox2.Text = All(kk,-12.3,10.1);
}
// Main
private double Add(double a, double b)
{
return a+b;
}
private double Sub(double a, double b)
{
return a-b;
}
private double Mul(double a, double b)
{
return a*b;
}
private double Div(double a, double b)
{
return a/b;
}
private string All(D4 ss, double a, double
b)
{
if(ss(a,b)>0.0) return "bigger than zero";
else return
"small";
}
private delegate double D4(double a, double b);
Exception handling: Programmer can control errors, with which we meet anomalous situations that
the program can recover from
Code with try-catch-finally:
private void button1_Click(object sender,
System.EventArgs e)
{
double a;
try
{
a =
Convert.ToDouble(textBox1.Text);
}
catch(FormatException
errrr)
{
MessageBox.Show(errrr.Message,"you gave
nothing.",MessageBoxButtons.OK, MessageBoxIcon.Error);
a =
1.0;
}
catch(IndexOutOfRangeException)
{
a =
3.0;
}
finally
{
a =5.0;
}
double b = 10.0/a;
textBox2.Text
= Convert.ToString(b);
}
user-defined exception
//C#: Exception Handling:
User defined exceptions
//Author: rajeshvs
using System;
class MyException : Exception
{
public MyException(string str)
{
Console.WriteLine("User defined exception");
}
}
class MyClient
{
public static void Main()
{
try
{
throw new MyException("RAJESH");
}
catch(Exception e)
{
Console.WriteLine("Exception caught here" +
e.ToString());
}
Console.WriteLine("LAST STATEMENT");
}
}
In order to use Numerical Recipes as a library, we download
NumericalRecipes.zip
from internet. and unzip in an appropriate directory,
for example, /Visual Studio Projects/NumericalRecipes.
When we make an WindowsApplication1 (which is default) project,
we can see a Form1.cs in the WindowsApplication1 project under the
WindowsApplication1 solution.
Put our mouse at the solution name, and click the right button of
mouse, then we can see some menu. Find the item of Add and add the
project of NumericalRecipes. Then we can see two projects: one is
our project, and the other is NumericalRecipes. Now what we have to
do is that we allow the original project to notice the library (the
second project). In our project, we should find Reference. Put
mouse on Reference, click the right button, and add the project of
NumericalRecipes. It is convenient to use "using
NR=NumericalRecipes;" in the file of Form1.cs of our original project.
C# is useful to create graphics.
Usual coordinate system measured in pixels.
(0,0)-------x--------(maxX,0)
|
|
|
| | |
y---------(x,y) |
| |
(0,maxY)------------(maxX,maxY)
Graphics object allows one access to a graphics context.
To access or create a graphic object
Colors: ARGB(alpha-red-green-blue), alpha means transparency.
All represented by bytes: 0-255.
We can use names of color: Color.Red, Color.Green, Color.Blue, Color.Yellow, Color.Pink.
Brushes and Pens: See below codes.
Shapes: DrawLine(pen1, x1,y1,x2,y2); FillRectangle(brush1,x1,y1,width,height);
Graphics Transforms; g.TranslateTransform(a,b); x -> x+a, y->y+b g.RotateTransform(a)
Code:
Graphics g;
private void button1_Click(object sender,
System.EventArgs e)
{
g = panel1.CreateGraphics();
// Color c =
Color.FromArgb(255,255,0,0);
ColorDialog c = new ColorDialog();
c.FullOpen
= true;
DialogResult re = c.ShowDialog();
SolidBrush b = new
SolidBrush(c.Color);
// g.FillEllipse(b,0,0,100,135);
Pen p = new
Pen(b,2);
// g.DrawEllipse(p,2,34,200,226);
double v0 =
Convert.ToDouble(textBox1.Text);
PointF[] po = new PointF[100];
for(int
time = 0; time < po.Length ; time++)
po[time] = new
PointF((float)(v0*time),(float)(150.0+100.0*Math.Sin(0.2*time)));
g.DrawLines(p,
po);
}
private void button2_Click(object sender, System.EventArgs
e)
{
g.Clear(panel1.BackColor);
}
There are nice two classes named as File and Directory.
They are useful to write data into hard disc.
Or we
can use StreamWriter.
Code:
private
void button1_Click(object sender, System.EventArgs e){
string s = textBox2.Text;
SaveFileDialog file
= new SaveFileDialog();
DialogResult res =
file.ShowDialog();
file.CheckFileExists = false;
string filename =
file.FileName;
StreamWriter wr = new
StreamWriter(filename);
wr.WriteLine(s);
wr.Close();
}
Two Forms
private
void button1_Click(object sender, System.EventArgs e){
textBox1.Text="i will see";
Form2 form2 = new Form2();
form2.Show();
} // Form1 method
private
void button1_Click(object sender, System.EventArgs e){
textBox1.Text = "second form works";
}
private void button2_Click(object sender, System.EventArgs e)
{
this.Dispose();
} // Form2 method
Extensible Array: ArrayList al = new ArrayList(1);
We can add arbitrary number of lists.
Code:
private
void button1_Click(object sender, System.EventArgs e){
ArrayList x = new ArrayList(1);
int ix = 10;
double
y = 234.999;
string z =
"yyyyy";
x.Add(ix);
x.Add(345.876);
x.Add(y);
x.Add("ssss");
x.Add(z);
x.Insert(2,"in
front of y=234.999");
x.Remove(y);
x.RemoveAt(0);
for(int i =0;
i< x.Count; i++)
textBox2.Text +=
Convert.ToString(x[i])+"\r\n";
x.Clear();
}
One of the best way in handling data would be using Excel.
In order to use Excel, we first have to install Microsoft.Office.Interop.Excel.dll by executing oxppia.zip
into ProgramFiles/.NETFramework/Microsoft.Net.
You can find the dll library using the keyword "Primary Interoperator Assemblers" in google.
After we add it as a reference, we can run the following code.
using
System;using
System.Reflection; // In order to handle Type.Missingusing
Xls = Microsoft.Office.Interop.Excel;namespace
Science.Mathematics.Graphics{
/// <summary> /// Excel /// </summary> public class Excel{
public Excel(){
}
private string bookname="Book1", sheetname="Sheet1",cell="A1", cellend="B2";
public string NameOfBook{
get{return bookname;} set{bookname = value;}}
public string NameOfSheet{
get{return sheetname;} set{sheetname = value;}}
public string StartingCell{
get{return cell;} set{cell = value;}}
public string EndingCell{
get{return cellend;} set{cellend = value;}}
public void Write(double[,] obj){
Xls.Application objApp =
new Xls.Application();Xls.Workbooks objBooks = objApp.Workbooks;
Xls.Workbook objBook = objApp.Workbooks.Open
(System.Windows.Forms.Application.StartupPath + "\\"+bookname+".xls",
Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,Type.Missing);
Xls.Sheets objSheets = objBook.Worksheets;
int findsheet = 0;Xls.Worksheet objSheet;
for(int k = 0; k < objSheets.Count; k++){
objSheet = (Xls.Worksheet)objSheets.get_Item(k+1);
if(objSheet.Name == sheetname) findsheet = k+1;}
if(findsheet==0){
objSheet = (Xls.Worksheet)objSheets.Add( Missing.Value,Missing.Value,
Missing.Value, Missing.Value);
objSheet.Name = sheetname;
}
else objSheet = (Xls.Worksheet)objSheets.get_Item(findsheet);Xls.Range range;
range = objSheet.get_Range(cell, Missing.Value);
range = range.get_Resize(obj.GetLength(0),obj.GetLength(1));
range.set_Value(Missing.Value, obj);
objBook.Save();
// objApp.Visible = true;
// objApp.UserControl = true;
objApp.Quit();
}
private int row, column; public int NumberOfRow{
get{return row;}}
public int NumberOfColumn{
get{return column;}}
public void FindSize(){
Xls.Application objApp =
new Xls.Application();Xls.Workbooks objBooks = objApp.Workbooks;
Xls.Workbook objBook = objApp.Workbooks.Open
(System.Windows.Forms.Application.StartupPath + "\\"+bookname+".xls",
Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,Type.Missing);
Xls.Sheets objSheets = objBook.Worksheets;
int findsheet = 0;Xls.Worksheet objSheet;
for(int k = 0; k < objSheets.Count; k++){
objSheet = (Xls.Worksheet)objSheets.get_Item(k+1);
if(objSheet.Name == sheetname) findsheet = k+1;}
objSheet = (Xls.Worksheet)objSheets.get_Item(findsheet);
Xls.Range range = objSheet.get_Range(cell,cellend);
Object[,] x = (Object[,])range.get_Value( Missing.Value );
row = x.GetLength(0);
column = x.GetLength(1);
objApp.Quit();
}
public void Read(double[,] y){
Xls.Application objApp =
new Xls.Application();Xls.Workbooks objBooks = objApp.Workbooks;
Xls.Workbook objBook = objApp.Workbooks.Open
(System.Windows.Forms.Application.StartupPath + "\\"+bookname+".xls",
Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,Type.Missing,
Type.Missing,Type.Missing,Type.Missing,Type.Missing);
Xls.Sheets objSheets = objBook.Worksheets;
int findsheet = 0;Xls.Worksheet objSheet;
for(int k = 0; k < objSheets.Count; k++){
objSheet = (Xls.Worksheet)objSheets.get_Item(k+1);
if(objSheet.Name == sheetname) findsheet = k+1;}
objSheet = (Xls.Worksheet)objSheets.get_Item(findsheet);
Xls.Range range = objSheet.get_Range(cell,cellend);
Object[,] x = (Object[,])range.get_Value( Missing.Value );
for(int i = 0; i<y.GetLength(0); i++) for(int j = 0; j<y.GetLength(1); j++)y[i,j] = Convert.ToDouble(x[i+1,j+1]);
// objApp.Visible = true;
// objApp.UserControl = true;
objApp.Quit();
}
}
}
And then, use the tool for graph, Origin.
using
System;namespace
Science.Mathematics.Graphics{
/// <summary> /// Origin /// </summary>public class Origin
{
public Origin(){
}
private string name; public string NameOfFile{
get{return name;}set{name=value;}
}
public void Run(){
System.Diagnostics.Process Proc =
new System.Diagnostics.Process();Proc.StartInfo.WorkingDirectory = System.Windows.Forms.Application.StartupPath;
Proc.StartInfo.FileName = name+".opj";
Proc.Start();
}
}
}
There are several project types such as ConsoleApplication, WindowsApplication, WebApplication, and WebService.
The following code is one of WebApplication where we use WebService also.
Code:
private localhost.Service1 ws = new
localhost.Service1();
private void Button1_Click(object sender,
System.EventArgs e)
{
TextBox2.Text
=
Convert.ToString(ws.Fac(Convert.ToInt32(TextBox1.Text)));
}
WebService will be one of powerful tools in the future of computing. Be aware of the power of WebService. The following code is a part of a project of WebService.
Code:
[WebMethod]
public string HelloWorld()
{
return
"Hello World";
}
[WebMethod]
public int Fac(int x)
{
if(x == 0)
return 1;
else return x*Fac(x-1);
}
It is possible to make a windows application which runs in a specific computer only. To do so, we have to use Mac number which is an identification for each computer.
Code:
using
System;using System.Management;
namespace
EngineLibrary{
/// <summary> /// MACAddress /// </summary> public class WhoAmI{
private string given="000802DE1CD4"; //"0004764BDFEF"; // Typical Mac Number public WhoAmI(){
}
private string address; public string MACAddress{
get{return address;}}
private bool same; public bool Same{
get{return same;}}
public void Find(){
ManagementClass mC =
new ManagementClass("Win32_NetworkAdapterConfiguration");ManagementObjectCollection mOC = mC.GetInstances();
address=String.Empty;
foreach(ManagementObject mO in mOC){
if(address==String.Empty){
if((bool)mO["IPEnabled"]==true) address=mO["MacAddress"].ToString();}
mO.Dispose();
}
address=address.Replace(":","");
same = (address==given) ?
true : false;}
}
}
The driver code to use the class of WhoAmI is following.
Code:
using
System.Windows.Forms;................
WhoAmI iAm = new WhoAmI();
iAm.Find();
if(iAm.Same)
{
}
else
{
try{throw new Exception();}
catch (Exception)
{
MessageBox.Show("Please support our authors.",
"Invalid user",MessageBoxButtons.OK, MessageBoxIcon.Error );
}
}
We can show a pdf file in a windows application form. It is important to refer two dll files: AxInterop.AcroPDFLib.dll, Interop.AcroPDFLib.dll which can be downloaded in the Internet.
Code:
using
System;using
System.Drawing;using
System.Collections;using
System.ComponentModel;using
System.Windows.Forms;using
System.Data;namespace
ShowPDF{
/// <summary> /// Form1 /// </summary> public class Form1 : System.Windows.Forms.Form{
private AxAcroPDFLib.AxAcroPDF axAcroPDF1; private void InitializeAdobe(){
try{
System.Resources.ResourceManager resources =
newSystem.Resources.ResourceManager(
typeof(Form1)); this.axAcroPDF1 = new AxAcroPDFLib.AxAcroPDF();((System.ComponentModel.ISupportInitialize)(
this.axAcroPDF1)).BeginInit(); this.axAcroPDF1.Enabled = true; this.axAcroPDF1.Location = new System.Drawing.Point(84,38); this.axAcroPDF1.Name = "axPdf1"; this.axAcroPDF1.OcxState =((System.Windows.Forms.AxHost.State)(resources.GetObject("axAcroPDF1.OcxState")));
this.axAcroPDF1.Size = new System.Drawing.Size(854,470);
this.axAcroPDF1.TabIndex = 0; this.Controls.Add(this.axAcroPDF1);((System.ComponentModel.ISupportInitialize)(
this.axAcroPDF1)).EndInit();axAcroPDF1.LoadFile("../../aoki.pdf");
axAcroPDF1.Show();
}
catch (Exception ex){
MessageBox.Show(ex.Message);
}
}
/// <summary> /// /// </summary> private System.ComponentModel.Container components = null; public Form1(){
// // Windows Form //InitializeComponent();
InitializeAdobe();
// // TODO: InitializeComponent //}
/// <summary> /// /// </summary> protected override void Dispose( bool disposing ){
if( disposing ){
if (components != null){
components.Dispose();
}
}
base.Dispose( disposing );}
#region
Windows Form Designer generated code /// <summary> /// /// /// </summary> private void InitializeComponent(){
// // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(344, 326); this.Name = "Form1"; this.Text = "Form1";}
#endregion
/// <summary> /// /// </summary>[STAThread]
static void Main(){
Application.Run(
new Form1());}
}
}