Ejemplo n.º 1
0
        public void Initialise(Grid grid, int size)
        {
            tile_values_ = new Board();
            goal_board_ = new Board();
            game_grid_ = grid;
            moves_ = new List<Move>();
            hf_ = new HelperFunctions();
            blank_pos_ = new Position();

            ChangeGridSize(size);
        }
Ejemplo n.º 2
0
        public bool Run(Board board, Position blank_pos, Board goal_board, ref List<Move> moves, int grid_size, ref int boards_searched, ref int open_list_size, ref long timer, ref long mem_used)
        {
            hf_ = new HelperFunctions();

            if (hf_.CompareBoards(board, goal_board))
                return true; //start board is goal

            size_ = grid_size;

            BFSNode root = new BFSNode(board, blank_pos);
            BFSNode goal = new BFSNode();
            
            HashSet<Board> searched_boards = new HashSet<Board>(new BoardEqualityComparer());
            Queue<BFSNode> search = new Queue<BFSNode>();
            search.Enqueue(root);

            bool goal_reached = false;
            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            while(search.Count > 0 && !goal_reached)// && sw.ElapsedMilliseconds < 10000)
            {
                BFSNode node_to_expand = new BFSNode(search.Dequeue());

                List<BFSNode> children = GetChildren(node_to_expand);

                foreach(BFSNode child in children)
                {
                    if (hf_.CompareBoards(child.board, searched_boards)) continue;
                    else if (child.board.Equals(goal_board)) { timer = sw.ElapsedMilliseconds; sw.Stop(); goal_reached = true; goal = child; }
                    else { search.Enqueue(child); searched_boards.Add(child.board); }
                }
            }

            mem_used = GC.GetTotalMemory(false);
            open_list_size = search.Count;
            boards_searched = searched_boards.Count;

            if (goal_reached)  TraverseTree(ref moves, goal);

            searched_boards.Clear();
            search.Clear();
            GC.Collect();

            return goal_reached;
        }
        public ActionResult VerifyEmailAddress(string GUID)
        {
            var user = userRepository.Users.Where(uid => uid.GUID == GUID).FirstOrDefault();
            if (user != null)
            {
                bool resUser = userRepository.ActiveEmialVerification(user);
                //Session["ChangePassword"] = "******";
                if (resUser)
                {
                    //create a session for the user.
                    var pass = Encryption.DecryptStringAES(user.Password, rand);
                    if (authProvider.Authenticate(user.Email, pass, userRepository))
                    {
                        Session["user"] = userRepository.GetUserByEmailAddress(user.Email);
                        //Session["folderss"] = null;

                        User userObj = (User)Session["user"];
                        var accountObj = accRepository.Accounts.FirstOrDefault(x => x.ID == userObj.AccountID);
                        Session["account"] = accountObj;
                        var folders = CCFolderRepository.CCFolders.Where(guid => guid.AccountGUID == accountObj.AccountGUID).ToList();
                        Session["folderss"] = folders;

                        List<NotificationListViewModel> notificationList = new List<NotificationListViewModel>();
                        HelperFunctions HF = new HelperFunctions();
                        notificationList = HF.generateNotificationList(accountObj);
                        if (notificationList.Count > 0)
                            Session["notifications"] = notificationList;
                        else
                            Session["notifications"] = null;
                    }

                    ViewBag.VerifiedMessageSucess = "You have successfully activated your user account."; ViewBag.VerifiedMessageFail = "";
                }
                else { ViewBag.VerifiedMessageFail = "Failed to activate your account."; ViewBag.VerifiedMessageSucess = ""; }
            }
            else
            {
                ViewBag.VerifiedMessageFail = "Sorry, We couldn't find your account.";
                ViewBag.VerifiedMessageSucess = "";
            }
            return View();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public static void Main(string[] args)
        {
            NLogger.Info("Start MainController With args: {0}", String.Join(", ", args));

            ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); };
            X509Certificate cert = null;

            //
            // Set up the command line argument processing
            //
            var options = new Options();

            if (!Parser.Default.ParseArguments(args, options))
            {
                //NLogger.Fatal("Invalid arguements");
                Environment.Exit(Parser.DefaultExitCodeFail);
            }

            //
            // If the user didn't enter the Oppm arguments check the property file for values
            //
            if (options.OppmHost.IsNullOrEmpty() && Settings.Default.Properties["OppmHost"] != null)
            {
                options.OppmHost = Settings.Default.OppmHost;
            }

            if (options.OppmUser.IsNullOrEmpty() && Settings.Default.Properties["OppmUser"] != null)
            {
                options.OppmUser = Settings.Default.OppmUser;
            }

            if (options.OppmPassword.IsNullOrEmpty() && Settings.Default.Properties["OppmPassword"] != null)
            {
                options.OppmPassword = Settings.Default.OppmPassword;
            }


            if (options.UseCert)
            {
                cert = HelperFunctions.GetDodCert();
            }

            //
            // Exit if we don't have the oppm login values and the user's wants to commit
            //
            if (options.OppmUser.IsNullOrEmpty())
            {
                NLogger.Fatal("A Oppm username is required to commit."); Environment.Exit(-1);
            }

            if (options.OppmPassword.IsNullOrEmpty())
            {
                NLogger.Fatal("A Oppm password is required to commit."); Environment.Exit(-1);
            }

            if (options.OppmHost.IsNullOrEmpty())
            {
                NLogger.Fatal("A Oppm hostname is required to commit."); Environment.Exit(-1);
            }

            //
            // Check to see that the xlsxfilename has a .xlsx extension
            //
            if (!Path.GetExtension(options.XlsxDataFileName).IsEqualTo(".xlsx", true))
            {
                Console.WriteLine(options.GetUsage());
                NLogger.Fatal("{0} is not a valid xlxs filename", Path.GetExtension(options.XlsxDataFileName));
                Environment.Exit(-1);
            }

            //
            // Now let's make sure it exits.
            //
            if (!File.Exists(options.XlsxDataFileName))
            {
                NLogger.Fatal("{0} does not exists", Path.GetExtension(options.XlsxDataFileName));
                Environment.Exit(-1);
            }

            if (options.XlsxMapFileName.IsNullOrEmpty() || options.XlsxMapFileName.IsEqualTo("XlsxDataFileName", true))
            {
                options.XlsxMapFileName = options.XlsxDataFileName;
            }

            //
            // Check to see that the xlsxfilename has a .xlsx extension
            //
            if (!Path.GetExtension(options.XlsxMapFileName).IsEqualTo(".xlsx", true))
            {
                NLogger.Fatal("{0} is not a valid xlxs filename", Path.GetExtension(options.XlsxMapFileName));
                Environment.Exit(-1);
            }

            //
            // Now let's make sure it exits.
            //
            if (!File.Exists(options.XlsxDataFileName))
            {
                NLogger.Fatal("{0} does not exists", Path.GetExtension(options.XlsxMapFileName));
                Environment.Exit(-1);
            }

            //
            // OK it appears we have everything we need to do the import.
            //
            try
            {
                var itemCategoryXlsx = new ItemCategoryXlsx {
                    Certificate = cert
                };
                itemCategoryXlsx.RunImport(options);
            }
            catch (Exception ex)
            {
                NLogger.Error(ex.Message);
            }



            NLogger.Info("Stop MainController");

            Environment.Exit(0);
        }
Ejemplo n.º 5
0
    public void SetLayout(bool random)
    {
        if (random)
        {
            PickRandomLayout(false);
        }
        else
        {
            PickRandomLayout(true);
        }

        Adjustcolliders();
        var c = Character.instance;

        c.transform.DOScale(Vector3.zero, 0.5f).OnComplete(() => {
            switch (currentLayout)
            {
            case ScreenState.Bottom:
                c.transform.DORotate(Vector3.zero, 0.5f, RotateMode.Fast).SetEase(Ease.OutBack, 1.0f, 0.5f);
                break;

            case ScreenState.Right:
                c.transform.DORotate(new Vector3(0.0f, 0.0f, 90.0f), 0.5f, RotateMode.Fast).SetEase(Ease.OutBack, 1.0f, 0.5f);
                break;

            case ScreenState.Top:
                c.transform.DORotate(new Vector3(0.0f, 0.0f, 180.0f), 0.5f, RotateMode.Fast).SetEase(Ease.OutBack, 1.0f, 0.5f);
                break;

            case ScreenState.Left:
                c.transform.DORotate(new Vector3(0.0f, 0.0f, 270.0f), 0.5f, RotateMode.Fast).SetEase(Ease.OutBack, 1.0f, 0.5f);
                break;
            }
            //set the falling speed
            c.SetFallingSpeed(GetCurrentScreen().fallingSpeed);
            foreach (Node n in GetCurrentScreen().nodes)
            {
                n.gameObject.SetActive(true);
            }
            if (HelperFunctions.IsEven(screenIndex))
            {
                foreach (BackgroundQuadrant bq in GameManager.instance.backgroundQuads)
                {
                    bq.portraitView = true;
                    if (bq.transform.localScale.x > 2.0f)
                    {
                        bq.transform.DOScaleX(1.0f, 0.5f).OnComplete(() => {
                            bq.transform.DOScaleY(1.0f, 0.5f);
                        });
                    }
                }
            }
            else
            {
                foreach (BackgroundQuadrant bq in GameManager.instance.backgroundQuads)
                {
                    bq.portraitView = false;
                    //if the y scale is greater than 0.5
                    if (bq.transform.localScale.y > 0.5f)
                    {
                        //transform quadrants
                        bq.transform.DOScaleY(0.3333f, 0.5f).OnComplete(() => {
                            bq.transform.DOScaleX(3.0f, 0.5f);
                        });
                    }
                }
            }
            SequenceManager.instance.AdjustSequenceSpeed(0.0f);
            c.SetScoreTextRotation(GetCurrentScreen().rotation);
            UserInterface.instance.MoveUI(false);
            c.transform.DOMove(GetCurrentScreen().startPoint.position, 0.0f).OnComplete(() => {
                c.Resize();
            });
        });
    }
Ejemplo n.º 6
0
        public virtual Paragraph InsertParagraphAfterSelf(string text, bool trackChanges, Formatting formatting)
        {
            XElement newParagraph = new XElement
                                    (
                XName.Get("p", Document.w.NamespaceName), new XElement(XName.Get("pPr", Document.w.NamespaceName)), HelperFunctions.FormatInput(text, formatting.Xml)
                                    );

            if (trackChanges)
            {
                newParagraph = Paragraph.CreateEdit(EditType.ins, DateTime.Now, newParagraph);
            }

            Xml.AddAfterSelf(newParagraph);
            XElement newlyInserted = Xml.ElementsAfterSelf().First();

            Paragraph p = new Paragraph(Document, newlyInserted, -1);

            return(p);
        }
 public static float TopSpacing()
 {
     //return 200;
     return(HelperFunctions.GetCanvasSize(Screen.safeArea.y));
 }
 public static Task ConnectAsync <TType>(this IConnectable <TType, IPEndPoint> client, string address, int port, TimeSpan timeout)
 {
     return(HelperFunctions.Wrap(address, port, Timeout.In <string, int>(timeout, client.Connect)));
 }
Ejemplo n.º 9
0
 public override string MakeChiSquare()
 {
     ChiSquare = HelperFunctions.MakeChiSquare(RealRho, ElectronDensityArray, null, 0, 0, ParamSize());
     return(ChiSquare.ToString("##.### E-0"));
 }
Ejemplo n.º 10
0
        public ActionResult Index()
        {
            TempData["SelectedMenu"] = "Summary";
            TempData["SelectedSubMenu"] = "";
            TempData["SelectedSubMenuFolder"] = "";
            User userObj = (User)Session["user"];
            Account accountObj = (Account)Session["account"];
            if (userObj != null)
            {
                //if (accountObj.isOverFlow == true)
                //{
                //    return RedirectToAction("BillingOptions", "Admin", new { id = 1 });
                //}

                LimitationsViewModel limitationsObj = new LimitationsViewModel();
                HelperFunctions HF = new HelperFunctions();
                limitationsObj = HF.updateAccountLimitations(accountObj);
                Session["limitations"] = limitationsObj;

                if (userObj.isPasswordChange == false)
                {
                    return RedirectToAction("ChangePassword", "Admin");
                }

                if (Session["trialData"] == null)
                {
                    if (accountObj.HasPurchased == false)
                    {
                        if ((((DateTime)(accountObj.TrialEnds) - (DateTime)(DateTime.Now.Date)).TotalDays > (CCGlobalValues.trialPeriod - 2)) | (((DateTime)(accountObj.TrialEnds) - (DateTime)(DateTime.Now.Date)).TotalDays < 2))
                        {
                            TrialDataModel trialObj = new TrialDataModel();
                            trialObj.hasPurchased = accountObj.HasPurchased;
                            trialObj.createdDate = accountObj.CreatedDate;
                            trialObj.trialEndDate = accountObj.TrialEnds;
                            trialObj.showPurchaseOptions = true;
                            Session["trialData"] = trialObj;

                            return RedirectToAction("Index", "Admin");
                        }
                        else if (((DateTime)(accountObj.TrialEnds) - (DateTime)(DateTime.Now.Date)).TotalDays < CCGlobalValues.trialPeriod)
                        {
                            TrialDataModel trialObj = new TrialDataModel();
                            trialObj.hasPurchased = accountObj.HasPurchased;
                            trialObj.createdDate = accountObj.CreatedDate;
                            trialObj.trialEndDate = accountObj.TrialEnds;
                            trialObj.showPurchaseOptions = true;
                            Session["trialData"] = trialObj;
                        }
                    }
                }

                if (accountObj.HasPurchased == true & Session["trialData"] != null)
                {
                    Session["trialData"] = null;
                }

                AdminViewModel ObjModel = new AdminViewModel();
                List<AdminDashboardViewModel> objDash = new List<AdminDashboardViewModel>();
                List<List<ConnectionInforViewModel>> connectionInforByConnction = new List<List<ConnectionInforViewModel>>();

                if (CCFolderRepository.CCFolders != null) { }
                var allFolders = CCFolderRepository.CCFolders.Where(guid => guid.AccountGUID == accountObj.AccountGUID).ToList();

                ObjModel.noOfFolders = CCFolderRepository.CCFolders.Where(F => F.AccountGUID == accountObj.AccountGUID).Count();
                ObjModel.noOfConnections = CCConnectionRepository.CCSubscriptions.Where(C => C.AccountGUID == accountObj.AccountGUID).Count();
                ObjModel.noOfUsers = CCUserRepository.Users.Where(U => U.AccountID == userObj.AccountID).Count();
                //ObjModel.noOfSubscriptionsPurchased = 0;
                ObjModel.noOfTotalItems = CCItemRepository.CCContacts.Where(I => I.AccountGUID == accountObj.AccountGUID & I.isDeleted == false).Count();

                // get saved quantity
                var accDetails = accountRepo.Accounts.Where(aguid => aguid.AccountGUID == accountObj.AccountGUID).FirstOrDefault();
                var planLeval = planRepository.Plans.Where(pid => pid.ID == accDetails.PlanID).FirstOrDefault().PlanLevel;

                    var featureQuality = featureRepository.Features.Where(pid => pid.PlanLevel == planLeval & pid.Type == "Max Items per Folder").FirstOrDefault();
                    var savedQuality = purchRepository.Purchases.Where(fid => fid.FeatureID == featureQuality.ID && fid.AccountGUID == accountObj.AccountGUID).FirstOrDefault();

                    if (savedQuality != null)
                    {
                        var quantitySaved = (savedQuality.Quantity) / (featureQuality.Quantity);
                        ObjModel.NoOfConnection = quantitySaved * 5;
                        ObjModel.noOfSubscriptionsPurchased = quantitySaved;
                        //limitationsObj.availableCconnectionCount = (int)ObjModel.NoOfConnection - (int)ObjModel.noOfConnections;
                        //limitationsObj.maxItemCountPerFolder = featureQuality.Quantity;
                        //if (featureRepository.Features.Where(pid => pid.PlanLevel == planLeval & pid.Type == "Sync Calendar").FirstOrDefault().Quantity == 0)
                        //    limitationsObj.isCalendarSyncAvailable = false;
                        //else
                        //    limitationsObj.isCalendarSyncAvailable = true;
                    }
                    else
                    {
                        ObjModel.NoOfConnection = 0;
                        ObjModel.noOfSubscriptionsPurchased = 0;
                    }

                foreach (var folder in allFolders)
                {
                    AdminDashboardViewModel dash = new AdminDashboardViewModel();
                    List<ConnectionInforViewModel> connectionInforByFolder = new List<ConnectionInforViewModel>();

                    dash.FolderName = folder.Name;
                    dash.FolderID = folder.FolderID;
                    dash.FolderType = folder.Type;
                    dash.NumberOfItems = CCContactRepository.CCContacts.Where(fid => fid.FolderID == folder.FolderID & fid.AccountGUID == accountObj.AccountGUID & fid.isDeleted == false).Count();
                    dash.NumberOfConnections = CCConnectionRepository.CCSubscriptions.Where(fid => fid.FolderID == folder.FolderID & fid.AccountGUID == accountObj.AccountGUID).Count();

                    if (folder.IsPaused == false)
                    {
                        dash.IsPaused = false;
                    }
                    else
                    {
                        dash.IsPaused = true;
                    }
                    objDash.Add(dash);

                    var connections = CCConnectionRepository.CCSubscriptions.Where(fid => fid.FolderID == folder.FolderID & fid.AccountGUID == accountObj.AccountGUID);
                    foreach (var conn in connections)
                    {
                        ConnectionInforViewModel connectionInfor = new ConnectionInforViewModel();
                        connectionInfor.FolderName = folder.Name;
                        connectionInfor.ConnctionFolderName = conn.FolderName;
                        connectionInfor.ConnectionID = conn.ConnectionID;

                        if (DateTime.Parse(conn.LastSyncTime) < DateTime.Parse("1902-01-01 00:00"))
                        {
                            connectionInfor.LastSyncTime = "Never";
                        }
                        else
                        {

                            DateTime timeUtc = DateTime.Parse(conn.LastSyncTime);
                            DateTime cstTime = new DateTime();
                            try
                            {
                                TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById(accountObj.TimeZone.ToString());
                                cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
                                Console.WriteLine("The date and time are {0} {1}.",
                                                  cstTime,
                                                  cstZone.IsDaylightSavingTime(cstTime) ?
                                                          cstZone.DaylightName : cstZone.StandardName);
                            }
                            catch (TimeZoneNotFoundException)
                            {
                                Console.WriteLine("Timezone conversion error");
                            }
                            catch (InvalidTimeZoneException)
                            {
                                Console.WriteLine("conn.LastSyncTime");
                            }

                            connectionInfor.LastSyncTime = cstTime.ToString();

                            //connectionInfor.LastSyncTime = conn.LastSyncTime;
                        }
                        connectionInfor.Type = conn.Type;
                        connectionInfor.FolderID = folder.FolderID;
                        if (conn.IsRunning == null) { connectionInfor.IsRunning = false; }
                        else if (conn.IsRunning == false) { connectionInfor.IsRunning = false; }
                        else if (conn.IsRunning == true) { connectionInfor.IsRunning = true; }
                        if (conn.IsPaused == false)
                        {
                            connectionInfor.IsPaused = false;
                            connectionInfor.rowClass = "notPaused ";
                        }
                        else
                        {
                            connectionInfor.IsPaused = true;
                            connectionInfor.rowClass = "Paused ";
                        }
                        connectionInforByFolder.Add(connectionInfor);

                    }

                    connectionInforByConnction.Add(connectionInforByFolder);

                }
                var assemblyVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                ViewBag.version = assemblyVersion;
                Session["version"] = assemblyVersion;
                ObjModel.FoldersInfor = objDash;
                ObjModel.ConnectionsInfor = connectionInforByConnction;
                return View(ObjModel);
            }
            return View();
        }
Ejemplo n.º 11
0
 /// <summary>
 ///     Gets a list of connected devices
 ///     Intended to be used called via the AHK wrapper...
 ///     ... so it can convert the return value into an AHK array
 /// </summary>
 /// <returns></returns>
 public HelperFunctions.DeviceInfo[] GetDeviceList()
 {
     return(HelperFunctions.GetDeviceList(_deviceContext));
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Creates a new account in the membership system with the specified <paramref name="userName"/>, <paramref name="password"/>,
        /// <paramref name="email"/>, and belonging to the specified <paramref name="roles"/>. If required, it sends a verification
        /// e-mail to the user, sends an e-mail notification to admins, and creates a user album. The account will be disabled when
        /// <paramref name="isSelfRegistration"/> is <c>true</c> and either the system option RequireEmailValidationForSelfRegisteredUser
        /// or RequireApprovalForSelfRegisteredUser is enabled.
        /// </summary>
        /// <param name="userName">Account name of the user. Cannot be null or empty.</param>
        /// <param name="password">The password for the user. Cannot be null or empty.</param>
        /// <param name="email">The email associated with the user. Required when <paramref name="isSelfRegistration"/> is true
        /// and email verification is enabled.</param>
        /// <param name="roles">The names of the roles to assign to the user. The roles must already exist. If null or empty, no
        /// roles are assigned to the user.</param>
        /// <param name="isSelfRegistration">Indicates when the user is creating his or her own account. Set to false when an
        /// administrator creates an account.</param>
        /// <returns>Returns the newly created user.</returns>
        /// <exception cref="MembershipCreateUserException">Thrown when an error occurs during account creation. Check the StatusCode
        /// property for a MembershipCreateStatus value.</exception>
        public static UserEntity CreateUser(string userName, string password, string email, string[] roles, bool isSelfRegistration)
        {
            #region Validation

            if (String.IsNullOrEmpty(userName))
            {
                throw new ArgumentException("userName");
            }

            if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentException("password");
            }

            if ((String.IsNullOrEmpty(email)) && (HelperFunctions.IsValidEmail(userName)))
            {
                // No email address was specified, but the user name happens to be in the form of an email address,
                // so let's set the email property to the user name.
                email = userName;
            }

            #endregion

            // Step 1: Create the user. Any number of exceptions may occur; we'll let the caller deal with them.
            UserEntity user = CreateUser(userName, password, email);

            // Step 2: If this is a self-registered account and email verification is enabled or admin approval is required,
            // disable it. It will be approved when the user validates the email or the admin gives approval.
            if (isSelfRegistration)
            {
                if (Config.GetCore().RequireEmailValidationForSelfRegisteredUser || Config.GetCore().RequireApprovalForSelfRegisteredUser)
                {
                    user.IsApproved = false;
                    UpdateUser(user);
                }
            }

            // Step 3: Add user to roles.
            if ((roles != null) && (roles.Length > 0))
            {
                foreach (string role in roles)
                {
                    RoleController.AddUserToRole(userName, role);
                }
            }

            // Step 4: Notify admins that an account was created.
            NotifyAdminsOfNewlyCreatedAccount(user, isSelfRegistration, false);

            // Step 5: Send user a welcome message or a verification link.
            if (HelperFunctions.IsValidEmail(user.Email))
            {
                NotifyUserOfNewlyCreatedAccount(user);
            }
            else if (isSelfRegistration && Config.GetCore().RequireEmailValidationForSelfRegisteredUser)
            {
                // Invalid email, but we need one to send the email verification. Throw error.
                throw new MembershipCreateUserException(MembershipCreateStatus.InvalidEmail);
            }

            HelperFunctions.PurgeCache();

            return(user);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// In certain cases, the web-based installer creates a text file in the App Data directory that is meant as a signal to this
        /// code that additional setup steps are required. If this file is found, carry out the additional actions. This file is
        /// created in the SetFlagForMembershipConfiguration() method of pages\install.ascx.cs.
        /// </summary>
        internal static void ProcessInstallerFile()
        {
            string filePath = Path.Combine(AppSetting.Instance.PhysicalApplicationPath, Path.Combine(GlobalConstants.AppDataDirectory, GlobalConstants.InstallerFileName));

            if (!File.Exists(filePath))
            {
                return;
            }

            string adminUserName;
            string adminPwd;
            string adminEmail;

            using (StreamReader sw = File.OpenText(filePath))
            {
                adminUserName = sw.ReadLine();
                adminPwd      = sw.ReadLine();
                adminEmail    = sw.ReadLine();
            }

            HelperFunctions.BeginTransaction();

            #region Create the Sys Admin role.

            // Create the Sys Admin role. If it already exists, make sure it has AllowAdministerSite permission.
            string sysAdminRoleName = Resources.GalleryServerPro.Installer_Sys_Admin_Role_Name;
            if (!RoleController.RoleExists(sysAdminRoleName))
            {
                RoleController.CreateRole(sysAdminRoleName);
            }

            IGalleryServerRole role = Factory.LoadGalleryServerRole(sysAdminRoleName);
            if (role == null)
            {
                role = Factory.CreateGalleryServerRoleInstance(sysAdminRoleName, true, true, true, true, true, true, true, true, true, true, false);
                role.RootAlbumIds.Add(Factory.LoadRootAlbumInstance().Id);
                role.Save();
            }
            else
            {
                // Role already exists. Make sure it has Sys Admin permission.
                if (!role.AllowAdministerSite)
                {
                    role.AllowAdministerSite = true;
                    role.Save();
                }
            }

            #endregion

            #region Create the Sys Admin user account.

            // Create the Sys Admin user account. Will throw an exception if the name is already in use.
            try
            {
                CreateUser(adminUserName, adminPwd, adminEmail);
            }
            catch (MembershipCreateUserException ex)
            {
                if (ex.StatusCode == MembershipCreateStatus.DuplicateUserName)
                {
                    // The user already exists. Update the password and email address to our values.
                    UserEntity user = GetUser(adminUserName, true);
                    ChangePassword(user.UserName, GetPassword(user.UserName), adminPwd);
                    user.Email = adminEmail;
                    UpdateUser(user);
                }
            }

            // Add the Sys Admin user to the Sys Admin role.
            if (!RoleController.IsUserInRole(adminUserName, sysAdminRoleName))
            {
                RoleController.AddUserToRole(adminUserName, sysAdminRoleName);
            }

            #endregion

            #region Create sample album and image

            if (!Config.GetCore().MediaObjectPathIsReadOnly)
            {
                DateTime currentTimestamp = DateTime.Now;
                IAlbum   sampleAlbum      = null;
                foreach (IAlbum album in Factory.LoadRootAlbumInstance().GetChildGalleryObjects(GalleryObjectType.Album))
                {
                    if (album.DirectoryName == "Samples")
                    {
                        sampleAlbum = album;
                        break;
                    }
                }
                if (sampleAlbum == null)
                {
                    // Create sample album.
                    sampleAlbum                        = Factory.CreateAlbumInstance();
                    sampleAlbum.Parent                 = Factory.LoadRootAlbumInstance();
                    sampleAlbum.Title                  = "Samples";
                    sampleAlbum.DirectoryName          = "Samples";
                    sampleAlbum.Summary                = "Welcome to Gallery Server Pro!";
                    sampleAlbum.CreatedByUserName      = adminUserName;
                    sampleAlbum.DateAdded              = currentTimestamp;
                    sampleAlbum.LastModifiedByUserName = adminUserName;
                    sampleAlbum.DateLastModified       = currentTimestamp;
                    sampleAlbum.Save();
                }

                // Look for sample image in sample album.
                IGalleryObject sampleImage = null;
                foreach (IGalleryObject image in sampleAlbum.GetChildGalleryObjects(GalleryObjectType.Image))
                {
                    if (image.Original.FileName == Constants.SAMPLE_IMAGE_FILENAME)
                    {
                        sampleImage = image;
                        break;
                    }
                }

                if (sampleImage == null)
                {
                    // Sample image not found. Pull image from assembly, save to disk, and create a media object from it.
                    string sampleDirPath       = Path.Combine(AppSetting.Instance.MediaObjectPhysicalPath, sampleAlbum.DirectoryName);
                    string sampleImageFilename = HelperFunctions.ValidateFileName(sampleDirPath, Constants.SAMPLE_IMAGE_FILENAME);
                    string sampleImageFilepath = Path.Combine(sampleDirPath, sampleImageFilename);

                    System.Reflection.Assembly asm = Assembly.GetExecutingAssembly();
                    using (Stream stream = asm.GetManifestResourceStream(String.Concat("GalleryServerPro.Web.gs.images.", Constants.SAMPLE_IMAGE_FILENAME)))
                    {
                        if (stream != null)
                        {
                            BinaryWriter bw     = new BinaryWriter(File.Create(sampleImageFilepath));
                            byte[]       buffer = new byte[stream.Length];
                            stream.Read(buffer, 0, (int)stream.Length);
                            bw.Write(buffer);
                            bw.Flush();
                            bw.Close();
                        }
                    }

                    if (File.Exists(sampleImageFilepath))
                    {
                        IGalleryObject image = Factory.CreateImageInstance(new FileInfo(sampleImageFilepath), sampleAlbum);
                        image.Title                  = "Margaret, Skyler and Roger Martin (December 2008)";
                        image.CreatedByUserName      = adminUserName;
                        image.DateAdded              = currentTimestamp;
                        image.LastModifiedByUserName = adminUserName;
                        image.DateLastModified       = currentTimestamp;
                        image.Save();
                    }
                }
            }

            #endregion

            HelperFunctions.CommitTransaction();
            HelperFunctions.PurgeCache();

            File.Delete(filePath);
        }
Ejemplo n.º 14
0
        bool GetProjectInfo(string execPath, bool native, out string execCmd, out IEnumerable <string> rccItems)
        {
            execCmd  = "";
            rccItems = null;

            foreach (var project in HelperFunctions.ProjectsInSolution(Vsix.Instance.Dte))
            {
                var vcProject = project.Object as VCProject;
                if (vcProject == null)
                {
                    continue;
                }

                var vcConfigs = vcProject.Configurations as IVCCollection;
                if (vcConfigs == null)
                {
                    continue;
                }
                var activeConfig = project.ConfigurationManager.ActiveConfiguration;
                if (activeConfig == null)
                {
                    continue;
                }
                var activeConfigId = string.Format("{0}|{1}",
                                                   activeConfig.ConfigurationName, activeConfig.PlatformName);
                var vcConfig = vcConfigs.Item(activeConfigId) as VCConfiguration;
                if (vcConfig == null)
                {
                    continue;
                }

                var props = vcProject as IVCBuildPropertyStorage;

                var localDebugCommand = props.GetPropertyValue("LocalDebuggerCommand",
                                                               vcConfig.Name, "UserFile");

                var remoteDebugCommand = props.GetPropertyValue("RemoteDebuggerCommand",
                                                                vcConfig.Name, "UserFile");

                string debugCommand = (native || string.IsNullOrEmpty(remoteDebugCommand))
                    ? localDebugCommand : remoteDebugCommand;

                bool sameFile = string.Equals(execPath, Path.GetFullPath(debugCommand),
                                              StringComparison.InvariantCultureIgnoreCase);

                if (!sameFile)
                {
                    continue;
                }

                OutputWriteLine(string.Format("Debugging project '{0}'...", vcProject.Name));

                var qtProject = QtProject.Create(vcProject);
                if (qtProject == null)
                {
                    OutputWriteLine("DISABLED: Non-Qt project");
                    return(false);
                }

                if (!qtProject.IsQtMsBuildEnabled())
                {
                    OutputWriteLine("DISABLED: Non-Qt/MSBuild project");
                    return(false);
                }

                if (!qtProject.QmlDebug)
                {
                    OutputWriteLine("DISABLED: QML debugging disabled in Qt project settings");
                    return(false);
                }

                var execArgs = props.GetPropertyValue(
                    native ? "LocalDebuggerCommandArguments" : "RemoteDebuggerCommandArguments",
                    vcConfig.Name, "UserFile");
                if (string.IsNullOrEmpty(execArgs))
                {
                    OutputWriteLine("DISABLED: Error reading command line arguments");
                    return(false);
                }

                var cmd = "\"" + execPath + "\" " + execArgs;

                if (!QmlDebugger.CheckCommandLine(execPath, cmd))
                {
                    OutputWriteLine("DISABLED: Error parsing command line arguments");
                    return(false);
                }

                OutputWriteLine("Starting QML debug session...");

                execCmd  = cmd;
                rccItems = ((IVCCollection)vcProject.Files).Cast <VCFile>()
                           .Where(x => x.ItemType == QtRcc.ItemTypeName)
                           .Select(x => x.FullPath);

                return(true);
            }

            OutputWriteLine("DISABLED: Could not identify project being debugged");

            return(false);
        }
Ejemplo n.º 15
0
        private async Task <bool> Run()
        {
            if (AutoRetainerSortSettings.Instance.InventoryOptions.Count == 0)
            {
                LogCritical("You don't have any inventories (or sorting rules for them) added yet! Go check the settings?");
                TreeRoot.Stop("No sort settings.");
                return(false);
            }

            if (!ItemSortStatus.AnyRulesExist())
            {
                LogCritical("You don't have any sorting rules set up... maybe go hit the Auto-Setup button?");
                TreeRoot.Stop("No sort settings.");
                return(false);
            }

            LogCritical($"The journey begins! {Strings.AutoSetup_CacheAdvice}");
            await GeneralFunctions.StopBusy(true, true, false);

            var retData = await HelperFunctions.GetOrderedRetainerArray(true);

            if (retData.Length == 0)
            {
                LogCritical("No retainers. Exiting.");
                TreeRoot.Stop("No retainer data found.");
                return(false);
            }

            foreach (var pair in AutoRetainerSortSettings.Instance.InventoryOptions)
            {
                if (pair.Key < 0)
                {
                    continue;
                }

                if (pair.Key >= retData.Length)
                {
                    LogCritical($"{pair.Value.Name}'s index of {pair.Key.ToString()} doesn't exist in retainer data.");
                    TreeRoot.Stop("Invalid index.");
                    return(false);
                }

                if (!retData[pair.Key].Active)
                {
                    LogCritical($"{pair.Value.Name} isn't an active retainer!");
                    TreeRoot.Stop("Retainer inactive.");
                    return(false);
                }
            }

            ItemSortStatus.ItemSortInfoCache.Clear();

            await ItemFinder.FlashSaddlebags();

            ItemSortStatus.UpdateFromCache(retData);

            if (AutoRetainerSortSettings.Instance.PrintMoves)
            {
                alreadyPrintedUniques.Clear();
                foreach (CachedInventory cachedInventory in ItemSortStatus.GetAllInventories())
                {
                    PrintMoves(cachedInventory.Index);
                }
            }

            while (ItemSortStatus.AnyUnsorted())
            {
                if (ItemSortStatus.FilledAndSortedInventories.Contains(ItemSortStatus.PlayerInventoryIndex))
                {
                    LogCritical("Everything currently in the player's inventory belongs there, but it's full! Can't move items like this. I quit.");
                    break;
                }

                await DepositFromPlayer();
                await RetrieveFromInventories();

                await Coroutine.Sleep(250);

                ItemSortStatus.UpdateFromCache(retData);
                await Coroutine.Sleep(250);
            }

            foreach (CachedInventory cachedInventory in ItemSortStatus.GetAllInventories())
            {
                foreach (ItemSortInfo sortInfo in cachedInventory.ItemCounts.Select(x => ItemSortStatus.GetSortInfo(x.Key)))
                {
                    int[] localIndexCache = sortInfo.MatchingIndexes.ToArray();
                    if (localIndexCache.Length == 0)
                    {
                        continue;
                    }
                    if (sortInfo.SortStatus(cachedInventory.Index) == SortStatus.MoveButUnable)
                    {
                        if (ItemSortStatus.FilledAndSortedInventories.Contains(cachedInventory.Index) || (cachedInventory.FreeSlots == 0 && cachedInventory.AllBelong()))
                        {
                            LogCritical($"We want to move {sortInfo.Name} to {ItemSortStatus.GetByIndex(localIndexCache[0]).Name} but it's full and everything there belongs. Too bad!");
                        }
                        else if (sortInfo.ItemInfo.Unique)
                        {
                            if (localIndexCache.Length == 1)
                            {
                                LogCritical($"We want to move {sortInfo.Name} to {ItemSortStatus.GetByIndex(localIndexCache[0]).Name} but it's unique and that inventory already has one. Too bad!");
                            }
                            else
                            {
                                LogCritical($"We want to move {sortInfo.Name} but it's unique and all inventories set for it already have one. Too bad!");
                            }
                        }
                        else
                        {
                            LogCritical($"We want to move {sortInfo.Name} to {ItemSortStatus.GetByIndex(localIndexCache[0]).Name} " +
                                        $"but it can't be moved there for... some reason. IndexStatus: {sortInfo.IndexStatus(cachedInventory.Index).ToString()}");
                        }
                    }
                }
            }

            await GeneralFunctions.ExitRetainer(true);

            if (AutoRetainerSortSettings.Instance.AutoGenLisbeth)
            {
                string lisbethSettingsPath = LisbethRuleGenerator.GetSettingsPath();
                if (!string.IsNullOrEmpty(lisbethSettingsPath))
                {
                    LisbethRuleGenerator.PopulateSettings(lisbethSettingsPath);
                    LogSuccess("Auto-populated Lisbeth's retainer item rules!");
                    MessageBox.Show(
                        Strings.LisbethRules_RestartRB,
                        "Just Letting You Know...",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                }
                else
                {
                    LogCritical("Couldn't find Lisbeth settings path! We won't auto-generate retainer rules.");
                }
            }

            TreeRoot.Stop("Done sorting inventories.");
            return(false);
        }
Ejemplo n.º 16
0
        public IActionResult Create(IFormCollection dados, IFormFile FotografiaDivulgacao, IFormFile VideoDivulgacao)
        {
            Aula aula = new Aula
            {
                // Guardar o id do admin que criou
                NumAdmin = HttpContext.Session.GetString("UserId"),
                // Guardar o professor associado a esta aula
                NumProfessor = dados["IdProfessor"],
                // alterar
                DiaSemana = HelperFunctions.GetDay(dados["DiaSemana"]),

                HoraInicio           = TimeSpan.Parse(dados["HoraInicio"] + ":00"),
                Lotacao              = int.Parse(dados["Lotacao"]),
                ValidoDe             = DateTime.Parse(dados["ValidoDe"]),
                ValidoAte            = DateTime.Parse(dados["ValidoAte"]),
                Nome                 = dados["Nome"],
                Descricao            = dados["Descricao"],
                FotografiaDivulgacao = Path.GetFileName(FotografiaDivulgacao.FileName),
                VideoDivulgacao      = Path.GetFileName(VideoDivulgacao.FileName)
            };

            if (ModelState.IsValid)
            {
                _context.Add(aula);
                _context.SaveChanges();

                //guardar ficheiros no wwwroot
                string caminho          = Path.Combine(_hostEnvironment.ContentRootPath, "wwwroot\\Ficheiros");
                string nome_ficheiro    = Path.GetFileName(FotografiaDivulgacao.FileName);
                string caminho_completo = Path.Combine(caminho, nome_ficheiro);

                FileStream f = new FileStream(caminho_completo, FileMode.Create);
                FotografiaDivulgacao.CopyTo(f);

                f.Close();


                string caminho1          = Path.Combine(_hostEnvironment.ContentRootPath, "wwwroot\\Ficheiros");
                string nome_ficheiro1    = Path.GetFileName(VideoDivulgacao.FileName);
                string caminho_completo1 = Path.Combine(caminho1, nome_ficheiro1);

                FileStream ff = new FileStream(caminho_completo1, FileMode.Create);
                VideoDivulgacao.CopyTo(ff);

                ff.Close();

                return(RedirectToAction(nameof(Index)));
            }
            List <string> Horas = new List <string>();

            ViewData["NomeProfessor"] = new SelectList(_context.Professores.Include(x => x.NumProfessorNavigation), "NumProfessorNavigation.NumCC", "NumProfessorNavigation.Nome");
            List <string> dias = new List <string>()
            {
                "Segunda-Feira", "Terça-Feira", "Quarta-Feira", "Quinta-Feira", "Sexta-Feira", "Sábado", "Domingo"
            };

            ViewData["DiaSemana"] = new SelectList(dias);
            Ginasio gym = _context.Ginasios.SingleOrDefault();
            int     numero_aulas_diarias = Convert.ToInt32(((gym.Hora_Fecho.TotalMinutes - gym.Hora_Abertura.TotalMinutes)) / 50);
            int     min_cont             = (int)gym.Hora_Abertura.TotalMinutes;

            for (int i = 0; i < numero_aulas_diarias; i++)
            {
                // timespan do total de minutos
                Horas.Add(new TimeSpan(0, min_cont, 0).ToString(@"hh\:mm"));
                min_cont += 50;
            }
            ViewData["HorasInicio"] = new SelectList(Horas);

            return(View(aula));
        }
Ejemplo n.º 17
0
    public void InitializeSettings()
    {
        bool saveAssets = false;

        settingsPath = string.IsNullOrEmpty(settingsPath) || !File.Exists(settingsPath) ? HelperFunctions.GetAssetPath("PureDataSettings.asset") : settingsPath;
        settingsPath = string.IsNullOrEmpty(settingsPath) ? "Assets/PureDataSettings.asset" : settingsPath;

        if (references == null)
        {
            references = new PureDataReferences(Instance);
        }
        references.Initialize(Instance);

        if (generalSettings == null)
        {
            generalSettings = PureDataGeneralSettings.Create(settingsPath);
            saveAssets      = true;
        }
        generalSettings.Initialize(Instance);

        if (busManager == null)
        {
            busManager = PureDataBusManager.Create(settingsPath);
            busManager.UpdateMixer();
            saveAssets = true;
        }
        busManager.Initialize(Instance);

        if (spatializerManager == null)
        {
            spatializerManager = PureDataSpatializerManager.Create(settingsPath);
            saveAssets         = true;
        }
        spatializerManager.Initialize(Instance);

        if (containerManager == null)
        {
            containerManager = PureDataContainerManager.Create(settingsPath);
            saveAssets       = true;
        }
        containerManager.Initialize(Instance);

        if (sequenceManager == null)
        {
            sequenceManager = PureDataSequenceManager.Create(settingsPath);
            sequenceManager.UpdateSequenceContainer();
            saveAssets = true;
        }
        sequenceManager.Initialize(Instance);

        if (saveAssets)
        {
            HelperFunctions.SaveAssets();
        }
    }
Ejemplo n.º 18
0
        public static void SyncIncludeFiles(VCProject vcproj, List <string> priFiles,
                                            List <string> projFiles, DTE dte, bool flat, FakeFilter fakeFilter)
        {
            var cmpPriFiles = new List <string>(priFiles.Count);

            foreach (var s in priFiles)
            {
                cmpPriFiles.Add(HelperFunctions.NormalizeFilePath(s).ToLower());
            }
            cmpPriFiles.Sort();

            var cmpProjFiles = new List <string>(projFiles.Count);

            foreach (var s in projFiles)
            {
                cmpProjFiles.Add(HelperFunctions.NormalizeFilePath(s).ToLower());
            }

            var qtPro           = QtProject.Create(vcproj);
            var filterPathTable = new Hashtable(17);
            var pathFilterTable = new Hashtable(17);

            if (!flat && fakeFilter != null)
            {
                var rootFilter = qtPro.FindFilterFromGuid(fakeFilter.UniqueIdentifier);
                if (rootFilter == null)
                {
                    qtPro.AddFilterToProject(Filters.SourceFiles());
                }

                CollectFilters(rootFilter, null, ref filterPathTable, ref pathFilterTable);
            }

            // first check for new files
            foreach (var file in cmpPriFiles)
            {
                if (cmpProjFiles.IndexOf(file) > -1)
                {
                    continue;
                }

                if (flat)
                {
                    vcproj.AddFile(file); // the file is not in the project
                }
                else
                {
                    var path = HelperFunctions.GetRelativePath(vcproj.ProjectDirectory, file);
                    if (path.StartsWith(".\\", StringComparison.Ordinal))
                    {
                        path = path.Substring(2);
                    }

                    var i = path.LastIndexOf('\\');
                    if (i > -1)
                    {
                        path = path.Substring(0, i);
                    }
                    else
                    {
                        path = ".";
                    }

                    if (pathFilterTable.Contains(path))
                    {
                        var f = pathFilterTable[path] as VCFilter;
                        f.AddFile(file);
                        continue;
                    }

                    var filter = BestMatch(path, pathFilterTable);

                    var filterDir = filterPathTable[filter] as string;
                    var name      = path;
                    if (!name.StartsWith("..", StringComparison.Ordinal) && name.StartsWith(filterDir, StringComparison.Ordinal))
                    {
                        name = name.Substring(filterDir.Length + 1);
                    }

                    var newFilter = filter.AddFilter(name) as VCFilter;
                    newFilter.AddFile(file);

                    filterPathTable.Add(newFilter, path);
                    pathFilterTable.Add(path, newFilter);
                }
            }

            // then check for deleted files
            foreach (var file in cmpProjFiles)
            {
                if (cmpPriFiles.IndexOf(file) == -1)
                {
                    // the file is not in the pri file
                    // (only removes it from the project, does not del. the file)
                    var info = new FileInfo(file);
                    HelperFunctions.RemoveFileInProject(vcproj, file);
                    Messages.PaneMessage(dte, "--- (Importing .pri file) file: " + info.Name +
                                         " does not exist in .pri file, move to " + vcproj.ProjectDirectory + "Deleted");
                }
            }
        }
Ejemplo n.º 19
0
        private void WriteProSolution(ProSolution prosln, bool openFile)
        {
            var sln = prosln.ProjectSolution;

            if (string.IsNullOrEmpty(sln.FileName))
            {
                return;
            }

            var fi            = new FileInfo(sln.FullName);
            var slnDir        = fi.Directory;
            var createSlnFile = false;

            if ((slnDir != null) && (prosln.ProFiles.Count > 1))
            {
                if (MessageBox.Show(SR.GetString("ExportProject_SolutionProFileBuildIn", slnDir.FullName),
                                    SR.GetString("ExportSolution"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    createSlnFile = true;
                }
            }

            if (createSlnFile)
            {
                StreamWriter sw;
                var          slnName     = HelperFunctions.RemoveFileNameExtension(fi);
                var          slnFileName = slnDir.FullName + "\\" + slnName + ".pro";

                if (File.Exists(slnFileName))
                {
                    if (MessageBox.Show(SR.GetString("ExportProject_ExistsOverwriteQuestion", slnFileName),
                                        SR.GetString("ExportSolution"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                    {
                        return;
                    }
                }

                try {
                    sw = new StreamWriter(File.Create(slnFileName));
                } catch (Exception e) {
                    Messages.DisplayErrorMessage(e);
                    return;
                }

                var content = new ProFileContent(null);

                var option = new ProFileOption("TEMPLATE");
                option.NewOption    = null; // just one option...
                option.AssignSymbol = ProFileOption.AssignType.AT_Equals;
                content.Options.Add(option);
                option.List.Add("subdirs");

                option = new ProFileOption("SUBDIRS");
                option.ShortComment = "#Projects";
                content.Options.Add(option);

                string proFullName, relativePath;
                char[] trimChars = { '\\' };
                foreach (var profile in prosln.ProFiles)
                {
                    var fiProject       = new FileInfo(profile.Project.ProjectFile);
                    var projectBaseName = HelperFunctions.RemoveFileNameExtension(fiProject);
                    proFullName  = profile.Project.ProjectDirectory + projectBaseName + ".pro";
                    relativePath = HelperFunctions.GetRelativePath(slnDir.FullName, proFullName);
                    relativePath = relativePath.TrimEnd(trimChars);
                    relativePath = HelperFunctions.ChangePathFormat(relativePath.Remove(0, 2));
                    option.List.Add(relativePath);
                }

                using (sw) {
                    sw.WriteLine(Resources.exportSolutionHeader);
                    for (var i = 0; i < content.Options.Count; i++)
                    {
                        WriteProFileOption(sw, content.Options[i]);
                    }
                }

                if (openFile)
                {
                    dteObject.OpenFile(Constants.vsViewKindTextView, slnFileName).Activate();
                }
            }
        }
Ejemplo n.º 20
0
 public static Task WriteAsync(this IUVStream <ArraySegment <byte> > stream, byte[] data)
 {
     return(HelperFunctions.Wrap(data, stream.Write));
 }
Ejemplo n.º 21
0
        // ScanCode notes: https://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html
        private void DoPoll(object sender, EventArgs e)
        {
            _pollThreadRunning = true;
            var stroke = new ManagedWrapper.Stroke();

            // Iterate through all Keyboards
            for (var i = 1; i < 11; i++)
            {
                var isMonitoredKeyboard = IsMonitoredDevice(i) == 1;
                var hasSubscription     = false;
                var hasContext          = _contextCallbacks.ContainsKey(i);

                // Process any waiting input for this keyboard
                while (ManagedWrapper.Receive(_deviceContext, i, ref stroke, 1) > 0)
                {
                    var block = false;
                    // If this is not a monitored keyboard, skip.
                    // This check should not really be needed as the IsMonitoredDevice() predicate should only match monitored keyboards...
                    // ... but in case it does, we want to ignore this bit and pass the input through
                    if (isMonitoredKeyboard)
                    {
                        var            isKeyMapping   = false; // True if this is a mapping to a single key, else it would be a mapping to a whole device
                        var            processedState = HelperFunctions.KeyboardStrokeToKeyboardState(stroke);
                        var            code           = processedState.Code;
                        var            state          = processedState.State;
                        MappingOptions mapping        = null;

                        if (_keyboardMappings.ContainsKey(i))
                        {
                            mapping = _keyboardMappings[i];
                        }
                        else if (_keyboardKeyMappings.ContainsKey(i) && _keyboardKeyMappings[i].ContainsKey(code))
                        {
                            isKeyMapping = true;
                            mapping      = _keyboardKeyMappings[i][code];
                        }
                        if (mapping != null)
                        {
                            // Process Subscription Mode

                            #region KeyCode, State, Extended Flag translation

                            // Begin translation of incoming key code, state, extended flag etc...
                            var processMappings = true;

                            #endregion

                            if (processedState.Ignore)
                            {
                                // Set flag to stop Context Mode from firing
                                hasSubscription = true;
                                // Set flag to indicate disable mapping processing
                                processMappings = false;
                            }

                            // Code and state now normalized, proceed with checking for subscriptions...
                            if (processMappings)
                            {
                                hasSubscription = true;

                                if (mapping.Block)
                                {
                                    block = true;
                                }
                                if (mapping.Concurrent)
                                {
                                    if (isKeyMapping)
                                    {
                                        ThreadPool.QueueUserWorkItem(threadProc => mapping.Callback(state));
                                    }
                                    else
                                    {
                                        ThreadPool.QueueUserWorkItem(threadProc => mapping.Callback(code, state));
                                    }
                                }
                                else
                                {
                                    if (isKeyMapping)
                                    {
                                        _workerThreads[i][code]?.Actions.Add(() => mapping.Callback(state));
                                    }
                                    else
                                    {
                                        _deviceWorkerThreads[i]?.Actions.Add(() => mapping.Callback(code, state));
                                    }
                                }
                            }
                        }
                    }

                    // If the key was blocked by Subscription Mode, then move on to next key...
                    if (block)
                    {
                        continue;
                    }

                    // If this key had no subscriptions, but Context Mode is set for this keyboard...
                    // ... then set the Context before sending the key
                    if (!hasSubscription && hasContext)
                    {
                        _contextCallbacks[i](1);
                    }

                    // Pass the key through to the OS.
                    ManagedWrapper.Send(_deviceContext, i, ref stroke, 1);

                    // If we are processing Context Mode, then Unset the context variable after sending the key
                    if (!hasSubscription && hasContext)
                    {
                        _contextCallbacks[i](0);
                    }
                }
            }

            // Process Mice
            for (var i = 11; i < 21; i++)
            {
                var isMonitoredMouse = IsMonitoredDevice(i) == 1;
                var hasSubscription  = false;
                var hasContext       = _contextCallbacks.ContainsKey(i);

                while (ManagedWrapper.Receive(_deviceContext, i, ref stroke, 1) > 0)
                {
                    var moveRemoved = false;
                    var hasMove     = false;
                    if (isMonitoredMouse)
                    {
                        var x = stroke.mouse.x;
                        var y = stroke.mouse.y;
                        //Debug.WriteLine($"AHK| Stroke Seen. State = {stroke.mouse.state}, Flags = {stroke.mouse.flags}, x={x}, y={y}");

                        // Process mouse movement
                        var isAbsolute = (stroke.mouse.flags & (ushort)ManagedWrapper.MouseFlag.MouseMoveAbsolute) ==
                                         (ushort)ManagedWrapper.MouseFlag.MouseMoveAbsolute;
                        //Determine whether or not to report mouse movement.
                        // For Relative mode, this is fairly simple - if x and y are both 0, no movement was reported (Since a real mouse never reports x=0/y=0)
                        // For Absolute mode, x=0/y=0 is reported, but we should limit this to only reporting once...
                        // ... so when x=0/y=0 is seen in absolute mode, set the flag _absoluteMode00Reported to true and allow it to be reported...
                        // then on subsequent reports of x=0/y=0 for absolute mode, if _absoluteMode00Reported is already true, then do not report movement...
                        // ... In absolute mode, when x!=0/y!=0 is received, clear the _absoluteMode00Reported flag
                        if (isAbsolute)
                        {
                            if (x == 0 && y == 0)
                            {
                                if (!_absoluteMode00Reported)
                                {
                                    hasMove = true;
                                    _absoluteMode00Reported = true;
                                }
                                else
                                {
                                    hasMove = false;
                                }
                            }
                            else
                            {
                                hasMove = true;
                                _absoluteMode00Reported = false;
                            }
                        }
                        else
                        {
                            hasMove = (x != 0 || y != 0);
                        }

                        if (hasMove)
                        {
                            // Process Absolute Mouse Move
                            if (isAbsolute)
                            {
                                if (_mouseMoveAbsoluteMappings.ContainsKey(i))
                                {
                                    var mapping = _mouseMoveAbsoluteMappings[i];
                                    hasSubscription = true;
                                    //var debugStr = $"AHK| Mouse stroke has absolute move of {x}, {y}...";

                                    if (mapping.Concurrent)
                                    {
                                        ThreadPool.QueueUserWorkItem(threadProc => mapping.Callback(x, y));
                                    }
                                    else if (_workerThreads.ContainsKey(i) && _workerThreads[i].ContainsKey(7))
                                    {
                                        _workerThreads[i][7]?.Actions.Add(() => mapping.Callback(x, y));
                                    }
                                    if (mapping.Block)
                                    {
                                        moveRemoved    = true;
                                        stroke.mouse.x = 0;
                                        stroke.mouse.y = 0;
                                        //debugStr += "Blocking";
                                    }
                                    else
                                    {
                                        //debugStr += "Not Blocking";
                                    }

                                    //Debug.WriteLine(debugStr);
                                }
                            }

                            // Process Relative Mouse Move
                            //else if ((stroke.mouse.flags & (ushort) ManagedWrapper.MouseFlag.MouseMoveRelative) == (ushort) ManagedWrapper.MouseFlag.MouseMoveRelative) / flag is 0, so always true!
                            else
                            {
                                if (_mouseMoveRelativeMappings.ContainsKey(i))
                                {
                                    var mapping = _mouseMoveRelativeMappings[i];
                                    hasSubscription = true;
                                    //var debugStr = $"AHK| Mouse stroke has relative move of {x}, {y}...";

                                    if (mapping.Concurrent)
                                    {
                                        ThreadPool.QueueUserWorkItem(threadProc => mapping.Callback(x, y));
                                    }
                                    else if (_workerThreads.ContainsKey(i) && _workerThreads[i].ContainsKey(8))
                                    {
                                        _workerThreads[i][8]?.Actions.Add(() => mapping.Callback(x, y));
                                    }
                                    if (mapping.Block)
                                    {
                                        moveRemoved    = true;
                                        stroke.mouse.x = 0;
                                        stroke.mouse.y = 0;
                                        //debugStr += "Blocking";
                                    }
                                    else
                                    {
                                        //debugStr += "Not Blocking";
                                    }

                                    //Debug.WriteLine(debugStr);
                                }
                            }
                        }


                        var isMouseButtonsMapping = _mouseButtonsMappings.ContainsKey(i);

                        // Process Mouse Buttons - do this AFTER mouse movement, so that absolute mode has coordinates available at the point that the button callback is fired
                        if (stroke.mouse.state != 0 && _mouseButtonMappings.ContainsKey(i) || isMouseButtonsMapping)
                        {
                            var btnStates = HelperFunctions.MouseStrokeToButtonStates(stroke);
                            foreach (var btnState in btnStates)
                            {
                                if (!isMouseButtonsMapping && !_mouseButtonMappings[i].ContainsKey(btnState.Button))
                                {
                                    continue;
                                }

                                hasSubscription = true;
                                MappingOptions mapping = null;
                                if (isMouseButtonsMapping)
                                {
                                    mapping = _mouseButtonsMappings[i];
                                }
                                else
                                {
                                    mapping = _mouseButtonMappings[i][btnState.Button];
                                }

                                var state = btnState;

                                if (mapping.Concurrent)
                                {
                                    if (isMouseButtonsMapping)
                                    {
                                        ThreadPool.QueueUserWorkItem(threadProc =>
                                                                     mapping.Callback(btnState.Button, state.State));
                                    }
                                    else
                                    {
                                        ThreadPool.QueueUserWorkItem(threadProc => mapping.Callback(state.State));
                                    }
                                }
                                else
                                {
                                    if (isMouseButtonsMapping)
                                    {
                                        _deviceWorkerThreads[i]?.Actions
                                        .Add(() => mapping.Callback(btnState.Button, state.State));
                                    }
                                    else
                                    {
                                        _workerThreads[i][btnState.Button]?.Actions
                                        .Add(() => mapping.Callback(state.State));
                                    }
                                }


                                if (mapping.Block)
                                {
                                    // Remove the event for this button from the stroke, leaving other button events intact
                                    stroke.mouse.state -= btnState.Flag;
                                    // If we are removing a mouse wheel event, then set rolling to 0 if no mouse wheel event left
                                    if (btnState.Flag == 0x400 || btnState.Flag == 0x800)
                                    {
                                        if ((stroke.mouse.state & 0x400) != 0x400 &&
                                            (stroke.mouse.state & 0x800) != 0x800)
                                        {
                                            //Debug.WriteLine("AHK| Removing rolling flag from stroke");
                                            stroke.mouse.rolling = 0;
                                        }
                                    }

                                    //Debug.WriteLine($"AHK| Removing flag {btnState.Flag} from stoke, leaving state {stroke.mouse.state}");
                                }
                                else
                                {
                                    //Debug.WriteLine($"AHK| Leaving flag {btnState.Flag} in stroke");
                                }
                            }
                        }
                    }

                    // Forward on the stroke if required
                    if (hasSubscription)
                    {
                        // Subscription mode
                        // If the stroke has a move that was not removed, OR it has remaining button events, then forward on the stroke
                        if ((hasMove && !moveRemoved) || stroke.mouse.state != 0)
                        {
                            //Debug.WriteLine($"AHK| Sending stroke. State = {stroke.mouse.state}. hasMove={hasMove}, moveRemoved={moveRemoved}");
                            ManagedWrapper.Send(_deviceContext, i, ref stroke, 1);
                        }
                        else
                        {
                            // Everything removed from stroke, do not forward
                            //Debug.WriteLine("AHK| Mouse stroke now empty, not forwarding");
                        }
                    }
                    else if (hasContext)
                    {
                        // Context Mode - forward stroke with context wrapping
                        _contextCallbacks[i](1);
                        ManagedWrapper.Send(_deviceContext, i, ref stroke, 1);
                        _contextCallbacks[i](0);
                    }
                    else
                    {
                        // No subscription or context mode - forward on
                        //Debug.WriteLine($"AHK| Sending stroke. State = {stroke.mouse.state}. hasMove={hasMove}, moveRemoved={moveRemoved}");
                        ManagedWrapper.Send(_deviceContext, i, ref stroke, 1);
                    }
                    //Debug.WriteLine($"AHK| ");
                }
            }

            _pollThreadRunning = false;
        }
Ejemplo n.º 22
0
 public static Task <int> WriteAsync(this IUVStream <ArraySegment <byte> > stream, string text)
 {
     return(HelperFunctions.Wrap <string, int>(text, stream.Write));
 }
 public static Task ConnectAsync <TType, TEndPoint>(this IConnectable <TType, TEndPoint> client, TEndPoint endPoint, TimeSpan timeout)
 {
     return(HelperFunctions.Wrap(endPoint, Timeout.In <TEndPoint>(timeout, client.Connect)));
 }
Ejemplo n.º 24
0
 public static Task ShutdownAsync(this IUVStream <ArraySegment <byte> > stream)
 {
     return(HelperFunctions.Wrap(stream.Shutdown));
 }
Ejemplo n.º 25
0
 public override string MakeFitnessScore()
 {
     FitnessScore = HelperFunctions.EDFitnessScore(RealRho, ElectronDensityArray, 0, 0, ParamSize());
     return(FitnessScore.ToString("##.### E-0"));
 }
Ejemplo n.º 26
0
 public override void GetSWVersion(string message)
 {
     byte[] comByte = HelperFunctions.HexToByte(message);
     base._resetCtrl.ResetRxSwVersion = base.m_Protocols.ConvertRawToFields(comByte);
     base._commWindow.UpdateWindowTitleBar(base._commWindow.PortName + ": " + base._resetCtrl.ResetRxSwVersion);
 }
        public async Task <ApiResponse <PromoCodeDTO> > CreatePromoCode(CreatePromoCodeDTO model)
        {
            ApiResponse <PromoCodeDTO> result = new ApiResponse <PromoCodeDTO>();

            try
            {
                PromoCode promoCodeToCreate = new PromoCode();
                promoCodeToCreate.CreationDate       = DateTime.Now;
                promoCodeToCreate.ExpiryDate         = model.ExpiryDate;
                promoCodeToCreate.OriginalUsageCount = model.UsageCount;
                promoCodeToCreate.UsageCount         = model.UsageCount;
                promoCodeToCreate.DiscountRate       = model.DiscountRate;

                if (model.DiscountRate > 100)
                {
                    result.Succeeded = false;
                    result.Errors.Add("Error creating promo code , discount rate is more than 100% !");
                    return(result);
                }

                if (model.ExpiryDate < DateTime.Now)
                {
                    result.Succeeded = false;
                    result.Errors.Add("Please enter a valid expiry date !");
                    return(result);
                }

                string code;

                while (true)
                {
                    code = HelperFunctions.GenerateRandomNumber();

                    var promoCodeResult = await unitOfWork.PromoCodeManager.GetAsync(a => a.Code == code);

                    List <PromoCode> promoCodesList = promoCodeResult.ToList();

                    if (promoCodesList.Count == 0)
                    {
                        break;
                    }
                }


                promoCodeToCreate.Code = code;

                var createPromoCodeResult = await unitOfWork.PromoCodeManager.CreateAsync(promoCodeToCreate);

                await unitOfWork.SaveChangesAsync();

                if (createPromoCodeResult != null)
                {
                    result.Data      = mapper.Map <PromoCodeDTO>(createPromoCodeResult);
                    result.Succeeded = true;
                    return(result);
                }
                else
                {
                    result.Succeeded = false;
                    result.Errors.Add("Error creating promo code");
                    return(result);
                }
            }
            catch (Exception ex)
            {
                result.Succeeded = false;
                result.Errors.Add(ex.Message);
                return(result);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Initializes a new instance of an <see cref="Audio"/> object.
        /// </summary>
        /// <param name="id">The ID that uniquely identifies this object. Specify int.MinValue for a new object.</param>
        /// <param name="parentAlbum">The album that contains this object. This is a required parameter.</param>
        /// <param name="thumbnailFilename">The filename of the thumbnail image.</param>
        /// <param name="thumbnailWidth">The width (px) of the thumbnail image.</param>
        /// <param name="thumbnailHeight">The height (px) of the thumbnail image.</param>
        /// <param name="thumbnailSizeKb">The size (KB) of the thumbnail image.</param>
        /// <param name="optimizedFilename">The filename of the optimized image.</param>
        /// <param name="optimizedWidth">The width (px) of the optimized image.</param>
        /// <param name="optimizedHeight">The height (px) of the optimized image.</param>
        /// <param name="optimizedSizeKb">The size (KB) of the optimized image.</param>
        /// <param name="originalFilename">The filename of the original image.</param>
        /// <param name="originalWidth">The width (px) of the original image.</param>
        /// <param name="originalHeight">The height (px) of the original image.</param>
        /// <param name="originalSizeKb">The size (KB) of the original image.</param>
        /// <param name="sequence">An integer that represents the order in which this image should appear when displayed.</param>
        /// <param name="createdByUsername">The user name of the account that originally added this object to the data store.</param>
        /// <param name="dateAdded">The date this image was added to the data store.</param>
        /// <param name="lastModifiedByUsername">The user name of the account that last modified this object.</param>
        /// <param name="dateLastModified">The date this object was last modified.</param>
        /// <param name="isPrivate">Indicates whether this object should be hidden from un-authenticated (anonymous) users.</param>
        /// <param name="isInflated">A bool indicating whether this object is fully inflated.</param>
        /// <param name="audioFile">A <see cref="FileInfo"/> object containing the original audio file for this object. This is intended to be
        ///   specified when creating a new media object from a file. Specify null when instantiating an object for an existing database
        ///   record.</param>
        /// <param name="metadata">A collection of <see cref="Data.MetadataDto" /> instances containing metadata for the
        ///   object. Specify null if not available.</param>
        /// <exception cref="InvalidMediaObjectException">Thrown when
        /// <paramref name="audioFile"/> is specified (not null) and the file it refers to is not in the same directory
        /// as the parent album's directory.</exception>
        /// <exception cref="UnsupportedMediaObjectTypeException">Thrown when
        /// <paramref name="audioFile"/> is specified (not null) and its file extension does not correspond to an audio MIME
        /// type, as determined by the MIME type definition in the configuration file.</exception>
        /// <remarks>This constructor does not verify that <paramref name="audioFile"/> refers to a file type that is enabled in the
        /// configuration file.</remarks>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="parentAlbum" /> is null.</exception>
        internal Audio(int id, IAlbum parentAlbum, string thumbnailFilename, int thumbnailWidth, int thumbnailHeight, int thumbnailSizeKb, string optimizedFilename, int optimizedWidth, int optimizedHeight, int optimizedSizeKb, string originalFilename, int originalWidth, int originalHeight, int originalSizeKb, int sequence, string createdByUsername, DateTime dateAdded, string lastModifiedByUsername, DateTime dateLastModified, bool isPrivate, bool isInflated, FileInfo audioFile, IEnumerable <MetadataDto> metadata)
        {
            if (parentAlbum == null)
            {
                throw new ArgumentNullException("parentAlbum");
            }

            System.Diagnostics.Debug.Assert(((originalFilename.Length > 0) || (audioFile != null)), "Invalid Audio constructor arguments: The original filename or a FileInfo reference to the original file must be passed to the Audio constructor.");

            this.Id        = id;
            this.Parent    = parentAlbum;
            this.GalleryId = this.Parent.GalleryId;
            //this.Title = title;
            this.Sequence               = sequence;
            this.CreatedByUserName      = createdByUsername;
            this.DateAdded              = dateAdded;
            this.LastModifiedByUserName = lastModifiedByUsername;
            this.DateLastModified       = dateLastModified;
            this.IsPrivate              = isPrivate;
            this.IsWritable             = parentAlbum.IsWritable;

            this.SaveBehavior       = Factory.GetMediaObjectSaveBehavior(this);
            this.DeleteBehavior     = Factory.GetMediaObjectDeleteBehavior(this);
            this.MetadataReadWriter = Factory.GetMetadataReadWriter(this);

            string parentPhysicalPath = this.Parent.FullPhysicalPathOnDisk;

            IGallerySettings gallerySetting = Factory.LoadGallerySetting(GalleryId);

            // Thumbnail image
            this.Thumbnail            = DisplayObject.CreateInstance(this, thumbnailFilename, thumbnailWidth, thumbnailHeight, DisplayObjectType.Thumbnail, new GenericThumbnailCreator(this));
            this.Thumbnail.FileSizeKB = thumbnailSizeKb;
            if (thumbnailFilename.Length > 0)
            {
                // The thumbnail is stored in either the album's physical path or an alternate location (if thumbnailPath config setting is specified) .
                string thumbnailPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(parentPhysicalPath, gallerySetting.FullThumbnailPath, gallerySetting.FullMediaObjectPath);
                this.Thumbnail.FileNamePhysicalPath = Path.Combine(thumbnailPath, thumbnailFilename);
            }

            // Optimized audio
            this.Optimized            = DisplayObject.CreateInstance(this, optimizedFilename, optimizedWidth, optimizedHeight, DisplayObjectType.Optimized, new AudioOptimizedCreator(this));
            this.Optimized.FileSizeKB = optimizedSizeKb;
            if (optimizedFilename.Length > 0)
            {
                // Calcululate the full file path to the optimized audio. If the optimized filename is equal to the original filename, then no
                // optimized version exists, and we'll just point to the original. If the names are different, then there is a separate optimized
                // image file, and it is stored in either the album's physical path or an alternate location (if optimizedPath config setting is specified).
                string optimizedPath = parentPhysicalPath;

                if (optimizedFilename != originalFilename)
                {
                    optimizedPath = HelperFunctions.MapAlbumDirectoryStructureToAlternateDirectory(parentPhysicalPath, gallerySetting.FullOptimizedPath, gallerySetting.FullMediaObjectPath);
                }

                this.Optimized.FileNamePhysicalPath = System.IO.Path.Combine(optimizedPath, optimizedFilename);
            }

            // Original audio file
            this.Original = DisplayObject.CreateInstance(this, originalFilename, originalWidth, originalHeight, DisplayObjectType.Original, new NullObjects.NullDisplayObjectCreator());
            this.Original.ExternalHtmlSource = String.Empty;
            this.Original.ExternalType       = MimeTypeCategory.NotSet;

            if (audioFile != null)
            {
                this.Optimized.FileInfo = audioFile;                // Will throw InvalidMediaObjectException if the file's directory is not the same as the album's directory.
                this.Original.FileInfo  = audioFile;                // Will throw InvalidMediaObjectException if the file's directory is not the same as the album's directory.

                if (this.Original.MimeType.TypeCategory != MimeTypeCategory.Audio)
                {
                    throw new Events.CustomExceptions.UnsupportedMediaObjectTypeException(this.Original.FileInfo);
                }

                this.Optimized.Width  = gallerySetting.DefaultAudioPlayerWidth;
                this.Optimized.Height = gallerySetting.DefaultAudioPlayerHeight;

                this.Original.Width  = gallerySetting.DefaultAudioPlayerWidth;
                this.Original.Height = gallerySetting.DefaultAudioPlayerHeight;

                int fileSize = (int)(audioFile.Length / 1024);
                this.Optimized.FileSizeKB = (fileSize < 1 ? 1 : fileSize);                // Very small files should be 1, not 0.
                this.Original.FileSizeKB  = (fileSize < 1 ? 1 : fileSize);                // Very small files should be 1, not 0.

                if (IsNew)
                {
                    ExtractMetadata();
                }
            }
            else
            {
                this.Original.FileNamePhysicalPath = Path.Combine(parentPhysicalPath, originalFilename);
                this.Original.FileSizeKB           = originalSizeKb;
            }

            if (metadata != null)
            {
                AddMeta(GalleryObjectMetadataItemCollection.FromMetaDtos(this, metadata));
            }

            this.IsInflated = isInflated;

            // Setting the previous properties has caused HasChanges = true, but we don't want this while
            // we're instantiating a new object. Reset to false.
            this.HasChanges = false;

            // Set up our event handlers.
            //this.Saving += new EventHandler(Image_Saving); // Don't need
            this.Saved += MediaObject_Saved;
        }
    public static float BottomSpacing()
    {
        float bpos = HelperFunctions.GetHeight(Config.width) - ((HelperFunctions.GetCanvasSize(Screen.safeArea.height) + HelperFunctions.GetCanvasSize(Screen.safeArea.y)));

        return(bpos);
    }
Ejemplo n.º 30
0
            private static dynamic HandleLink(string url, string fileName, Mode mode, Type type)
            {
                string subDirectory;

                switch (type)
                {
                case Type.Race:
                    subDirectory = "race_pages";
                    break;

                case Type.Background:
                    subDirectory = "background_pages";
                    break;

                case Type.Class:
                    subDirectory = "class_pages";
                    break;

                case Type.Subclass:
                    subDirectory = "subclass_pages";
                    break;

                case Type.Feat:
                    subDirectory = "feat_pages";
                    break;

                default:
                    throw new Exception("Invalid Type");
                }

                if (fileName.Contains('/'))
                {
                    fileName = fileName.Replace("/", "");
                }
                if (fileName.Contains(' '))
                {
                    fileName = fileName.Replace(" ", "_");
                }

                fileName = Config.DownloadedPagesDir + "/" + subDirectory + "/" + fileName + ".html.txt";


                string html;

                if (mode == Mode.ScrapeFiles)
                {
                    html = File.ReadAllText(fileName);
                }
                else
                {
                    html = HelperFunctions.GetHtmlFromUrl(url);
                }


                if (mode == Mode.ScrapeFiles)
                {
                    if (!Config.Silent)
                    {
                        Console.WriteLine("parsing: " + url);
                    }

                    switch (type)
                    {
                    case Type.Race:
                        return(RacePageParser.ParseRacePage(html));

                    case Type.Background:
                        return(null);

                    case Type.Class:
                        return(ClassPageParser.ParseClassPage(html));

                    case Type.Subclass:
                        return(SubclassPageParser.ParseSubclassPage(html));

                    case Type.Feat:
                        return(null);

                    default:
                        throw new Exception("Invalid Type");
                    }
                }
                else
                {
                    if (!Config.Silent)
                    {
                        Console.WriteLine("downloading: " + url);
                    }
                    File.WriteAllText(fileName, html);
                }


                return(null);
            }
Ejemplo n.º 31
0
        public ActionResult Login(LogOnViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (authProvider.Authenticate(model.EmailAddress, model.Password, this.userRepository))
                {
                    var userObj = userRepository.GetUserByEmailAddress(model.EmailAddress);
                    Session["user"] = userObj;
                    var accountObj = accRepository.Accounts.FirstOrDefault(x => x.ID == userObj.AccountID);
                    Session["account"] = accountObj;
                    var timeZone = accRepository.Accounts.Where(aid => aid.ID == userObj.AccountID).FirstOrDefault().TimeZone;
                    Session["timeZone"] = timeZone;
                    Session["SysAdminDetails"] = null;

                    List<NotificationListViewModel> notificationList = new List<NotificationListViewModel>();

                    CronJobController CJC = new CronJobController();
                    Session["account"] = CJC.checkAccountTrialExpiryForAccount(accountObj);

                    //save details into error table
                    //SaveLogonDetails(model.EmailAddress);

                    if ( userObj.UserType == "Admin" || userObj.UserType == "Standard")
                    {
                        if (userObj.EmailVerified == true)
                        {
                            //get the folders
                            var folders = CCFolderRepository.CCFolders.Where(guid => guid.AccountGUID == accountObj.AccountGUID).ToList();
                            Session["folderss"] = folders;

                            HelperFunctions HF = new HelperFunctions();
                            notificationList = HF.generateNotificationList(accountObj);

                            HF.CheckAcccountStatus(accountObj);

                            if(notificationList.Count>0)
                                Session["notifications"] = notificationList;
                            else
                                Session["notifications"] = null;

                            return Redirect(returnUrl ?? Url.Action("Index", "Admin"));
                        }
                        else
                        {
                            return Redirect(returnUrl ?? Url.Action("ResendVerification", "SignUp", new { uid = userObj.ID }));
                        }
                    }
                    else if (userObj.UserType == "SystemAdmin")
                    {
                        HelperFunctions HF = new HelperFunctions();
                        notificationList = HF.generateNotificationList(accountObj);
                        if (notificationList.Count > 0)
                            Session["notifications"] = notificationList;

                        Session["SysAdminDetails"] = userRepository.GetUserByEmailAddress(model.EmailAddress);

                        return Redirect(returnUrl ?? Url.Action("Index", "CorporateContactsAdmin"));
                    }
                    else
                    {
                        return Redirect(returnUrl ?? Url.Action("SetupSync", "User"));
                    }
                }
                else
                {
                    //save details into error table
                    //SaveLogonDetails(model.EmailAddress);
                    ModelState.AddModelError("", "Incorrect username or password");
                    return View();

                }
            }
            else
            {
                return View();
            }
        }
Ejemplo n.º 32
0
 void Die()
 {
     HelperFunctions.IncrementInt("Gunflowers Harvested");
     GenerateDrops();
     Destroy(gameObject);
 }
Ejemplo n.º 33
0
        public bool Run(Board board, Position blank_pos, Board goal_board, ref List<Move> moves, int grid_size, ref int boards_searched, ref int open_list_size, ref long timer, ref long memory_used)
        {
            hf_ = new HelperFunctions();

            if (hf_.CompareBoards(board, goal_board))
                return true;

            size_ = grid_size;

            AStarNode root = new AStarNode(board, null, blank_pos, null);
            AStarNode goal = new AStarNode(goal_board, null, null, null);

            PriorityQueue open_q = new PriorityQueue();
            HashSet<AStarNode> open_d = new HashSet<AStarNode>();
            HashSet<AStarNode> closed_list = new HashSet<AStarNode>();
            
            open_q.Add(root);
            open_d.Add(root);
            bool goal_found = false;

            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
            sw.Start();

            
            while(open_q.Size() > 0 && !goal_found) // && sw.ElapsedMilliseconds < 10000)
            {
                AStarNode next_node = open_q.GetNext();
                open_d.Remove(next_node);
                if (next_node.board_.Equals(goal.board_))
                {
                    timer = sw.ElapsedMilliseconds;
                    sw.Stop();
                    goal_found = true;
                    goal = next_node;
                    continue;
                }

                List<AStarNode> successors = GetChildren(next_node);

                foreach(AStarNode successor in successors)
                {
                    if (hf_.CompareBoards(successor, closed_list))
                        continue;

                    successor.g = next_node.g + 1;

                    if (hf_.CompareBoards(successor, open_d)) 
                        continue;

                    successor.h = ManhattanDistance(successor.board_);
                    successor.f = successor.g + successor.h;
                    open_q.Add(successor);
                    open_d.Add(successor);
                }

                closed_list.Add(next_node);
            }

            memory_used = GC.GetTotalMemory(false);
            open_list_size = open_q.Size();
            boards_searched = closed_list.Count;

            if(goal_found) TraverseTree(ref moves, goal);

            closed_list.Clear();
            open_d.Clear();
            open_q.Clear();
            GC.Collect();

            return goal_found;
        }
Ejemplo n.º 34
0
 public int GetKeyboardIdFromHandle(string handle, int instance = 1)
 {
     return(HelperFunctions.GetDeviceIdFromHandle(_deviceContext, false, handle, instance));
 }
        public int checkToFreezeAccount(Account acc)
        {
            var folderList = CCFolderRepository.CCFolders.Where(f => f.AccountGUID == acc.AccountGUID).ToList();

            foreach(var fold in folderList)
            {
                int FolderItemCount = CCItemRepository.CCContacts.Where(i => i.FolderID == fold.FolderID).Count();

                LimitationsViewModel limitationsObj = new LimitationsViewModel();
                HelperFunctions HF = new HelperFunctions();
                limitationsObj = HF.updateAccountLimitations(acc);

                if ((FolderItemCount > limitationsObj.maxItemCountPerFolder) | (fold.isOverFlow == true))
                {
                    return 1;
                }
            }
            return 0;
        }
Ejemplo n.º 36
0
 public int GetDeviceIdFromHandle(bool isMouse, string handle, int instance = 1)
 {
     return(HelperFunctions.GetDeviceIdFromHandle(_deviceContext, isMouse, handle, instance));
 }
Ejemplo n.º 37
0
 public int GetDeviceId(bool isMouse, int vid, int pid, int instance = 1)
 {
     return(HelperFunctions.GetDeviceId(_deviceContext, isMouse, vid, pid, instance));
 }
        public ActionResult ImpersonatedAccount(long AccID)
        {
            if (Session["SysAdminDetails"] != null)
            {
                TempData["SelectedMenu"] = "AccImpersontation";

                var userObj = CCUserRepository.GetUserByEmailAddress(CCUserRepository.Users.First(U => U.AccountID == AccID).Email);
                Session["user"] = userObj;
                var accountObj = CCAccRepository.Accounts.FirstOrDefault(x => x.ID == userObj.AccountID);
                Session["account"] = accountObj;
                var timeZone = CCAccRepository.Accounts.Where(aid => aid.ID == userObj.AccountID).FirstOrDefault().TimeZone;
                Session["timeZone"] = timeZone;
                var folders = CCFolderRepository.CCFolders.Where(guid => guid.AccountGUID == accountObj.AccountGUID).ToList();
                Session["folderss"] = folders;

                LimitationsViewModel limitationsObj = new LimitationsViewModel();
                HelperFunctions HF1 = new HelperFunctions();
                limitationsObj = HF1.updateAccountLimitations(accountObj);
                Session["limitations"] = limitationsObj;

                List<NotificationListViewModel> notificationList = new List<NotificationListViewModel>();

                CronJobController CJC = new CronJobController();
                Session["account"] = CJC.checkAccountTrialExpiryForAccount(accountObj);

                HelperFunctions HF = new HelperFunctions();
                notificationList = HF.generateNotificationList(accountObj);

                HF.CheckAcccountStatus(accountObj);

                if (notificationList.Count > 0)
                    Session["notifications"] = notificationList;
                else
                    Session["notifications"] = null;

                if (((DateTime)(accountObj.TrialEnds) - (DateTime)(DateTime.Now.Date)).TotalDays < CCGlobalValues.trialPeriod)
                {
                    TrialDataModel trialObj = new TrialDataModel();
                    trialObj.hasPurchased = accountObj.HasPurchased;
                    trialObj.createdDate = accountObj.CreatedDate;
                    trialObj.trialEndDate = accountObj.TrialEnds;
                    trialObj.showPurchaseOptions = true;
                    Session["trialData"] = trialObj;
                }

                ImpersonateAccountsSysAdminModel model = new ImpersonateAccountsSysAdminModel();

                var AccountsInfo = CCAccRepository.Accounts.Where(A => A.ID == AccID).FirstOrDefault();

                model.SelectedAccountInfo = AccountsInfo;
                model.FolderCount = CCFolderRepository.CCFolders.Where(F => F.AccountGUID == AccountsInfo.AccountGUID).Count();
                model.ConnectionCount = CCConnectionRepository.CCSubscriptions.Where(C => C.AccountGUID == AccountsInfo.AccountGUID).Count();
                model.UserCount = CCUserRepository.Users.Where(U => U.AccountID == AccountsInfo.ID).Count();
                model.SubscriptionCount = 0;
                model.ItemsCount = CCItemRepository.CCContacts.Where(I => I.AccountGUID == AccountsInfo.AccountGUID).Count();
                model.SelectedAccountOwner = CCUserRepository.Users.First(U => U.AccountID == AccountsInfo.ID).FullName;

                //Sync Graph Data

                List<string> SyncDates = new List<string>();
                List<double> SyncDateUsage = new List<double>();

                DateTime startDate = DateTime.Now.Date.AddDays(-1);

                for (int i = 6; i > -1; i--)
                {
                    SyncDates.Add((startDate.AddDays(-i)).ToShortDateString());
                }

                for (int i = 0; i < SyncDates.Count(); i++)
                {
                    DateTime syncDateStart = DateTime.Parse(SyncDates[i]);
                    DateTime syncDateEnd = syncDateStart.AddHours(23).AddMinutes(59);

                    SyncDateUsage.Add(CCSyncItemsRepository.CCSyncItems.Where(SI => SI.LastUpdated >= syncDateStart && SI.LastUpdated <= syncDateEnd).Count());
                }

                model.SyncDates = SyncDates;
                model.SyncDateUsage = SyncDateUsage;

                return View(model);
            }
            else
            {
                return RedirectToAction("Login", "Login");
            }
        }