示例#1
0
        public void SentStudentsNotifyMessage(IEnumerable <StudentCheckTime> models, SentType sentType)
        {
            try
            {
                foreach (var item in models)
                {
                    var sentCount = 1;
                    if (MySqlDataConnection.SentSuccess(item.EmpId, sentType))
                    {
                        continue;
                    }

                    var responseMsg = SentOnceNotifyMessage(item, sentType);
                    while (responseMsg.success != "1")
                    {
                        sentCount += 1;
                        if (sentCount > 10)
                        {
                            break;
                        }
                        Thread.Sleep(TimeSpan.FromSeconds(double.Parse(GlobalConfig.AppSettings("ThreadSleepSentMessageSec"))));
                        responseMsg = SentOnceNotifyMessage(item, sentType);
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(double.Parse(GlobalConfig.AppSettings("ThreadSleepSentMessageSec"))));
                }
            }
            catch (Exception ex)
            {
                SaveExceptionLog(ex);
            }
        }
示例#2
0
        public bool SentSuccess(string empId, SentType sentType)
        {
            bool result = false;

            try
            {
                using (var connection = new MySqlConnection(connString))
                {
                    var item  = connection.Query <StudentSentMessage>(MySqlDbQuery.SentSuccess(), new { emp_id = empId }).ToList();
                    var model = new StudentSentMessage();

                    if (sentType == SentType.Entry)
                    {
                        var entryStartTime = GlobalConfig.AppSettings("entryStartTime").Split(':');
                        var entryEndTime   = GlobalConfig.AppSettings("entryEndTime").Split(':');

                        var timeStart = new TimeSpan(int.Parse(entryStartTime[0]), int.Parse(entryStartTime[1]), int.Parse(entryStartTime[2]));
                        var timeEnd   = new TimeSpan(int.Parse(entryEndTime[0]), int.Parse(entryEndTime[1]), int.Parse(entryEndTime[2]));

                        model = item.GetStudentSentMessage(timeStart, timeEnd).FirstOrDefault();
                    }
                    else if (sentType == SentType.Exit)
                    {
                        var exitStartTime = GlobalConfig.AppSettings("exitStartTime").Split(':');
                        var exitEndTime   = GlobalConfig.AppSettings("exitEndTime").Split(':');

                        var timeStart = new TimeSpan(int.Parse(exitStartTime[0]), int.Parse(exitStartTime[1]), int.Parse(exitStartTime[2]));
                        var timeEnd   = new TimeSpan(int.Parse(exitEndTime[0]), int.Parse(exitEndTime[1]), int.Parse(exitEndTime[2]));

                        model = item.GetStudentSentMessage(timeStart, timeEnd).FirstOrDefault();
                    }
                    if (model != null)
                    {
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                SaveExceptionLog(ex);
                result = false;
            }

            return(result);
        }
示例#3
0
        /// <summary>
        /// Вызывается при построении шаблона.
        /// </summary>
        protected override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            VisualStateManager.GoToState(this, SentType.ToString(), true);
        }
示例#4
0
        public Text TextParse()
        {
            String   word     = null;
            String   sentense = null;
            SentType type     = SentType.Interrogative;

            if (File.Exists(Path))
            {
                using (StreamReader file = new StreamReader(Path))
                {
                    text = new Text();
                    sent = new Sentence();
                    while (!file.EndOfStream)
                    {
                        char ch = (char)file.Read();
                        // if ((int)ch == 13 || (int)ch == 10) ch = ' ';//для того, чтобы не выводило непонятные символы
                        if (punctuationMarks.Contains(ch) || endMarks.Contains(ch))
                        {
                            nextWord  = new Word(word, ch);
                            sentense += word + ch;
                            word      = null;
                            if (endMarks.Contains(ch))
                            {
                                for (int i = 0; i < punctuationMarks.Length; i++)
                                {
                                    if (ch == '.')
                                    {
                                        type = SentType.Declarative;
                                        break;
                                    }
                                    else if (ch == '!')
                                    {
                                        type = SentType.Exclamatory;
                                        break;
                                    }
                                    else
                                    {
                                        type = SentType.Interrogative;
                                        break;
                                    }
                                }
                                sent.Add(nextWord);
                                sent.Sentences(sentense, type);
                                text.Add(sent);
                                sent     = new Sentence();
                                sentense = null;
                            }
                            else
                            {
                                sent.Add(nextWord);
                            }
                            for (int i = 0; i < punctuationMarks.Length; i++)
                            {
                                if (file.Peek() == (int)punctuationMarks[i])
                                {
                                    ch = (char)file.Read();
                                }
                            }
                        }
                        else
                        {
                            word += ch;
                        }
                    }
                }
            }
            return(text);
        }
示例#5
0
        public void StudentSentMessage(IEnumerable <StudentCheckTime> models, SentType sentType)
        {
            try
            {
                var url = GlobalConfig.AppSettings("sentMessageService")
                          .Replace("{schoolCode}", GlobalConfig.AppSettings("schoolCode"))
                          .Replace("{roleCode}", GlobalConfig.AppSettings("roleCode"));

                var studentSentMessageDb = new List <StudentSentMessage>();

                if (sentType == SentType.Entry)
                {
                    studentSentMessageDb = studentService.GetStudentSentMessageEntry(Helper.GetDate("current")).ToList();
                }
                else if (sentType == SentType.Exit)
                {
                    studentSentMessageDb = studentService.GetStudentSentMessageExit(Helper.GetDate("current")).ToList();
                }

                var studentForSentMessage = models.Where(s => !studentSentMessageDb.Any(s2 => s.EmpId == s2.EmpId));

                foreach (var item in studentForSentMessage)
                {
                    var results = new List <StudentSentMessage>();
                    var client  = new RestClient(url);
                    var request = new RestRequest(Method.POST);
                    request.AddBody("content-type", "application/form-data");

                    request.AddParameter("students", "999902");
                    request.AddParameter("message", $"ID: {item.EmpId} Name: {item.EmpName} {sentType.ToString()}: {item.ChkTime}");
                    request.AddParameter("rooms", "");
                    request.AddParameter("username", "0411");

                    // delay x sec
                    Thread.Sleep(TimeSpan.FromSeconds(int.Parse(GlobalConfig.AppSettings("ThreadSleepSentMessageSec"))));

                    client.ExecuteAsync(request, response =>
                    {
                        var data = response.Content;

                        StudentSentMessage model = new StudentSentMessage();
                        var json = response.Content;

                        ResponseMessage res = JsonConvert.DeserializeObject <ResponseMessage>(json);

                        if (res != null)
                        {
                            if (res.success == "1")
                            {
                                model = new StudentSentMessage()
                                {
                                    EmpId    = item.EmpId,
                                    Status   = $"{SentStatus.Success}",
                                    SentType = sentType.ToString(),
                                    SentTime = DateTime.Parse(Helper.GetDateNowStringUs("yyyy-MM-dd HH:mm:ss"))
                                };
                                results.Add(model);
                            }

                            //await mySqlDataConnection.SaveStudentSentMessage(results);
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                studentService.SaveExceptionLog(ex);
            }
        }
示例#6
0
        public ResponseMessage SentOnceNotifyMessage(StudentCheckTime model, SentType sentType)
        {
            var result = new ResponseMessage();

            if (MySqlDataConnection.SentSuccess(model.EmpId, sentType))
            {
                result = new ResponseMessage()
                {
                    success = "1"
                };
                return(result);
            }

            var studentsAddPara = GlobalConfig.AppSettings("students");

            //var roomsAddPara = GlobalConfig.AppSettings("rooms");
            //var messageAddPara = GlobalConfig.AppSettings("message");
            //var usernameAddPara = GlobalConfig.AppSettings("username");
            //var appName = GlobalConfig.AppSettings("appName");

            #region for test
            var students = studentsAddPara.Split('|');
            if (GlobalConfig.Index > students.Length - 1)
            {
                GlobalConfig.Index = 0;
            }
            var sentStd = students[GlobalConfig.Index];
            GlobalConfig.Index += 1;
            #endregion

            var studentsReq = studentsAddPara == "" ? model.EmpId : sentStd;

            var url = GlobalConfig.AppSettings("sentMessageService")
                      .Replace("{schoolCode}", GlobalConfig.AppSettings("schoolCode"))
                      .Replace("{studentCode}", studentsReq);

            var client  = new RestClient(url);
            var request = new RestRequest(Method.POST);
            request.AddBody("content-type", "application/form-data");

            #region message
            //entry
            //ทดสอบ
            //รหัสนักเรียน
            //ชื่อ
            //เวลาเข้าเรียน

            //exit
            //ทดสอบ
            //รหัสนักเรียน
            //ชื่อ
            //เวลาเลิกเรียน
            #endregion

            request.AddParameter("students", studentsReq);
            if (sentType == SentType.Entry)
            {
                request.AddParameter("message",
                                     $"ส่งจากระบบ" + System.Environment.NewLine +
                                     $"รหัสนักเรียน: {model.EmpId}" + System.Environment.NewLine +
                                     $"ชื่อ: {model.EmpName}" + System.Environment.NewLine +
                                     $"เวลาเข้าเรียน: {model.ChkTime}");
            }
            else if (sentType == SentType.Exit)
            {
                request.AddParameter("message",
                                     $"ส่งจากระบบ" + System.Environment.NewLine +
                                     $"รหัสนักเรียน: {model.EmpId}" + System.Environment.NewLine +
                                     $"ชื่อ: {model.EmpName}" + System.Environment.NewLine +
                                     $"เวลาเลิกเรียน: {model.ChkTime}");
            }

            //request.AddParameter("rooms", roomsAddPara);
            //request.AddParameter("username", usernameAddPara);

            StudentSentMessage sentMessage = new StudentSentMessage();

            var json = client.Execute <ResponseMessage>(request).Content;
            result = JsonConvert.DeserializeObject <ResponseMessage>(json);

            //if (res != null)
            //{
            if (result.success == "1")
            {
                GlobalConfig.StudentCount += 1;
                sentMessage = new StudentSentMessage()
                {
                    EmpId    = model.EmpId,
                    Status   = $"{SentStatus.Success}",
                    SentType = sentType.ToString(),
                    SentTime = DateTime.Parse(Helper.GetDateNowStringUs("yyyy-MM-dd HH:mm:ss")),
                    ChkTime  = model.ChkTime
                };

                MySqlDataConnection.SaveStudentSentMessage(sentMessage);
            }
            else
            {
                sentMessage = new StudentSentMessage()
                {
                    EmpId    = model.EmpId,
                    Status   = $"{SentStatus.Error} : {result.error}",
                    SentType = sentType.ToString(),
                    SentTime = DateTime.Parse(Helper.GetDateNowStringUs("yyyy-MM-dd HH:mm:ss")),
                    ChkTime  = model.ChkTime
                };
                MySqlDataConnection.SaveStudentSentMessage(sentMessage);
            }
            //}

            #region sent Async

            //client.ExecuteAsync(request, response =>
            //{
            //    StudentSentMessage sentMessage = new StudentSentMessage();
            //    var json = response.Content;

            //    ResponseMessage resAsync = JsonConvert.DeserializeObject<ResponseMessage>(json);

            //    result = resAsync;

            //    if (resAsync != null)
            //    {
            //        if (resAsync.success == "1")
            //        {
            //            sentMessage = new StudentSentMessage()
            //            {
            //                EmpId = model.EmpId,
            //                Status = $"{SentStatus.Success}",
            //                SentType = sentType.ToString(),
            //                SentTime = DateTime.Parse(Helper.GetDateNowStringUs("yyyy-MM-dd HH:mm:ss")),
            //                ChkTime = model.ChkTime
            //            };

            //            MySqlDataConnection.SaveStudentSentMessage(sentMessage);
            //        }
            //        else
            //        {
            //            sentMessage = new StudentSentMessage()
            //            {
            //                EmpId = model.EmpId,
            //                Status = $"{SentStatus.Error} : {resAsync.error}",
            //                SentType = sentType.ToString(),
            //                SentTime = DateTime.Parse(Helper.GetDateNowStringUs("yyyy-MM-dd HH:mm:ss")),
            //                ChkTime = model.ChkTime
            //            };
            //            MySqlDataConnection.SaveStudentSentMessage(sentMessage);
            //        }
            //    }
            //});
            #endregion

            return(result);
        }
示例#7
0
 public bool SentMessageSuccess(IEnumerable <StudentCheckTime> models, SentType sentType)
 {
     throw new NotImplementedException();
 }
示例#8
0
        public void SentStudentNotifyMessage(IEnumerable <StudentCheckTime> models, SentType sentType)
        {
            try
            {
                var url = GlobalConfig.AppSettings("sentMessageService")
                          .Replace("{schoolCode}", GlobalConfig.AppSettings("schoolCode"))
                          .Replace("{roleCode}", GlobalConfig.AppSettings("roleCode"));


                var studentForSentMessage = new List <StudentCheckTime>();

                if (models.ToList().Count > 0)
                {
                    studentForSentMessage = models.ToList();
                }
                else
                {
                    if (sentType == SentType.Entry)
                    {
                        // get students checktime from databas
                        GlobalConfig.StudentCheckTimes = GetStudentsEntryMySql(GlobalConfig.Date);

                        // get students sent message from database
                        GlobalConfig.StudentSentMessages = GetStudentsSentMessagesEntryFromMySql(GlobalConfig.CurrentDate);

                        var diff = GlobalConfig.StudentCheckTimes.ToList().Count - GlobalConfig.StudentSentMessages.ToList().Count;

                        if (diff != 0)
                        {
                            // get students sent message error
                            var StudentSentMessagesError = GlobalConfig.StudentCheckTimes.Where(s => !GlobalConfig.StudentSentMessages.Any(s2 => s.EmpId == s2.EmpId));

                            if (StudentSentMessagesError.ToList().Count == 0)
                            {
                                return;
                            }

                            SentStudentNotifyMessage(StudentSentMessagesError.Take(30), sentType);
                        }
                    }
                    else if (sentType == SentType.Exit)
                    {
                        // get students checktime from databas
                        GlobalConfig.StudentCheckTimes = GetStudentsExitMySql(GlobalConfig.Date);

                        // get students sent message from database
                        GlobalConfig.StudentSentMessages = GetStudentsSentMessagesExitFromMySql(GlobalConfig.CurrentDate);

                        var diff = GlobalConfig.StudentCheckTimes.ToList().Count - GlobalConfig.StudentSentMessages.ToList().Count;

                        if (diff != 0)
                        {
                            // get students sent message error
                            var StudentSentMessagesError = GlobalConfig.StudentCheckTimes.Where(s => !GlobalConfig.StudentSentMessages.Any(s2 => s.EmpId == s2.EmpId));

                            if (StudentSentMessagesError.ToList().Count == 0)
                            {
                                return;
                            }

                            SentStudentNotifyMessage(StudentSentMessagesError.Take(30), sentType);
                        }
                    }

                    return;
                }

                foreach (var item in studentForSentMessage)
                {
                    var results = new List <StudentSentMessage>();
                    var client  = new RestClient(url);
                    var request = new RestRequest(Method.POST);
                    request.AddBody("content-type", "application/form-data");

                    request.AddParameter("students", "999902");
                    request.AddParameter("message", $"ID: {item.EmpId} Name: {item.EmpName} {sentType.ToString()}: {item.ChkTime}");
                    request.AddParameter("rooms", "");
                    request.AddParameter("username", "0411");

                    // delay x sec
                    //Thread.Sleep(TimeSpan.FromSeconds(int.Parse(GlobalConfig.AppSettings("ThreadSleepSentMessageSec"))));
                    Thread.Sleep(100);

                    client.ExecuteAsync(request, response =>
                    {
                        var data = response.Content;

                        StudentSentMessage model = new StudentSentMessage();
                        var json = response.Content;

                        ResponseMessage res = JsonConvert.DeserializeObject <ResponseMessage>(json);

                        if (res != null)
                        {
                            if (res.success == "1")
                            {
                                model = new StudentSentMessage()
                                {
                                    EmpId    = item.EmpId,
                                    Status   = $"{SentStatus.Success}",
                                    SentType = sentType.ToString(),
                                    SentTime = DateTime.Parse(Helper.GetDateNowStringUs("yyyy-MM-dd HH:mm:ss"))
                                };
                                results.Add(model);
                                //GlobalConfig.StudentSentMessages.Add(model);


                                MySqlDataConnection.SaveStudentSentMessage(results);
                            }
                            else
                            {
                                model = new StudentSentMessage()
                                {
                                    EmpId    = item.EmpId,
                                    Status   = $"{SentStatus.Error} : {res.error}",
                                    SentType = sentType.ToString(),
                                    SentTime = DateTime.Parse(Helper.GetDateNowStringUs("yyyy-MM-dd HH:mm:ss"))
                                };
                                //GlobalConfig.StudentSentMessages.Add(model);
                            }
                        }
                        else
                        {
                            model = new StudentSentMessage()
                            {
                                EmpId    = item.EmpId,
                                Status   = $"{SentStatus.Error}",
                                SentType = sentType.ToString(),
                                SentTime = DateTime.Parse(Helper.GetDateNowStringUs("yyyy-MM-dd HH:mm:ss"))
                            };
                            //GlobalConfig.StudentSentMessages.Add(model);
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                SaveExceptionLog(ex);
            }
        }
示例#9
0
 public void Sentences(String sentence, SentType type)
 {
     this.sentence = sentence;
     this.type     = type;
 }
示例#10
0
        public async Task <List <JSON_FileMetadata> > UploadLocal(object FileToUP, SentType TheUpType, string Filename, bool AutoRename = true, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            var parameters = new AuthDictionary
            {
                { "folderid", FolderID.ToString() },
                { "filename", Filename },
                { "nopartial", "1" },
                { "renameifexists", AutoRename ? "1" : null }
            };

            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                System.Net.Http.Handlers.ProgressMessageHandler progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpSendProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Uploading..."
                    }); };
                using (HttpClient localHttpClient = new HtpClient(progressHandler))
                {
                    HttpRequestMessage HtpReqMessage = new HttpRequestMessage(HttpMethod.Post, new pUri("/uploadfile", parameters.RemoveEmptyValues()));
                    // '''''''''''''''''''''''''''''''''
                    HttpContent streamContent = null;
                    switch (TheUpType)
                    {
                    case SentType.filepath:
                        streamContent = new StreamContent(new System.IO.FileStream(FileToUP.ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read));
                        break;

                    case SentType.memorystream:
                        streamContent = new StreamContent((System.IO.Stream)FileToUP);
                        break;

                    case SentType.bytesArray:
                        streamContent = new StreamContent(new System.IO.MemoryStream((byte[])FileToUP));
                        break;
                    }
                    streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    HtpReqMessage.Content             = streamContent;
                    // ''''''''''''''''will write the whole content to H.D WHEN download completed'''''''''''''''''''''''''''''
                    using (HttpResponseMessage ResPonse = await localHttpClient.SendAsync(HtpReqMessage, HttpCompletionOption.ResponseContentRead, token).ConfigureAwait(false))
                    {
                        string result = await ResPonse.Content.ReadAsStringAsync();

                        token.ThrowIfCancellationRequested();
                        if (ResPonse.StatusCode == HttpStatusCode.OK && JObject.Parse(result).Value <int>("result").Equals(0))
                        {
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = "Upload completed successfully"
                            });
                            return(JsonConvert.DeserializeObject <List <JSON_FileMetadata> >(JObject.Parse(result).SelectToken("metadata").ToString(), JSONhandler));
                        }
                        else
                        {
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = $"The request returned with HTTP status code {ResPonse.ReasonPhrase}"
                            });
                            ShowError(result);
                            return(null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new pCloudException(ex.Message, 1001);
                }
                return(null);
            }
        }