Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
khizh.doc
Скачиваний:
3
Добавлен:
23.12.2018
Размер:
1.25 Mб
Скачать

Перелік посилань

  1. http://msdn.microsoft.com/ru-ru/library/d56de412.aspx

  2. http://ru.wikipedia.org/wiki/Службы_Windows

  3. http://code.google.com/apis/maps/documentation/staticmaps

Додаток

Service1.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.Linq;

using System.ServiceProcess;

using System.Text;

using Microsoft.Win32;

using System.IO;

using System.Drawing;

using System.Drawing.Imaging;

using System.Text.RegularExpressions;

using System.Threading;

using System.Net;

using System.Timers;

namespace VaiserKursovaGoogleMapsClient

{

public partial class Service1 : ServiceBase

{

public Service1()

{

InitializeComponent();

}

private static void OnTimedEvent(object source, ElapsedEventArgs e)

{

Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);

RegTools.ReadRegistryMapData();

}

private static System.Timers.Timer aTimer;

protected override void OnStart(string[] args)

{

aTimer = new System.Timers.Timer();

aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

aTimer.Interval = 4000;

aTimer.Enabled = true;

}

protected override void OnStop()

{

aTimer.Stop();

}

}

}

RegTools.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Text.RegularExpressions;

using Microsoft.Win32;

using System.IO;

namespace VaiserKursovaGoogleMapsClient

{

class MapInfo

{

public int zoom_level;

public double longtitude;

public double latitude;

public string type;

public int width;

public int height;

}

public class RegTools

{

protected static int maxLogsMonthAge = ReadRegistryLogLifeTimeData();

private static Regex dateSelector = new Regex(@"GoogleMapsClient_\d{2}-(?<month>\d+)-(?<year>\d{4}).log$");

public static string logsFolderPath = @"C:\Windows\Logs\";

private static string Normalize(string value, string[] mapData)

{

string pattern = value + "(.+)";

string result = null;

foreach (var elem in mapData)

{

//Console.WriteLine(elem);

var match = Regex.Match(elem, pattern).Groups[1].Value;

if (!String.IsNullOrWhiteSpace(match))

{

result = match;

}

}

return result;

}

private static void DeleteValue(string ValueName)

{

RegistryKey registrykeyHKLM = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\GoogleMapsClient", true);

registrykeyHKLM.DeleteValue(ValueName);

registrykeyHKLM.Close();

}

public static void ReadRegistryMapData()

{

MapInfo result = new MapInfo();

DeleteOldLogs();

var date = DateTime.Now;

try

{

const string keyName = @"HKEY_LOCAL_MACHINE\SOFTWARE\GoogleMapsClient";

const string valueName = "Claim";

var MapData = (string[])Registry.GetValue(keyName, valueName, new string[] { "Non Exist" });

if ((MapData.Length > 0) && (MapData[0] != "Non Exist") && (!String.IsNullOrWhiteSpace(MapData[0])))

{

result.type = Normalize("Type:", MapData);

result.width = Int32.Parse(Normalize("Width:", MapData));

result.height = Int32.Parse(Normalize("Height:", MapData));

result.latitude = Double.Parse(Normalize("Latitude:", MapData).Replace(".", ","));

result.longtitude = Double.Parse(Normalize("Longtitude:", MapData).Replace(".", ","));

result.zoom_level = Int32.Parse(Normalize("Zoom:", MapData));

DeleteValue("Claim");

Map map = new Map(result);

}

else

{

WriteToLog("\r\n-----------------------------------------" + date + "----------------------------------------------------------------\r\nЗаявка відсутня");

}

}

catch (Exception e)

{

WriteToLog("\r\n-----------------------------------------" + date + "----------------------------------------------------------------\r\nЗаявка некоректна. Виправте або скасуйте заявку!");

Console.WriteLine(e + "");

}

}

public static int ReadRegistryLogLifeTimeData()

{

int result = int.MaxValue;

try

{

const string keyName = "HKEY_LOCAL_MACHINE\\SOFTWARE\\GoogleMapsClient";

const string valueName_Log_Age = "Log_Age";

result = (int)Registry.GetValue(keyName, valueName_Log_Age, int.MaxValue);

}

catch (Exception e)

{

WriteToLog("LogLifeTimeRegistryRead Error: " + e.Message);

}

return result;

}

public static void WriteToLog(string text)

{

var date = DateTime.Now;

string path = logsFolderPath + "GoogleMapsClient_" + date.Day + "-" + date.Month + "-" + date.Year + ".log";

File.AppendAllText(path, "\r\n" + text);

}

public static void DeleteOldLogs()

{

var logFiles = Directory.GetFiles(logsFolderPath, "GoogleMapsClient_*.log");

foreach (var path in logFiles)

{

if (dateSelector.IsMatch(path))

{

var matchedItem = dateSelector.Match(path);

try

{

int month = int.Parse(matchedItem.Groups["month"].Value);

int year = int.Parse(matchedItem.Groups["year"].Value);

int filesMonthAge = DateTime.Now.Month - month - 1 + (DateTime.Now.Year - year) * 12;

if (filesMonthAge >= maxLogsMonthAge) File.Delete(path);

}

catch { }

}

}

}

}

}

Map.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Drawing;

using System.Net;

using System.Threading;

using System.IO;

namespace VaiserKursovaGoogleMapsClient

{

class Map

{

private int SideTileCountWidth;//тайлов с одной стороны по горизонтали

private int SideTileCountHeight;//тайлов с одной стороны по вертикали

private int TileSize = 600;

private double x0;//координаты центра координат новой системы

private double y0;

private int ZoomLevel;

private double weightX;

private double weightY;

double ts;

private List<List<Bitmap>> MapList = new List<List<Bitmap>>();//полная коллекция bitmaps

public Map(int zoom_level, int width, int height, double longtitude, double latitude, string type)

{

this.weightX = 0.7048 / Math.Pow(2, zoom_level - 1);

this.weightY = 0.43 / Math.Pow(2, zoom_level - 1);

this.x0 = longtitude;

this.y0 = latitude;

this.ZoomLevel = zoom_level;

SideTileCountWidth = (int)Math.Ceiling((width / 2 - this.TileSize / 2) / Convert.ToDouble(this.TileSize));

SideTileCountHeight = (int)Math.Ceiling((height / 2 - this.TileSize / 2) / Convert.ToDouble(this.TileSize));

Console.WriteLine("SideTileCountHeight = " + this.SideTileCountHeight + "\r\nSideTileCountWidth = " + this.SideTileCountWidth);

try

{

this.DownloadMap(zoom_level, width, height, longtitude, latitude, type);

this.SaveMap(ts);

}

catch

{

Console.WriteLine("pogano");

return;

}

}

public Map(MapInfo data)

{

this.weightX = 0.7048 / Math.Pow(2, data.zoom_level - 1);

this.weightY = 0.448 / Math.Pow(2, data.zoom_level - 1);

this.x0 = data.longtitude;

this.y0 = data.latitude;

this.ZoomLevel = data.zoom_level;

SideTileCountWidth = (int)Math.Ceiling((data.width / 2 - this.TileSize / 2) / Convert.ToDouble(this.TileSize));

SideTileCountHeight = (int)Math.Ceiling((data.height / 2 - this.TileSize / 2) / Convert.ToDouble(this.TileSize));

Console.WriteLine("SideTileCountHeight = " + this.SideTileCountHeight + "\r\nSideTileCountWidth = " + this.SideTileCountWidth);

try

{

this.DownloadMap(data.zoom_level, data.width, data.height, data.longtitude, data.latitude, data.type);

this.SaveMap(ts);

}

catch

{

Console.WriteLine("pogano");

return;

}

}

private void DownloadMap(int zoom_level, int width, int height, double longtitude, double latitude, string type)

{

var TimeStart = DateTime.Now;

for (int y = SideTileCountHeight; y >= -SideTileCountHeight; y--)

{

List<Bitmap> MapLine = new List<Bitmap>();

for (int x = -SideTileCountWidth; x <= SideTileCountWidth; x++)

{

MapLine.Add(this.DownloadTile(y * TileSize, x * TileSize, TileSize, type));

Thread.Sleep(000);

}

MapList.Add(MapLine);

}

var TimeStop = DateTime.Now;

ts = TimeStop.Subtract(TimeStart).TotalSeconds;

}

private void SaveMap(double ts)//карта пока ещё не кропнута под нужный размер

{

Console.WriteLine(MapList[0].Count);

Bitmap bmp = new Bitmap(MapList[0].Count * this.TileSize, MapList.Count * this.TileSize);

Console.WriteLine("bmp width = " + bmp.Width);

Console.WriteLine("bmp height= " + bmp.Height);

for (int y = 0; y < MapList.Count; y++)//по строкам

{

for (int x = 0; x < MapList[y].Count; x++)//по тайлам

{

for (int row = 0; row < MapList[y][x].Height; row++)//по пикселям строки

{

for (int col = 0; col < MapList[y][x].Width; col++)

{

//Console.WriteLine(y * this.TileSize + row + "," + x * this.TileSize + col);

Color PixelColor = MapList[y][x].GetPixel(row, col);

Color color = Color.FromArgb(PixelColor.R, PixelColor.G, PixelColor.B);

bmp.SetPixel(x * this.TileSize + row, y * this.TileSize + col, color);

}

}

}

}

var date = DateTime.Now;

var LogText = "\r\n-----------------------------------------" + date + "----------------------------------------------------------------\r\n" +

"ЗАЯВКА ПРИЙНЯТА!Карта збережена під ім’ям " + date + ".bmp\r\n" +

"Час завантаження " + ts + "секунд\r\n";

RegTools.WriteToLog(LogText);

this.SaveBMP(bmp, @"C:\WINDOWS\Data\" + date.Day + "-" + date.Month + "-" + date.Year + "_" + date.Hour + "-" + date.Minute + "-" + date.Second + ".bmp");

}

private string NormalizeX(int x)

{

string StrResult;

var result = x * weightX + x0;

if (result >= 180)

{

result = -180 + result % 180;

}

if (result < -180)

{

result = 180 - (-result % 180);

}

StrResult = result.ToString().Replace(',', '.');

return StrResult;

}

private string NormalizeY(int y)

{

string StrResult;

var result = y * weightY + y0;

if (result > 90)

{

result = 90;

//throw new Exception("large resolution");

}

if (result < -90)

{

result = -90;

//throw new Exception("large resolution");

}

StrResult = result.ToString().Replace(',', '.');

return StrResult;

}

public static string IntoString(double m)

{

string result = m.ToString().Replace(',', '.');

return result;

}

public Bitmap DownloadTile(int _y, int _x, int TileSize, string type)

{

try

{

var x = this.NormalizeX(_x);

var y = this.NormalizeY(_y);

WebClient client = new WebClient();

Stream stream = client.OpenRead("http://maps.google.com/maps/api/staticmap?center=" + y + "," + x + "&zoom=" + this.ZoomLevel + "&size=" + this.TileSize + "x" + this.TileSize + "&maptype=" + type + "&sensor=false");

Bitmap bmp = new Bitmap(stream);

Console.WriteLine("width:" + bmp.Width + "\r\nheight:" + bmp.Height);

stream.Flush();

stream.Close();

return bmp;

}

catch (Exception e)

{

Console.WriteLine(e.Message);

return null;

}

}

public void SaveBMP(Bitmap bitmap, string filename)

{

if (bitmap != null)

{

bitmap.Save(filename);

}

else Console.WriteLine("img null");

}

}

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]