public virtual Message InsertOrUpdateWithoutIdentity(T entity) { Message message; try { _dbContext.SqlConnection.Open(); var isExist = _iBaseRepository.Get(entity); var affectedRow = 0; if (isExist == null) { affectedRow = _iBaseRepository.InsertWithoutIdentity(entity); message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been saved successfully.") : SetMessage.SetInformationMessage("No data has been saved."); } else { affectedRow = _iBaseRepository.Update(entity); message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been updated successfully.") : SetMessage.SetInformationMessage("No data has been updated."); } } catch (Exception exception) { return(SetMessage.SetErrorMessage(exception.Message)); } finally { _dbContext.SqlConnection.Close(); } return(message); }
public bool OnReceiveMessage(CiMessageEntity messageEntity) { bool returnValue = false; returnValue = true; if (this.InvokeRequired) { SetMessage SetMessage = new SetMessage(OnReceiveMessage); this.Invoke(SetMessage, new object[] { messageEntity }); } else { messageEntity.MSGContent = ReplaceMessage(messageEntity.MSGContent); StringBuilder sbContent = new StringBuilder(); sbContent.Append("<div style='color:#00f;font-size:12px;'>" + messageEntity.CreateBy + " ["); if (isToday((DateTime)messageEntity.CreateOn)) { sbContent.Append(((DateTime)messageEntity.CreateOn).ToLongTimeString() + "]:</div>"); } else { sbContent.Append(((DateTime)messageEntity.CreateOn).ToString(SystemInfo.DateTimeFormat) + "]:</div>"); } sbContent.Append(messageEntity.MSGContent); OneShow.Append(sbContent.ToString()); this.webMsg.DocumentText = this.webMsg.DocumentText.Insert(this.webMsg.DocumentText.Length, GetHtmlFace(sbContent.ToString())); this.PlaySound(); FlashWindow(this.Handle, true); } return(returnValue); }
public virtual Message Delete(T entity) { Message message; try { _dbContext.SqlConnection.Open(); var affectedRow = 0; affectedRow = _iBaseRepository.Delete(entity); message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been deleted successfully.") : SetMessage.SetInformationMessage("No data has been deleted."); } catch (Exception exception) { message = exception.Message.Substring(0, 50) == "The DELETE statement conflicted with the REFERENCE" ? SetMessage.SetInformationMessage("You can't delete this information because it is already used by other.") : SetMessage.SetErrorMessage(exception.Message); } finally { _dbContext.SqlConnection.Close(); } return(message); }
// Установка ника при подключении, в конце ожидается ответ от сервера об успешном подключении public static void SetUsername() { if (_tcpClient != null) { var stream = _tcpClient.GetStream(); var buffer = new byte[2048]; string data = null; int i; while ((i = stream.Read(buffer, 0, buffer.Length)) != 0) { data = Encoding.Unicode.GetString(buffer, 0, i); if (IsOkMessage(data)) { SendOkMessage(); break; } SetMessage?.Invoke(data, true); } if (NeedDisconnect(i)) { Disconnect?.Invoke(); } } }
public Message ChangeTestStatus(int testId, bool status) { Message message = null; var affectedRow = 0; try { using (TransactionScope scope = new TransactionScope()) { _dbContext.SqlConnection.Open(); if (testId > 0) { var test = _iTestRepository.GetById(testId); test.IsPublished = status; affectedRow = _iTestRepository.Update(test); message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been updated successfully.") : SetMessage.SetInformationMessage("No data has been updated."); } scope.Complete(); } } catch (Exception exception) { throw new Exception(exception.Message); } finally { _dbContext.SqlConnection.Close(); } return(message); }
public bool OnReceiveMessage(BaseMessageEntity messageEntity) { bool returnValue = false; // 判断消息,是否发送给本窗体的 //if (this.ReceiverId.Equals(Message.ReceiverId)) //{ returnValue = true; if (this.InvokeRequired) { SetMessage SetMessage = new SetMessage(OnReceiveMessage); this.Invoke(SetMessage, new object[] { messageEntity }); } else { //this.txtMessage.AppendText(messageEntity.CreateBy + " " + ((DateTime)messageEntity.CreateOn).ToString(BaseSystemInfo.DateTimeFormat) + " 说: " + "\r\n"); //this.txtMessage.AppendText(messageEntity.Content + "\r\n"); //this.txtMessage.AppendText("- - - - - - - - - - - - - - -" + "\r\n"); //this.txtMessage.ScrollToCaret(); //StringBuilder sbContent = new StringBuilder(); //sbContent.Append("<div style='color:#00f;font-size:12px;'>" + messageEntity.CreateBy + " ["); //if (isToday((DateTime)messageEntity.CreateOn)) //{ // sbContent.Append(((DateTime)messageEntity.CreateOn).ToLongTimeString() + "]:</div>"); //} //else //{ // sbContent.Append(((DateTime)messageEntity.CreateOn).ToString(BaseSystemInfo.DateTimeFormat) + "]:</div>"); //} //// Web里的单点登录识别码进行转换 //messageEntity.Contents = messageEntity.Contents.Replace("{OpenId}", this.UserInfo.OpenId); //sbContent.Append(messageEntity.Contents); //strOneShow.Append(sbContent.ToString()); //this.webBMsg.DocumentText = this.webBMsg.DocumentText.Insert(this.webBMsg.DocumentText.Length, sbContent.ToString()); messageEntity.Contents = ReplaceMessage(messageEntity.Contents); StringBuilder sbContent = new StringBuilder(); sbContent.Append("<div style='color:#00f;font-size:12px;'>" + messageEntity.CreateBy + " ["); if (isToday((DateTime)messageEntity.CreateOn)) { sbContent.Append(((DateTime)messageEntity.CreateOn).ToLongTimeString() + "]:</div>"); } else { sbContent.Append(((DateTime)messageEntity.CreateOn).ToString(BaseSystemInfo.DateTimeFormat) + "]:</div>"); } sbContent.Append(messageEntity.Contents); OneShow.Append(sbContent.ToString()); this.webMessage.DocumentText = this.webMessage.DocumentText.Insert(this.webMessage.DocumentText.Length, GetHtmlFace(sbContent.ToString())); this.PlaySound(); FlashWindow(this.Handle, true); } //} return(returnValue); }
protected virtual void OnRaiseAddEmpEvent(SetMessage e) { EventHandler <SetMessage> handler = AddNodeEvent; if (handler != null) { handler(this, e); } }
private void Chatapp_Datarecived(object sender, EventArgs e) { MessageEventargs msg = e as MessageEventargs; SetMessage messageDelegate = MessageReceived; string message = msg.Message.ToString(); int status = Int32.Parse(msg.Status.ToString()); string username = msg.Username.ToString(); //Console.WriteLine("Datarecived event " + message); Invoke(messageDelegate, username, message, status); }
public ActionResult AddFavoriteTest(FavoriteTest favoriteTest) { if (User.Identity.IsAuthenticated) { favoriteTest.UserId = WebHelper.CurrentSession.Content.LoggedInUser.UserId; var message = _iFavoriteTestService.AddToFavorite(favoriteTest); return(Json(message, JsonRequestBehavior.AllowGet)); } else { var message = SetMessage.SetLoginRequiredMessage(); return(Json(message, JsonRequestBehavior.AllowGet)); } }
public Message ChangePassword(User user) { Message message; try { using (var scope = new TransactionScope()) { _dbContext.SqlConnection.Open(); var isExist = _iUserRepository.Get(new User { UserId = user.UserId }); var affectedRow = 0; if (isExist == null) { return(SetMessage.SetInformationMessage("User information not found.")); } var currentPassword = CryptographyHelper.Decrypt(isExist.Password); if (currentPassword != user.CurrentPassword) { return(SetMessage.SetInformationMessage("Invalid current password.")); } isExist.Password = CryptographyHelper.Decrypt(user.Password); affectedRow = _iUserRepository.Update(isExist); message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been updated successfully.") : SetMessage.SetInformationMessage("No data has been updated."); message = SetMessage.SetSuccessMessage("Information has been updated successfully."); scope.Complete(); } } catch (Exception exception) { return(SetMessage.SetErrorMessage(exception.Message)); } finally { _dbContext.SqlConnection.Close(); } return(message); }
void HandleAddNodeEvent(object sender, SetMessage e) { this.Enabled = true; if (e.Message != "0k") { if (CurrEditNode != null) { CurrEditNode.Nodes.Add(e.Message).Tag = e.Tag; } else { tv_Departments.Nodes.Add(e.Message).Tag = e.Tag; } } }
public void Notify(string message) { try { if (this.InvokeRequired) { SetMessage e = new SetMessage(Notify); this.Invoke(e, message); } lblmsg.Text = message; } catch { } }
public bool Set(string varName, object value, int timeout) { var socket = new SnmpSocket(_manager); var request = new SetMessage(); BuildRequest(request, new Variable(_manager.Mib[varName], value.ToString())); var task = Task.Run(() => socket.GetResponse(request, DeviceEndPoint)); if (task.Wait(timeout)) { return(task.Result.ErrorStatus == ErrorStatus.Success); } return(false); }
// Бесконечный цикл получения сообщений public static void ReceiveMessages() { if (_tcpClient != null) { var stream = _tcpClient.GetStream(); var buffer = new byte[2048]; string data = null; int i; while ((i = stream.Read(buffer, 0, buffer.Length)) != 0) { data = Encoding.Unicode.GetString(buffer, 0, i); SetMessage?.Invoke(data, false); } } }
public bool OnReceiveMessage(BaseMessageEntity entity) { bool result = false; if (this.InvokeRequired) { SetMessage setMessage = new SetMessage(OnReceiveMessage); this.Invoke(setMessage, new object[] { entity }); } else { ShowMessage(entity); result = true; } return(result); }
public bool OnReceiveMessage(BaseMessageEntity messageEntity) { bool returnValue = false; if (this.InvokeRequired) { SetMessage SetMessage = new SetMessage(OnReceiveMessage); this.Invoke(SetMessage, new object[] { messageEntity }); } else { OnReceiveMessage(messageEntity.Contents, ((DateTime)messageEntity.CreateOn).ToString(BaseSystemInfo.DateTimeFormat)); returnValue = true; } return(returnValue); }
public Form() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; SetMessage setMessage = PrintMessage; SetUsers setUsers = PrintUsers; Server server = new Server(); server.ExceptionReport += (exceptionSender, args) => { PrintMessage("Error: " + args.Exception.Message); }; server.Listen(setMessage, setUsers); }
public Message AddToFavorite(FavoriteTest favoriteTest) { Message message; try { using (var scope = new TransactionScope()) { _dbContext.SqlConnection.Open(); var affectedRow = 0; var isExist = _iFavoriteTestRepository.GetByUserId(favoriteTest.TestId, favoriteTest.UserId); if (isExist != null) { affectedRow = _iFavoriteTestRepository.Delete(isExist); message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Favorite Test remove successfully.") : SetMessage.SetInformationMessage("No data has been deleted."); message.State = 1;// To trace that favorite test is deleted. } else { affectedRow = _iFavoriteTestRepository.InsertWithoutIdentity(favoriteTest); message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Test has been favorite successfully.") : SetMessage.SetInformationMessage("No data has been saved."); } scope.Complete(); } } catch (Exception exception) { return(SetMessage.SetErrorMessage(exception.Message)); } finally { _dbContext.SqlConnection.Close(); } return(message); }
public Message UpdateUserLogoutTime(int userId) { Message message; try { _dbContext.SqlConnection.Open(); var affectedRow = _iUserLoginInformationRepository.UpdateUserLogoutTime(userId); message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been saved successfully.") : SetMessage.SetInformationMessage("No data has been saved."); } catch (Exception exception) { return(SetMessage.SetErrorMessage(exception.Message)); } finally { _dbContext.SqlConnection.Close(); } return(message); }
public void Export() { SetMessage?.Invoke(this, new MessageEventArgs { Message = Localization.RetrievingRomSetFromDatabase }); using var ctx = Context.Create(Settings.Settings.Current.DatabasePath); RomSet romSet = ctx.RomSets.Find(_romSetId); if (romSet == null) { SetMessage?.Invoke(this, new MessageEventArgs { Message = Localization.CouldNotFindRomSetInDatabase }); WorkFinished?.Invoke(this, System.EventArgs.Empty); return; } SetMessage?.Invoke(this, new MessageEventArgs { Message = Localization.ExportingRoms }); _machines = ctx.Machines.Where(m => m.RomSet.Id == _romSetId).ToArray(); SetProgressBounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = _machines.Length }); _machinePosition = 0; CompressNextMachine(); }
/// <summary> /// 发送数据包,使用此方法时,请先对事件SetMessage赋值 /// 如果消息没有被处理赋值,则会返回null /// </summary> /// <param name="obj">message的<see cref="Type"></param> /// <returns></returns> public byte[] Send(Type type) { var message = Activator.CreateInstance(type) as MavlinkMessage; MavlinkPacket packet = new MavlinkPacket(message); packet.SystemId = 1; packet.ComponentId = 1; packet.SequenceNumber = (byte)((SequenceNumber >> 24) & 0xFF); if (SequenceNumber == 255) { SequenceNumber = 0; } else { SequenceNumber++; } type.GetField("time_usec").SetValue(message, GetTimeStamp()); if (SetMessage == null || !SetMessage.Invoke(message, type)) { return(null); } return(Send(packet)); }
public Message FinishTest(TestTaken testTaken) { Message message; try { using (var scope = new TransactionScope()) { _dbContext.SqlConnection.Open(); if (testTaken.TakenId == 0) { return(SetMessage.SetErrorMessage("Taken Information not found. System unable to process your test result without taken id.")); } var isExist = _iTestTakenRepository.Get(testTaken); var affectedRow = 0; isExist.EndTime = DateTime.UtcNow; var testInformation = _iTestRepository.Get(new Test { TestId = testTaken.TestId }); var correctAnswer = 0; foreach (var details in testTaken.TestTakenDetails) { details.TakenId = isExist.TakenId; details.TestId = isExist.TestId; var correctAnswerOption = String.Join(",", _iQuestionAnswerOptionRepository.GetByQuestionId(details.QuestionId, true).Where(c => c.IsCorrectAnswer).Select(a => a.AnswerOptionId)); var givenAnswerOption = String.Join(",", testTaken.TestTakenDetails.Where(c => c.QuestionId == details.QuestionId).Select(a => a.AnswerOptionId)); if (correctAnswerOption == givenAnswerOption) { details.IsCorrectAnswer = true; correctAnswer++; } _iTestTakenDetailsRepository.InsertWithoutIdentity(details); } var totalQuestion = testInformation.NoOfQuestion; var score = Convert.ToDecimal((correctAnswer * 100.0 / totalQuestion)); isExist.Score = score; affectedRow = _iTestTakenRepository.Update(isExist); var user = _iUserRepository.Get(new User { UserId = isExist.UserId }); //if (user != null && user.RaasForceUserId != null && user.RaasForceUserId > 0) //{ // var restClient = new RestClient(ConfigurationManager.AppSettings["ApiUrl"]); // var request = new RestRequest("api/iTestApp/InsertOrUpdateTestResult?param1=" + user.RaasForceUserId + "¶m2=" + testTaken.TestId + "¶m3=" + testTaken.TakenId + "¶m4=" + score.ToString("#"), Method.GET) { RequestFormat = DataFormat.Json }; // var result = restClient.Execute<HttpResponseMessage>(request); //} message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been saved successfully.") : SetMessage.SetInformationMessage("No data has been saved."); scope.Complete(); } } catch (Exception exception) { return(SetMessage.SetErrorMessage(exception.Message)); } finally { _dbContext.SqlConnection.Close(); } return(message); }
void HandleAddEmpEvent(object sender, SetMessage e) { ShowEmployeeGrid((int)CurrNode.Tag); this.Enabled = true; }
protected void OnSetMessage(string message) { SetMessage?.Invoke(this, new SetMessageEventArgs(message)); }
public void SetStoregeItemValue(SetMessage message) { SetCellValue(message.Cell, message.Value); Self.Tell(PushNeighborsMessage.CreateMessage(message.Cell)); }
public Message UpdateUserInformation(User user, HttpPostedFileBase httpPostedFileBase, bool updateImageOnly = false) { Message message; try { using (var scope = new TransactionScope()) { _dbContext.SqlConnection.Open(); var isExist = _iUserRepository.Get(new User { UserId = user.UserId }); var affectedRow = 0; Guid guid; guid = Guid.NewGuid(); HttpPostedFileBase file = httpPostedFileBase; var target = new MemoryStream(); var documentInformatio = new DocumentInformation(); if (isExist == null) { return(SetMessage.SetInformationMessage("User information not found.")); } if (!updateImageOnly) { isExist.FirstName = user.FirstName; isExist.LastName = user.LastName; isExist.MobileNo = user.MobileNo; affectedRow = _iUserRepository.Update(isExist); message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been updated successfully.") : SetMessage.SetInformationMessage("No data has been updated."); } if (httpPostedFileBase != null) { file.InputStream.CopyTo(target); } byte[] byteData = target.ToArray(); var imageUtility = new ImageUtility(); #region Insert Document Information if (httpPostedFileBase != null) { var size = imageUtility.GetPreferredImageSize(ImageDimensions.Common); byte[] byteAfterResize = imageUtility.EnforceResize(size.Width, size.Height, byteData, guid + Path.GetExtension(httpPostedFileBase.FileName)); documentInformatio.DocumentName = guid + Path.GetExtension(httpPostedFileBase.FileName); documentInformatio.DocumentByte = byteAfterResize; documentInformatio.DocumentSize = byteAfterResize.Length; _iDocumentInformationRepository.InsertWithoutIdentity(documentInformatio); if (documentInformatio.GlobalId > 0) { if (updateImageOnly) { isExist.PhotoFileName = (guid + Path.GetExtension(httpPostedFileBase.FileName)); isExist.GlobalId = documentInformatio.GlobalId > 0 ? documentInformatio.GlobalId : 0; affectedRow = _iUserRepository.Update(isExist); } else { user.PhotoFileName = (guid + Path.GetExtension(httpPostedFileBase.FileName)); user.GlobalId = documentInformatio.GlobalId > 0 ? documentInformatio.GlobalId : 0; affectedRow = _iUserRepository.Update(user); } } string folderPath = HttpContext.Current.Server.MapPath(Constants.ImagePath.ImageFolderPath); bool isUpload = imageUtility.ImageSaveToPath(folderPath, byteData, guid + Path.GetExtension(httpPostedFileBase.FileName), ImageDimensions.Common); } #endregion message = SetMessage.SetSuccessMessage("Information has been updated successfully."); scope.Complete(); } } catch (Exception exception) { return(SetMessage.SetErrorMessage(exception.Message)); } finally { _dbContext.SqlConnection.Close(); } return(message); }
public Message Register(User user, HttpPostedFileBase httpPostedFileBase) { Message message; try { using (var scope = new TransactionScope()) { _dbContext.SqlConnection.Open(); var isExist = _iUserRepository.GetUser(user.Email); var affectedRow = 0; Guid guid; guid = Guid.NewGuid(); HttpPostedFileBase file = httpPostedFileBase; var target = new MemoryStream(); var documentInformatio = new DocumentInformation(); int loggedInUserId = WebHelper.CurrentSession.Content.LoggedInUser != null ? WebHelper.CurrentSession.Content.LoggedInUser.UserId : 0; if (isExist == null) { //User password encryption user.Password = CryptographyHelper.Encrypt(user.Password); //By default user will be active user.IsActive = true; // Registration time globalId 0 user.GlobalId = 0; if (loggedInUserId > 0) { user.CreatedBy = loggedInUserId; user.UserType = user.UserType; } else { user.UserType = Convert.ToInt32(AppUsers.User); } affectedRow = _iUserRepository.InsertWithoutIdentity(user); message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been saved successfully.") : SetMessage.SetInformationMessage("No data has been saved."); } else { user.IsActive = true; user.UserId = isExist.UserId; user.Password = isExist.Password; affectedRow = _iUserRepository.Update(user); message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been updated successfully.") : SetMessage.SetInformationMessage("No data has been updated."); } if (httpPostedFileBase != null) { file.InputStream.CopyTo(target); } byte[] byteData = target.ToArray(); var imageUtility = new ImageUtility(); #region Insert Document Information if (httpPostedFileBase != null) { var size = imageUtility.GetPreferredImageSize(ImageDimensions.Common); byte[] byteAfterResize = imageUtility.EnforceResize(size.Width, size.Height, byteData, guid + Path.GetExtension(httpPostedFileBase.FileName)); documentInformatio.DocumentName = guid + Path.GetExtension(httpPostedFileBase.FileName); documentInformatio.DocumentByte = byteAfterResize; documentInformatio.DocumentSize = byteAfterResize.Length; _iDocumentInformationRepository.InsertWithoutIdentity(documentInformatio); if (documentInformatio.GlobalId > 0) { user.PhotoFileName = (httpPostedFileBase != null ? guid + Path.GetExtension(httpPostedFileBase.FileName) : null); user.GlobalId = documentInformatio.GlobalId > 0 ? documentInformatio.GlobalId : 0; affectedRow = _iUserRepository.Update(user); } } #endregion #region Image Resize and Save To Path string folderPath = HttpContext.Current.Server.MapPath(Constants.ImagePath.ImageFolderPath); if (httpPostedFileBase != null) { bool isUpload = imageUtility.ImageSaveToPath(folderPath, byteData, guid + Path.GetExtension(httpPostedFileBase.FileName), ImageDimensions.Common); } #endregion scope.Complete(); } } catch (Exception exception) { return(SetMessage.SetErrorMessage(exception.Message)); } finally { _dbContext.SqlConnection.Close(); } return(message); }
public Message InsertOrUpdateWithoutIdentity(Question question, HttpPostedFileBase httpPostedFileBase) { Message message; try { using (var scope = new TransactionScope()) { _dbContext.SqlConnection.Open(); var isExistQuestion = _iQuestionRepository.Get(question); var affectedRow = 0; var guid = Guid.NewGuid(); if (isExistQuestion == null) { affectedRow = _iQuestionRepository.InsertWithoutIdentity(question); #region Question Answer Option - Insert foreach (var answerOption in question.QuestionAnswerOptionList) { answerOption.QuestionId = question.QuestionId; _iQuestionAnswerOptionRepository.InsertWithoutIdentity(answerOption); } #endregion message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been saved successfully.") : SetMessage.SetInformationMessage("No data has been saved."); } else { affectedRow = _iQuestionRepository.Update(question); #region Question Answer Option - Update foreach (var answerOption in question.QuestionAnswerOptionList) { answerOption.QuestionId = question.QuestionId; _iQuestionAnswerOptionRepository.Update(answerOption); } #endregion message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been updated successfully.") : SetMessage.SetInformationMessage("No data has been updated."); } #region Question Answer Image if (httpPostedFileBase != null) { var file = httpPostedFileBase; var target = new MemoryStream(); var documentInformatio = new DocumentInformation(); file.InputStream.CopyTo(target); byte[] byteData = target.ToArray(); ImageUtility imageUtility = new ImageUtility(); if (isExistQuestion == null) { #region Insert Document Information var size = imageUtility.GetPreferredImageSize(ImageDimensions.Common); byte[] byteAfterResize = imageUtility.EnforceResize(size.Width, size.Height, byteData, guid + Path.GetExtension(httpPostedFileBase.FileName)); documentInformatio.DocumentName = guid + Path.GetExtension(httpPostedFileBase.FileName); documentInformatio.DocumentByte = byteAfterResize; documentInformatio.DocumentSize = byteAfterResize.Length; _iDocumentInformationRepository.InsertWithoutIdentity(documentInformatio); #region Question - GlobalId Update question.QuestionImageName = (httpPostedFileBase != null ? guid + Path.GetExtension(httpPostedFileBase.FileName) : null); question.GlobalId = documentInformatio.GlobalId > 0 ? documentInformatio.GlobalId : 0; affectedRow = _iQuestionRepository.Update(question); #endregion #endregion } else { #region Update Document Information var isExistDocumentInformatio = _iDocumentInformationRepository.Get(new DocumentInformation { GlobalId = isExistQuestion.GlobalId }); if (isExistDocumentInformatio != null) { var size = imageUtility.GetPreferredImageSize(ImageDimensions.Common); byte[] byteAfterResize = imageUtility.EnforceResize(size.Width, size.Height, byteData, guid + Path.GetExtension(httpPostedFileBase.FileName)); isExistDocumentInformatio.DocumentName = guid + Path.GetExtension(httpPostedFileBase.FileName); isExistDocumentInformatio.DocumentByte = byteAfterResize; isExistDocumentInformatio.DocumentSize = byteAfterResize.Length; _iDocumentInformationRepository.Update(isExistDocumentInformatio); } #endregion } #region Image Resize and Save To Path string folderPath = HttpContext.Current.Server.MapPath(Constants.ImagePath.ImageFolderPath); if (httpPostedFileBase != null) { bool isUpload = imageUtility.ImageSaveToPath(folderPath, byteData, guid + Path.GetExtension(httpPostedFileBase.FileName), ImageDimensions.Common); } #endregion } #endregion scope.Complete(); } } catch (Exception exception) { return(SetMessage.SetErrorMessage(exception.Message)); } finally { _dbContext.SqlConnection.Close(); } return(message); }
public Message InsertOrUpdateWithoutIdentity(Test test, HttpPostedFileBase httpPostedFileBase) { Message message; try { using (var scope = new TransactionScope()) { _dbContext.SqlConnection.Open(); if (test.NoOfQuestion != test.TestWiseQuestions.Count()) { return(SetMessage.SetErrorMessage("No of question not match! Please select (" + test.NoOfQuestion + ")question from question list")); } var isExist = _iTestRepository.Get(test); var affectedRow = 0; var guid = Guid.NewGuid(); var file = httpPostedFileBase; var target = new MemoryStream(); var documentInformatio = new DocumentInformation(); if (isExist == null) { test.IsActive = true; affectedRow = _iTestRepository.InsertWithoutIdentity(test); foreach (var testWiseQuestions in test.TestWiseQuestions) { testWiseQuestions.TestId = test.TestId; _iTestWiseQuestionRepository.InsertWithoutIdentity(testWiseQuestions); } message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been saved successfully.") : SetMessage.SetInformationMessage("No data has been saved."); } else { affectedRow = _iTestRepository.Update(test); _iTestWiseQuestionRepository.DeleteByTestId(test.TestId); foreach (var testWiseQuestions in test.TestWiseQuestions) { testWiseQuestions.TestId = test.TestId; _iTestWiseQuestionRepository.InsertWithoutIdentity(testWiseQuestions); } message = affectedRow > 0 ? SetMessage.SetSuccessMessage("Information has been updated successfully.") : SetMessage.SetInformationMessage("No data has been updated."); } if (httpPostedFileBase != null) { file.InputStream.CopyTo(target); } byte[] byteData = target.ToArray(); var imageUtility = new ImageUtility(); #region Insert Document Information if (httpPostedFileBase != null) { var size = imageUtility.GetPreferredImageSize(ImageDimensions.Common); byte[] byteAfterResize = imageUtility.EnforceResize(size.Width, size.Height, byteData, guid + Path.GetExtension(httpPostedFileBase.FileName)); documentInformatio.DocumentName = guid + Path.GetExtension(httpPostedFileBase.FileName); documentInformatio.DocumentByte = byteAfterResize; documentInformatio.DocumentSize = byteAfterResize.Length; _iDocumentInformationRepository.InsertWithoutIdentity(documentInformatio); if (documentInformatio.GlobalId > 0) { test.TestIconName = (httpPostedFileBase != null ? guid + Path.GetExtension(httpPostedFileBase.FileName) : null); test.GlobalId = documentInformatio.GlobalId > 0 ? documentInformatio.GlobalId : 0; affectedRow = _iTestRepository.Update(test); } } #endregion #region Image Resize and Save To Path string folderPath = HttpContext.Current.Server.MapPath(Constants.ImagePath.ImageFolderPath); if (httpPostedFileBase != null) { bool isUpload = imageUtility.ImageSaveToPath(folderPath, byteData, guid + Path.GetExtension(httpPostedFileBase.FileName), ImageDimensions.Common); } #endregion scope.Complete(); } } catch (Exception exception) { return(SetMessage.SetErrorMessage(exception.Message)); } finally { _dbContext.SqlConnection.Close(); } return(message); }
public bool OnReceiveMessage(BaseMessageEntity messageEntity) { bool returnValue = false; if (this.InvokeRequired) { SetMessage SetMessage = new SetMessage(OnReceiveMessage); this.Invoke(SetMessage, new object[] { messageEntity }); } else { OnReceiveMessage(messageEntity.Contents, ((DateTime)messageEntity.CreateOn).ToString(BaseSystemInfo.DateTimeFormat)); returnValue = true; } return returnValue; }
public void Message(string message) { if (this.statusStrip1.InvokeRequired) { SetMessage s = new SetMessage(Message); this.BeginInvoke(s, new object[] { message }); } else tsEmailStatus.Text = message; Application.DoEvents(); }
public Form1() { InitializeComponent(); _myDelegate = new SetMessage(SetMessageMethod); }
public bool OnReceiveMessage(BaseMessageEntity messageEntity) { bool returnValue = false; // 判断消息,是否发送给本窗体的 //if (this.ReceiverId.Equals(Message.ReceiverId)) //{ returnValue = true; if (this.InvokeRequired) { SetMessage SetMessage = new SetMessage(OnReceiveMessage); this.Invoke(SetMessage, new object[] { messageEntity }); } else { //this.txtMessage.AppendText(messageEntity.CreateBy + " " + ((DateTime)messageEntity.CreateOn).ToString(BaseSystemInfo.DateTimeFormat) + " 说: " + "\r\n"); //this.txtMessage.AppendText(messageEntity.Content + "\r\n"); //this.txtMessage.AppendText("- - - - - - - - - - - - - - -" + "\r\n"); //this.txtMessage.ScrollToCaret(); //StringBuilder sbContent = new StringBuilder(); //sbContent.Append("<div style='color:#00f;font-size:12px;'>" + messageEntity.CreateBy + " ["); //if (isToday((DateTime)messageEntity.CreateOn)) //{ // sbContent.Append(((DateTime)messageEntity.CreateOn).ToLongTimeString() + "]:</div>"); //} //else //{ // sbContent.Append(((DateTime)messageEntity.CreateOn).ToString(BaseSystemInfo.DateTimeFormat) + "]:</div>"); //} //// Web里的单点登录识别码进行转换 //messageEntity.Contents = messageEntity.Contents.Replace("{OpenId}", this.UserInfo.OpenId); //sbContent.Append(messageEntity.Contents); //strOneShow.Append(sbContent.ToString()); //this.webBMsg.DocumentText = this.webBMsg.DocumentText.Insert(this.webBMsg.DocumentText.Length, sbContent.ToString()); messageEntity.Contents = ReplaceMessage(messageEntity.Contents); StringBuilder sbContent = new StringBuilder(); sbContent.Append("<div style='color:#00f;font-size:12px;'>" + messageEntity.CreateBy + " ["); if (isToday((DateTime)messageEntity.CreateOn)) { sbContent.Append(((DateTime)messageEntity.CreateOn).ToLongTimeString() + "]:</div>"); } else { sbContent.Append(((DateTime)messageEntity.CreateOn).ToString(BaseSystemInfo.DateTimeFormat) + "]:</div>"); } sbContent.Append(messageEntity.Contents); OneShow.Append(sbContent.ToString()); this.webMessage.DocumentText = this.webMessage.DocumentText.Insert(this.webMessage.DocumentText.Length, GetHtmlFace(sbContent.ToString())); this.PlaySound(); FlashWindow(this.Handle, true); } //} return returnValue; }
void CompressNextMachine() { SetProgress?.Invoke(this, new ProgressEventArgs { Value = _machinePosition }); if (_machinePosition >= _machines.Length) { SetMessage?.Invoke(this, new MessageEventArgs { Message = Localization.Finished }); WorkFinished?.Invoke(this, System.EventArgs.Empty); return; } Machine machine = _machines[_machinePosition]; SetMessage2?.Invoke(this, new MessageEventArgs { Message = machine.Name }); using var ctx = Context.Create(Settings.Settings.Current.DatabasePath); string machineName = machine.Name; Dictionary <string, MediaByMachine> mediasByMachine = ctx.MediasByMachines. Where(f => f.Machine.Id == machine.Id && f.Media.IsInRepo). ToDictionary(f => f.Name); if (mediasByMachine.Count > 0) { SetProgress2Bounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = mediasByMachine.Count }); if (machineName.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)) { machineName = machineName.Substring(0, machineName.Length - 4); } string machinePath = Path.Combine(_outPath, machineName); if (!Directory.Exists(machinePath)) { Directory.CreateDirectory(machinePath); } long mediaPosition = 0; foreach (KeyValuePair <string, MediaByMachine> mediaByMachine in mediasByMachine) { string outputPath = Path.Combine(machinePath, mediaByMachine.Key); if (!outputPath.EndsWith(".aif", StringComparison.InvariantCultureIgnoreCase)) { outputPath += ".aif"; } SetProgress2?.Invoke(this, new ProgressEventArgs { Value = mediaPosition }); string repoPath = null; string md5Path = null; string sha1Path = null; string sha256Path = null; DbMedia media = mediaByMachine.Value.Media; if (media.Sha256 != null) { byte[] sha256Bytes = new byte[32]; string sha256 = media.Sha256; for (int i = 0; i < 32; i++) { if (sha256[i * 2] >= 0x30 && sha256[i * 2] <= 0x39) { sha256Bytes[i] = (byte)((sha256[i * 2] - 0x30) * 0x10); } else if (sha256[i * 2] >= 0x41 && sha256[i * 2] <= 0x46) { sha256Bytes[i] = (byte)((sha256[i * 2] - 0x37) * 0x10); } else if (sha256[i * 2] >= 0x61 && sha256[i * 2] <= 0x66) { sha256Bytes[i] = (byte)((sha256[i * 2] - 0x57) * 0x10); } if (sha256[(i * 2) + 1] >= 0x30 && sha256[(i * 2) + 1] <= 0x39) { sha256Bytes[i] += (byte)(sha256[(i * 2) + 1] - 0x30); } else if (sha256[(i * 2) + 1] >= 0x41 && sha256[(i * 2) + 1] <= 0x46) { sha256Bytes[i] += (byte)(sha256[(i * 2) + 1] - 0x37); } else if (sha256[(i * 2) + 1] >= 0x61 && sha256[(i * 2) + 1] <= 0x66) { sha256Bytes[i] += (byte)(sha256[(i * 2) + 1] - 0x57); } } string sha256B32 = Base32.ToBase32String(sha256Bytes); sha256Path = Path.Combine(Settings.Settings.Current.RepositoryPath, "aaru", "sha256", sha256B32[0].ToString(), sha256B32[1].ToString(), sha256B32[2].ToString(), sha256B32[3].ToString(), sha256B32[4].ToString(), sha256B32 + ".aif"); } if (media.Sha1 != null) { byte[] sha1Bytes = new byte[20]; string sha1 = media.Sha1; for (int i = 0; i < 20; i++) { if (sha1[i * 2] >= 0x30 && sha1[i * 2] <= 0x39) { sha1Bytes[i] = (byte)((sha1[i * 2] - 0x30) * 0x10); } else if (sha1[i * 2] >= 0x41 && sha1[i * 2] <= 0x46) { sha1Bytes[i] = (byte)((sha1[i * 2] - 0x37) * 0x10); } else if (sha1[i * 2] >= 0x61 && sha1[i * 2] <= 0x66) { sha1Bytes[i] = (byte)((sha1[i * 2] - 0x57) * 0x10); } if (sha1[(i * 2) + 1] >= 0x30 && sha1[(i * 2) + 1] <= 0x39) { sha1Bytes[i] += (byte)(sha1[(i * 2) + 1] - 0x30); } else if (sha1[(i * 2) + 1] >= 0x41 && sha1[(i * 2) + 1] <= 0x46) { sha1Bytes[i] += (byte)(sha1[(i * 2) + 1] - 0x37); } else if (sha1[(i * 2) + 1] >= 0x61 && sha1[(i * 2) + 1] <= 0x66) { sha1Bytes[i] += (byte)(sha1[(i * 2) + 1] - 0x57); } } string sha1B32 = Base32.ToBase32String(sha1Bytes); sha1Path = Path.Combine(Settings.Settings.Current.RepositoryPath, "aaru", "sha1", sha1B32[0].ToString(), sha1B32[1].ToString(), sha1B32[2].ToString(), sha1B32[3].ToString(), sha1B32[4].ToString(), sha1B32 + ".aif"); } if (media.Md5 != null) { byte[] md5Bytes = new byte[16]; string md5 = media.Md5; for (int i = 0; i < 16; i++) { if (md5[i * 2] >= 0x30 && md5[i * 2] <= 0x39) { md5Bytes[i] = (byte)((md5[i * 2] - 0x30) * 0x10); } else if (md5[i * 2] >= 0x41 && md5[i * 2] <= 0x46) { md5Bytes[i] = (byte)((md5[i * 2] - 0x37) * 0x10); } else if (md5[i * 2] >= 0x61 && md5[i * 2] <= 0x66) { md5Bytes[i] = (byte)((md5[i * 2] - 0x57) * 0x10); } if (md5[(i * 2) + 1] >= 0x30 && md5[(i * 2) + 1] <= 0x39) { md5Bytes[i] += (byte)(md5[(i * 2) + 1] - 0x30); } else if (md5[(i * 2) + 1] >= 0x41 && md5[(i * 2) + 1] <= 0x46) { md5Bytes[i] += (byte)(md5[(i * 2) + 1] - 0x37); } else if (md5[(i * 2) + 1] >= 0x61 && md5[(i * 2) + 1] <= 0x66) { md5Bytes[i] += (byte)(md5[(i * 2) + 1] - 0x57); } } string md5B32 = Base32.ToBase32String(md5Bytes); md5Path = Path.Combine(Settings.Settings.Current.RepositoryPath, "aaru", "md5", md5B32[0].ToString(), md5B32[1].ToString(), md5B32[2].ToString(), md5B32[3].ToString(), md5B32[4].ToString(), md5B32 + ".aif"); } if (File.Exists(sha256Path)) { repoPath = sha256Path; } else if (File.Exists(sha1Path)) { repoPath = sha1Path; } else if (File.Exists(md5Path)) { repoPath = md5Path; } if (repoPath == null) { throw new ArgumentException(string.Format(Localization.CannotFindHashInRepository, media.Sha256 ?? media.Sha1 ?? media.Md5)); } var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); var outFs = new FileStream(outputPath, FileMode.Create, FileAccess.Write); SetMessage3?.Invoke(this, new MessageEventArgs { Message = string.Format(Localization.Copying, Path.GetFileName(outputPath)) }); SetProgress3Bounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = inFs.Length }); byte[] buffer = new byte[BUFFER_SIZE]; while (inFs.Position + BUFFER_SIZE <= inFs.Length) { SetProgress3?.Invoke(this, new ProgressEventArgs { Value = inFs.Position }); inFs.Read(buffer, 0, buffer.Length); outFs.Write(buffer, 0, buffer.Length); } buffer = new byte[inFs.Length - inFs.Position]; SetProgress3?.Invoke(this, new ProgressEventArgs { Value = inFs.Position }); inFs.Read(buffer, 0, buffer.Length); outFs.Write(buffer, 0, buffer.Length); inFs.Close(); outFs.Close(); mediaPosition++; } } Dictionary <string, DiskByMachine> disksByMachine = ctx.DisksByMachines. Where(f => f.Machine.Id == machine.Id && f.Disk.IsInRepo). ToDictionary(f => f.Name); if (disksByMachine.Count > 0) { SetProgress2Bounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = disksByMachine.Count }); if (machineName.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)) { machineName = machineName.Substring(0, machineName.Length - 4); } string machinePath = Path.Combine(_outPath, machineName); if (!Directory.Exists(machinePath)) { Directory.CreateDirectory(machinePath); } long diskPosition = 0; foreach (KeyValuePair <string, DiskByMachine> diskByMachine in disksByMachine) { string outputPath = Path.Combine(machinePath, diskByMachine.Key); if (!outputPath.EndsWith(".chd", StringComparison.InvariantCultureIgnoreCase)) { outputPath += ".chd"; } SetProgress2?.Invoke(this, new ProgressEventArgs { Value = diskPosition }); string repoPath = null; string md5Path = null; string sha1Path = null; DbDisk disk = diskByMachine.Value.Disk; if (disk.Sha1 != null) { byte[] sha1Bytes = new byte[20]; string sha1 = disk.Sha1; for (int i = 0; i < 20; i++) { if (sha1[i * 2] >= 0x30 && sha1[i * 2] <= 0x39) { sha1Bytes[i] = (byte)((sha1[i * 2] - 0x30) * 0x10); } else if (sha1[i * 2] >= 0x41 && sha1[i * 2] <= 0x46) { sha1Bytes[i] = (byte)((sha1[i * 2] - 0x37) * 0x10); } else if (sha1[i * 2] >= 0x61 && sha1[i * 2] <= 0x66) { sha1Bytes[i] = (byte)((sha1[i * 2] - 0x57) * 0x10); } if (sha1[(i * 2) + 1] >= 0x30 && sha1[(i * 2) + 1] <= 0x39) { sha1Bytes[i] += (byte)(sha1[(i * 2) + 1] - 0x30); } else if (sha1[(i * 2) + 1] >= 0x41 && sha1[(i * 2) + 1] <= 0x46) { sha1Bytes[i] += (byte)(sha1[(i * 2) + 1] - 0x37); } else if (sha1[(i * 2) + 1] >= 0x61 && sha1[(i * 2) + 1] <= 0x66) { sha1Bytes[i] += (byte)(sha1[(i * 2) + 1] - 0x57); } } string sha1B32 = Base32.ToBase32String(sha1Bytes); sha1Path = Path.Combine(Settings.Settings.Current.RepositoryPath, "chd", "sha1", sha1B32[0].ToString(), sha1B32[1].ToString(), sha1B32[2].ToString(), sha1B32[3].ToString(), sha1B32[4].ToString(), sha1B32 + ".chd"); } if (disk.Md5 != null) { byte[] md5Bytes = new byte[16]; string md5 = disk.Md5; for (int i = 0; i < 16; i++) { if (md5[i * 2] >= 0x30 && md5[i * 2] <= 0x39) { md5Bytes[i] = (byte)((md5[i * 2] - 0x30) * 0x10); } else if (md5[i * 2] >= 0x41 && md5[i * 2] <= 0x46) { md5Bytes[i] = (byte)((md5[i * 2] - 0x37) * 0x10); } else if (md5[i * 2] >= 0x61 && md5[i * 2] <= 0x66) { md5Bytes[i] = (byte)((md5[i * 2] - 0x57) * 0x10); } if (md5[(i * 2) + 1] >= 0x30 && md5[(i * 2) + 1] <= 0x39) { md5Bytes[i] += (byte)(md5[(i * 2) + 1] - 0x30); } else if (md5[(i * 2) + 1] >= 0x41 && md5[(i * 2) + 1] <= 0x46) { md5Bytes[i] += (byte)(md5[(i * 2) + 1] - 0x37); } else if (md5[(i * 2) + 1] >= 0x61 && md5[(i * 2) + 1] <= 0x66) { md5Bytes[i] += (byte)(md5[(i * 2) + 1] - 0x57); } } string md5B32 = Base32.ToBase32String(md5Bytes); md5Path = Path.Combine(Settings.Settings.Current.RepositoryPath, "chd", "md5", md5B32[0].ToString(), md5B32[1].ToString(), md5B32[2].ToString(), md5B32[3].ToString(), md5B32[4].ToString(), md5B32 + ".chd"); } if (File.Exists(sha1Path)) { repoPath = sha1Path; } else if (File.Exists(md5Path)) { repoPath = md5Path; } if (repoPath == null) { throw new ArgumentException(string.Format(Localization.CannotFindHashInRepository, disk.Sha1 ?? disk.Md5)); } var inFs = new FileStream(repoPath, FileMode.Open, FileAccess.Read); var outFs = new FileStream(outputPath, FileMode.Create, FileAccess.Write); SetMessage3?.Invoke(this, new MessageEventArgs { Message = string.Format(Localization.Copying, Path.GetFileName(outputPath)) }); SetProgress3Bounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = inFs.Length }); byte[] buffer = new byte[BUFFER_SIZE]; while (inFs.Position + BUFFER_SIZE <= inFs.Length) { SetProgress3?.Invoke(this, new ProgressEventArgs { Value = inFs.Position }); inFs.Read(buffer, 0, buffer.Length); outFs.Write(buffer, 0, buffer.Length); } buffer = new byte[inFs.Length - inFs.Position]; SetProgress3?.Invoke(this, new ProgressEventArgs { Value = inFs.Position }); inFs.Read(buffer, 0, buffer.Length); outFs.Write(buffer, 0, buffer.Length); inFs.Close(); outFs.Close(); diskPosition++; } } _filesByMachine = ctx.FilesByMachines.Where(f => f.Machine.Id == machine.Id && f.File.IsInRepo). ToDictionary(f => f.Name); if (_filesByMachine.Count == 0) { _machinePosition++; Task.Run(CompressNextMachine); return; } SetProgress2Bounds?.Invoke(this, new ProgressBoundsEventArgs { Minimum = 0, Maximum = _filesByMachine.Count }); if (!machineName.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)) { machineName += ".zip"; } var zf = new ZipFile(Path.Combine(_outPath, machineName), Encoding.UTF8) { CompressionLevel = CompressionLevel.BestCompression, CompressionMethod = CompressionMethod.Deflate, EmitTimesInUnixFormatWhenSaving = true, EmitTimesInWindowsFormatWhenSaving = true, UseZip64WhenSaving = Zip64Option.AsNecessary, SortEntriesBeforeSaving = true }; zf.SaveProgress += Zf_SaveProgress; foreach (KeyValuePair <string, FileByMachine> fileByMachine in _filesByMachine) { // Is a directory if ((fileByMachine.Key.EndsWith("/", StringComparison.InvariantCultureIgnoreCase) || fileByMachine.Key.EndsWith("\\", StringComparison.InvariantCultureIgnoreCase)) && fileByMachine.Value.File.Size == 0) { ZipEntry zd = zf.AddDirectoryByName(fileByMachine.Key.Replace('/', '\\')); zd.Attributes = FileAttributes.Normal; zd.CreationTime = DateTime.UtcNow; zd.AccessedTime = DateTime.UtcNow; zd.LastModified = DateTime.UtcNow; zd.ModifiedTime = DateTime.UtcNow; continue; } ZipEntry zi = zf.AddEntry(fileByMachine.Key, Zf_HandleOpen, Zf_HandleClose); zi.Attributes = FileAttributes.Normal; zi.CreationTime = DateTime.UtcNow; zi.AccessedTime = DateTime.UtcNow; zi.LastModified = DateTime.UtcNow; zi.ModifiedTime = DateTime.UtcNow; } zf.Save(); }