예제 #1
0
        public HighRiskData(string databaseName)
        {
            // Initialize variables
            this.databaseName = databaseName;
            this.database = "ug12db_" + this.databaseName;

            // Access data
            data = new Data(this.databaseName);
        }
예제 #2
0
        public SiteWelfareData(string databaseName)
        {
            // Initialize variables
            this.databaseName = databaseName;
            this.database     = "ug12db_" + this.databaseName;

            // Access data
            data       = new Data(this.databaseName);
            welfareIds = data.GetAllWelfareIds();
        }
예제 #3
0
        public SiteLoop(string databaseName)
        {
            // Initialize variables
            this.databaseName = databaseName;
            this.database = "ug12db_" + this.databaseName;

            // Access data
            this.data = new Data(this.databaseName);
            this.loopIds = data.GetAllSiteLoopsIds();
        }
예제 #4
0
        /// <summary>
        /// Runs through the databases a single time and emails all outstanding tasks
        /// </summary>
        public void MonitorTasks()
        {
            // Get a list of all databases (schemas) to search through
            string[] databases = LocalData.GetAllDatabases();

            // Loop over them
            for (int i = 0; i < databases.Length; ++i)
            {
                // Search for any pending tasks in each database
                data = new Data(databases[i]);

                // Get all pending tasks
                int[] tasks = data.GetPendingScheduledTasks();

                // Loop over all tasks
                foreach (int taskId in tasks)
                {
                    // Process the task
                    this.ProcessTask(data, taskId);
                    System.Threading.Thread.Sleep(1000);
                }
            }
        }
예제 #5
0
        /// <summary>
        /// Send a request to the server
        /// </summary>
        /// <param name="accountId">Integer, account id</param>
        /// <param name="scheduledTaskId">Integer, scheduledtask id</param>
        /// <returns>Returns response from server</returns>
        private string SendRequest(int accountId, int scheduledTaskId)
        {
            string responseFromServer = null;
            WebResponse response = null;
            Stream data;

            // Build URI
            string post = String.Format("account_id={0}&id={1}",
                WebUtility.HtmlEncode(accountId.ToString()),
                WebUtility.HtmlEncode(scheduledTaskId.ToString())
            );

            // Get byte array of url
            Byte[] byteArray = Encoding.UTF8.GetBytes(post);

            // Create request
            WebRequest request = WebRequest.Create(URL + "/?" + post);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            request.Timeout = 300000;

            // Write the byte data into the stream
            try
            {
                data = request.GetRequestStream();
                data.Write(byteArray, 0, byteArray.Length);
                data.Close();
            }
            catch (Exception ex)
            {
                Log.Error("Data stream error: " + ex.Message);
            }

            // Get the response
            try
            {
                response = request.GetResponse();
                data = response.GetResponseStream();
                // Read the data stram
                StreamReader reader = new StreamReader(data);
                responseFromServer = reader.ReadToEnd();

                // CLean up
                reader.Close();
                data.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                Log.Error("Stream error: " + ex.Message);
            }

            return responseFromServer;
        }
예제 #6
0
        /// <summary>
        /// Requests the report to be generated by the task Id. Must be provided a data connection to
        /// access the database methods.
        /// </summary>
        /// <param name="data">Handles database methods</param>
        /// <param name="taskId">Integer - task Id</param>
        private void ProcessTask(Data data, int taskId)
        {
            string exportFile = null;
            try
            {
                int accountId = data.GetAccountIdForDatabase();

                if(accountId==281)
                {

                    if(taskId==1)
                    {

                //accountId = 282;
                //taskId = 1;
                //accountId = 259;
                //taskId = 1;

                // Send request to server to generate report and return file name
                exportFile = this.SendRequest(accountId, taskId);

                exportFile = Regex.Replace(exportFile, @"\s", "");
              //  exportFile = "509542_08072015054608.pdf";

                // Check for null response
                if (exportFile == null)
                {
                    // Get task name
                    string taskName = data.GetScheduledTaskName(taskId);

                    // Log a warning
                    Log.Warning(String.Format(
                        "Scheduled task returned false for account: {0}, task scheduled: {1}, task name:",
                        accountId,
                        taskId,
                        taskName
                    ));

                    // Email the issue to admins
                    this.EmailIssue(taskName);

                    return;
                }

                // Assign response as new file
                file = new FileInfo(exportFile);

                // task[0] = timecycle_id | task[1] = content_id | task[2] = sctNextRun | task[3] = sctDescription | task[4] = sctEmailSubject
                string[] task     = data.GetScheduledTask(taskId);

                // Get email list
                string[] emails   = data.GetScheduledTaskEmailList(taskId);

                // Get report type
                string reportType = data.GetReportNameByContentId(Convert.ToInt32(task[1]));

                // Send the emails
                this.EmailTask(emails, task[3], task[4]);

                // Set next run time
                DateTime d = Convert.ToDateTime(task[2]);
                TimeSpan lastRunTime = new TimeSpan(d.Hour, d.Minute, d.Second);
                DateTime lastRunDateTime = DateTime.Today.Add(lastRunTime);

                // Create last run and next run
                string lastRun = lastRunDateTime.ToString("yyyy-MM-dd HH:mm:ss");
                string nextRun = Utility.AddTimeCycle(lastRun, Convert.ToInt32(task[0]));

                // Update task
                UpdateQuery update = new UpdateQuery();
                update.SetTable("scheduledtask");
                update.SetFields(new string[] { "sctNextRun", "sctLastRun" });
                update.SetId(taskId.ToString());
                update.AddRowValue(nextRun);
                update.AddRowValue(lastRun);

                // Enter into database
                data.UpdateTaskScheduler(update);

                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Task process error:\r\n" + ex.ToString());
            }
        }
예제 #7
0
        public void ProcessRequest(HttpContext ctx)
        {
            string json;
            using (var reader = new System.IO.StreamReader(ctx.Request.InputStream))
            {
                json = reader.ReadToEnd();
                obj.Write_ErrorLog("1:" + json);
                json = System.Web.HttpUtility.UrlDecode(json);
                if (json.Contains("DeviceData="))
                {
                    json = json.Remove(0, 11);
                }
            }
            ctx.Response.ContentType = "text/plain";
            if (!string.IsNullOrEmpty(json))
            {
                try
                {
                    try
                    {
                        // Parse JSON into dynamic object, convenient!
                        System.Collections.Generic.Dictionary<string, object> values = JsonConvert.DeserializeObject<System.Collections.Generic.Dictionary<string, object>>(json);

                        Newtonsoft.Json.Linq.JObject results = Newtonsoft.Json.Linq.JObject.Parse(json);
                        int recard_count = 0;
                        string DateUTC = "";
                        foreach (var result in results["Records"])
                        {
                            string Reason = (string)result["Reason"];
                            //  DateUTC = (string)result["DateUTC"];
                            if (Reason == "17")
                            {
                                Newtonsoft.Json.Linq.JObject results1 = Newtonsoft.Json.Linq.JObject.Parse(Convert.ToString(result));
                                foreach (var result1 in results1["Fields"])
                                {
                                    string cdata = (string)result1["Data"];
                                    if (!string.IsNullOrEmpty(Convert.ToString(cdata)))
                                    {
                                        recard_count = recard_count + 1;
                                    }
                                }
                            }
                        }
                        if (recard_count != 0)
                        {

                            string dev_SerNo = (string)results["SerNo"];

                            G60_Data obj_DB_name = new G60_Data();
                            DataTable dt_database_name = new DataTable();
                            dt_database_name = obj_DB_name.get_database_name(dev_SerNo);
                            if (dt_database_name.Rows.Count > 0)
                            {
                                string databaseName = dt_database_name.Rows[0]["schCode"].ToString();

                                // Add data
                                UniGuardLib.Data data = new UniGuardLib.Data(databaseName);

                                /*********************************************
                                 * INSERT IMPORT DATA
                                 *********************************************/

                                InsertQuery insertImport = new InsertQuery();
                                insertImport.SetTable("import");
                                insertImport.SetFields(new string[4] { "impDate", "impTime", "impRecordCount", "impLiveData" });

                                // Adjust time if necessary
                                string importDateTime = (Convert.ToDateTime(DateTime.Now)).ToString();
                                string newImportDate = data.AdjustTimezone(importDateTime, "yyyy-MM-dd", dev_SerNo);
                                string newImportTime = data.AdjustTimezone(importDateTime, "HH:mm:ss", dev_SerNo);

                                //string newImportDate = (Convert.ToDateTime(importDateTime)).ToString("yyyy-MM-dd");
                                //string newImportTime = (Convert.ToDateTime(importDateTime)).ToString("HH:mm:ss");

                                // Add rows
                                insertImport.AddRowValues(new string[4] { newImportDate, newImportTime, recard_count.ToString(), "1" });

                                // Insert the import and retrieve the import Id
                                Data objdata = new Data(databaseName);
                                int importId = objdata.InsertImport(insertImport);

                                /*********************************************
                                 * INSERT PATROL RECORDS
                                 *********************************************/
                                if (recard_count > 0)
                                {

                                    foreach (var result in results["Records"])
                                    {
                                        if (((string)result["DateUTC"]) != null)
                                        {
                                            DateUTC = (string)result["DateUTC"];
                                        }

                                        // this can be a string or null
                                        string Reason = (string)result["Reason"];
                                        if (Reason == "17")
                                        {
                                            Newtonsoft.Json.Linq.JObject results1 = Newtonsoft.Json.Linq.JObject.Parse(Convert.ToString(result));

                                            foreach (var result1 in results1["Fields"])
                                            {
                                                string cdata = (string)result1["Data"];
                                                if (!string.IsNullOrEmpty(Convert.ToString(cdata)))
                                                {
                                                    var base64 = cdata;
                                                    var base64_data = Convert.FromBase64String(base64);
                                                    string hexValue = ByteArrayToString(base64_data);
                                                    int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
                                                    // Prepare new InserQuery for patrol data
                                                    InsertQuery insertPatrol = new InsertQuery();
                                                    insertPatrol.SetTable("patrol");
                                                    insertPatrol.SetFields(new string[5] { "import_id", "patTSN", "patDate", "patTime", "patRSN" });

                                                    //string date = (Convert.ToDateTime(DateUTC)).ToString("yyyy-MM-dd");
                                                    //string time = (Convert.ToDateTime(DateUTC)).ToString("HH:mm:ss");
                                                    //string date = newImportDate1;
                                                    //string time = newImportTime1;

                                                    string importDateTime1 = (Convert.ToDateTime(DateUTC)).ToString();
                                                    string date = data.AdjustTimezone(importDateTime1, "yyyy-MM-dd", dev_SerNo);
                                                    string time = data.AdjustTimezone(importDateTime1, "HH:mm:ss", dev_SerNo);

                                                    insertPatrol.AddRowValues(new string[5] { importId.ToString(), Convert.ToString(decValue), date, time, Convert.ToString(dev_SerNo) });
                                                    data.InsertPatrol(insertPatrol);

                                                }
                                            }
                                        }
                                    }

                                }
                            }

                        }
                    }
                    catch (Exception ex)
                    {
                        obj.Write_ErrorLog("2:" + ex.ToString());
                        System.Collections.Generic.Dictionary<string, object> values = JsonConvert.DeserializeObject<System.Collections.Generic.Dictionary<string, object>>(json);
                        string logFolder = @"C:\g60";
                        string serialNumber = values["SerNo"].ToString();
                        string fileName = string.Format("{0} - {1}.txt", serialNumber, DateTime.Now.ToString("yyyyMMddHHmmss"));
                        System.IO.File.WriteAllText(System.IO.Path.Combine(logFolder, fileName), json);
                        obj.Write_ErrorLog("3:" + json);
                        ctx.Response.Write("Insert successful");
                    }
                }
                catch (Exception ex)
                {
                    obj.Write_ErrorLog("4:" + ex.ToString());
                    // System.Collections.Generic.Dictionary<string, object> values = JsonConvert.DeserializeObject<System.Collections.Generic.Dictionary<string, object>>(json);
                    string logFolder = @"C:\g60";
                    string serialNumber = "1234";
                    string fileName = string.Format("{0} - {1}.txt", serialNumber, DateTime.Now.ToString("yyyyMMddHHmmss"));
                    System.IO.File.WriteAllText(System.IO.Path.Combine(logFolder, fileName), json);
                    obj.Write_ErrorLog("4:" + json);
                    ctx.Response.Write("Insert successful");
                    ctx.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                    ctx.Response.Write(string.Format("ERROR: {0}", ex.Message));
                }
            }
            else
            {
                ctx.Response.TrySkipIisCustomErrors = true;
                ctx.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                obj.Write_ErrorLog("6:" + "ERROR: No POST Data!");
                ctx.Response.Write(string.Format("ERROR: No POST Data!"));
            }
        }
예제 #8
0
        /// <summary>
        /// Reads the current working file and stores it to the database,
        /// then deletes the (temporary) file.
        /// </summary>
        private bool storeDataFromFile(bool liveData = false)
        {
            // If it's a uif file, move it to temp

            // Get the new file
            FileInfo newFile = new FileInfo(TEMPPATH + file.Name);
            Data data = new Data(this.databaseName);

            string line;
            string recorderSerial = null;
            List<string> lines = new List<string>();
            int totalRecords = Utility.TotalLines(newFile.FullName);
            // Kill if total records = 0
            if (totalRecords == 0) return false;

            // Let's read the first line and get the serial number
            try
            {
                string firstLine = null;
                using (StreamReader reader = new StreamReader(newFile.FullName))
                {
                    firstLine = reader.ReadLine();
                    reader.Close();
                }

                // Let's get the serial number
                string[] sampleData = firstLine.Split(',');
                recorderSerial = sampleData[5];
            }
            catch (Exception ex)
            {
                Log.Error("File read error: " + ex.ToString());
            }

            string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string currentDate = data.AdjustTimezone(dt, "yyyy-MM-dd", recorderSerial);
            string currentTime = data.AdjustTimezone(dt, "HH:mm:ss", recorderSerial);

            // Initialise the InsertQuery method for Imports
            InsertQuery insertImport = new InsertQuery();
            insertImport.SetTable("import");
            insertImport.SetFields(new string[] { "impDate", "impTime", "impRecordCount", "impLiveData" });

            // Add rows
            insertImport.AddRowValues(new string[] {
                currentDate,
                currentTime,
                totalRecords.ToString(),
                liveData ? "1" : "0"
            });

            // Add data
            int importId = data.InsertImport(insertImport);

            // Prepare a new InserQuery for shock data
            InsertQuery insertShock = new InsertQuery();
            insertShock.SetTable("shock");
            insertShock.SetFields(new string[] { "import_id", "shocktype_id", "shkDate", "shkTime", "shkRSN" });

            // Prepare new InserQuery for patrol data
            InsertQuery insertPatrol = new InsertQuery();
            insertPatrol.SetTable("patrol");
            insertPatrol.SetFields(new string[] { "import_id", "patTSN", "patDate", "patTime", "patRSN" });

            // Prepare a new InsertQuery for lowvoltage data
            InsertQuery insertVoltage = new InsertQuery();
            insertVoltage.SetTable("lowvoltage");
            insertVoltage.SetFields(new string[] { "import_id", "lowReading", "lowDate", "lowTime", "lowRSN"});

            // Read the file line by line
            try
            {
                // Initialise StreamReader
                using (StreamReader reader = new StreamReader(newFile.FullName))
                {
                    int patrolCounter = 0;
                    int patrolShock = 0;
                    int patrolVoltage = 0;

                    while ((line = reader.ReadLine()) != null)
                    {
                        // Split by commas
                        string[] patrolData = line.Split(',');
                        DateTime date = new DateTime();

                        try
                        {
                            // Check if data comes in dd-mm-yyyy
                            string text = patrolData[3];
                            string patt = @"(\d){2}-(\d){2}-(\d){4}";
                            Regex regex = new Regex(patt, RegexOptions.IgnoreCase);
                            Match match = regex.Match(text);
                            if (match.ToString() == patrolData[3])
                            {
                                text = text.Replace('-', '/');
                            }

                            // Convert the date from dd/MM/yy to yyyy-MM-dd
                            string[] dateParams = text.Split('/');
                            date = new DateTime(
                                Convert.ToInt32(dateParams[2]),
                                Convert.ToInt32(dateParams[1]),
                                Convert.ToInt32(dateParams[0])
                            );
                        }
                        catch (Exception ex)
                        {
                            Log.Warning("Decrypt Test Failed " + ex.ToString());
                        }

                        // If patrolData[0] is 1, then it is a normal tag read
                        if (patrolData[0] == "1")
                        {
                            // Insert patrol data
                            insertPatrol.AddRowValues(new string[5] {

                                // MUST change this field in the Data() class if also adding to OLD databases,
                                // best to use MySQL's in-built last_insert_id() to get the other ID
                                importId.ToString(),
                                patrolData[2],
                                date.ToString("yyyy-MM-dd"),
                                patrolData[4],
                                patrolData[5]
                            });

                            // Increase patrol counter
                            patrolCounter++;

                            // Make sections of 1000 and store them into db
                            if (patrolCounter > 1000)
                            {
                                // Insert it
                                data.InsertPatrol(insertPatrol);
                                // Clear it
                                insertPatrol.SetRowValues(new List<string[]>());
                                // Reset the counter
                                patrolCounter = 0;
                            }

                        }

                        // If patrolData[o] is 2, then its a shock log
                        if (patrolData[0] == "2")
                        {
                            // Insert patrol data
                            insertShock.AddRowValues(new string[5] {

                                // MUST change this field in the Data() class if also adding to OLD databases,
                                // best to use MySQL's in-built last_insert_id() to get the other ID
                                importId.ToString(),
                                patrolData[2],
                                date.ToString("yyyy-MM-dd"),
                                patrolData[4],
                                patrolData[5]
                            });

                            // Increase patrol counter
                            patrolShock++;

                            // Make sections of 1000 and store them into db
                            if (patrolShock > 1000)
                            {
                                // Insert it
                                data.InsertShock(insertShock);

                                // Clear it
                                insertShock.SetRowValues(new List<string[]>());

                                // Reset the counter
                                patrolShock = 0;
                            }
                        }

                        // If patrolData[0] is 4, then the record is low voltage
                        if (patrolData[0] == "4")
                        {
                            // Get number
                            double battReading = Convert.ToDouble(patrolData[2]) / 1000;

                            // Insert patrol data
                            insertVoltage.AddRowValues(new string[5] {
                                importId.ToString(),
                                battReading.ToString(),
                                date.ToString("yyyy-MM-dd"),
                                patrolData[4],
                                patrolData[5]
                            });

                            // Increase patrol counter
                            patrolVoltage++;

                            // Make sections of 1000 and store them into db
                            if (patrolVoltage > 1000)
                            {
                                // Insert it
                                data.InsertVoltage(insertVoltage);

                                // Clear it
                                insertVoltage.SetRowValues(new List<string[]>());

                                // Reset the counter
                                patrolVoltage = 0;
                            }
                        }

                    }
                    // Close the reader
                    reader.Close();
                }

                // Insert left overs if necessary
                if (insertPatrol.GetAllValues().Count > 0) data.InsertPatrol(insertPatrol);
                if (insertShock.GetAllValues().Count > 0) data.InsertShock(insertShock);
                if (insertVoltage.GetAllValues().Count > 0) data.InsertVoltage(insertVoltage);

                // Initialise the InsertQuery method for UploadActivity
                InsertQuery insertUploadActivity = new InsertQuery();
                insertUploadActivity.SetTable("uploadactivity");
                insertUploadActivity.SetFields(new string[] { "account_id", "uplDate", "uplTime", "uplRecords", "uplLiveData" });
                // Add rows
                insertUploadActivity.AddRowValues(new string[] {
                    data.GetAccountIdForDatabase().ToString(),
                    currentDate,
                    currentTime,
                    totalRecords.ToString(),
                    liveData ? "1" : "0"
                });
                // Insert it
                data.InsertUploadActivity(insertUploadActivity);
            }
            catch (Exception ex)
            {
                Log.Warning("Attempted to decrypt file which does not exist: " + newFile.FullName + "\r\n" + ex.ToString());
                return false;
            }

            // Attempt to delete the file
            try
            {
                newFile.Delete();
            }
            catch (Exception ex)
            {
                Log.Error("Could not delete temporary file: " + newFile.FullName + "\r\n" + ex.ToString());
                return false;
            }

            return true;
        }
예제 #9
0
        /// <summary>
        /// Stores GPRS Data to database
        /// </summary>
        public void StoreData()
        {
            // Count everything
            string[][] nr = normalRecords.ToArray();
            string[][] ar = alarmRecords.ToArray();
            string[][] cr = customRecords.ToArray();
            string[][] lr = lowVoltageRecords.ToArray();
            int nrc = nr.Length;
            int arc = ar.Length;
            int crc = cr.Length;
            int lrc = lr.Length;
            int totalRecords = nrc + arc + crc + lrc;
            bool storedData = false;

            // Add data
            Data data = new Data(this.databaseName);

            /*********************************************
             * INSERT IMPORT DATA
             *********************************************/

            InsertQuery insertImport = new InsertQuery();
            insertImport.SetTable("import");
            insertImport.SetFields(new string[4] { "impDate", "impTime", "impRecordCount", "impLiveData" });

            // Adjust time if necessary
            string importDateTime = this.importDate + " " + this.importTime;
            string newImportDate = data.AdjustTimezone(importDateTime, "yyyy-MM-dd", this.recorderSerial);
            string newImportTime = data.AdjustTimezone(importDateTime, "HH:mm:ss", this.recorderSerial);

            // Add rows
            insertImport.AddRowValues(new string[4] { newImportDate, newImportTime, totalRecords.ToString(), "1" });

            // Insert the import and retrieve the import Id
            int importId = data.InsertImport(insertImport);

            /*********************************************
             * INSERT PATROL RECORDS
             *********************************************/
            if (nrc > 0)
            {
                // Prepare new InserQuery for patrol data
                InsertQuery insertPatrol = new InsertQuery();
                insertPatrol.SetTable("patrol");
                insertPatrol.SetFields(new string[5] { "import_id", "patTSN", "patDate", "patTime", "patRSN" });

                // Queue normal records for insertion
                for (int i = 0; i < nrc; ++i)
                {
                    string date = data.AdjustTimezone(nr[i][1], "yyyy-MM-dd", nr[i][2]);
                    string time = data.AdjustTimezone(nr[i][1], "HH:mm:ss", nr[i][2]);

                    if (data.CheckPatrol(nr[i][0], date, time, nr[i][2]))
                        insertPatrol.AddRowValues(new string[5] { importId.ToString(), nr[i][0], date, time, nr[i][2] });
                }

                // Insert it
                if (insertPatrol.Count > 0)
                {
                    data.InsertPatrol(insertPatrol);
                    storedData = true;
                }

            }

            /*********************************************
             * INSERT EVENT RECORDS
             *********************************************/

            if ((arc + crc) > 0)
            {
                // Prepare new InsertQuery for event data
                InsertQuery insertEvent = new InsertQuery();
                insertEvent.SetTable("event");
                insertEvent.SetFields(new string[5] { "import_id", "eventtype_id", "evnDate", "evnTime", "evnRSN" });

                // Queue alarm records for insertion
                if (arc > 0)
                {
                    for (int i = 0; i < arc; ++i)
                    {
                        string date = data.AdjustTimezone(ar[i][0], "yyyy-MM-dd", ar[i][1]);
                        string time = data.AdjustTimezone(ar[i][0], "HH:mm:ss", ar[i][1]);
                        insertEvent.AddRowValues(new string[5] { importId.ToString(), 1.ToString(), date, time, ar[i][1] });
                    }
                }

                // Queue custom records for insertion
                if (crc > 0)
                {
                    for (int i = 0; i < crc; ++i)
                    {
                        string date = data.AdjustTimezone(cr[i][0], "yyyy-MM-dd", cr[i][1]);
                        string time = data.AdjustTimezone(cr[i][0], "HH:mm:ss", cr[i][1]);
                        insertEvent.AddRowValues(new string[5] { importId.ToString(), 2.ToString(), date, time, cr[i][1] });
                    }
                }

                // Insert it
                if (insertEvent.Count > 0)
                {
                    data.InsertEvent(insertEvent);
                    storedData = true;
                }
            }

            /*********************************************
             * INSERT LOW VOLTAGE RECORDS
             *********************************************/

            if (lrc > 0)
            {
                // Prepare new InsertQuery
                InsertQuery insertVoltage = new InsertQuery();
                insertVoltage.SetTable("lowvoltage");
                insertVoltage.SetFields(new string[5] { "import_id", "lowReading", "lowDate", "lowTime", "lowRSN" });

                // Queue low voltage records for insertion
                for (int i = 0; i < lrc; ++i)
                {
                    string date = data.AdjustTimezone(lr[i][0], "yyyy-MM-dd", lr[i][1]);
                    string time = data.AdjustTimezone(lr[i][0], "HH:mm:ss", lr[i][1]);
                    insertVoltage.AddRowValues(new string[5] { importId.ToString(), lr[i][2], date, time, lr[i][1] });
                }

                // Insert it
                if (insertVoltage.Count > 0)
                {
                    data.InsertLowVoltage(insertVoltage);
                    storedData = true;
                }
            }

            /*********************************************
             * INSERT UPLOAD ACTIVITY
             *********************************************/

            // Only required for new legacy databases
            InsertQuery insertUploadActivity = new InsertQuery();
            insertUploadActivity.SetTable("uploadactivity");
            insertUploadActivity.SetFields(new string[5] { "account_id", "uplDate", "uplTime", "uplRecords", "uplLiveData" });

            // Add rows
            string accountId = data.GetAccountIdForDatabase().ToString();
            insertUploadActivity.AddRowValues(new string[5] { accountId, importDate, importTime, totalRecords.ToString(), "1" });

            // Insert it
            if (storedData)
                data.InsertUploadActivity(insertUploadActivity);
            else
                // Delete the import if not used
                data.DeleteImport(importId);
        }
예제 #10
0
        public void ProcessRequest(HttpContext ctx)
        {
            string json;

            using (var reader = new System.IO.StreamReader(ctx.Request.InputStream))
            {
                json = reader.ReadToEnd();
                obj.Write_ErrorLog("1:" + json);
                json = System.Web.HttpUtility.UrlDecode(json);
                if (json.Contains("DeviceData="))
                {
                    json = json.Remove(0, 11);
                }
            }
            ctx.Response.ContentType = "text/plain";
            if (!string.IsNullOrEmpty(json))
            {
                try
                {
                    try
                    {
                        // Parse JSON into dynamic object, convenient!
                        System.Collections.Generic.Dictionary <string, object> values = JsonConvert.DeserializeObject <System.Collections.Generic.Dictionary <string, object> >(json);

                        Newtonsoft.Json.Linq.JObject results = Newtonsoft.Json.Linq.JObject.Parse(json);
                        int    recard_count = 0;
                        string DateUTC      = "";
                        foreach (var result in results["Records"])
                        {
                            string Reason = (string)result["Reason"];
                            //  DateUTC = (string)result["DateUTC"];
                            if (Reason == "17")
                            {
                                Newtonsoft.Json.Linq.JObject results1 = Newtonsoft.Json.Linq.JObject.Parse(Convert.ToString(result));
                                foreach (var result1 in results1["Fields"])
                                {
                                    string cdata = (string)result1["Data"];
                                    if (!string.IsNullOrEmpty(Convert.ToString(cdata)))
                                    {
                                        recard_count = recard_count + 1;
                                    }
                                }
                            }
                        }
                        if (recard_count != 0)
                        {
                            string dev_SerNo = (string)results["SerNo"];


                            G60_Data  obj_DB_name      = new G60_Data();
                            DataTable dt_database_name = new DataTable();
                            dt_database_name = obj_DB_name.get_database_name(dev_SerNo);
                            if (dt_database_name.Rows.Count > 0)
                            {
                                string databaseName = dt_database_name.Rows[0]["schCode"].ToString();


                                // Add data
                                UniGuardLib.Data data = new UniGuardLib.Data(databaseName);

                                /*********************************************
                                * INSERT IMPORT DATA
                                *********************************************/

                                InsertQuery insertImport = new InsertQuery();
                                insertImport.SetTable("import");
                                insertImport.SetFields(new string[4] {
                                    "impDate", "impTime", "impRecordCount", "impLiveData"
                                });

                                // Adjust time if necessary
                                string importDateTime = (Convert.ToDateTime(DateTime.Now)).ToString();
                                string newImportDate  = data.AdjustTimezone(importDateTime, "yyyy-MM-dd", dev_SerNo);
                                string newImportTime  = data.AdjustTimezone(importDateTime, "HH:mm:ss", dev_SerNo);

                                //string newImportDate = (Convert.ToDateTime(importDateTime)).ToString("yyyy-MM-dd");
                                //string newImportTime = (Convert.ToDateTime(importDateTime)).ToString("HH:mm:ss");

                                // Add rows
                                insertImport.AddRowValues(new string[4] {
                                    newImportDate, newImportTime, recard_count.ToString(), "1"
                                });

                                // Insert the import and retrieve the import Id
                                Data objdata  = new Data(databaseName);
                                int  importId = objdata.InsertImport(insertImport);

                                /*********************************************
                                * INSERT PATROL RECORDS
                                *********************************************/
                                if (recard_count > 0)
                                {
                                    foreach (var result in results["Records"])
                                    {
                                        if (((string)result["DateUTC"]) != null)
                                        {
                                            DateUTC = (string)result["DateUTC"];
                                        }

                                        // this can be a string or null
                                        string Reason = (string)result["Reason"];
                                        if (Reason == "17")
                                        {
                                            Newtonsoft.Json.Linq.JObject results1 = Newtonsoft.Json.Linq.JObject.Parse(Convert.ToString(result));



                                            foreach (var result1 in results1["Fields"])
                                            {
                                                string cdata = (string)result1["Data"];
                                                if (!string.IsNullOrEmpty(Convert.ToString(cdata)))
                                                {
                                                    var    base64      = cdata;
                                                    var    base64_data = Convert.FromBase64String(base64);
                                                    string hexValue    = ByteArrayToString(base64_data);
                                                    int    decValue    = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
                                                    // Prepare new InserQuery for patrol data
                                                    InsertQuery insertPatrol = new InsertQuery();
                                                    insertPatrol.SetTable("patrol");
                                                    insertPatrol.SetFields(new string[5] {
                                                        "import_id", "patTSN", "patDate", "patTime", "patRSN"
                                                    });

                                                    //string date = (Convert.ToDateTime(DateUTC)).ToString("yyyy-MM-dd");
                                                    //string time = (Convert.ToDateTime(DateUTC)).ToString("HH:mm:ss");
                                                    //string date = newImportDate1;
                                                    //string time = newImportTime1;

                                                    string importDateTime1 = (Convert.ToDateTime(DateUTC)).ToString();
                                                    string date            = data.AdjustTimezone(importDateTime1, "yyyy-MM-dd", dev_SerNo);
                                                    string time            = data.AdjustTimezone(importDateTime1, "HH:mm:ss", dev_SerNo);

                                                    insertPatrol.AddRowValues(new string[5] {
                                                        importId.ToString(), Convert.ToString(decValue), date, time, Convert.ToString(dev_SerNo)
                                                    });
                                                    data.InsertPatrol(insertPatrol);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        obj.Write_ErrorLog("2:" + ex.ToString());
                        System.Collections.Generic.Dictionary <string, object> values = JsonConvert.DeserializeObject <System.Collections.Generic.Dictionary <string, object> >(json);
                        string logFolder    = @"C:\g60";
                        string serialNumber = values["SerNo"].ToString();
                        string fileName     = string.Format("{0} - {1}.txt", serialNumber, DateTime.Now.ToString("yyyyMMddHHmmss"));
                        System.IO.File.WriteAllText(System.IO.Path.Combine(logFolder, fileName), json);
                        obj.Write_ErrorLog("3:" + json);
                        ctx.Response.Write("Insert successful");
                    }
                }
                catch (Exception ex)
                {
                    obj.Write_ErrorLog("4:" + ex.ToString());
                    // System.Collections.Generic.Dictionary<string, object> values = JsonConvert.DeserializeObject<System.Collections.Generic.Dictionary<string, object>>(json);
                    string logFolder    = @"C:\g60";
                    string serialNumber = "1234";
                    string fileName     = string.Format("{0} - {1}.txt", serialNumber, DateTime.Now.ToString("yyyyMMddHHmmss"));
                    System.IO.File.WriteAllText(System.IO.Path.Combine(logFolder, fileName), json);
                    obj.Write_ErrorLog("4:" + json);
                    ctx.Response.Write("Insert successful");
                    ctx.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                    ctx.Response.Write(string.Format("ERROR: {0}", ex.Message));
                }
            }
            else
            {
                ctx.Response.TrySkipIisCustomErrors = true;
                ctx.Response.StatusCode             = (int)System.Net.HttpStatusCode.InternalServerError;
                obj.Write_ErrorLog("6:" + "ERROR: No POST Data!");
                ctx.Response.Write(string.Format("ERROR: No POST Data!"));
            }
        }