HW3 Figure JSON

FigureJSON

[
{“__type”:”FigureAreaPerimeterCalculator.Quadrilateral”,
“Bounds”:{“__type”:”FigureAreaPerimeterCalculator.FigureBound”,”X”:400,”Y”:300,”Width”:200,”Height”:200},
“Color”:13,
“Vertices”:[{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:400,”Y”:300},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:400,”Y”:500},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:600,”Y”:500},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:600,”Y”:300}],
“Sides”:[200,200,200,200],
“Angles”:[1.5707963267948966,1.5707963267948966,1.5707963267948966,1.5707963267948966]},
{“__type”:”FigureAreaPerimeterCalculator.Quadrilateral”,
“Bounds”:{“__type”:”FigureAreaPerimeterCalculator.FigureBound”,”X”:10,”Y”:10,”Width”:290,”Height”:200},
“Color”:11,
“Vertices”:[{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:10,”Y”:10},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:10,”Y”:210},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:300,”Y”:210},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:300,”Y”:10}],
“Sides”:[200,290,200,290],
“Angles”:[1.5707963267948966,1.5707963267948966,1.5707963267948966,1.5707963267948966]},
{“__type”:”FigureAreaPerimeterCalculator.Quadrilateral”,
“Bounds”:{“__type”:”FigureAreaPerimeterCalculator.FigureBound”,”X”:50,”Y”:240,”Width”:100,”Height”:100},
“Color”:14,
“Vertices”:[{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:50,”Y”:240},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:10,”Y”:340},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:110,”Y”:340},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:150,”Y”:240}],
“Sides”:[107.70329614269008,100,107.70329614269008,100],
“Angles”:[1.9513027039072615,1.1902899496825317,1.9513027039072615,1.1902899496825317]},
{“__type”:”FigureAreaPerimeterCalculator.Quadrilateral”,
“Bounds”:{“__type”:”FigureAreaPerimeterCalculator.FigureBound”,”X”:200,”Y”:350,”Width”:100,”Height”:160},
“Color”:10,
“Vertices”:[{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:200,”Y”:350},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:50,”Y”:510},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:350,”Y”:510},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:300,”Y”:350}],
“Sides”:[219.31712199461307,300,167.6305461424021,100],
“Angles”:[2.3239476077570913,0.81764504583270214,1.2679114584199251,1.873681195169868]},
{“__type”:”FigureAreaPerimeterCalculator.Quadrilateral”,
“Bounds”:{“__type”:”FigureAreaPerimeterCalculator.FigureBound”,”X”:325,”Y”:225,”Width”:25,”Height”:75},
“Color”:1,
“Vertices”:[{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:325,”Y”:225},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:300,”Y”:300},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:325,”Y”:375},{“__type”:”FigureAreaPerimeterCalculator.Point”,”X”:350,”Y”:300}],
“Sides”:[79.05694150420949,79.05694150420949,79.05694150420949,79.05694150420949],
“Angles”:[0.64350110879328448,2.4980915447965089,0.64350110879328448,2.4980915447965089]}
]

Getting Started with Windows Forms

http://msdn.microsoft.com/en-us/library/ms229601(VS.80).aspx

 

Windows Forms Application

.NET2015

 

 

 

  • 메뉴에서 File->New->Project->Visual C# 템플릿->Windows Forms Application를 선택한 후 “프로젝트 이름(예를 들어, WindowFormHello)”을 적고 확인버튼을 누르면 빈폼 프로젝트가 생성된다.
 form1
 form2

 

컨트롤 코드 추가

  • Toolbox(도구상자) 에서 컨트롤을 선택(예를 들어, Label 또는 Button)하여 Dialog기반의 Form1 안에 추가하여 편집한다.
 form3

컨트롤에 이벤트 추가하기
-컨트롤 (예를들어, 버튼을 더블클릭하면 또는 이벤트목록중 Click이벤트에 더블클릭하면)에 클릭 이벤트에 대한 이벤트핸들러에 내용(예를 들어, 레이블의 Text를 “Button Clicked”)을 작성한다.
private void button1_Click(object sender, EventArgs e)
{

// button1을 클릭하면 label1 텍스트 변경

label1.text = “Button Clicked”;
// button1을 클릭하면 Form2 팝업

Form2 f = new Form2();

f.ShowDialog();
}

form8

폼 코드 추가

  • Project 에서 폼을 추가(Add New Item)하여 Form2 를 추가한다.

form5

form6

 

  • Toolbox(도구상자) 에서 컨트롤을 선택(예를 들어, Label 또는 Textbox)하여 Dialog기반의 Form2 안에 추가하여 편집한다.

form7

  • Form2 안에 코드를 추가한다.

form9

빌드(F7) 후 실행(F5)하기

 

TRACE macro

TRACE macro
-윈도우 응용프로그램 개발시 Visual Studio IDE의 Output Window (출력창)에 Debug하는 내용을 출력하고자 할 때 System.Diagnostics.Trace.WriteLine(…..)을 사용
-기존의 C# Console 응용프로그램에서 System.Console.WriteLine(….)와 동일
-기존의 MFC 윈도우 프로그래밍에서 TRACE 매크로와 비슷 (C의 printf와 동일한 형식 지원)
-기존의 WIN32 윈도우 프로그래밍에서 OutputDebugString 함수와 같은 기능 (C의 printf와 동일한 형식 지원)

Figure Class

public enum FigureType // FigureType 판별
{
Triangle,
EquilateralTriangle,
IsoscelesTriangle,
ScaleneTriangle,
Quadrilateral,
Square,
Rectangle,
Parallelogram,
Rhombus,
Trapezoid,
None
}
public class FigureTypeResolver : JavaScriptTypeResolver // JSON serialization & deserialization
{
public override Type ResolveType(string id)
{
return Type.GetType(id);
}

public override string ResolveTypeId(Type type)
{
if (type == null)
{
throw new ArgumentNullException(“type”);
}

return type.FullName;
}
}

public class FigureBound // TopLeft Point(X,Y) & Width & Height
{
public int X
{
set;
get;
}

public int Y
{
set;
get;
}

public int Width
{
set;
get;
}

public int Height
{
set;
get;
}

public FigureBound() : this (0, 0, 10, 10)
{
}

public FigureBound(int x, int y, int width, int height)
{
Set(x, y, width, height);
}

public void Set(int x, int y, int width, int height)
{
this.X = x;
this.Y = y;
this.Width = width;
this.Height = height;
}
public override string ToString() { return (String.Format(“({0}, {1}, {2}, {3})”, X, Y, Width, Height)); } // ToString method override
}

public abstract class Figure
{
public ConsoleColor Color
{
get;
set;
}

protected List<Point> vertices = null;
public List<Point> Vertices // Use Point.cs (Not System.Drawing.Point) for JSON
{
get
{
return vertices;
}
set
{
vertices = value;
UpdateBounds(); // 새 정점에 따른 바운딩박스 계산
UpdateSides(); // 새 정점에 따른 변들 계산
UpdateAngles(); // 새 정점에 따른 내각들 계산
}
}

public FigureBound Bounds = new FigureBound(); // 바운딩박스

public List<double> Sides // 변
{
get;
set;
}

public List<double> Angles // 각도 (radian)
{
get;
set;
}

public abstract void UpdateBounds();
public abstract void UpdateSides();
public abstract void UpdateAngles();

public override string ToString()
{
string listOfVertices = null;
string listOfSides = null;
string listOfAngles = null;
if (Vertices != null)
{
//listOfVertices = string.Join(” , “, Vertices.ToArray()); // .NET4
listOfVertices = string.Join(” , “, Array.ConvertAll(Vertices.ToArray(), x => x.ToString())); // ealier than .NET4
listOfSides = string.Join(” , “, Array.ConvertAll(Sides.ToArray(), x => x.ToString())); // ealier than .NET4
listOfAngles = string.Join(” , “, Array.ConvertAll(Angles.ToArray(), x => x.ToString())); // ealier than .NET4
}
return String.Format(“{0} : {1} : {2} : {3} : {4} : {5}”, GetType().Name, Color, listOfVertices, Bounds, listOfAngles, listOfSides);
} // ToString method override

public void Draw(Graphics g)
{
Brush b = new SolidBrush(System.Drawing.Color.FromName(this.Color.ToString()));
System.Drawing.Point[] points = Array.ConvertAll(Vertices.ToArray(), x => (System.Drawing.Point)x); // Use with Point.cs type conversion operator overload
g.FillPolygon(b, points);
}
}

JSON

AddReference Add Reference

AddReference2System.Web.Extensions 추가

 

using System.Web.Script.Serialization;
// JSON serialize
JavaScriptSerializer serializer = new JavaScriptSerializer(new FigureTypeResolver());
var json = serializer.Serialize(figureList.ToArray());
Console.WriteLine(json);

// JSON deserialize
JavaScriptSerializer deserializer = new JavaScriptSerializer(new FigureTypeResolver());
var loadedFigureList = (List<Figure>)deserializer.Deserialize(json, figureList.GetType());

// convert every item to Figure
for (int i = 0; i < loadedFigureList.Count; i++)
{
var f = (Figure)loadedFigureList[i];
FigureType type = FigureCalculator.GetFigureType(f);
Console.WriteLine(type);
Console.WriteLine(FigureCalculator.Perimeter(type, f));
Console.WriteLine(FigureCalculator.Area(type, f));
}

Import

// 디렉토리 안에 있는 모든 파일을 읽는다
public static void Import(string path, string ext, ref List<Figure> fList)
{
if (Directory.Exists(path))
{
Console.WriteLine(path);
string[] files = Directory.GetFiles(path, ext);
foreach (var file in files) Import(file, ref tList);
}
}

// 개별 파일을 읽는다
public static void Import(string filename, ref List<Figure> fList)
{
// 파일이 존재하면 읽어서 JSON deserialize하여 fList로 로딩한다.
}

HW3 Angle between two vectors

If v1 and v2 are normalised so that |v1|=|v2|=1, then angle = acos(v1•v2)

http://www.euclideanspace.com/maths/algebra/vectors/angleBetween/

// 세 점으로부터 도형의 내각 구하기
public static double InnerAngle(Point p1, Point p2, Point p3)
{
Point v1 = new Point(p1.X – p2.X, p1.Y – p2.Y); // v1 = p1 – p2
Point v2 = new Point(p3.X – p2.X, p3.Y – p2.Y); // v2 = p3 – p2
double len1 = Math.Sqrt(v1.X * v1.X + v1.Y * v1.Y); // v1.Length()
double len2 = Math.Sqrt(v2.X * v2.X + v2.Y * v2.Y); // v2.Length()
double nx1 = v1.X / len1; // n1 = v1.Normalize
double ny1 = v1.Y / len1;
double nx2 = v2.X / len2; // n2 = v2.Normalize
double ny2 = v2.Y / len2;
double dot = (nx1 * nx2) + (ny1 * ny2); // DotProduct(n1, n2)
double radian = Math.Acos(dot);
return (radian * 180.0 / Math.PI); // RadianToDegree
}

// 두 점 간의 거리 구하기

public static double Distance(Point p, Point q)
{
return Math.Sqrt((p.X – q.X) * (p.X – q.X) + (p.Y – q.Y) * (p.Y – q.Y));
}