示例#1
0
 public SectionResponseEnum Execute(PackageClass packageClass, ActionItem actionItem)
 {
   if (ItemProcessed != null)
     ItemProcessed(this, new InstallEventArgs("Message box"));
   MessageBox.Show(actionItem.Params[Const_MESSAGE].Value);
   return SectionResponseEnum.Ok;
 }
示例#2
0
    public SectionResponseEnum Execute(PackageClass packageClass, ActionItem actionItem)
    {
      if (ItemProcessed != null)
        ItemProcessed(this, new InstallEventArgs("Create ShortCut"));

      try
      {
        UnInstallItem unInstallItem =
          packageClass.UnInstallInfo.BackUpFile(actionItem.Params[Const_Loc].GetValueAsPath(), "CopyFile");

        WshShellClass wshShell = new WshShellClass();
        // Create the shortcut

        IWshShortcut myShortcut = (IWshShortcut)wshShell.CreateShortcut(actionItem.Params[Const_Loc].GetValueAsPath());
        myShortcut.TargetPath = Path.GetFullPath(actionItem.Params[Const_Target].GetValueAsPath());
        myShortcut.WorkingDirectory = Path.GetDirectoryName(myShortcut.TargetPath);
        myShortcut.Description = actionItem.Params[Const_Description].Value;

        if (!string.IsNullOrEmpty(actionItem.Params[Const_Icon].Value))
          myShortcut.IconLocation = actionItem.Params[Const_Icon].GetValueAsPath();
        else
          myShortcut.IconLocation = actionItem.Params[Const_Target].GetValueAsPath();

        myShortcut.Save();

        FileInfo info = new FileInfo(actionItem.Params[Const_Loc].GetValueAsPath());
        unInstallItem.FileDate = info.CreationTimeUtc;
        unInstallItem.FileSize = info.Length;
        packageClass.UnInstallInfo.Items.Add(unInstallItem);
      }
      catch (Exception) {}

      return SectionResponseEnum.Ok;
    }
示例#3
0
 public Action(ActionItem item, ActionType type, TimeSpan duration)
 {
     Id = Guid.NewGuid();
     Item = item;
     Duration = duration;
     Type = type;
 }
示例#4
0
 public SectionResponseEnum Execute(PackageClass packageClass, ActionItem actionItem)
 {
   packageClass.FileInstalled += packageClass_FileInstalled;
   packageClass.Install();
   packageClass.FileInstalled -= packageClass_FileInstalled;
   return SectionResponseEnum.Ok;
 }
示例#5
0
        public void GetArgumentsForFileMode(
            string targetFolder, string targetFile1,
            string targetFile2, string format)
        {
            int ExpectedWriteLineCallCount = 0;
            List<string> ExpectedWriteLineCallValues = new List<string>();

            if (targetFolder != null)
            {
                ++ExpectedWriteLineCallCount;
                ExpectedWriteLineCallValues.Add(targetFolder);
            }

            string[] targetFiles = null;
            if (targetFile2 != null)
            {
                targetFiles = new string[] { targetFile1, targetFile2 };
                ExpectedWriteLineCallCount += 2;
            }
            else if (targetFile1 != null)
            {
                targetFiles = new string[] { targetFile1, };
                ++ExpectedWriteLineCallCount;
            }

            ExpectedWriteLineCallValues.AddRange(targetFiles);

            ActionItem TestSubject = new ActionItem();
            TestSubject.TargetListMode = TargetMode.File;
            TestSubject.ArgumentsFormat = format;

            RecorderWriterBase WriterRecorder = new RecorderWriterBase("bogas $%@#!");
            TestSubject.Writer = WriterRecorder;

            string ActualArguments = TestSubject.GetArguments(targetFolder, targetFiles);

            Assert.AreEqual(ExpectedWriteLineCallCount, WriterRecorder.Recordings.WriteLineStringRecording.CallCount, "Writeline was not called the correct number of times.");

            for (int i = 0; i < ExpectedWriteLineCallCount; i++)
            {
                Assert.In(ExpectedWriteLineCallValues[i],
                    WriterRecorder.Recordings.WriteLineStringRecording.AllPassedStringline,
                    string.Format("This value was not written: {0}", ExpectedWriteLineCallValues[i]));
            }

            string ExpectedArguements;

            if (format != null)
            {
                format = format.Replace("{0}", @"""{0}"" ");
                ExpectedArguements = string.Format(format, TestSubject.TempFilePath);
            }
            else
                ExpectedArguements = string.Format(@"""{0}"" ", TestSubject.TempFilePath);

            Assert.AreEqual(ExpectedArguements, ActualArguments);
            Assert.IsTrue(WriterRecorder.Recordings.DisposeRecording.Called, "The writer was not disposed!");
        }
示例#6
0
 public ValidationResponse Validate(PackageClass packageClass, ActionItem actionItem)
 {
   if (!string.IsNullOrEmpty(actionItem.ConditionGroup) && packageClass.Groups[actionItem.ConditionGroup] == null)
     return new ValidationResponse
              {
                Message = actionItem.Name + " condition group not found " + actionItem.ConditionGroup,
                Valid = false
              };
   return new ValidationResponse();
 }
示例#7
0
 public ActionList(string controller)
 {
     Add = new ActionItem(controller, DefaultAddAction);
     Upd = new ActionItem(controller, DefaultUpdAction);
     Del = new ActionItem(controller, DefaultDelAction);
     Grid = new ActionItem(controller, DefaultGridAction);
     Sort = new ActionItem(controller, DefaultSortAction);
     Filter = new ActionItem(controller, DefaultFilterAction);
     Paging = new ActionItem(controller, DefaultPagingAction);
 }
示例#8
0
 public SectionResponseEnum Execute(PackageClass packageClass, ActionItem actionItem)
 {
   if (ItemProcessed != null)
     ItemProcessed(this, new InstallEventArgs("Kill Task"));
   Process[] prs = Process.GetProcesses();
   foreach (Process pr in prs)
   {
     if (pr.ProcessName.Equals(actionItem.Params[Const_MESSAGE].Value, StringComparison.InvariantCultureIgnoreCase))
       pr.Kill();
   }
   return SectionResponseEnum.Ok;
 }
示例#9
0
 public ValidationResponse Validate(PackageClass packageClass, ActionItem actionItem)
 {
   if (!string.IsNullOrEmpty(actionItem.ConditionGroup) && packageClass.Groups[actionItem.ConditionGroup] == null)
     return new ValidationResponse()
              {
                Message = actionItem.Name + " condition group not found " + actionItem.ConditionGroup,
                Valid = false
              };
   if (string.IsNullOrEmpty(actionItem.Params[Const_Loc].Value))
     return new ValidationResponse()
              {Message = "[CreateFolder] no destnation folder specified !", Valid = false};
   return new ValidationResponse();
 }
        public void DrawActionDialog(IPlatformDrawer platform, Rect bounds, ActionItem item, Action cancel = null)
        {
            if (item == null) return;

            platform.DrawStretchBox(bounds, CachedStyles.WizardSubBoxStyle, 13);

            bounds = bounds.PadSides(15);

            var descriptionHeight = string.IsNullOrEmpty(item.Description) ? 50 : platform.CalculateTextHeight(item.Description, CachedStyles.BreadcrumbTitleStyle, bounds.width) + 60;

            var headerRect = bounds.WithHeight(40);
            var iconRect = bounds.WithSize(41, 41);
            
            var descriptionRect = headerRect.Below(headerRect).Translate(0,-22).WithHeight(descriptionHeight);
            var inspectorRect = bounds.Below(descriptionRect).Clip(bounds);
            var executeButtonRect = new Rect()
                .WithSize(100, 30)
                .InnerAlignWithBottomRight(bounds);

            if (!_inspectors.ContainsKey(item))
            {
                var uFrameMiniInspector = new uFrameMiniInspector(item.Command);
                _inspectors.Add(item, uFrameMiniInspector);
            }
            var inspector = _inspectors[item];
            var inspectorHeight = inspector.Height;


            _scrollPosition = GUI.BeginScrollView(bounds.AddHeight(-30).AddWidth(15), _scrollPosition,
                bounds.WithHeight(headerRect.height + iconRect.height + descriptionRect.height + inspectorHeight));

            platform.DrawLabel(headerRect, item.Title, CachedStyles.WizardSubBoxTitleStyle, DrawingAlignment.MiddleCenter);
            platform.DrawImage(iconRect, string.IsNullOrEmpty(item.Icon) ? "CreateEmptyDatabaseIcon" : item.Icon, true);
            platform.DrawLabel(descriptionRect, item.Description, CachedStyles.BreadcrumbTitleStyle, DrawingAlignment.MiddleLeft);

            inspector.Draw(descriptionRect.WithHeight(inspectorHeight).Pad(0,0,10,0).Below(descriptionRect));

            //Draw generic inspector


                GUI.EndScrollView();
            if ( cancel != null)
            {
                platform.DoButton(executeButtonRect.InnerAlignWithBottomLeft(bounds), "Cancel", ElementDesignerStyles.DarkButtonStyle, cancel);
            }

            platform.DoButton(executeButtonRect, string.IsNullOrEmpty(item.Verb) ? "Create" : item.Verb, ElementDesignerStyles.DarkButtonStyle, () =>
            {
                InvertApplication.Execute(item.Command);
            });
        }
示例#11
0
 private async Task<bool> Action(ActionItem item, NavigationEventArgs e)
 {
     tbInformation.Text = item.message;
     Error error = await item.function();
     if (error != null)
     {
         tbInformation.Text = error.message;
         await Task.Delay(new TimeSpan(0, 0, 3));
         //Frame.Navigate(typeof(ConnectPage));
         base.OnNavigatedTo(e);
         return false;
     }
     else
         return true;
 }
示例#12
0
 public SectionResponseEnum Execute(PackageClass packageClass, ActionItem actionItem)
 {
   try
   {
     if (ItemProcessed != null)
       ItemProcessed(this, new InstallEventArgs("Create Folder"));
     if (!Directory.Exists(actionItem.Params[Const_Loc].GetValueAsPath()))
       Directory.CreateDirectory(actionItem.Params[Const_Loc].GetValueAsPath());
     UnInstallItem unInstallItem = new UnInstallItem();
     unInstallItem.ActionType = DisplayName;
     unInstallItem.ActionParam = new SectionParamCollection(actionItem.Params);
     unInstallItem.ActionParam[Const_Loc].Value = actionItem.Params[Const_Loc].GetValueAsPath();
     packageClass.UnInstallInfo.Items.Add(unInstallItem);
   }
   catch {}
   return SectionResponseEnum.Ok;
 }
示例#13
0
        public void AddAction(string image, string title, string href)
        {
            #region arguments

            if (string.IsNullOrEmpty(title))
            {
                throw new ArgumentNullException("title");
            }
            if (string.IsNullOrEmpty(href))
            {
                throw new ArgumentNullException("href");
            }

            #endregion

            ActionItem actionItem = new ActionItem() { Image = image, Title = title, HRef = href };
            this.actionItems.Add(actionItem);
        }
示例#14
0
        public void GetArgumentsForCommandLineMode(
            string targetFolder, string targetFile1,
            string targetFile2, string format,
            string expectedArguements)
        {
            string[] targetFiles = null;
            if (targetFile2 != null)
                targetFiles = new string[] { targetFile1, targetFile2 };
            else if (targetFile1 != null)
                targetFiles = new string[] { targetFile1, };

            ActionItem TestSubject = new ActionItem();
            TestSubject.TargetListMode = TargetMode.CommandLine;
            TestSubject.ArgumentsFormat = format;

            string ActualArguments = TestSubject.GetArguments(targetFolder, targetFiles);

            Assert.AreEqual(expectedArguements, ActualArguments);
        }
示例#15
0
 public SectionResponseEnum Execute(PackageClass packageClass, ActionItem actionItem)
 {
   if (ItemProcessed != null)
     ItemProcessed(this, new InstallEventArgs("Clear skin cache"));
   try
   {
     Directory.Delete(MpeInstaller.TransformInRealPath("%Cache%"), true);
     Directory.CreateDirectory(MpeInstaller.TransformInRealPath("%Cache%"));
   }
   catch (Exception)
   {
     if (ItemProcessed != null)
       ItemProcessed(this, new InstallEventArgs("Error clearing skin cache"));
     return SectionResponseEnum.Ok;
   }
   if (ItemProcessed != null)
     ItemProcessed(this, new InstallEventArgs("Clear skin cache done"));
   return SectionResponseEnum.Ok;
 }
        public void DrawDatabasesWizard(Rect bounds)
        {

           // platform.DrawStretchBox(bounds, CachedStyles.WizardBoxStyle, 13);

            var actions = new List<ActionItem>();
            var items = new List<DatabasesListItem>();
            var databasesActionsBounds = bounds.LeftHalf().TopHalf().PadSides(2);
            var databasesListBounds = bounds.RightHalf().PadSides(2);
            var databasesActionInspectorBounds = bounds.LeftHalf().BottomHalf().PadSides(2);
            var closeButtonBounds = new Rect().WithSize(80, 30).InnerAlignWithBottomRight(databasesListBounds.PadSides(15));

            Signal<IQueryDatabasesActions>(_ => _.QueryDatabasesActions(actions));
            Signal<IQueryDatabasesListItems>(_ => _.QueryDatabasesListItems(items));
            Signal<IDrawActionsPanel>(_ => _.DrawActionsPanel(Drawer, databasesActionsBounds, actions,(a,m)=> SelectedItem = a));
            Signal<IDrawActionDialog>(_ => _.DrawActionDialog(Drawer, databasesActionInspectorBounds,SelectedItem,()=> SelectedItem = null));
            Signal<IDrawDatabasesList>(_ => _.DrawDatabasesList(Drawer, databasesListBounds, items));

            Drawer.DoButton(closeButtonBounds, "Close", ElementDesignerStyles.DarkButtonStyle, () => EnableWizard = false);
        }
示例#17
0
    public SectionResponseEnum Execute(PackageClass packageClass, ActionItem actionItem)
    {
      if (actionItem.Params[Const_APP].GetValueAsBool() && packageClass.Silent)
        return SectionResponseEnum.Ok;

      Process myProcess = new Process();

      try
      {
        myProcess.StartInfo.UseShellExecute = false;
        myProcess.StartInfo.FileName = MpeInstaller.TransformInRealPath(actionItem.Params[Const_APP].Value);
        myProcess.StartInfo.Arguments = MpeInstaller.TransformInRealPath(actionItem.Params[Const_Params].Value);
        myProcess.StartInfo.CreateNoWindow = true;

        if (packageClass.Silent)
        {
          myProcess.StartInfo.CreateNoWindow = true;
          myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
        }
        myProcess.Start();
        if (actionItem.Params[Const_Wait].GetValueAsBool())
        {
          myProcess.WaitForExit();
          if (myProcess.ExitCode != 0)
            return SectionResponseEnum.Error;
        }
      }
      catch
      {
        if (ItemProcessed != null)
          ItemProcessed(this, new InstallEventArgs("Error to start application"));
        return SectionResponseEnum.Error;
      }
      UnInstallItem unInstallItem = new UnInstallItem();
      unInstallItem.ActionType = DisplayName;
      unInstallItem.ActionParam = new SectionParamCollection(actionItem.Params);
      unInstallItem.ActionParam[Const_APP].Value = actionItem.Params[Const_APP].GetValueAsPath();
      unInstallItem.ActionParam[Const_Un_APP].Value = actionItem.Params[Const_Un_APP].GetValueAsPath();
      packageClass.UnInstallInfo.Items.Add(unInstallItem);
      return SectionResponseEnum.Ok;
    }
        private OLocation CreateRouteDeco(SiteData _site, ActionItem action)
        {
            var deco = new OLocation
            {
                Id         = string.Join("/", _site.Id, action.GetCustomerName(), action.GetCustomerReference()),
                Reference  = action.GetCustomerReference(),
                Name       = action.GetCustomerName(),
                ClientId   = _site.Id,
                ReceivedOn = DateTime.Now,
                Coords     = new Trackmatic.Rest.SpecializedObservableCollection <OCoord>()
                {
                    new OCoord()
                    {
                        Latitude  = action.GetLatitude(),
                        Longitude = action.GetLongitude(),
                        Radius    = 100
                    }
                },
                Entrance = new OCoord()
                {
                    Latitude  = action.GetLatitude(),
                    Longitude = action.GetLongitude(),
                },
                StructuredAddress = new StructuredAddress()
                {
                    UnitNo            = action.GetUnitNo(),
                    BuildingName      = action.GetBuildingName(),
                    SubDivisionNumber = action.GetSubDivisionNumber(),
                    StreetNo          = action.GetStreetNo(),
                    Street            = action.GetStreet(),
                    Suburb            = action.GetSuburb(),
                    City       = action.GetCity(),
                    Province   = action.GetProvince(),
                    PostalCode = action.GetPostalCode()
                }
            };

            return(deco);
        }
示例#19
0
 public ActionEdit(PackageClass packageClass, ActionItem item)
 {
     _loading      = true;
     _packageClass = packageClass;
     _actionItem   = item;
     InitializeComponent();
     Icon          = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
     cmb_type.Text = item.ActionType;
     cmb_group.Items.Add("");
     foreach (var group in packageClass.Groups.Items)
     {
         cmb_group.Items.Add(group.Name);
     }
     cmb_group.SelectedItem = item.ConditionGroup;
     if (_actionItem.Params.Items.Count < 1)
     {
         btn_params.Enabled = false;
     }
     lbl_description.Text      = MpeInstaller.ActionProviders[item.ActionType].Description;
     cmb_execute.SelectedIndex = (int)item.ExecuteLocation;
     _loading = false;
 }
        private void StartReceiving(TInnerChannel channel, bool canBlock)
        {
            TItem local;

            do
            {
                local = default(TItem);
                try
                {
                    IAsyncResult state = this.BeginTryReceiveItem(channel, this.onTryReceiveComplete, channel);
                    if (!state.CompletedSynchronously)
                    {
                        break;
                    }
                    if (!canBlock)
                    {
                        ActionItem.Schedule(this.asyncHandleReceiveComplete, state);
                        break;
                    }
                    this.EndTryReceiveItem(channel, state, out local);
                    if (local == null)
                    {
                        break;
                    }
                }
                catch (Exception exception)
                {
                    if (Fx.IsFatal(exception))
                    {
                        throw;
                    }
                    if (!base.HandleException(exception, channel))
                    {
                        channel.Abort();
                        break;
                    }
                }
            }while ((local == null) || this.HandleReceiveComplete(local, channel));
        }
示例#21
0
        protected override void OnListen()
        {
            IPEndPoint endPoint = this.transportSettings.EndPoint as IPEndPoint;

            if (endPoint == null)
            {
                throw new InvalidOperationException(SRClient.ListenOnIPEndpoint);
            }

            this.listenSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            this.listenSocket.Bind(endPoint);
            this.listenSocket.Listen(this.transportSettings.TcpBacklog);

            for (int i = 0; i < this.transportSettings.ListenerAcceptorCount; ++i)
            {
                SocketAsyncEventArgs listenEventArgs = new SocketAsyncEventArgs();
                listenEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(this.OnAcceptComplete);
                listenEventArgs.UserToken  = this;

                ActionItem.Schedule(AcceptTransportLoop, listenEventArgs);
            }
        }
示例#22
0
        public ActionResult New(ProjectPrimaryKey projectPrimaryKey, EditViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(ViewEdit(viewModel));
            }

            var actionItem = new ActionItem(ModelObjectHelpers.NotYetAssignedID, ModelObjectHelpers.NotYetAssignedID, DateTime.Now, DateTime.Now, ModelObjectHelpers.NotYetAssignedID);

            viewModel.UpdateModel(actionItem, CurrentFirmaSession);
            HttpRequestStorage.DatabaseEntities.AllActionItems.Add(actionItem);

            var shouldCreateProjectProjectStatus = IsNewProjectProjectStatusNeeded(actionItem);

            if (shouldCreateProjectProjectStatus)
            {
                CreateNewProjectProjectStatus(actionItem);
            }

            SetMessageForDisplay($"Successfully added new {FieldDefinitionEnum.ActionItem.ToType().GetFieldDefinitionLabel()}.");
            return(new ModalDialogFormJsonResult());
        }
        public ValidationResponse Validate(PackageClass packageClass, ActionItem actionItem)
        {
            if (!File.Exists(actionItem.Params[Const_Loc].Value))
            {
                return new ValidationResponse()
                       {
                           Valid = false, Message = " [Install Extension] File not found " + actionItem.Params[Const_Loc].Value
                       }
            }
            ;
            if (!string.IsNullOrEmpty(actionItem.ConditionGroup) && packageClass.Groups[actionItem.ConditionGroup] == null)
            {
                return new ValidationResponse()
                       {
                           Message = actionItem.Name + " condition group not found " + actionItem.ConditionGroup,
                           Valid   = false
                       }
            }
            ;

            return(new ValidationResponse());
        }
示例#24
0
        public void OnOuterListenerOpen(ChannelDemuxerFilter filter, IChannelListener listener, TimeSpan timeout)
        {
            TimeoutHelper helper = new TimeoutHelper(timeout);

            this.openSemaphore.Enter(helper.RemainingTime());
            try
            {
                if (this.ShouldOpenInnerListener(filter, listener))
                {
                    try
                    {
                        this.innerListener.Open(helper.RemainingTime());
                        this.innerChannel = this.innerListener.AcceptChannel(helper.RemainingTime());
                        this.innerChannel.Open(helper.RemainingTime());
                        lock (this.ThisLock)
                        {
                            if (this.abortOngoingOpen)
                            {
                                this.AbortState();
                                return;
                            }
                        }
                        ActionItem.Schedule(DatagramChannelDemuxer <TInnerChannel, TInnerItem> .startReceivingStatic, this);
                        return;
                    }
                    catch (Exception exception)
                    {
                        this.pendingInnerListenerOpenException = exception;
                        throw;
                    }
                }
                this.ThrowPendingOpenExceptionIfAny();
            }
            finally
            {
                this.openSemaphore.Exit();
            }
        }
示例#25
0
        public async Task <IHttpActionResult> PostAsync(int projectId, int?parentId, [FromBody] ActionItemDto model, CancellationToken cancellationToken)
        {
            if (model == null || !ModelState.IsValid)
            {
                return(BadRequest());
            }
            var project = await _projectManager.FindByIdAsync(projectId, cancellationToken);

            await ApiSecurity.AuthorizeAsync(project, AccessPermission.CanEdit, cancellationToken);

            var parentAction = default(ActionItem);

            if (parentId != null)
            {
                parentAction = await _projectManager.GetActionByIdAsync((int)parentId, cancellationToken);

                if (parentAction == null || parentAction.Project.Id != project.Id)
                {
                    return(BadRequest());
                }
            }
            var action = new ActionItem
            {
                Type    = model.Type,
                Enabled = model.Enabled,
                Name    = model.Name,
                Options = model.Options
            };
            var validationResult = await _projectManager.AddActionAsync(project, parentAction, action, cancellationToken);

            if (!validationResult.Succeeded)
            {
                return(this.ValidationContent(validationResult));
            }
            var actionResult = await _projectManager.GetActionByIdAsync(action.Id, cancellationToken);

            return(new ActionContentResult(HttpStatusCode.Created, _actionLinkService, actionResult, this));
        }
示例#26
0
        public async System.Threading.Tasks.Task <ActionResult> ActionInput(ActionListModel inputModel, IList <ActionItem> actionItem, string inputitem, string commititem)
        {
            var list = actionItem;

            if (list == null || list.Count == 0)
            {
                list = new List <ActionItem>();
            }

            if (inputitem != null)
            {
                ActionItem actItem = new ActionItem()
                {
                    Title       = inputModel.Title,
                    Description = inputModel.Description,
                    Assigned    = inputModel.Assigned,
                    Period      = inputModel.Period
                };
                list.Add(actItem);

                //リスト置き換え
                ModelState.Clear();
                inputModel.Title       = string.Empty;
                inputModel.Description = string.Empty;
                inputModel.Assigned    = string.Empty;
                inputModel.Period      = string.Empty;
                inputModel.ActionList  = list;

                return(View(inputModel));
            }
            else
            {
                //リストの登録
                await tableUtils.AddActionListAsync(inputModel.BoardId, list.ToList());

                return(Redirect("/Kpt/actionlist/" + inputModel.BoardId));
            }
        }
 protected void Complete(Exception exception)
 {
     if (completed)
     {
         return;
     }
     lock (ThisLock)
     {
         if (completed)
         {
             return;
         }
         completed = true;
     }
     try
     {
         if (callback != null)
         {
             // complete the AsyncResult on a separate thread so that the queue can progress.
             // this prevents a deadlock when the callback attempts to call Close.
             // this may cause the callbacks to be called in a differnet order in which they completed, but that
             // is ok because each callback is associated with a different object (channel or listener factory)
             ActionItem.Schedule(new Action <object>(AsyncComplete), exception);
         }
         else
         {
             AsyncComplete(exception);
         }
     }
     catch (Exception e)
     {
         if (Fx.IsFatal(e))
         {
             throw;
         }
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(SR.GetString(SR.MessagePropagationException), e);
     }
 }
        private void createMainMenu()
        {
            Menu       versionAndCapitals = new Menu("Version and Capitals");
            ActionItem countCaptials      = new ActionItem("Count Captials");

            countCaptials.Selected += countCaptials_Selected;
            ActionItem showVersion = new ActionItem("Show Version");

            showVersion.Selected += showVersion_Selected;
            Menu       showDateOrTime = new Menu("Show Date/Time");
            ActionItem showTime       = new ActionItem("Show Time");

            showTime.Selected += showTime_Selected;
            ActionItem showDate = new ActionItem("Show Date");

            showDate.Selected += showDate_Selected;
            m_MainMenu.AddItemToListMenu(versionAndCapitals);
            m_MainMenu.AddItemToListMenu(showDateOrTime);
            versionAndCapitals.AddItemToListMenu(countCaptials);
            versionAndCapitals.AddItemToListMenu(showVersion);
            showDateOrTime.AddItemToListMenu(showTime);
            showDateOrTime.AddItemToListMenu(showDate);
        }
示例#29
0
            public int CompareTo(ActionItem other)
            {
                int r;

                if (other.Boundary == Int32.MaxValue && Boundary == Int32.MaxValue)
                {
                    r = 0;
                }
                else if (other.Boundary == Int32.MaxValue)
                {
                    r = -1;
                }
                else if (Boundary == Int32.MaxValue)
                {
                    r = 1;
                }
                else
                {
                    r = unchecked (Boundary - other.Boundary);
                }

                return(r == 0 ? other.Id - Id : r);
            }             // func CompareTo
        private void createMainMenu()
        {
            Menu       versionAndCapitals = new Menu("Version and Capitals");
            ActionItem countCaptials      = new ActionItem("Count Captials");

            countCaptials.AddActionItemSelectedObserver(new MenuActions.CountCaptialsSelected());
            ActionItem showVersion = new ActionItem("Show Version");

            showVersion.AddActionItemSelectedObserver(new MenuActions.ShowVersionSelected());
            Menu       showDateOrTime = new Menu("Show Date/Time");
            ActionItem showTime       = new ActionItem("Show Time");

            showTime.AddActionItemSelectedObserver(new MenuActions.ShowTimeSelected());
            ActionItem showDate = new ActionItem("Show Date");

            showDate.AddActionItemSelectedObserver(new MenuActions.ShowDateSelected());
            m_MainMenu.AddItemToListMenu(versionAndCapitals);
            m_MainMenu.AddItemToListMenu(showDateOrTime);
            versionAndCapitals.AddItemToListMenu(countCaptials);
            versionAndCapitals.AddItemToListMenu(showVersion);
            showDateOrTime.AddItemToListMenu(showTime);
            showDateOrTime.AddItemToListMenu(showDate);
        }
示例#31
0
 protected override void ProcessChannel(TInnerChannel channel)
 {
     try
     {
         IAsyncResult state = this.BeginTryReceiveItem(channel, this.onReceiveComplete, channel);
         if (state.CompletedSynchronously)
         {
             ActionItem.Schedule(this.asyncHandleReceiveComplete, state);
         }
     }
     catch (Exception exception)
     {
         if (Fx.IsFatal(exception))
         {
             throw;
         }
         if (DiagnosticUtility.ShouldTraceError)
         {
             DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Error);
         }
         channel.Abort();
     }
 }
        public void ProcessTransferred(SequenceRangeCollection ranges, int quotaRemaining)
        {
            bool flag;
            bool flag2;

            this.strategy.ProcessAcknowledgement(ranges, out flag, out flag2);
            if (!flag && !flag2)
            {
                if (this.strategy.ProcessTransferred(ranges, quotaRemaining))
                {
                    ActionItem.Schedule(sendRetries, this);
                }
                else
                {
                    this.OnTransferComplete();
                }
            }
            else
            {
                WsrmFault fault = new InvalidAcknowledgementFault(this.id, ranges);
                this.RaiseFault(fault.CreateException(), fault);
            }
        }
 protected override void OnOpened()
 {
     base.OnOpened();
     if (Thread.CurrentThread.IsThreadPoolThread)
     {
         try
         {
             this.StartReceiving();
         }
         catch (Exception exception)
         {
             if (Fx.IsFatal(exception))
             {
                 throw;
             }
             base.ReliableSession.OnUnknownException(exception);
         }
     }
     else
     {
         ActionItem.Schedule(new Action <object>(ReliableOutputSessionChannelOverDuplex.StartReceiving), this);
     }
 }
示例#34
0
        private void BindCore(ref MessageRpc rpc, bool startOperation)
        {
            SynchronizationContext syncContext = GetSyncContext(rpc.InstanceContext);

            if (syncContext != null)
            {
                IResumeMessageRpc resume = rpc.Pause();
                if (startOperation)
                {
                    syncContext.OperationStarted();
                    syncContext.Post(ThreadAffinityStartCallbackDelegate, resume);
                }
                else
                {
                    syncContext.Post(ThreadAffinityEndCallbackDelegate, resume);
                }
            }
            else if (rpc.SwitchedThreads)
            {
                IResumeMessageRpc resume = rpc.Pause();
                ActionItem.Schedule(ThreadBehavior.CleanThreadCallbackDelegate, resume);
            }
        }
示例#35
0
        private void ActionItem_PropertyChanged(ActionItem item, PropertyChangedEventArgs e)
        {
            var guiItem = this.GetItem(item.Key);

            switch (e.PropertyName)
            {
            case "Caption":
                guiItem.Caption = item.Caption;
                break;

            case "Enabled":
                guiItem.Enabled = item.Enabled;
                break;

            case "Visible":
                SetVisibility(item, guiItem);
                break;

            case "ToolTipText":
                guiItem.ResetSuperTip();
                guiItem.SuperTip = new SuperToolTip();
                guiItem.SuperTip.Items.Add(item.ToolTipText);
                break;

            case "GroupCaption":
                Trace.WriteLine("GroupCaption must not be changed after item is added to header.");
                break;

            case "RootKey":
                Trace.WriteLine("RootKey must not be changed after item is added to header.");
                break;

            case "Key":
            default:
                throw new NotSupportedException(" This Header Control implementation doesn't have an implementation for or has banned modifying that property.");
            }
        }
 public AcceptAsyncResult(SocketConnectionListener listener, AsyncCallback callback, object state) : base(callback, state)
 {
     this.listener                        = listener;
     this.socketAsyncEventArgs            = listener.TakeSocketAsyncEventArgs();
     this.socketAsyncEventArgs.UserToken  = this;
     this.socketAsyncEventArgs.Completed += acceptAsyncCompleted;
     base.OnCompleting                    = onCompleting;
     if (!Thread.CurrentThread.IsThreadPoolThread)
     {
         if (startAccept == null)
         {
             startAccept = new Action <object>(SocketConnectionListener.AcceptAsyncResult.StartAccept);
         }
         ActionItem.Schedule(startAccept, this);
     }
     else
     {
         bool flag;
         bool flag2 = false;
         try
         {
             flag  = this.StartAccept();
             flag2 = true;
         }
         finally
         {
             if (!flag2)
             {
                 this.ReturnSocketAsyncEventArgs();
             }
         }
         if (flag)
         {
             base.Complete(true);
         }
     }
 }
    public SectionResponseEnum Execute(PackageClass packageClass, ActionItem actionItem)
    {
      if (packageClass.Silent)
        return SectionResponseEnum.Ok;
      try
      {
        if (!packageClass.Silent && File.Exists(MpeInstaller.TransformInRealPath(actionItem.Params[Const_APP].Value)))
        {
          string assemblyFileName = MpeInstaller.TransformInRealPath(actionItem.Params[Const_APP].Value);
          AppDomainSetup setup = new AppDomainSetup();
          setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
          setup.PrivateBinPath = Path.GetDirectoryName(assemblyFileName);
          setup.ApplicationName = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
          setup.ShadowCopyFiles = "true";
          setup.ShadowCopyDirectories = Path.GetDirectoryName(assemblyFileName);
          AppDomain appDomain = AppDomain.CreateDomain("pluginDomain", null, setup);

          PluginLoader remoteExecutor =
            (PluginLoader)
            appDomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location,
                                                  typeof (PluginLoader).ToString());
          remoteExecutor.Load(assemblyFileName);
          remoteExecutor.Dispose();

          AppDomain.Unload(appDomain);
        }
      }
      catch (Exception)
      {
        if (ItemProcessed != null)
          ItemProcessed(this, new InstallEventArgs("Error to configure plugin"));
        return SectionResponseEnum.Ok;
      }
      if (ItemProcessed != null)
        ItemProcessed(this, new InstallEventArgs("Plugin configuration donne"));
      return SectionResponseEnum.Ok;
    }
示例#38
0
        public void ValidateParameters_Static(string planFile)
        {
            // Arrange
            Plan plan = Plan.FromYaml($"{__plansRoot}\\{planFile}");
            Dictionary <string, string> parms = new Dictionary <string, string>
            {
                { "sleep0", "2001" },
                { "sleep1", "2001" },
                { "sleep2", "2001" },
                { "sleep3", "2000" }
            };

            // Act
            plan.Start(parms, true, true);

            // Assert
            string     expected = "DynamicValue [2001] failed validation rule type requirement of [DateTime] for parameter [sleep0].";
            ActionItem action   = plan.ResultPlan.Actions.Single(a => a.Name.Equals("action0", StringComparison.OrdinalIgnoreCase));
            bool       found    = action.Result.Message.Contains(expected);

            Assert.IsTrue(found);

            expected = "DynamicValue [2001] failed validation rule [^([1-9]|[01][0-9][0-9]|200[0-0])$] for parameter [sleep1].";
            action   = plan.ResultPlan.Actions.Single(a => a.Name.Equals("action1", StringComparison.OrdinalIgnoreCase));
            found    = action.Result.Message.Contains(expected);
            Assert.IsTrue(found);

            expected = "DynamicValue [2001] failed validation rule [RestrictToOptions] for parameter [sleep2].";
            action   = plan.ResultPlan.Actions.Single(a => a.Name.Equals("action2", StringComparison.OrdinalIgnoreCase));
            found    = action.Result.Message.Contains(expected);
            Assert.IsTrue(found);

            expected = "EmptyHandler ExitData default value.";
            action   = plan.ResultPlan.Actions.Single(a => a.Name.Equals("action3", StringComparison.OrdinalIgnoreCase));
            found    = action.Result.ExitData.ToString().Contains(expected);
            Assert.IsTrue(found);
        }
 protected override void OnOpened()
 {
     base.OnOpened();
     base.SetConnections();
     if (Thread.CurrentThread.IsThreadPoolThread)
     {
         try
         {
             base.StartReceiving(false);
         }
         catch (Exception exception)
         {
             if (Fx.IsFatal(exception))
             {
                 throw;
             }
             base.ReliableSession.OnUnknownException(exception);
         }
     }
     else
     {
         ActionItem.Schedule(new Action <object>(ClientReliableDuplexSessionChannel.StartReceivingStatic), this);
     }
 }
示例#40
0
        // 向列表中选定的图片执行参数中指定的操作。
        public bool ApplyPhotoAction(ActionItem actionItem)
        {
            bool savedPhoto = false;

            if ((this.Mode == PhotosMode.Thumbnails))
            {
                // 处于缩略图模式时只能旋转图片
                if ((listView.SelectedItems.Count > 0))
                {
                    Cursor.Current = Cursors.WaitCursor;
                    // 旋转选定的图片
                    RotateThumbnails(actionItem);
                    //Global.Progress.Complete(this);
                    savedPhoto     = true;
                    Cursor.Current = Cursors.Default;
                }
            }
            else
            {
                // 将操作项传入PhotoViewer组件以执行内存中工作图片的更新
                photoViewer.ApplyPhotoAction(actionItem);
            }
            return(savedPhoto);
        }
 public ValidationResponse Validate(PackageClass packageClass, ActionItem actionItem)
 {
     if (string.IsNullOrEmpty(actionItem.Params[Const_Loc].Value) && string.IsNullOrEmpty(actionItem.Params[Const_Guid].Value))
     {
         return new ValidationResponse()
                {
                    Valid = false, Message = "No file location and no Id specified"
                }
     }
     ;
     if (!string.IsNullOrEmpty(actionItem.Params[Const_Loc].Value) && !File.Exists(actionItem.Params[Const_Loc].Value))
     {
         return new ValidationResponse()
                {
                    Valid = false, Message = "File not found " + actionItem.Params[Const_Loc].Value
                }
     }
     ;
     if (!string.IsNullOrEmpty(actionItem.Params[Const_Guid].Value) && MpeInstaller.KnownExtensions.Get(actionItem.Params[Const_Guid].Value) == null)
     {
         return new ValidationResponse()
                {
                    Valid = false, Message = "Extension with Id " + actionItem.Params[Const_Loc].Value + " unknown"
                }
     }
     ;
     if (!string.IsNullOrEmpty(actionItem.ConditionGroup) && packageClass.Groups[actionItem.ConditionGroup] == null)
     {
         return new ValidationResponse()
                {
                    Valid = false, Message = actionItem.Name + " condition group not found " + actionItem.ConditionGroup
                }
     }
     ;
     return(new ValidationResponse());
 }
示例#42
0
        public static MainMenu BuildDelegateMenu()
        {
            /// Create ActionItems:
            ActionItemFunctionDelegate showVersionFunction = new TestExamples.ShowVersion().Invoke;
            MenuItem actionItem1 = new ActionItem("Show Version", showVersionFunction);
            ActionItemFunctionDelegate charsCountFunction = new TestExamples.CharsCount().Invoke;
            MenuItem actionItem2 = new ActionItem("Chars Count", charsCountFunction);
            ActionItemFunctionDelegate countSpacesFunction = new TestExamples.CountSpaces().Invoke;
            MenuItem actionItem3 = new ActionItem("Count Spaces", countSpacesFunction);
            ActionItemFunctionDelegate showTimeFunction = new TestExamples.ShowTime().Invoke;
            MenuItem actionItem4 = new ActionItem("Show Time", showTimeFunction);
            ActionItemFunctionDelegate showDateFunction = new TestExamples.ShowDate().Invoke;
            MenuItem actionItem5 = new ActionItem("Show Date", showDateFunction);

            /// Create SubMenus:
            SubMenu subMenu1 = new SubMenu("Actions");

            subMenu1.AddMenuItem(actionItem2);
            subMenu1.AddMenuItem(actionItem3);
            SubMenu subMenu2 = new SubMenu("Version and Actions");

            subMenu2.AddMenuItem(actionItem1);
            subMenu2.AddMenuItem(subMenu1);
            SubMenu subMenu3 = new SubMenu("Show Date/Time");

            subMenu3.AddMenuItem(actionItem4);
            subMenu3.AddMenuItem(actionItem5);

            /// Create MainMenu
            MainMenu mainMenu = new MainMenu();

            mainMenu.AddItemToMainMenu(subMenu2);
            mainMenu.AddItemToMainMenu(subMenu3);

            return(mainMenu);
        }
示例#43
0
        public static MainMenu BuildInterfaceMenu()
        {
            /// Create leaves:
            IAction  showVersionRunnable   = new TestExamples.ShowVersion();
            MenuItem actionItemShowVer     = new ActionItem("Show Version", showVersionRunnable);
            IAction  charsCountRunnable    = new TestExamples.CharsCount();
            MenuItem actionItemCharCount   = new ActionItem("Chars Count", charsCountRunnable);
            IAction  countSpacesRunnable   = new TestExamples.CountSpaces();
            MenuItem actionItemCountSpaces = new ActionItem("Count Spaces", countSpacesRunnable);
            IAction  showTimeRunnable      = new TestExamples.ShowTime();
            MenuItem actionItemShowTime    = new ActionItem("Show Time", showTimeRunnable);
            IAction  showDateRunnable      = new TestExamples.ShowDate();
            MenuItem actionItemShowDate    = new ActionItem("Show Date", showDateRunnable);

            /// Create sub menus:
            SubMenu subMenuActions = new SubMenu("Actions");

            subMenuActions.AddMenuItem(actionItemCharCount);
            subMenuActions.AddMenuItem(actionItemCountSpaces);
            SubMenu subMenuVerAndActions = new SubMenu("Version and Actions");

            subMenuVerAndActions.AddMenuItem(actionItemShowVer);
            subMenuVerAndActions.AddMenuItem(subMenuActions);
            SubMenu subMenuDateAndTime = new SubMenu("Show Date/Time");

            subMenuDateAndTime.AddMenuItem(actionItemShowTime);
            subMenuDateAndTime.AddMenuItem(actionItemShowDate);

            /// Create Main menu
            MainMenu mainMenu = new MainMenu();

            mainMenu.AddItemToMainMenu(subMenuVerAndActions);
            mainMenu.AddItemToMainMenu(subMenuDateAndTime);

            return(mainMenu);
        }
        private static PackageClass GetNewProject()
        {
            PackageClass packageClass = new PackageClass();

            packageClass.Groups.Items.Add(new GroupItem("Default"));
            packageClass.Sections.Add("Welcome Screen");
            packageClass.Sections.Items[0].WizardButtonsEnum = WizardButtonsEnum.NextCancel;
            packageClass.Sections.Add("Install Section");
            var item = new ActionItem("InstallFiles")
            {
                Params =
                    new SectionParamCollection(
                        MpeInstaller.ActionProviders["InstallFiles"].GetDefaultParams())
            };

            packageClass.Sections.Items[1].Actions.Add(item);
            packageClass.Sections.Items[1].WizardButtonsEnum = WizardButtonsEnum.Next;
            packageClass.Sections.Add("Setup Complete");
            packageClass.Sections.Items[2].WizardButtonsEnum = WizardButtonsEnum.Finish;

            packageClass.CreateMPDependency();

            return(packageClass);
        }
 public void Edit(ActionItem actionItem)
 {
     using var cmd   = context.Connection.CreateCommand();
     cmd.CommandText = @"UPDATE `ActionItems` SET `Content` = @Content, `Completed` = @Completed WHERE `Id` = @Id";
     cmd.Parameters.Add(new MySqlParameter
     {
         ParameterName = "@Id",
         DbType        = DbType.String,
         Value         = actionItem.Id.ToString()
     });
     cmd.Parameters.Add(new MySqlParameter
     {
         ParameterName = "@Content",
         DbType        = DbType.String,
         Value         = actionItem.Content
     });
     cmd.Parameters.Add(new MySqlParameter
     {
         ParameterName = "@Completed",
         DbType        = DbType.Byte,
         Value         = actionItem.Completed
     });
     cmd.ExecuteNonQuery();
 }
示例#46
0
        public override bool Enqueue(ItemType item, long sequenceNumber)
        {
            if (sequenceNumber > windowStart)
            {
                items.Add(sequenceNumber, item);
                return(false);
            }

            windowStart++;

            while (items.ContainsKey(windowStart))
            {
                if (Channel.EnqueueWithoutDispatch(item, DequeueCallback))
                {
                    ActionItem.Schedule(OnDispatchCallback, null);
                }

                item = items[windowStart];
                items.Remove(windowStart);
                windowStart++;
            }

            return(Channel.EnqueueWithoutDispatch(item, DequeueCallback));
        }
示例#47
0
        // Handles the interaction made in the GUI And Calls
        // The respective method.In case the item is Food
        // The Feed method is called
        public void HandleInteraction(ActionItem item)
        {
            switch (item.ActionType)
            {
            case ActionItem.Type.Food:
                myGirlfriend.Feed(item);
                break;

            case ActionItem.Type.Love:
                myGirlfriend.Curess(item);
                break;

            case ActionItem.Type.Relaxing:
                myGirlfriend.Relax(item);
                break;

            case ActionItem.Type.Hygiene:
                myGirlfriend.CleanUp(item);
                break;

            default:
                break;
            }
        }
示例#48
0
文件: service.cs 项目: aliisjafri/YMC
        private static ActionItem MapActionItem(IDataReader rdr)
        {
            ActionItem e   = new ActionItem();
            int        ord = 0;

            e.Id           = rdr.GetSafeInt32(ord++);
            e.UserId       = rdr.GetSafeInt32(ord++);
            e.AssignedDate = rdr.GetSafeUtcDateTime(ord++);
            e.DueDate      = rdr.GetSafeUtcDateTime(ord++);
            e.Description  = rdr.GetSafeString(ord++);
            ActionItemType ait = new ActionItemType();

            e.ActionItemType    = ait;
            e.ActionItemType.Id = rdr.GetSafeInt32(ord++);
            e.Name = rdr.GetSafeString(ord++);
            Status ais = new Status();

            e.ActionItemStatus      = ais;
            e.ActionItemStatus.Id   = rdr.GetSafeInt32(ord++);
            e.ActionItemType.Name   = rdr.GetSafeString(ord++);
            e.ActionItemStatus.Name = rdr.GetSafeString(ord++);
            e.IsOverDue             = rdr.GetSafeInt32(ord++);
            return(e);
        }
示例#49
0
        public int ScheduleAt(DateTime time, AnkhAction action)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            if (time.Kind == DateTimeKind.Utc)
                time = time.ToLocalTime();

            lock (_actions)
            {
                while (_actions.ContainsKey(time))
                    time = time.Add(TimeSpan.FromMilliseconds(1));

                ActionItem ai = new ActionItem(unchecked(++_nextActionId), action);

                _actions.Add(time, ai);

                Reschedule();
                return ai.Id;
            }
        }
示例#50
0
		public override bool Equals(ActionItem other)
		{
			return this.Equals(other as AcceptActionItem);
		}
示例#51
0
	public void ReadLoopActionData() {
		if (loopActions == null) {
			loopActionNames = null;
			return;
		}		
		
		List<ActionItem> list = new List<ActionItem>();
		
		ActionItem item = new ActionItem();
		item.index = 0;
		item.caption = "(None)";
		list.Add(item);
		
		if (loopActions != null) {
			XmlReader reader = XmlReader.Create(new StringReader(loopActions.text));
	
			while (reader.Read())
		    {
				// Only detect start elements.
				if (reader.IsStartElement())
				{
					switch (reader.Name) {
					case "Item":
						if (item != null && item.index > 0) {
							list.Add(item);
						}
						item = new ActionItem();
						break;
						
					case "index":
						if (reader.Read() && reader.NodeType == XmlNodeType.Text) {
							item.index = int.Parse(reader.Value);
						}
						break;
	
					case "category":
						if (reader.Read() && reader.NodeType == XmlNodeType.Text) {
							item.category = reader.Value;
						}
						break;
	
					case "filename":
						if (reader.Read() && reader.NodeType == XmlNodeType.Text) {
							item.filename = reader.Value;
						}
						break;
	
					case "caption":
						if (reader.Read() && reader.NodeType == XmlNodeType.Text) {
							item.caption = reader.Value;
						}
						break;
					}
			    }
			}
			
			if (item != null && item.index > 0)
				list.Add(item);
		}
		
		loopActionNames = new string[list.Count];
		loopActionIds = new int[list.Count];
		
		for (int i = 0; i < list.Count; i++) {
			item = list[i];
			
			if (i == 0)
				loopActionNames[i] = item.caption;
			else {
				
				
				loopActionNames[i] = string.Format("{0}/{1}. {2} ", item.category, item.index, item.filename);
				
				
				char[] temp = item.caption.ToCharArray();
				int length = 40;
				if( item.caption.Length < length )
					length = item.caption.Length;
					
				
				for(int count=0; count < length ;count++ ) {
					loopActionNames[i] += temp[count];
				}
				//loopActionNames[i] = string.Format("{0}/{1}. {2} {3}", item.category, item.index, item.filename, item.caption);
			}
			loopActionIds[i] = item.index;
		}
	}	
示例#52
0
 public int ItemsCount(PackageClass packageClass, ActionItem actionItem)
 {
   return 1;
 }
示例#53
0
        public void DefineSettings()
        {
            StringResources stx = new StringResources( "Settings" );

            string CurrentLang = Properties.LANGUAGE;
            SettingsSection LangSection = new SettingsSection()
            {
                Title = stx.Text( "Language" )
                , Data = new ActiveItem[]
                {
                    new ActionItem(
                        stx.Text( "Language_E")
                        , CurrentLang == "en-US"
                            ? stx.Text( "Desc_Language_C" )
                            : stx.Text( "Desc_Language_AE" )
                        , "en-US"
                    )
                    , new ActionItem(
                        stx.Text( "Language_T")
                        , CurrentLang == "zh-TW"
                            ? stx.Text( "Desc_Language_C" )
                            : stx.Text( "Desc_Language_AT" )
                        , "zh-TW"
                    )
                    , new ActionItem(
                        stx.Text( "Language_S")
                        , CurrentLang == "zh-CN"
                            ? stx.Text( "Desc_Language_C" )
                            : stx.Text( "Desc_Language_AS" )
                        , "zh-CN"
                    )
                    , new ActionItem(
                        stx.Text( "Language_J")
                        , CurrentLang == "ja"
                            ? stx.Text( "Desc_Language_C" )
                            : stx.Text( "Desc_Language_AJ" )
                        , "ja"
                    )
                }
                , ItemAction = ChangeLanguage
                , IsEnabled = true
            };

            if ( MainStage.Instance.IsPhone )
            {
                if ( CurrentLang != "en-US" ) LangSection.Data.ElementAt( 0 ).Desc = "Mobile user may not be able change the language here, please visit the wiki for help";
                if ( CurrentLang != "zh-TW" ) LangSection.Data.ElementAt( 1 ).Desc = "\u624B\u6A5F\u7528\u6236\u53EF\u80FD\u7121\u6CD5\u8B8A\u66F4\u8A9E\u8A00\uFF0C\u8A73\u60C5\u8ACB\u53C3\u770B\u5E6B\u52A9";
                if ( CurrentLang != "zh-CN" ) LangSection.Data.ElementAt( 2 ).Desc = "\u624B\u673A\u7528\u6237\u53EF\u80FD\u65E0\u6CD5\u53D8\u66F4\u8BED\u8A00\uFF0C\u8BE6\u60C5\u8BF7\u53C2\u770B\u5E2E\u52A9";
                if ( CurrentLang != "ja" ) LangSection.Data.ElementAt( 3 ).Desc = "\u643A\u5E2F\u96FB\u8A71\u30E6\u30FC\u30B6\u30FC\u306F\u3001\u8A00\u8A9E\u3092\u5909\u66F4\u3067\u304D\u306A\u3044\u5834\u5408\u304C\u3042\u308A\u307E\u3059\u3002\u8A73\u7D30\u306B\u3064\u3044\u3066\u306F\u3001\u30D8\u30EB\u30D7\u3092\u53C2\u7167\u3057\u3066\u304F\u3060\u3055\u3044\u3002";
            }

            MainView.ItemsSource = new SettingsSection[]
            {
                new SettingsSection()
                {
                    Title = stx.Text( "Storage" )
                    , Data = new ActiveItem[]
                    {
                        new ActionItem( stx.Text( "Data_Cache"), stx.Text( "Desc_Data_Cache" ), typeof( Data.Cache ) )
                        , new ActionItem( stx.Text( "Data_Illustration"), stx.Text( "Desc_Data_Illustration" ), typeof( Data.Illustration ) )
                        , new ActionItem( stx.Text( "Data_Preload"), stx.Text( "Desc_Data_Preload" ), typeof( Data.Preload ) )
                        , new ActionItem( stx.Text( "EBWin"), stx.Text( "Desc_EBWin_Short" ), typeof( Data.EBWin ) )
                        , OneDriveButton = new ActionItem( "OneDrive", Properties.ENABLE_ONEDRIVE ? stx.Text( "Enabled" ) : stx.Text( "Disabled" ), false )
                        // , new ActionItem( stx.Text( "Data_Connection"), stx.Text( "Desc_Data_Connection" ), typeof( Data.Cache ) )
                    }
                    , ItemAction = PopupSettings
                    , IsEnabled = true
                }
                , new SettingsSection()
                {
                    Title = stx.Text( "Appearance" )
                    , Data = new ActiveItem[]
                    {
                        new ActionItem( stx.Text( "Appearance_ContentReader"), stx.Text( "Desc_Appearance_ContentReader" ), typeof( Themes.ContentReader ) )
                        , new ActionItem( stx.Text( "Appearance_Theme"), stx.Text( "Desc_Appearance_Backgrounds" ), typeof( Themes.ThemeColors ) )
                        , new ActionItem( stx.Text( "Appearance_Layout"), stx.Text( "Desc_Appearance_Layout" ), typeof( Themes.Layout ) )
                    }
                    , ItemAction = PopupSettings
                    , IsEnabled = true
                }
                , LangSection
                , new SettingsSection()
                {
                    Title = stx.Text( "Advanced" )
                    , Data = new ActiveItem[]
                    {
                        new ActionItem( stx.Text( "Advanced_Server"), stx.Text( "Desc_Advanced_Server" ), typeof( Advanced.ServerSelector ) )
                        , new ActionItem( stx.Text( "Advanced_Misc"), stx.Text( "Desc_Advanced_Misc" ), typeof( Advanced.Misc ) )
#if DEBUG || TESTING 
                        , new ActionItem( stx.Text( "Advanced_Debug"), stx.Text( "Desc_Advanced_Debug" ), typeof( Advanced.Debug ) )
#endif
                    }
                    , ItemAction = PopupSettings
                    , IsEnabled = true
                }
                , new SettingsSection()
                {
                    Title = stx.Text( "Help" )
                    , Data = new ActiveItem[]
                    {
                        new ActionItem( stx.Text( "Help_Wiki"), stx.Text( "Desc_Help_Wiki" ), "https://github.com/tgckpg/wenku10/wiki" )
                        , new ActionItem( stx.Text( "Help_Slack"), stx.Text( "Desc_Help_Slack" ), "https://blog.astropenguin.net/article/view/wenku10-%E7%9A%84%E8%A8%8E%E8%AB%96%E7%B5%84/" )
                        , new ActionItem( stx.Text( "Help_BugFeature"), stx.Text( "Desc_Help_BugFeature" ), "https://bugzilla.astropenguin.net/" )
                    }
                    , ItemAction = HelpAction
                    , IsEnabled = true
                }
            };
        }
 public void NavigateToActionItem(ActionItem actionItem)
 {
     if (actionItem == null) throw new ArgumentNullException("actionItem");
     var navParams = new NavigationParameters { { "ActionItem", actionItem } };
     switch (actionItem.ActionType)
     {
         case ActionItemType.MissingUtilityBill:
             NavService.Navigate("MissingBillPage", navParams);
             break;
         case ActionItemType.PrebillingApproval:
             NavService.Navigate("PrebillingTabbedPage", navParams);
             break;
         case ActionItemType.UtilityAlert:
             NavService.Navigate("UtilityAlertPage", navParams);
             break;
     }
 }
 public HomePageViewModel(INavigationService navigationService, IEventAggregator eventAggregator) : base(navigationService, eventAggregator)
 {
     EventAgg.GetEvent<LoggedInEvent>().Subscribe(HandleLoginEvent);
     ActionItems = new ObservableCollection<ActionItem>();
     Properties = new ObservableCollection<PropertyDetail>();
     PhoneCommand = new DelegateCommand<string>(ExecPhoneCommand);
     EmailCommand = new DelegateCommand<string>(ExecEmailCommand);
     HamburgerCommand = new DelegateCommand(ExecHamburger);
     GroupByCommand = new DelegateCommand(ExecGroupBy);
     ForwardCommand = new DelegateCommand(ExecForward);
     IsLoading = false;
     MultiSelect = false;
     IsActionGrp = true;
     IsNotActionGrp = false;
     IsPrebillingSwiped = false;
     IsUtilityAlertSwiped = false;
     GroupStr = "Type";
     AmEmail = "Loading. . .";
     AmPhone = "Loading. . .";
     AmName = "Loading. . .";
     PsrEmail = "Loading. . .";
     PsrPhone = "Loading. . .";
     PsrName = "Loading. . .";
     SwipedItem = new ActionItem { ActionType = ActionItemType.PrebillingApproval };
     LoadText = "Inverting the flux capacitor. . .";
 }
示例#56
0
    public SectionResponseEnum Execute(PackageClass packageClass, ActionItem actionItem)
    {
      // load extension from zip if provided
      PackageClass embeddedPackage = null;
      if (!string.IsNullOrEmpty(actionItem.Params[Const_Loc].Value))
      {
        embeddedPackage = new PackageClass().ZipProvider.Load(actionItem.Params[Const_Loc].Value);
        if (embeddedPackage == null && string.IsNullOrEmpty(actionItem.Params[Const_Guid].Value))
          return SectionResponseEnum.Ok;
      }

      // check if there is already an installed version with a higher version than the embedded
      PackageClass installedPak = MpeInstaller.InstalledExtensions.Get(embeddedPackage != null ? embeddedPackage.GeneralInfo.Id : actionItem.Params[Const_Guid].Value);
      if (installedPak != null && embeddedPackage != null && installedPak.GeneralInfo.Version.CompareTo(embeddedPackage.GeneralInfo.Version) >= 0)
      {
          return SectionResponseEnum.Ok;
      }

      // download new version
      if (embeddedPackage == null && !string.IsNullOrEmpty(actionItem.Params[Const_Guid].Value) &&
        (installedPak == null ||
        (!string.IsNullOrEmpty(actionItem.Params[Const_Version].Value) && installedPak.GeneralInfo.Version.CompareTo(new Version(actionItem.Params[Const_Version].Value)) >= 0)))
      {
        // we don't want incompatible versions
        MpeInstaller.KnownExtensions.HideByDependencies();
        PackageClass knownPackage = MpeInstaller.KnownExtensions.Get(actionItem.Params[Const_Guid].Value);
        if (knownPackage == null && (DateTime.Now - ApplicationSettings.Instance.LastUpdate).TotalHours > 12)
        {
          // package unknown and last download of update info was over 12 hours ago -> update the list first
          ExtensionUpdateDownloader.UpdateList(false, false, null, null);
          // search for the package again - we don't want incompatible versions
          MpeInstaller.KnownExtensions.HideByDependencies();
          knownPackage = MpeInstaller.KnownExtensions.Get(actionItem.Params[Const_Guid].Value);
        }
        if (knownPackage != null)
        {
          // make sure the package has at least the asked version
          if (knownPackage.GeneralInfo.Version.CompareTo(new Version(actionItem.Params[Const_Version].Value)) >= 0)
          {
            // download extension package
            string newPackageLoacation = ExtensionUpdateDownloader.GetPackageLocation(knownPackage, null, null);
            if (File.Exists(newPackageLoacation))
              embeddedPackage = new PackageClass().ZipProvider.Load(newPackageLoacation);
          }
        }
      }

      if (embeddedPackage == null) // no package was embedded or downloaded
        return SectionResponseEnum.Ok;

      if (ItemProcessed != null)
        ItemProcessed(this, new InstallEventArgs("Install extension " + embeddedPackage.GeneralInfo.Name));

      if (installedPak != null)
      {
        // uninstall previous version, if the new package has the setting to force uninstall of previous version on update
        if (embeddedPackage.GeneralInfo.Params[ParamNamesConst.FORCE_TO_UNINSTALL_ON_UPDATE].GetValueAsBool())
        {
          installedPak.Silent = true;
          installedPak.UnInstallInfo = new UnInstallInfoCollection(installedPak);
          installedPak.UnInstallInfo = installedPak.UnInstallInfo.Load();
          if (installedPak.UnInstallInfo == null)
            installedPak.UnInstallInfo = new UnInstallInfoCollection();
          installedPak.UnInstall();
          embeddedPackage.CopyGroupCheck(installedPak);
          installedPak = null;
        }
      }

      embeddedPackage.Silent = actionItem.Params[Const_Silent].GetValueAsBool();
      if (embeddedPackage.StartInstallWizard())
      {
        if (installedPak != null)
        {
          MpeCore.MpeInstaller.InstalledExtensions.Remove(installedPak);
          MpeCore.MpeInstaller.Save();
        }
      }
      return SectionResponseEnum.Ok;
    }
示例#57
0
 public int ItemsCount(PackageClass packageClass, ActionItem actionItem)
 {
   return packageClass.GetInstallableFileCount();
 }
示例#58
0
 public ValidationResponse Validate(PackageClass packageClass, ActionItem actionItem)
 {
   if (string.IsNullOrEmpty(actionItem.Params[Const_Loc].Value) && string.IsNullOrEmpty(actionItem.Params[Const_Guid].Value))
     return new ValidationResponse() 
       { Valid = false, Message = "No file location and no Id specified" };
   if (!string.IsNullOrEmpty(actionItem.Params[Const_Loc].Value) && !File.Exists(actionItem.Params[Const_Loc].Value))
     return new ValidationResponse()
       { Valid = false, Message = "File not found " + actionItem.Params[Const_Loc].Value};
   if (!string.IsNullOrEmpty(actionItem.Params[Const_Guid].Value) && MpeInstaller.KnownExtensions.Get(actionItem.Params[Const_Guid].Value) == null)
     return new ValidationResponse() 
       { Valid = false, Message = "Extension with Id " + actionItem.Params[Const_Loc].Value + " unknown" };
   if (!string.IsNullOrEmpty(actionItem.ConditionGroup) && packageClass.Groups[actionItem.ConditionGroup] == null)
     return new ValidationResponse()
       { Valid = false,  Message = actionItem.Name + " condition group not found " + actionItem.ConditionGroup };
   return new ValidationResponse();
 }
示例#59
0
 public static bool Can(ActionItem action)
 {
     if (Entity == null || AllowedActions == null) return false;
     return AllowedActions.Contains(action);
 }
		/// <summary>
		/// Parses the action items from the parse table.
		/// </summary>
		/// <param name="listTerm">A list of action item terms.</param>
		/// <param name="labels">The labels in the parse table.</param>
		/// <returns>The parsed action items.</returns>
		/// <example>
		/// The list term might look like this:
		/// <code>
		/// [shift(22),reduce(0,280,0,[follow-restriction([char-class([42,47])])])]
		/// </code>
		/// </example>
		private IEnumerable<ActionItem> ParseActionItems(IListTerm listTerm, IReadOnlyList<Label> labels)
		{
			#region Contract
			Contract.Requires<ArgumentNullException>(listTerm != null);
			Contract.Requires<ArgumentNullException>(labels != null);
			Contract.Ensures(Contract.Result<IEnumerable<ActionItem>>() != null);
			#endregion

			var result = new ActionItem[listTerm.Count];
			int index = 0;
			foreach (var term in listTerm.SubTerms)
			{
				ActionItem actionItem;
				if (term.IsCons("accept", 0))
					actionItem = ParseAccept((IConsTerm)term);
				else if (term.IsCons("shift", 1))
					actionItem = ParseShift((IConsTerm)term);
				else if (term.IsCons("reduce", 3))
					actionItem = ParseReduce((IConsTerm)term, labels);
				else if (term.IsCons("reduce", 4))
					actionItem = ParseReduce((IConsTerm)term, labels);
				else
					throw new InvalidParseTableException("Unrecognized term: " + term);

				result[index++] = actionItem;
			}

			return result;
		}