/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(OpStatusCode.BadRequest); StringBuilder rt = new StringBuilder(); try { if (param.Equals("open", StringComparison.InvariantCultureIgnoreCase)) { if (mciSendString("set CDAudio door open", rt, 127, IntPtr.Zero) == 0) opResult.StatusCode = OpStatusCode.Ok; } else { if (mciSendString("set CDAudio door closed", rt, 127, IntPtr.Zero) == 0) opResult.StatusCode = OpStatusCode.Ok; } } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); opResult.StatusCode = OpStatusCode.Success; try { if (AddInModule.getMediaExperience() == null) { opResult.StatusCode = OpStatusCode.BadRequest; opResult.AppendFormat("No media playing"); } else if (m_set) { TimeSpan position = TimeSpan.FromSeconds(double.Parse(param)); AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.Position = position; } else { TimeSpan position = AddInHost.Current.MediaCenterEnvironment.MediaExperience.Transport.Position; opResult.AppendFormat("Position={0}", position); } } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.AppendFormat(ex.Message); } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <returns></returns> public OpResult Execute(string param) { // Now try to read again OpResult opResult = new OpResult(); try { if (AddInModule.getMediaExperience() == null) { opResult.StatusCode = OpStatusCode.BadRequest; opResult.AppendFormat("No media playing"); } else { foreach (KeyValuePair<string, object> entry in AddInHost.Current.MediaCenterEnvironment.MediaExperience.MediaMetadata) { opResult.AppendFormat("{0}={1}", entry.Key, entry.Value); } opResult.StatusCode = OpStatusCode.Ok; } } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { XmlDocument doc = new XmlDocument(); doc.Load(System.Environment.GetEnvironmentVariable("windir") + "\\ehome\\vmcController.xml"); XmlNodeList commands = doc.DocumentElement.SelectNodes("macros/macro[@id='" + param + "']/action"); if (commands.Count == 0) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = "Macro not found"; } else { RemoteCommands rc = new RemoteCommands(); OpResult innerOp; opResult.StatusCode = OpStatusCode.Ok; foreach (XmlNode command in commands) { innerOp = rc.Execute(command.Attributes.GetNamedItem("command").Value,command.InnerText); opResult.StatusText += innerOp.StatusCode.ToString() + ": " + innerOp.StatusText + "<br>"; } } } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Sends the specified string to the application as keystrokes. /// </summary> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); ushort key = 0; try { param = param.ToUpper(); foreach (char c in param.ToCharArray(0, param.Length)) { key = (ushort)NativeMethods.VkKeyScan(c); bool shift = ((NativeMethods.VkKeyScan(c) & 0x0100) > 0); SendKeyCmd skc = new SendKeyCmd(key, shift, false, false); opResult = skc.Execute(""); if (debug) { MsgBoxCmd mbc = new MsgBoxCmd(); string s = String.Format("\"Just sent a character!\" \"Character sent: '{0}', vk: {1}\" 1", c, key); mbc.Execute(s); } if (opResult.StatusCode != OpStatusCode.Success) break; } if (debug) { MsgBoxCmd mbc = new MsgBoxCmd(); mbc.Execute("\"Length: " + param.Length + "\" \"Sent: '" + param + "'\" 5"); } } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); foreach (Process p in Process.GetProcesses()) { try { if (p.MainModule.ModuleName.Contains("ehshell")) try { p.Kill(); Process.Start("ehshell.exe"); opResult.StatusCode = OpStatusCode.Ok; } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } } catch (Exception) { } } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { Match match = m_regex.Match(param); if (match.Success) { string imagefile = match.Groups["imagepath"].Value.Replace("/","\\"); // get latest image file from directory, notation example: @"c:\temp\test*.jpg" if (imagefile.Contains("*")) { imagefile = GetFileInfo.GetNewestImage(imagefile); } opResult.AppendFormat("response={0}", AddInHost.Current.MediaCenterEnvironment.DialogNotification( match.Groups["message"].Value, new System.Collections.ArrayList(1), int.Parse(match.Groups["timeout"].Value), "file://" + imagefile ).ToString()); opResult.StatusCode = OpStatusCode.Ok; } } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
public Source_GPIO( rfid.Constants.GpioPin nativePin, OpState state ) : base() { this.nativePin = nativePin; this.access = OpAccess.SET; this.state = state; this.status = OpResult.FAILURE; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { opResult.StatusCode = OpStatusCode.Ok; opResult.AppendFormat("version={0}", AddInHost.Current.MediaCenterEnvironment.Version.ToString()); } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { AddInHost.Current.MediaCenterEnvironment.MediaExperience.GoToFullScreen(); opResult.StatusCode = OpStatusCode.Success; } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { opResult.StatusCode = OpStatusCode.Ok; opResult.AppendFormat("NIT={0}","Niewenhuijse IT, Nieuwdorp (www.niewenhuijse.nl)"); } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { bool bTemplate = true; OpResult opResult = new OpResult(); string page_file = ""; string page = ""; opResult.StatusCode = OpStatusCode.Ok; try { if (param.IndexOf("-help") >= 0) { opResult = showHelp(opResult); return opResult; } // Use custom format? if (!m_templates.ContainsKey(param)) { bTemplate = false; page = "Error: Template '" + param + "' not found!\r\n All available templates:\r\n"; page += listTemplates(); } else page_file = m_templates[param]; if (page_file.Length > 0) page = loadTemplateFile(page_file); // Convert tags: if (bTemplate) { Regex rTags = new Regex("%%(?<rex>.+?)%%"); Match match = rTags.Match(page); while (match.Success) { string value = getRex(match.Groups["rex"].Value); page = page.Replace("%%" + match.Groups["rex"].Value + "%%", value); match = match.NextMatch(); } } opResult.AppendFormat("{0}", page); } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { if (NativeMethods.SendMessage(GetWindowHandle(), WM_SYSCOMMAND, wParam, lParam) == 0) opResult.StatusCode = OpStatusCode.Success; else opResult.StatusCode = OpStatusCode.BadRequest; } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { List<ScheduleEvent> events; StringBuilder sb = new StringBuilder(); OpResult opResult = new OpResult(); if (m_eventSchedule == null) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = m_exception; return opResult; } try { if (param.Equals("recorded", StringComparison.InvariantCultureIgnoreCase)) events = m_eventSchedule.GetScheduleEvents(DateTime.MinValue, DateTime.MaxValue, ScheduleEventStates.HasOccurred) as List<ScheduleEvent>; else if (param.Equals("recording", StringComparison.InvariantCultureIgnoreCase)) events = m_eventSchedule.GetScheduleEvents(DateTime.MinValue, DateTime.MaxValue, ScheduleEventStates.IsOccurring) as List<ScheduleEvent>; else if (param.Equals("scheduled", StringComparison.InvariantCultureIgnoreCase)) events = m_eventSchedule.GetScheduleEvents(DateTime.Now, DateTime.Now.AddDays(7), ScheduleEventStates.WillOccur) as List<ScheduleEvent>; else { opResult.StatusCode = OpStatusCode.BadRequest; return opResult; } events.Sort(CompareScheduleEvents); foreach (ScheduleEvent item in events) { opResult.AppendFormat("{0}={1} ({2}-{3})", item.Id, item.GetExtendedProperty("Title"), item.StartTime.ToLocalTime().ToString("g"), item.EndTime.ToLocalTime().ToShortTimeString() ); } opResult.StatusCode = OpStatusCode.Ok; } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
public OpResult AddStudentEvaluation(StudentEvaluation addStudentEvaluation) { var result = new OpResult(); //try //{ using (var cmd = new SqlCommand()) { // Build the command cmd.Connection = Cxn; cmd.CommandText = "INSERT INTO [EnglishDB].[dbo].[StudentEvaluations]([StudentEvaluationId],[UserId],[EvaluationId],[TimeOfEvaluation],[EvaluationCount]) " + "VALUES (@seid, @uid, @eid, @toe, @ec)"; cmd.Parameters.Add(new SqlParameter("seid", addStudentEvaluation.Id)); cmd.Parameters.Add(new SqlParameter("uid", addStudentEvaluation.UserId)); cmd.Parameters.Add(new SqlParameter("eid", addStudentEvaluation.EvaluationId)); cmd.Parameters.Add(new SqlParameter("toe", addStudentEvaluation.TimeOfEvaluation)); cmd.Parameters.Add(new SqlParameter("ec", addStudentEvaluation.EvaluationCount)); // Execute the Insert if (Cxn.State == ConnectionState.Open) Cxn.Close(); Cxn.Open(); var insertCount = cmd.ExecuteNonQuery(); Cxn.Close(); if (insertCount != 1) { result.OperationWasSuccessful = false; result.Error = new ArgumentException(string.Format("{0} schedules were inserted when only 1 should have been inserted.", insertCount)); } else { result.OperationWasSuccessful = true; } } //} //catch (Exception ex) //{ // result.OperationWasSuccessful = false; // result.Error = ex; //} return result; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { string[] args = param.Split(' '); PageId pageId = (PageId)Enum.Parse(typeof(PageId), args[0], true); object obj = (args.Length == 2 ? args[1] : null); AddInHost.Current.MediaCenterEnvironment.NavigateToPage(pageId, obj); opResult.StatusCode = OpStatusCode.Success; } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { foreach (KeyValuePair<string, object> entry in AddInHost.Current.MediaCenterEnvironment.Capabilities) { opResult.AppendFormat("{0}={1}", entry.Key, entry.Value); } opResult.StatusCode = OpStatusCode.Ok; } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location); string version = fileVersionInfo.ProductVersion; opResult.StatusCode = OpStatusCode.Ok; opResult.AppendFormat("version={0}", version + " (" + AddInHost.Current.MediaCenterEnvironment.CpuClass + ")"); } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
public OpResult AddStudent(Student addStudent) { var result = new OpResult(); try { using (var cmd = new SqlCommand()) { // Build the command cmd.Connection = Cxn; cmd.CommandText = "INSERT INTO [EnglishDB].[dbo].[Students]([UserId],[StudentNumber],[School]) " + "VALUES (@Id, @sNumber, @school)"; cmd.Parameters.Add(new SqlParameter("Id", addStudent.Id)); cmd.Parameters.Add(new SqlParameter("sNumber", addStudent.StudentNumber)); cmd.Parameters.Add(new SqlParameter("school", addStudent.School)); if (Cxn.State == System.Data.ConnectionState.Open) Cxn.Close(); // Execute the Insert Cxn.Open(); var insertCount = cmd.ExecuteNonQuery(); Cxn.Close(); if (insertCount != 1) { result.OperationWasSuccessful = false; result.Error = new ArgumentException(string.Format("{0} schedules were inserted when only 1 should have been inserted.", insertCount)); } else { result.OperationWasSuccessful = true; } } } catch (Exception ex) { result.OperationWasSuccessful = false; result.Error = ex; } return result; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(OpStatusCode.Success); try { if (param.Equals("Up", StringComparison.InvariantCultureIgnoreCase)) AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeUp(); else if (param.Equals("Down", StringComparison.InvariantCultureIgnoreCase)) AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeDown(); else if (param.Equals("Mute", StringComparison.InvariantCultureIgnoreCase)) AddInHost.Current.MediaCenterEnvironment.AudioMixer.Mute = true; else if (param.Equals("UnMute", StringComparison.InvariantCultureIgnoreCase)) AddInHost.Current.MediaCenterEnvironment.AudioMixer.Mute = false; else if (param.Equals("Get", StringComparison.InvariantCultureIgnoreCase)) { opResult.StatusCode = OpStatusCode.Ok; opResult.AppendFormat("volume={0}", (int)(AddInHost.Current.MediaCenterEnvironment.AudioMixer.Volume / 1310.7)); } else { int desiredLevel = int.Parse(param); if (desiredLevel > 50 || desiredLevel < 0) { opResult.StatusCode = OpStatusCode.BadRequest; return opResult; } int volume = (int)(AddInHost.Current.MediaCenterEnvironment.AudioMixer.Volume / 1310.7); for (int level = volume; level > desiredLevel; level--) AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeDown(); for (int level = volume; level < desiredLevel; level++) AddInHost.Current.MediaCenterEnvironment.AudioMixer.VolumeUp(); } } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
public OpResult AddQuestion(Question addQuestion) { var result = new OpResult(); try { using (var cmd = new SqlCommand()) { // Build the command cmd.Connection = Cxn; cmd.CommandText = "INSERT INTO [EnglishDB].[dbo].[Questions]([QuestionId],[EvaluationId],[Question],[Number]) " + "VALUES (@QuestionId, @EvaluationId, @Question, @Number)"; cmd.Parameters.Add(new SqlParameter("QuestionId", addQuestion.Id)); cmd.Parameters.Add(new SqlParameter("EvaluationId", addQuestion.EvaluationId)); cmd.Parameters.Add(new SqlParameter("Question", addQuestion.QuestionString)); cmd.Parameters.Add(new SqlParameter("Number", addQuestion.Number)); // Execute the Insert Cxn.Open(); var insertCount = cmd.ExecuteNonQuery(); Cxn.Close(); if (insertCount != 1) { result.OperationWasSuccessful = false; result.Error = new ArgumentException(string.Format("{0} schedules were inserted when only 1 should have been inserted.", insertCount)); } else { result.OperationWasSuccessful = true; } } } catch (Exception ex) { result.OperationWasSuccessful = false; result.Error = ex; } return result; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { if (setNowPlaying()) { opResult.StatusCode = OpStatusCode.Success; } else { opResult.StatusCode = OpStatusCode.BadRequest; } } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(OpStatusCode.Success); try { Microsoft.MediaCenter.MediaChanger changer = AddInHost.Current.MediaCenterEnvironment.MediaChangers[0]; int slotAddress = int.Parse(param); try { changer.UnloadDisc(0); } catch { } changer.LoadDisc(slotAddress, 0); } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
public OpResult DeleteStudentEvaluation(string StudentEvaluationId) { var result = new OpResult(); try { using (var cmd = new SqlCommand()) { // Build the command cmd.Connection = Cxn; cmd.CommandText = "DELETE StudentEvaluations WHERE StudentEvaluationId = @StudentEvaluationId"; cmd.Parameters.Add(new SqlParameter("StudentEvaluationId", StudentEvaluationId)); // Execute the deletion Cxn.Open(); var deleteCount = cmd.ExecuteNonQuery(); Cxn.Close(); if (deleteCount != 1) { result.OperationWasSuccessful = false; result.Error = new ArgumentException(string.Format("{0} StudentEvaluations were deleted when only 1 should have been deleted.", deleteCount)); } else { result.OperationWasSuccessful = true; } } } catch (Exception ex) { result.OperationWasSuccessful = false; result.Error = ex; } return result; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { switch (m_mediaType) { case MediaType.Dvd: param = param.Replace('\\', '/'); break; case MediaType.Audio: case MediaType.Video: case MediaType.Dvr: param = param.Replace(@"\", @"\\"); break; //case MediaType.TV: // // Check for a channel number and convert to a callsign // int channelNum; // if (int.TryParse(param, out channelNum)) // { // Channel channel = Guide.GuideInstance.GetChannelByNumber(channelNum); // if (channel != null) param = channel.DefaultService.CallSign; // } // break; } if (AddInHost.Current.MediaCenterEnvironment.PlayMedia(m_mediaType, param, m_appendToQueue)) { opResult.StatusCode = OpStatusCode.Success; } else { opResult.StatusCode = OpStatusCode.BadRequest; } } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { Match match = m_regex.Match(param); if (match.Success) { opResult.AppendFormat("response={0}", AddInHost.Current.MediaCenterEnvironment.Dialog( match.Groups["message"].Value, match.Groups["caption"].Value, DialogButtons.Ok, int.Parse(match.Groups["timeout"].Value), false).ToString()); opResult.StatusCode = OpStatusCode.Ok; } } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
/// <summary> /// Executes the specified param. /// </summary> /// <param name="param">The param.</param> /// <param name="result">The result.</param> /// <returns></returns> public OpResult Execute(string param) { OpResult opResult = new OpResult(); try { Match match = m_regex.Match(param); if (!match.Success) { opResult.StatusCode = OpStatusCode.BadRequest; return opResult; } /* Guide guide = Guide.GuideInstance as Guide; if (match.Groups["channel"].Value.Equals("all", StringComparison.InvariantCultureIgnoreCase)) { foreach (Channel channel in guide.Channels) GetChannelEpg(channel, opResult); } else { foreach (string numStr in match.Groups["channel"].Value.Split(',')) GetChannelEpg(guide.GetChannelByNumberString(numStr), opResult); } * */ opResult.StatusCode = OpStatusCode.Ok; } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return opResult; }
protected override OpResult _Store(Supplier _obj) { if (_obj == null) { return(OpResult.NotifyStoreAction(OpResult.ResultStatus.ObjectIsNull, _obj, "Supplier object cannot be deleted as it is null")); } bool is_creating = !Exists(_obj); DbInsertStatement clause = DbMgr.CreateInsertClause(); clause.InsertColumn("CardID", DbMgr.CreateStringFieldEntry(_obj.CardIdentification)); clause.InsertColumn("FirstName", DbMgr.CreateStringFieldEntry(_obj.FirstName)); clause.InsertColumn("CoLastName", DbMgr.CreateStringFieldEntry(_obj.LastName)); clause.InsertColumn("CardStatus", DbMgr.CreateStringFieldEntry(_obj.IsInactive)); if (RepositoryMgr.IsMultiUserVersion && _obj.Currency != null) { clause.InsertColumn("CurrencyCode", DbMgr.CreateStringFieldEntry(_obj.Currency.CurrencyCode)); } PopulateAddress(clause, _obj, 1); PopulateAddress(clause, _obj, 2); PopulateAddress(clause, _obj, 3); PopulateAddress(clause, _obj, 4); PopulateAddress(clause, _obj, 5); clause.InsertColumn("Picture", DbMgr.CreateStringFieldEntry(_obj.Picture)); clause.InsertColumn("Notes", DbMgr.CreateStringFieldEntry(_obj.Notes)); clause.InsertColumn("Identifiers", DbMgr.CreateStringFieldEntry(_obj.Identifiers)); clause.InsertColumn("CustomField1", DbMgr.CreateStringFieldEntry(_obj.CustomField1)); clause.InsertColumn("CustomField2", DbMgr.CreateStringFieldEntry(_obj.CustomField2)); clause.InsertColumn("CustomField3", DbMgr.CreateStringFieldEntry(_obj.CustomField3)); if (this.RepositoryMgr.IsMultiUserVersion) { clause.InsertColumn("BillingRate", DbMgr.CreateDoubleFieldEntry(_obj.HourlyBillingRate)); clause.InsertColumn("CostPerHour", DbMgr.CreateDoubleFieldEntry(_obj.EstimatedCostPerHour)); } if (_obj.Terms != null) { clause.InsertColumn("PaymentIsDue", DbMgr.CreateIntFieldEntry(_obj.Terms.PaymentIsDue)); clause.InsertColumn("DiscountDays", DbMgr.CreateIntFieldEntry(_obj.Terms.DiscountDays)); clause.InsertColumn("BalanceDueDays", DbMgr.CreateIntFieldEntry(_obj.Terms.BalanceDueDays)); clause.InsertColumn("PercentDiscount", DbMgr.CreateDoubleFieldEntry(_obj.Terms.EarlyPaymentDiscountPercent)); //clause.InsertColumn("PercentMonthlyCharge", DbMgr.CreateDoubleFieldEntry(_obj.Terms.LatePaymentChargePercent)); } if (_obj.TaxCode != null) { clause.InsertColumn("TaxCode", DbMgr.CreateStringFieldEntry(_obj.TaxCode.Code)); } clause.InsertColumn("CreditLimit", DbMgr.CreateDoubleFieldEntry(_obj.CreditLimit)); clause.InsertColumn("TaxIDNumber", DbMgr.CreateStringFieldEntry(_obj.TaxIDNumber)); clause.InsertColumn("VolumeDiscount", DbMgr.CreateDoubleFieldEntry(_obj.VolumeDiscount)); if (_obj.PurchaseLayout != null) { clause.InsertColumn("PurchaseLayout", DbMgr.CreateStringFieldEntry(_obj.PurchaseLayout.InvoiceTypeID)); } if (_obj.PaymentMethod != null) { clause.InsertColumn("PaymentMethod", DbMgr.CreateStringFieldEntry(_obj.PaymentMethod.MethodType)); } clause.InsertColumn("PaymentNotes", DbMgr.CreateStringFieldEntry(_obj.PaymentNotes)); clause.InsertColumn("NameOnCard", DbMgr.CreateStringFieldEntry(_obj.PaymentNameOnCard)); clause.InsertColumn("CardNumber", DbMgr.CreateStringFieldEntry(_obj.PaymentCardNumber)); clause.InsertColumn("ExpiryDate", DbMgr.CreateStringFieldEntry(_obj.PaymentExpirationDate)); clause.InsertColumn("BSB", DbMgr.CreateStringFieldEntry(_obj.PaymentBSB)); string bank_account_number_text = _obj.PaymentBankAccountNumber; bank_account_number_text = bank_account_number_text.Replace("-", ""); int bank_account_number; if (int.TryParse(bank_account_number_text, out bank_account_number)) { clause.InsertColumn("AccountNumber", DbMgr.CreateIntFieldEntry(bank_account_number)); } clause.InsertColumn("AccountName", DbMgr.CreateStringFieldEntry(_obj.PaymentBankAccountName)); string statement_text = RepositoryMgr.DataFileInformationMgr.Company.CompanyName.ToUpper(); clause.InsertColumn("StatementText", DbMgr.CreateStringFieldEntry(statement_text)); clause.InsertColumn("ABN", DbMgr.CreateStringFieldEntry(_obj.ABN));; clause.InsertColumn("ABNBranch", DbMgr.CreateStringFieldEntry(_obj.ABNBranch)); if (_obj.ExpenseAccount != null) { string expense_account_number_text = _obj.ExpenseAccount.AccountNumber; expense_account_number_text = expense_account_number_text.Replace("-", ""); int expense_account_number; if (int.TryParse(expense_account_number_text, out expense_account_number)) { clause.InsertColumn("ExpenseAccount", DbMgr.CreateIntFieldEntry(expense_account_number)); } } if (_obj.PurchaseComment != null) { clause.InsertColumn("PurchaseComment", DbMgr.CreateStringFieldEntry(_obj.PurchaseComment.Text)); } if (_obj.ShippingMethod != null) { clause.InsertColumn("ShippingMethod", DbMgr.CreateStringFieldEntry(_obj.ShippingMethod.Method)); } if (_obj.FreightTaxCode != null) { clause.InsertColumn("FreightTaxCode", DbMgr.CreateStringFieldEntry(_obj.FreightTaxCode.Code)); } clause.InsertColumn("UseSuppliersTaxCode", DbMgr.CreateStringFieldEntry(_obj.UseSupplierTaxCode)); if (_obj.InvoiceDelivery != null) { clause.InsertColumn("PurchaseDelivery", DbMgr.CreateStringFieldEntry(_obj.InvoiceDelivery.InvoiceDeliveryID)); } clause.InsertColumn("PaymentMemo", DbMgr.CreateStringFieldEntry(_obj.PaymentMemo)); clause.Into("Import_Supplier_Cards"); DbCommand cmdSQLInsert = CreateDbCommand(clause); DbTransaction myTrans = DbMgr.DbConnection.BeginTransaction(); try { cmdSQLInsert.CommandText = clause.ToString(); cmdSQLInsert.Transaction = myTrans; cmdSQLInsert.ExecuteNonQuery(); myTrans.Commit(); } catch (OdbcException ex) { myTrans.Rollback(); Log(ex.Message); //Console.WriteLine(ex.ToString()); if (is_creating) { return(OpResult.NotifyStoreAction(OpResult.ResultStatus.CreatedWithException, _obj, ex.ToString())); } return(OpResult.NotifyStoreAction(OpResult.ResultStatus.UpdatedWithException, _obj, ex.ToString())); } catch (Exception ex) { Log(ex.Message); //Console.WriteLine(ex.ToString()); if (is_creating) { return(OpResult.NotifyStoreAction(OpResult.ResultStatus.CreatedWithException, _obj, ex.ToString())); } return(OpResult.NotifyStoreAction(OpResult.ResultStatus.UpdatedWithException, _obj, ex.ToString())); } _obj.FromDb = true; if (is_creating) { return(OpResult.NotifyStoreAction(OpResult.ResultStatus.Created, _obj)); } return(OpResult.NotifyStoreAction(OpResult.ResultStatus.Updated, _obj)); }
public static new OpResult AddRange(List <Sys.Entity.SysMenus> entities, bool isSave = true) { CurrentRepository.AddRange(entities, isSave); return(OpResult.Success()); }
/// <summary> /// 验证 /// </summary> /// <param name="nvl"></param> /// <param name="id"></param> /// <returns></returns> public OpResult Verification(System.Collections.Specialized.NameValueCollection nvl, int id, TradersStore tradersStore) { //商户号 var CID = (nvl["CID"] ?? "").Trim(); //门店名称 var StoreName = (nvl["StoreName"] ?? "").Trim(); if (CID != "") { if (!Tool.IsNumber(CID)) { return(OpResult.Fail("商户号不存在")); } else { int cid = Convert.ToInt32(CID); if (!payLicenseService.isExistByWhere(o => o.CID == cid)) { return(OpResult.Fail("该商户号未申请支付许可")); } else { if (!payLicenseService.isExistByWhere(o => o.CID == cid && o.State == (short)TraderPayLicenseState.Audited)) { return(OpResult.Fail("该商户号当前商户信息状态不是已审核,无法新增/修改门店")); } else if (!bankAccountService.isExistByWhere(o => o.CID == cid && o.State == (int)TraderBalanceAccountState.Enabled)) { return(OpResult.Fail("该商户号当前结算账户状态不是可用,无法新增/修改门店")); } else if (!tradersPaySecretKeyService.isExistByWhere(o => o.CID == cid && o.State == (int)TraderPayCchannelState.Enabled)) { return(OpResult.Fail("该商户号当前支付通道状态不是可用,无法新增/修改门店")); } else { var list = tradersService.getUserList().Where(o => o.UserId == tradersStore.AssignUID); if (!list.Any()) { return(OpResult.Fail("指派人不正确")); } if (id > 0) { if (isExistByWhere(o => o.CID == cid && o.StoreName == StoreName && o.Id != id)) { return(OpResult.Fail("该门店名称已经存在")); } } else { if (isExistByWhere(o => o.CID == cid && o.StoreName == StoreName)) { return(OpResult.Fail("该门店名称已经存在")); } } } } } } return(OpResult.Success()); }
private FileService.ReturnMessage ReturnResult(OpResult result) { if (result != OpResult.Succeed) { string resultText = string.Empty; switch (result) { case OpResult.AlreadyExist: resultText = Resource.FileSystemFileExists; break; case OpResult.Denied: resultText = Resource.AccessDenied; break; case OpResult.Error: default: resultText = Resource.GenericError; break; case OpResult.FileLimitExceed: resultText = Resource.FileSystemFileLimitReached; break; case OpResult.FileSizeLimitExceed: resultText = Resource.FileSystemFileSizeLimitReached; break; case OpResult.FileTypeNotAllowed: resultText = Resource.FileTypeNotAllowed; break; case OpResult.FolderLimitExceed: resultText = Resource.FileSystemFolderLimitReached; break; case OpResult.FolderNotFound: resultText = Resource.FileSystemFolderNotFound; break; case OpResult.NotFound: resultText = Resource.FileSystemFileNotFound; break; case OpResult.QuotaExceed: resultText = Resource.FileSystemQuotaExceeded; break; } return(new FileService.ReturnMessage { Success = false, Error = resultText }); } else { return(new FileService.ReturnMessage { Success = true }); } }
/// <summary> /// 状态 /// </summary> /// <param name="ids"></param> /// <param name="state">2是可用,3是被驳回,4是暂停,5是注销,6是无效</param> /// <returns></returns> public OpResult UpState(string ids, short state, string specific) { OpResult opr = ExistState(ids, state); if (!opr.Successed) { return(opr); } else { try { using (EFDbContext context = new EFDbContext()) { using (TransactionScope transaction = new TransactionScope()) { var idss = ids.Split(',').Select(o => int.Parse(o)); DateTime dt = DateTime.Now; string UID = CurrentUser.UID; UpListByWhere(o => idss.Contains(o.Id), o => { o.State = state; o.AuditDT = dt; o.AuditUID = UID; o.ModifyDT = dt; o.ModifyUID = UID; }); if (state == (short)TraderBalanceAccountState.Enabled) { var CIDS = GetListByWhere(o => idss.Contains(o.Id)).Select(o => o.CID); payLicenseService.UpAdmin(CIDS, 1); SaveChanges(); } var listLog = GetListByWhere(o => idss.Contains(o.Id)); foreach (var v in listLog) { ApproveLog approveLog = new ApproveLog(); approveLog.ModuleNum = Convert.ToInt16(ApproveLogNum.支付许可); approveLog.ItemId = v.LicenseId; approveLog.CreateTime = dt; if (state == 3) { approveLog.OperationType = Convert.ToInt16(ApproveLogType.驳回); } else { approveLog.OperationType = Convert.ToInt16(ApproveLogType.审批); } approveLog.OperatorUID = UID; if (state == 2) { approveLog.Description = "结算账户已被设为可用" + (specific == "" ? "" : ":" + specific); } else if (state == 3) { approveLog.Description = "结算账户被驳回" + (specific == "" ? "" : ":" + specific); } else if (state == 4) { approveLog.Description = "结算账户被暂停" + (specific == "" ? "" : ":" + specific); } else if (state == 5) { approveLog.Description = "结算账户被注销" + (specific == "" ? "" : ":" + specific); } else if (state == 6) { approveLog.Description = "结算账户被设为无效" + (specific == "" ? "" : ":" + specific); } //审核日志 approveLogService.InsertUpdate(approveLog, 0); } //提交事务 transaction.Complete(); return(OpResult.Success()); } } } catch (Exception e) { LogEngine.WriteError(e); return(OpResult.Fail(e.InnerException.InnerException.Message)); } } }
/// <summary> /// 删除一条设备报废记录 /// </summary> /// <param name="model"></param> /// <returns></returns> private OpResult DeleteEquipmentDiscardRecord(EquipmentDiscardRecordModel model) { OpResult result = OpResult.SetErrorResult("暂不提供删除方法"); return(result); }
/// <summary> /// 订单完成时更新会员积分、成长值、现金消费金额、会员等级 /// </summary> /// <param name="orderNo"></param> /// <returns></returns> public OpResult CompletedOrderUpdateMemberInfo(string orderNo) { var result = OpResult.Fail("订单完成时,更新会员信息失败"); try { var order = context.Orders.Where(o => o.No == orderNo && o.IsDeleted != 1).FirstOrDefault(); if (order.Status != OrderStatus.Completed) { result = OpResult.Fail("订单未完成,无法更新会员信息"); return(result); } var member = context.Customers.Where(o => o.Id == order.CustomerId && o.IsDeleted != 1).FirstOrDefault(); if (CommonRules.InternalAccount.Contains(member.Mobile)) {//公司内部账号,不累计积分和成长值 member.TotalActualRMBPay = member.TotalActualRMBPay + order.ActualPay; } else { var memberLevel = context.MemberLevel.Where(o => o.MemberLevelValue == member.MemberLevelValue && o.IsDeleted != 1).FirstOrDefault(); //保存增加积分记录 if ((int)(order.ActualPay * memberLevel.IntegralMultiples) > 0) { MemberIntegralLog memberIntegralLog = CreateNewMemberIntegralLog(order.CustomerId, order.No, (int)(order.ActualPay * memberLevel.IntegralMultiples), order.ActualPay, string.Format("完成订单,订单号:{0},增加{1}积分", order.No, (int)(order.ActualPay * memberLevel.IntegralMultiples))); memberIntegralLog.Id = CommonRules.GUID; context.MemberIntegralLog.Add(memberIntegralLog); } //保存增加成长值记录 if ((int)(order.ActualPay * memberLevel.GrowthValueMultiples) > 0) { MemberGrowthValueLog memberGrowthValueLog = CreateNewMemberGrowthValueLog(order.CustomerId, order.No, (int)(order.ActualPay * memberLevel.GrowthValueMultiples), order.ActualPay, string.Format("完成订单,订单号:{0},增加{1}成长值", order.No, (int)(order.ActualPay * memberLevel.GrowthValueMultiples))); memberGrowthValueLog.Id = CommonRules.GUID; context.MemberGrowthValueLog.Add(memberGrowthValueLog); } //更新会员信息(只计算现金支付部分)(先记录后更新,否则记录中会有两倍成长值) member.Integral = member.Integral + (int)(order.ActualPay * memberLevel.IntegralMultiples); member.GrowthValue = member.GrowthValue + (int)(order.ActualPay * memberLevel.GrowthValueMultiples); member.TotalActualRMBPay = member.TotalActualRMBPay + order.ActualPay; //更新会员等级(取可升级等级值的最大值) var newCurMemberLevel = context.MemberLevel.Where(o => o.MinGrowthValue <= member.GrowthValue && o.IsDeleted != 1).ToList(); if (newCurMemberLevel != null) { var curLevel = newCurMemberLevel.Max(o => o.MemberLevelValue); if (curLevel != member.MemberLevelValue) {//会员等级发生变化 member.UpdateMemberLevelTime = DateTime.Now; } member.MemberLevelValue = curLevel; } } context.SaveChanges(); result = OpResult.Success("更新会员信息成功"); } catch (Exception ex) { result = OpResult.Fail(string.Format("订单完成时,更新会员信息失败,订单号:{0},异常信息:{1}", orderNo, ex.Message)); } return(result); }
/// <summary> /// 修改一条设备报废记录 /// </summary> /// <param name="model"></param> /// <returns></returns> private OpResult EditEquipmentDiscardRecord(EquipmentDiscardRecordModel model) { OpResult result = OpResult.SetErrorResult("咱不提供修改方法"); return(result); }
private OpResult do_basic_list(OpResult or, WMPLib.IWMPStringCollection list, string list_type, string template, string default_template) { int result_count = list.count; or.AppendFormat("{0}", basic_replacer(getTemplate(template + ".H", ""), "", "", result_count, -1)); // Header string c_last = " "; for (int j = 0; j < list.count; j++) { string list_item = list.Item(j); if (list_item.Length > 0) { string s_out = ""; if (first_letter(list_item) != c_last) { if (j > 0) { s_out = getTemplate(template + ".Alpha-", ""); s_out = basic_replacer(s_out, list_type, list.Item(j - 1), result_count, j); s_out = basic_replacer(s_out, "letter", c_last, result_count, j); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); // Alpha- } c_last = first_letter(list_item); s_out = getTemplate(template + ".Alpha+", ""); s_out = basic_replacer(s_out, list_type, list_item, result_count, j); s_out = basic_replacer(s_out, "letter", c_last, result_count, j); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); // Alpha + } s_out = getTemplate(template + ".Entry", default_template); s_out = basic_replacer(s_out, list_type, list_item, result_count, j); s_out = basic_replacer(s_out, "letter", c_last, result_count, j); s_out = do_conditional_replace(s_out, "all_filters", request_params); s_out = do_conditional_replace(s_out, "genreFilter", genre_filter); s_out = do_conditional_replace(s_out, "artistFilter", artist_filter); s_out = do_conditional_replace(s_out, "albumFilter", album_filter); //opResult.AppendFormat("artist={0}", artists.Item(j)); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); // Entry } } if (result_count > 0) // Close the final alpha grouping { string s_out = getTemplate(template + ".Alpha-", ""); s_out = basic_replacer(s_out, list_type, list.Item(result_count - 1), result_count, result_count); s_out = basic_replacer(s_out, "letter", c_last, result_count, result_count); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); // Alpha- } return or; }
private void OnPwdValidate(OpResult rs) { this.HandleOpError(rs); }
/// <summary> /// /// </summary> /// <param name="obj"></param> /// <param name="httpFiles"></param> /// <param name="fieldName"></param> /// <param name="columnName"></param> /// <param name="fieldCols">字段和对应列</param> /// <param name="dt">导入表数据</param> /// <returns></returns> public static OpResult ImportSet(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName, ref Dictionary <string, char> fieldCols, ref System.Data.DataTable dt) { var op = new OpResult(); if (httpFiles.Count <= 0 || httpFiles[0].ContentLength <= 0) { op.Message = "请先选择Excel文件"; return(op); } var stream = httpFiles[0].InputStream; var ext = httpFiles[0].FileName.Substring(httpFiles[0].FileName.LastIndexOf(".")); if (!(ext.Equals(".xls", StringComparison.CurrentCultureIgnoreCase) || ext.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))) { op.Message = "请先选择Excel文件"; return(op); } var path = ""; var fullPath = Utility.Helpers.FileHelper.SaveAttachPath(ref path, "temps"); httpFiles[0].SaveAs(fullPath + httpFiles[0].FileName); fieldCols = fieldCols ?? new Dictionary <string, char>(); if (!fieldName.IsNullOrEmpty() && !columnName.IsNullOrEmpty()) { var fields = fieldName.Split(','); var columns = columnName.Split(','); if (fields.Length != columns.Length) { op.Message = "配置的字段和列数不一致!"; return(op); } for (var i = 0; i < fields.Length; i++) { if (columns[i].IsNullOrEmpty()) { continue; } fieldCols[fields[i]] = Convert.ToChar(columns[i]); } //if (fieldCols.Values.Distinct().Count() != fieldCols.Values.Count()) //{ // op.Message = "配置的列存在重复!"; // return op; //} obj.FieldJson = fieldCols.Select(o => new { o.Key, o.Value }).ToJson(); } if (obj.Id == 0) { if (!BaseService <ImportSet> .IsExist(o => o.TableName == obj.TableName && o.CompanyId == obj.CompanyId)) { op = BaseService <ImportSet> .Add(obj); } else { op.Successed = true; } } else { var res = BaseService <ImportSet> .FindById(obj.Id); obj.ToCopyProperty(res); op = BaseService <ImportSet> .Update(res); } if (!op.Successed) { return(op); } dt = new ExportExcel().ToDataTable(stream, minRow: obj.MinRow, maxRow: obj.MaxRow.GetValueOrDefault()); if (dt == null || dt.Rows.Count <= 0) { op.Message = "无数据,无法导入!"; op.Successed = false; return(op); } #region 去掉空格 foreach (DataColumn dc in dt.Columns) { if (dc.DataType == typeof(string)) { foreach (DataRow dr in dt.Rows) { if (!(dr[dc] is DBNull)) { dr[dc] = dr[dc].ToString().Trim(); } } } } #endregion #region 允许配置在同一列 var cols = fieldCols.GroupBy(o => o.Value).Where(o => o.Count() > 1).ToList();//取重复列 foreach (var item in cols) { System.Diagnostics.Debug.WriteLine(item.Key);//重复列value var idx = Convert.ToInt32(item.Key) - 65; foreach (var subitem in item) { System.Diagnostics.Debug.WriteLine(subitem.Key);//重复列key var lastValue = Convert.ToChar(fieldCols.Values.OrderBy(o => o).LastOrDefault() + 1); if (dt.Columns[idx].CloneTo(subitem.Key)) { fieldCols[subitem.Key] = lastValue; } } } #endregion op.Successed = true; return(op); }
public virtual OpResult Record() { OpResult result = _Record(); return(result); }
public FileService.ReturnObject UploadFiles() { FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { log.Error(string.Format(Resource.FileSystemProviderNotLoaded, WebConfigSettings.FileSystemProvider)); return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = string.Format(Resource.FileSystemProviderNotLoaded, WebConfigSettings.FileSystemProvider) })); } fileSystem = p.GetFileSystem(); if (fileSystem == null) { log.Error(string.Format(Resource.FileSystemNotLoadedFromProvider, WebConfigSettings.FileSystemProvider)); return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = string.Format(Resource.FileSystemNotLoadedFromProvider, WebConfigSettings.FileSystemProvider) })); } virtualPath = fileSystem.VirtualRoot; var context = HttpContext.Current; HttpFileCollection files = context.Request.Files.Count > 0 ? context.Request.Files : null; OpResult results = OpResult.Error; StringBuilder errors = new StringBuilder(); SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings(); string uploadPath = virtualPath; bool canUpload = ( WebUser.IsAdminOrContentAdmin || SiteUtils.UserIsSiteEditor() || WebUser.IsInRoles(siteSettings.GeneralBrowseAndUploadRoles) || WebUser.IsInRoles(siteSettings.UserFilesBrowseAndUploadRoles) || WebUser.IsInRoles(siteSettings.RolesThatCanDeleteFilesInEditor) ); if (files.Count == 0) { log.Info(Resource.NoFileSelectedWarning); return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = Resource.NoFileSelectedWarning })); } if (WebConfigSettings.DisableFileManager) { log.Info(Resource.FileManagerDisabledMessage); return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = Resource.FileManagerDisabledMessage })); } if (siteSettings == null) { return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = Resource.FileSystemSiteSettingsNotLoaded })); } if (!canUpload) { return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = Resource.AccessDenied })); } if (context.Request.Form.Get("destination") != null) { uploadPath = FilePath(VirtualPathUtility.AppendTrailingSlash(context.Request.Form.Get("destination"))); } if (files != null) { var fileUploadsRemaining = fileSystem.Permission.MaxFiles - fileSystem.CountAllFiles(); if (fileUploadsRemaining < files.Count) { log.Info("upload rejected due to fileSystem.Permission.MaxFiles"); string errorMessage; if (fileUploadsRemaining == 0) { errorMessage = Resource.FileSystemFileLimitReached; } else { errorMessage = string.Format(Resource.FileSystemFileLimitRemainder, fileUploadsRemaining); } return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = errorMessage })); } for (int f = 0; f < files.Count; f++) { HttpPostedFile file = files[f]; bool doUpload = true; if (file.ContentLength > fileSystem.Permission.MaxSizePerFile) { log.Info(Resource.FileSystemFileTooLargeError); errors.AppendLine(Resource.FileSystemFileTooLargeError); doUpload = false; } else if (fileSystem.GetTotalSize() + file.ContentLength >= fileSystem.Permission.Quota) { log.Info(Resource.FileSystemStorageQuotaError); errors.AppendLine(Resource.FileSystemStorageQuotaError); doUpload = false; } if (!fileSystem.Permission.IsExtAllowed(VirtualPathUtility.GetExtension(file.FileName))) { log.Info(Resource.FileTypeNotAllowed); errors.AppendLine(Resource.FileTypeNotAllowed); doUpload = false; } string destPath = VirtualPathUtility.Combine(uploadPath, Path.GetFileName(file.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles)); string ext = Path.GetExtension(file.FileName); string mimeType = file.ContentType; if (doUpload) { using (Stream s = file.InputStream) { results = fileSystem.SaveFile(destPath, s, mimeType, true); } if (results != OpResult.Succeed) { errors.AppendLine(results.ToString()); } } } if (errors.Length > 0) { return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = errors.ToString() })); } return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = true })); } else { return(new FileService.ReturnObject(new FileService.ReturnMessage { Success = false, Error = Resource.NoFileSelectedWarning })); } }
protected virtual OpResult _Delete() { return(OpResult.NotifyDeleteAction(OpResult.ResultStatus.NoActionTaken, null)); }
public OpResult SaveOrUpdate(Plans plan) { if (plan.Id.IsNullOrEmpty()) { plan.Id = Guid.NewGuid().ToString("N"); plan.CreateDT = DateTime.Now; plan.CreateUID = CurrentUser.UID; plan.Status = 375; PlanRepository.Add(plan, false); } else { var source = PlanRepository.GetQuery(o => o.Id == plan.Id).Include(o => o.Attachments).Include(o => o.Replys).FirstOrDefault(); plan.ToCopyProperty(source, new List <string>() { "CreateDT", "CreateUID", "Status" }); if (plan.Attachments != null) { source.Attachments.AddRange(plan.Attachments); } if (plan.Replys != null) { source.Replys.AddRange(plan.Replys); } } if (plan.Attachments != null) { string path = ""; string fullPath = FileHelper.SaveAttachPath(ref path); for (var i = plan.Attachments.Count - 1; i >= 0; i--) { var attach = plan.Attachments[i]; if (!attach.Bytes.Any()) { plan.Attachments.Remove(attach); continue; } attach.CreateDT = DateTime.Now; attach.CreateUID = CurrentUser.UID; attach.ItemId = plan.Id; attach.NewName = Guid.NewGuid().ToString("N") + "." + attach.ExtName; attach.Path = path; using (var fs = new FileStream(fullPath + attach.NewName, FileMode.OpenOrCreate)) { fs.Write(attach.Bytes, 0, attach.Bytes.Length); fs.Close(); } } } if (plan.Replys != null) { plan.Replys.Each(o => { o.CreateDT = DateTime.Now; o.Creater = CurrentUser.FullName; o.CreateUID = CurrentUser.UID; o.PlanId = plan.Id; }); } PlanRepository.SaveChanges(); return(OpResult.Success()); }
public OpResult ExportMemberCard(string ids) { //查询对应数据 try { #region MyRegion //var datas = _service.GetMakingMembershipCardByIds(ids); //var top1MemberCard = BaseService<MembershipCard>.CurrentRepository.Entities.OrderByDescending(o => o.CreateDT).FirstOrDefault(); //var oldCardNo = top1MemberCard.CardSN; //var currentCardNo = string.Empty; //int num = 0; //if (top1MemberCard != null && top1MemberCard.CardSN.Length > 6) //{ // oldCardNo = top1MemberCard.CardSN.Substring(top1MemberCard.CardSN.Length - 7, 7); // int.TryParse(oldCardNo, out num); //} ////统计当前的所有批次 //var batchs = string.Empty; ////生成相应会员卡信息 //foreach (var item in datas) //{ // //判断状态 0=未制卡 // if (item.State == 0) // { // batchs += "," + item.BatchSN; // //生成会员卡数据 // for (int i = 0; i < item.MakeNumber; i++) // { // num++; // currentCardNo = num.ToString(); // while (currentCardNo.Length < 7) // { // currentCardNo = currentCardNo.Insert(0, "0"); // } // var cardinfo = BaseService<CardInfo>.CurrentRepository.Entities.Where(o => o.CardTypeId == item.CardType).FirstOrDefault(); // var cardType = 1; // if (cardinfo != null) // { // if (cardinfo.CardType == 1) // { // cardType = 2; // } // } // //生成卡号:1位卡类型(1=固定面值;2=充值卡) 4位区号 7位商户号 7位序列号(港澳6位) // var cardSn = cardType + "3640" + "1000101" + currentCardNo; // var securitycode = ExtendHelper.GetRandomStr(7); // var isExit = BaseService<MakingMembershipCard>.CurrentRepository.Entities.Any(o => o.SecurityCode == securitycode); // while (isExit) // { // securitycode = ExtendHelper.GetRandomStr(7); // isExit = BaseService<MakingMembershipCard>.CurrentRepository.Entities.Any(o => o.SecurityCode == securitycode); // } // MembershipCard _memberCard = new MembershipCard() // { // CompanyId = CommonService.CompanyId, // BatchSN = item.BatchSN, // CardSN = cardSn, // CardType = cardinfo.CardTypeId, // ReChargeTotal = 0, // GiveTotal = 0, // Balance = 0, // Integer = 0, // Deposit = 0, // State = 0, // ExpiryStart = item.ExpiryStart, // ExpiryEnd = item.ExpiryEnd, // CreateDT = DateTime.Now, // CreateUID = Sys.CurrentUser.UID, // SecurityCode = securitycode, // ExportDT = DateTime.Now,//加入导出人,导出时间 // ExportUID = Pharos.Sys.CurrentUser.UID// // }; // BaseService<MembershipCard>.CurrentRepository.Add(_memberCard, false); // } // } //} //BaseService<MembershipCard>.CurrentRepository.Update(new MembershipCard()); #endregion var datas = _service.GetMakingMembershipCardByIds(ids); if (datas == null || datas.Count == 0) { return(new OpResult() { Successed = false, Message = "找不到原数据!" }); } StringBuilder batchs = new StringBuilder(); foreach (var item in datas) { batchs.Append("," + item.BatchSN); } //导出到excel new ExportExcel() { IsBufferOutput = true, HeaderText = title }.ToExcel(fileName, dt, fields.ToArray(), names.ToArray(), mergerCols, totalCols); string fileName = "会员卡" + DateTime.Now.ToString("HHmmss"); SqlParameter[] parms = { new SqlParameter("@batchs", batchs.ToString()), new SqlParameter("@companyId", Sys.SysCommonRules.CompanyId) }; string sql = "SELECT BatchSN,CardSN,c.CardName AS CardType,Balance,Deposit,ExpiryStart,ExpiryEnd,SecurityCode,s.FullName as ExportUID FROM dbo.MembershipCard AS m LEFT JOIN dbo.CardInfo AS c ON m.CardTypeId=c.CardTypeId LEFT JOIN dbo.SysUserInfo AS s ON m.ExportUID =s.UID where (( CAST(CHARINDEX(BatchSN, @batchs) AS int)) > 0) AND m.CompanyId=@companyId"; //var sql = BaseService<MembershipCard>.CurrentRepository.Entities.Where(o => o.CompanyId == CommonService.CompanyId && batchs.Contains(o.BatchSN)); var dataResult = new DBHelper().DataTableText(sql, parms); if (dataResult.Rows.Count == 0) { return(OpResult.Fail("当前无未导出数据!")); } string[] fields = { "BatchSN", "CardSN", "CardType", "Balance", "Deposit", "ExpiryStart", "ExpiryEnd", "SecurityCode", "ExportUID" }; string[] names = { "批次", "卡号", "卡类型", "可用金额", "押金", "有效期开始", "有效期截止", "防伪码", "导出人" }; var fileUrl = new ExportExcel() { IsBufferOutput = true }.ToExcel(fileName, dataResult, fields, names, null); //更新导出时间 SqlParameter[] param1 = { new SqlParameter("@batchs", batchs.ToString()), new SqlParameter("@UID", Sys.CurrentUser.UID), new SqlParameter("@companyId", CommonService.CompanyId) }; string updateSql = "UPDATE dbo.MembershipCard SET ExportDT=GETDATE(),ExportUID=@UID where (( CAST(CHARINDEX(BatchSN, @batchs) AS int)) > 0) AND CompanyId=@companyId"; new DBHelper().DataTableText(updateSql, param1); foreach (var item in datas) { StringBuilder _ids = new StringBuilder(); _ids.Append("," + item.Id); _service.UpdateState(2, ids); } return(new OpResult() { Successed = true, Message = "操作成功!", Data = fileUrl }); } catch (Exception e) { return(new OpResult() { Successed = false, Message = e.Message }); } }
public static OpResult Import(ImportSet obj, System.Web.HttpFileCollectionBase httpFiles, string fieldName, string columnName, short businessType) { var op = new OpResult(); var errLs = new List <string>(); int count = 0; try { Dictionary <string, char> fieldCols = null; DataTable dt = null; op = ImportSetService.ImportSet(obj, httpFiles, fieldName, columnName, ref fieldCols, ref dt); if (!op.Successed) { return(op); } var supplierClass = SysDataDictService.FindList(o => o.DicPSN == (int)DicType.供应商分类); var otherClass = supplierClass.FirstOrDefault(o => o.Title.StartsWith("其")); var suppliers = GetList(); var users = UserInfoService.GetList(); var max = SysDataDictService.GetMaxSN; var clsIdx = Convert.ToInt32(fieldCols["ClassifyId"]) - 65; var titleIdx = Convert.ToInt32(fieldCols["Title"]) - 65; var fulltitleIdx = Convert.ToInt32(fieldCols["FullTitle"]) - 65; var linkmanIdx = Convert.ToInt32(fieldCols["Linkman"]) - 65; var designeeIdx = Convert.ToInt32(fieldCols["Designee"]) - 65; count = dt.Rows.Count; for (int i = dt.Rows.Count - 1; i >= 0; i--) { try { var dr = dt.Rows[i]; var text = dr[clsIdx].ToString(); if (text.IsNullOrEmpty()) { errLs.Add("行号[" + i + "]供应商分类为空!"); dt.Rows.RemoveAt(i);//去除不导入 continue; } var cls = supplierClass.FirstOrDefault(o => o.Title == text); if (cls != null) { dr[clsIdx] = cls.DicSN.ToString(); } else { if (obj.RefCreate) { var data = new Sys.Entity.SysDataDictionary() { DicPSN = (int)DicType.供应商分类, DicSN = max++, Status = true, Title = text, CompanyId = CommonService.CompanyId }; SysDataDictService.Add(data); supplierClass.Add(data); dr[clsIdx] = data.DicSN.ToString(); } else if (otherClass != null) { dr[clsIdx] = otherClass.DicSN.ToString(); } else { errLs.Add("供应商分类[" + text + "]不存在!"); dt.Rows.RemoveAt(i);//去除不导入 continue; } } text = dr[designeeIdx].ToString(); var user = users.FirstOrDefault(o => o.FullName == text); if (user != null) { dr[designeeIdx] = user.UID; } else { errLs.Add("指派人[" + text + "]不存在!"); dt.Rows.RemoveAt(i); continue; } text = dr[titleIdx].ToString().Trim(); var fulltext = dr[fulltitleIdx].ToString().Trim(); var linkman = dr[linkmanIdx].ToString().Trim(); if (text.IsNullOrEmpty()) { errLs.Add("行号[" + text + "]简称为空!"); dt.Rows.RemoveAt(i); } else if (fulltext.IsNullOrEmpty()) { errLs.Add("简称[" + text + "]全称为空!"); dt.Rows.RemoveAt(i); } else if (linkman.IsNullOrEmpty()) { errLs.Add("简称[" + text + "]联系人为空!"); dt.Rows.RemoveAt(i); } else if (suppliers.Any(o => o.Title == text)) { errLs.Add("简称[" + text + "]已存在!"); dt.Rows.RemoveAt(i); } else if (suppliers.Any(o => o.FullTitle == fulltext)) { errLs.Add("全称[" + fulltext + "]已存在!"); dt.Rows.RemoveAt(i); } else { suppliers.Add(new Supplier() { Title = text, FullTitle = fulltext }); } } catch (Exception e) { throw new Exception("供应商分类处理失败!", e); } } StringBuilder sb = new StringBuilder(); sb.Append("begin tran "); foreach (DataRow dr in dt.Rows) { sb.Append("insert into Supplier"); sb.Append("(CompanyId,BusinessType,Id,"); sb.Append(string.Join(",", fieldCols.Keys)); sb.Append(") values("); sb.AppendFormat("{0},", obj.CompanyId); sb.AppendFormat(businessType + ","); sb.AppendFormat("'{0}',", CommonRules.GUID); foreach (var de in fieldCols) { var index = Convert.ToInt32(de.Value) - 65; try { var text = dr[index].ToString(); sb.Append("'" + text + "',"); } catch (Exception e) { throw new Exception("列选择超过范围!", e); } } sb = sb.Remove(sb.Length - 1, 1); sb.Append(");"); } sb.Append(" commit tran"); op.Successed = new Pharos.Logic.DAL.CommonDAL()._db.ExecuteNonQueryText(sb.ToString(), null) > 0; log.WriteInsert(obj.TableName == "Supplier" ? "供应商导入" : "批发商导入", Pharos.Sys.LogModule.档案管理); } catch (Exception ex) { op.Message = ex.Message; op.Successed = false; Log.WriteError(ex); errLs.Add("导入出现异常!"); } return(CommonService.GenerateImportHtml(errLs, count)); }
public ActionResult CreateOrder(CreateOrderModel createOrderModel) { string msg = ""; Orders order = null; bool check = true; OpResult result = new OpResult { }; var cartIDs = CookieHelper.GetCookieValue("cartids").Split(',').ToList(); List <string> couponDetailIdList = null; List <string> giftCardDetailIdList = null; if (!string.IsNullOrEmpty(createOrderModel.CouponDetailIds)) { couponDetailIdList = createOrderModel.CouponDetailIds.Split(',').ToList(); } if (!string.IsNullOrEmpty(createOrderModel.GiftCardDetailIds)) { giftCardDetailIdList = createOrderModel.GiftCardDetailIds.Split(',').ToList(); } #region 验证 var validateResult = osv.ValidateOrderIsAllowCreate(createOrderModel); if (validateResult.Successed == false) { check = false; msg = validateResult.Message; } #endregion ViewBag.msg = msg; if (check) { string userid = CurrentMember.MemberId.ToString(); Action <Orders> setAddress; #region if (createOrderModel.RdType == DeliveryType.D2D) { setAddress = osv.SetOrderAddress(a => a.Id.Equals(createOrderModel.AddressId, StringComparison.OrdinalIgnoreCase)); } else { setAddress = osv.SetOrderAddress(null, a => a.Id.Equals(createOrderModel.LogistId, StringComparison.OrdinalIgnoreCase), createOrderModel.Name, createOrderModel.Mobile); } #endregion result = osv.CreateOrder( //客户 a => a.Id.Equals(userid), //设置地址 setAddress, //订单产品 a => { return(osv.GetOrderDetailsByCarts(a, cartIDs)); }, //发票 null, //订单编辑 a => { a.OrderSource = OrderSource.OnlineOrder; a.Candle = createOrderModel.Candle; a.RequiredTime = createOrderModel.Time; a.FeeType = createOrderModel.FeeType; a.CouponPay = createOrderModel.CouponPay; a.GiftCardPay = createOrderModel.GiftCardPay; a.IntegralPay = createOrderModel.IntegralPay; a.UsedIntegralVal = createOrderModel.UsedIntegralVal; a.DeliverMsg = createOrderModel.DeliverMsg; }, //用户 userid , 0, createOrderModel.TimeBucket, couponDetailIdList, giftCardDetailIdList, createOrderModel.OrderTotalAmount); ViewBag.msg = result.Message; } if (check == false || result.Successed == false) { return(Content(string.Format(@"<script>alert('{0}'); window.location.href='/cart/settlement'</script>", string.IsNullOrEmpty(ViewBag.msg) ? "" : ViewBag.msg))); //return Redirect("/cart/settlement"); } order = (Orders)result.Data; new CartService().RemoveCart(cartIDs); if (order.NeedPay == 0) { return(Redirect("/cart/OrderConfirm/" + order.No)); } if (order.FeeType == FeeType.WXPay && order.TradeStatus == TradeStatus.NotPay) { return(Redirect("/Tenpay/GetPayUrl/" + order.No)); } return(Redirect("/cart/OrderConfirm/" + order.No)); }
public static OpResult SaveOrUpdate(Supplier obj) { var re = new OpResult(); var classify = SysDataDictService.GetSupplierTypes(); List <SysUserInfo> list = new List <SysUserInfo>(); string desig = GetUser(obj.Designee, list); string stateTitle = obj.MasterState == 1 ? "可用" : "关闭"; obj.CompanyId = CommonService.CompanyId; if (!obj.MasterAccount.IsNullOrEmpty() && SupplierService.IsExist(o => o.Id != obj.Id && o.MasterAccount == obj.MasterAccount && o.BusinessType == 1 && o.CompanyId == obj.CompanyId)) { re.Message = "账号已存在"; } else if (!obj.Title.IsNullOrEmpty() && SupplierService.IsExist(o => o.Id != obj.Id && o.Title == obj.Title && o.BusinessType == 1 && o.CompanyId == obj.CompanyId)) { re.Message = "供应商简称已存在"; } else if (!obj.FullTitle.IsNullOrEmpty() && SupplierService.IsExist(o => o.Id != obj.Id && o.FullTitle == obj.FullTitle && o.BusinessType == 1 && o.CompanyId == obj.CompanyId)) { re.Message = "供应商全称已存在"; } else if (obj.Id.IsNullOrEmpty()) { obj.Id = Logic.CommonRules.GUID; obj.BusinessType = 1; re = SupplierService.Add(obj); #region 写入日志 string msg = "成功新增供应商!"; var module = Pharos.Sys.LogModule.档案管理; if (re.Successed) { string designee = (string.IsNullOrEmpty(obj.Designee) && string.IsNullOrEmpty(desig)) ? "" : ",指派人=" + desig; string phoneNum = string.IsNullOrEmpty(obj.MobilePhone) ? "" : ",手机=" + obj.MobilePhone; string telNum = string.IsNullOrEmpty(obj.Tel) ? "" : ",电话=" + obj.Tel; string email = string.IsNullOrEmpty(obj.Email) ? "" : ",邮箱=" + obj.Email; string address = string.IsNullOrEmpty(obj.Address) ? "" : ",地址=" + obj.Address; msg += "<br />Id=" + obj.Id + ","; msg += "<br />分类=" + GetTitle(classify, obj.ClassifyId) + designee + ",简称=" + obj.Title + ",全称=" + obj.FullTitle + ",联系人=" + obj.Linkman + phoneNum + telNum + email + address + ",账号=" + obj.MasterAccount + ",状态=" + stateTitle + "。"; } else { msg = "新增供应商失败!"; } log.WriteInsert(msg, module); #endregion } else { var supp = SupplierService.FindById(obj.Id); var exc = new List <string>(); if (obj.MasterPwd.IsNullOrEmpty()) { exc.Add("MasterPwd"); } exc.Add("CompanyId"); var isUpdateClassify = obj.ClassifyId != supp.ClassifyId; var isUpdateDesignee = obj.Designee != supp.Designee; var isUpdateLinkman = obj.Linkman != supp.Linkman; var isUpdatePhone = obj.MobilePhone != supp.MobilePhone; var isUpdateTel = obj.Tel != supp.Tel; var isUpdateEmail = obj.Email != supp.Email; var isUpdateAddress = obj.Address != supp.Address; var isUpdateState = obj.MasterState != supp.MasterState; var isUpdatePwd = string.IsNullOrEmpty(obj.MasterPwd) ? false : (obj.MasterPwd != supp.MasterPwd); bool isUpdate = isUpdateClassify || isUpdateDesignee || isUpdateLinkman || isUpdatePhone || isUpdateTel || isUpdateEmail || isUpdateAddress || isUpdatePwd || isUpdateState; obj.ToCopyProperty(supp, exc); re = SupplierService.Update(supp); #region 写入日志 string msg = "成功修改供应商!"; var module = Pharos.Sys.LogModule.档案管理; if (re.Successed) { int n = 0; if (isUpdate) { msg += "<br />Id=" + obj.Id + ",<br />"; if (isUpdateClassify) { var classifyTitle = GetTitle(classify, obj.ClassifyId); msg += "分类=" + classifyTitle; n = n + 1; } if (isUpdateDesignee) { msg += n > 0 ? ",指派人=" + desig : "指派人=" + desig; n = n + 1; } if (isUpdateLinkman) { msg += n > 0 ? ",联系人=" + obj.Linkman : "联系人=" + obj.Linkman; n = n + 1; } if (isUpdatePhone) { msg += n > 0 ? ",手机=" + obj.MobilePhone : "手机=" + obj.MobilePhone; n = n + 1; } if (isUpdateTel) { msg += n > 0 ? ",电话=" + obj.Tel : "电话=" + obj.Tel; n = n + 1; } if (isUpdateEmail) { msg += n > 0 ? ",邮箱=" + obj.Email : "邮箱=" + obj.Email; n = n + 1; } if (isUpdateAddress) { msg += n > 0 ? ",地址=" + obj.Address : "地址=" + obj.Address; n = n + 1; } if (isUpdateState) { msg += n > 0 ? ",状态=" + stateTitle : "状态=" + stateTitle; n = n + 1; } if (isUpdatePwd) { msg += n > 0 ? ",并修改了密码" : "修改了密码"; } msg += "。"; log.WriteUpdate(msg, module); } } else { msg = "修改供应商失败!"; log.WriteUpdate(msg, module); } #endregion } return(re); }
private FileService.ReturnMessage MoveOrRename(string origin, string dest, bool move = false) { try { OpResult result = OpResult.NotFound; string dir = VirtualPathUtility.GetDirectory(dest); string destination = dir + Path.GetFileName(dest); if (!move) { switch (FolderOrFile(origin)) { case "folder": result = fileSystem.MoveFolder(FilePath(origin, false, true), FilePath(dir + "/" + CleanFileName(destination, "folder"), false, true)); break; case "file": if (AllowedExtension(origin) && AllowedExtension(dest)) { result = fileSystem.MoveFile(FilePath(origin), FilePath(dir + "/" + CleanFileName(dest, "file")), overwriteExistingFiles); } else { result = OpResult.FileTypeNotAllowed; } break; } } else { switch (FolderOrFile(origin)) { case "folder": string org = FilePath(origin, false, true); string des = FilePath(destination + "/" + CleanFileName(origin, "folder"), false, true); result = fileSystem.MoveFolder(org, des); break; case "file": if (AllowedExtension(origin) && FolderOrFile(dest) == "folder") { result = fileSystem.MoveFile(FilePath(origin), FilePath(destination + "/" + CleanFileName(origin, "file")), false); } else { result = OpResult.FileTypeNotAllowed; } break; } } return(ReturnResult(result)); } catch (Exception ex) { log.Error(ex); return(new FileService.ReturnMessage { Success = false, Error = ex.ToString() }); } }
/// <summary> /// 从网页上保存地址 /// </summary> /// <param name="currentUserID"></param> /// <param name="address"></param> /// <returns></returns> public OpResult SaveWebCustomerAddress(string currentUserID, CustomerAddress address) { OpResult result = new OpResult(); result.Successed = false; try { CustomerAddress custAddress = new CustomerAddress(); bool isExist = address.Id.IsNotNullOrEmpty();//false为add,true为update var addresses = context.CustomerAddress.Where(a => a.CustomerId.Equals(currentUserID) && a.IsDeleted != 1); if (address.Id.IsNullOrTrimEmpty()) { //Add if (addresses.Count() >= 10) { throw new Exception("最多保存10条收获地址"); } custAddress.Id = custAddress.NewGuid(); custAddress.CreatedBy = currentUserID; custAddress.CreatedOn = DateTime.Now; } else { //update if (address.LogisticsSiteId.IsNotNullOrEmpty()) { //原为自提则判断地址是否修改,修改则add var site = context.LogisticsSite.SingleOrDefault(l => l.Id.Equals(address.LogisticsSiteId) && l.IsDeleted != 1); if (address.Province != site.SiteProvince || address.City != site.SiteCity || address.Area != site.SiteArea || address.Address != site.SiteAddress) { custAddress.Id = custAddress.NewGuid(); custAddress.CreatedBy = currentUserID; custAddress.CreatedOn = DateTime.Now; } } else { custAddress = context.CustomerAddress.SingleOrDefault(a => a.Id.Equals(address.Id) && a.IsDeleted != 1); if (custAddress != null) { custAddress.ModifiedBy = currentUserID; custAddress.ModifiedOn = DateTime.Now; } } //默认地址不能在修改时改为非默认 if (custAddress.IsDef == 0 && address.IsDef == 1) { throw new Exception("保存失败!请先设其他地址为默认地址"); } } //custAddress.Id = custAddress.NewGuid(); //custAddress.CreatedBy = currentUserID; //custAddress.CreatedOn = DateTime.Now; custAddress.CustomerId = currentUserID; custAddress.IsDeleted = 0; if (address.IsDef == 0) { foreach (var addr in addresses) { addr.IsDef = 1; } custAddress.IsDef = 0; } else { custAddress.IsDef = 1; } //收货人不能为空 #region if (address.Receiver.IsNullOrTrimEmpty()) { throw new Exception("收货人不能为空"); } if (address.Receiver.Length > 20) { throw new Exception("收货人名称过长"); } custAddress.Receiver = address.Receiver; #endregion //地区不能为空 #region if (address.Province.IsNullOrTrimEmpty()) { throw new Exception("省份不能为空"); } if (address.Province.Length > 10) { throw new Exception("省份名称过长"); } custAddress.Province = address.Province; if (address.City.IsNullOrTrimEmpty()) { throw new Exception("城市不能为空"); } if (address.City.Length > 10) { throw new Exception("城市名称过长"); } custAddress.City = address.City; if (address.Area.IsNullOrTrimEmpty()) { throw new Exception("地区不能为空"); } if (address.Area.Length > 10) { throw new Exception("地区名称过长"); } custAddress.Area = address.Area; #endregion //街道地址不能为空 #region if (address.Address.IsNullOrTrimEmpty()) { throw new Exception("街道地址不能为空"); } if (address.Address.Length > 100) { throw new Exception("街道地址过长"); } custAddress.Address = address.Address; #endregion //手机与固定电话 #region if (address.ReceiverTel.IsNullOrTrimEmpty() && address.ReceiverMobile.IsNullOrTrimEmpty()) { throw new Exception("手机或固定电话至少填写一项"); } if (address.ReceiverTel.Length > 20) { throw new Exception("固定电话过长"); } if (address.ReceiverMobile.Length > 20) { throw new Exception("手机号码过长"); } custAddress.ReceiverTel = address.ReceiverTel; custAddress.ReceiverMobile = address.ReceiverMobile; #endregion //邮编 custAddress.ZipCode = address.ZipCode; if (isExist == false) { context.CustomerAddress.Add(custAddress); } if (context.SaveChanges() > 0) { result.Successed = true; result.Data = custAddress; } return(result); } catch (Exception ex) { result.Message = ex.Message; return(result); } }
/// <summary> /// 将实时考勤数据转移至本月数据表中 /// </summary> /// <returns></returns> public OpResult TransimitAttendDatas(DateTime qryDate) { qryDate = qryDate.ToDate(); //处理总记录数 int totalRecord = 0, record = 0; var datasInTime = this.fingerPrintDataInTime.FingPrintDatas.FindAll(e => e.SlodCardDate == qryDate); if (datasInTime == null || datasInTime.Count == 0) { return(OpResult.SetErrorResult("没有考勤数据要进行汇总")); } AttendanceDbHelpHandler.BackupData(datasInTime); //一次载入该日期的所有考勤数据到内存中 var dayAttendDatas = this.irep.Entities.Where(e => e.AttendanceDate == qryDate); //获取所有人员信息到内存中 var workers = AttendanceDbHelpHandler.GetWorkerInfos(); var departments = AttendanceDbHelpHandler.GetDepartmentDatas(); //中间时间 DateTime middleTime = new DateTime(qryDate.Year, qryDate.Month, qryDate.Day, 13, 0, 0); //处理实时考勤数据 ArWorkerInfo worker = null; //将考勤中数据中的人进行分组 List <string> attendWorkerIdList = datasInTime.Select(e => e.WorkerId).Distinct().ToList(); ClassTypeModel ctmdl = null; DepartmentModel depm = null; attendWorkerIdList.ForEach(workerId => { record = 0; //获取每个人的信息 worker = workers.FirstOrDefault(w => w.WorkerId == workerId); if (worker == null) { var m = ArchiveService.ArchivesManager.WorkerIdChangeManager.GetModel(workerId); if (m != null) { worker = workers.FirstOrDefault(w => w.WorkerId == m.NewWorkerId); } } //从实时考勤数据表中获取该员工的考勤数据 var attendDataPerWorker = datasInTime.FindAll(f => f.WorkerId == workerId).OrderBy(o => o.SlodCardTime).ToList(); var currentAttendData = dayAttendDatas.FirstOrDefault(e => e.WorkerId == workerId);//从内存中进行查找 if (worker != null) { ctmdl = AttendanceDbHelpHandler.GetClassType(workerId, qryDate); depm = departments.FirstOrDefault(d => d.DataNodeName == worker.Department); worker.ClassType = ctmdl == null ? "白班" : ctmdl.ClassType; worker.Department = depm == null ? worker.Department : depm.DataNodeText; int len = attendDataPerWorker.Count; for (int i = 0; i < len; i++) { var attendance = attendDataPerWorker[i]; //如果考勤数据表没有该人员的考勤数据 if (currentAttendData == null) { //则初始化考勤数据 record += InitAttendData(attendance, worker, attendance.SlodCardTime, out currentAttendData, middleTime); } else { //反之则合并数据 record += MergeAttendTime(currentAttendData, attendance.SlodCardTime); } } if (record == len)//如果处理记录与目标数量一致则进行备份数据 { this.fingerPrintDataInTime.BackupData(attendDataPerWorker, record); //从内存中移除数据,减少查询时间 //workers.Remove(worker); //从内存中移除该人员的考勤数据,减少查询时间 attendDataPerWorker.ForEach(m => datasInTime.Remove(m)); totalRecord += record; } } else { this.fingerPrintDataInTime.StoreNoIdentityWorkerInfo(attendDataPerWorker[0]); } }); return(OpResult.SetSuccessResult("处理考勤数据成功!", record > 0)); }
public OpResult Execute(RemotedWindowsMediaPlayer remotePlayer, string param) { OpResult opResult = new OpResult(); try { if (MediaExperienceWrapper.Instance == null || remotePlayer.getPlayState() == WMPPlayState.wmppsUndefined) { opResult.StatusCode = OpStatusCode.BadRequest; opResult.StatusText = "No media playing"; } else if (m_set) { if (param.Equals("")) { throw new Exception("Not a supported playrate!"); } PlayRateEnum playRate = (PlayRateEnum)Enum.Parse(typeof(PlayRateEnum), param, true); switch (playRate) { case PlayRateEnum.Pause: remotePlayer.getPlayerControls().pause(); break; case PlayRateEnum.Play: remotePlayer.getPlayerControls().play(); break; case PlayRateEnum.Stop: remotePlayer.getPlayerControls().stop(); break; case PlayRateEnum.FR: if (remotePlayer.getPlayerControls().get_isAvailable("FastReverse")) { remotePlayer.getPlayerControls().fastReverse(); } else { throw new Exception("Not supported"); } break; case PlayRateEnum.FF: if (remotePlayer.getPlayerControls().get_isAvailable("FastForward")) { remotePlayer.getPlayerControls().fastForward(); } else { throw new Exception("Not supported"); } break; case PlayRateEnum.SkipBack: remotePlayer.getPlayerControls().previous(); break; case PlayRateEnum.SkipForward: remotePlayer.getPlayerControls().next(); break; default: throw new Exception("Not a supported playrate!"); } opResult.StatusCode = OpStatusCode.Success; } else { WMPPlayState state = remotePlayer.getPlayState(); //string value = Enum.GetName(typeof(WMPPlayState), state).Remove(0, 5); PlayStateObject pObject = new PlayStateObject(); pObject.play_state = CurrentState.getTruncatedPlayState(remotePlayer.getPlayState()); opResult.StatusCode = OpStatusCode.Success; opResult.ContentObject = pObject; } } catch (Exception ex) { opResult.StatusCode = OpStatusCode.Exception; opResult.StatusText = ex.Message; } return(opResult); }
public static new OpResult Delete(List <Sys.Entity.SysMenus> list) { CurrentRepository.RemoveRange(list); return(OpResult.Success()); }
protected virtual OpResult _Record() { return(OpResult.NotifyStoreAction(OpResult.ResultStatus.NoActionTaken, null)); }
/// <summary> /// 验证订单是否允许被创建 /// </summary> /// <param name="createOrderModel"></param> /// <returns></returns> public OpResult ValidateOrderIsAllowCreate(CreateOrderModel createOrderModel) { var result = OpResult.Success(); if (createOrderModel.RdType == DeliveryType.FixedSite) { if (createOrderModel.Name.IsNullOrTrimEmpty()) { result = OpResult.Fail("提货人名称不能为空"); return(result); } if (createOrderModel.Mobile.IsNullOrTrimEmpty()) { result = OpResult.Fail("提货人手机不能为空"); return(result); } if (createOrderModel.Mobile.IsMobile()) { result = OpResult.Fail("提货人手机格式不正确"); return(result); } } #region 验证优惠部分 List <string> couponIdList = null; if (!string.IsNullOrEmpty(createOrderModel.CouponDetailIds)) { couponIdList = createOrderModel.CouponDetailIds.Split(',').ToList(); var isHasRepetition = couponIdList.GroupBy(o => o).Where(g => g.Count() > 1).Count() > 0; if (isHasRepetition == true) { result = OpResult.Fail("不能重复使用同一张优惠券"); return(result); } } List <string> giftCardIdList = null; if (!string.IsNullOrEmpty(createOrderModel.GiftCardDetailIds)) { giftCardIdList = createOrderModel.GiftCardDetailIds.Split(',').ToList(); var isHasRepetition = giftCardIdList.GroupBy(o => o).Where(g => g.Count() > 1).Count() > 0; if (isHasRepetition == true) { result = OpResult.Fail("不能重复使用同一张代金卡"); return(result); } } //验证优惠券是否可以使用 result = _couponsService.ValidateCouponDetailsIsAllowUse(couponIdList); if (result.Successed == false) { return(result); } //验证代金卡是否可以使用 result = _giftCardDetailService.ValidateGiftCardDetailAllowUse(giftCardIdList); if (result.Successed == false) { return(result); } #endregion return(result); }
public ActionResult UploadImgs(string productId) { OpResult result = null; productId = ReplaceProductId(productId); var files = Request.Files; //var maxFile = 1024 * 1024; var dir = "/Files/" + DateTime.Now.ToString("yyyyMMdd") + "/"; var dirPath = Server.MapPath(dir); if (Directory.Exists(dirPath) == false) { Directory.CreateDirectory(dirPath); } if (files.Count > 0) { var entities = new List <BaseFile>(); var bfService = new BaseFileService(); foreach (var fileKey in files.AllKeys) { var index = fileKey.Split('_')[1].ToInt32(); var file = files[fileKey]; BaseFile entity = null; if (file != null) { // Verify that the user selected a file if (file != null && file.ContentLength > 0) { entity = new BaseFile(); // extract only the fielname entity.OldName = Path.GetFileName(file.FileName); entity.SuffixName = GetSuffix(entity.OldName); entity.NewName = DataHelper.GetSystemID() + "." + entity.SuffixName; entity.Url = dir + entity.NewName; entity.Sorting = index; string filePath = dirPath + entity.NewName; var minFilePath = filePath + "_min" + ".jpg"; var middleFilePath = filePath + "_middle" + ".jpg"; // TODO: need to define destination //var path = Path.Combine(Server.MapPath("~/Files"), fileName); file.SaveAs(filePath); PictureHelper.MakeThumbnail(filePath, minFilePath, 200, 200, "Cut"); PictureHelper.MakeThumbnail(filePath, middleFilePath, 280, 280, "Cut"); } entities.Add(entity); } } var result1 = bfService.SaveBaseFiles(entities, productId, UserCache.CurrentUser.Id); if (result1 != null) { result = OpResult.Success("上传成功", "", result1); } else { result = OpResult.Fail("上传失败"); } } else { result = OpResult.Fail("没有可上传的文件"); } return(Json(result)); }
/// <summary> /// 设置设备校验日期规则 /// </summary> /// <param name="model"></param> /// <returns></returns> private OpResult SetEquipmentCheckDateRule(EquipmentCheckRecordModel model, EquipmentModel equipment) { equipment.CheckDate = model.CheckDate; equipment.OpSign = OpMode.Edit; return(OpResult.SetResult("更新设备校验日期成功!", "更新设备校验日期失败!", EquipmentCrudFactory.EquipmentCrud.Store(equipment).Result)); }
protected override OpResult _Store(AuthRole _obj) { if (_obj == null) { return(OpResult.NotifyStoreAction(OpResult.ResultStatus.ObjectIsNull, _obj, "AuditTrail object cannot be created as it is null")); } if (Exists(_obj)) { ExecuteNonQuery(GetQuery_UpdateQuery(_obj)); RemoveRoleItem(_obj); RemoveRoleRole(_obj); InsertRoleItem(_obj); InsertRoleRole(_obj); return(OpResult.NotifyStoreAction(OpResult.ResultStatus.Updated, _obj)); } DbInsertStatement clause = null; clause = DbMgr.CreateInsertClause(); Dictionary <string, DbFieldEntry> fields = GetFields(_obj); clause .InsertColumns(fields) .Into("AuthRole"); ExecuteNonQuery(clause); if (_obj.RoleID == null) { _obj.RoleID = DbMgr.GetLastInsertID(); } foreach (AuthRole child_role in _obj.Children) { Store(child_role); DbSelectStatement select_statement = DbMgr.CreateSelectClause(); select_statement .SelectCount() .From("AuthRoleRole") .Criteria .IsEqual("AuthRoleRole", "ParentRoleID", _obj.RoleID) .IsEqual("AuthRoleRole", "ChildRoleID", child_role.RoleID); bool relationship_not_found = ExecuteScalarInt(select_statement) == 0; if (relationship_not_found) { clause = DbMgr.CreateInsertClause(); clause .InsertColumn("ParentRoleID", DbMgr.CreateIntFieldEntry(_obj.RoleID)) .InsertColumn("ChildRoleID", DbMgr.CreateIntFieldEntry(child_role.RoleID)) .InsertColumn("Description", DbMgr.CreateStringFieldEntry(string.Format("{0} is superset of {1}", _obj.RoleName, child_role.RoleName))) .Into("AuthRoleRole"); ExecuteNonQuery(clause); } } foreach (AuthItem item in _obj.ForbiddenItems) { DbSelectStatement select_statement = DbMgr.CreateSelectClause(); select_statement .SelectCount() .From("AuthRoleItem") .Criteria .IsEqual("AuthRoleItem", "RoleID", _obj.RoleID) .IsEqual("AuthRoleItem", "ItemID", item.ItemID); bool relationship_not_found = ExecuteScalarInt(select_statement) == 0; if (relationship_not_found) { clause = DbMgr.CreateInsertClause(); clause .InsertColumn("RoleID", DbMgr.CreateIntFieldEntry(_obj.RoleID)) .InsertColumn("ItemID", DbMgr.CreateIntFieldEntry(item.ItemID)) .InsertColumn("Description", DbMgr.CreateStringFieldEntry(string.Format("{0} can act on {1}", _obj.RoleName, item.ItemName))) .Into("AuthRoleItem"); ExecuteNonQuery(clause); } } _obj.FromDb = true; return(OpResult.NotifyStoreAction(OpResult.ResultStatus.Created, _obj)); }
public OpResult showHelp(OpResult or) { or.AppendFormat("music-list-artists [~filters~] [~custom-template~] - lists all matching artists"); or.AppendFormat("music-list-album-artists [~filters~] [~custom-template~] - lists all matching album artists - See WARNING"); or.AppendFormat("music-list-songs [~filters~] [~custom-template~] - lists all matching songs"); or.AppendFormat("music-list-albums [~filters~] [~custom-template~] - lists all matching albums"); or.AppendFormat("music-list-genres [~filters~] [~custom-template~] - lists all matching genres"); or.AppendFormat("music-play [~filters~] [~index-list~] - plays all matching songs"); or.AppendFormat("music-queue [~filters~] [~index-list~] - queues all matching songs"); or.AppendFormat("music-cover [~filters~] [~index-list~] [size-x:width] [size-y:height] - serves the cover image (first match)"); or.AppendFormat(" "); or.AppendFormat("Where:"); or.AppendFormat(" [~filters~] is one or more of: [~artist-filter~] [~album-filter~] [~genre-filter~] "); or.AppendFormat(" [~artist-filter~] is one of:"); or.AppendFormat(" artist:<text> - matches track artists that start with <text> (\"artist:ab\" would match artists \"ABBA\" and \"ABC\")"); or.AppendFormat(" artist:*<text> - matches track artists that have any words that start with <text> (\"artist:*ab\" would match \"ABBA\" and \"The Abstracts\")"); or.AppendFormat(" exact-artist:<text> - matches the track artist that exactly matches <text> (\"exact-artist:ab\" would only match an artist names \"Ab\")"); or.AppendFormat(" [~album-filter~] is one of:"); or.AppendFormat(" album:<text> - matches albums that start with <text> (\"album:ab\" would match the album \"ABBA Gold\" and \"Abbey Road\")"); or.AppendFormat(" exact_album:<text> - matches the album exactly named <text> (\"exact_album:ab\" would only match an album named \"Ab\")"); or.AppendFormat(" [~genre-filter~] is one of:"); or.AppendFormat(" genre:<text> - matches genre that start with <text> (\"genre:ja\" would match the genre \"Jazz\")"); or.AppendFormat(" genre:*<text> - matches genres that contain <text> (\"genre:*rock\" would match \"Rock\" and \"Alternative Rock\")"); or.AppendFormat(" exact_genre:<text> - matches the genere exactly named <text> (\"exact_genre:ja\" would only match an genre named \"Ja\")"); or.AppendFormat(" [~index-list~] is of the form:"); or.AppendFormat(" indexes:idx1,idx2... - specifies one or more specific songs returned by the filter"); or.AppendFormat(" Where idx1,idx2... is a comma separated list with no spaces (e.g. 'indexes:22,23,27')"); or.AppendFormat(" [~custom-template~] is of the form:"); or.AppendFormat(" template:<name> - specifies a custom template <name> defined in the \"music.template\" file"); or.AppendFormat(" [size-x:~width~] - Resizes the served image, where ~width~ is the max width of the served image"); or.AppendFormat(" [size-y:~height~] - Resizes the served image, where ~height~ is the max height of the served image"); or.AppendFormat(" "); or.AppendFormat("Parameter Notes:"); or.AppendFormat(" - Index numbers are just an index into the returned results and may change - they are not static!"); or.AppendFormat(" - Both size-x and size-y must be > 0 or the original image will be returned without resizing."); or.AppendFormat(" "); or.AppendFormat(" "); or.AppendFormat("Examples:"); or.AppendFormat(" music-list-artists - would return all artists in the music collection"); or.AppendFormat(" music-list-album-artists - would return all album artists in the music collection"); or.AppendFormat(" - WARNING: artists are filtered on the track level so this may be inconsistent"); or.AppendFormat(" music-list-genres - would return all the genres in the music collection"); or.AppendFormat(" music-list-artists artist:b - would return all artists in the music collection whose name starts with \"B\""); or.AppendFormat(" music-list-artists album:b - would return all artists in the music collection who have an album with a title that starts with \"B\""); or.AppendFormat(" music-list-albums artist:b - would return all albums by an artist whose name starts with \"B\""); or.AppendFormat(" music-list-albums artist:b album:*b - would return all albums that have a word starting with \"B\" by an artist whose name starts with \"B\""); or.AppendFormat(" music-list-albums genre:jazz - would return all the jazz albums"); or.AppendFormat(" music-list-songs exact-artist:\"tom petty\" - would return all songs by \"Tom Petty\", but not songs by \"Tom Petty and the Heart Breakers \""); or.AppendFormat(" music-play exact_album:\"abbey road\" indexes:1,3 - would play the second and third songs (indexes are zero based) returned by the search for an album named \"Abbey Road\""); or.AppendFormat(" music-queue exact-artist:\"the who\" - would add all songs by \"The Who\" to the now playing list"); return or; }
/// <summary> /// 修改数据仓库 model.OpSign = add/edit/delete /// </summary> /// <param name="model"></param> /// <returns></returns> public OpResult Store(EquipmentMaintenanceRecordModel model) { //先查找查找设备 找到后判断校验日期要不要写入 然后写入校验记录 再修改设备信息 如果失败 删除校验记录 model.OpDate = DateTime.Now.ToDate(); model.OpTime = DateTime.Now; string opContext = "设备保养"; OpResult opResult = OpResult.SetErrorResult("未执行任何操作!"); if (model == null) { return(OpResult.SetErrorResult("保养记录不能为空!")); } //设备是否存在 var equipment = EquipmentCrudFactory.EquipmentCrud.FindBy(new QueryEquipmentDto() { SearchMode = 1, AssetNumber = model.AssetNumber }).FirstOrDefault(); if (equipment == null) { return(OpResult.SetErrorResult("未找到保养单上的设备\r\n请确定财产编号是否正确!")); } //设置保养记录 设备名称 model.EquipmentName = equipment.EquipmentName; //保存操作记录 try { if (equipment.MaintenanceDate != model.MaintenanceDate) { switch (model.OpSign) { case OpMode.Add: //新增 opResult = irep.Insert(model).ToOpResult_Add(opContext, model.Id_Key); break; case OpMode.Edit: //修改 opResult = irep.Update(u => u.Id_Key == model.Id_Key, model).ToOpResult_Eidt(opContext); break; case OpMode.Delete: //删除 opResult = irep.Delete(model.Id_Key).ToOpResult_Delete(opContext); break; default: opResult = OpResult.SetErrorResult("操作模式溢出"); break; } //如果保存记录成功 if (opResult.Result) { opResult = SetEquipmentMaintenanceDateRule(model, equipment); if (!opResult.Result) //如果设备未更新成功 { irep.Delete(model.Id_Key).ToOpResult_Delete(opContext); return(opResult); } } opResult.Attach = model; return(opResult); } else { return(OpResult.SetErrorResult("设备保养日期与录入日期相等")); } } catch (Exception ex) { throw new Exception(ex.InnerException.Message); } }
private OpResult do_detailed_list(OpResult or, WMPLib.IWMPMedia media_item, int idx, string template) { string artist = ""; string album = ""; string letter = ""; bool added = false; int index = idx; if (index < 0) index = the_state.trackCount; if (media_item != null) { artist = media_item.getItemInfo("WM/AlbumArtist"); if (artist == "") artist = media_item.getItemInfo("Author"); album = media_item.getItemInfo("WM/AlbumTitle"); letter = first_letter(artist); } // End of artist? if (artist != the_state.artist) { if (the_state.album.Length > 0) { var s_out = replacer(getTemplate(template + ".Album-", DEFAULT_DETAIL_ALBUM_END), index); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); } if (the_state.artist.Length > 0) { var s_out = replacer(getTemplate(template + ".Artist-", DEFAULT_DETAIL_ARTIST_END), index); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); } // End of current aplha? if (letter != the_state.letter && the_state.letter.Length == 1) { var s_out = replacer(getTemplate(template + ".Alpha-", ""), index); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); } if (index >= 0) { the_state.resetArtist(artist); the_state.resetAlbum(album); } if (media_item != null) { the_state.add_song_to_album(media_item); added = true; // Start new aplha? if (letter != the_state.letter) { the_state.letter = letter; var s_out = replacer(getTemplate(template + ".Alpha+", ""), index); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); } // Start new artist if (the_state.artist.Length > 0) { var s_out = replacer(getTemplate(template + ".Artist+", DEFAULT_DETAIL_ARTIST_START), index); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); } // Start new album if (the_state.album.Length > 0) { var s_out = replacer(getTemplate(template + ".Album+", DEFAULT_DETAIL_ALBUM_START), index); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); } } } // End of album? else if (album != the_state.album) { if (the_state.album.Length > 0) { var s_out = replacer(getTemplate(template + ".Album-", DEFAULT_DETAIL_ALBUM_END), index); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); } if (index >= 0) the_state.resetAlbum(album); if (media_item != null) { the_state.add_song_to_album(media_item); added = true; if (the_state.album.Length > 0) { var s_out = replacer(getTemplate(template + ".Album+", DEFAULT_DETAIL_ALBUM_START), index); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); } } } // Do track: if (media_item != null) { if (!added) the_state.add_song_to_album(media_item); var s_out = replacer(getTemplate(template + ".Entry", DEFAULT_DETAIL_SONG), index); if (s_out.Length > 0) or.AppendFormat("{0}", s_out); } return or; }
/// <summary> /// 设置设备保养日期规则 /// </summary> /// <param name="model"></param> /// <returns></returns> private OpResult SetEquipmentMaintenanceDateRule(EquipmentMaintenanceRecordModel model, EquipmentModel equipment) { equipment.MaintenanceDate = model.MaintenanceDate; equipment.OpSign = OpMode.Edit; return(OpResult.SetResult("更新设备保养日期成功!", "更新设备保养日期失败!", EquipmentCrudFactory.EquipmentCrud.Store(equipment).Result)); }