SafeNet/Landmarks_Import/MainClass.cs
2021-02-24 13:50:23 +02:00

220 lines
7.5 KiB
C#

using SafeNetLib;
using System;
using System.Collections;
using System.IO;
using System.Threading;
using System.Xml;
namespace Landmarks_Import
{
internal class MainClass
{
public static Config cfg;
public static Boolean doneReadFromFile = false;
private volatile Queue LandmarksList = new Queue();
private volatile landmark tmpLand = null;
private DBhandle DB;
private string MyConString;
public MainClass()
{
}
public void Start()
{
LoadConfig();
if (!CheckFiles())
{
Console.ReadKey();
Thread.Sleep(2000);
return;
}
MyConString = "SERVER=" + cfg.SERVER + "; " +
"DATABASE=" + cfg.DATABASE + "; " +
"UID=" + cfg.UID + "; " +
"PASSWORD=" + cfg.PASSWORD + "; Pooling=false;";
DB = new DBhandle(MyConString, null);
DB.land_dupl = cfg.duplicatesFileName;
DB.StartDB();
StartThreads();
Console.ReadKey();
}
private void StartThreads()
{
ThreadPool.QueueUserWorkItem(state => ReadFromFile());
ThreadPool.QueueUserWorkItem(state => ProcessCoordinates());
}
#region Config and Working with Files
private bool LoadConfig()
{
bool ret = false;
cfg = new Config();
ret = true;
return ret;
}
private bool CheckFiles()
{
if (!File.Exists(cfg.fileName))
{
Utils.ConsWrite(DebugMSG_Type.always, "Source file missing!");
return false;
}
if (File.Exists(cfg.fileName) && Path.GetExtension(cfg.fileName) != ".csv")
{
Utils.ConsWrite(DebugMSG_Type.always, "Invalid file type! Only .csv accepted!");
return false;
}
if (!File.Exists(cfg.errorFileName))
{
File.Create(cfg.errorFileName);
}
return true;
}
private void ReadFromFile()
{
try
{
string line;
FileStream aFile = new FileStream(cfg.fileName, FileMode.Open);
StreamReader sr = new StreamReader(aFile);
//header
sr.ReadLine();
// read data in line by line
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
//line = sr.ReadLine();
string[] csv = line.Split(',');
landmark lnd = new landmark();
lnd.name = string.Format("{0}-{1}-{2}", csv[2], csv[0], csv[1]);
lnd.address = string.Format("{0} {1} {2} {3} {4}", csv[3], csv[4], csv[5], csv[6], csv[7]);
lnd.icon = cfg.iconName;
lnd.radius = cfg.radius;
lnd.userID = cfg.userID;
getCoordinates(lnd.address, out lnd.lat, out lnd.lng, out lnd.innerException);
if (lnd.lat != -181 && lnd.lng != -181)
{
LandmarksList.Enqueue(lnd);
}
else
{
WriteErrorsToFile(lnd.address, lnd.innerException);
}
Thread.Sleep(cfg.timeRequest);
}
sr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void WriteErrorsToFile(string invalidAddress, string exception)
{
try
{
using (System.IO.StreamWriter file = File.AppendText(cfg.errorFileName))
{
file.WriteLine(DateTime.Now.ToString() + "," + invalidAddress + "," + exception);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
#endregion Config and Working with Files
#region Coordinates
private volatile XmlDocument doc = null;
private volatile XmlNode element = null;
private void getCoordinates(String address, out decimal LAT, out decimal LNG, out string innerEx)
{
doc = new XmlDocument();
LNG = -181; LAT = -181; innerEx = "";
try
{
// Note: Generally, you should store your private key someplace safe
// and read them into your code
const string keyString = "SWWf2O7SWZMGAMqsJj8Am1x3zdE=";
// The URL shown in these examples is a static URL which should already
// be URL-encoded. In practice, you will likely have code
// which assembles your URL from user or web service input
// and plugs those values into its parameters.
string urlString = "https://maps.googleapis.com/maps/api/geocode/xml?address=" + address + "&client=gme-safemobile";
string url = GoogleSignedUrl.Sign(urlString, keyString);
doc.Load(url);
#region oldcode
//direct link without credentials
//doc.Load("http://maps.googleapis.com/maps/api/geocode/xml?address=" + address + "&sensor=false");
#endregion oldcode
element = doc.SelectSingleNode("//GeocodeResponse/status");
if (element.InnerText == "OK")
{
element = doc.SelectSingleNode("//GeocodeResponse/result/geometry/location/lat");
LAT = Convert.ToDecimal(element.InnerText);
element = doc.SelectSingleNode("//GeocodeResponse/result/geometry/location/lng");
LNG = Convert.ToDecimal(element.InnerText);
}
else
{
Utils.ConsWrite(DebugMSG_Type.always, "Failed to retrieve coordinates for address:" + address + " response:" + element.InnerText);
innerEx = element.InnerText;
}
}
catch (Exception ex)
{
Utils.ConsWrite(DebugMSG_Type.always, "Error on coordinates calc:" + ex.ToString());
//WriteErrorsToFile(address);
}
//Utils.ConsWrite(DebugMSG_Type.always, string.Format("Prin google: lat={0}, lng={1}", LAT, LNG));
}
private void ProcessCoordinates()
{
int Counter = 0;
int ExitCounter = 0;
while (true)
{
while (LandmarksList.Count > 0)
{
ExitCounter = 0;
tmpLand = (landmark)LandmarksList.Dequeue();
Counter++;
Utils.WriteLine("Counter value:" + Counter,ConsoleColor.Green);
DB.Insert_Landmark(tmpLand);
}
if(LandmarksList.Count == 0)
{
ExitCounter++;
Console.WriteLine("Nothing to process!");
Thread.Sleep(1000);
if(ExitCounter==10)
{
Console.WriteLine("Job done!");
return;
}
}
}
}
#endregion Coordinates
}
}