public void Generate(TemplateInfo templateInfo, IClientContext clientContext, IClientModel clientModel)
 {
     using (var stream = new StreamReader(templateInfo.Open()))
     {
         GenerateForTemplate(templateInfo.Id, stream.ReadToEnd(), clientContext, clientModel);
     }
 }
        protected NewMasterDataCommand(IMessageBroker messageBroker, IClientContext clientContext)
        {
            Text = () => LanguageData.General_New ;

            this.messageBroker = messageBroker;
            this.clientContext = clientContext;
        }
 private async Task EndRequestAsync(IClientContext context)
 {
     for (var i = 0; i < _modules.Length; i++)
     {
         await _modules[i].EndRequest(context);
     }
 }
Example #4
0
 private async Task EndRequestAsync(IClientContext context)
 {
     for (var i = 0; i < _modules.Length; i++)
     {
         await _modules[i].EndRequest(context);
     }
 }
        public NewEmployeeCommand(IMessageBroker messageBroker, IClientContext clientContext)
        {
            Text = () => LanguageData.General_New;

            this.messageBroker = messageBroker;
            this.clientContext = clientContext;
        }
Example #6
0
        private async Task ExecuteConnectModules(ITcpChannel channel, IClientContext context)
        {
            var result = ModuleResult.Continue;

            for (var i = 0; i < _modules.Length; i++)
            {
                var connectMod = _modules[i] as IConnectionEvents;
                if (connectMod == null)
                    continue;

                try
                {
                    result = await connectMod.OnClientConnected(context);
                }
                catch (Exception exception)
                {
                    context.Error = exception;
                    result = ModuleResult.SendResponse;
                }

                if (result != ModuleResult.Continue)
                    break;
            }

            switch (result)
            {
                case ModuleResult.Disconnect:
                    channel.Close();
                    break;
                case ModuleResult.SendResponse:
                    channel.Send(context.ResponseMessage);
                    break;
            }
        }
Example #7
0
        public static void OnCharacterJoined(CharacterJoinedCommand characterJoinedCommand, IClientContext clientContext)
        {
            if (clientContext.Token != null)
                return;

            ((ClientContext)clientContext).Token = characterJoinedCommand.Token;
        }
Example #8
0
        public NewHouseCommand(IClientContext clientContext, IMessageBroker messageBroker)
        {
            Text = () => LanguageData.General_New;

            this.messageBroker = messageBroker;
            this.clientContext = clientContext;
        }
        internal static void Start(IClientContext context)
        {
            //Load Graphics
            Graphics.InitGraphics();

            //Load Sounds
            Audio.Init();
            Audio.PlayMusic(ClientConfiguration.Instance.MenuMusic, 3, 3, true);

            //Init Network
            Networking.Network.InitNetwork(context);
            Fade.FadeIn();

            //Make Json.Net Familiar with Our Object Types
            var id = Guid.NewGuid();

            foreach (var val in Enum.GetValues(typeof(GameObjectType)))
            {
                var type = ((GameObjectType)val);
                if (type != GameObjectType.Event && type != GameObjectType.Time)
                {
                    var lookup = type.GetLookup();
                    var item   = lookup.AddNew(type.GetObjectType(), id);
                    item.Load(item.JsonData);
                    lookup.Delete(item);
                }
            }
        }
        public async Task<ModuleResult> ProcessAsync(IClientContext context)
        {
            //already authenticated
            if (context.ChannelData["Principal"] != null)
            {
                Console.WriteLine("Server: Loading identity");
                Thread.CurrentPrincipal = (IPrincipal) context.ChannelData["Principal"];
                return ModuleResult.Continue;
            }

            // Not authenticated, ignore messages
            var msg = context.RequestMessage as Login;
            if (msg == null)
            {
                Console.WriteLine("Server: Not logged in and not the Login request.");
                context.ResponseMessage = new AuthenticationException("You must run the Login request.");
                return ModuleResult.SendResponse;
            }

            // successful authentication
            if (msg.UserName == "jonas")
            {
                Console.WriteLine("Server: Authenticated successfully.");
                context.ChannelData["Principal"] = new GenericPrincipal(new GenericIdentity("jonas", "manual"),
                    new string[0]);
                context.ResponseMessage = new LoginReply() {Success = true, Account = new Account()};
                return ModuleResult.SendResponse;
            }

            Console.WriteLine("Server: Login failed.");
            context.ResponseMessage = new LoginReply() { Success = false };
            return ModuleResult.SendResponse;
        }
        public async Task<ModuleResult> ProcessAsync(IClientContext context)
        {
            var attributes = context.RequestMessage.GetType().GetCustomAttributes<AuthorizeAttribute>();
            foreach (var attribute in attributes)
            {
                var entityWithRoles = context.RequestMessage as IEntityWithRoles;
                if (entityWithRoles != null)
                {
                    foreach (var role in entityWithRoles.Roles)
                    {
                        if (Thread.CurrentPrincipal.IsInRole(role))
                            continue;

                        context.ResponseMessage =
                            new AuthenticationException(
                                string.Format(
                                    "You are not allowed to invoke '{0}', as you are not part of role '{1}'.",
                                    context.RequestMessage.GetType().Name, role));
                        return ModuleResult.SendResponse;
                    }
                }

                foreach (var role in attribute.Roles)
                {
                    if (Thread.CurrentPrincipal.IsInRole(role))
                        continue;

                    context.ResponseMessage =
                                new AuthorizationException(context.RequestMessage.GetType(), role);
                    return ModuleResult.SendResponse;
                }
            }
            return ModuleResult.Continue;
        }
Example #12
0
        public IFeature WithContext(IClientContext context)
        {
            var fsh = Copy() as FeatureStateBaseHolder;

            fsh.SetContext(context);
            return(fsh);
        }
        protected NewMasterDataCommand(IMessageBroker messageBroker, IClientContext clientContext)
        {
            Text = () => LanguageData.General_New;

            this.messageBroker = messageBroker;
            this.clientContext = clientContext;
        }
Example #14
0
 public ClientForm(IClientContext context)
 {
     InitializeComponent();
     this.context     = context;
     context.Message += Context_Message;
     context.Closed  += Context_Closed;
 }
        public NewHouseCommand(IClientContext clientContext, IMessageBroker messageBroker)
        {
            Text = () => LanguageData.General_New;

            this.messageBroker = messageBroker;
            this.clientContext = clientContext;
        }
        public virtual IMessageLite OnExecute(IClientContext client, RpcRequestHeader requestHeader,
                                              CodedInputStream input, RpcResponseHeader.Builder responseHeader)
        {
            RpcCallContext previous = RpcCallContext.g_current;

            try
            {
                responseHeader.SetMessageId(requestHeader.MessageId);
                requestHeader.CallContext.Client = client;
                RpcCallContext.g_current         = requestHeader.CallContext;

                IMessageLite responseBody = CallMethod(requestHeader, input);

                if (RpcCallContext.g_current != null && !requestHeader.CallContext.Equals(RpcCallContext.g_current))
                {
                    responseHeader.SetCallContext(RpcCallContext.g_current);
                }

                return(responseBody);
            }
            catch (Exception ex)
            {
                OnException(requestHeader, responseHeader, ex);
                return(RpcVoid.DefaultInstance);
            }
            finally
            {
                RpcCallContext.g_current = previous;
            }
        }
        // Token: 0x0600223B RID: 8763 RVA: 0x0007E7A4 File Offset: 0x0007C9A4
        internal IEnumerable <IListItem> GetItems(UserContext userContext, string endPointUrl, string documentLibrary, string location, IndexedPageView requestedData, AttachmentItemsSort sort, out int totalItemCount, DataProviderCallLogEvent logEvent)
        {
            IEnumerable <IListItem> result;

            using (IClientContext clientContext = OneDriveProUtilities.CreateAndConfigureClientContext(userContext.LogonIdentity, endPointUrl))
            {
                totalItemCount = 0;
                IList documentsLibrary             = OneDriveProUtilities.GetDocumentsLibrary(clientContext, documentLibrary);
                OneDriveProItemsPage page          = this.UpdatePageCache(clientContext, userContext, documentsLibrary, documentLibrary, location, requestedData, sort, logEvent);
                CamlQuery            camlDataQuery = this.GetCamlDataQuery(location, requestedData, this.GetListItemCollectionPosition(page), sort);
                IListItemCollection  items         = documentsLibrary.GetItems(camlDataQuery);
                IFolder folder = string.IsNullOrEmpty(location) ? documentsLibrary.RootFolder : clientContext.Web.GetFolderByServerRelativeUrl(location);
                items.Load(clientContext, new Expression <Func <ListItemCollection, object> > [0]);
                folder.Load(clientContext, new Expression <Func <Folder, object> >[]
                {
                    (Folder x) => (object)x.ItemCount
                });
                OneDriveProUtilities.ExecuteQueryWithTraces(userContext, clientContext, logEvent, "GetItems");
                int startIndex = requestedData.Offset % 200;
                int endIndex   = startIndex + requestedData.MaxRows;
                totalItemCount = folder.ItemCount;
                result         = items.ToList <IListItem>().Where((IListItem item, int index) => index >= startIndex && index < endIndex);
            }
            return(result);
        }
        // Token: 0x0600223F RID: 8767 RVA: 0x0007EA34 File Offset: 0x0007CC34
        private void GetListItemChangesSinceToken(IClientContext context, OwaIdentity identity, string listName, string location, out string changeToken, out bool hasChanges, DataProviderCallLogEvent logEvent)
        {
            changeToken = null;
            hasChanges  = false;
            DownloadResult downloadResult = OneDriveProUtilities.SendRestRequest("POST", string.Format("{0}/_vti_bin/client.svc/web/lists/getByTitle('{1}')/GetListItemChangesSinceToken", context.Url, listName), identity, this.GetRequestStream(location, this.ChangeToken), logEvent, "GetListItemChangesSinceToken");

            if (!downloadResult.IsSucceeded)
            {
                OneDriveProItemsPagingMetadata.TraceError(OneDriveProItemsPagingMetadata.LogMetadata.GetListItemChangesSinceToken, downloadResult.Exception);
                hasChanges = true;
                return;
            }
            using (XmlReader xmlReader = XmlReader.Create(downloadResult.ResponseStream))
            {
                while (xmlReader.Read())
                {
                    if (xmlReader.NodeType == XmlNodeType.Element)
                    {
                        if (xmlReader.LocalName == "Changes")
                        {
                            changeToken = xmlReader.GetAttribute("LastChangeToken");
                        }
                        else if (xmlReader.LocalName == "row" && xmlReader.NamespaceURI == "#RowsetSchema")
                        {
                            hasChanges = true;
                            break;
                        }
                    }
                }
            }
        }
        // Token: 0x0600223D RID: 8765 RVA: 0x0007E938 File Offset: 0x0007CB38
        private OneDriveProItemsPage UpdatePageCache(IClientContext clientContext, UserContext userContext, IList list, string listName, string location, IndexedPageView requestedData, AttachmentItemsSort sort, DataProviderCallLogEvent logEvent)
        {
            string changeToken;
            bool   flag;

            this.GetListItemChangesSinceToken(clientContext, userContext.LogonIdentity, listName, location, out changeToken, out flag, logEvent);
            this.ChangeToken = changeToken;
            if (flag)
            {
                this.PageMap.Clear();
            }
            int num = this.ComputeStartPageIndex(requestedData);
            OneDriveProItemsPage nearestPage = this.GetNearestPage(num);
            int num2 = (nearestPage != null) ? nearestPage.PageIndex : -1;

            if (nearestPage == null || num != nearestPage.PageIndex)
            {
                ListItemCollectionPosition listItemCollectionPosition = this.GetListItemCollectionPosition(nearestPage);
                CamlQuery           query = OneDriveProUtilities.CreatePagedCamlPageQuery(location, sort, listItemCollectionPosition, Math.Abs(num - num2) * 200 + 200);
                IListItemCollection items = list.GetItems(query);
                items.Load(clientContext, new Expression <Func <ListItemCollection, object> > [0]);
                OneDriveProUtilities.ExecuteQueryWithTraces(userContext, clientContext, logEvent, "UpdatePageCache");
                this.UpdateCache(items, nearestPage);
            }
            OneDriveProItemsPage result;

            this.PageMap.TryGetValue(num, out result);
            return(result);
        }
Example #20
0
        private async Task <object> AuthenticateUser(IClientContext context, IUserAccount user, string sessionSalt,
                                                     IAuthenticate authenticateRequest)
        {
            object response;

            if (user.IsLocked)
            {
                response = _authenticationMessageFactory.CreateAuthenticationResult(AuthenticateReplyState.Locked, null);
            }
            else
            {
                var serverHash = _passwordHasher.HashPassword(user.HashedPassword, sessionSalt);
                if (_passwordHasher.Compare(serverHash, authenticateRequest.AuthenticationToken))
                {
                    context.ChannelData["Principal"] = await PrincipalFactory.CreatePrincipalAsync(user);

                    var proof = _passwordHasher.HashPassword(user.HashedPassword, authenticateRequest.ClientSalt);
                    response = _authenticationMessageFactory.CreateAuthenticationResult(AuthenticateReplyState.Success,
                                                                                        proof);
                }
                else
                {
                    response =
                        _authenticationMessageFactory.CreateAuthenticationResult(AuthenticateReplyState.IncorrectLogin,
                                                                                 null);
                }
            }
            return(response);
        }
 /// <inheritdoc />
 public void Start(IClientContext context, Action postStartupAction)
 {
     using (var game = new IntersectGame(context, postStartupAction))
     {
         game.Run();
     }
 }
Example #22
0
        internal override void Completed(MediatorContext mediatorContext, IClientContext clientContext, IPeerContext peerContext, OperationCompletedEventArgs oce)
        {
            ClientConst.OperationResult operationResult = oce.Result;

            if (operationResult == ClientConst.OperationResult.Successful)
            {
                Logger.GetLog().Info("接続が完了しました(接続数: " + peerContext.Connections + ")。");

                mediatorContext.State = new ConnectedState();
            }
            else if (operationResult == ClientConst.OperationResult.Restartable)
            {
                Logger.GetLog().Info("IPアドレスが変化しているため、再接続します。");

                peerContext.DisconnectAll();

                Logger.GetLog().Info("ピア接続をすべて切断しました(接続数: " + peerContext.Connections + ")");

                mediatorContext.State = new DisconnectedState();
                mediatorContext.Connect();
            }
            else if (operationResult == ClientConst.OperationResult.Retryable)
            {
                // FIXME: 再試行すること。いまは放置プレイ
                Logger.GetLog().Info("接続に失敗しましたが、再試行可能なエラーです。");

                mediatorContext.State = new DisconnectedState();
            }
            else
            {
                throw new NotSupportedException();
            }
        }
        /// <summary>
        ///     ProcessAsync message
        /// </summary>
        /// <param name="context">Context information</param>
        /// <returns>If message processing can continue</returns>
        /// <remarks>
        ///     <para>
        ///         Check the <see cref="ModuleResult" /> property to see how the message processing have gone so
        ///         far.
        ///     </para>
        /// </remarks>
        public async Task <ModuleResult> ProcessAsync(IClientContext context)
        {
            var principal = context.ChannelData["Principal"] as IPrincipal;

            if (principal != null)
            {
                Thread.CurrentPrincipal = principal;
                return(ModuleResult.Continue);
            }

            var user = context.ChannelData["AuthenticationUser"] as IUserAccount;

            if (user == null)
            {
                var preRequest = context.RequestMessage as IAuthenticationHandshake;
                if (preRequest == null)
                {
                    context.ResponseMessage =
                        new AuthenticationException(
                            "You need to send a message that implements IClientPreAuthentication.");
                    return(ModuleResult.SendResponse);
                }

                user = await _fetcher.FindUserAsync(preRequest.UserName);

                var msg = _authenticationMessageFactory.CreateServerPreAuthentication(user);
                context.ResponseMessage                   = msg;
                context.ChannelData["SessionSalt"]        = msg.SessionSalt;
                context.ChannelData["AuthenticationUser"] = user;
                return(ModuleResult.SendResponse);
            }


            var authenticateRequest = context.RequestMessage as IAuthenticate;

            if (authenticateRequest == null)
            {
                context.ResponseMessage =
                    new AuthenticationException(
                        "You need to send a message that implements IClientAuthentication as the second message to authenticate properly.");
                return(ModuleResult.SendResponse);
            }

            var sessionSalt = context.ChannelData["SessionSalt"] as string;

            if (sessionSalt == null)
            {
                context.ResponseMessage =
                    new AuthenticationException(
                        "Invalid authentication process (salt not found)..");
                return(ModuleResult.SendResponse);
            }


            var response = await AuthenticateUser(context, user, sessionSalt, authenticateRequest);

            context.ResponseMessage = response;
            return(ModuleResult.SendResponse);
        }
Example #24
0
 public static void OnPositionChanged(PositionChangedCommand positionChangedCommand, ILocationControl locationControl, IClientContext clientContext)
 {
     var character = clientContext.Characters.Get(positionChangedCommand.CharacterId);
     if (character == null)
         return;
     character.Data.Position = positionChangedCommand.Position;
     locationControl.Update(character);
 }
Example #25
0
 public CreateStatementCommandHandler(IDoctrinaDbContext context, IMediator mediator, IMapper mapper, IClientContext clientContext)
     : base(mediator, mapper)
 {
     _context       = context;
     _mediator      = mediator;
     _mapper        = mapper;
     _clientContext = clientContext;
 }
Example #26
0
        private string DeterminePercentageKey(IClientContext context, List <string> rsiPercentageAttributes)
        {
            if (rsiPercentageAttributes == null || rsiPercentageAttributes.Count == 0)
            {
                return(context.DefaultPercentageKey);
            }

            return(string.Join("$", rsiPercentageAttributes.Select(pa => context.GetAttr(pa, "<none>"))));
        }
Example #27
0
        public MaintainTimer(IMediatorContext mediatorContext, IClientContext clientContext)
        {
            this.mediatorContext = mediatorContext;
            this.clientContext   = clientContext;

            mediatorContext.Completed += MediatorContext_Completed;

            timer = new Timer(Tick);
        }
Example #28
0
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="uof"></param>
 public SyncService(IUnitOfWork <IClientContext> uof, IConnectivityService connectivityService, Lazy <IErrorService> errorService, SyncConfiguration configuration)
 {
     this.uof = uof;
     this.connectivityService = connectivityService;
     this.errorService        = errorService;
     this.configuration       = configuration;
     this.context             = uof.Context;
     Set = context.Set <T>();
 }
        internal void GenerateForTemplate(string templateId, string template, IClientContext clientContext, IClientModel model)
        {
            var parser         = VeilStaticConfiguration.GetParserInstance("handlebars");
            var helperHandlers = _helperHandlerFactory.Create().ToArray();

            var tree = parser.Parse(templateId, new StringReader(template), typeof(object), _memberLocator, helperHandlers);

            new ClientNodeVisitor(clientContext, model).Visit(tree);
        }
Example #30
0
 public ChartService(IClientContext clientContext, IFlightContext flightContext, IFlightAirportsContext flightAirportsContext, ITicketContext ticketContext, UserManager <ApplicationUser> userContext, ICountryContext countryContext, ICityContext cityContext)
 {
     _clientContext         = clientContext;
     _flightContext         = flightContext;
     _flightAirportsContext = flightAirportsContext;
     _ticketContext         = ticketContext;
     _userContext           = userContext;
     _countryContext        = countryContext;
     _cityContext           = cityContext;
 }
Example #31
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="next"></param>
 /// <param name="loggerFactory"></param>
 public ErrorHandleMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
 {
     _next   = next ?? throw new ArgumentNullException(nameof(next));
     _logger = loggerFactory?.CreateLogger <ErrorHandleMiddleware>() ?? throw new ArgumentNullException(nameof(loggerFactory));
     try
     {
         _clientContext = IocResolver.Resolve <IClientContext>();
     }
     catch { }
 }
Example #32
0
        public ClientForm(IClientContext context)
        {
            InitializeComponent();
            int value = Interlocked.Increment(ref id);

            this.Text        = $"Client {value}";
            this.context     = context;
            context.Message += Context_Message;
            context.Closed  += Context_Closed;
        }
 public TicketService(IShowsRepository showsRepository, ITicketsRepository ticketsRepository, IReservationsRepository reservationsRepository, IClientContext clientContext, ISearchService searchService, IMapper mapper, BookMyTicketDBContext bookMyTicketDBContext)
 {
     _showsRepository        = showsRepository;
     _ticketsRepository      = ticketsRepository;
     _reservationsRepository = reservationsRepository;
     _clientContext          = clientContext;
     _mapper                = mapper;
     _searchService         = searchService;
     _bookMyTicketDBContext = bookMyTicketDBContext;
 }
        internal override void Completed(MediatorContext mediatorContext, IClientContext clientContext, IPeerContext peerContext, OperationCompletedEventArgs oce)
        {
            if (oce.Result == ClientConst.OperationResult.Retryable)
            {
                mediatorContext.State = new ConnectedState();
                return;
            }

            mediatorContext.State = new DisconnectedState();
        }
        // Token: 0x06000213 RID: 531 RVA: 0x000085D0 File Offset: 0x000067D0
        internal static IList GetDocumentsLibrary(IClientContext context, string documentLibraryName)
        {
            string text = new Uri(context.Url).LocalPath;

            if (!text.EndsWith("/"))
            {
                text += "/";
            }
            return(context.Web.GetList(text + documentLibraryName));
        }
        public MainWindow(IBootstrapper bootstrapper, IMessageBroker messageBroker, IClientContext clientContext)
        {
            InitializeComponent();

            this.bootstrapper = bootstrapper;
            this.messageBroker = messageBroker;
            this.clientContext = clientContext;

            this.Loaded += MainWindow_Loaded;
            this.PreviewMouseMove += MainWindow_PreviewMouseMove;
        }
Example #37
0
        public WatchList(IClientContext clientContext)
        {
            if (clientContext == null)
            {
                throw new ArgumentNullException("clientContext");
            }

            this.clientContext = clientContext;
            this.clientContext.RegisterMessageHandler <PersonMessage> (OnPersonMessage);
            this.clientContext.RegisterMessageHandler <BuddyListMessage> (OnBuddyListMessage);
        }
Example #38
0
 public EnsureUserLoggedIn(
     IClientContext userContext,
     IHttpContextAccessor httpContext,
     IUserService userService,
     JwtIssuerOptions jwtIssuerOptions)
 {
     _clientContext    = userContext;
     _httpContext      = httpContext;
     _userService      = userService;
     _jwtIssuerOptions = jwtIssuerOptions;
 }
		public IClientModel Evaluate(IClientContext context, IClientModel model, string name, IDictionary<string, string> parameters)
		{
			// TODO: Use async
			var templateInfo = _templateRepository.GetTemplateAsync(parameters["template"].Trim('"')).Result;
			if (templateInfo == null)
				return model;

			_clientTemplateGenerator.Generate(templateInfo, new PartialClientContextAdapter(templateInfo.Id, context), model);

			return model;
		}
Example #40
0
        public MainWindow(IBootstrapper bootstrapper, IMessageBroker messageBroker, IClientContext clientContext)
        {
            InitializeComponent();


            this.bootstrapper  = bootstrapper;
            this.messageBroker = messageBroker;
            this.clientContext = clientContext;

            this.Loaded           += MainWindow_Loaded;
            this.PreviewMouseMove += MainWindow_PreviewMouseMove;
        }
Example #41
0
        public IClientModel Evaluate(IClientContext context, IClientModel model, string name, IDictionary<string, string> parameters)
        {
            var key = parameters.Keys.First().Trim('"');
            var builder = new StringBuilder();
            using (var writer = new StringWriter(builder))
            {
                _handler.RenderLabel(key, new RenderingContext(writer));
            }

            context.WriteLiteral(builder.ToString());
            return model;
        }
Example #42
0
        public MainWindow()
        {
            InitializeComponent();

            Loaded += MainWindow_Loaded;
            KeyDown += MainWindow_KeyDown;
            App.MainController.PersonSessionChanged += OnPersonSessionChanged;

            SetTitle();

            _menu.Visibility = Visibility.Collapsed;
            _clientContext = new ClientContext(_log);

            _inputController = new InputController(this);
        }
        public EmployeeCostListViewModel(IMessageBroker broker, IClientContext clientContext, IEmployeeCostService costService,
            NewEmployeeCostCommand newCommand, EditEmployeeCostCommand editCommand, DeleteEmployeeCostCommand deleteCommand,
            RefreshCommand refreshCommand)
        {
            this.broker = broker;
            this.costService = costService;
            pageSize = clientContext.PageSize;

            NewCommand = newCommand;
            EditCommand = editCommand;
            DeleteCommand = deleteCommand;
            RefreshCommand = refreshCommand;
            RefreshCommand.MessageName = CommonMessages.RefreshEmployeeCostList;
            NavigationCommands = new List<CommandBase>{NewCommand,  DeleteCommand, RefreshCommand};

            SubscribeMessages();
        }
        public HenDepreciationListViewModel(IMessageBroker broker, IClientContext clientContext,  IHenDepreciationService service,
            NewHenDepreciationCommand newCommand, EditHenDepreciationCommand editCommand, DeleteHenDepreciationCommand deleteCommand, RefreshCommand refreshCommand)
        {
            this.broker = broker;
            this.service =service;
            pageSize = clientContext.PageSize;

            NewCommand = newCommand;
            EditCommand = editCommand;
            DeleteCommand = deleteCommand;
            RefreshCommand = refreshCommand;

            RefreshCommand.MessageName = CommonMessages.RefreshHenDepreciationList;
            NavigationCommands = new List<CommandBase>() { NewCommand, DeleteCommand, RefreshCommand };

            SubscribeMessages();
        }
        private void btnConnect_Click(object sender, EventArgs e)
        {
            Context = ClientFactory.GetContext(
                new SDataClientContextFactory(),
                new SDataContextConfiguration()
                {
                    Servername = Servername,
                    Port = Port,
                    Username = Username,
                    Password = Password,
                    MaxRequestSize = MaxRequestSize
                }
            );

            Cursor.Current = Cursors.WaitCursor;

            PopulateTree();

            Cursor.Current = Cursors.Arrow;
        }
        public UsageListViewModel(IMessageBroker messageBroker, IClientContext clientContext, IConsumableUsageService usageService,
            NewUsageCommand newCommand, EditUsageCommand editCommand, DeleteUsageCommand deleteCommand,
            RefreshCommand refreshCommand)
        {
            this.messageBroker = messageBroker;
            this.usageService = usageService;

            pageSize = clientContext.PageSize;

            NewCommand = newCommand;
            EditCommand = editCommand;
            DeleteCommand = deleteCommand;
            RefreshCommand = refreshCommand;

            RefreshCommand.MessageName = CommonMessages.RefreshUsageList;

            NavigationCommands = new List<CommandBase>(){NewCommand, DeleteCommand, RefreshCommand};

            SubscribeMessages();
        }
Example #47
0
        protected virtual void OnExecute(IClientContext client, Stream input, Stream output)
        {
            RpcRequestHeader requestHeader = RpcRequestHeader.DefaultInstance;
            RpcResponseHeader.Builder responseHeader = RpcResponseHeader.CreateBuilder();
            try
            {
                requestHeader = RpcRequestHeader.ParseDelimitedFrom(input, ExtensionRegistry);
                responseHeader.SetMessageId(requestHeader.MessageId);

                IMessageLite responseBody = OnExecute(client, requestHeader, CodedInputStream.CreateInstance(input),
                                                      responseHeader);

                responseHeader.Build().WriteDelimitedTo(output);
                responseBody.WriteTo(output);
            }
            catch (Exception ex)
            {
                OnException(requestHeader, responseHeader, ex);
                responseHeader.Build().WriteDelimitedTo(output);
            }
        }
Example #48
0
 public static void OnCharacterDetected(CharacterDetectedCommand characterDetectedCommand, ILocationControl locationControl, IClientContext clientContext)
 {
     clientContext.Characters.Add(characterDetectedCommand.Character);
     locationControl.Add(characterDetectedCommand.Character);
 }
 public AdditionalCostServiceClient(IClientContext clientContext)
     : base(clientContext)
 {
 }
 public EmployeeCostServiceClient(IClientContext clientContext)
     : base(clientContext)
 {
 }
 public ConsumableUsageServiceClient(IClientContext context)
     : base(context)
 {
 }
 public async Task EndRequest(IClientContext context)
 {
 }
Example #53
0
        private async Task ExecuteDisconnectModules(IClientContext context)
        {
            for (var i = 0; i < _modules.Length; i++)
            {
                var connectMod = _modules[i] as IConnectionEvents;
                if (connectMod == null)
                    continue;

                try
                {
                    await connectMod.OnClientDisconnect(context);
                }
                catch (Exception exception)
                {
                    if (ModuleFailed != null)
                        ModuleFailed(connectMod, new ThreadExceptionEventArgs(exception));
                }
            }
        }
 public HenHouseServiceClient(IClientContext clientContext)
     : base(clientContext)
 {
 }
        /// <summary>
        ///     Begin request is always called for all modules.
        /// </summary>
        /// <param name="context">Context information</param>
#pragma warning disable 1998
        public async Task BeginRequestAsync(IClientContext context)
#pragma warning restore 1998
        {
        }
 private async Task<object> AuthenticateUser(IClientContext context, IUserAccount user, string sessionSalt,
     IAuthenticate authenticateRequest)
 {
     object response;
     if (user.IsLocked)
         response = _authenticationMessageFactory.CreateAuthenticationResult(AuthenticateReplyState.Locked, null);
     else
     {
         var serverHash = _passwordHasher.HashPassword(user.HashedPassword, sessionSalt);
         if (_passwordHasher.Compare(serverHash, authenticateRequest.AuthenticationToken))
         {
             context.ChannelData["Principal"] = await PrincipalFactory.CreatePrincipalAsync(user);
             var proof = _passwordHasher.HashPassword(user.HashedPassword, authenticateRequest.ClientSalt);
             response = _authenticationMessageFactory.CreateAuthenticationResult(AuthenticateReplyState.Success,
                 proof);
         }
         else
             response =
                 _authenticationMessageFactory.CreateAuthenticationResult(AuthenticateReplyState.IncorrectLogin,
                     null);
     }
     return response;
 }
        /// <summary>
        ///     ProcessAsync message
        /// </summary>
        /// <param name="context">Context information</param>
        /// <returns>If message processing can continue</returns>
        /// <remarks>
        ///     <para>
        ///         Check the <see cref="ModuleResult" /> property to see how the message processing have gone so
        ///         far.
        ///     </para>
        /// </remarks>
        public async Task<ModuleResult> ProcessAsync(IClientContext context)
        {
            var principal = context.ChannelData["Principal"] as IPrincipal;
            if (principal != null)
            {
                Thread.CurrentPrincipal = principal;
                return ModuleResult.Continue;
            }

            var handshake = context.RequestMessage as IAuthenticationHandshake;
            if (handshake != null)
            {
                if (_step != 0)
                {
                    context.ResponseMessage =
                        new AuthenticationException(
                            "Invalid authentication process.");
                    return ModuleResult.SendResponse;
                }

                var user = await _fetcher.FindUserAsync(handshake.UserName);
                var msg = _authenticationMessageFactory.CreateServerPreAuthentication(user);
                context.ResponseMessage = msg;
                context.ChannelData["SessionSalt"] = msg.SessionSalt;
                context.ChannelData["AuthenticationUser"] = user;
                _step = 1;
                return ModuleResult.SendResponse;
            }
            if (_step == 0)
                return ModuleResult.Continue;

            var authenticateRequest = context.RequestMessage as IAuthenticate;
            if (authenticateRequest != null)
            {
                var user = context.ChannelData["AuthenticationUser"] as IUserAccount;
                if (user == null || _step != 1)
                {
                    context.ResponseMessage = new AuthenticationException("Invalid authentication process");
                    _step = 0;
                    return ModuleResult.SendResponse;
                }
                _step = 0;

                var sessionSalt = context.ChannelData["SessionSalt"] as string;
                if (sessionSalt == null)
                {
                    context.ResponseMessage =
                        new AuthenticationException(
                            "Invalid authentication process (salt not found)..");
                    return ModuleResult.SendResponse;
                }


                var response = await AuthenticateUser(context, user, sessionSalt, authenticateRequest);
                context.ResponseMessage = response;
                return ModuleResult.SendResponse;
            }

            return ModuleResult.Continue;
        }
        private static void PerformTests(IClientContext context)
        {
            IAccount Account;
            IList<IAccount> AccountList;

            using (new CustomStopWatch("Test 1"))
            {
                Console.WriteLine("Test 1: Get an SLX entity by ID (Account with Nested Address)");
                Account = context.GetById<IAccount>("AGHEA0002669", "Address");
                Console.WriteLine("Account.AccountName = " + Account.AccountName);
                Console.WriteLine("Account.Address.City = " + Account.Address.City);
            }
            Console.WriteLine("--- Press any key to continue ---");
            Console.ReadKey();
            using (new CustomStopWatch("Test 2"))
            {
                Console.WriteLine("Test 2: Get an entity calculated property");
                Console.WriteLine("Account.Address.FullAddress = " + Account.Address.FullAddress);
            }
            Console.WriteLine("--- Press any key to continue ---");
            Console.ReadKey();
            using (new CustomStopWatch("Test 3"))
            {
                Console.WriteLine("Test 3: Call an entity method");
                Console.WriteLine("Account.Address.FormatFullAddress() returns: " + Account.Address.FormatFullAddress());
            }
            Console.WriteLine("--- Press any key to continue ---");
            Console.ReadKey();
            using (new CustomStopWatch("Test 4"))
            {
                Console.WriteLine("Test 4: Lazy Load entity traversal");
                Console.WriteLine("Account.Contact.Count returns:" +
                    Account.Contacts.Count.ToString());
                foreach (IContact Contact in Account.Contacts)
                {
                    Console.WriteLine("Contact NamePFL & Title = " +
                        Contact.NamePFL + ", " + Contact.Title);
                }
                Console.WriteLine("Account.Opportunities.Count returns:" +
                    Account.Opportunities.Count.ToString());
                foreach (IOpportunity Opportunity in Account.Opportunities)
                {
                    Console.WriteLine("Opportunity Description & SalesPotential = " +
                        Opportunity.Description + ", " + Opportunity.SalesPotential.ToString());
                    Console.WriteLine(" OpportunityProduct Count = " +
                        Opportunity.Products.Count.ToString());
                    foreach (IOpportunityProduct OpportunityProduct in Opportunity.Products)
                    {
                        Console.WriteLine("  Product Name, Quantity & Price = " +
                            OpportunityProduct.Product.Name + ", " +
                            OpportunityProduct.Quantity.ToString() + ", " +
                            OpportunityProduct.ExtendedPrice.ToString());
                    }
                }
            }
            Console.WriteLine("--- Press any key to continue ---");
            Console.ReadKey();
            using (new CustomStopWatch("Test 5"))
            {
                Console.WriteLine("Test 5: LINQ Query for SLX Entities");
                AccountList = context.CreateQuery<IAccount>().Where(x => x.AccountName.StartsWith("Sa")).ToList();
                Console.WriteLine("There are " + AccountList.Count + " Accounts that start with 'Sa':");
                foreach (IAccount LAccount in AccountList)
                {
                    Console.WriteLine("Account Name & Address City = " + LAccount.AccountName + ", " + LAccount.Address.City);
                }
            }
            Console.WriteLine("--- Press any key to continue ---");
            Console.ReadKey();
            using (new CustomStopWatch("Test 6"))
            {
                Console.WriteLine("Test 6: Create New SLX Entities");
                IAccount newAccount = context.CreateNew<IAccount>();
                newAccount.AccountName = "Sage (UK) Limited";
                newAccount.MainPhone = "+44 (0)191 294 3000";
                newAccount.Fax = "+44 (0) 118 927 0615";
                newAccount.WebAddress = "www.sage.co.uk";
                newAccount.Save();
                Console.WriteLine("Account " + newAccount.ToString() + "Created, " +
                    "ID = " + newAccount.Id.ToString());
                // Save creates a Primary Address object automatically
                newAccount.Address.Description = "Mailing";
                newAccount.Address.Address1 = "Sage House";
                newAccount.Address.Address2 = "Wharfdale Road";
                newAccount.Address.City = "Winnersh";
                newAccount.Address.State = "Wokingham";
                newAccount.Address.PostalCode = "RG41 5RD";
                newAccount.Address.Country = "England";
                newAccount.Address.Save();
                newAccount.Save();
                Console.WriteLine("Account Primary Address Created, ID = " + newAccount.Address.Id.ToString());
                // Related Contact
                //IContact Contact = context.CreateNew<IContact>();
                //newAccount.Contacts.Add(Contact);
                //newAccount.Save();
                //Contact.FirstName = "Michael";
                //Contact.LastName = "Wilkinson";
                //Contact.Suffix = "Jr.";
                //Contact.Title = "CRM/SalesLogix Consultant";
                //Contact.WorkPhone = newAccount.MainPhone;
                //Contact.Fax = newAccount.Fax;
                //Contact.Mobile = "+44 (0)777 354 8144";
                //Contact.Save();
                //Console.WriteLine("Contact Created, ID = " + Contact.Id.ToString());
                // Save creates a Primary Address object automatically
                //Contact.Address.Address1 = newAccount.Address.Address1;
                //Contact.Address.Address2 = newAccount.Address.Address2;
                //Contact.Address.Address3 = newAccount.Address.Address3;
                //Contact.Address.Address4 = newAccount.Address.Address4;
                //Contact.Address.City = newAccount.Address.City;
                //Contact.Address.State = newAccount.Address.State;
                //Contact.Address.PostalCode = newAccount.Address.PostalCode;
                //Contact.Address.Country = newAccount.Address.County;
                //Contact.Address.Save();
                //Contact.Save();
                //Console.WriteLine("Contact Address Created, ID = " + Contact.Address.Id.ToString());
                // Related Opportunity
                //IOpportunity Opportunity = context.CreateNew<IOpportunity>();
                //Opportunity.Account = newAccount;
                //Opportunity.Description = "Sage UK Microsoft Programs";
                //Opportunity.CloseProbability = 30;
                //Opportunity.EstimatedClose = DateTime.Now.AddDays(10);
                //Opportunity.Save();
                //Console.WriteLine("Opportunity Created, ID = " + Opportunity.Id.ToString());
                //// Related Opportunity Contact
                //IOpportunityContact OpportunityContact = context.CreateNew<IOpportunityContact>();
                //OpportunityContact.Opportunity = Opportunity;
                //OpportunityContact.Contact = Contact;
                //OpportunityContact.Influence = "Decision Maker";
                //OpportunityContact.Save();
                //// Related Opportunity Products
                //IList<IProduct> ProductList = context.CreateQuery<IProduct>().Where(x => x.Name.StartsWith("MS")).ToList();
                //foreach (IProduct Product in ProductList)
                //{
                //    IOpportunityProduct OpportunityProduct = context.CreateNew<IOpportunityProduct>();
                //    OpportunityProduct.Opportunity = Opportunity;
                //    OpportunityProduct.Product = Product;
                //    OpportunityProduct.Quantity = 2;
                //    OpportunityProduct.Price = Product.Price;
                //    OpportunityProduct.CalculateExtendedPrice();
                //    OpportunityProduct.Save();
                //    Console.WriteLine("Opportunity Product Created, ID = " + OpportunityProduct.Id.ToString());
                //}
                //Opportunity.CalculateSalesPotential();
                //Opportunity.ValidateOpportunity();
                //Opportunity.Save();

            }

            Console.WriteLine("--- Press any key to continue ---");
            Console.ReadKey();
            using (new CustomStopWatch("Test 8"))
            {
                Console.WriteLine("Test 8: Delete SLX Entities");
                AccountList = context.CreateQuery<IAccount>().Where(x => x.AccountName.Equals("Sage (UK) Limited")).ToList();
                foreach (IAccount LAccount in AccountList)
                {
                    LAccount.Delete();
                }
            }
            Console.WriteLine("--- Press any key to continue ---");
            Console.ReadKey();

                //if (account.AccountExtension.Id == null)
                //{
                //    account.AccountExtension.CustomerId = 100000218;
                //    //account.AccountExtension.AccountId = account.Id.ToString();
                //    //account.AccountExtension.Account = account;
                //    account.AccountExtension.Save();
                //}
                //else
                //{
                //    account.AccountExtension.CustomerId++;
                //    account.AccountExtension.Save();
                //    Console.WriteLine("Extensions bereits im System vorhanden: {0}", account.AccountExtension.CustomerId);
                //}

                //account.AccountExtension.Account = account;
                //account.AccountExtension.Save();

                //IAccountExtension extension = account.AccountExtension;

                //if (extension == null)
                //    Console.WriteLine("extension is missing");
                //else
                //    Console.WriteLine(extension.CustomerId);

                //Console.WriteLine(account.AccountName);

                //using (new CustomStopWatch("All Accounts with a"))
                //{
                //    int counter = 0;

                //    foreach (var account in context.CreateQuery<IAccount>().Where(x => x.Id == "AA2EK0013901"))
                //    {
                //        //Console.WriteLine("{0}, {1}", account.AccountName, account.Id);
                //        counter++;
                //    }
                //    Console.WriteLine("Received {0} rows", counter);
                //}

                //IAccount newAccount = context.CreateNew<IAccount>();

                //newAccount.AccountName = "Testkunde 123";
                //newAccount.Save();

                //var thing = context.CreateQuery<IAccount>();

                //foreach (var account in context.CreateQuery<IAccount>().Where(x => x.AccountName.StartsWith("BE Bosworth")))
                //{
                //    var result = account.CanChangeOwner();
                //    Console.WriteLine("CanChangeOwner returns a {0} value", result.ToString());

                //    Console.WriteLine("{0}", account.ShippingAddress.City);

                //    foreach (var contact in account.Contacts)
                //    {

                //        Console.WriteLine("{0}, {1}", contact.Id, contact.FirstName);
                //    }

                //}

                //{
                //    var opp = context.GetById<IOpportunity>("ODEMOA000002");

                //    foreach (IOpportunityCompetitor competitor in opp.GetClosedWonLostOppCompetitors())
                //    {
                //        Console.WriteLine(competitor.Strengths);
                //    }
                //}

                //foreach (var opportunity in context.CreateQuery<IOpportunity>().Where(x => x.Account.AccountName.StartsWith("Abbott")))
                //{
                //    Console.WriteLine("{0}, {1}", opportunity.Id, opportunity.Description);
                //    foreach (var item in collection)
                //    {

                //    } opportunity.ValidateOpportunity();
                //}
        }
        /// <summary>
        ///     Always called for all modules.
        /// </summary>
        /// <param name="context">Context information</param>
        /// <remarks>
        ///     <para>
        ///         Check the <see cref="ModuleResult" /> property to see how the message processing have gone so
        ///         far.
        ///     </para>
        /// </remarks>
#pragma warning disable 1998
        public async Task EndRequest(IClientContext context)
#pragma warning restore 1998
        {
        }
			public PartialClientContextAdapter(string templateId, IClientContext adaptee)
			{
				_adaptee = adaptee;
				this.TemplateId = templateId;
			}