XDocument settings; //xml settings document #endregion Fields #region Constructors public DataHandler() { //instantiate lists history = new History(); bookmarks = new Bookmarks(); //set path to user.home path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\settings.xml"; //Read xml from user home, if no document exist, skip try { reader = XmlTextReader.Create(@path); settings = XDocument.Load(reader); //create objects and lists from xml loadBookmarks(); loadHistory(); loadHomePage(); reader.Close(); } catch (FileNotFoundException) { //skip this step } }
private static List<History> CalculateHistory(double total, double rate, int month) { double payment = GradedCredit.CalculateMainMonthlyPayment(total, month); List<History> historyList = new List<History>(); double residue = total; for (int i = 1; i <= month; i++) { double percent = residue * rate / 12; History history = new History() { Month = i, Percent = percent, Debt = payment, Residue = residue }; historyList.Add(history); residue -= payment; } return historyList; }
public HistoryWindow() { InitializeComponent(); historial = new Historiales(); medic = new Medic(); user = new User(); history = new History(); medics = medic.GetAll(); users = user.GetAll(); histories = history.GetAll(); foreach (Usuarios user in users) { comboUsers.Items.Add(user.nombre + " " + user.apellidos); } foreach (Medicos medic in medics) { comboMedics.Items.Add(medic.nombre + " " + medic.apellidos); } historialGrid.ItemsSource = histories.ToArray(); }
public MainForm() { InitializeComponent(); InitializeFilters(); _history = new History<Bitmap>(10); UpdateMenuHistoryItems(); }
public void TestMaxLength() { var buffer = _testHost.ExportProvider.GetExport<ITextBufferFactoryService>().Value.CreateTextBuffer(); buffer.Insert(0, "0123456789"); var snapshot = buffer.CurrentSnapshot; var history = new History(maxLength: 0); history.Add(new SnapshotSpan(snapshot, new Span(0, 1))); Assert.Empty(GetHistoryEntries(history)); history = new History(maxLength: 1); history.Add(new SnapshotSpan(snapshot, new Span(0, 1))); Assert.Equal(new[] { "0" }, GetHistoryEntries(history)); history.Add(new SnapshotSpan(snapshot, new Span(1, 1))); Assert.Equal(new[] { "1" }, GetHistoryEntries(history)); // Oldest entry is dropped. history = new History(maxLength: 2); history.Add(new SnapshotSpan(snapshot, new Span(0, 1))); Assert.Equal(new[] { "0" }, GetHistoryEntries(history)); history.Add(new SnapshotSpan(snapshot, new Span(1, 1))); Assert.Equal(new[] { "0", "1" }, GetHistoryEntries(history)); history.Add(new SnapshotSpan(snapshot, new Span(2, 1))); Assert.Equal(new[] { "1", "2" }, GetHistoryEntries(history)); // Oldest entry is dropped. }
/// <summary> /// Initializes a new instance of the class, which creates a console for executing commands while running a game. /// </summary> /// <param name="game"></param> /// <param name="interp"></param> /// <param name="font"></param> public XnaConsoleComponent(Game game, SpriteFont font) : base(game) { this.game = game; device = game.GraphicsDevice; spriteBatch = new SpriteBatch(device); this.font = font; background = new Texture2D(device, 1, 1); background.SetData<Color>(new Color[1] { new Color(0, 0, 0, 125) }); InputBuffer = ""; history = new History(); WriteLine("###"); WriteLine("### " + Version); WriteLine("###"); consoleXSize = Game.Window.ClientBounds.Right - Game.Window.ClientBounds.Left - 20; consoleYSize = font.LineSpacing * LinesDisplayed + 20; lineWidth = (int)(consoleXSize / font.MeasureString("a").X) - 2; //calculate number of letters that fit on a line, using "a" as example character State = ConsoleState.Closed; StateStartTime = 0; LastKeyState = this.CurrentKeyState = Keyboard.GetState(); firstInterval = 500f; repeatInterval = 50f; //used for repeating keystrokes keyTimes = new Dictionary<Keys, double>(); for (int i = 0; i < Enum.GetValues(typeof(Keys)).Length; i++) { Keys key = (Keys)Enum.GetValues(typeof(Keys)).GetValue(i); keyTimes[key] = 0f; } }
public HistoryViewModel(int? playerId) : this() { if (playerId != null) { using (IGameDataService dataService = new GameDataService()) { IEnumerable<DB.Match> playingMatches = dataService.GetAllMatchesForPlayer(playerId.Value); foreach (var match in playingMatches) { DB.Player opponent = dataService.GetPlayer(match.PlayerOneId == playerId ? match.PlayerTwoId : match.PlayerOneId); DB.Game currentGame = dataService.GetGame(match.CurrentGameId.Value); DB.Player winningPlayer = null; if (match.WinningPlayerId != null) winningPlayer = dataService.GetPlayer(match.WinningPlayerId.Value); HistoryViewModel.History history = new History(); history.MatchId = match.MatchId; history.OpponentName = opponent.PlayerName; history.Winner = winningPlayer != null ? winningPlayer.PlayerName : "none"; history.EndDate = match.EndDate; history.StartDateTime = match.CreateDate; this.Histories.Add(history); } } } }
public void CreateEvent(History history) { try { history.EventDate = DateTime.Now.ToString("MM-dd-yy h:mm:ss tt"); if(string.IsNullOrEmpty(history.IP)) history.IP = (string)HttpContext.Current.Session["ip_address"]; if(string.IsNullOrEmpty(history.EventUser)) history.EventUser = HttpContext.Current.User.Identity.Name; using (NpgsqlConnection conn = new NpgsqlConnection(Utility.DBString)) { NpgsqlCommand cmd = new NpgsqlCommand("history_createevent", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new NpgsqlParameter("@eventDate", history.EventDate)); cmd.Parameters.Add(new NpgsqlParameter("@type", history.Type)); cmd.Parameters.Add(new NpgsqlParameter("@event", history.Event)); cmd.Parameters.Add(new NpgsqlParameter("@ip", history.IP)); cmd.Parameters.Add(new NpgsqlParameter("@user", history.EventUser)); cmd.Parameters.Add(new NpgsqlParameter("@notes", history.Notes)); cmd.Parameters.Add(new NpgsqlParameter("@typeid", history.TypeID)); conn.Open(); cmd.ExecuteNonQuery(); } } catch (Exception ex) { Logger.Log(ex.ToString()); } }
public static List<History> ConvertToHistories(this DataInterchange data) { var parsedHistories = new List<History>(); if (data.resultType == ResultType.orders) return parsedHistories; var rowset = data.rowsets.First(); foreach (var row in rowset.rows) { var history = new History(); for (var i = 0; i < row.Count; i++) { var prop = typeof(History).GetProperty(data.columns[i], BindingFlags.Public | BindingFlags.Instance); if (null != prop && prop.CanWrite) { prop.SetValue(history, row[i], null); } } history.typeID = rowset.typeID; history.regionID = rowset.regionID; history.generatedAt = rowset.generatedAt; parsedHistories.Add(history); } return parsedHistories; }
/// <summary> /// Saves the changes. /// </summary> /// <param name="modelType">Type of the model.</param> /// <param name="categoryGuid">The category unique identifier.</param> /// <param name="entityId">The entity identifier.</param> /// <param name="changes">The changes.</param> /// <param name="relatedModelType">Type of the related model.</param> /// <param name="relatedModelId">The related model identifier.</param> /// <param name="CurrentPersonId">The current person identifier.</param> public void SaveChanges( Type modelType, Guid categoryGuid, int entityId, List<string> changes, string caption, Type relatedModelType, int? relatedEntityId, int? CurrentPersonId ) { var entityType = EntityTypeCache.Read(modelType); var category = CategoryCache.Read(categoryGuid); int? relatedEntityTypeId = null; if (relatedModelType != null) { var relatedEntityType = EntityTypeCache.Read(relatedModelType); if (relatedModelType != null) { relatedEntityTypeId = relatedEntityType.Id; } } if (entityType != null && category != null) { foreach ( string message in changes.Where( m => m != null && m != "" ) ) { var history = new History(); history.EntityTypeId = entityType.Id; history.CategoryId = category.Id; history.EntityId = entityId; history.Caption = caption; history.Summary = message; history.RelatedEntityTypeId = relatedEntityTypeId; history.RelatedEntityId = relatedEntityId; history.CreatedByPersonId = CurrentPersonId; history.CreationDateTime = DateTime.Now; Add( history, CurrentPersonId ); Save( history, CurrentPersonId ); } } }
public List<History> GetHistories(Roll roll) { string sql = HistorySql(roll); var reader = Data_Context.RunSelectSQLQuery(sql, 30); var histories = new List<History>(); if (reader.HasRows) { var sReader = new SpecialistsReader(); while (reader.Read()) { string uName = reader["UserName"] as string; var spec = sReader.GetSpecialist(uName); string m = reader["Message"] as string; DateTime date = reader.GetDateTime(3); string step = reader["CurrentQueue"] as string; var note = new History(spec, m, date, step); histories.Add(note); } Data_Context.CloseConnection(); return histories; } else return null; }
void MainWindow_Load(object sender, EventArgs e) { var indexManager = Program.IndexUpdateManager; indexManager.UpdaterChange += IndexUpdaterCallback; indexManager.CheckIndexIsFresh ().ContinueWith (t => { if (t.IsFaulted) Console.WriteLine ("Error while checking indexes: {0}", t.Exception); else if (!t.Result) indexManager.PerformSearchIndexCreation (); else indexManager.AdvertiseFreshIndex (); }).ContinueWith (t => Console.WriteLine ("Error while creating indexes: {0}", t.Exception), TaskContinuationOptions.OnlyOnFaulted); SetupSearch (); SetupDocTree (); SetupBookmarks (); history = new History (backButton, forwardButton); docBrowser.DocumentTitleChanged += (s, _) => currentTitle = docBrowser.DocumentTitle; docBrowser.DocumentCompleted += (s, _) => loadedFromString = false; docBrowser.Navigating += (s, nav) => { if (loadedFromString) return; LoadUrl (nav.Url.IsFile ? nav.Url.Segments.LastOrDefault () : nav.Url.OriginalString, true); nav.Cancel = true; }; if (!string.IsNullOrEmpty (initialUrl)) LoadUrl (initialUrl, true); }
/// <summary> /// Initializes a new instance of the class, which creates a console for executing commands while running a game. /// </summary> /// <param name="game"></param> /// <param name="interp"></param> /// <param name="font"></param> public XnaConsoleComponent() { #if !XBOX device = Game.GraphicsDevice; spriteBatch = new SpriteBatch(device); this.font = XdtkResources.Font; background = new Texture2D(device, 1, 1, 1, TextureUsage.None, SurfaceFormat.Color); background.SetData<Color>(new Color[1] { new Color(0, 0, 0, 125) }); InputBuffer = ""; history = (History)XdtkResources.Config.Get("XnaConsole.History", new XnaConsoleComponent.History()); XdtkResources.Config.Set("XnaConsole.History", history); WriteLine(XdtkConsole.Version); consoleXSize = Game.Window.ClientBounds.Right - Game.Window.ClientBounds.Left - 200; consoleYSize = font.LineSpacing * LinesDisplayed + 20; lineWidth = (int)(consoleXSize / font.MeasureString("a").X) - 2; //calculate number of letters that fit on a line, using "a" as example character State = ConsoleState.Closed; StateStartTime = 0; LastKeyState = this.CurrentKeyState = Keyboard.GetState(); firstInterval = 500f; repeatInterval = 50f; //used for repeating keystrokes keyTimes = new Dictionary<Keys, double>(); for (int i = 0; i < Enum.GetValues(typeof(Keys)).Length; i++) { Keys key = (Keys)Enum.GetValues(typeof(Keys)).GetValue(i); keyTimes[key] = 0f; } #endif }
public XRayImage (ViewObject viewObject, StatusBarItems statusBarItems, History history, SysConfiguration SysConfig) { InitializeComponent(); MainXRayView.Image.Visibility = System.Windows.Visibility.Hidden; m_MagnifierSettings.IsMagniferEnabled = false; m_MagnifierSettings.Radius = 0; m_MagnifierSettings.MagnFactor = 2.0; m_MagnifierSettings.AspectRatio = 0; m_MaxDetectorsPerBoard = viewObject.MaxDetectorsPerBoard; m_bitsPerPixel = viewObject.BitsPerPixel; m_ViewObject = viewObject; m_statusBarItems = statusBarItems; MainXRayView.Setup(viewObject, history, SysConfig); MainXRayView.adonerImageObject.measureAdorner.SamplingSpace = viewObject.SamplingSpace; MainXRayView.adonerImageObject.measureAdorner.SamplingSpeed = viewObject.SamplingSpeed; MainXRayView.Cursor = Cursors.Hand; MainXRayView.Image.MouseMove += new MouseEventHandler(Img_MouseMove); MainXRayView.Image.MouseLeave += new MouseEventHandler(Img_MouseLeave); MainXRayView.MagnifierDockPanel.SizeChanged += new SizeChangedEventHandler(Magnifier_SizeChanged); MainXRayView.MagnifierDockPanel.MouseMove += new MouseEventHandler(Magnifier_MouseMove); MainXRayView.MagnifierDockPanel.MouseLeftButtonDown += new MouseButtonEventHandler(Magnifier_MouseMove); }
void MainWindow_Load(object sender, EventArgs e) { var indexManager = Program.IndexUpdateManager; indexManager.UpdaterChange += IndexUpdaterCallback; indexManager.CheckIndexIsFresh ().ContinueWith (t => { if (t.IsFaulted) Logger.LogError ("Error while checking indexes", t.Exception); else if (!t.Result) indexManager.PerformSearchIndexCreation (); else indexManager.AdvertiseFreshIndex (); }).ContinueWith (t => Logger.LogError ("Error while creating indexes", t.Exception), TaskContinuationOptions.OnlyOnFaulted); SetupSearch (); SetupDocTree (); SetupBookmarks (); history = new History (backButton, forwardButton); docBrowser.DocumentTitleChanged += (s, _) => currentTitle = docBrowser.DocumentTitle; docBrowser.DocumentCompleted += (s, _) => loadedFromString = false; docBrowser.Navigating += (s, nav) => { if (loadedFromString) return; string url = nav.Url.OriginalString; if (nav.Url.IsFile) { var segs = nav.Url.Segments; url = segs.LastOrDefault () == "*" ? segs.Skip (segs.Length - 2).Aggregate (string.Concat) : segs.LastOrDefault (); } LoadUrl (url, true); nav.Cancel = true; }; LoadUrl (string.IsNullOrEmpty (initialUrl) ? "root:" : initialUrl, syncTreeView: true); }
public void TestInvertedIntersect() { var a = History.AllTime (); a.Add (new DateTime (2010, 1, 1)); a.Add (new DateTime (2010, 1, 10)); var b = new History (); b.Add (new DateTime (2010, 1, 8)); b.Add (new DateTime (2010, 1, 12)); var c = History.Intersect (a, b); Assert.False (c.Inverted); Assert.True (c[0] == new DateTime (2010, 1, 10)); Assert.True (c[1] == new DateTime (2010, 1, 12)); var d = History.Intersect (b, a); Assert.False (d.Inverted); Assert.True (d[0] == new DateTime (2010, 1, 10)); Assert.True (d[1] == new DateTime (2010, 1, 12)); b.Inverted = true; var e = History.Intersect (a, b); Assert.True (e.Inverted); Assert.True (e[0] == new DateTime (2010, 1, 1)); Assert.True (e[1] == new DateTime (2010, 1, 12)); }
public IEnumerable<Card> Play(IEnumerable<Card> hand, IEnumerable<Card> table, int rank, Suit suit, Mode mode, bool revolution, History history) { if (revolution && rank != Card.RankOfJoker) { rank = 14 - rank; } if (hand == null || hand.Count() == 0) return null; int count = table.Count(); // 初手はとりあえず一番弱いのを出しとく。 if (mode.Match(Mode.First)) { var min = hand.Min(x => Game.Rank(x, revolution)); return hand.Where(x => Game.Rank(x, revolution) == min); } if (mode.Match(Mode.Normal)) { if(mode.Match(Mode.SuitBound)) { return hand.MinCard(x => Game.Rank(x, revolution) > rank && x.Suit == suit, revolution); } else { return hand.MinCard(x => Game.Rank(x, revolution) > rank, revolution); } } if(mode.Match(Mode.Multiple)) { for (int i = rank + 1; i <= 13; i++) { // 出せる var c = hand.Where(x => Game.Rank(x, revolution) == i); if (c.Count() >= count) return c.Take(count); // Joker含めれば出せる if (c.Count() + 1 == count && hand.FirstOrDefault(x => x.Suit == Suit.Joker) != null) return c.Concat(hand.Where(x => x.Suit == Suit.Joker).Take(count)); } } if (mode.Match(Mode.SequenceBound)) return null; //todo また未対応 if (mode.Match(Mode.Sequence)) { if (mode.Match(Mode.SuitBound)) return hand.Sequence(rank, revolution, count, suit); else return hand.Sequence(rank, revolution, count); } return null; }
public RedoButton(History history) { this.history = history; history.Change += OnChange; this.Image = Properties.Resources.Redo_icon; OnChange(); }
public FilterParameter (DockPanel panel, int width, int height, History history, SysConfiguration config) { dockPanel = panel; Width = width; Height = height; History = history; SysConfig = config; }
public WherigoModel() { Core = new WFCoreAdapter(); CartridgeStore = new CartridgeStore(); History = Models.History.FromCacheOrCreate(); }
protected override void OnClosed(EventArgs e) { _editHistory.Changed -= _EditHistory_Changed; _editHistory = null; _template = null; _objectSpace = null; dashboardDesigner.Dashboard.Dispose(); dashboardDesigner = null; base.OnClosed(e); }
public RedoItem(History history) { this.history = history; history.Change += OnChange; this.Image = Properties.Resources.Redo_icon; this.Text = "Redo"; this.ShortcutKeys = Keys.Control | Keys.Y; OnChange(); }
public void CanCreateHistory() { var x = new History("Czech Republic", "Prague", DateTime.Now, "Sunny", 10.5, Unit.Celsius); Assert.IsTrue(x.Country == "Czech Republic"); Assert.IsTrue(x.City == "Prague"); Assert.IsTrue(x.Clouds == "Sunny"); Assert.IsTrue(x.Temperature.Number == 10.5); Assert.IsTrue(x.Temperature.Unit == Unit.Celsius); }
//--------------------------------------------------------------------- // Constructor //--------------------------------------------------------------------- public Layer(int pWidth, int pHeight, string pName, string pID) { ID = pID; Name = pName; Opacity = 1.0f; Visible = true; History = new History(); m_bitmap = new Bitmap(pWidth, pHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); m_area = new Rectangle(0, 0, pWidth, pHeight); }
public void SaveGameResult(TrainOfWordsParams tParams) { using (var context = new GameModelContainer()) { var game = context.Games.FirstOrDefault(game1 => game1.Name == "TrainOfWords"); if (game == null) return; var date = DateTime.Now; var historyParams = new List<HistoryParam> { new HistoryParam { GameParam = game.GameParams.FirstOrDefault(param => param.Name == "Level"), Value = tParams.Level.ToString(CultureInfo.InvariantCulture) } }; var historyResults = new List<HistoryResult> { new HistoryResult { GameResult = game.GameResults.FirstOrDefault(param => param.Name == "Correct Trials"), Value = tParams.CorrectTrials }, new HistoryResult { GameResult = game.GameResults.FirstOrDefault(param => param.Name == "Failures"), Value = tParams.Failures }, new HistoryResult { GameResult = game.GameResults.FirstOrDefault(param => param.Name == "Time"), Value = tParams.Time } }; var history = new History { Game = game, Date = date, HistoryParams = historyParams, HistoryResults = historyResults }; var player = context.Players.FirstOrDefault(player1 => player1.Id == _player.Id); if (player == null) return; player.Histories.Add(history); context.SaveChanges(); } }
static HistoryGlobal() { history = new History<IDirectoryViewItem>(); history.SerializationKey = SerializationKey; SerializationHelper.RegisterUser(history); if (SerializationHelper.DataLoaded) { history.ApplyLoadedData(); } }
public void TestAfter() { var a = new History (); a.Add (new DateTime (2003, 3, 15)); a.Add (new DateTime (2003, 3, 20)); var b = a.After (new DateTime (2003, 3, 18)); Assert.True (b.Count == 2); Assert.True (b[0] == new DateTime (2003, 3, 18)); Assert.True (b[1] == new DateTime (2003, 3, 20)); }
public void CanUpdateHistoryTemperature() { var x = new History("Czech Republic", "Prague", DateTime.Now, "Sunny", 10.5, Unit.Celsius); x.UpdateTemperature(50, Unit.Fahrenheit); Assert.IsTrue(x.Country == "Czech Republic"); Assert.IsTrue(x.City == "Prague"); Assert.IsTrue(x.Clouds == "Sunny"); Assert.IsTrue(x.Temperature.Number == 50); Assert.IsTrue(x.Temperature.Unit == Unit.Fahrenheit); }
private bool dirChanged = true; //determines if directory has changed and is needed to reload #endregion Fields #region Constructors public PreviewView() { InitializeComponent(); FileSystem = new WindowsFileSystem(); History = new History<IDirectoryViewItem>(); Binding bind = new Binding("Items"); bind.Source = FileSystem; lbContent.SetBinding(ListBox.ItemsSourceProperty, bind); lbContent.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged); }
public void TestBefore() { var a = new History (); a.Add (new DateTime (2002, 3, 15)); a.Add (new DateTime (2002, 3, 20)); var b = a.Before (new DateTime (2002, 3, 18)); Assert.False (b.Inverted); Assert.True (b.Count == 2); Assert.True (b[0] == new DateTime (2002, 3, 15)); Assert.True (b[1] == new DateTime (2002, 3, 18)); }
public ItalicCommand(HtmlDocument document, History history) { _document = document; _history = history; }
public async Task <IActionResult> RegisterLocationFromUser(LocationForRegisterDto locationForRegisterDto) { var ReelsFromRepo = await _repo.GetReel(locationForRegisterDto.Id); if (ReelsFromRepo == null) { return(BadRequest("Pagal pateikta ID ritė nerasta")); } var ComponentasFromRepo = await _srepo.GetCompCMnf(ReelsFromRepo.CMnf); int likutis = ReelsFromRepo.QTY - locationForRegisterDto.QTY; if (likutis <= 0) { return(BadRequest("Rite tusčia, bandote padeti tuščia pakuotę, nurasote didesni kieki nei buvo uzregistruota riteje")); } var res = Int32.TryParse(ReelsFromRepo.Location, out _); if (res == true) { int result = Int32.Parse(ReelsFromRepo.Location); if (result > 0) { return(BadRequest("Ši ritė turėtų būti padėta į " + ReelsFromRepo.Location + " slotą !!!!!")); } } var user = await _userManager.FindByIdAsync(locationForRegisterDto.UserId); locationForRegisterDto.UserId = null; if (locationForRegisterDto.Location is null) { locationForRegisterDto.Location = user.UserName; locationForRegisterDto.UserId = user.Id.ToString(); } var HistoryToCreate = new History { Mnf = ReelsFromRepo.CMnf, NewLocation = locationForRegisterDto.Location, NewQty = likutis, OldLocation = ReelsFromRepo.Location, OldQty = ReelsFromRepo.QTY, ComponentasId = ComponentasFromRepo.Id, DateAdded = DateTime.Now, ReelId = locationForRegisterDto.Id, UserId = user.Id }; var createHistory = await _srepo.RegisterHistory(HistoryToCreate); locationForRegisterDto.QTY = likutis; _mapper.Map(locationForRegisterDto, ReelsFromRepo); if (await _repo.SaveAll()) { return(NoContent()); } else { return(BadRequest("Could notregister location")); } }
public static void Save() { History.GetInstance().Push(new EcoSnapshot()); }
public ActionResult AttachCreate(AttachmentViewModel attachmentVm) { if (ModelState.IsValid) { if (attachmentVm.FileObj != null && attachmentVm.FileObj.ContentLength > 0) { var cu = User.Identity.GetUserName(); var usr = db.Users.Single(u => u.UserName == cu).Id; var attachment = new Attachement() { UserId = usr, DateAttached = DateTime.Now, FileUNQName = Guid.NewGuid().ToString() + attachmentVm.FileObj.FileName, Description = attachmentVm.Description, FileName = attachmentVm.FileObj.FileName, TicketId = attachmentVm.TicketId, UpLoaded = true }; var path = HttpContext.Server.MapPath("~/Repository/Attachments/" + attachmentVm.TicketId + "/"); var fullName = Path.Combine(path, attachment.FileUNQName); if (!Directory.Exists(path)) { //Server.MapPath(path); Directory.CreateDirectory(path); } attachmentVm.FileObj.SaveAs(fullName); db.Attachements.Add(attachment); db.SaveChanges(); //Update Last Updated Field var ct = db.Tickets.Single(id => id.Id == attachmentVm.TicketId); ct.Attachments = true; ct.LastedUpdated = DateTime.Now; db.Entry(ct).State = EntityState.Modified; db.SaveChanges(); // Create History Event var eventstr = "Attachment, ID No." + attachment.Id.ToString() + ", made associated with Ticket No." + attachmentVm.TicketId + ""; var he = new History(ct.Id, usr, eventstr); db.Histories.Add(he); db.SaveChanges(); // Notify Assignee var ne = new Notification(ct.Id, ct.AssignedId, eventstr); db.Notifications.Add(ne); db.SaveChanges(); // Notify Project Manager if not assignee var nep = new Notification(ct.Id, ct.User1.Id, eventstr); if (ne.UserId != nep.UserId) { db.Notifications.Add(nep); db.SaveChanges(); } return(RedirectToAction("Index")); } //ViewBag.TicketId = new SelectList(db.Tickets, "Id", "Title", attachment.TicketId); //ViewBag.UserId = new SelectList(db.Users, "Id", "Name", attachment.UserId); //return View(attachment); } return(View()); }
/// <summary> /// Process task completion by scheduling the next task or completing the workflow /// </summary> /// <param name="db"></param> /// <param name="workflow"></param> /// <param name="execution"></param> /// <param name="history"></param> /// <param name="decisions"></param> private static void ProcessActivityTaskCompletedEvent(Database db, WorkflowObj workflow, Execution execution, History history, List <History> decisions) { // There should(!) be no contention for the data modified in this process var evt = ActivityTaskCompletedEvent.Create(history); var se = ActivityTaskScheduledEvent.Create(db.GetHistoryEvent(execution.ExecutionId, evt.SchedulingEventId)); var completedTask = workflow.Tasks.Single(t => t.TaskId == se.TaskId); // Default task outflow var outflow = "Out"; // Update variables if (evt.Result != null) { // Update the variables if there are any normal results (not prefixed with "$") if (evt.Result.Properties().Any(p => !p.Name.StartsWith("$"))) { var variables = db.Variables.Where(v => v.Execution == execution).ToArray(); foreach (var o in completedTask.Outputs.Where(o => o.Value.Var != null)) { // If the activity has not returned a value for an output then we don't update the mapped variable // In general it is probably best if activities return values for all outputs to avoid confusion JToken value; if (evt.Result.TryGetValue(o.Key, out value)) { variables.Single(v => v.Name == o.Value.Var).Json = value.ToString(Formatting.None); } } } // Get the correct outflow JToken outflowToken; if (evt.Result.TryGetValue("$outflow", out outflowToken)) { if (outflowToken.Type == JTokenType.String) { outflow = (string)outflowToken; } else { throw new ApplicationException("Task outflow identifier must be a string"); } } } var nextTaskId = completedTask.Outflows.Single(o => o.Name == outflow).Target; var nextTask = workflow.Tasks.Single(t => t.TaskId == nextTaskId); // A task with no outflows is an end if (nextTask.Outflows.Length == 0) { Console.WriteLine($"Execution state = {execution.ExecutionState.State}"); if (ExState.Create(execution.ExecutionState.State) != ExState.Cleanup) { CreateWorkflowCompletedEvent(execution, decisions); } AttemptCleanup(db, execution, workflow, decisions); } else { CreateTaskScheduledEvent(db, execution, nextTask, decisions); } }
public string FTP_FLPolk(string address, string parcelNumber, string ownername, string searchType, string orderNumber, string directParcel) { GlobalClass.global_orderNo = orderNumber; HttpContext.Current.Session["orderNo"] = orderNumber; GlobalClass.global_parcelNo = parcelNumber; string StartTime = "", AssessmentTime = "", TaxTime = "", CitytaxTime = "", LastEndTime = ""; var driverService = PhantomJSDriverService.CreateDefaultService(); driverService.HideCommandPromptWindow = true; using (driver = new PhantomJSDriver())//ChromeDriver(); { try { StartTime = DateTime.Now.ToString("HH:mm:ss"); if (searchType == "titleflex") { gc.TitleFlexSearch(orderNumber, "", "", address, "FL", "Polk"); if ((HttpContext.Current.Session["TitleFlex_Search"] != null && HttpContext.Current.Session["TitleFlex_Search"].ToString() == "Yes")) { driver.Quit(); return("MultiParcel"); } else if (HttpContext.Current.Session["titleparcel"].ToString() == "") { HttpContext.Current.Session["Nodata_FLPolk"] = "Yes"; driver.Quit(); return("No Data Found"); } parcelNumber = HttpContext.Current.Session["titleparcel"].ToString(); searchType = "parcel"; } if (searchType == "address") { driver.Navigate().GoToUrl("http://www.polkpa.org/CamaDisplay.aspx?OutputMode=Input&searchType=RealEstate&page=FindByAddress"); gc.CreatePdf_WOP(orderNumber, "Address Search", driver, "FL", "Polk"); driver.FindElement(By.Id("address")).SendKeys(address); driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[1]/div[3]/table/tbody/tr/td/input")).SendKeys(Keys.Enter); gc.CreatePdf_WOP(orderNumber, "Address Search Result", driver, "FL", "Polk"); try { IWebElement ImultiCount = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/span[1]")); strMultiCount = GlobalClass.Before(ImultiCount.Text, " Matches found"); if (Convert.ToInt32(strMultiCount) != 1 && Convert.ToInt32(strMultiCount) >= 1) { if (Convert.ToInt32(strMultiCount) > 25) { HttpContext.Current.Session["multiparcel_FLPolk_Count"] = "Maximum"; return("Maximum"); } IWebElement IMultiTable = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[3]/table/tbody")); IList <IWebElement> IMultiRow = IMultiTable.FindElements(By.TagName("tr")); IList <IWebElement> IMultiTD; foreach (IWebElement multi in IMultiRow) { IMultiTD = multi.FindElements(By.TagName("td")); if (IMultiTD.Count != 0 && IMultiTD.Count > 1 && !multi.Text.Contains("Owner Name") && Convert.ToInt32(strMultiCount) <= 25) { HttpContext.Current.Session["multiparcel_FLPolk"] = "Yes"; gc.CreatePdf_WOP(orderNumber, "Multi Parcel Result", driver, "FL", "Polk"); strAddress = IMultiTD[1].Text; strParcelId = IMultiTD[2].Text; strOwnerName = IMultiTD[3].Text; string strMultiDetails = strOwnerName + "~" + strAddress; gc.insert_date(orderNumber, strParcelId, 426, strMultiDetails, 1, DateTime.Now); } } driver.Quit(); return("MultiParcel"); } } catch { } } if (searchType == "parcel") { driver.Navigate().GoToUrl("http://www.polkpa.org/CamaDisplay.aspx?OutputMode=Input&searchType=RealEstate&page=FindByID"); gc.CreatePdf(orderNumber, parcelNumber, "Parcel Search", driver, "FL", "Polk"); driver.FindElement(By.Id("parcelID")).SendKeys(parcelNumber); driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[1]/div[3]/table/tbody/tr/td/input")).SendKeys(Keys.Enter); gc.CreatePdf(orderNumber, parcelNumber, "Parcel Search Result", driver, "FL", "Polk"); } if (searchType == "ownername") { driver.Navigate().GoToUrl("http://www.polkpa.org/CamaDisplay.aspx?OutputMode=Input&searchType=RealEstate&page=FindByOwnerName"); gc.CreatePdf_WOP(orderNumber, "Owner Search", driver, "FL", "Polk"); driver.FindElement(By.Id("OwnerName")).SendKeys(ownername); driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[1]/div[3]/table/tbody/tr/td/input")).SendKeys(Keys.Enter); gc.CreatePdf_WOP(orderNumber, "Owner Search Result", driver, "FL", "Polk"); try { IWebElement ImultiCount = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/span[1]")); strMultiCount = GlobalClass.Before(ImultiCount.Text, " Matches found"); if (Convert.ToInt32(strMultiCount) != 1 && Convert.ToInt32(strMultiCount) >= 1) { if (Convert.ToInt32(strMultiCount) > 25) { HttpContext.Current.Session["multiparcel_FLPolk_Count"] = "Maximum"; return("Maximum"); } IWebElement IMultiTable = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[3]/table/tbody")); IList <IWebElement> IMultiRow = IMultiTable.FindElements(By.TagName("tr")); IList <IWebElement> IMultiTD; foreach (IWebElement multi in IMultiRow) { IMultiTD = multi.FindElements(By.TagName("td")); if (IMultiTD.Count != 0 && IMultiTD.Count > 1 && !multi.Text.Contains("Owner Name") && Convert.ToInt32(strMultiCount) <= 25) { HttpContext.Current.Session["multiparcel_FLPolk"] = "Yes"; gc.CreatePdf_WOP(orderNumber, "Multi Parcel Result", driver, "FL", "Polk"); strOwnerName = IMultiTD[1].Text; strParcelId = IMultiTD[2].Text; strAddress = IMultiTD[3].Text; string strMultiDetails = strOwnerName + "~" + strAddress; gc.insert_date(orderNumber, strParcelId, 426, strMultiDetails, 1, DateTime.Now); } } driver.Quit(); return("MultiParcel"); } } catch { } } try { IWebElement INodata = driver.FindElement(By.Id("CamaDisplayArea")); if (INodata.Text.Contains("0 Matches found for search results")) { HttpContext.Current.Session["Nodata_FLPolk"] = "Yes"; driver.Quit(); return("No Data Found"); } } catch { } try { IWebElement ImultiCount = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/span[1]")); strMultiCount = GlobalClass.Before(ImultiCount.Text, " Matches found"); if (Convert.ToInt32(strMultiCount) == 1 && Convert.ToInt32(strMultiCount) != 0) { IWebElement IMultiTable = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[3]/table/tbody")); IList <IWebElement> IMultiRow = IMultiTable.FindElements(By.TagName("tr")); IList <IWebElement> IMultiTD; foreach (IWebElement multi in IMultiRow) { IMultiTD = multi.FindElements(By.TagName("td")); if (IMultiTD.Count != 0 && IMultiTD.Count > 1 && !multi.Text.Contains("Owner Name") && Convert.ToInt32(strMultiCount) == 1) { gc.CreatePdf_WOP(orderNumber, "Search Result", driver, "FL", "Polk"); try { Ilink = IMultiTD[2].FindElement(By.TagName("a")); } catch { } try { Ilink = IMultiTD[1].FindElement(By.TagName("a")); } catch { } strSearchLink = Ilink.GetAttribute("href"); } } } } catch { } driver.Navigate().GoToUrl(strSearchLink); string strParcelNo = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/table[1]/tbody/tr[1]/td[1]")).Text; strParcelNumber = GlobalClass.After(strParcelNo, "Parcel Details: "); gc.CreatePdf(orderNumber, strParcelNumber, "Property Search Result", driver, "FL", "Polk"); strOwner1 = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/table[2]/tbody/tr/td[1]/table[1]/tbody/tr[1]/td[1]")).Text.Trim(); try { strOwner2 = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/table[2]/tbody/tr/td[1]/table[1]/tbody/tr[2]/td[1]")).Text.Trim(); } catch { } try { strOwner3 = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/table[2]/tbody/tr/td[1]/table[1]/tbody/tr[3]/td[1]")).Text.Trim(); } catch { } if (strOwner1 != "") { strOwner = strOwner1 + " " + strOwner2 + " " + strOwner3; } strproperty = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/table[2]/tbody/tr/td[1]/table[3]/tbody")).Text.Trim(); strSiteAddress1 = gc.Between(strproperty, "Address 1 ", "\r\n"); try { strSiteAddress2 = gc.Between(strproperty, "\r\n", "Address 2\r\n"); strSiteAddress = strSiteAddress1 + strSiteAddress2; } catch { } strCity = gc.Between(strproperty, "City ", "\r\nState"); strState = gc.Between(strproperty, "State", "\r\nZip Code"); strZip = GlobalClass.After(strproperty, "\r\nZip Code ").Replace("-", ""); strParcelInformation = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/table[2]/tbody/tr/td[1]/table[4]/tbody")).Text; strNeighBorHood = gc.Between(strParcelInformation, "Neighborhood", "\r\nSubdivision"); strSubdivision = gc.Between(strParcelInformation, "\r\nSubdivision\r\n", "\r\nProperty (DOR) Use Code"); strPropertyCode = gc.Between(strParcelInformation, "Property (DOR) Use Code", "\r\nAcreage"); strAcreage = gc.Between(strParcelInformation, "Acreage", "\r\nTaxing District"); strTaxingDistrict = gc.Between(strParcelInformation, "Taxing District", "\r\nCommunity Redevelopment Area"); strCommunityArea = GlobalClass.After(strParcelInformation, "Community Redevelopment Area "); try { strYear = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[6]/table/tbody")).Text; strYearBuilt = gc.Between(strYear, "Actual Year Built: ", "\r\nEffective Year: "); } catch { } string strPropertyDetails = strOwner.Trim() + "~" + strSiteAddress + "~" + strCity + "~" + strState + "~" + strZip + "~" + strNeighBorHood + "~" + strSubdivision + "~" + strPropertyCode + "~" + strAcreage + "~" + strTaxingDistrict + "~" + strCommunityArea + "~" + strYearBuilt; gc.insert_date(orderNumber, strParcelNumber, 428, strPropertyDetails, 1, DateTime.Now); try { IWebElement IValuesTable = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[12]/table[1]/tbody")); IList <IWebElement> IValuesRow = IValuesTable.FindElements(By.TagName("tr")); IList <IWebElement> IValuesTD; foreach (IWebElement value in IValuesRow) { IValuesTD = value.FindElements(By.TagName("td")); if (IValuesTD.Count != 0 && !value.Text.Contains("Desc Value")) { if (IValuesTD[0].Text == "Land Value") { strLandValue = IValuesTD[1].Text; } if (IValuesTD[0].Text == "Building Value") { strBuildingValue = IValuesTD[1].Text; } if (IValuesTD[0].Text == "Misc. Items Value") { strMiscItemValue = IValuesTD[1].Text; } if (IValuesTD[0].Text == "Land Classified Value") { strLClassifiedValue = IValuesTD[1].Text; } if (IValuesTD[0].Text == "Just Market Value") { strMarketValue = IValuesTD[1].Text; } if (IValuesTD[0].Text == "*Cap Differential and Portability") { strCDPValue = IValuesTD[1].Text; } if (IValuesTD[0].Text == "Agriculture Classification") { strAgriculture = IValuesTD[1].Text; } if (IValuesTD[0].Text == "Assessed Value") { strAssessedValue = IValuesTD[1].Text; } if (IValuesTD[0].Text == "Exempt Value (County)") { strExemptValue = IValuesTD[1].Text; } if (IValuesTD[0].Text == "Taxable Value (County)") { strTaxableValue = IValuesTD[1].Text; } } } } catch { } string strValueSummary = strLandValue + "~" + strBuildingValue + "~" + strMiscItemValue + "~" + strLClassifiedValue + "~" + strMarketValue + "~" + strCDPValue + "~" + strAgriculture + "~" + strAssessedValue + "~" + strExemptValue + "~" + strTaxableValue; gc.insert_date(orderNumber, strParcelNumber, 429, strValueSummary, 1, DateTime.Now); try { string strValuesD = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[12]/div[1]")).Text; strValuesDistrict = GlobalClass.Before(strValuesD, "\r\nDistrict Description Final\r\n"); } catch { } try { IWebElement IValueDistrict = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[12]/div[1]/table/tbody")); IList <IWebElement> IValueDistrictRow = IValueDistrict.FindElements(By.TagName("tr")); IList <IWebElement> IValueDistrictTd; foreach (IWebElement district in IValueDistrictRow) { IValueDistrictTd = district.FindElements(By.TagName("td")); if (IValueDistrictTd.Count != 0 && !district.Text.Contains("District Description")) { strDD = IValueDistrictTd[0].Text; strFTR = IValueDistrictTd[1].Text; strAV = IValueDistrictTd[2].Text; strFAT = IValueDistrictTd[3].Text; strEX = IValueDistrictTd[4].Text; strFTS = IValueDistrictTd[5].Text; strTV = IValueDistrictTd[6].Text; strFT = IValueDistrictTd[7].Text; string strValueDistrictDetails = strValuesDistrict + "~" + strDD + "~" + strFTR + "~" + strAV + "~" + strFAT + "~" + strEX + "~" + strFTS + "~" + strTV + "~" + strFT + "~" + "-"; gc.insert_date(orderNumber, strParcelNumber, 437, strValueDistrictDetails, 1, DateTime.Now); } } } catch { } try { strNonValorem = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[12]/div[2]/h3")).Text; } catch { } try { IWebElement INonAdValoremTable = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[12]/div[2]/table/tbody")); IList <IWebElement> INonAdValoremRow = INonAdValoremTable.FindElements(By.TagName("tr")); IList <IWebElement> INonAdValoremTD; foreach (IWebElement Nvalorem in INonAdValoremRow) { INonAdValoremTD = Nvalorem.FindElements(By.TagName("td")); if (INonAdValoremTD.Count != 0 && (!Nvalorem.Text.Contains("Units") || !Nvalorem.Text.Contains("Rate")) && !Nvalorem.Text.Contains("Total Assessments")) { strLN = INonAdValoremTD[0].Text; strCode = INonAdValoremTD[1].Text; strDesc = INonAdValoremTD[2].Text; strUnits = INonAdValoremTD[3].Text; strRate = INonAdValoremTD[4].Text; strAssessment = INonAdValoremTD[5].Text; string strNonValoremDetails = strNonValorem + "~" + strLN + "~" + strCode + "~" + "-" + "~" + strDesc + "~" + strUnits + "~" + strRate + "~" + strAssessment; gc.insert_date(orderNumber, strParcelNumber, 439, strNonValoremDetails, 1, DateTime.Now); } if (INonAdValoremTD.Count != 0 && Nvalorem.Text.Contains("Total Assessments") && INonAdValoremTD.Count == 2) { strLN = INonAdValoremTD[0].Text; strAssessment = INonAdValoremTD[1].Text; string strNonValoremDetails = strNonValorem + "~" + "-" + "~" + strLN + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + strAssessment; gc.insert_date(orderNumber, strParcelNumber, 439, strNonValoremDetails, 1, DateTime.Now); } } } catch { } try { IWebElement ITaxesTable = driver.FindElement(By.XPath("//*[@id='CamaDisplayArea']/div[12]/table[2]/tbody")); IList <IWebElement> ITaxesRow = ITaxesTable.FindElements(By.TagName("tr")); IList <IWebElement> ITaxesTD; foreach (IWebElement tax in ITaxesRow) { ITaxesTD = tax.FindElements(By.TagName("td")); if (ITaxesTD.Count != 0 && !tax.Text.Contains("Your final tax bill may contain Non-Ad") && !tax.Text.Contains("Desc")) { strTDesc = ITaxesTD[0].Text; strLastYear = ITaxesTD[1].Text; strFinal = ITaxesTD[2].Text; string strTaxesDetails = strTDesc + "~" + strLastYear + "~" + strFinal; gc.insert_date(orderNumber, strParcelNumber, 440, strTaxesDetails, 1, DateTime.Now); } } } catch { } AssessmentTime = DateTime.Now.ToString("HH:mm:ss"); //Tax Details try { driver.Navigate().GoToUrl("http://www.polktaxes.com/generalinfo/officehours_locations.aspx"); Thread.Sleep(3000); strTaxAuthority = driver.FindElement(By.XPath("//*[@id='main']/div/div/div/div/div[2]/div/div[6]/div[1]/p")).Text; } catch { } driver.Navigate().GoToUrl("http://fl-polk-taxcollector.governmax.com/collectmax/collect30.asp"); Thread.Sleep(3000); IWebElement iframeElement = driver.FindElement(By.XPath("/html/frameset/frame")); driver.SwitchTo().Frame(iframeElement); IWebElement IParcelSerach = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table/tbody/tr[1]/td/table[2]/tbody/tr/td[1]/center/a")); IJavaScriptExecutor js = driver as IJavaScriptExecutor; js.ExecuteScript("arguments[0].click();", IParcelSerach); Thread.Sleep(2000); IWebElement IAccountSearch = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[1]/td[1]/table/tbody/tr[2]/td/table/tbody/tr[4]/td")).FindElement(By.TagName("a")); string strAccountSearch = IAccountSearch.GetAttribute("href"); driver.Navigate().GoToUrl(strAccountSearch); Thread.Sleep(2000); gc.CreatePdf(orderNumber, strParcelNumber, "Tax Search", driver, "FL", "Polk"); strParcel = strParcelNumber.Replace("-", ""); strparcelFirst = strParcel.Substring(4, 2); strParcelsecond = strParcel.Substring(2, 2); strParcelthird = strParcel.Substring(0, 2); strparcelMiddle = strParcel.Substring(6, 6); strparcelLast = strParcel.Substring(12, 6); strFullParcel = strparcelFirst + strParcelsecond + strParcelthird + "-" + strparcelMiddle + "-" + strparcelLast; driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr/td/table/tbody/tr[2]/td/font/input")).SendKeys(strFullParcel); driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table/tbody/tr/td/table/tbody/tr[3]/td/input")).SendKeys(Keys.Enter); Thread.Sleep(6000); gc.CreatePdf(orderNumber, strParcelNumber, "Tax Search Result", driver, "FL", "Polk"); strAccountNo = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[2]/td[1]")).Text; strTaxType = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[2]/td[2]")).Text; strTaxYear = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[2]/td[3]")).Text; strMailingAddress = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[3]/td/table/tbody/tr[1]/td[1]/font[3]")).Text; strPhysicalAddress = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/font[3]")).Text; strGeoNo = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[3]/td/table/tbody/tr[1]/td[2]/font[6]")).Text; strExemptAmount = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[5]/td[1]")).Text; strTaxableAmount = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[5]/td[2]")).Text; strLegalDiscription = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[6]/td/table/tbody/tr/td/font[2]")).Text; string strTaxAssessmentDetails = strAccountNo + "~" + strTaxType + "~" + strTaxYear + "~" + strMailingAddress + "~" + strPhysicalAddress + "~" + strGeoNo + "~" + strExemptAmount + "~" + strTaxableAmount + "~" + strLegalDiscription + "~" + strTaxAuthority; gc.insert_date(orderNumber, strAccountNo, 441, strTaxAssessmentDetails, 1, DateTime.Now); try { strValorem = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[7]/td")).Text; } catch { } IWebElement ITaxValoremTable = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[8]/td/table[1]/tbody")); IList <IWebElement> ITaxValoremRow = ITaxValoremTable.FindElements(By.TagName("tr")); IList <IWebElement> ITaxValoremTD; foreach (IWebElement valorem in ITaxValoremRow) { ITaxValoremTD = valorem.FindElements(By.TagName("td")); if (ITaxValoremTD.Count != 0 && !valorem.Text.Contains("Taxing Authority")) { try { strTaxAuthority = ITaxValoremTD[0].Text; strTaxRate = ITaxValoremTD[1].Text; strTaxAssessedValue = ITaxValoremTD[2].Text; strTaxExemptionAmount = ITaxValoremTD[3].Text; strTaxbleValue = ITaxValoremTD[4].Text; strTaxAmount = ITaxValoremTD[5].Text; } catch { } string strTaxValoremDetails = strValorem + "~" + strTaxAuthority + "~" + strTaxRate + "~" + strTaxAssessedValue + "~" + "-" + "~" + strTaxExemptionAmount + "~" + "-" + "~" + strTaxbleValue + "~" + "-" + "~" + strTaxAmount; gc.insert_date(orderNumber, strAccountNo, 437, strTaxValoremDetails, 1, DateTime.Now); } } IWebElement ITaxValoremTotalTable = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[8]/td/table[2]/tbody")); IList <IWebElement> ITaxValoremTotalRow = ITaxValoremTotalTable.FindElements(By.TagName("tr")); IList <IWebElement> ITaxValoremTotalTD; foreach (IWebElement total in ITaxValoremTotalRow) { ITaxValoremTotalTD = total.FindElements(By.TagName("td")); if (ITaxValoremTotalTD.Count != 0) { strTotalMillege = ITaxValoremTotalTD[0].Text; strTotalMillegeAmount = ITaxValoremTotalTD[1].Text; strTotalTax = ITaxValoremTotalTD[2].Text; strTotalTaxAmount = ITaxValoremTotalTD[3].Text; string strTaxValoremDetails = strValorem + "~" + strTotalMillege + "~" + strTotalMillegeAmount + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + strTotalTax + "~" + strTotalTaxAmount; gc.insert_date(orderNumber, strAccountNo, 437, strTaxValoremDetails, 1, DateTime.Now); } } try { strTaxNonValorem = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[9]/td")).Text; } catch { } try { IWebElement ITaxNonValoremTable = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[10]/td/table[1]/tbody")); IList <IWebElement> ITaxNonValoremRow = ITaxNonValoremTable.FindElements(By.TagName("tr")); IList <IWebElement> ITaxNonValoremTD; foreach (IWebElement Nvalorem in ITaxNonValoremRow) { ITaxNonValoremTD = Nvalorem.FindElements(By.TagName("td")); if (ITaxNonValoremTD.Count != 0 && !Nvalorem.Text.Contains("Code")) { try { strNonCode = ITaxNonValoremTD[0].Text; strNonAuthority = ITaxNonValoremTD[1].Text; strNonAmount = ITaxNonValoremTD[2].Text; string strTaxNonValoremDetails = strTaxNonValorem + "~" + "-" + "~" + strNonCode + "~" + strNonAuthority + "~" + "-" + "~" + "-" + "~" + "-" + "~" + strNonAmount; gc.insert_date(orderNumber, strAccountNo, 439, strTaxNonValoremDetails, 1, DateTime.Now); } catch { } } } } catch { } try { IWebElement ITaxTotalAssessTable = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[10]/td/table[2]/tbody")); IList <IWebElement> ITaxTotalAssessRow = ITaxTotalAssessTable.FindElements(By.TagName("tr")); IList <IWebElement> ITaxTotalAssessTD; foreach (IWebElement totalass in ITaxTotalAssessRow) { ITaxTotalAssessTD = totalass.FindElements(By.TagName("td")); if (ITaxTotalAssessTD.Count != 0 && totalass.Text.Contains("Total Assessments ")) { strTotalAss = ITaxTotalAssessTD[0].Text; strTotalAssAmount = ITaxTotalAssessTD[1].Text; string strTaxTotalAssess = "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + strTotalAss + "~" + strTotalAssAmount; gc.insert_date(orderNumber, strAccountNo, 439, strTaxTotalAssess, 1, DateTime.Now); } } } catch { } try { IWebElement ITotalTaxAssess = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[3]/tbody/tr[11]/td/table/tbody")); IList <IWebElement> ITotalTaxAssessRow = ITotalTaxAssess.FindElements(By.TagName("tr")); IList <IWebElement> ITotalTaxAssessTD; foreach (IWebElement Totaltax in ITotalTaxAssessRow) { ITotalTaxAssessTD = Totaltax.FindElements(By.TagName("td")); if (ITotalTaxAssessTD.Count != 0 && Totaltax.Text.Contains("Taxes & Assessments ")) { strTotalTaxAssess = ITotalTaxAssessTD[2].Text; strTotalTaxAssessAmount = ITotalTaxAssessTD[3].Text; string strTotalTaxAssessDetails = "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + strTotalTaxAssess + "~" + strTotalTaxAssessAmount; gc.insert_date(orderNumber, strAccountNo, 439, strTotalTaxAssessDetails, 1, DateTime.Now); } } } catch { } try { IWebElement IDTaxTable = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[4]/tbody/tr/td/table/tbody")); IList <IWebElement> IDTaxRow = IDTaxTable.FindElements(By.TagName("tr")); IList <IWebElement> IDTaxTD; foreach (IWebElement DTax in IDTaxRow) { IDTaxTD = DTax.FindElements(By.TagName("td")); if (IDTaxTD.Count != 0 && !DTax.Text.Contains("If Paid By")) { strDPaid = IDTaxTD[0].Text; strPAmount = IDTaxTD[1].Text; string strDTaxDetails = strDPaid + "~" + strPAmount + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-"; gc.insert_date(orderNumber, strAccountNo, 442, strDTaxDetails, 1, DateTime.Now); } } } catch { } try { IWebElement IDTaxTransactionTable = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[5]/tbody")); IList <IWebElement> IDTaxTransactionRow = IDTaxTransactionTable.FindElements(By.TagName("tr")); IList <IWebElement> IDTaxTransactionTD; foreach (IWebElement Transaction in IDTaxTransactionRow) { IDTaxTransactionTD = Transaction.FindElements(By.TagName("td")); if (IDTaxTransactionTD.Count != 0 && !Transaction.Text.Contains("Date Paid")) { strDatePaid = IDTaxTransactionTD[0].Text; strTransaction = IDTaxTransactionTD[1].Text; strReciept = IDTaxTransactionTD[2].Text; strDyear = IDTaxTransactionTD[3].Text; strDAmount = IDTaxTransactionTD[4].Text; string strTotalTaxAssessDetails = "-" + "~" + "-" + "~" + strDatePaid + "~" + strTransaction + "~" + strReciept + "~" + strDyear + "~" + strDAmount + "~" + "-"; gc.insert_date(orderNumber, strAccountNo, 442, strTotalTaxAssessDetails, 1, DateTime.Now); } } } catch { } try { IWebElement IDPriorTax = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table[6]/tbody/tr[2]/td/table/tbody")); IList <IWebElement> IDPriorTaxRow = IDPriorTax.FindElements(By.TagName("tr")); IList <IWebElement> IDPriorTaxTD; foreach (IWebElement prior in IDPriorTaxRow) { IDPriorTaxTD = prior.FindElements(By.TagName("td")); if (IDPriorTaxTD.Count != 0) { strDPrior = IDPriorTaxTD[0].Text; string strTotalTaxAssessDetails = "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + strDPrior; gc.insert_date(orderNumber, strAccountNo, 442, strTotalTaxAssessDetails, 1, DateTime.Now); } } } catch { } try { IWebElement IPaySearch = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[1]/td[1]/table/tbody/tr[2]/td/table/tbody/tr[7]/td")).FindElement(By.TagName("a")); string strPaySearch = IPaySearch.GetAttribute("href"); driver.Navigate().GoToUrl(strPaySearch); Thread.Sleep(3000); gc.CreatePdf(orderNumber, strParcelNumber, "Tax Payment History Result", driver, "FL", "Polk"); } catch { } try { IWebElement ITaxPaymentTable = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table/tbody/tr/td/table[2]/tbody")); IList <IWebElement> ITaxPaymentRow = ITaxPaymentTable.FindElements(By.TagName("tr")); IList <IWebElement> ITaxPaymentTD; foreach (IWebElement Pay in ITaxPaymentRow) { ITaxPaymentTD = Pay.FindElements(By.TagName("td")); if (ITaxPaymentTD.Count != 0 && !Pay.Text.Contains("Account Number ")) { strTaxPayType = ITaxPaymentTD[1].Text; strTaxPayYear = ITaxPaymentTD[2].Text; string strTotalTaxAssessD = strTaxPayType + "~" + strTaxPayYear + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-" + "~" + "-"; gc.insert_date(orderNumber, strAccountNo, 443, strTotalTaxAssessD, 1, DateTime.Now); } } } catch { } for (int i = 3; i < 30; i++) { try { IWebElement ITaxPHTable = driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr[2]/td[2]/table/tbody/tr/td/table/tbody/tr/td/table[" + i + "]/tbody")); IList <IWebElement> ITaxPHRow = ITaxPHTable.FindElements(By.TagName("tr")); IList <IWebElement> ITaxPHTD; foreach (IWebElement History in ITaxPHRow) { ITaxPHTD = History.FindElements(By.TagName("td")); if (ITaxPHTD.Count != 0 && !History.Text.Contains("Year ") && !History.Text.Contains("Paid By ") && !History.Text.Contains("Payment History")) { try { strTaxPHYear = ITaxPHTD[0].Text; strTaxPayFolio = ITaxPHTD[1].Text; strTaxPayDatePaid = ITaxPHTD[2].Text; strTaxPayReceipt = ITaxPHTD[3].Text; strTaxPayAmountBilled = ITaxPHTD[4].Text; strTaxPayAmountPaid = ITaxPHTD[5].Text; strTaxPayDetails = strTaxPHYear + "~" + strTaxPayFolio + "~" + strTaxPayDatePaid + "~" + strTaxPayReceipt + "~" + strTaxPayAmountBilled + "~" + strTaxPayAmountPaid; } catch { } } string[] strTaxPayCount = strTaxPayDetails.Split('~'); if (ITaxPHTD.Count != 0 && strTaxPayCount.Length == 6 && (History.Text.Contains("Paid By ") || !History.Text.Trim().Contains(""))) { strTaxPaidBy = ITaxPHTD[1].Text; if (strTaxPayDetails.Replace("-", "").Replace("~", "") != "") { string strTotalTaxAssessDetails = "-" + "~" + "-" + "~" + strTaxPayDetails + "~" + strTaxPaidBy; gc.insert_date(orderNumber, strAccountNo, 443, strTotalTaxAssessDetails, 1, DateTime.Now); } } } } catch { } } TaxTime = DateTime.Now.ToString("HH:mm:ss"); LastEndTime = DateTime.Now.ToString("HH:mm:ss"); gc.insert_TakenTime(orderNumber, "FL", "Polk", StartTime, AssessmentTime, TaxTime, CitytaxTime, LastEndTime); driver.Quit(); gc.mergpdf(orderNumber, "FL", "Polk"); return("Data Inserted Successfully"); } catch (Exception ex) { driver.Quit(); throw ex; } } }
/// <summary> /// 设计项目试验7的打印报表 /// </summary> /// <param name="filepath"></param> public static void Exp_PDF2(string filepath, int status) { PdfReader pdfReader = null; PdfImportedPage pageTemplate = null; int i, j, k; Document document = null; Paragraph Title; //============================================加载模板并在模板后添加新表格================================================== string tempPath = Path.GetDirectoryName(filepath) + Path.GetFileNameWithoutExtension(filepath) + "_temp.pdf"; try { pdfReader = new PdfReader(filepath); Rectangle pageSize = pdfReader.GetPageSize(1); document = new Document(pageSize); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(tempPath, FileMode.Create)); document.Open(); int total = pdfReader.NumberOfPages + 1; PdfContentByte cbUnder = writer.DirectContentUnder; for (i = 1; i < total; i++) { pageTemplate = writer.GetImportedPage(pdfReader, i); cbUnder.AddTemplate(pageTemplate, 0, 0); document.NewPage(); } //============================================设计试验7的表格================================================== table = new PdfPTable(2);// 设计试验7的表格总共有6列 table.WidthPercentage = 100; if (MainFrom.comBoxData_Form == "HBK-II/1") { Title = new Paragraph("7. 滑板控制装置连续收板(程控20次)试验记录", fonttitle); } else { Title = new Paragraph("8. 滑板控制装置连续收板(程控20次)试验记录", fonttitle); } Title.SetAlignment("center"); document.Add(Title); nullb = new Paragraph(" ", fonttitle2); nullb.Leading = 10; //此数值用于调整空白大小0 document.Add(nullb); int flag = 1; PdfPTable table1 = new PdfPTable(6); PdfPTable table2 = new PdfPTable(6); if (status == 0) { dtb = SY7_DB(); } else { dtb = History.Final_Pdf("SY7_Lxsb_Ck_Final"); } table1 = Export_Table_Design.SY7_Table1(table1, ref flag, dtb); //表格7设计单独做一个函数 table2 = Export_Table_Design.SY7_Table2(table2, ref flag, dtb); //表格7设计单独做一个函数 cell1 = new PdfPCell(table1); cell1.Padding = 0; table.AddCell(cell1); cell1 = new PdfPCell(table2); cell1.Padding = 0.5f; table.AddCell(cell1); document.Add(table); //將table放到pdf文件中 Title = new Paragraph(" 注:试验中“√”表示动作正常,“×”表示动作异常", fonttitle3); document.Add(Title); //将标题段加入PDF文档中 } catch (Exception ex) { throw ex; } finally { document.Close(); if (pdfReader != null) { pdfReader.Close(); } File.Copy(tempPath, filepath, true); File.Delete(tempPath); } }
/// <summary> /// 加载设计的pdf模板,并对需要赋值的地方赋值 /// </summary> public static void Exp_PDF(int status) { String str = " "; SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Text documents (*.pdf)|*.pdf"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出Text文件到"; DateTime now = DateTime.Now; if (status == 0) { string date = now.Year.ToString().PadLeft(2) + "-" + now.Month.ToString().PadLeft(2, '0') + "-" + now.Day.ToString().PadLeft(2, '0'); SY_Data data = new SY_Data(MainFrom.comBoxData_Form, MainFrom.textB_HbData_Form, MainFrom.textB_CgqData_Form, MainFrom.Uname, date); getCount(data); string[] com = MainFrom.comBoxData_Form.Split('/'); string pno = ""; for (int k = 0; k < com.Length; k++) { pno = pno + com[k]; } saveFileDialog.FileName = count + "_" + pno + "_" + MainFrom.textB_HbData_Form + "_" + MainFrom.Uname + "_" + MainFrom.textB_CgqData_Form + "_" + now.Year.ToString().PadLeft(2) + "" + now.Month.ToString().PadLeft(2, '0') + "" + now.Day.ToString().PadLeft(2, '0') + "-" + now.Hour.ToString().PadLeft(2, '0') + "" + now.Minute.ToString().PadLeft(2, '0') + "" + now.Second.ToString().PadLeft(2, '0'); } else { string[] com = History.Cp_no.Split('/'); string p_no = ""; for (int k = 0; k < com.Length; k++) { p_no = p_no + com[k]; } saveFileDialog.FileName = History.Sycs + "_" + p_no + "_" + History.Kzx_no + "_" + History.Czy + "_" + History.Cgq_no + "_" + History.Sy_date + "-" + now.Hour.ToString().PadLeft(2, '0') + "" + now.Minute.ToString().PadLeft(2, '0') + "" + now.Second.ToString().PadLeft(2, '0'); } DialogResult result = saveFileDialog.ShowDialog(); if (result == DialogResult.OK) { PdfReader pdfReader; PdfStamper pdfStamper; AcroFields pdfFormFields; BaseFont bf1 = BaseFont.CreateFont("C:\\Windows\\Fonts\\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //文件保存的真正路径 string tempFilePath = saveFileDialog.FileName; string path = AppDomain.CurrentDomain.BaseDirectory, sql; int flag = 1; if (MainFrom.comBoxData_Form == "HBK-II/1") { path = System.IO.Directory.GetParent(path).Parent.Parent.FullName + "\\II型车.pdf"; pdfReader = new PdfReader(path);//模板的路径 pdfStamper = new PdfStamper(pdfReader, new FileStream(tempFilePath, FileMode.OpenOrCreate)); pdfFormFields = pdfStamper.AcroFields; pdfStamper.FormFlattening = true; pdfFormFields.AddSubstitutionFont(bf1); if (status == 0) { pdfFormFields.SetField("CPXH", MainFrom.comBoxData_Form); pdfFormFields.SetField("HBKZXBH", MainFrom.textB_HbData_Form); pdfFormFields.SetField("JDCGQBH", MainFrom.textB_CgqData_Form); pdfFormFields.SetField("SYY", MainFrom.Uname); } else { pdfFormFields.SetField("CPXH", History.Cp_no); pdfFormFields.SetField("HBKZXBH", History.Kzx_no); pdfFormFields.SetField("JDCGQBH", History.Cgq_no); pdfFormFields.SetField("SYY", History.Czy); } //试验1的报表 if (status == 0) { dtb = SY1_DB(); } else { dtb = History.Final_Pdf("SY1_Fdsk_Final"); } Export_Table_Design.SY1_Table(pdfFormFields, ref flag, dtb); flag = 1; if (status == 0) { dtb = SY2_DB(); } else { dtb = History.Final_Pdf("SY2_Gzzd_Final"); } Export_Table_Design.SY2_Table(pdfFormFields, ref flag, dtb); pdfStamper.Close(); pdfReader.Close(); } else { path = System.IO.Directory.GetParent(path).Parent.Parent.FullName + "\\I型车.pdf"; pdfReader = new PdfReader(path);//模板的路径 pdfStamper = new PdfStamper(pdfReader, new FileStream(tempFilePath, FileMode.OpenOrCreate)); pdfFormFields = pdfStamper.AcroFields; pdfStamper.FormFlattening = true; pdfFormFields.AddSubstitutionFont(bf1); if (status == 0) { pdfFormFields.SetField("CPXH", MainFrom.comBoxData_Form); pdfFormFields.SetField("HBKZXBH", MainFrom.textB_HbData_Form); pdfFormFields.SetField("JDCGQBH", MainFrom.textB_CgqData_Form); pdfFormFields.SetField("SYY", MainFrom.Uname); } else { pdfFormFields.SetField("CPXH", History.Cp_no); pdfFormFields.SetField("HBKZXBH", History.Kzx_no); pdfFormFields.SetField("JDCGQBH", History.Cgq_no); pdfFormFields.SetField("SYY", History.Czy); } //试验1的报表 if (status == 0) { dtb = SY1_DB(); } else { dtb = History.Final_Pdf("SY1_Fdsk_Final"); } Export_Table_Design.SY1_Table(pdfFormFields, ref flag, dtb); flag = 1; if (status == 0) { dtb = SY2_DB(); } else { dtb = History.Final_Pdf("SY2_Gzzd_Final"); } Export_Table_Design.SY2_Table(pdfFormFields, ref flag, dtb); pdfStamper.Close(); pdfReader.Close(); } Exp_PDF1(saveFileDialog.FileName, status); } }
private void Transcript(object sender, RoutedEventArgs e) { var transcript = History.ToArray(); var request = HttpWebRequest.Create(new Uri(baseUrl + "/UploadTranscript.ashx", UriKind.Absolute)); request.Method = "POST"; request.BeginGetRequestStream(delegate(IAsyncResult requestResult) { try { using (var stream = request.EndGetRequestStream(requestResult)) { var settings = new XmlWriterSettings { Indent = true, IndentChars = "\t" }; using (var writer = XmlWriter.Create(stream, settings)) { // writer.WriteProcessingInstruction( "xml-stylesheet", "type=\"text/xsl\" encoding=\"UTF-8\" href=\"Transcript.xslt\" version=\"1.0\"" ); writer.WriteStartElement("Transcript"); writer.WriteAttributeString("storyUrl", Uri.UnescapeDataString("ShadowDemo")); foreach (var item in transcript) { if (item.HasInput) { writer.WriteElementString("Input", item.Input); } if (item.HasOutput) { writer.WriteStartElement("Output"); foreach (var channel in item.OutputArgs.Package) { writer.WriteStartElement(channel.Key.ToString()); if (channel.Value.IsXml()) { writer.WriteRaw(StoryHistoryItem.EnsureXml(channel.Value)); } else { writer.WriteString(channel.Value); } writer.WriteEndElement(); } writer.WriteEndElement(); } } writer.WriteEndElement(); } } request.BeginGetResponse(delegate(IAsyncResult responseResult) { try { var response = request.EndGetResponse(responseResult); var buffer = new byte[response.ContentLength]; response.GetResponseStream().Read(buffer, 0, buffer.Length); Dispatcher.BeginInvoke(delegate { HtmlPage.Window.Navigate( new Uri(string.Format("{0}/Transcript.aspx?k={1}", baseUrl, Encoding.UTF8.GetString(buffer, 0, buffer.Length))), "_blank"); }); } // TODO: Handle this... catch { } }, null); } // TODO: Handle this... catch { } }, null); }
public virtual IActionResult HistoriesIdPut([FromRoute] int id, [FromBody] History item) { return(this._service.HistoriesIdPutAsync(id, item)); }
public virtual IActionResult HistoriesPost([FromBody] History item) { return(this._service.HistoriesPostAsync(item)); }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); // get person Person person = null; string personAttributeValue = GetAttributeValue( action, "Person" ); Guid? guidPersonAttribute = personAttributeValue.AsGuidOrNull(); if ( guidPersonAttribute.HasValue ) { var attributePerson = AttributeCache.Read( guidPersonAttribute.Value, rockContext ); if ( attributePerson != null || attributePerson.FieldType.Class != "Rock.Field.Types.PersonFieldType" ) { string attributePersonValue = action.GetWorklowAttributeValue( guidPersonAttribute.Value ); if ( !string.IsNullOrWhiteSpace( attributePersonValue ) ) { Guid personAliasGuid = attributePersonValue.AsGuid(); if ( !personAliasGuid.IsEmpty() ) { person = new PersonAliasService( rockContext ).Queryable() .Where( a => a.Guid.Equals( personAliasGuid ) ) .Select( a => a.Person ) .FirstOrDefault(); if ( person == null ) { errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString() ) ); return false; } } } } } if ( person == null ) { errorMessages.Add( "The attribute used to provide the person was invalid, or not of type 'Person'." ); return false; } // determine the phone type to edit DefinedValueCache phoneType = null; var phoneTypeAttributeValue = action.GetWorklowAttributeValue( GetAttributeValue( action, "PhoneTypeAttribute" ).AsGuid() ); if ( phoneTypeAttributeValue != null ) { phoneType = DefinedValueCache.Read( phoneTypeAttributeValue.AsGuid() ); } if ( phoneType == null ) { phoneType = DefinedValueCache.Read( GetAttributeValue( action, "PhoneType" ).AsGuid() ); } if ( phoneType == null ) { errorMessages.Add( "The phone type to be updated was not selected." ); return false; } // get the ignore blank setting var ignoreBlanks = GetActionAttributeValue( action, "IgnoreBlankValues" ).AsBoolean( true ); // get the new phone number value string phoneNumberValue = GetAttributeValue( action, "PhoneNumber" ); Guid? phoneNumberValueGuid = phoneNumberValue.AsGuidOrNull(); if ( phoneNumberValueGuid.HasValue ) { phoneNumberValue = action.GetWorklowAttributeValue( phoneNumberValueGuid.Value ); } else { phoneNumberValue = phoneNumberValue.ResolveMergeFields( GetMergeFields( action ) ); } phoneNumberValue = PhoneNumber.CleanNumber( phoneNumberValue ); // gets value indicating if phone number is unlisted string unlistedValue = GetAttributeValue( action, "Unlisted" ); Guid? unlistedValueGuid = unlistedValue.AsGuidOrNull(); if ( unlistedValueGuid.HasValue ) { unlistedValue = action.GetWorklowAttributeValue( unlistedValueGuid.Value ); } else { unlistedValue = unlistedValue.ResolveMergeFields( GetMergeFields( action ) ); } bool? unlisted = unlistedValue.AsBooleanOrNull(); // gets value indicating if messaging should be enabled for phone number string smsEnabledValue = GetAttributeValue( action, "MessagingEnabled" ); Guid? smsEnabledValueGuid = smsEnabledValue.AsGuidOrNull(); if ( smsEnabledValueGuid.HasValue ) { smsEnabledValue = action.GetWorklowAttributeValue( smsEnabledValueGuid.Value ); } else { smsEnabledValue = smsEnabledValue.ResolveMergeFields( GetMergeFields( action ) ); } bool? smsEnabled = smsEnabledValue.AsBooleanOrNull(); var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneType.Id ); string oldValue = string.Empty; if ( phoneNumber == null ) { phoneNumber = new PhoneNumber { NumberTypeValueId = phoneType.Id }; person.PhoneNumbers.Add( phoneNumber ); } else { oldValue = phoneNumber.NumberFormattedWithCountryCode; } if ( !string.IsNullOrWhiteSpace( phoneNumberValue ) || !ignoreBlanks ) { phoneNumber.Number = phoneNumberValue; } if ( unlisted.HasValue ) { phoneNumber.IsUnlisted = unlisted.Value; } if ( smsEnabled.HasValue ) { phoneNumber.IsMessagingEnabled = smsEnabled.Value; } var changes = new List<string>(); History.EvaluateChange( changes, string.Format( "{0} Phone", phoneType.Value ), oldValue, phoneNumber.NumberFormattedWithCountryCode ); if ( changes.Any() ) { changes.Add( string.Format( "<em>(Updated by the '{0}' workflow)</em>", action.ActionType.ActivityType.WorkflowType.Name ) ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes, false ); } rockContext.SaveChanges(); action.AddLogEntry( string.Format( "Updated {0} phone for {1} to {2}.", phoneType.Value, person.FullName, phoneNumber.NumberFormattedWithCountryCode ) ); return true; }
/// <param name="args"> array of command line arguments </param> public static void Main(string[] args) { initialize_History(); initialize_KeyMapEntry(); // TODO: Check and accomplish variable declarations: string varPart; // Converts the input to lowercase, cuts out interpunctation // and pads the string string userInput; string reply; int posAster; int[] offsets; bool isRepeated; bool isGone; int[] findInfo; // TODO: You may have to modify input instructions, // possibly by enclosing Console.ReadLine() calls with // Parse methods according to the variable type, e.g.: // i = int.Parse(Console.ReadLine()); // Title information Console.WriteLine("************* ELIZA **************"); Console.WriteLine("* Original design by J. Weizenbaum"); Console.WriteLine("**********************************"); Console.WriteLine("* Adapted for Basic on IBM PC by"); Console.WriteLine("* - Patricia Danielson"); Console.WriteLine("* - Paul Hashfield"); Console.WriteLine("**********************************"); Console.WriteLine("* Adapted for Structorizer by"); Console.WriteLine("* - Kay Gürtzig / FH Erfurt 2016"); Console.WriteLine("* Version: 2.3 (2020-02-24)"); Console.WriteLine("* (Requires at least Structorizer 3.30-03 to run)"); Console.WriteLine("**********************************"); // Stores the last five inputs of the user in a ring buffer, // the second component is the rolling (over-)write index. History history = new History(new string[] { "", "", "", "", "" }, 0); const string[,] replies = setupReplies(); const string[,] reflexions = setupReflexions(); const string[,] byePhrases = setupGoodByePhrases(); const KeyMapEntry[] keyMap = setupKeywords(); offsets[length(keyMap) - 1] = 0; isGone = false; // Starter Console.WriteLine("Hi! I\'m your new therapist. My name is Eliza. What\'s your problem?"); do { userInput = Console.ReadLine(); // Converts the input to lowercase, cuts out interpunctation // and pads the string // Converts the input to lowercase, cuts out interpunctation // and pads the string userInput = normalizeInput(userInput); isGone = checkGoodBye(userInput, byePhrases); if (!isGone) { reply = "Please don\'t repeat yourself!"; isRepeated = checkRepetition(history, userInput); if (!isRepeated) { findInfo = findKeyword(keyMap, userInput); ??? keyIndex = findInfo[0]; if (keyIndex < 0) { // Should never happen... keyIndex = length(keyMap) - 1; } KeyMapEntry entry = keyMap[keyIndex]; // Variable part of the reply varPart = ""; if (length(entry.keyword) > 0) { varPart = conjugateStrings(userInput, entry.keyword, findInfo[1], reflexions); }
public HistoryModel(History histories) { this.Assign(histories); Periods = new HistoryModel(); }
public async Task CreateHistory(History history) { // Check if employee exists in the db if (await RecordExists(history)) { throw new InvalidOperationException("This history record already exists."); } // Create a person entity with all needed relations var person = new Person { BusinessEntity = new BusinessEntity { rowguid = Guid.NewGuid(), ModifiedDate = DateTime.Now, BusinessEntityAddress = new List <BusinessEntityAddress> { new BusinessEntityAddress { Address = new Address { AddressLine1 = "Not specified", AddressLine2 = Guid.NewGuid().ToString(), // to avoid bug with 2 different employees having the same address City = "Not specified", PostalCode = "Not specified", rowguid = Guid.NewGuid(), ModifiedDate = DateTime.Now, StateProvince = await context.StateProvince.FirstOrDefaultAsync() }, AddressType = await context.AddressType.FirstOrDefaultAsync(at => at.Name == "Home"), ModifiedDate = DateTime.Now, rowguid = Guid.NewGuid() } } }, FirstName = history.FirstName, LastName = history.LastName, PersonType = "EM", NameStyle = false, EmailPromotion = 0, rowguid = Guid.NewGuid(), ModifiedDate = DateTime.Now, }; // Create new employee with random properties var random = new Random(); var employee = new DAL.Employee { Person = person, NationalIDNumber = random.Next().ToString(), LoginID = $"adventure-works/{history.FirstName.ToLower() + random.Next().ToString()}", JobTitle = "Intern", BirthDate = new DateTime(random.Next(1970, 2000), random.Next(1, 12), random.Next(1, 28)), MaritalStatus = "S", Gender = random.Next(0, 1) == 1 ? "M" : "F", HireDate = DateTime.Now - TimeSpan.FromDays(1), SalariedFlag = false, VacationHours = 25, SickLeaveHours = 0, CurrentFlag = true, rowguid = Guid.NewGuid(), ModifiedDate = DateTime.Now }; Department department = await context.Department.Where(e => e.Name == history.Department).FirstAsync(); Shift shift = await context.Shift.Where(e => e.ShiftID == 1).FirstAsync(); var record = new EmployeeDepartmentHistory { ShiftID = shift.ShiftID, StartDate = history.StartDate, EndDate = history.EndDate, ModifiedDate = DateTime.Now, Department = department, Employee = employee, Shift = shift }; context.EmployeeDepartmentHistory.Add(record); await context.SaveChangesAsync(); }
/// <summary> /// 设计试验3到试验6的打印报表 /// </summary> /// <param name="filepath"></param> public static void Exp_PDF1(string filepath, int status) { PdfReader pdfReader = null; PdfImportedPage pageTemplate = null; int i, j, k; Document document = null; Paragraph Title; //============================================加载模板并在模板后添加新表格================================================== string tempPath = Path.GetDirectoryName(filepath) + Path.GetFileNameWithoutExtension(filepath) + "_temp.pdf"; try { pdfReader = new PdfReader(filepath); Rectangle pageSize = pdfReader.GetPageSize(1); document = new Document(pageSize); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(tempPath, FileMode.Create)); document.Open(); int total = pdfReader.NumberOfPages + 1; PdfContentByte cbUnder = writer.DirectContentUnder; for (i = 1; i < total; i++) { pageTemplate = writer.GetImportedPage(pdfReader, i); cbUnder.AddTemplate(pageTemplate, 0, 0); document.NewPage(); } //============================================设计试验3的表格================================================== table = new PdfPTable(3);// 设计试验3的表格总共有3列 table.WidthPercentage = 82; table.SetTotalWidth(new float[] { 100f, 200f, 250f }); ///表頭設計 //添加段落,第二个参数指定使用fonttitle格式的字体,写入中文必须指定字体否则无法显示中文 Title = new Paragraph("3. 滑板控制装置首板收板时间试验记录", fonttitle); Title.SetAlignment("center"); //设置居中 document.Add(Title); //将标题段加入PDF文档中 //空一行 nullb = new Paragraph(" ", fonttitle2); nullb.Leading = 10; //此数值用于调整空白大小0 document.Add(nullb); if (status == 0) { dtb = SY3_DB();//表格3设计单独做一个函数 } else { dtb = History.Final_Pdf("SY3_Timer_Final"); } table = Export_Table_Design.SY3_Table(table, dtb); document.Add(table);//將table放到pdf文件中 //===================================================设计试验4的表格================================= //空一行 nullb = new Paragraph(" ", fonttitle2); nullb.Leading = 60; //此数值用于调整空白大小0 document.Add(nullb); table = new PdfPTable(5); // 设计试验4的表格总共有5列 table.WidthPercentage = 82; table.SetTotalWidth(new float[] { 100f, 200f, 200f, 200f, 200f }); Title = new Paragraph("4. 滑板控制装置连续收板(手动20次)试验记录", fonttitle); Title.SetAlignment("center"); document.Add(Title); nullb = new Paragraph(" ", fonttitle2); nullb.Leading = 10; //此数值用于调整空白大小0 document.Add(nullb); if (status == 0) { dtb = SY4_DB();//表格4设计单独做一个函数 } else { dtb = History.Final_Pdf("SY4_Lxsb_Final"); } table = Export_Table_Design.SY4_Table(table, dtb); document.Add(table); //將table放到pdf文件中 Title = new Paragraph(" 注:试验中“√”表示动作正常,“×”表示动作异常", fonttitle3); document.Add(Title); //将标题段加入PDF文档中 //=============================================添加新的一页,设计试验5的表格========================= document.SetPageSize(PageSize.A4.Rotate()); // 重新设置文档为横向 document.NewPage(); table = new PdfPTable(18); // 设计试验5的表格总共有18列 table.WidthPercentage = 100; Title = new Paragraph("5. 滑板控制装置分档程控控制及程控精度试验记录", fonttitle); Title.SetAlignment("center"); document.Add(Title); nullb = new Paragraph(" ", fonttitle2); nullb.Leading = 10; //此数值用于调整空白大小0 document.Add(nullb); if (status == 0) { dtb = SY5_DB();//表格5设计单独做一个函数 } else { dtb = History.Final_Pdf("SY5_Fdck_Final"); } table = Export_Table_Design.SY5_Table(table, dtb); document.Add(table); //將table放到pdf文件中 Title = new Paragraph(" 注:表中θ表示尾翼板角度,β表示首下板角度,φ表示首上板角度", fonttitle3); document.Add(Title); //将标题段加入PDF文档中 //=============================================添加新的一页,设计试验6的表格========================= document.SetPageSize(PageSize.A4.Rotate()); // 重新设置文档为横向 document.NewPage(); table = new PdfPTable(21); // 设计试验6的表格总共有21列 table.WidthPercentage = 100; Title = new Paragraph("6. 滑板控制装置系统调试精度试验记录", fonttitle); Title.SetAlignment("center"); document.Add(Title); nullb = new Paragraph(" ", fonttitle2); nullb.Leading = 10; //此数值用于调整空白大小0 document.Add(nullb); if (status == 0) { dtb = SY6_DB();//表格3设计单独做一个函数 } else { dtb = History.Final_Pdf("SY6_Xtts_Final"); } table = Export_Table_Design.SY6_Table(table, dtb); document.Add(table);//將table放到pdf文件中 Title = new Paragraph("注:表中θ表示尾翼板角度,β表示首下板角度,φ表示首上板角度", fonttitle3); Title.SetAlignment("center"); document.Add(Title); //将标题段加入PDF文档中 //=============================================添加新的一页,设计火炮试验的表格========================= if (MainFrom.comBoxData_Form != "HBK-II/1") { document.SetPageSize(PageSize.A4.Rotate()); // 重新设置文档为横向 document.NewPage(); table = new PdfPTable(13); // 设计试验8的表格总共有13列 table.WidthPercentage = 100; Paragraph Title1 = new Paragraph("7. 滑板控制装置(I型车)火炮联锁试验记录", fonttitle); Title1.SetAlignment("center"); document.Add(Title1); nullb = new Paragraph(" ", fonttitle2); nullb.Leading = 10; //此数值用于调整空白大小0 document.Add(nullb); if (status == 0) { dtb = SY8_DB();//表格火炮联锁试验设计单独做一个函数 } else { dtb = History.Final_Pdf("SY8_Hplx_Final"); } table = Export_Table_Design.SY8_Table(table, dtb); document.Add(table); //將table放到pdf文件中 Title1 = new Paragraph("注:试验中“√”表示动作正常,“×”表示动作异常", fonttitle3); document.Add(Title1); //将标题段加入PDF文档中 } } catch (Exception ex) { throw ex; } finally { document.Close(); if (pdfReader != null) { pdfReader.Close(); } File.Copy(tempPath, filepath, true); File.Delete(tempPath); Exp_PDF2(filepath, status); } }
/// <summary> /// When a task fails, follow the error outflow if one exists else fail the workflow /// </summary> /// <param name="db"></param> /// <param name="workflow"></param> /// <param name="execution"></param> /// <param name="history"></param> /// <param name="decisions"></param> private static void ProcessActivityTaskFailedEvent(Database db, WorkflowObj workflow, Execution execution, History history, List <History> decisions) { // There should(!) be no contention for the data modified in this process var evt = ActivityTaskFailedEvent.Create(history); var se = ActivityTaskScheduledEvent.Create(db.GetHistoryEvent(execution.ExecutionId, evt.SchedulingEventId)); var failedTask = workflow.Tasks.Single(t => t.TaskId == se.TaskId); var nextTaskId = failedTask.FailOutflow?.Target; if (!string.IsNullOrEmpty(nextTaskId)) { var nextTask = workflow.Tasks.Single(t => t.TaskId == nextTaskId); CreateTaskScheduledEvent(db, execution, nextTask, decisions); } decisions.Add(new WorkflowExecutionFailedEvent { Reason = $"Task {se.TaskId} failed with no recovery action defined" }); AttemptCleanup(db, execution, workflow, decisions); }
public IEnumerator showDialog(Dialog d) { yield return(null); // for proper dialog rendering if (!(d.areControlsSet())) { throw new Exception("Not all elements of dialog has been set."); } dialog = new GameObject("Icon Dialog"); dialog.transform.SetParent(Runtime.canvas.transform); dialog.transform.position = new Vector2(Screen.width / 2f, Screen.height / 2f); // creating dim (background) view GameObject dialogDim = new GameObject("Dim", typeof(Button), typeof(UnityEngine.UI.Image)); dialogDim.transform.SetParent(dialog.transform); dialogDim.transform.localPosition = Vector2.zero; dialogDim.GetComponent <UnityEngine.UI.Image>().color = Color.clear; dialogDim.GetComponent <RectTransform>().sizeDelta = new Vector2(Screen.width, Screen.height); dialogDim.GetComponent <Button>().targetGraphic = dialogDim.GetComponent <UnityEngine.UI.Image>(); dialogDim.GetComponent <Button>().onClick.AddListener(() => { History.GoBack(); }); History.AddWindow(this); // creating panel GameObject dialogPanel = new GameObject("Dialog Panel", typeof(UnityEngine.UI.Image)); dialogPanel.transform.SetParent(dialog.transform); dialogPanel.GetComponent <UnityEngine.UI.Image>().color = Config.ORANGE; dialogPanel.transform.localPosition = Vector2.zero; float panelWidth = Mathf.Min(Screen.width, Screen.height) - new DP(16f); // in pixels float iconWidth = new DP(72f); float buttonWidth = new DP(90f); float textWidthWithMargins = panelWidth - iconWidth - buttonWidth; float textWidth = textWidthWithMargins - new DP(8f); float panelHeigth = new DP(80f); GameObject dialogIcon = new GameObject("Icon", typeof(UnityEngine.UI.Image)); dialogIcon.transform.SetParent(dialogPanel.transform); dialogIcon.GetComponent <RectTransform>().sizeDelta = Vector2.one * new DP(24f); dialogIcon.GetComponent <UnityEngine.UI.Image>().sprite = d.IconSprite; GameObject dialogText = new GameObject("Text", typeof(Text)); dialogText.transform.SetParent(dialogPanel.transform); dialogText.GetComponent <RectTransform>().sizeDelta = new Vector2(textWidth, dialogText.GetComponent <RectTransform>().sizeDelta.y); dialogText.GetComponent <Text>().font = Resources.Load <Font>("fonts/Roboto-Regular"); dialogText.GetComponent <Text>().fontSize = new SP(14f); dialogText.GetComponent <Text>().color = Color.black; dialogText.GetComponent <Text>().alignment = TextAnchor.MiddleCenter; dialogText.GetComponent <Text>().text = d.Text; dialogText.GetComponent <RectTransform>().sizeDelta = new Vector2(textWidth, dialogText.GetComponent <Text>().preferredHeight); GameObject positiveButton = new GameObject("Button", typeof(Button), typeof(UnityEngine.UI.Image)); positiveButton.transform.SetParent(dialogPanel.transform); GameObject positiveButtonText = new GameObject("Text", typeof(Text)); Text positiveButtonTextComponent = positiveButtonText.GetComponent <Text>(); positiveButtonText.transform.SetParent(positiveButton.transform); positiveButtonTextComponent.font = Resources.Load <Font>("fonts/Roboto-Regular"); positiveButtonTextComponent.fontSize = new SP(14f); positiveButtonTextComponent.alignment = TextAnchor.MiddleCenter; positiveButtonTextComponent.color = Color.white; positiveButtonTextComponent.text = d.ButtonText.ToUpper(); positiveButton.GetComponent <RectTransform>().sizeDelta = positiveButtonText.GetComponent <RectTransform>().sizeDelta; positiveButton.GetComponent <UnityEngine.UI.Image>().color = Color.clear; positiveButton.GetComponent <Button>().targetGraphic = positiveButton.GetComponent <UnityEngine.UI.Image>(); positiveButton.GetComponent <Button>().onClick.AddListener(() => { History.GoBack(); d.OnButtonClick(); }); dialogPanel.GetComponent <RectTransform>().sizeDelta = new Vector2(panelWidth, panelHeigth); float panelLeftX = dialogPanel.transform.position.x - panelWidth / 2f; float panelRightX = dialogPanel.transform.position.x + panelWidth / 2f; float iconPositionX = panelLeftX + iconWidth / 2f; dialogIcon.transform.position = new Vector2(iconPositionX, dialogPanel.transform.position.y); float textPositionX = panelLeftX + iconWidth + textWidthWithMargins / 2f; dialogText.transform.position = new Vector2(textPositionX, dialogPanel.transform.position.y); float buttonPositionX = panelRightX - buttonWidth / 2f; positiveButton.transform.position = new Vector2(buttonPositionX, dialogPanel.transform.position.y); float panelXposition = default(float), panelYposition = default(float), panelRotation = default(float); float panelMargin = new UI.DP(5f); // set dialog position switch (Input.deviceOrientation) { case DeviceOrientation.FaceDown: case DeviceOrientation.FaceUp: case DeviceOrientation.Portrait: case DeviceOrientation.Unknown: { panelRotation = 0f; panelXposition = Screen.width / 2f; panelYposition = d.view.yMin + panelMargin + panelHeigth / 2f; } break; case DeviceOrientation.LandscapeLeft: { panelRotation = 270f; panelXposition = d.view.xMin + panelMargin + panelHeigth / 2f;; panelYposition = Screen.height / 2f; } break; case DeviceOrientation.LandscapeRight: { panelRotation = 90f; panelXposition = d.view.xMax - panelMargin - panelHeigth / 2f;; panelYposition = Screen.height / 2f; } break; case DeviceOrientation.PortraitUpsideDown: { panelRotation = 180f; panelXposition = Screen.width / 2f; panelYposition = d.view.yMax - panelMargin - panelHeigth / 2f; } break; } dialogPanel.transform.eulerAngles = Vector3.forward * panelRotation; dialogPanel.transform.position = new Vector2(panelXposition, panelYposition); }
/// <summary> /// Two stage workflow execution start. /// First create and initialise the workflow variables /// Then schedule the first task /// If this process is interrupted then the variables /// </summary> /// <param name="db"></param> /// <param name="workflow"></param> /// <param name="execution"></param> /// <param name="history"></param> /// <param name="decisions"></param> private static void ProcessWorkflowExecutionStartedEvent(Database db, WorkflowObj workflow, Execution execution, History history, List <History> decisions) { var evt = WorkflowExecutionStartedEvent.Create(history); CreateVariables(db, evt, execution, workflow); // Ensure that the variables are set up for the first task // This should never fail due to conflict db.SubmitChanges(); // Scheduling the first task var startTaskId = workflow.Tasks.Single(t => t.ActivityName == "start").Outflows.Single(o => o.Name == "Out").Target; var startTask = workflow.Tasks.Single(t => t.TaskId == startTaskId); CreateTaskScheduledEvent(db, execution, startTask, decisions); }
public HistoryModel(History history) { Type = history.Type; Id = history.Id; LastTime = history.LastTime; }
public PositionStage(Config config, History history, bool registerByDefault, List <string> patterns, List <string> substitutions, string separatorSubstitutionSource) : base(config, history, registerByDefault, patterns, substitutions, separatorSubstitutionSource) { }
public Move MakeMove(PieceColor color) { try { var startTime = DateTime.Now; var board = Board.DeepClone(); switch (color) { case PieceColor.White: Board.LastMove = Board.MakeMove(WhitePlayerEngine.MakeMove(Board, Variant, GameMoves)); break; case PieceColor.Black: Board.LastMove = Board.MakeMove(BlackPlayerEngine.MakeMove(Board, Variant, GameMoves)); break; } var endTime = DateTime.Now; History.Add(new HistoryBoard(startTime, endTime, board, color)); if (Board.BoardArray.Where(p => p < 0).Count() == 0) { throw new NoAvailablePiecesException(PieceColor.Black, Board.LastMove); } if (Board.BoardArray.Where(p => p > 0).Count() == 0) { throw new NoAvailablePiecesException(PieceColor.White, Board.LastMove); } GameMoves.Add(Board.LastMove); if (IsDraw()) { throw new DrawException(); } return(Board.LastMove); } catch (NotAvailableMoveException exception) { string winner = ""; winner = exception.Color == PieceColor.Black ? "W" : "B"; AddGameToDatabase(winner); throw; } catch (NoAvailablePiecesException exception) { string winner = ""; switch (exception.Color) { case PieceColor.White when Variant == GameVariant.Checkers: case PieceColor.Black when Variant == GameVariant.Anticheckers: winner = "B"; break; case PieceColor.Black when Variant == GameVariant.Checkers: case PieceColor.White when Variant == GameVariant.Anticheckers: winner = "W"; break; } AddGameToDatabase(winner); throw; } catch (DrawException) { AddGameToDatabase("D"); throw; } catch { throw; } }
public async Task OnPostMovies(string intent) { showMoviePosters = "none"; await ShowPoster(Program.Fetch.Search); search = Program.Fetch.Search; this.search = Program.Fetch.Search; await Program.Fetch.GrabMovieAsync(intent); vidNinja = new JsonNinja(Program.Fetch.Videos); filter = vidNinja.GetDetails("\"results\""); vidNinja = new JsonNinja(filter[0]); List <string> vidNames = vidNinja.GetNames(); List <string> vidVals = vidNinja.GetVals(); jNinja = new JsonNinja(Program.Fetch.Details); List <string> detailNames = jNinja.GetNames(); List <string> detailVals = jNinja.GetVals(); //get movie details display = "grid"; title = jNinja.GetDetails("\"title\""); List <string> ratings = jNinja.GetIds("\"vote_average\""); rating = ratings[0] + "/10.0"; List <string> descriptions = jNinja.GetDetails("\"overview\""); description = descriptions[0]; List <string> backDrops = jNinja.GetDetails("\"poster_path\""); if (backDrops.Count == 2) { backDrop = backDrops[1];// backdrop or movieposter } else { backDrop = backDrops[0];// backdrop or movieposter } //get youtube movie keys for poster vidClips = vidNinja.GetDetails("\"key\""); //get movie cast jNinja = new JsonNinja(Program.Fetch.Credits); List <string> creditNames = jNinja.GetNames(); List <string> creditVals = jNinja.GetVals(); filter = jNinja.GetDetails("\"cast\""); jNinja = new JsonNinja(filter[0]); History.SetMovieID(creditVals[0]); //to be used by rental method History.SetBackDrop(backDrop); //same as poster, for cast page backdrop and rental method History.SetMovieTitle(title[0]); //for use with rental method List <string> actorName = jNinja.GetDetails("\"name\""); castID = jNinja.GetIds("\"id\""); actorImg = jNinja.GetDetails("\"profile_path\""); List <string> character = jNinja.GetDetails("\"character\""); int voteStat = DisplayVote(); if (voteStat == 2) { thumbsDown = 0.4f; inBetween = 0.4f; } else if (voteStat == 1) { thumbsUp = 0.4f; thumbsDown = 0.4f; } else if (voteStat == 0) { thumbsUp = 0.4f; inBetween = 0.4f; } else { //do nothing } moviePosterShow = "block"; }
public async Task <IActionResult> RegisterLocation(LocationForRegisterDto locationForRegisterDto) { var ReelsFromRepo = await _repo.GetReel(locationForRegisterDto.Id); if (ReelsFromRepo == null) { return(BadRequest("Pagal pateikta ID ritė nerasta")); } var ComponentasFromRepo = await _srepo.GetCompCMnf(ReelsFromRepo.CMnf); int likutis = ReelsFromRepo.QTY - locationForRegisterDto.QTY; if (likutis <= 0) { return(BadRequest("Rite tusčia, bandote padeti tuščia pakuotę, nurasote didesni kieki nei buvo uzregistruota riteje")); } var res = Int32.TryParse(ReelsFromRepo.Location, out _); if (res == true) { int result = Int32.Parse(ReelsFromRepo.Location); if (result > 0) { return(BadRequest("Ši ritė turėtų būti padėta į " + ReelsFromRepo.Location + " slotą !!!!!")); } } var rxmsg = await _can.SetReelLocation(); //testo tikslais /* Rxmsg rxmsg = new Rxmsg * { * DLC = 0, * ID = 2, * Msg = new byte[] { 25, 6, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF } * }; */ int Location = rxmsg.Msg[1] + (rxmsg.Msg[0] * 10); var reelByLocation = await _repo.GetByLocation(Location.ToString()); if (reelByLocation != null) { return(BadRequest("Ritės vieta jau užimta")); } var user = await _userManager.FindByIdAsync(locationForRegisterDto.UserId); var HistoryToCreate = new History { Mnf = ReelsFromRepo.CMnf, NewLocation = Location.ToString(), NewQty = likutis, OldLocation = ReelsFromRepo.Location, OldQty = ReelsFromRepo.QTY, ComponentasId = ComponentasFromRepo.Id, DateAdded = DateTime.Now, ReelId = locationForRegisterDto.Id, UserId = user.Id }; var createHistory = await _srepo.RegisterHistory(HistoryToCreate); locationForRegisterDto.QTY = likutis; locationForRegisterDto.UserId = null; locationForRegisterDto.Location = Location.ToString(); _mapper.Map(locationForRegisterDto, ReelsFromRepo); if (await _repo.SaveAll()) { return(NoContent()); } else { return(BadRequest("Could notregister location")); } }
public async Task <IActionResult> Approve(int id) { var finalApprover = true; var appIfFinalCount = await bdoFormHeaderService.CheckRequestApproveCount(id); var request = new RequestApproval { user = name, requestId = id, approve = true }; await bdoFormHeaderService.InsertAsync(request); await bdoFormHeaderService.SaveChangesAsync(); var actionsCode = "Approve"; var history = new History { RequestId = id, actionCode = actionsCode, user = name, groupCode = "mauEncoder", date = DateTime.Now, action = "Approve: Approve Count 1", }; if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var maef = await maefService.FindAsync(id); if (maef == null) { return(NotFound()); } if (maef.approver1 == null) { maef.approver1 = name; maef.decisionDate1 = DateTime.Now; maef.approverDecision1 = actionsCode; } else if (maef.approver2 == null) { maef.approver2 = name; maef.decisionDate2 = DateTime.Now; maef.approverDecision2 = actionsCode; } else if (maef.approver3 == null) { maef.approver3 = name; maef.decisionDate3 = DateTime.Now; maef.approverDecision3 = actionsCode; } await maefService.Update(maef); await maefService.SaveChangesAsync(); var appCount = await bdoFormHeaderService.ApproveCountAsync(id); //count approve on requestapproval table var appSetup = await bdoFormHeaderService.GetApproveCount(id); //count approval count on requiredapproval table var requestRecords = await bdoFormHeaderService.FindAsync(id); var requestStatus = requestRecords.Status; /*update status*/ if (appIfFinalCount == appSetup && requestStatus == 8 && finalApprover == true) { if (maef.chkWithReq && maef.chkWithException && maef.chkApprovePendingCust) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 16); history.action = "Approve: APPROVED WRWEPC"; } else if (maef.chkWithReq && maef.chkApprovePendingCust) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 17); history.action = "Approve: APPROVED WRPC"; } else if (maef.chkWithReq && maef.chkWithException) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 18); history.action = "Approve: APPROVED WRWE"; } else if (maef.chkApprove) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 11); history.action = "Approve: APPROVED"; } else if (maef.chkDecline) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 12); history.action = "Approve: DECLINED"; } else if (maef.chkWithReq) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 13); history.action = "Approve: APPROVED WR"; } else if (maef.chkWithException) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 15); history.action = "Approve: APPROVED WE"; } else if (maef.chkApprovePendingCust) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 14); history.action = "Approve: APPROVED PC"; } await bdoFormHeaderService.SaveChangesAsync(); } else { if (appCount >= appSetup) { if (maef.chkWithReq && maef.chkWithException && maef.chkApprovePendingCust) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 16); history.action = "Approve: APPROVED WRWEPC"; } else if (maef.chkWithReq && maef.chkApprovePendingCust) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 17); history.action = "Approve: APPROVED WRPC"; } else if (maef.chkWithReq && maef.chkWithException) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 18); history.action = "Approve: APPROVED WRWE"; } else if (maef.chkApprove) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 11); history.action = "Approve: APPROVED"; } else if (maef.chkDecline) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 12); history.action = "Approve: DECLINED"; } else if (maef.chkWithReq) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 13); history.action = "Approve: APPROVED WR"; } else if (maef.chkWithException) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 15); history.action = "Approve: APPROVED WE"; } else if (maef.chkApprovePendingCust) { var requestData = await bdoFormHeaderService.FindAsync(id); bdoFormHeaderService.Update(requestData, 14); history.action = "Approve: APPROVED PC"; } await bdoFormHeaderService.SaveChangesAsync(); } } await maefService.InsertRemarksAsync(history); await maefService.SaveChangesAsync(); return(Ok()); }
private void AddGameToDatabase(string winner) { player_information whitePlayerInformation = new player_information() { algorithm = new algorithm() { algorithm_name = WhitePlayerEngine.Kind.ToString() }, number_of_pieces = Board.NumberOfWhitePiecesAtBeggining, player = WhitePlayerEngine.Kind == EngineKind.Human ? new player() { player_name = "syntaximus" } : new player() { player_name = "CPU" } }; player_information blackPlayerInformation = new player_information() { algorithm = new algorithm() { algorithm_name = BlackPlayerEngine.Kind.ToString() }, number_of_pieces = Board.NumberOfBlackPiecesAtBeggining, player = BlackPlayerEngine.Kind == EngineKind.Human ? new player() { player_name = "syntaximus" } : new player() { player_name = "CPU" } }; if (WhitePlayerEngine.GetType() == typeof(AlphaBetaEngine)) { var engine = (AlphaBetaEngine)WhitePlayerEngine; whitePlayerInformation.tree_depth = engine.AlphaBetaTreeDepth; } if (BlackPlayerEngine.GetType() == typeof(AlphaBetaEngine)) { var engine = (AlphaBetaEngine)BlackPlayerEngine; blackPlayerInformation.tree_depth = engine.AlphaBetaTreeDepth; } if (WhitePlayerEngine.GetType() == typeof(MctsEngine)) { var engine = (MctsEngine)WhitePlayerEngine; whitePlayerInformation.uct_parameter = engine.UctParameter; whitePlayerInformation.number_of_iterations = engine.NumberOfIterations; } if (BlackPlayerEngine.GetType() == typeof(MctsEngine)) { var engine = (MctsEngine)BlackPlayerEngine; blackPlayerInformation.uct_parameter = engine.UctParameter; blackPlayerInformation.number_of_iterations = engine.NumberOfIterations; } game_type gameType = new game_type() { game_type_name = Variant.ToString() }; List <game_move> gameMoves = new List <game_move>(); foreach (var move in History.Skip(1)) { var gameMove = new game_move() { player = move.PieceColor == PieceColor.White ? "W" : "B", start_time = move.StartTime, end_time = move.EndTime, from_position = move.Board.LastMove.OldPiece.Position, to_position = move.Board.LastMove.NewPiece.Position, beated_pieces_count = move.Board.LastMove.BeatedPieces?.Count ?? 0, beated_pieces = move.Board.LastMove.GetBeatedPiecesString(), board_after_move = move.Board.ToString() }; gameMoves.Add(gameMove); } int moveCount = History.Count; _databaseLayer.AddGame(whitePlayerInformation, blackPlayerInformation, gameType, gameMoves, Board.Size, winner, moveCount, StartDate); }
// // Swipe Panel Events // private void ProcessSwipe(string swipeData) { try { using (var rockContext = new RockContext()) { // create swipe object SwipePaymentInfo swipeInfo = new SwipePaymentInfo(swipeData); swipeInfo.Amount = this.Amounts.Sum(a => a.Value); // if not anonymous then add contact info to the gateway transaction if (this.AnonymousGiverPersonAliasId != this.SelectedGivingUnit.PersonAliasId) { var giver = new PersonAliasService(rockContext).Queryable("Person, Person.PhoneNumbers").Where(p => p.Id == this.SelectedGivingUnit.PersonAliasId).FirstOrDefault(); swipeInfo.FirstName = giver.Person.NickName; swipeInfo.LastName = giver.Person.LastName; if (giver.Person.PhoneNumbers != null) { Guid homePhoneValueGuid = new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME); var homephone = giver.Person.PhoneNumbers.Where(p => p.NumberTypeValue.Guid == homePhoneValueGuid).FirstOrDefault(); if (homephone != null) { swipeInfo.Phone = homephone.NumberFormatted; } } var homeLocation = giver.Person.GetHomeLocation(); if (homeLocation != null) { swipeInfo.Street1 = homeLocation.Street1; if (!string.IsNullOrWhiteSpace(homeLocation.Street2)) { swipeInfo.Street2 = homeLocation.Street2; } swipeInfo.City = homeLocation.City; swipeInfo.State = homeLocation.State; swipeInfo.PostalCode = homeLocation.PostalCode; } } // add comment to the transaction swipeInfo.Comment1 = GetAttributeValue("PaymentComment"); // get gateway FinancialGateway financialGateway = null; GatewayComponent gateway = null; Guid? gatewayGuid = GetAttributeValue("CreditCardGateway").AsGuidOrNull(); if (gatewayGuid.HasValue) { financialGateway = new FinancialGatewayService(rockContext).Get(gatewayGuid.Value); if (financialGateway != null) { financialGateway.LoadAttributes(rockContext); } gateway = financialGateway.GetGatewayComponent(); } if (gateway != null) { string errorMessage = string.Empty; var transaction = gateway.Charge(financialGateway, swipeInfo, out errorMessage); if (transaction != null) { _transactionCode = transaction.TransactionCode; var personName = new PersonAliasService(rockContext) .Queryable().AsNoTracking() .Where(a => a.Id == this.SelectedGivingUnit.PersonAliasId) .Select(a => a.Person.NickName + " " + a.Person.LastName) .FirstOrDefault(); transaction.AuthorizedPersonAliasId = this.SelectedGivingUnit.PersonAliasId; transaction.TransactionDateTime = RockDateTime.Now; transaction.FinancialGatewayId = financialGateway.Id; var txnType = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION)); transaction.TransactionTypeValueId = txnType.Id; transaction.Summary = swipeInfo.Comment1; if (transaction.FinancialPaymentDetail == null) { transaction.FinancialPaymentDetail = new FinancialPaymentDetail(); } transaction.FinancialPaymentDetail.SetFromPaymentInfo(swipeInfo, gateway, rockContext); Guid sourceGuid = Guid.Empty; if (Guid.TryParse(GetAttributeValue("Source"), out sourceGuid)) { var source = DefinedValueCache.Get(sourceGuid); if (source != null) { transaction.SourceTypeValueId = source.Id; } } foreach (var accountAmount in this.Amounts.Where(a => a.Value > 0)) { var transactionDetail = new FinancialTransactionDetail(); transactionDetail.Amount = accountAmount.Value; transactionDetail.AccountId = accountAmount.Key; transaction.TransactionDetails.Add(transactionDetail); var account = new FinancialAccountService(rockContext).Get(accountAmount.Key); } var batchService = new FinancialBatchService(rockContext); // Get the batch var batch = batchService.Get( GetAttributeValue("BatchNamePrefix"), swipeInfo.CurrencyTypeValue, swipeInfo.CreditCardTypeValue, transaction.TransactionDateTime.Value, financialGateway.GetBatchTimeOffset()); var batchChanges = new History.HistoryChangeList(); if (batch.Id == 0) { batchChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Batch"); History.EvaluateChange(batchChanges, "Batch Name", string.Empty, batch.Name); History.EvaluateChange(batchChanges, "Status", null, batch.Status); History.EvaluateChange(batchChanges, "Start Date/Time", null, batch.BatchStartDateTime); History.EvaluateChange(batchChanges, "End Date/Time", null, batch.BatchEndDateTime); } decimal newControlAmount = batch.ControlAmount + transaction.TotalAmount; History.EvaluateChange(batchChanges, "Control Amount", batch.ControlAmount.FormatAsCurrency(), newControlAmount.FormatAsCurrency()); batch.ControlAmount = newControlAmount; transaction.BatchId = batch.Id; batch.Transactions.Add(transaction); rockContext.WrapTransaction(() => { rockContext.SaveChanges(); HistoryService.SaveChanges( rockContext, typeof(FinancialBatch), Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(), batch.Id, batchChanges ); }); // send receipt in one is configured and not giving anonymously if (!string.IsNullOrWhiteSpace(GetAttributeValue("ReceiptEmail")) && (this.AnonymousGiverPersonAliasId != this.SelectedGivingUnit.PersonAliasId)) { _receiptSent = true; SendReceipt(); } HidePanels(); ShowReceiptPanel(); } else { lSwipeErrors.Text = String.Format("<div class='alert alert-danger'>An error occurred while process this transaction. Message: {0}</div>", errorMessage); } } else { lSwipeErrors.Text = "<div class='alert alert-danger'>Invalid gateway provided. Please provide a gateway. Transaction not processed.</div>"; } } } catch (Exception ex) { lSwipeErrors.Text = String.Format("<div class='alert alert-danger'>An error occurred while process this transaction. Message: {0}</div>", ex.Message); } }
public void PopulateHistory(int historyFunctionType, T objectModel, Models.Object @object, long userId, long?targetObjectId, long houseId) { var now = DateTime.Now; if (historyFunctionType == (int)HistoryFunctionTypes.Create) { var isSubObject = DetermineIfCurrentObjectIsSubObject(@object); if (isSubObject) { var history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, TargetId = targetObjectId, ObjectId = @object.ObjectId }; this.SaveHistory(history, userId); } else { if (@object.ObjectTypeId == (int)ObjectTypes.HouseStatus) { var newHouseStatusModel = objectModel as HouseStatus; var history = new History() { FunctionTypeId = historyFunctionType, ColumnName = "Status", NewValue = newHouseStatusModel.Status.ToString(), When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; this.SaveHistory(history, userId); } else { var history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; this.SaveHistory(history, userId); } } } else if (historyFunctionType == (int)HistoryFunctionTypes.Update) { var history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; // Parent Objects switch (@object.ObjectTypeId) { case (long)ObjectTypes.User: var oldUserModel = context.Users.AsNoTracking().Single(x => x.ObjectId == @object.ObjectId); var newuUserModel = objectModel as User; if (oldUserModel.Username != newuUserModel.Username) { history.ColumnName = "Username"; history.OldValue = oldUserModel.Username; history.NewValue = newuUserModel.Username; } this.SaveHistory(history, userId); break; case (long)ObjectTypes.House: var oldHouseModel = context.Houses.AsNoTracking().Single(x => x.ObjectId == @object.ObjectId); var newHouseModel = objectModel as House; if (oldHouseModel.Name != newHouseModel.Name) { history.ColumnName = "Name"; history.OldValue = oldHouseModel.Name; history.NewValue = newHouseModel.Name; } this.SaveHistory(history, userId); break; case (long)ObjectTypes.Inventory: var oldInventoryModel = context.Inventories.AsNoTracking().Single(x => x.ObjectId == @object.ObjectId); var newInventoryModel = objectModel as Inventory; if (oldInventoryModel.Name != newInventoryModel.Name) { history.ColumnName = "Name"; history.OldValue = oldInventoryModel.Name; history.NewValue = newInventoryModel.Name; this.SaveHistory(history, userId); } if (oldInventoryModel.Details != newInventoryModel.Details) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "Details"; history.OldValue = oldInventoryModel.Details; history.NewValue = newInventoryModel.Details; this.SaveHistory(history, userId); } if (oldInventoryModel.Status != newInventoryModel.Status) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "Status"; history.OldValue = oldInventoryModel.Status.ToString(); history.NewValue = newInventoryModel.Status.ToString(); this.SaveHistory(history, userId); } if (oldInventoryModel.IsCompleted != newInventoryModel.IsCompleted) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "IsCompleted"; history.OldValue = oldInventoryModel.IsCompleted.ToString(); history.NewValue = newInventoryModel.IsCompleted.ToString(); this.SaveHistory(history, userId); } break; case (long)ObjectTypes.Hygiene: var oldHygieneModel = context.Hygienes.AsNoTracking().Single(x => x.ObjectId == @object.ObjectId); var newHygieneModel = objectModel as Hygiene; if (oldHygieneModel.Name != newHygieneModel.Name) { history.ColumnName = "Name"; history.OldValue = oldHygieneModel.Name; history.NewValue = newHygieneModel.Name; this.SaveHistory(history, userId); } if (oldHygieneModel.Details != newHygieneModel.Details) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "Details"; history.OldValue = oldHygieneModel.Details; history.NewValue = newHygieneModel.Details; this.SaveHistory(history, userId); } if (oldHygieneModel.Status != newHygieneModel.Status) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "Status"; history.OldValue = oldHygieneModel.Status.ToString(); history.NewValue = newHygieneModel.Status.ToString(); this.SaveHistory(history, userId); } if (oldHygieneModel.IsCompleted != newHygieneModel.IsCompleted) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "IsCompleted"; history.OldValue = oldHygieneModel.IsCompleted.ToString(); history.NewValue = newHygieneModel.IsCompleted.ToString(); this.SaveHistory(history, userId); } break; case (long)ObjectTypes.Issue: var oldIssueModel = context.Issues.AsNoTracking().Single(x => x.ObjectId == @object.ObjectId); var newIssueModel = objectModel as Issue; if (oldIssueModel.Name != newIssueModel.Name) { history.ColumnName = "Name"; history.OldValue = oldIssueModel.Name; history.NewValue = newIssueModel.Name; this.SaveHistory(history, userId); } if (oldIssueModel.Details != newIssueModel.Details) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "Details"; history.OldValue = oldIssueModel.Details; history.NewValue = newIssueModel.Details; this.SaveHistory(history, userId); } if (oldIssueModel.Status != newIssueModel.Status) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "Status"; history.OldValue = oldIssueModel.Status.ToString(); history.NewValue = newIssueModel.Status.ToString(); this.SaveHistory(history, userId); } if (oldIssueModel.IsCompleted != newIssueModel.IsCompleted) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "IsCompleted"; history.OldValue = oldIssueModel.IsCompleted.ToString(); history.NewValue = newIssueModel.IsCompleted.ToString(); this.SaveHistory(history, userId); } break; case (long)ObjectTypes.Survey: var oldSurveyModel = context.Surveys.AsNoTracking().Single(x => x.ObjectId == @object.ObjectId); var newSurveyModel = objectModel as Survey; if (oldSurveyModel.Name != newSurveyModel.Name) { history.ColumnName = "Name"; history.OldValue = oldSurveyModel.Name; history.NewValue = newSurveyModel.Name; this.SaveHistory(history, userId); } if (oldSurveyModel.Details != newSurveyModel.Details) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "Details"; history.OldValue = oldSurveyModel.Details; history.NewValue = newSurveyModel.Details; this.SaveHistory(history, userId); } if (oldSurveyModel.Status != newSurveyModel.Status) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "Status"; history.OldValue = oldSurveyModel.Status.ToString(); history.NewValue = newSurveyModel.Status.ToString(); this.SaveHistory(history, userId); } if (oldSurveyModel.IsCompleted != newSurveyModel.IsCompleted) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "IsCompleted"; history.OldValue = oldSurveyModel.IsCompleted.ToString(); history.NewValue = newSurveyModel.IsCompleted.ToString(); this.SaveHistory(history, userId); } break; } // Child objects - Metadata switch (@object.ObjectTypeId) { case (long)ObjectTypes.HouseStatus: var oldHouseStatusModel = context.HouseStatuses.AsNoTracking().Single(x => x.ObjectId == @object.ObjectId); var newHouseStatusModel = objectModel as HouseStatus; if (oldHouseStatusModel.Status != newHouseStatusModel.Status) { history.ColumnName = "Status"; history.OldValue = oldHouseStatusModel.Status.ToString(); history.NewValue = newHouseStatusModel.Status.ToString(); this.SaveHistory(history, userId); } break; case (long)ObjectTypes.HouseSettings: var oldHouseSettingsModel = context.HouseSettings.AsNoTracking().Single(x => x.ObjectId == @object.ObjectId); var newHouseSettingsModel = objectModel as HouseSettings; if (oldHouseSettingsModel.RentDueDateDay != newHouseSettingsModel.RentDueDateDay) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "RentDueDateDay"; history.OldValue = oldHouseSettingsModel.RentDueDateDay.ToString(); history.NewValue = newHouseSettingsModel.RentDueDateDay.ToString(); this.SaveHistory(history, userId); } if (oldHouseSettingsModel.HouseName != newHouseSettingsModel.HouseName) { history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, ObjectId = @object.ObjectId }; history.ColumnName = "HouseName"; history.OldValue = oldHouseSettingsModel.HouseName; history.NewValue = newHouseSettingsModel.HouseName; this.SaveHistory(history, userId); } break; case (long)ObjectTypes.Comment: // TODO: Implement this case, when comments become editable break; case (long)ObjectTypes.Image: // Will we event implement a case where images are going to be updated? break; } } else if (historyFunctionType == (int)HistoryFunctionTypes.Delete) { var isSubObject = DetermineIfCurrentObjectIsSubObject(@object); if (isSubObject) { var history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, UserId = userId, DeletedObjectDate = DateTime.Now, TargetId = targetObjectId, ObjectId = @object.ObjectId }; switch (@object.ObjectTypeId) { case (long)ObjectTypes.Comment: history.DeletedObjectObjectType = (long)ObjectTypes.Comment; this.SaveHistory(history, userId); break; case (long)ObjectTypes.Image: history.DeletedObjectObjectType = (long)ObjectTypes.Image; this.SaveHistory(history, userId); break; } } else { DeleteObjectMetadataSubObjects(@object); var history = new History() { FunctionTypeId = historyFunctionType, When = now, HouseId = houseId, DeletedObjectDate = DateTime.Now, UserId = userId, ObjectId = @object.ObjectId }; switch (@object.ObjectTypeId) { case (long)ObjectTypes.User: var userModel = objectModel as User; history.DeletedObjectName = userModel.Username; history.DeletedObjectObjectType = @object.ObjectTypeId; this.SaveHistory(history, userId); break; case (long)ObjectTypes.House: var houseModel = objectModel as House; history.DeletedObjectName = houseModel.Name; history.DeletedObjectObjectType = @object.ObjectTypeId; this.SaveHistory(history, userId); break; case (long)ObjectTypes.Inventory: var inventoryModel = objectModel as Inventory; history.DeletedObjectName = inventoryModel.Name; history.DeletedObjectObjectType = @object.ObjectTypeId; this.SaveHistory(history, userId); break; case (long)ObjectTypes.Hygiene: var hygieneModel = objectModel as Hygiene; history.DeletedObjectName = hygieneModel.Name; history.DeletedObjectObjectType = @object.ObjectTypeId; this.SaveHistory(history, userId); break; case (long)ObjectTypes.Issue: var issueModel = objectModel as Issue; history.DeletedObjectName = issueModel.Name; history.DeletedObjectObjectType = @object.ObjectTypeId; this.SaveHistory(history, userId); break; case (long)ObjectTypes.Survey: var surveyModel = objectModel as Survey; history.DeletedObjectName = surveyModel.Name; history.DeletedObjectObjectType = @object.ObjectTypeId; this.SaveHistory(history, userId); break; } } } }