TemperatureColor

int r = 0, g = 0, b = 0;
if (Temperature <= 0.0)
{
// BLUE(0, 0, 255) (~ 0.0F)
r = 0; g = 0; b = 255;
}
else if ((Temperature > 0.0) && (Temperature <= 20.0))
{
// BLUE(0, 0, 255)->CYAN(0, 255, 255) (0.0F ~ 20.0F)
r = 0; g = (int)(255 * (Temperature + 0.0) / 20); b = 255;
}

// CYAN(0, 255, 255)->GREEN(0, 255, 0) (20.0F ~ 40.0F)

// GREEN(0, 255, 0)->YELLOW(255, 255, 0) (40.0F ~ 60.0F)

// YELLOW(255, 255, 0)->RED(255, 0, 0) (60.0F ~ 80.0F)

// RED(255, 0, 0) (80.0F ~)

return Color.FromArgb(75, r, g, b);

HW4

단국대학교 멀티미디어공학전공 HCI프로그래밍2 (2015년 가을학기) 실습

날짜: 2015년 11월 20일

 

– 실습번호 : lab-04 (Due by 12/11)

– 실습제목 : Window.Forms Controls (ListView, ComboBox, etc), RSS, XML, GMap.Net, YahooWeather, LINQ

– 실습요약 : 지도 위에 현재의 날씨 정보를 보여준다.

 

– 실습문제

Resources.zip 파일을 사용하여 imageList 를 만든다.

  1. GMap.Net 컨트롤을 설치한다.

http://www.independent-software.com/gmap-net-tutorial-maps-markers-and-polygons/

http://dis.dankook.ac.kr/lectures/hci15/?p=541 커스텀 컨트롤 추가 참고

 

        private void Form1_Load(object sender, EventArgs e)
        {
            // Initialize map:
            gMapControl1.MapProvider = GMap.NET.MapProviders.GoogleMapProvider.Instance;
            GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
            gMapControl1.SetPositionByKeywords(“Seoul, Korea”);
            gMapControl1.CanDragMap = true;
            gMapControl1.DragButton = MouseButtons.Left;
            gMapControl1.MouseWheelZoomType = GMap.NET.MouseWheelZoomType.MousePositionAndCenter;
            gMapControl1.MinZoom = 3;
            gMapControl1.MaxZoom = 19;
            gMapControl1.Zoom = 4;
            gMapControl1.ScrollControlIntoView(this);

            // Update gMapMarker using weather list
            UpdateWeatherMarker(weatherList); // 구현 필요 – GMapMarkerImage과 GMapMarkerCircle를 사용하여 gMapControl1에 마커를 표현
        }

 

  1. 야후 날씨 정보 Yahoo Weather RSS Feed 설명

https://developer.yahoo.com/weather/documentation.html

 

  1. WOEID (World On Earth ID) 설명

https://developer.yahoo.com/geo/geoplanet/guide/concepts.html

 

  1. WOEID.csv 파일을 읽어서 List<WOEID>를 만든다.

NEWWOEID

http://dis.dankook.ac.kr/lectures/hci15/?p=572 Person.csv 파일 읽기 참고

 

  1. WOEID (World On Earth ID)에 따라 최근 야후 날씨 정보를 Feed 할 수 있다.

string url = string.Format(“http://weather.yahooapis.com/forecastrss?w={0}”, woeid);

http://weather.yahooapis.com/forecastrss?w=1132599 Seoul Yahoo Weather RSS

Yahoo! Weather – Seoul, KR (Seoul Yahoo Weather RSS XML 파일 예시)

  1. WeatherData 클래스를 만든다.

public class Condition

{

public string Text { get; set; }

public int Code { get; set; } // 0 (tornado) 3200 (not available)

public int Temperature { get; set; } // cloudy, rain, etc

public string Date { get; set; }

public Color TemperatureColor {} // Fahrenheit Color 계산 구현요망

}

public class Forecast

{

public string Day { get; set; }

public string Date { get; set; }

public int Low { get; set; }

public int High { get; set; }

public string Text { get; set; }

public int Code { get; set; }

}

public class WeatherData

{

public long WOEID { get; set; } // LINQ join을 위해 추가

public string Title { get; set; }

public double Lat { get; set; }

public double Lon { get; set; }

public string Link { get; set; }

public Condition Condition = new Condition();

public List<Forecast> FiveForecast = new List<Forecast>();

}

 

  1. List<WOEID>를 이용해서 Rss 피드해서 List<WeatherData >를 만든다.

http://dis.dankook.ac.kr/lectures/hci13/2013/11/26/%ec%a2%85%eb%a1%9c%ea%b5%ac-%ea%b0%80%ed%9a%8c%eb%8f%99-%eb%8f%99%eb%84%a4%ec%98%88%eb%b3%b4-rss-feed/ 기상청 RSS 서비스 Parsing 예시

http://dis.dankook.ac.kr/lectures/hci12/2012/11/21/readrssfeed/ 실시간 지진 데이타 RSS Parsing 예시

 

  1. List<WeatherData>를 이용해서 GMap.NET에 marker에는 현재 날씨 상태(Code)에 따른 아이콘 이미지를 보여주고, 그 위에 현재 날씨 온도(Temperature)에 따른 색깔로 원(circle polygon)을 그려준다.

http://www.independent-software.com/gmap-net-tutorial-maps-markers-and-polygons/

class GMapMarkerCircle : GMapMarker { // 날씨 온도에 따른 색깔로 Circle을 그려주고 그 아래엔 온도를 텍스트로 보여줌

public Color MarkerColor { get; set; }

public Brush Fill = null;

// 생성자에서 Fill = new SolidBrush(MarkerColor);

public override void OnRender(Graphics g) {

g.FillEllipse(Fill, new Rectangle(LocalPosition.X – R/2, LocalPosition.Y – R/2, R, R));

}

}

class GMapMarkerImage : GMapMarker { // 날씨 상태에 따른 Image와 Tooltip으로 날씨 상태 정보를 보여줌

public Image MarkerImage { get; set; }

public override void OnRender(Graphics g) {

g.DrawImage(MarkerImage, LocalPosition.X, LocalPosition.Y, Size.Width, Size.Height);

}

}

WeatherMap

지도에서 아이콘 이미지를 오른쪽 마우스로 클릭하면 위도, 경도 정보가 텍스트박스에 나타남.

private void gMapControl1_OnMarkerClick(GMapMarker item, MouseEventArgs e) { //  내부 구현 필요

}

콤보박스(ComboBox)에서 관심 지역을 선택하면 위도, 경도 정보가  텍스트박스에 나타나고 해당 지역으로 이동함.

private void comboBox1_SelectedValueChanged(object sender, EventArgs e) { // 내부 구현 필요

}

위도 경도 정보를 넣고 ‘이동’ 버튼을 누르면 해당 지역으로 이동함.

private void button1_Click(object sender, EventArgs e) { // 내부구현 필요

}

‘선택지역 날씨 자세히 보기’ 버튼을 누르면 웹 페이지를 띄움.

private void button2_Click(object sender, EventArgs e) { // 내부구현 필요

}

WeatherWeb

‘지역 전체 날씨보기’ 버튼을 누르면 비모달형 Form2가 뜨면서 지도에 보이는 지역의 날씨 정보를 ListView로 보여줌.

private void button3_Click(object sender, EventArgs e) { // 내부구현 필요

}

WeatherList

private void Form2_Load(object sender, EventArgs e) { // 내부구현 필요

// LINQ Joined Query 를 통하여 listView item에 추가

}

 

ReadRssFeed

using System.Net; // HttpWebRequest

public static WeatherData ReadWeatherDataFeedBy(long woeid)
{
//create a new list of the rss feed items to return
string url = string.Format(“http://weather.yahooapis.com/forecastrss?w={0}”, woeid);

try
{
//create an http request which will be used to retrieve the rss feed
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = 200000;
request.Method = WebRequestMethods.Http.Get;

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

if (response.StatusCode != HttpStatusCode.OK)
{
System.Diagnostics.Trace.WriteLine(“Response StatusCode: ” + response.StatusCode);
return null;
}

//loop through the rss items in the dataset and populate the list of rss feed items
using (DataSet rssData = new DataSet())
{
//read the xml from the stream of the web request
rssData.ReadXml(response.GetResponseStream());
//loop through the rss items in the dataset and populate the list of rss feed item
foreach (DataRow itemRow in rssData.Tables[“item”].Rows)
{
WeatherData weatherData = new WeatherData();
weatherData.WOEID = woeid;
weatherData.Title = (string)itemRow[“title”]; // Convert.ToString(itemRow[“title”]);
double lat, lon;
if (!double.TryParse((string)itemRow[“lat”], out lat))
return null;
weatherData.Lat = lat; //  latitude
if (!double.TryParse((string)itemRow[“long”], out lon))
return null;
weatherData.Lon = lon;  // longitude
weatherData.Link = url; // url link
string pubDate = (string)itemRow[“pubDate”]; // pubDate
string description = (string)itemRow[“description”]; // description

foreach (DataRow conditionRow in rssData.Tables[“condition”].Rows)
{
weatherData.Condition.Text = (string)conditionRow[“text”]; // weather condition text
weatherData.Condition.Code = int.Parse((string)conditionRow[“code”]); // weather condition code
weatherData.Condition.Temperature = int.Parse((string)conditionRow[“temp”]); // weather temperature
weatherData.Condition.Date = (string)conditionRow[“date”]; // weather published date
}

foreach (DataRow focastRow in rssData.Tables[“forecast”].Rows)
{
weatherData.FiveForecast.Add(new Forecast()
{
Day = (string)focastRow[“day”], // day
Date = (string)focastRow[“date”], // date
Low = int.Parse((string)focastRow[“low”]),  // low temperature
High = int.Parse((string)focastRow[“high”]), // high temperature
Text = (string)focastRow[“text”], // weather condition text
Code = int.Parse((string)focastRow[“code”]) // code
});
}

System.Diagnostics.Trace.WriteLine(weatherData);
return weatherData;
}
return null;
}
}
catch (Exception e)
{
System.Diagnostics.Trace.WriteLine(“Error while reading ” + e.Message);
return null;
}
}

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]}
]

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));
}