private Commands.Command GetTouchCommand() { Commands.Command command = new Commands.Command(); command.CommandType = Commands.eCommandType.Touch; return(command); }
void receiveLoop() { while (connected) { byte[] dataByte = null; int pos = 0; int read = 1; try { byte[] lenByte = new byte[4]; while (pos < lenByte.Length) { read = socket.Receive(lenByte, pos, lenByte.Length - pos); pos += read; App.globalDownCounter.addBytes((ulong)read); } pos = 0; App.globalDownCounter.addBytes(4); dataByte = new byte[BitConverter.ToInt32(lenByte, 0)]; if (dataByte.Length > 0) { while (pos < dataByte.Length) { read = socket.Receive(dataByte, pos, dataByte.Length - pos); pos += read; App.globalDownCounter.addBytes((ulong)read); } } } catch { continue; } Commands.Command c = App.serializer.deserialize(dataByte); if (c is Commands.DataCommand) { pos = 0; read = 1; App.speedLimiter.limitDownload((ulong)((Commands.DataCommand)c).data.Length); byte[] chunk = new byte[((Commands.DataCommand)c).dataLength]; while (pos < chunk.Length) { read = socket.Receive(chunk, pos, (int)App.speedLimiter.limitDownload((ulong)(chunk.Length - pos), rateLimiterDisabled)); pos += read; App.globalDownCounter.addBytes((ulong)read); } ((Commands.DataCommand)c).data = chunk; } if (c is Commands.HelloCommand) { hello = (Commands.HelloCommand)c; } while (commandReceived == null && connected) { System.Threading.Thread.Sleep(10); } commandReceived?.Invoke(c, this); } }
public TimingSet(Soheil.Core.ViewModels.PP.Editor.ProcessEditorVm vm) { IsInitializing = () => vm._isInitializing; SetIsInitializing = v => vm._isInitializing = v; GetCycleTime = () => vm.Model.StateStationActivity == null ? 0f : vm.Model.StateStationActivity.CycleTime; GetLowerBound = () => DateTime.MinValue;//vm.Model.Task.StartDateTime.TruncateMilliseconds(); GetUpperBound = () => DateTime.MaxValue; _suppress = true; vm.Model.TargetCount = vm.Model.TargetCount <= 0 ? 1 : vm.Model.TargetCount; vm.Model.DurationSeconds = vm.Model.DurationSeconds < GetCycleTime() ? (int)GetCycleTime() : vm.Model.DurationSeconds; vm.Model.EndDateTime = vm.Model.EndDateTime - vm.Model.StartDateTime < TimeSpan.FromSeconds(GetCycleTime()) ? vm.Model.StartDateTime + TimeSpan.FromSeconds(GetCycleTime()) : vm.Model.EndDateTime; TargetPoint = vm.Model.TargetCount; StartDateTime = vm.Model.StartDateTime; DurationSeconds = vm.Model.DurationSeconds; EndDateTime = vm.Model.EndDateTime; AutoDurationCommand = new Commands.Command(o => { DurationSeconds = (int)(TargetPoint * GetCycleTime()); }); AutoTargetPointCommand = new Commands.Command(o => { TargetPoint = (int)(DurationSeconds / GetCycleTime()); }); }
public OperatorManagerVm(Dal.SoheilEdmContext uow) { _uow = uow; //OperatorsList.Add(OperatorEditorVm.CreateAnonymous()); #region get all operators and convert them to VM OperatorDataService = new DataServices.OperatorDataService(_uow); var allOperators = OperatorDataService.GetActives(); foreach (var oper in allOperators) { var operVm = new OperatorEditorVm(oper); //Notify // Add|Remove selected|deselected operator in vm operVm.SelectedOperatorChanged += Operator_SelectedOperatorChanged; //Updates role in uow operVm.OperatorRoleChanged += Operator_RoleChanged; OperatorsList.Add(operVm); } #endregion #region init commands ClearSearchCommand = new Commands.Command(textBox => { if (textBox is System.Windows.Controls.TextBox) (textBox as System.Windows.Controls.TextBox).Clear(); }); RefreshCommand = new Commands.Command(o => refresh()); #endregion }
public static void StartingRoom () { //while (true) //{ Commands.Command command = Commands.HandleCommand (); switch (command) { case Commands.Command.MoveForward: { Console.WriteLine ("You enter the room and spot doors to the east and west."); Room1 (); break; } case Commands.Command.Look: { Console.Out.WriteLine ("There's a door to the north"); StartingRoom (); break; } case Commands.Command.Quit: { break; } default: { Console.Out.WriteLine ("I can't do that now."); StartingRoom (); break; } } }
/// <summary> /// Creates an instance of <see cref="WorkShiftVm"/> with the given model and work shift prototype viewModel /// </summary> /// <param name="model"></param> /// <param name="prototype"></param> public WorkShiftVm(Model.WorkShift model, WorkShiftPrototypeVm prototype) { Model = model; Prototype = prototype; StartSeconds = model.StartSeconds; EndSeconds = model.EndSeconds; IsOpen = model.IsOpen; //add workbreak models foreach (var workBreak in model.WorkBreaks) { var wbreak = new WorkBreakVm(workBreak); wbreak.DeleteCommand = new Commands.Command(o => Breaks.Remove(wbreak)); Breaks.Add(wbreak); } //auto add future workbreak models Breaks.CollectionChanged += (s, e) => { if (e.NewItems != null) foreach (WorkBreakVm wbreak in e.NewItems) { Model.WorkBreaks.Add(wbreak.Model); } if(e.OldItems!=null) foreach (WorkBreakVm wbreak in e.OldItems) { Model.WorkBreaks.Remove(wbreak.Model); } }; ToggleIsOpenCommand = new Commands.Command(o => IsOpen = !IsOpen); }
public override void send(Commands.Command c) { if (c is Commands.DataCommand) { ((Commands.DataCommand)c).dataLength = ((Commands.DataCommand)c).data.Length; } byte[] b = App.serializer.serialize(c); int len = b.Length; lock (sendLock) { try { client.GetStream().Write(BitConverter.GetBytes(len), 0, 4); App.globalUpCounter.addBytes((ulong)4); client.GetStream().Write(b, 0, b.Length); App.globalUpCounter.addBytes((ulong)b.Length); if (c is Commands.DataCommand) { int pos = 0; while (pos < ((Commands.DataCommand)c).data.Length) { int amt = (int)App.speedLimiter.limitUpload((ulong)(((Commands.DataCommand)c).data.Length - pos), rateLimiterDisabled); client.GetStream().Write(((Commands.DataCommand)c).data, pos, amt); pos += amt; App.globalUpCounter.addBytes(amt); } } } catch { return; } } }
/// <summary> /// Adds a new dynamic command to Rhino. /// </summary> /// <param name="plugin">Plugin that owns the command.</param> /// <param name="cmd">Command to add.</param> /// <returns>true on success, false on failure.</returns> public static bool RegisterDynamicCommand(PlugIn plugin, Commands.Command cmd) { // every command must have a RhinoId and Name attribute bool rc = false; if (plugin != null) { try { plugin.m_commands.Add(cmd); int sn = cmd.m_runtime_serial_number; IntPtr pPlugIn = plugin.NonConstPointer(); string englishName = cmd.EnglishName; string localName = cmd.LocalName; const int commandStyle = 2; //scripted Guid id = cmd.Id; UnsafeNativeMethods.CRhinoCommand_Create(pPlugIn, id, englishName, localName, sn, commandStyle, 0); rc = true; } catch (Exception ex) { ExceptionReport(ex); } } return rc; }
/// <summary> /// Creates a ViewModel for an index parameter in which the duration is the given number of hours /// </summary> /// <param name="hours">Number of hours applied for the index parameter</param> /// <param name="total">Total number of hours for the index</param> public IndexTime(double hours, double total, string text = null) { Hours = hours; Perc = 100 * hours / total; Text = text; SelectCommand = new Commands.Command(o => { if (o != null) { IsByProduct = o.ToString() == "ppmByProduct"; if (Selected != null) Selected(this); return; } //for detailed indices if (!string.IsNullOrWhiteSpace(Text)) { if (Selected != null) Selected(this); } //for normal indices else if (ShowSubItems) { ShowSubItems = false; } else { ShowSubItems = true; //load if (Selected != null) Selected(this); } }); }
public TaskEditorHolderVm() { CreateNewTaskCommand = new Commands.Command(o => { if (TaskCreated != null) TaskCreated(); }); }
public DefectionReportCollection(ProcessReportVm parent) { Parent = parent; AddCommand = new Commands.Command(o => { var model = new Model.DefectionReport { ProcessReport = parent.Model, LostCount = 0, LostTime = 0, ProductDefection = null, ModifiedBy = LoginInfo.Id, }; foreach (var po in Parent.Model.Process.ProcessOperators) { model.OperatorDefectionReports.Add(new Model.OperatorDefectionReport { Operator = po.Operator, DefectionReport = model, Code = po.Operator.Code, ModifiedBy = LoginInfo.Id, }); } parent.Model.DefectionReports.Add(model); var vm = new DefectionReportVm(this, model); List.Add(vm); }); }
/// <summary> /// Creates an instance of FilterableItemVm /// </summary> /// <param name="id">Id of the model represented by this vm</param> /// <param name="text">Text to show for this Vm in GUI</param> /// <param name="vm">Use this parameter only if this FilterableItemVm is a wrapper around the given vm (parameter)</param> private FilterableItemVm(int id, string text, DependencyObject vm = null) { Id = id; Text = text; ViewModel = vm; SelectCommand = new Commands.Command(o => Parent.SelectedItem = this); }
/// <summary> /// Initializes the commands (SelectCommand) /// </summary> protected void InitializeCommands() { SelectCommand = new Commands.Command(o => { if (Selected != null) Selected(this); }); }
// Helper methods private Commands.Command GetSpeakableDtmfCommand() { Commands.Command command = new Commands.Command(); command.CommandType = Commands.eCommandType.Dtmf; command.OperationType = Commands.eOperationType.Prompt; return(command); }
private Commands.Command GetNonspeakableDtmfCommand() { Commands.Command command = new Commands.Command(); command.CommandType = Commands.eCommandType.Dtmf; command.OperationType = Commands.eOperationType.DoNothing; return(command); }
public OeeMachineDetailVm() { SelectCommand = new Commands.Command(o => { IsSelected = true; if (Selected != null) Selected(); }); }
void initializeCommands() { SelectCommand = new Commands.Command(o => { _changeOperatorCount = true; IsSelected = !IsSelected; _changeOperatorCount = false; }); }
private void UnrecognizedResponse(Commands.Command i_command) { ElseElement(); switch (i_command.OperationType) { case Commands.eOperationType.DoNothing: GotoElement(CurrentFormUrl()); break; case Commands.eOperationType.GotoMenu: AudioElement(i_command.ConfirmationWavUrl, i_command.ConfirmationText); GotoElement(i_command.Response); break; case Commands.eOperationType.Repeat: AudioElement(i_command.ConfirmationWavUrl, i_command.ConfirmationText); GotoElement(CurrentFormUrl()); break; case Commands.eOperationType.Transfer: TransferElementStart(i_command.Response); PromptElementStart(eBargeIn.NotSpecified); AudioElement(i_command.ConfirmationWavUrl, i_command.ConfirmationText); PromptElementEnd(); TransferElementEnd(); break; case Commands.eOperationType.CodeBlock: if (String.Empty == i_command.Response) { // Cannot have an empty default for speech since if it hits then user will stay in MOH since an empty else clause doesn't cause any action (hence no Inactivity Timer restart). // Shouldn't have an empty default for DTMF since if it hits then the system waits until the Inactivity Timer expires before responding, rather than once the DTMF end detection has happened. GotoElement(CurrentFormUrl()); } else { WriteRaw(i_command.Response); } break; case Commands.eOperationType.Hangup: AudioElement(i_command.ConfirmationWavUrl, i_command.ConfirmationText); ExitElement(); break; case Commands.eOperationType.Prompt: AudioElement(i_command.ConfirmationWavUrl, i_command.ConfirmationText); break; default: Console.Error.WriteLine(String.Format("{0} DialogBuilder.UnrecognizedResponse: Unknown OperationType encountered ({1})", DateTime.Now, i_command.OperationType)); //$$$ LP - Write to log instead of console. break; } }
public void Execute_CommandNull_ThrowsArgumentNullException() { // Arrange var simulation = new Simulation(); Commands.Command command = null; // Act & Assert Assert.Throws <ArgumentNullException>("command", () => simulation.Execute(command)); }
public void WriteEmbeddedCommand(Commands.Command command) { using var stream = new MemoryStream(); using (var writer = new DefaultBinaryWriter(stream, _cgm)) { writer.WriteCommand(command); } _bucket.AddRange(stream.ToArray()); }
protected Commands.Command GetCommand(Func <Task> execute, Func <bool> canExecute = null, [CallerMemberName] string propertyName = null) { if (!_propertyValues.ContainsKey(propertyName)) { _propertyValues[propertyName] = new Commands.Command(execute, canExecute); } return((Commands.Command)_propertyValues[propertyName]); }
public override void send(Commands.Command c) { if (c is Commands.DataCommand) { App.globalUpCounter.addBytes(((Commands.DataCommand)c).data.Length); upCounter.addBytes(((Commands.DataCommand)c).data.Length); App.speedLimiter.limitUpload((ulong)((Commands.DataCommand)c).data.Length, rateLimiterDisabled); } this.c.received(c); }
public void received(Commands.Command c) { if (c is Commands.DataCommand) { App.globalDownCounter.addBytes(((Commands.DataCommand)c).data.Length); downCounter.addBytes(((Commands.DataCommand)c).data.Length); App.speedLimiter.limitDownload((ulong)((Commands.DataCommand)c).data.Length, rateLimiterDisabled); } commandReceived?.Invoke(c); }
/// <summary> /// Initialise this command file with the command to write. /// </summary> /// <param name="command"></param> /// <param name="extraData"></param> public void Initialise(Commands.Command command) { this.Aliases = command.Aliases; this.CommandType = command.CommandHandlerType.ToString(); this.Examples = command.Examples; this.ExtraData = command.ExtraData; this.Help = command.Help; this.Module = command.Module.ToString(); this.RequiresSymbol = command.RequiresSymbol.ToString(); }
/// <summary> /// Creates an instance of FilterBoxVm /// </summary> public FilterBoxVm() { ClearCommand = new Commands.Command(o => SelectedItem = null); DeleteCommand = new Commands.Command(o => { if (_parent != null) _parent.FilterBoxes.Remove(this); if (FilterBoxDeleted != null) FilterBoxDeleted(this); }); }
/// <summary> /// Creates an instance of JobProductVm with given model, parent and data service /// </summary> /// <param name="model"></param> /// <param name="parentVm"></param> /// <param name="jobDataService"></param> public JobProductVm(Model.Product model, ProductGroupVm parentVm, DataServices.JobDataService jobDataService) : base(model, parentVm) { CreateNewJob = new Commands.Command (vm => { var job = Soheil.Core.ViewModels.PP.Editor.PPEditorJob.CreateForProduct(model, jobDataService); ((Soheil.Core.ViewModels.PP.Editor.JobEditorVm)vm).JobList.Add(job); } ); }
/// <summary> /// Creates an instance of ChoiceEditorVm with given StateStationActivity model and PPEditorProcess parent /// </summary> /// <param name="model"></param> /// <param name="parent"></param> public ChoiceEditorVm(Model.StateStationActivity model) { Model = model; CycleTime = Model.CycleTime; ManHour = Model.ManHour; IsMany = model.IsMany; SelectCommand = new Commands.Command(o => { if (Selected != null) Selected(this); }); }
public OeeMachineVm(Model.Machine model) { Model = model; Name = model.Name; Code = model.Code; _data = new List<OeeRecord>(); SelectCommand = new Commands.Command(o => { if (Selected != null) Selected(); }); }
public override void send(Commands.Command c) { if (c is Commands.DataCommand) { ((Commands.DataCommand)c).dataLength = ((Commands.DataCommand)c).data.Length; } byte[] b = App.serializer.serialize(c); int len = b.Length; lock (sendLock) { try { int pos = 0; int read = 1; while (pos < 4) { read = socket.Send(BitConverter.GetBytes(len), pos, 4 - pos); App.globalUpCounter.addBytes((ulong)read); pos += read; } pos = 0; App.globalUpCounter.addBytes(4); while (pos < b.Length) { read = socket.Send(b, pos, b.Length - pos); App.globalUpCounter.addBytes((ulong)read); pos += read; } if (c is Commands.DataCommand) { b = ((Commands.DataCommand)c).data; pos = 0; read = 1; while (pos < b.Length) { int amt = (int)App.speedLimiter.limitUpload((ulong)(b.Length - pos), rateLimiterDisabled); read = socket.Send(b, pos, amt); App.globalUpCounter.addBytes((ulong)read); pos += read; } } } catch { return; } } }
private void ProcessCommand(string i_sCondition, Commands.Command i_command, bool i_bIsConfirmationEnabled, ref bool io_bUseElseIf) { if (!io_bUseElseIf) { IfElementStart(i_sCondition); io_bUseElseIf = true; } else { ElseIfElement(i_sCondition); } Response(i_command, i_bIsConfirmationEnabled); }
private void HandleActionExecuted(Commands.Command command) { if (command is null) { return; } lastActionInfo = player?.PlayedCommand?.PlaybackSpot.ToString(); if (audioManager != null && audioManager.Configuration.EnableAutoVoicing && command is Commands.PrintText printAction) { lastAutoVoiceName = $"{player.PlayedScript.Name}/{printAction.PlaybackSpot.LineNumber}.{printAction.PlaybackSpot.InlineIndex}"; } }
public static string[] FindNecessaryParameters(Commands.Command cmd) { List <string> parameters = new List <string>(); foreach (string parameter in cmd.Usage) { if (!(parameter.Contains("["))) { parameters.Add(parameter.Substring(1, parameter.Length - 2)); } } return(parameters.ToArray()); }
public ConnectorVm(Model.Connector model, StateVm start, StateVm end, DataServices.ConnectorDataService connectorDataService, bool isLoose = false) { Model = model; Start = start; End = end; IsLoose = isLoose; DeleteCommand = new Commands.Command(o => { if(Model != null) connectorDataService.DeleteModel(Model); if (ConnectorRemoved != null) ConnectorRemoved(); }); }
private void HandleActionExecuted(Commands.Command command) { if (command is null) { return; } lastActionInfo = $"{player.PlayedScript.Name} #{player.PlayedCommand.LineIndex}.{player.PlayedCommand.InlineIndex}"; if (audioManager != null && audioManager.AutoVoicingEnabled && command is Commands.PrintText printAction) { lastAutoVoiceName = $"{player.PlayedScript.Name}/{printAction.LineNumber}.{printAction.InlineIndex}"; } }
// Constructor public PrioritizedCommand(Commands.Command newCommand) { /*if (newCommand.GetType() == typeof(Tests.DynamicDamageCommand)) { damage = ((Tests.DynamicDamageCommand)newCommand).Strength; } else*/ if (newCommand.GetType() == typeof(Commands.DamageCommand)) { damage = ((Commands.DamageCommand)newCommand).Strength; } range = newCommand.Range; command = newCommand; next = null; targetOptions = new List<CommandInfo>(); }
public void sendCommand(Commands.Command c) { byte[] b = App.serializer.serialize(c); if (isLocal) { foreach (System.Net.IPAddress a in internalAddress) { App.udpSend(b, b.Length, new System.Net.IPEndPoint(a, localControlPort)); } } else { App.udpSend(b, b.Length, actualEndpoint); } }
protected override void SendLocalPlayerCommand(Commands.Command command, bool isReliable) { //TODO: add reliable commands support packetWriter.BaseStream.Position = 0; packetWriter.Write((byte)PacketType.PlayerCommand); AddSyncBodyToOutgoingPacket(); Commands.PackCommand(command, packetWriter); udpNetwork.Send(sendBuffer, 0, (int)packetWriter.BaseStream.Position); packetLastSendTime = Time.unscaledTime; }
protected override void SendLocalPlayerCommand(Commands.Command command, bool isReliable) { foreach (var futureCommand in futureCommands) { if (futureCommand.playerId == localPlayerId) { return; } } futureCommands.Add(new PlayerCommand { playerId = localPlayerId, command = command }); }
public void Execute(TimeCommand _) { if (Connection == null) { Console.WriteLine("There is no connection to server!"); return; } var request = new Commands.Command() { CommandType = CommandType.TimeRequest }; Connection.Send(request); var response = Connection.Receive().Deserialize <TextCommand>(); Console.WriteLine(response.Text); }
/// <summary> /// Creates an instance of <see cref="WorkDayVm "/> with all its WorkShifts /// </summary> /// <param name="model"></param> /// <param name="prototypes">chooses its instance of prototype from this collection</param> public WorkDayVm(Model.WorkDay model, ICollection<WorkShiftPrototypeVm> prototypes) { _model = model; Name = model.Name; Color = model.Color; BusinessState = model.BusinessState; foreach (var workShift in model.WorkShifts) { var shift = new WorkShiftVm(workShift, prototypes.First(x => x.Id == workShift.WorkShiftPrototype.Id)); shift.IsOpenChanged += newVal => updateThreeStateIsOpen(); Shifts.Add(shift); } Shifts.CollectionChanged += (s, e) => { if (e.NewItems != null) foreach (WorkShiftVm shift in e.NewItems) { _model.WorkShifts.Add(shift.Model); shift.IsOpenChanged += newVal => updateThreeStateIsOpen(); } if (e.OldItems != null) foreach (WorkShiftVm shift in e.OldItems) { _model.WorkShifts.Remove(shift.Model); } updateThreeStateIsOpen(); }; ToggleIsOpenCommand = new Commands.Command(o => { if (Shifts.Any(x => !x.IsOpen)) foreach (var shift in Shifts) shift.IsOpen = true; else foreach (var shift in Shifts) shift.IsOpen = false; updateThreeStateIsOpen(); }); updateThreeStateIsOpen(); }
public static void Room7 () { Commands.Command command = Commands.HandleCommand (); switch (command) { case Commands.Command.MoveForward: { ExitRoom (); break; } case Commands.Command.MoveLeft: { Console.WriteLine ("You enter the room and spot doors to the east and south."); Room8 (); break; } case Commands.Command.MoveRight: { Console.WriteLine ("You enter the room and spot doors to the south and west."); Room6 (); break; } case Commands.Command.Look: { Console.Out.WriteLine ("There's a door to the north, east, and west" + " with some light coming from the northern room."); Room7 (); break; } case Commands.Command.Quit: { break; } default: { Console.Out.WriteLine ("I can't do that now."); Room7 (); break; } } }
public static void Room10 () { Commands.Command command = Commands.HandleCommand (); switch (command) { case Commands.Command.MoveForward: { Console.WriteLine ("You enter the room and spot doors to the north and south."); Room9 (); break; } case Commands.Command.MoveBackward: { Console.WriteLine ("You enter the room and spot doors to the north and south."); Room11 (); break; } case Commands.Command.MoveRight: { Console.WriteLine ("You enter the room and spot doors to the east and west."); Room13 (); break; } case Commands.Command.Look: { Console.Out.WriteLine ("There's a door to the north, south, and east."); Room10 (); break; } case Commands.Command.Quit: { break; } default: { Console.Out.WriteLine ("I can't do that now."); Room10 (); break; } } }
/// <summary> /// Reads a response from the stream to CWSRestart /// </summary> /// <returns>A tuple containting the Command and the content of the response. Can be null if no response was read</returns> private Tuple <Commands.Command, string> readResponse() { if (tryConnect()) { StreamReader reader = new StreamReader(client, System.Text.Encoding.UTF8, true, 2048, true); string response = reader.ReadLine(); if (response == null) { return(null); } string[] messages = response.Split(new string[] { " " }, 3, StringSplitOptions.None); if (messages.Count() == 2 || messages.Count() == 3) { Commands.Action a = (Commands.Action)Enum.Parse(typeof(Commands.Action), messages[0]); Commands.Command c = (Commands.Command)Enum.Parse(typeof(Commands.Command), messages[1]); string message = (messages.Count() == 3) ? messages[2] : ""; switch (a) { case Commands.Action.POST: reader.Close(); return(new Tuple <Commands.Command, string>(c, message)); default: reader.Close(); throw new NotImplementedException(); } } else { reader.Close(); throw new NotImplementedException(); } } return(null); }
public void WriteCommand(Commands.Command command) { var oldCommand = _currentCommand; _currentCommand = command; // write to bucket command.WriteAsBinary(this); WriteHeader(command); if (_bucket.Count % 2 == 1) { _bucket.Add(0); } _bucket.SaveToStream(_stream); _bucket.Clear(); _currentCommand = oldCommand; }
public void SaveFile(Commands.Command commandToSave, string filename) { try { CommandFile file = new CommandFile(errorLogger); file.Initialise(commandToSave); string contents = file.ToXML(); if (contents != null) { if (!filename.EndsWith(".xml")) { filename += ".xml"; } File.WriteAllText(Path.Combine(saveDirectory, filename), contents); } } catch (Exception ex) { errorLogger.LogException(ex, ErrorSeverity.Error); } }
public NPTReportVm(NPTVm parent) { Parent = parent; DurationSeconds = parent.DurationSeconds; EndDateTime = parent.StartDateTime.AddSeconds(parent.DurationSeconds); AddCommand = new Commands.Command(o => { var model = new Model.NonProductiveTaskReport(); model.ReportDurationSeconds = DurationSeconds; IsSelected = false; }); FocusCommand = new Commands.Command(o => { IsSelected = true; }); CancelCommand = new Commands.Command(o => { IsSelected = false; }); }
/// <summary> /// Send the given command with the given content and method to CWSRestart /// </summary> /// <param name="command"></param> /// <param name="content"></param> /// <param name="action"></param> /// <returns>True if the command was sent succesful, otherwise false</returns> private bool sendCommand(Commands.Command command, String content, Commands.Action action) { try { if (tryConnect()) { StreamWriter writer = new StreamWriter(client, System.Text.Encoding.UTF8, 2048, true); string message = String.Format("{0} {1} {2}", action, command, content); writer.WriteLine(message); writer.Close(); return(true); } return(false); } catch (IOException) { disconnectClient(); return(false); } }
public byte[] serialize(Commands.Command c) { System.IO.MemoryStream m = new System.IO.MemoryStream(); System.IO.BinaryWriter b = new System.IO.BinaryWriter(m); string t = c.GetType().FullName; b.Write(Encoding.UTF8.GetByteCount(t)); b.Write(Encoding.UTF8.GetBytes(t)); string d = Newtonsoft.Json.JsonConvert.SerializeObject(c); b.Write(Encoding.UTF8.GetByteCount(d)); b.Write(Encoding.UTF8.GetBytes(d)); b.Flush(); byte[] output = m.ToArray(); b.Dispose(); m.Dispose(); return(output); }
public TimingSet(Soheil.Core.ViewModels.PP.Report.ProcessReportVm vm) { IsInitializing = () => vm._isInInitializingPhase; SetIsInitializing = v => vm._isInInitializingPhase = v; GetCycleTime = () => vm.Model.Process.StateStationActivity.CycleTime; GetLowerBound = () => vm.Model.Process.StartDateTime; GetUpperBound = () => vm.Model.Process.EndDateTime; TargetPoint = vm.Model.ProcessReportTargetPoint; DurationSeconds = vm.Model.DurationSeconds; StartDateTime = vm.Model.StartDateTime; EndDateTime = vm.Model.EndDateTime; AutoDurationCommand = new Commands.Command(o => { DurationSeconds = (int)(TargetPoint * GetCycleTime()); }); AutoTargetPointCommand = new Commands.Command(o => { TargetPoint = (int)(DurationSeconds / GetCycleTime()); }); }
public SetupTimeTableVm(AccessType access) { Access = access; CanEdit = (int)access >= (int)AccessType.Update; RefreshAllCommand = new Commands.Command(o => { var models = new DataServices.StationDataService().GetActives(); foreach (var model in models) { Stations.Add(new Station(model)); } if (Stations.Any()) { if (SelectedStation != null) { SelectedStation = Stations.FirstOrDefault(x => x.Id == SelectedStation.Id); } } }); RefreshAllCommand.Execute(null); }
/// <summary> /// Initializes the command(s) /// </summary> void initializeCommands() { ChangeCommand = new Commands.Command(value => { //memorize the previous data var previousData = Data; //finds the new value for ILUO in any way possible //command parameter is null if (value == null) Data = ILUO.N; //command parameter is enum if (value is ILUO) Data = (ILUO)value; //command parameter is string else if (value is string) { if (string.IsNullOrWhiteSpace((string)value)) Data = ILUO.N; var c = ((string)value).ToUpper()[0]; switch (c) { case 'N': Data = ILUO.N; break; case 'I': Data = ILUO.I; break; case 'L': Data = ILUO.L; break; case 'U': Data = ILUO.U; break; case 'O': Data = ILUO.O; break; default: Data = ILUO.N; break; } } //if any change to Data occurs fire the IluoChanged event if (previousData != Data && IluoChanged != null) IluoChanged(this); }); }
/// <summary> /// Initialize Commands /// </summary> private void initCommands() { SaveAllCommand = new Commands.Command(o => { try { foreach (var state in States) { state.PromptSave(); } fpcDataService.ApplyChanges(); //check for tracability Soheil.Core.PP.Smart.SmartJob.AutoRouteCheck(this.Id); //always throws, so no after lines } catch (SoheilExceptionBase exp) { string msg = ""; if (exp.Level == ExceptionLevel.Error) msg += "FPC تعریف شده قابل مسیریابی نمی باشد.\nدر صورتی که می خواهید از قابلیت افزودن خودکار Job استفاده نمایید بایستی FPC را اصلاح کنید.\n"; msg += exp.Message; Message = new DependencyMessageBox(msg, exp.Caption, MessageBoxButton.OK, exp.Level); } catch (Exception exp) { Message = new DependencyMessageBox( exp, "در ذخیره سازی خطای پیش آمد.", "خطا", MessageBoxButton.OK, ExceptionLevel.Error); } }); ExpandAllCommand = new Commands.Command(o => { var items = States.Where(x => x.StateType == StateType.Mid); foreach (var item in items) { item.ShowDetails = true; } }); CollapseAllCommand = new Commands.Command(o => { foreach (var item in States.Where(x => x.StateType == StateType.Mid)) { item.ShowDetails = false; } }); ResetZoomCommand = new Commands.Command(o => Zoom = 1d); }
public DefectionReportVm(DefectionReportCollection parent, Model.DefectionReport model) { Model = model; Index = parent.Parent.DefectionReports.List.Count + 1; Parent = parent; IsG2 = model.IsG2; ProductDefection = FilterBoxVm.CreateForProductDefections( model.ProductDefection == null ? -1 : model.ProductDefection.Id, model.ProcessReport.Process.StateStationActivity.StateStation.State.FPC.Product.Id); var pdrepo = new Dal.Repository<Model.ProductDefection>(Parent.Parent.UOW); ProductDefection.FilterableItemSelected += (s, old, v) => Model.ProductDefection = pdrepo.FirstOrDefault(x => x.Id == v.Id); if (ProductDefection.SelectedItem == null) ProductDefection.SelectedItem = ProductDefection.FilteredList.FirstOrDefault(); //create and load OperatorDefectionReports GuiltyOperators = FilterBoxVmCollection.CreateForGuiltyOperators(model.OperatorDefectionReports, Parent.Parent.UOW); var odrRepo = new Dal.Repository<Model.OperatorDefectionReport>(Parent.Parent.UOW); GuiltyOperators.OperatorSelected += (vm, oldOp, newOp) => { if (newOp.Model == null) return; if (vm.Model == null) { //create and add new ODR var odr = new Model.OperatorDefectionReport { DefectionReport = model, Operator = newOp.Model, ModifiedBy = LoginInfo.Id, }; odrRepo.Add(odr); vm.Model = odr; } else { //update existing ODR (vm.Model as Model.OperatorDefectionReport).Operator = newOp.Model; } }; GuiltyOperators.OperatorRemoved += vm => { if (vm.Model != null) { model.OperatorDefectionReports.Remove(vm.Model as Model.OperatorDefectionReport); odrRepo.Delete(vm.Model as Model.OperatorDefectionReport); } }; AffectsTaskReport = model.AffectsTaskReport; LostSeconds = model.LostTime; LostCount = model.LostCount; Description = model.Description; DeleteCommand = new Commands.Command(o => { //correct sums Parent.SumOfLostCount -= LostCount; Parent.SumOfLostTime-= LostSeconds; Parent.SumOfTimeEquivalent -= TimeEquivalent; Parent.SumOfCountEquivalent -= QuantityEquivalent; //delete Parent.List.Remove(this); Model.ProcessReport.DefectionReports.Remove(Model); new DataServices.ProcessReportDataService(Parent.Parent.UOW).Delete(Model); //reset indices for (int i = 0; i < Parent.List.Count; i++) { Parent.List[i].Index = i + 1; } }); }
public TaskVm(Model.Task taskModel, Dal.SoheilEdmContext uow) { //data service UOW = uow; _taskReportDataService = new DataServices.TaskReportDataService(UOW); Message = new EmbeddedException(); //update model data Model = taskModel; StartDateTime = taskModel.StartDateTime; StartDateTimeChanged += newVal => Model.StartDateTime = newVal; DurationSeconds = taskModel.DurationSeconds; DurationSecondsChanged += newVal => Model.DurationSeconds = newVal; //TaskTargetPoint = taskModel.TaskTargetPoint; TaskProducedG1 = taskModel.TaskReports.Sum(x => x.TaskProducedG1); //this non-crucial block of code is likely to throw try { //calculate the number of distinct operators var ids = new List<int>(); foreach (var item in taskModel.Processes) { ids.AddRange(item.ProcessOperators.Select(x => x.Operator.Id)); } TaskOperatorCount = ids.Distinct().Count(); } catch { TaskOperatorCount = -1; }///??? does happen? #region FillEmptySpaces Command FillEmptySpacesCommand = new Commands.Command(o => { var models = Model.TaskReports.OrderBy(x => x.ReportStartDateTime).ToArray(); var dt = StartDateTime; var tp = Model.TaskTargetPoint; if (models.Any()) tp -= models.Sum(x => x.TaskReportTargetPoint); //insert before each task report foreach (var model in models) { if (model.ReportStartDateTime - dt > TimeSpan.FromSeconds(1)) { //insert taskReport newModel before model var duration = model.ReportStartDateTime - dt; var newModel = new Model.TaskReport { Task = Model, Code = Model.Code, ReportStartDateTime = dt, ReportEndDateTime = model.ReportStartDateTime, ReportDurationSeconds = (int)duration.TotalSeconds, TaskProducedG1 = 0, TaskReportTargetPoint = (int)(duration.TotalSeconds * Model.TaskTargetPoint / Model.DurationSeconds), CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now, ModifiedBy = LoginInfo.Id, }; Model.TaskReports.Add(newModel); } dt = model.ReportEndDateTime; } //insert after last task report if (Model.EndDateTime - dt > TimeSpan.FromSeconds(1)) { //insert taskReport after last model var duration = Model.EndDateTime - dt; var newModel = new Model.TaskReport { Task = Model, Code = Model.Code, ReportStartDateTime = dt, ReportEndDateTime = Model.EndDateTime, ReportDurationSeconds = (int)duration.TotalSeconds, TaskProducedG1 = 0, TaskReportTargetPoint = (int)(duration.TotalSeconds * Model.TaskTargetPoint / Model.DurationSeconds), CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now, ModifiedBy = LoginInfo.Id, }; Model.TaskReports.Add(newModel); } //reload reports ReloadTaskReports(); }); #endregion }
public StoppageReportVm(StoppageReportCollection parent, Model.StoppageReport model) { Model = model; Index = parent.Parent.StoppageReports.List.Count + 1; Parent = parent; int[] causeIds = null; if (model.Cause != null) if (model.Cause.Parent != null) if (model.Cause.Parent.Parent != null) causeIds = new int[3] { model.Cause.Parent.Parent.Id, model.Cause.Parent.Id, model.Cause.Id }; StoppageLevels = FilterBoxVmCollection.CreateForStoppageReport(this, causeIds); GuiltyOperators = FilterBoxVmCollection.CreateForGuiltyOperators(model.OperatorStoppageReports, Parent.Parent.UOW); var osrRepo = new Dal.Repository<Model.OperatorStoppageReport>(Parent.Parent.UOW); GuiltyOperators.OperatorSelected += (vm, oldOp, newOp) => { if (newOp.Model == null) return; //update model if (vm.Model == null) { //create and add new OSR var osr = new Model.OperatorStoppageReport { StoppageReport = model, Operator = newOp.Model, ModifiedBy = LoginInfo.Id, }; osrRepo.Add(osr); vm.Model = osr; } else { //update existing OSR (vm.Model as Model.OperatorStoppageReport).Operator = newOp.Model; } }; GuiltyOperators.OperatorRemoved += vm => { if (vm.Model != null) { model.OperatorStoppageReports.Remove((vm.Model as Model.OperatorStoppageReport)); osrRepo.Delete((vm.Model as Model.OperatorStoppageReport)); } }; AffectsTaskReport = model.AffectsTaskReport; LostSeconds = model.LostTime; LostCount = model.LostCount; Description = model.Description; DeleteCommand = new Commands.Command(o => { //correct sums Parent.SumOfLostCount -= LostCount; Parent.SumOfLostTime-= LostSeconds; Parent.SumOfTimeEquivalent -= TimeEquivalent; Parent.SumOfCountEquivalent -= QuantityEquivalent; //delete Parent.List.Remove(this); Model.ProcessReport.StoppageReports.Remove(Model); new DataServices.ProcessReportDataService(Parent.Parent.UOW).Delete(Model); //reset indices for (int i = 0; i < Parent.List.Count; i++) { Parent.List[i].Index = i + 1; } }); }
void initializeCommands() { SelectCommand = new Commands.Command(o => { if (JobSelected != null) JobSelected(Id); }); }
private void initCommands() { SaveCommand = new Commands.Command(o => { try { PromptSave(); ParentWindowVm.fpcDataService.stateDataService.AttachModel(Model); } catch (Common.SoheilException.SoheilExceptionBase exp) { string msg = ""; if (exp.Level == Common.SoheilException.ExceptionLevel.Error) msg += "قادر به ذخیره مرحله نیست\n"; msg += exp.Message; ParentWindowVm.Message = new Common.SoheilException.DependencyMessageBox(msg, exp.Caption, MessageBoxButton.OK, exp.Level); } catch (Exception exp) { ParentWindowVm.Message = new Common.SoheilException.DependencyMessageBox(exp); } }); DeleteCommand = new Commands.Command(o => { try { //check for constraints var entity = new Dal.Repository<Model.State>(new Dal.SoheilEdmContext()).Single(x => x.Id == Id); if (entity != null && entity.StateStations.Any(ss => ss.Blocks.Any())) { ParentWindowVm.Message = new Common.SoheilException.DependencyMessageBox("این مرحله (بعضی از ایستگاهها) در برنامه تولید استفاده شده است", "Error", MessageBoxButton.OK, Common.SoheilException.ExceptionLevel.Error); return; } var connectors = ParentWindowVm.Connectors.Where(x => x.Start.Id == Id || x.End.Id == Id).ToList(); ParentWindowVm.fpcDataService.stateDataService.DeleteModel(Model); //notify deletion (to remove state and its connectors from parent) if (StateDeleted != null) StateDeleted(connectors); } catch (Common.SoheilException.SoheilExceptionBase exp) { string msg = ""; if (exp.Level == Common.SoheilException.ExceptionLevel.Error) msg += "قادر به حذف مرحله نیست\n"; msg += exp.Message; ParentWindowVm.Message = new Common.SoheilException.DependencyMessageBox(msg, exp.Caption, MessageBoxButton.OK, exp.Level); } catch (Exception exp) { ParentWindowVm.Message = new Common.SoheilException.DependencyMessageBox(exp); } }); SelectCommand = new Command(o => { if (StateSelected != null) StateSelected(); }); }
void initializeCommands() { OpenCommand = new Commands.Command(o => IsSelected = true); CloseCommand = new Commands.Command(o => IsSelected = false); SaveCommand = new Commands.Command(o => { IsSelected = !Save(o != null); //reload all process reports for the block if (LayoutChanged != null) LayoutChanged(); }); DeleteCommand = new Commands.Command(o => { try { IsSelected = false; _processReportDataService.DeleteModel(Model); //reload all process reports for the block if (LayoutChanged != null) LayoutChanged(); } catch(Exception ex) { Message.AddEmbeddedException(ex); } }); }
void initializeCommands() { SaveCommand = new Commands.Command(o => { _jobDataService.SaveAndGenerateTasks(this); bool refresh = true; if (o != null) if (o.GetType() == typeof(bool)) refresh = (bool)o; if (refresh && RefreshPPTable != null) RefreshPPTable(); }); DeleteJobCommand = new Commands.Command(o => { if (JobDeleted != null) JobDeleted(this); }); AddReplicationCommand = new Commands.Command(o => Replications.Add(new Model.Job())); RemoveReplicationCommand = new Commands.Command(o => { if (Replications.Count > 1) Replications.Remove(Replications.Last()); }); }
void initializeCommands() { SaveCommand = new Commands.Command(o => { UOW.Commit(); }); DeleteCommand = new Commands.Command(o => { _taskReportDataService.DeleteModel(Model); if (TaskReportDeleted != null) TaskReportDeleted(this); }); AutoDurationCommand = new Commands.Command(o => { var otherReports = Model.Task.TaskReports.Where(x => x != Model); var remainingTp = Model.Task.TaskTargetPoint - (otherReports.Any() ? otherReports.Sum(x => x.TaskReportTargetPoint) : 0); var remainingDur = Model.Task.DurationSeconds - (otherReports.Any() ? otherReports.Sum(x => x.ReportDurationSeconds) : 0); if (remainingTp <= 0 || remainingDur <= 0) DurationSeconds = 0; else DurationSeconds = (int)Math.Round(TargetPoint * remainingDur / (float)remainingTp); }); AutoTargetPointCommand = new Commands.Command(o => { var otherReports = Model.Task.TaskReports.Where(x => x != Model); var remainingTp = Model.Task.TaskTargetPoint - (otherReports.Any() ? otherReports.Sum(x => x.TaskReportTargetPoint) : 0); var remainingDur = Model.Task.DurationSeconds - (otherReports.Any() ? otherReports.Sum(x => x.ReportDurationSeconds) : 0); if (remainingTp <= 0 || remainingDur <= 0) TargetPoint = 0; else TargetPoint = (int)Math.Round(DurationSeconds * remainingTp / (float)remainingDur); }); }