示例#1
0
        /// <summary>
        /// Loads all required resources.
        /// </summary>
        private void Initialise()
        {
#if DEBUG
            Log.Initialise();
#else
            if (ConfigManager.Config.CreateLogFile)
            {
                Log.Initialise();
            }
#endif
            // Load compiled-in resources.
            EmbeddedResources.Load();

            Log.Send("------------------------------");
            Log.Send($"Starting pass-winmenu {Version}");
            Log.Send("------------------------------");

            // Set the security protocol to TLS 1.2 only.
            // We only use this for update checking (Git push over HTTPS is not handled by .NET).
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // Create the notification service first, so it's available if initialisation fails.
            notificationService = Notifications.Create();

            // Now load the configuration options that we'll need
            // to continue initialising the rest of the applications.
            LoadConfigFile();

            // Create the GPG wrapper.
            gpg = new GPG();
            gpg.FindGpgInstallation(ConfigManager.Config.Gpg.GpgPath);
            if (ConfigManager.Config.Gpg.GpgAgent.Config.AllowConfigManagement)
            {
                gpg.UpdateAgentConfig(ConfigManager.Config.Gpg.GpgAgent.Config.Keys);
            }
            // Create the Git wrapper, if enabled.
            InitialiseGit(ConfigManager.Config.Git, ConfigManager.Config.PasswordStore.Location);

            // Initialise the internal password manager.
            passwordManager = new PasswordManager(ConfigManager.Config.PasswordStore.Location, EncryptedFileExtension, gpg);
            passwordManager.PinentryFixEnabled = ConfigManager.Config.Gpg.PinentryFix;

            clipboard     = new ClipboardHelper();
            dialogCreator = new DialogCreator(notificationService, passwordManager, git, gpg);
            InitialiseUpdateChecker();

            actionDispatcher = new ActionDispatcher(notificationService, passwordManager, dialogCreator, clipboard, git, updateChecker);

            notificationService.AddMenuActions(actionDispatcher);

            // Assign our hotkeys.
            hotkeys = new HotkeyManager();
            AssignHotkeys(hotkeys);
        }
        /// <summary>
        /// create the payload for the rest request
        /// </summary>
        /// <param name="paymentInfo"><see cref="PaymentInfo" /></param>
        /// <param name="endpoint"><see cref="WirecardEndpoint" /></param>
        /// <param name="paymentMethod"><see cref="PaymentMethod" /></param>
        /// <returns>System.String.</returns>
        private string CreatePayload(PaymentInfo paymentInfo, WirecardEndpoint endpoint, WirecardPayment paymentMethod)
        {
            // create payload class
            var payload = new Payload
            {
                Payment = new Payment
                {
                    MerchantAccountId = new MerchantAccountId
                    {
                        Value = paymentMethod.MerchantAccountId
                    },
                    RequestId       = paymentInfo.RequestId,
                    TransactionType = (paymentInfo.TransactionType ?? paymentMethod.DefaultTransactionType).ToString().ToLower(),
                    RequestedAmount = paymentInfo.RequestedAmount,
                    AccountHolder   = paymentInfo.AccountHolder,
                    Shipping        = paymentInfo.Shipping,
                    PaymentMethods  = new PaymentMethods
                    {
                        PaymentMethod = new PaymentMethod[] {
                            new PaymentMethod {
                                Name = paymentMethod.Name
                            }
                        }
                    },
                    SuccessRedirectUrl = GetRedirecturl(endpoint.SuccessRedirectUrl),
                    FailRedirectUrl    = GetRedirecturl(endpoint.FailRedirectUrl),
                    CancelRedirectUrl  = GetRedirecturl(endpoint.CancelRedirectUrl),
                    Descriptor         = "test",
                    Notifications      = Notifications.Create(paymentMethod.RequestType, new Notification[] {
                        new Notification {
                            Url = GetRedirecturl(endpoint.IpnDefaultNotificationUrl)
                        },
                        new Notification {
                            Url = GetRedirecturl(endpoint.IpnSuccessNotificationUrl),
                            TransactionState = TransactionState.Success
                        },
                        new Notification {
                            Url = GetRedirecturl(endpoint.IpnFailedNotificationUrl),
                            TransactionState = TransactionState.Failed
                        }
                    }
                                                              )
                }
            };
            // create json string form payload class
            var data = JsonConvert.SerializeObject(payload, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            return(data);
        }
示例#3
0
    void TournamentCallback(List <Rival> currentTournamentPlayers, long currentTournamentEndDate, List <Rival> tournamentPlayers, int tournamentCoins)
    {
        if (ui.current != ui.main)
        {
            return;
        }

        if (currentTournamentPlayers == null || currentTournamentEndDate == 0)
        {
            TournamentShowError();
            return;
        }

        DestroyTournamentSlots();

        if (user.recordTimestamp != currentTournamentEndDate)
        {
            user.ResetRecord();
        }

        user.recordTimestamp = currentTournamentEndDate;
        tournamentEndDate    = currentTournamentEndDate.ToDateTime().ToLocalTime();
        if (tournamentEndDate > DateTime.Now)
        {
            tournamentEndDate += new TimeSpan(0, 0, 30);
        }
        else
        {
            tournamentEndDate = DateTime.Now + new TimeSpan(0, 1, 0);
        }

        Notifications.Create(Notifications.tournamentEnd, tournamentEndDate);

        CreateTournamentSlots(currentTournamentPlayers);

        if (tournamentPlayers != null && tournamentPlayers.Count > 0)
        {
            if (tournamentCoins > 0)
            {
                user.UpdateCoins(tournamentCoins, false);
            }

            ui.PopupShow(ui.tournamentResults);
            ui.tournamentResults.CreateTournamentSlots(tournamentPlayers, tournamentCoins);
        }
    }
        public HttpResponseMessage SetFavorite(string cardId)
        {
            try
            {
                var respList = new List <string>();

                // Check advertId is not NULL
                if (cardId == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_FAVORITE_CARDID_NULL)));
                }

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }

                var currentCard = _context.Cards.AsNoTracking().SingleOrDefault(a => a.Id == cardId);
                if (currentCard == null)
                {
                    respList.Add(cardId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_CARD_NOTFOUND, respList)));
                }

                if (currentCard.UserId == account.UserId)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.CreateBool(RespH.SRV_FAVORITE_WRONG_USER)));
                }
                bool status;
                var  favorite =
                    _context.Favorites.SingleOrDefault(f => f.CardId == cardId && f.UserId == account.UserId);
                if (favorite == null)
                {
                    var favoriteGUID = SequentialGuid.NewGuid().ToString();
                    _context.Favorites.Add(new Favorite
                    {
                        Id     = favoriteGUID,
                        CardId = cardId,
                        UserId = account.UserId
                    });
                    _context.SaveChanges();
                    // Create Notification
                    Notifications.Create(_context, currentCard.UserId, ConstVals.General, RespH.SRV_NOTIF_CARD_FAVORITED,
                                         favoriteGUID, null, null);

                    var user    = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                    var profile = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                    if (user.EmailNotifications)
                    {
                        using (MailSender mailSender = new MailSender())
                        {
                            var bem = new BaseEmailMessage
                            {
                                Code          = RespH.SRV_NOTIF_CARD_FAVORITED,
                                CardId        = currentCard.Id,
                                FromUserName  = profile.FirstName,
                                FromUserEmail = user.Email,
                                ToUserName    = currentCard.User.Profile.FirstName,
                                ToUserEmail   = currentCard.User.Email,
                                UnsubscrCode  = currentCard.User.EmailSubCode
                            };
                            mailSender.Create(_context, bem);
                        }
                    }
                    status = true;
                }
                else
                {
                    var notif = _context.Notifications.SingleOrDefault(n => n.FavoriteId == favorite.Id);
                    if (notif != null)
                    {
                        _context.Notifications.Remove(notif);
                    }
                    _context.SaveChanges();
                    _context.Favorites.Remove(favorite);
                    status = false;
                }
                _context.SaveChanges();
                return(Request.CreateResponse(HttpStatusCode.OK,
                                              RespH.CreateBool(RespH.SRV_DONE, new List <bool> {
                    status
                })));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
示例#5
0
        /// <summary>
        /// Loads all required resources.
        /// </summary>
        private void Initialise()
        {
            // Load compiled-in resources.
            EmbeddedResources.Load();

            Log.Send("------------------------------");
            Log.Send($"Starting pass-winmenu {Version}");
            Log.Send("------------------------------");

            Log.Send($"Enabled security protocols: {ServicePointManager.SecurityProtocol}");

            // Create the notification service first, so it's available if initialisation fails.
            notificationService = Notifications.Create();

            // Initialise the DI Container builder.
            var builder = new ContainerBuilder();

            builder.Register(_ => notificationService)
            .AsImplementedInterfaces()
            .SingleInstance();

            // Now load the configuration options that we'll need
            // to continue initialising the rest of the applications.
            var runtimeConfig = RuntimeConfiguration.Parse(Environment.GetCommandLineArgs());

            LoadConfigFile(runtimeConfig);

            builder.Register(_ => ConfigManager.Config).AsSelf();
            builder.Register(_ => ConfigManager.Config.Gpg).AsSelf();
            builder.Register(_ => ConfigManager.Config.Git).AsSelf();
            builder.Register(_ => ConfigManager.Config.PasswordStore).AsSelf();
            builder.Register(_ => ConfigManager.Config.Application.UpdateChecking).AsSelf();
            builder.Register(_ => ConfigManager.Config.PasswordStore.UsernameDetection).AsSelf();

#if DEBUG
            Log.EnableFileLogging();
#else
            if (ConfigManager.Config.CreateLogFile)
            {
                Log.EnableFileLogging();
            }
#endif

            // Register actions and hotkeys
            builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(ActionDispatcher)))
            .InNamespaceOf <ActionDispatcher>()
            .Except <ActionDispatcher>()
            .AsImplementedInterfaces();
            builder.RegisterType <HotkeyManager>()
            .AsSelf();

            builder.RegisterType <ActionDispatcher>()
            .WithParameter(
                (p, ctx) => p.ParameterType == typeof(Dictionary <HotkeyAction, IAction>),
                (info, context) => context.Resolve <IEnumerable <IAction> >().ToDictionary(a => a.ActionType));

            // Register environment wrappers
            builder.RegisterTypes(
                typeof(FileSystem),
                typeof(SystemEnvironment),
                typeof(Processes),
                typeof(ExecutablePathResolver)
                ).AsImplementedInterfaces();

            // Register GPG types
            builder.RegisterTypes(
                typeof(GpgInstallationFinder),
                typeof(GpgHomedirResolver),
                typeof(GpgAgentConfigReader),
                typeof(GpgAgentConfigUpdater),
                typeof(GpgTransport),
                typeof(GpgAgent),
                typeof(GpgResultVerifier),
                typeof(GPG)
                ).AsImplementedInterfaces()
            .AsSelf();

            // Register GPG installation
            // Single instance, as there is no need to look for the same GPG installation multiple times.
            builder.Register(context => context.Resolve <GpgInstallationFinder>().FindGpgInstallation(ConfigManager.Config.Gpg.GpgPath))
            .SingleInstance();

            builder.RegisterType <DialogCreator>()
            .AsSelf();

            // Register the internal password manager
            builder.Register(context => context.Resolve <IFileSystem>().DirectoryInfo.FromDirectoryName(context.Resolve <PasswordStoreConfig>().Location))
            .Named("PasswordStore", typeof(IDirectoryInfo));

            builder.RegisterType <GpgRecipientFinder>().WithParameter(
                (parameter, context) => true,
                (parameter, context) => context.ResolveNamed <IDirectoryInfo>("PasswordStore"))
            .AsImplementedInterfaces();

            builder.RegisterType <PasswordManager>().WithParameter(
                (parameter, context) => parameter.ParameterType == typeof(IDirectoryInfo),
                (parameter, context) => context.ResolveNamed <IDirectoryInfo>("PasswordStore"))
            .AsImplementedInterfaces()
            .AsSelf();

            builder.RegisterType <PasswordFileParser>().AsSelf();

            // Create the Git wrapper, if enabled.
            // This needs to be a single instance to stop startup warnings being displayed multiple times.
            builder.RegisterType <GitSyncStrategies>().AsSelf();
            builder.Register(CreateSyncService)
            .AsSelf()
            .SingleInstance();

            builder.Register(context => UpdateCheckerFactory.CreateUpdateChecker(context.Resolve <UpdateCheckingConfig>(), context.Resolve <INotificationService>()));
            builder.RegisterType <RemoteUpdateCheckerFactory>().AsSelf();
            builder.Register(context => context.Resolve <RemoteUpdateCheckerFactory>().Build()).AsSelf();

            // Build the container
            container = builder.Build();

            var gpgConfig = container.Resolve <GpgConfig>();
            if (gpgConfig.GpgAgent.Config.AllowConfigManagement)
            {
                container.Resolve <GpgAgentConfigUpdater>().UpdateAgentConfig(gpgConfig.GpgAgent.Config.Keys);
            }

            var actionDispatcher = container.Resolve <ActionDispatcher>();

            notificationService.AddMenuActions(actionDispatcher);

            // Assign our hotkeys.
            AssignHotkeys(actionDispatcher);

            // Start checking for updates
            updateChecker       = container.Resolve <UpdateChecker>();
            remoteUpdateChecker = container.Resolve <Option <RemoteUpdateChecker> >();

            if (container.Resolve <UpdateCheckingConfig>().CheckForUpdates)
            {
                updateChecker.Start();
            }
            remoteUpdateChecker.Apply(c => c.Start());
        }
        public HttpResponseMessage AcceptDeclineReservation(string reservId, string status)
        {
            try
            {
                var respList = new List <string>();

                // Check status is not NULL
                if (status == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_RESERVATION_NULL)));
                }

                // Check Status
                if (status != ConstVals.Accepted && status != ConstVals.Declined)
                {
                    respList.Add(status);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_WRONG_STATUS, respList)));
                }

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                ResponseDTO resp = CheckHelper.IsProfileFill(_context, account.UserId, true);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                //Check Reservation
                var currentReservation = _context.Reservations.SingleOrDefault(r => r.Id == reservId);
                // Check Reservation is not NULL
                if (currentReservation == null)
                {
                    respList.Add(reservId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_NOTFOUND, respList)));
                }

                var card =
                    _context.Cards.Include("Apartment")
                    .AsNoTracking()
                    .SingleOrDefault(a => a.Id == currentReservation.CardId);
                // Check CARD is not NULL
                if (card == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_CARD_NULL)));
                }


                // Check CARD User
                if (card.UserId != account.UserId)
                {
                    respList.Add(card.UserId);
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_CARD_WRONG_USER, respList)));
                }


                string notifCode;
                //Check status
                if (status == ConstVals.Accepted)
                {
                    // Check Available Dates
                    var reservationDates = new TimeRange(currentReservation.DateFrom, currentReservation.DateTo);

                    var unavailableDates = new List <TimeRange>();

                    var cardDates = _context.Dates.Where(x => x.CardId == card.Id);
                    if (cardDates.Any())
                    {
                        foreach (var unDate in cardDates)
                        {
                            unavailableDates.Add(new TimeRange(unDate.DateFrom, unDate.DateTo));
                        }
                        if (unavailableDates.Any(unavailableDate => unavailableDate.IntersectsWith(reservationDates)))
                        {
                            respList.Add(reservationDates.ToString());
                            respList.Add(unavailableDates.ToString());
                            return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                          RespH.Create(RespH.SRV_RESERVATION_UNAVAILABLE_DATE, respList)));
                        }
                    }
                    var currentReservations =
                        _context.Reservations.AsNoTracking().Where(
                            r =>
                            r.CardId == currentReservation.CardId && currentReservation.Status == ConstVals.Accepted);
                    foreach (var currentReserv in currentReservations)
                    {
                        var reservedDates = new TimeRange(currentReserv.DateFrom, currentReserv.DateTo);
                        if (reservedDates.IntersectsWith(reservationDates))
                        {
                            respList.Add(reservationDates.ToString());
                            respList.Add(reservedDates.ToString());
                            return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                          RespH.Create(RespH.SRV_RESERVATION_UNAVAILABLE_DATE, respList)));
                        }
                    }
                    notifCode = RespH.SRV_NOTIF_RESERV_ACCEPTED;
                }
                else
                {
                    notifCode = RespH.SRV_NOTIF_RESERV_DECLINED;
                }

                currentReservation.Status = status;
                _context.MarkAsModified(currentReservation);
                _context.SaveChanges();
                // Create Notification
                Notifications.Create(_context, currentReservation.UserId, ConstVals.General, notifCode, null,
                                     currentReservation.Id, null);

                var fromUser    = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                var fromProfile = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                var toUser      = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == currentReservation.UserId);
                var toProfile   = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == currentReservation.UserId);
                using (MailSender mailSender = new MailSender())
                {
                    var bem = new BaseEmailMessage
                    {
                        Code            = notifCode,
                        CardName        = card.Name,
                        CardType        = DicHelper.GetCardTypeByLang(card.Apartment.Type),
                        CardDescription = card.Description,
                        CardId          = card.Id,
                        DateFrom        = currentReservation.DateFrom,
                        DateTo          = currentReservation.DateTo,
                        FromUserName    = fromProfile.FirstName,
                        FromUserEmail   = fromUser.Email,
                        ToUserName      = toProfile.FirstName,
                        ToUserEmail     = toUser.Email,
                        UnsubscrCode    = toUser.EmailSubCode
                    };
                    mailSender.Create(_context, bem);
                }
                respList.Add(reservId);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_UPDATED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        public HttpResponseMessage MakeReservation(string cardId, string gender, DateTime dateFrom, DateTime dateTo)
        {
            try
            {
                var respList = new List <string>();

                // Check Reservation is not NULL
                if (cardId == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_RESERVATION_NULL)));
                }

                var card = _context.Cards.Include("Apartment").SingleOrDefault(a => a.Id == cardId);
                // Check CARD is not NULL
                if (card == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_CARD_NULL)));
                }

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                // Check Card Owner
                if (card.UserId == account.UserId)
                {
                    respList.Add(account.UserId);
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_SELF, respList)));
                }
                ResponseDTO resp = CheckHelper.IsProfileFill(_context, account.UserId);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }


                // Check CARD User
                //if (CARD.UserId != account.UserId)
                //{
                //    respList.Add(CARD.UserId);
                //    respList.Add(account.UserId);
                //    return this.Request.CreateResponse(HttpStatusCode.BadRequest,
                //        RespH.Create(RespH.SRV_CARD_WRONG_USER, respList));
                //}

                // Check Dates
                if (DateTime.Compare(dateFrom, dateTo) > 0)
                {
                    respList.Add(dateFrom.ToLocalTime().ToString(CultureInfo.InvariantCulture));
                    respList.Add(dateTo.ToLocalTime().ToString(CultureInfo.InvariantCulture));
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_CARD_WRONG_DATE, respList)));
                }

                // Check Reservation already exists
                if (
                    _context.Reservations.AsNoTracking().Any(
                        x =>
                        x.UserId == account.UserId && x.CardId == cardId && x.DateFrom == dateFrom &&
                        x.DateTo == dateTo))
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_EXISTS)));
                }

                // Check Available Dates
                var reservationDates = new TimeRange(dateFrom, dateTo);

                var unavailableDates =
                    _context.Dates.AsNoTracking().Where(x => x.CardId == card.Id)
                    .ToList()
                    .Select(unDate => new TimeRange(unDate.DateFrom, unDate.DateTo))
                    .ToList();

                if (unavailableDates.Any(unavailableDate => unavailableDate.IntersectsWith(reservationDates)))
                {
                    respList.Add(reservationDates.ToString());
                    respList.Add(unavailableDates.ToString());
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_UNAVAILABLE_DATE, respList)));
                }

                var currentReservations =
                    _context.Reservations.AsNoTracking()
                    .Where(r => r.CardId == cardId && r.Status == ConstVals.Accepted);
                foreach (var currentReservation in currentReservations)
                {
                    var reservedDates = new TimeRange(currentReservation.DateFrom, currentReservation.DateTo);
                    if (reservedDates.IntersectsWith(reservationDates))
                    {
                        respList.Add(reservationDates.ToString());
                        respList.Add(reservedDates.ToString());
                        return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                      RespH.Create(RespH.SRV_RESERVATION_UNAVAILABLE_DATE, respList)));
                    }
                }

                var reservationGuid = SequentialGuid.NewGuid().ToString();
                _context.Reservations.Add(new Reservation
                {
                    Id       = reservationGuid,
                    CardId   = cardId,
                    UserId   = account.UserId,
                    Status   = ConstVals.Pending,
                    Gender   = gender,
                    DateFrom = dateFrom,
                    DateTo   = dateTo
                });
                _context.SaveChanges();
                // Create Notification
                Notifications.Create(_context, card.UserId, ConstVals.General, RespH.SRV_NOTIF_RESERV_PENDING, null,
                                     reservationGuid, null);

                var user    = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                var profile = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                if (user.EmailNotifications)
                {
                    using (MailSender mailSender = new MailSender())
                    {
                        var bem = new BaseEmailMessage
                        {
                            Code            = RespH.SRV_NOTIF_RESERV_PENDING,
                            CardName        = card.Name,
                            CardType        = DicHelper.GetCardTypeByLang(card.Apartment.Type),
                            CardDescription = card.Description,
                            DateFrom        = dateFrom,
                            DateTo          = dateTo,
                            ToUserName      = profile.FirstName,
                            ToUserEmail     = user.Email,
                            CardId          = card.Id,
                            UnsubscrCode    = user.EmailSubCode
                        };
                        mailSender.Create(_context, bem);
                    }
                }

                var cardUser    = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == card.UserId);
                var cardProfile = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == card.UserId);
                if (cardUser.EmailNotifications)
                {
                    using (MailSender mailSender = new MailSender())
                    {
                        var bem = new BaseEmailMessage
                        {
                            Code            = RespH.SRV_NOTIF_RESERV_NEW,
                            CardName        = card.Name,
                            CardType        = DicHelper.GetCardTypeByLang(card.Apartment.Type),
                            CardDescription = card.Description,
                            FromUserName    = profile.FirstName,
                            DateFrom        = dateFrom,
                            DateTo          = dateTo,
                            ToUserName      = cardProfile.FirstName,
                            ToUserEmail     = cardUser.Email,
                            CardId          = card.Id,
                            UnsubscrCode    = cardUser.EmailSubCode
                        };
                        mailSender.Create(_context, bem);
                    }
                }
                respList.Add(reservationGuid);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_CREATED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }
        /// <summary>
        /// create the payload for the rest request
        /// </summary>
        /// <param name="paymentInfo"><see cref="PaymentInfo" /></param>
        /// <param name="endpoint"><see cref="WirecardEndpoint" /></param>
        /// <param name="paymentMethod"><see cref="PaymentMethod" /></param>
        /// <returns>System.String.</returns>
        private string CreatePayload(PaymentInfo paymentInfo, WirecardEndpoint endpoint, WirecardPayment paymentMethod)
        {
            PaymentMethods paymentMethods = null;

            if (!endpoint.SelectOnWirecardPage)
            {
                paymentMethods = new PaymentMethods
                {
                    PaymentMethod = new PaymentMethod[] {
                        new PaymentMethod {
                            Name = paymentInfo.TypeName ?? paymentMethod.Name
                        }
                    }
                };
            }

            // create payload class

            var payment = new Payment
            {
                MerchantAccountId = new MerchantAccountId
                {
                    Value = paymentMethod.MerchantAccountId
                },
                RequestId          = paymentInfo.RequestId,
                TransactionType    = (paymentInfo.TransactionType ?? paymentMethod.DefaultTransactionType).ToString().ToLower(),
                RequestedAmount    = paymentInfo.RequestedAmount,
                AccountHolder      = paymentInfo.AccountHolder,
                Shipping           = paymentInfo.Shipping,
                PaymentMethods     = paymentMethods,
                SuccessRedirectUrl = GetRedirecturl(endpoint.SuccessRedirectUrl),
                FailRedirectUrl    = GetRedirecturl(endpoint.FailRedirectUrl),
                CancelRedirectUrl  = GetRedirecturl(endpoint.CancelRedirectUrl),
                Descriptor         = paymentInfo.Descriptor ?? endpoint.Descriptor,
                Notifications      = Notifications.Create(paymentMethod.RequestType, new Notification[] {
                    new Notification {
                        Url = GetRedirecturl(endpoint.IpnDefaultNotificationUrl)
                    },
                    new Notification {
                        Url = GetRedirecturl(endpoint.IpnSuccessNotificationUrl),
                        TransactionState = TransactionState.Success
                    },
                    new Notification {
                        Url = GetRedirecturl(endpoint.IpnFailedNotificationUrl),
                        TransactionState = TransactionState.Failed
                    }
                }
                                                          ),

                Locale = paymentInfo.Locale
            };


            if (!string.IsNullOrEmpty(endpoint.Theme))
            {
                payment.Options = new Models.Options {
                    Theeme = endpoint.Theme
                };
            }

            // create json string form payload class
            var data = JsonConvert.SerializeObject(new Payload {
                Payment = payment
            }, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            return(data);
        }
        public HttpResponseMessage PostReview(string resId, ReviewDTO review)
        {
            try
            {
                var         respList = new List <string>();
                ResponseDTO resp;

                // Check Card is not NULL
                if (review == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_REVIEW_NULL)));
                }

                // Check Reservation is not NULL
                var reservation = _context.Reservations.AsNoTracking().SingleOrDefault(x => x.Id == resId);
                if (reservation == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_RESERVATION_NOTFOUND)));
                }

                // Check Reservation Status is Accepted
                if (reservation.Status != ConstVals.Accepted)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                                  RespH.Create(RespH.SRV_REVIEW_WRONG_RESERV_STATUS)));
                }

                // Check Reservation Dates
                if (reservation.DateTo >= DateTime.Now)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, RespH.Create(RespH.SRV_REVIEW_WRONG_DATE)));
                }

                // Check Review Text is not NULL
                resp = CheckHelper.IsNull(review.Text, "Text", RespH.SRV_REVIEW_REQUIRED);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                // Check Review Rating is not NULL
                //resp = CheckHelper.IsNull(review.Rating, "Rating", RespH.SRV_REVIEW_REQUIRED);
                //if (resp != null) return this.Request.CreateResponse(HttpStatusCode.BadRequest, resp);

                // Check Current User
                var currentUser = User as ServiceUser;
                if (currentUser == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized, RespH.Create(RespH.SRV_UNAUTH)));
                }
                var account = AuthUtils.GetUserAccount(_context, currentUser);
                if (account == null)
                {
                    respList.Add(currentUser.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                }
                resp = CheckHelper.IsProfileFill(_context, account.UserId);
                if (resp != null)
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, resp));
                }

                var newReview = new Review();
                // Set FromUserId
                newReview.FromUserId = account.UserId;

                // Set ToUserId
                if (reservation.UserId == account.UserId)
                {
                    newReview.ToUserId = reservation.Card.UserId;
                }
                if (reservation.Card.UserId == account.UserId)
                {
                    newReview.ToUserId = reservation.UserId;
                }

                // Check Review doesn't already exist
                var currentReview =
                    _context.Reviews.AsNoTracking().SingleOrDefault(
                        r =>
                        r.ReservationId == reservation.Id && r.FromUserId == newReview.FromUserId &&
                        r.ToUserId == newReview.ToUserId);
                if (currentReview != null)
                {
                    respList.Add(currentReview.Id);
                    return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                  RespH.Create(RespH.SRV_REVIEW_EXISTS, respList)));
                }
                var reviewGuid = SequentialGuid.NewGuid().ToString();
                newReview.Id            = reviewGuid;
                newReview.ReservationId = reservation.Id;
                newReview.Text          = review.Text;


                _context.Reviews.Add(newReview);

                string notifCode;
                // Rating Calculation
                if (review.Rating > 0)
                {
                    var profile = _context.Profile.SingleOrDefault(x => x.Id == newReview.ToUserId);
                    if (profile == null)
                    {
                        respList.Add(newReview.ToUserId);
                        return(Request.CreateResponse(HttpStatusCode.Unauthorized,
                                                      RespH.Create(RespH.SRV_USER_NOTFOUND, respList)));
                    }
                    newReview.Rating     = review.Rating;
                    notifCode            = RespH.SRV_NOTIF_REVIEW_RATING_ADDED;
                    profile.RatingCount += 1;
                    profile.Score       += newReview.Rating;
                    profile.Rating       = profile.Score / profile.RatingCount;
                }
                else
                {
                    newReview.Rating = 0;
                    notifCode        = RespH.SRV_NOTIF_REVIEW_ADDED;
                }
                _context.SaveChanges();
                // Create Notification
                Notifications.Create(_context, newReview.ToUserId, ConstVals.General, notifCode, null, null, reviewGuid);
                var fromUser    = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                var fromProfile = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == account.UserId);
                var toUser      = _context.Users.AsNoTracking().SingleOrDefault(x => x.Id == newReview.ToUserId);
                var toProfile   = _context.Profile.AsNoTracking().SingleOrDefault(x => x.Id == newReview.ToUserId);
                if (toUser.EmailNewsletter)
                {
                    using (MailSender mailSender = new MailSender())
                    {
                        var bem = new BaseEmailMessage
                        {
                            Code          = notifCode,
                            FromUserName  = fromProfile.FirstName,
                            FromUserEmail = fromUser.Email,
                            ToUserName    = toProfile.FirstName,
                            ToUserEmail   = toUser.Email,
                            ReviewText    = newReview.Text,
                            ReviewRating  = newReview.Rating,
                            UnsubscrCode  = toUser.EmailSubCode
                        };
                        mailSender.Create(_context, bem);
                    }
                }
                respList.Add(reviewGuid);
                return(Request.CreateResponse(HttpStatusCode.OK, RespH.Create(RespH.SRV_CREATED, respList)));
            }
            catch (Exception ex)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest,
                                              RespH.Create(RespH.SRV_EXCEPTION, new List <string> {
                    ex.InnerException.ToString()
                })));
            }
        }