Inheritance: MonoBehaviour
Beispiel #1
0
        public GenericHost(IConfigureThisEndpoint specifier, string[] args, List<Type> defaultProfiles, string endpointName, IEnumerable<string> scannableAssembliesFullName = null)
        {
            this.specifier = specifier;

            if (String.IsNullOrEmpty(endpointName))
            {
                endpointName = specifier.GetType().Namespace ?? specifier.GetType().Assembly.GetName().Name;
            }

            endpointNameToUse = endpointName;
            endpointVersionToUse = FileVersionRetriever.GetFileVersion(specifier.GetType());

            if (scannableAssembliesFullName == null || !scannableAssembliesFullName.Any())
            {
                var assemblyScanner = new AssemblyScanner();
                assemblyScanner.MustReferenceAtLeastOneAssembly.Add(typeof(IHandleMessages<>).Assembly);
                assembliesToScan = assemblyScanner
                    .GetScannableAssemblies()
                    .Assemblies;
            }
            else
            {
                assembliesToScan = scannableAssembliesFullName
                    .Select(Assembly.Load)
                    .ToList();
            }

            profileManager = new ProfileManager(assembliesToScan, args, defaultProfiles);

            wcfManager = new WcfManager();
        }
        /// <summary>
        ///     Accepts the type which will specify the users custom configuration.
        ///     This type should implement <see cref="IConfigureThisEndpoint" />.
        /// </summary>
        /// <param name="scannableAssembliesFullName">Assemblies full name that were scanned.</param>
        /// <param name="specifier"></param>
        /// <param name="args"></param>
        /// <param name="defaultProfiles"></param>
        public GenericHost(IConfigureThisEndpoint specifier, string[] args, List<Type> defaultProfiles,
            IEnumerable<string> scannableAssembliesFullName = null)
        {
            this.specifier = specifier;

            endpointNameToUse = specifier.GetType().Namespace ?? specifier.GetType().Assembly.GetName().Name;

            if (scannableAssembliesFullName == null || !scannableAssembliesFullName.Any())
            {
                var assemblyScanner = new AssemblyScanner();
                assemblyScanner.MustReferenceAtLeastOneAssembly.Add(typeof(IHandleMessages<>).Assembly);
                assembliesToScan = assemblyScanner
                    .GetScannableAssemblies()
                    .Assemblies;
            }
            else
            {
                assembliesToScan = scannableAssembliesFullName
                    .Select(Assembly.Load)
                    .ToList();
            }

            args = AddProfilesFromConfiguration(args);

            profileManager = new ProfileManager(assembliesToScan, args, defaultProfiles);
        }
 protected void btnSave_Click(object sender, EventArgs e)
 {
     var manager = new ProfileManager(this);
     Company.LegalEntityProfile.Website = txtWebSite.Text;
     manager.SaveLegalEntityProfile(Company.LegalEntityProfile);
     configWebsite.Visible = false;
 }
Beispiel #4
0
        /// <summary>
        /// Gets the name of the given <see cref="RnetBusObject"/> or generates one.
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static async Task<string> GetId(this RnetBusObject o, ProfileManager profileManager)
        {
            Contract.Requires<ArgumentNullException>(o != null);

            var p = await profileManager.GetProfile<IObject>(o);
            return p != null && !string.IsNullOrWhiteSpace(p.Id) ? p.Id : GetGeneratedName(o);
        }
    protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {
        InfoControl.Web.Security.MembershipManager mManager = new InfoControl.Web.Security.MembershipManager(this);
        InfoControl.Web.Security.DataEntities.User user = mManager.GetUserByName(CreateUserWizard1.UserName.ToString());

        Profile profile = new Profile();
        ProfileManager pManager = new ProfileManager(this);

        profile.Name = (CreateUserWizard1.FindControl("txtName") as TextBox).Text;
        profile.CPF = (CreateUserWizard1.FindControl("txtCPF") as TextBox).Text;
        //profile.Address = (CreateUserWizard1.FindControl("txtAddress") as TextBox).Text;
        profile.Phone = (CreateUserWizard1.FindControl("txtPhone") as TextBox).Text;
        //profile.Neighborhood = (CreateUserWizard1.FindControl("txtNeighborhood") as TextBox).Text;
        profile.PostalCode = (CreateUserWizard1.FindControl("txtPostalCode") as TextBox).Text;
        profile.ModifiedDate = DateTime.Now;        
        //profile.UserId = user.UserId;
        //profile.StateId = (CreateUserWizard1.FindControl("cboState") as DropDownList).SelectedValue;

        try
        {
            pManager.Insert(profile);
        }
        catch (Exception ex)
        {
            if (ex != null)
                return;
        }

        Context.Items.Add("UserId", user.UserId);
        Server.Transfer("User.aspx");
    }
        public void OnOpened(EMDKManager emdkManager)
        {
            mEmdkManager = emdkManager;
            String strStatus = "";
            String[] modifyData = new String[1];

            mProfileManager = (ProfileManager)mEmdkManager.GetInstance(EMDKManager.FEATURE_TYPE.Profile);

            EMDKResults results = mProfileManager.ProcessProfile(mProfileName, ProfileManager.PROFILE_FLAG.Set, modifyData);

            if (results.StatusCode == EMDKResults.STATUS_CODE.Success)
            {
                strStatus = "Profile processed succesfully";
            }
            else if (results.StatusCode == EMDKResults.STATUS_CODE.CheckXml)
            {
                //Inspect the XML response to see if there are any errors, if not report success
                using (XmlReader reader = XmlReader.Create(new StringReader(results.StatusString)))
                {
                    String checkXmlStatus = "Status:\n\n";
                    while (reader.Read())
                    {
                        switch (reader.NodeType)
                        {
                            case XmlNodeType.Element:
                                switch (reader.Name)
                                {
                                    case "parm-error":
                                        checkXmlStatus += "Parm Error:\n";
                                        checkXmlStatus += reader.GetAttribute("name") + " - ";
                                        checkXmlStatus += reader.GetAttribute("desc") + "\n\n";
                                        break;
                                    case "characteristic-error":
                                        checkXmlStatus += "characteristic Error:\n";
                                        checkXmlStatus += reader.GetAttribute("type") + " - ";
                                        checkXmlStatus += reader.GetAttribute("desc") + "\n\n";
                                        break;
                                }
                                break;
                        }
                    }
                    if (checkXmlStatus == "Status:\n\n")
                    {
                        strStatus = "Status: Profile applied successfully ...";
                    }
                    else
                    {
                        strStatus = checkXmlStatus;
                    }

                }
            }
            else
            {
                strStatus = "Something wrong on processing the profile";
            }

            Toast.MakeText(this, strStatus, ToastLength.Long).Show();
        }
 protected ControllerRequestProcessor(
     RootProcessor module,
     ProfileManager profileManager)
     : base(module, profileManager)
 {
     Contract.Requires<ArgumentNullException>(module != null);
     Contract.Requires<ArgumentNullException>(profileManager != null);
 }
        public DynamicHostController(IConfigureThisEndpoint specifier, string[] requestedProfiles, List<Type> defaultProfiles)
        {
            this.specifier = specifier;
            
            var assembliesToScan = new List<Assembly> {GetType().Assembly};

            profileManager = new ProfileManager(assembliesToScan, requestedProfiles, defaultProfiles);
        }
Beispiel #9
0
	// Use this for initialization
	void Start () {
		if(instance == null) {
			instance = this;
			loadedProfiles = new Dictionary<PlayerID, ProfileData>();
		} else if (instance != this) {
			Destroy(this);
		}
	}
        public DynamicHostController(IConfigureThisEndpoint specifier, string[] requestedProfiles,IEnumerable<Type> defaultProfiles)
        {
            this.specifier = specifier;

            var assembliesToScan = new[] {GetType().Assembly};

            profileManager = new ProfileManager(assembliesToScan, specifier, requestedProfiles, defaultProfiles);
            configManager = new ConfigManager(assembliesToScan, specifier);
        }
Beispiel #11
0
        /// <summary>
        /// Accepts the type which will specify the users custom configuration.
        /// This type should implement <see cref="IConfigureThisEndpoint"/>.
        /// </summary>
        /// <param name="specifier"></param>
        /// <param name="args"></param>
        /// <param name="defaultProfiles"></param>
        public GenericHost(IConfigureThisEndpoint specifier, string[] args,IEnumerable<Type> defaultProfiles)
        {
            this.specifier = specifier;

            var assembliesToScan = AssemblyScanner.GetScannableAssemblies();

            profileManager = new ProfileManager(assembliesToScan, specifier, args,defaultProfiles);
            configManager = new ConfigManager(assembliesToScan, specifier);
            wcfManager = new WcfManager(assembliesToScan);
            roleManager = new RoleManager(assembliesToScan);
        }
Beispiel #12
0
		/// <summary>
		/// Creates a new profile chooser form
		/// </summary>
		/// <param name="profiles">The list of profiles available</param>
		public ProfileChooser(ProfileManager profileManager)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

            foreach (string s in profileManager.ProfileNames)
			{
				list.Items.Add( s );
			}
		}
Beispiel #13
0
        /// <summary>
        /// Accepts the type which will specify the users custom configuration.
        /// This type should implement <see cref="IConfigureThisEndpoint"/>.
        /// </summary>
        /// <param name="specifier"></param>
        /// <param name="args"></param>
        /// <param name="defaultProfiles"></param>
        /// <param name="endpointName"></param>
        public GenericHost(IConfigureThisEndpoint specifier, string[] args, IEnumerable<Type> defaultProfiles, string endpointName)
        {
            this.specifier = specifier;
            Configure.GetEndpointNameAction = () => endpointName;

            var assembliesToScan = AssemblyScanner.GetScannableAssemblies()
                .ToList();

            profileManager = new ProfileManager(assembliesToScan, specifier, args, defaultProfiles);
            ProfileActivator.ProfileManager = profileManager;

            configManager = new ConfigManager(assembliesToScan, specifier);
            wcfManager = new WcfManager(assembliesToScan);
            roleManager = new RoleManager(assembliesToScan);
        }
    protected void txtSupplier_TextChanged(object sender, EventArgs e)
    {
        //attach the event Selecting(begin)
        OnSelectingSupplier(this, new SelectingSupplierEventArgs() { SupplierName = txtSupplier.Text });
        //select the supplier
        if (!String.IsNullOrEmpty(txtSupplier.Text))
        {
            profileManager = new ProfileManager(this);
            supplierManager = new SupplierManager(this);

            string[] identifications = txtSupplier.Text.Split('|');
            string identification = identifications[0].ToString().Trim();

            supplier = supplierManager.GetSupplier(Page.Company.CompanyId, identification);

            ShowSupplier(supplier);
        }

    }
    protected void txtTransporter_TextChanged(object sender, EventArgs e)
    {
        OnSelectingTransporter(this, new SelectingTransporterEventArgs() { TransporterName = txtTransporter.Text });
        ProfileManager profileManager;
        if (txtTransporter.Text.Contains('|'))
        {
            profileManager = new ProfileManager(this);
            transporterManager = new TransporterManager(this);

            string[] identifications = txtTransporter.Text.Split('|');
            string identification = identifications[0].ToString().Trim();

            LegalEntityProfile legalEntityProfile = profileManager.GetLegalEntityProfile(identification);
            if (legalEntityProfile != null)
                transporter = transporterManager.GetTransporterByLegalEntityProfile(Page.Company.CompanyId, legalEntityProfile.LegalEntityProfileId);

            ShowTransporter(transporter);
        }
    }
Beispiel #16
0
        public void OnOpened(EMDKManager emdkManagerInstance)
        {
            // This callback will be issued when the EMDK is ready to use.
            statusTextView.Text = "EMDK open success.";

            this.emdkManager = emdkManagerInstance;

            try
            {
                // Get the ProfileManager object to process the profiles
                profileManager = (ProfileManager)emdkManager.GetInstance(EMDKManager.FEATURE_TYPE.Profile);

                new ProcessProfileSetXMLTask().Execute(this);
            }
            catch (Exception e)
            {
                statusTextView.Text = "Error setting the profile.";
                Console.WriteLine("Exception:" + e.StackTrace);
            }
        }
    protected void txtUser_TextChanged(object sender, EventArgs e)
    {
        onSelectingUser(this, new SelectingUserEventArgs() { UserName = txtUser.Text });

        if (txtUser.Text.Contains("|"))
        {
            string[] identifications = txtUser.Text.Split('|');
            string identification = identifications[0].ToString().Trim();
            companyManager = new CompanyManager(this);
            profileManager = new ProfileManager(this);

            Profile profile = profileManager.GetProfile(identification);

            if (profile != null)
                user = companyManager.GetUserByProfile(profile.ProfileId);

            ShowUser(user);
            //ShowEmployee(employee);
        }

    }
    protected void txtCustomer_TextChanged(object sender, EventArgs e)
    {
        ProfileManager profileManager;
        //select the customer
        if (txtCustomer.Text.Contains("|"))
        {
            OnSelectingCustomer(this, new SelectingCustomerEventArgs() { CustomerName = txtCustomer.Text });

            customerManager = new CustomerManager(this);
            profileManager = new ProfileManager(this);

            string[] identifications = txtCustomer.Text.Split('|');
            string identification = identifications[0].ToString().Trim();

            customer = customerManager.GetCustomer(Page.Company.CompanyId, identification);

            ShowCustomer(customer);
            txtCustomer.Text = "";
        }

    }
Beispiel #19
0
        public RootProcessor(
            [Import] ICompositionService composition,
            [Import] RnetBus bus,
            [Import] DriverManager driverManager,
            [Import] ProfileManager profileManager,
            [ImportMany] IEnumerable<Lazy<IRequestProcessor, RequestProcessorMetadata>> requestProcessors,
            [ImportMany] IEnumerable<Lazy<IResponseProcessor, ResponseProcessorMetadata>> responseProcessors)
        {
            Contract.Requires<ArgumentNullException>(composition != null);
            Contract.Requires<ArgumentNullException>(bus != null);
            Contract.Requires<ArgumentNullException>(requestProcessors != null);
            Contract.Requires<ArgumentNullException>(responseProcessors != null);
            Contract.Requires<ArgumentNullException>(driverManager != null);
            Contract.Requires<ArgumentNullException>(profileManager != null);

            this.composition = composition;
            this.bus = bus;
            this.driverManager = driverManager;
            this.profileManager = profileManager;
            this.requestProcessors = requestProcessors;
            this.responseProcessors = responseProcessors;
        }
Beispiel #20
0
        public ControllerWindow(Controller controller)
        {
            this.controller = controller;
            this.manager = controller.ProfileManager;
            InitializeComponent();

            // build the viewer menu
            viewerMenu.MenuItems.Clear();
            Hashtable viewers = controller.ViewerManager.Viewers;
            foreach (DictionaryEntry de in viewers)
            {
                MenuItem item = new MenuItem(de.Key.ToString());
                item.Click +=new EventHandler(viewerClicked);
                viewerMenu.MenuItems.Add(item);
            }

            // build the Schon menu
            foreach (DictionaryEntry de in DataFaker.FakeScans)
            {
                MenuItem item = new MenuItem(de.Key.ToString());
                item.Click +=new EventHandler(schonClicked);
                schonMenu.MenuItems.Add(item);
            }
        }
Beispiel #21
0
        private void _importButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(_pathTextBox.Text))
                {
                    MessageBox.Show($"Please set a import path above.", "Error");
                    return;
                }

                var path = new Uri(_pathTextBox.Text);

                if (!Uri.IsWellFormedUriString(path.ToString(), UriKind.Absolute))
                {
                    MessageBox.Show($"Invalid import path! Please set a valid path above.", "Error");
                    return;
                }

                if (!File.Exists(path.AbsolutePath))
                {
                    MessageBox.Show($"No file exists at '{path.AbsolutePath}'!", "Error");
                    return;
                }

                var rawText = File.ReadAllText(path.AbsolutePath);
                if (string.IsNullOrEmpty(rawText))
                {
                    MessageBox.Show($"Could not process the file!", "Error");
                    return;
                }

                if (MefinoProfile.FromJson(rawText) is MefinoProfile profile)
                {
                    if (ProfileManager.AllProfiles.ContainsKey(profile.name))
                    {
                        var result = MessageBox.Show($"A profile already exists with the name '{profile.name}'!\n\nOverwrite?",
                                                     "Overwrite profile?",
                                                     MessageBoxButtons.YesNo);

                        if (result == DialogResult.No)
                        {
                            return;
                        }

                        ProfileManager.AllProfiles[profile.name] = profile;
                    }
                    else
                    {
                        ProfileManager.AllProfiles.Add(profile.name, profile);
                    }

                    ProfileManager.SetActiveProfile(profile, true);
                    ProfileManager.SaveProfiles();

                    LauncherPage.Instance.RefreshProfileDropdown();

                    this.Close();
                }
                else
                {
                    MessageBox.Show($"Could not process the file!", "Error");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Could not export the profile:\n\n{ex.Message}", "Error");
            }
        }
Beispiel #22
0
        private void Backup(object sender, RoutedEventArgs e)
        {
            var    connectionString = ProfileManager.GetConnectionString();
            string databaseName     = this.Databases.SelectedItems[0].ToString();

            if (this.Databases.SelectedItems.Count == 1)
            {
                var dialog = new SaveFileDialog
                {
                    AddExtension     = true,
                    CheckPathExists  = true,
                    Filter           = "*.bak | *.bak",
                    InitialDirectory = Path.GetDirectoryName(SqlServerManager.Instance.GetDatabaseFileName(databaseName, ProfileManager.GetConnectionString())),
                    Title            = "Specify folder to backup"
                };
                bool?showDialog = dialog.ShowDialog();
                if (showDialog.Value != true)
                {
                    return;
                }

                var path = dialog.FileName;

                var backupPath = Path.Combine(System.IO.Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + ".bak");
                WindowHelper.LongRunningTask(() => this.Backup(databaseName, connectionString, backupPath), "Back up database", this, "The backup is being created", null, true);
            }
        }
Beispiel #23
0
 private void Restore(object sender, RoutedEventArgs e)
 {
     if (FileSystem.FileSystem.Local.Directory.Exists(Clipboard.GetText()))
     {
         WindowHelper.ShowDialog(new DatabasesOperationsDialog(Clipboard.GetText()), this);
     }
     else if (FileSystem.FileSystem.Local.Directory.Exists(lastPathToRestore))
     {
         WindowHelper.ShowDialog(new DatabasesOperationsDialog(lastPathToRestore), this);
     }
     else if (this.Databases.SelectedItem != null)
     {
         WindowHelper.ShowDialog(new DatabasesOperationsDialog(Path.GetDirectoryName(SqlServerManager.Instance.GetDatabaseFileName(
                                                                                         this.Databases.SelectedItems[0].ToString(), ProfileManager.GetConnectionString()))
                                                               ), this);
     }
     else
     {
         WindowHelper.ShowDialog(new DatabasesOperationsDialog(), this);
     }
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        profileManager = new ProfileManager(this);

        ValEmail.ValidationGroup = ValidationGroup;
        reqHomePhone.ValidationGroup = ValidationGroup;
        reqPhone.ValidationGroup = ValidationGroup;

        reqSex.ValidationGroup = ValidationGroup;
        reqMaritalStatus.ValidationGroup = ValidationGroup;
        reqEducation.ValidationGroup = ValidationGroup;

        valCpf.ValidationGroup = ValidationGroup;
        valName.ValidationGroup = ValidationGroup;
        CpfValidator.ValidationGroup = ValidationGroup;
        CpfValidator2.ValidationGroup = ValidationGroup;
        btnSelect.ValidationGroup = ValidationGroup;
        Address.ValidationGroup = ValidationGroup;
    }
        public static void ImportPrinter(Printer printer, ProfileManager profileData, string profilePath)
        {
            var printerInfo = new PrinterInfo()
            {
                Name  = printer.Name,
                ID    = printer.Id.ToString(),
                Make  = printer.Make ?? "",
                Model = printer.Model ?? "",
            };

            profileData.Profiles.Add(printerInfo);

            var printerSettings = new PrinterSettings()
            {
                OemLayer = LoadOemLayer(printer)
            };

            printerSettings.OemLayer[SettingsKey.make]  = printerInfo.Make;
            printerSettings.OemLayer[SettingsKey.model] = printer.Model;

            LoadQualitySettings(printerSettings, printer);
            LoadMaterialSettings(printerSettings, printer);

            printerSettings.ID = printer.Id.ToString();

            printerSettings.UserLayer[SettingsKey.printer_name]             = printer.Name ?? "";
            printerSettings.UserLayer[SettingsKey.baud_rate]                = printer.BaudRate ?? "";
            printerSettings.UserLayer[SettingsKey.auto_connect]             = printer.AutoConnect ? "1" : "0";
            printerSettings.UserLayer[SettingsKey.default_material_presets] = printer.MaterialCollectionIds ?? "";
            printerSettings.UserLayer[SettingsKey.windows_driver]           = printer.DriverType ?? "";
            printerSettings.UserLayer[SettingsKey.device_token]             = printer.DeviceToken ?? "";
            printerSettings.UserLayer[SettingsKey.device_type]              = printer.DeviceType ?? "";

            if (string.IsNullOrEmpty(ProfileManager.Instance.LastProfileID))
            {
                ProfileManager.Instance.LastProfileID = printer.Id.ToString();
            }

            // Import macros from the database
            var allMacros = Datastore.Instance.dbSQLite.Query <CustomCommands>("SELECT * FROM CustomCommands WHERE PrinterId = " + printer.Id);

            printerSettings.Macros = allMacros.Select(macro => new GCodeMacro()
            {
                GCode        = macro.Value.Trim(),
                Name         = macro.Name,
                LastModified = macro.DateLastModified
            }).ToList();

            string query           = string.Format("SELECT * FROM PrinterSetting WHERE Name = 'PublishBedImage' and PrinterId = {0};", printer.Id);
            var    publishBedImage = Datastore.Instance.dbSQLite.Query <PrinterSetting>(query).FirstOrDefault();

            printerSettings.UserLayer[SettingsKey.publish_bed_image] = publishBedImage?.Value == "true" ? "1" : "0";

            // Print leveling
            var printLevelingData = PrintLevelingData.Create(
                printerSettings,
                printer.PrintLevelingJsonData,
                printer.PrintLevelingProbePositions);

            printerSettings.UserLayer[SettingsKey.print_leveling_data]    = JsonConvert.SerializeObject(printLevelingData);
            printerSettings.UserLayer[SettingsKey.print_leveling_enabled] = printer.DoPrintLeveling ? "true" : "false";

            printerSettings.UserLayer["manual_movement_speeds"] = printer.ManualMovementSpeeds;

            // make sure we clear the one time settings
            printerSettings.OemLayer[SettingsKey.spiral_vase]        = "";
            printerSettings.OemLayer[SettingsKey.bottom_clip_amount] = "";
            printerSettings.OemLayer[SettingsKey.layer_to_pause]     = "";

            // TODO: Where can we find CalibrationFiiles in the current model?
            //layeredProfile.SetActiveValue(""calibration_files"", ???);

            printerSettings.ID = printer.Id.ToString();

            printerSettings.DocumentVersion = PrinterSettings.LatestVersion;

            printerSettings.Helpers.SetComPort(printer.ComPort);

            printerSettings.Save();
        }
        private static void DoProcessSqlSyncQueue(string workingKey, byte[][] bufferBytes)
        {
            try
            {
                bool hasClear = false;
                foreach (var buffer in bufferBytes)
                {
                    DbBaseProvider dbProvider = null;
                    SqlStatement   statement  = null;
                    int            result     = 0;
                    try
                    {
                        statement  = ProtoBufUtils.Deserialize <SqlStatement>(buffer);
                        dbProvider = DbConnectionProvider.CreateDbProvider("", statement.ProviderType,
                                                                           statement.ConnectionString);
                        var paramList = ToSqlParameter(dbProvider, statement.Params);
                        result = dbProvider.ExecuteQuery(statement.CommandType, statement.CommandText, paramList);
                    }
                    catch (DbConnectionException connError)
                    {
                        TraceLog.WriteSqlError("SqlSync Error:{0}\r\nSql>>\r\n{1}", connError,
                                               statement != null ? statement.ToString() : "");
                        if (dbProvider != null)
                        {
                            //modify error: 40 - Could not open a connection to SQL Server
                            dbProvider.ClearAllPools();

                            //resend
                            var paramList = ToSqlParameter(dbProvider, statement.Params);
                            result = dbProvider.ExecuteQuery(statement.CommandType, statement.CommandText, paramList);
                        }
                        else
                        {
                            PutError(buffer, SqlSyncConnErrorQueueKey);
                        }
                    }
                    catch (Exception e)
                    {
                        TraceLog.WriteSqlError("SqlSync Error:{0}\r\nSql>>\r\n{1}", e,
                                               statement != null ? statement.ToString() : "");
                        PutError(buffer);
                        if (!hasClear && dbProvider != null)
                        {
                            //modify error: 40 - Could not open a connection to SQL Server
                            hasClear = true;
                            dbProvider.ClearAllPools();
                        }
                    }
                    finally
                    {
                        if (result > 0)
                        {
                            ProfileManager.ProcessSqlOfMessageQueueTimes(statement != null ? statement.Table : null);
                        }
                        else
                        {
                            ProfileManager.ProcessFailSqlOfMessageQueueTimes(statement != null ? statement.Table : null, 1);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("DoProcessSqlSyncQueue error:{0}\r\n", ex.Message, ex.StackTrace);
            }
        }
Beispiel #27
0
        /// <summary>
        /// Checks for known windows, buttons, etc and clicks them
        /// </summary>
        internal static void SafeCheckClickButtons()
        {
            try
            {
                if (!ZetaDia.IsInGame)
                {
                    SafeClick(BattleNetOK, ClickDelay.NoDelay, "Battle.Net OK", 1000, true);
                }

                // limit this thing running to once a second, to save CPU
                if (DateTime.UtcNow.Subtract(lastSafeClickCheck).TotalMilliseconds < 1000)
                {
                    return;
                }

                if (ZetaDia.IsLoadingWorld)
                {
                    return;
                }

                if (ZetaDia.IsPlayingCutscene)
                {
                    return;
                }

                if (!ZetaDia.Service.IsValid)
                {
                    return;
                }

                lastSafeClickCheck = DateTime.UtcNow;

                // Handled seperately out of game
                if (ZetaDia.IsInGame)
                {
                    SafeClick(PartyInviteOK, ClickDelay.Delay, "Party Invite", 750, true);
                }

                SafeClick(GenericOK, ClickDelay.Delay, "Generic OK", 0, true);
                SafeClick(BattleNetOK, ClickDelay.NoDelay, "Battle.Net OK", 1000, true);

                if (!ZetaDia.IsInGame)
                {
                    return;
                }

                if (ZetaDia.Me.IsDead)
                {
                    return;
                }

                if (!ZetaDia.Me.IsValid)
                {
                    return;
                }

                SafeClick(PartyLeaderBossAccept, ClickDelay.NoDelay, "Boss Portal Accept", 0, true);

                if (PartyFollowerBossAccept.IsValid && PartyFollowerBossAccept.IsVisible)
                {
                    SafeClick(PartyFollowerBossAccept, ClickDelay.NoDelay, "Boss Portal Accept", 0, true);
                    ProfileManager.Load(ProfileManager.CurrentProfile.Path);
                }

                SafeClick(MercenaryPartyOK, ClickDelay.NoDelay, "Mercenary Party OK");
                SafeClick(CustomizeBannerClose, ClickDelay.NoDelay, "Customize Banner Close");
            }
            catch (Exception ex)
            {
                Log.Info("Error clicking UI Button: " + ex);
            }
        }
Beispiel #28
0
        public void DoRightPanel(Rect canvas)
        {
            Rect labelRect = new Rect(canvas.x, canvas.y, canvas.width, Text.LineHeight);

            Widgets.Label(labelRect, "Applied profile: " + (ProfileManager.activeProfile?.ToString() ?? "-"));
            Rect nextApplyRect = new Rect(canvas.x, labelRect.yMax + 4f, canvas.width, Text.LineHeight);

            Widgets.Label(nextApplyRect, "Profile to be applied next startup: " + (ProfileManager.nextActiveProfile?.ToString() ?? "-"));
            Rect examineRect = new Rect(canvas.x, nextApplyRect.yMax + 4f, canvas.width, Text.LineHeight);

            Widgets.Label(examineRect, "Currently viewing: " + (ProfileManager.currentProfile?.ToString() ?? "-") + (ProfileManager.unsavedChanges ? " (unsaved changes)" : ""));

            bool canApplyNextProfile   = ProfileManager.currentProfile != null && ProfileManager.currentProfile != ProfileManager.nextActiveProfile;
            bool canUnapplyNextProfile = ProfileManager.nextActiveProfile != null;

            Rect applyRect       = new Rect(canvas.x, examineRect.yMax + 4f, 200f, Text.LineHeight);
            bool applyClicked    = Widgets.ButtonText(applyRect, "Apply Selected", drawBackground: canApplyNextProfile, doMouseoverSound: canApplyNextProfile, textColor: canApplyNextProfile ? Color.white : Color.grey, active: canApplyNextProfile);
            Rect unapplyRect     = new Rect(applyRect.xMax + Margin, examineRect.yMax + 4f, 200f, Text.LineHeight);
            bool unapplyClicked  = Widgets.ButtonText(unapplyRect, "Unapply Current", drawBackground: canUnapplyNextProfile, doMouseoverSound: canUnapplyNextProfile, textColor: canUnapplyNextProfile ? Color.white : Color.grey, active: canUnapplyNextProfile);
            Rect onlyErroredRect = new Rect(unapplyRect);

            onlyErroredRect.x = unapplyRect.xMax + Margin;
            bool oldErrored = onlyShowErrored;

            Widgets.CheckboxLabeled(onlyErroredRect, "Only show errors", ref onlyShowErrored);
            if (onlyShowErrored != oldErrored && ProfileManager.currentProfile != null)
            {
                ProfileManager.currentProfile.heightChanged = true;
            }
            Rect clearErrorsRect = new Rect(onlyErroredRect);

            clearErrorsRect.x = onlyErroredRect.xMax + Margin;
            bool clearErrorsClicked = Widgets.ButtonText(clearErrorsRect, "Delete all errors");

            if (clearErrorsClicked)
            {
                List <string> errorCommands = new List <string>();
                foreach (string command in ProfileManager.currentProfile?.loaded ?? Enumerable.Empty <string>())
                {
                    if (ProfileManager.currentProfile.HasError(command))
                    {
                        errorCommands.Add(command);
                    }
                }
                foreach (string error in errorCommands)
                {
                    ProfileManager.DeleteCommand(error);
                }
            }

            if (applyClicked && canApplyNextProfile)
            {
                ProfileManager.SetProfileToBeApplied();
                Dialog_MessageBox inform = new Dialog_MessageBox("Profile " + ProfileManager.nextActiveProfile + " will be applied after restart.");
                Find.WindowStack.Add(inform);
            }
            else if (unapplyClicked && canUnapplyNextProfile)
            {
                if (ProfileManager.activeProfile != null && ProfileManager.activeProfile == ProfileManager.nextActiveProfile)
                {
                    Dialog_MessageBox inform = new Dialog_MessageBox("Profile will be unapplied after restart.");
                    Find.WindowStack.Add(inform);
                }
                ProfileManager.UnsetProfileToBeApplied();
            }
            float totalTopHeight = labelRect.height + nextApplyRect.height + examineRect.height + applyRect.height + unapplyRect.height + 4f;
            Rect  outRect        = new Rect(canvas.x, unapplyRect.yMax + 4f, canvas.width - 20f, canvas.height - totalTopHeight);

            float profileHeight = ProfileManager.currentProfile != null?ProfileManager.currentProfile.GetHeight(outRect.width, onlyShowErrored) : 0f;

            float viewRectHeight = Mathf.Max(canvas.height - totalTopHeight, profileHeight);
            Rect  viewRect       = new Rect(canvas.x, unapplyRect.yMax + 4f, canvas.width - 36f, viewRectHeight);

            Widgets.DrawBoxSolid(outRect, Color.black);

            float curY  = viewRect.yMin;
            float oldY  = curY;
            int   index = 0;

            Widgets.BeginScrollView(outRect, ref detailScrollPosition, viewRect, true);
            using (List <string> .Enumerator? enumerator = ProfileManager.currentProfile?.loaded.GetEnumerator())
            {
                if (enumerator is List <string> .Enumerator iterate)
                {
                    bool noErrors = onlyShowErrored;
                    while (iterate.MoveNext())
                    {
                        string current          = iterate.Current;
                        string currentFormatted = Profile.FormatComand(current);
                        float  commandHeight    = ProfileManager.currentProfile.CommandHeight(current, outRect.width);
                        if (onlyShowErrored && !ProfileManager.currentProfile.HasError(current))
                        {
                            index++;
                            continue;
                        }
                        if (curY + commandHeight < detailScrollPosition.y || curY > detailScrollPosition.y + outRect.height + viewRect.yMin + commandHeight)
                        {
                            curY += commandHeight;
                            oldY  = curY;
                            index++;
                            continue;
                        }
                        Rect rowRect = new Rect(outRect.x, curY, outRect.width, commandHeight);
                        Widgets.Label(rowRect, currentFormatted);
                        curY += commandHeight;
                        //Widgets.Label(new Rect(outRect.x, curY, outRect.width, commandHeight), currentFormatted);
                        //Rect rowRect = new Rect(outRect.x, outRect.y + curHeight, canvas.width, commandHeight);
                        if (ProfileManager.currentProfile.HasError(current))
                        {
                            GUI.color = Color.yellow;
                            Widgets.DrawHighlightSelected(rowRect);
                        }
                        if (Mouse.IsOver(rowRect))
                        {
                            Widgets.DrawHighlight(rowRect);
                        }
                        GUI.color = Color.white;
                        if (ProfileManager.currentProfile == ProfileManager.activeProfile && Mouse.IsOver(rowRect) && Event.current.type == EventType.MouseDown && Event.current.button == 1)
                        {
                            int curIndex = index;
                            List <FloatMenuOption> options = new List <FloatMenuOption> {
                                new FloatMenuOption("Delete command", () => ProfileManager.DeleteCommand(curIndex), MenuOptionPriority.Default, null)
                            };
                            if (ProfileManager.activeProfile.HasError(current))
                            {
                                options.Add(new FloatMenuOption(ProfileManager.activeProfile.GetError(current), null));
                            }
                            Find.WindowStack.Add(new FloatMenu(options));
                            Event.current.Use();
                        }
                        oldY = curY;
                        index++;
                        noErrors = false;
                    }
                    if (ProfileManager.currentProfile?.loaded == null || ProfileManager.currentProfile.loaded.Count == 0)
                    {
                        Rect rowRect = new Rect(outRect.x, outRect.y, canvas.width, Text.LineHeight);
                        Widgets.Label(rowRect, "Empty profile");
                    }
                    else if (noErrors)
                    {
                        Rect rowRect = new Rect(outRect.x, outRect.y, canvas.width, Text.LineHeight);
                        Widgets.Label(rowRect, "No errors");
                    }
                }
                else
                {
                    Rect rowRect = new Rect(outRect.x, outRect.y, canvas.width, Text.LineHeight);
                    Widgets.Label(rowRect, "No profile selected");
                }
            }
            Widgets.EndScrollView();
        }
Beispiel #29
0
 private void _saveProfileButton_Click(object sender, EventArgs e)
 {
     ProfileManager.SaveProfiles();
 }
Beispiel #30
0
        private void updateOrderList()
        {
            orders.Clear();
            levelOrder.Clear();
            orders = OrderManager.loadOrders();

            dataGridView3.Rows.Clear();
            dataGridView3.DataSource = null;

            dataGridView3.ColumnCount      = 11;
            dataGridView3.Columns[0].Name  = "ID";
            dataGridView3.Columns[0].Width = 110;
            dataGridView3.Columns[1].Name  = "Criador";
            dataGridView3.Columns[2].Name  = "Valor";
            dataGridView3.Columns[3].Name  = "Mesa";
            dataGridView3.Columns[4].Name  = "Data Criado";
            dataGridView3.Columns[5].Name  = "Data Fechado";
            dataGridView3.Columns[6].Name  = "Ocorrência";
            dataGridView3.Columns[7].Name  = "Info Ocorrência";
            dataGridView3.Columns[8].Name  = "Detalhes de Pagamento";
            dataGridView3.Columns[9].Name  = "Conta Associada";
            dataGridView3.Columns[10].Name = "Tipo";

            int count = 1;

            foreach (Classes.Order o in orders)
            {
                if (checkBox1.Checked == o.DONE)
                {
                    levelOrder.Add(count, o);
                    count += 1;

                    ArrayList row = new ArrayList();
                    row.Add(o.ID + "");
                    row.Add(UserManager.getUserFirstName(o.CREATORUSERID));
                    row.Add(o.VALUE + "€");
                    String str;
                    int    table = o.TABLE;
                    if (table == -1)
                    {
                        str = "Nenhuma";
                    }
                    else
                    {
                        str = "" + table;
                    }
                    row.Add(str);
                    row.Add(o.DATECREATED);
                    row.Add(o.DATECLOSED);
                    String str2;
                    if (o.OCCURRENCE == true)
                    {
                        str2 = "Sim";
                    }
                    else
                    {
                        str2 = "Não";
                    }
                    row.Add(str2);
                    row.Add(o.OCCURRENCEINFO);
                    row.Add(o.PAYMENTDETAILS);
                    if (o.PEOPLEPROFILEID != null)
                    {
                        if (o.PEOPLEPROFILEID != "Nenhum")
                        {
                            Classes.Profile f = ProfileManager.getProfile(o.PEOPLEPROFILEID);
                            row.Add(f.FIRSTNAME + " " + f.LASTNAME);
                        }
                        else
                        {
                            row.Add("Nenhuma");
                        }
                    }
                    else
                    {
                        row.Add("-");
                    }
                    String str3;
                    if (o.ORDERTYPE == 0)
                    {
                        str3 = "Fatura";
                    }
                    else
                    {
                        str3 = "Mesas";
                    }
                    row.Add(str3);
                    dataGridView3.Rows.Add(row.ToArray());
                }
            }
            dataGridView3.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;

            DataGridViewButtonColumn btn = new DataGridViewButtonColumn();

            btn.HeaderText = "Produtos";
            btn.Name       = "produtos";
            btn.Text       = "Clica para ver";
            btn.UseColumnTextForButtonValue = true;
            dataGridView3.Columns.Add(btn);

            DataGridViewButtonColumn btn2 = new DataGridViewButtonColumn();

            btn2.HeaderText = "Eventos";
            btn2.Name       = "event";
            btn2.Text       = "Clica para ver";
            btn2.UseColumnTextForButtonValue = true;
            dataGridView3.Columns.Add(btn2);

            //checker

            foreach (DataGridViewRow rw in this.dataGridView3.Rows)
            {
                for (int i = 0; i < rw.Cells.Count; i++)
                {
                    if (rw.Cells[i].Value == null || rw.Cells[i].Value == DBNull.Value || String.IsNullOrWhiteSpace(rw.Cells[i].Value.ToString()))
                    {
                        rw.Cells[i].Value = "-";
                    }
                }
            }

            //checker

            foreach (DataGridViewRow rw in this.dataGridView1.Rows)
            {
                for (int i = 0; i < rw.Cells.Count; i++)
                {
                    if (rw.Cells[i].Value == null || rw.Cells[i].Value == DBNull.Value || String.IsNullOrWhiteSpace(rw.Cells[i].Value.ToString()))
                    {
                        rw.Cells[i].Value = "-";
                    }
                }
            }

            //checker

            foreach (DataGridViewRow rw in this.dataGridView2.Rows)
            {
                for (int i = 0; i < rw.Cells.Count; i++)
                {
                    if (rw.Cells[i].Value == null || rw.Cells[i].Value == DBNull.Value || String.IsNullOrWhiteSpace(rw.Cells[i].Value.ToString()))
                    {
                        rw.Cells[i].Value = "-";
                    }
                }
            }

            //checker

            foreach (DataGridViewRow rw in this.dataGridView4.Rows)
            {
                for (int i = 0; i < rw.Cells.Count; i++)
                {
                    if (rw.Cells[i].Value == null || rw.Cells[i].Value == DBNull.Value || String.IsNullOrWhiteSpace(rw.Cells[i].Value.ToString()))
                    {
                        rw.Cells[i].Value = "-";
                    }
                }
            }
        }
Beispiel #31
0
 public override void Initialize()
 {
     IocManager.RegisterByConvention(GetAssembly());
     ProfileManager.AddProfile <SafetyProfile>();
 }
 public void BtnTWLoginClicked()
 {
     ProfileManager.Login(Provider.TWITTER);
 }
 public void BtnGPLoginClicked()
 {
     ProfileManager.Login(Provider.GOOGLE);
 }
Beispiel #34
0
 /// <summary>
 /// default constructor
 /// initializes all the GUI components, initializes the internal objects and makes a default selection for all the GUI dropdowns
 /// In addition, all the jobs and profiles are being loaded from the harddisk
 /// </summary>
 public void constructMeGUIInfo()
 {
     muxProvider = new MuxProvider(this);
     this.codecs = new CodecManager();
     this.path = System.Windows.Forms.Application.StartupPath;
     this.jobUtil = new JobUtil(this);
     this.settings = new MeGUISettings();
     addPackages();
     this.profileManager = new ProfileManager(this.path);
     this.profileManager.LoadProfiles();
     this.mediaFileFactory = new MediaFileFactory(this);
     this.loadSettings();
     this.dialogManager = new DialogManager(this);
 }
Beispiel #35
0
        // Actually deal with a stuck - find an unstuck point etc.
        public static Vector3 UnstuckHandler(Vector3 vMyCurrentPosition, Vector3 vOriginalDestination)
        {
            // Update the last time we generated a path
            LastGeneratedStuckPosition = DateTime.Now;
            Navigator.Clear();

            // If we got stuck on a 2nd/3rd/4th "chained" anti-stuck route, then return the old move to target to keep movement of some kind going
            if (iTimesReachedStuckPoint > 0)
            {
                vSafeMovementLocation = Vector3.Zero;

                // Reset the path and allow a whole "New" unstuck generation next cycle
                iTimesReachedStuckPoint = 0;
                // And cancel unstucking for 9 seconds so DB can try to navigate
                iCancelUnstuckerForSeconds = (9 * iTotalAntiStuckAttempts);
                if (iCancelUnstuckerForSeconds < 20)
                {
                    iCancelUnstuckerForSeconds = 20;
                }
                _lastCancelledUnstucker = DateTime.Now;
                DbHelper.Log(TrinityLogLevel.Verbose, LogCategory.UserInformation, "Clearing old route and trying new path find to: " + LastMoveToTarget.ToString());
                Navigator.MoveTo(LastMoveToTarget, "original destination", false);
                return(vSafeMovementLocation);
            }
            // Only try an unstuck 10 times maximum in XXX period of time
            if (Vector3.Distance(vOriginalDestination, vMyCurrentPosition) >= 700f)
            {
                DbHelper.Log(TrinityLogLevel.Verbose, LogCategory.UserInformation, "You are " + Vector3.Distance(vOriginalDestination, vMyCurrentPosition).ToString() + " distance away from your destination.");
                DbHelper.Log(TrinityLogLevel.Verbose, LogCategory.UserInformation, "This is too far for the unstucker, and is likely a sign of ending up in the wrong map zone.");
                iTotalAntiStuckAttempts = 20;
            }
            // intell
            if (iTotalAntiStuckAttempts <= 15)
            {
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "Your bot got stuck! Trying to unstuck (attempt #{0} of 15 attempts) {1} {2} {3} {4}",
                             iTotalAntiStuckAttempts.ToString(),
                             "Act=\"" + ZetaDia.CurrentAct + "\"",
                             "questId=\"" + ZetaDia.CurrentQuest.QuestSNO + "\"",
                             "stepId=\"" + ZetaDia.CurrentQuest.StepId + "\"",
                             "worldId=\"" + ZetaDia.CurrentWorldId + "\""
                             );

                // check failed minimap markers
                MiniMapMarker.UpdateFailedMarkers();

                DbHelper.Log(TrinityLogLevel.Verbose, LogCategory.UserInformation, "(destination=" + vOriginalDestination.ToString() + ", which is " + Vector3.Distance(vOriginalDestination, vMyCurrentPosition).ToString() + " distance away)");

                vSafeMovementLocation = NavHelper.FindSafeZone(true, iTotalAntiStuckAttempts, vMyCurrentPosition);

                // Temporarily log stuff
                if (iTotalAntiStuckAttempts == 1 && GilesTrinity.Settings.Advanced.LogStuckLocation)
                {
                    FileStream LogStream = File.Open(Path.Combine(FileManager.LoggingPath, "Stucks - " + GilesTrinity.PlayerStatus.ActorClass.ToString() + ".log"), FileMode.Append, FileAccess.Write, FileShare.Read);
                    using (StreamWriter LogWriter = new StreamWriter(LogStream))
                    {
                        LogWriter.WriteLine(DateTime.Now.ToString() + ": Original Destination=" + LastMoveToTarget.ToString() + ". Current player position when stuck=" + vMyCurrentPosition.ToString());
                        LogWriter.WriteLine("Profile Name=" + ProfileManager.CurrentProfile.Name);
                    }
                    LogStream.Close();
                }
                // Now count up our stuck attempt generations
                iTotalAntiStuckAttempts++;
                return(vSafeMovementLocation);
            }

            iTimesReachedMaxUnstucks++;
            iTotalAntiStuckAttempts    = 1;
            vSafeMovementLocation      = Vector3.Zero;
            vOldPosition               = Vector3.Zero;
            iTimesReachedStuckPoint    = 0;
            TimeLastRecordedPosition   = DateTime.MinValue;
            LastGeneratedStuckPosition = DateTime.MinValue;
            // int iSafetyLoops = 0;
            if (iTimesReachedMaxUnstucks == 1)
            {
                Navigator.Clear();
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.Movement, "Anti-stuck measures now attempting to kickstart DB's path-finder into action.");
                Navigator.MoveTo(vOriginalDestination, "original destination", false);
                iCancelUnstuckerForSeconds = 40;
                _lastCancelledUnstucker    = DateTime.Now;
                return(vSafeMovementLocation);
            }
            if (iTimesReachedMaxUnstucks == 2)
            {
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.Movement, "Anti-stuck measures failed. Now attempting to reload current profile.");

                Navigator.Clear();

                ProfileManager.Load(Zeta.CommonBot.ProfileManager.CurrentProfile.Path);
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "Anti-stuck successfully reloaded current profile, DemonBuddy now navigating again.");
                return(vSafeMovementLocation);

                // Didn't make it to town, so skip instantly to the exit game system
                //iTimesReachedMaxUnstucks = 3;
            }
            // Exit the game and reload the profile
            if (GilesTrinity.Settings.Advanced.AllowRestartGame && DateTime.Now.Subtract(timeLastRestartedGame).TotalMinutes >= 15)
            {
                timeLastRestartedGame = DateTime.Now;
                string sUseProfile = GilesTrinity.FirstProfile;
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "Anti-stuck measures exiting current game.");
                // Load the first profile seen last run
                ProfileManager.Load(!string.IsNullOrEmpty(sUseProfile)
                                        ? sUseProfile
                                        : Zeta.CommonBot.ProfileManager.CurrentProfile.Path);
                Thread.Sleep(1000);
                GilesTrinity.ResetEverythingNewGame();
                ZetaDia.Service.Party.LeaveGame();
                // Wait for 10 second log out timer if not in town
                if (!ZetaDia.Me.IsInTown)
                {
                    Thread.Sleep(15000);
                }
            }
            else
            {
                DbHelper.Log(TrinityLogLevel.Normal, LogCategory.UserInformation, "Unstucking measures failed. Now stopping Trinity unstucker for 12 minutes to inactivity timers to kick in or DB to auto-fix.");
                iCancelUnstuckerForSeconds = 720;
                _lastCancelledUnstucker    = DateTime.Now;
                return(vSafeMovementLocation);
            }
            return(vSafeMovementLocation);
        }
Beispiel #36
0
        private void ImportStuff()
        {
            SiteData.CurrentSite = null;

            SiteData site = SiteData.CurrentSite;

            litMessage.Text = "<p>No Items Selected For Import</p>";
            string sMsg = "";

            if (chkSite.Checked || chkPages.Checked || chkPosts.Checked)
            {
                List <string> tags = site.GetTagList().Select(x => x.TagSlug.ToLower()).ToList();
                List <string> cats = site.GetCategoryList().Select(x => x.CategorySlug.ToLower()).ToList();

                exSite.TheTags.RemoveAll(x => tags.Contains(x.TagSlug.ToLower()));
                exSite.TheCategories.RemoveAll(x => cats.Contains(x.CategorySlug.ToLower()));

                sMsg += "<p>Imported Tags and Categories</p>";

                List <ContentTag> lstTag = (from l in exSite.TheTags.Distinct()
                                            select new ContentTag {
                    ContentTagID = Guid.NewGuid(),
                    SiteID = site.SiteID,
                    IsPublic = l.IsPublic,
                    TagSlug = l.TagSlug,
                    TagText = l.TagText
                }).ToList();

                List <ContentCategory> lstCat = (from l in exSite.TheCategories.Distinct()
                                                 select new ContentCategory {
                    ContentCategoryID = Guid.NewGuid(),
                    SiteID = site.SiteID,
                    IsPublic = l.IsPublic,
                    CategorySlug = l.CategorySlug,
                    CategoryText = l.CategoryText
                }).ToList();

                foreach (var v in lstTag)
                {
                    v.Save();
                }
                foreach (var v in lstCat)
                {
                    v.Save();
                }
            }
            SetMsg(sMsg);

            if (chkSnippet.Checked)
            {
                List <string> snippets = site.GetContentSnippetList().Select(x => x.ContentSnippetSlug.ToLower()).ToList();

                exSite.TheSnippets.RemoveAll(x => snippets.Contains(x.ContentSnippetSlug.ToLower()));

                sMsg += "<p>Imported Content Snippets</p>";

                List <ContentSnippet> lstSnip = (from l in exSite.TheSnippets.Distinct()
                                                 select new ContentSnippet {
                    SiteID = site.SiteID,
                    Root_ContentSnippetID = Guid.NewGuid(),
                    ContentSnippetID = Guid.NewGuid(),
                    CreateUserId = SecurityData.CurrentUserGuid,
                    CreateDate = site.Now,
                    EditUserId = SecurityData.CurrentUserGuid,
                    EditDate = site.Now,
                    RetireDate = l.RetireDate,
                    GoLiveDate = l.GoLiveDate,
                    ContentSnippetActive = l.ContentSnippetActive,
                    ContentBody = l.ContentBody,
                    ContentSnippetSlug = l.ContentSnippetSlug,
                    ContentSnippetName = l.ContentSnippetName
                }).ToList();

                foreach (var v in lstSnip)
                {
                    v.Save();
                }
            }
            SetMsg(sMsg);

            if (chkSite.Checked)
            {
                sMsg            += "<p>Updated Site Name</p>";
                site.SiteName    = exSite.TheSite.SiteName;
                site.SiteTagline = exSite.TheSite.SiteTagline;
                site.Save();
            }
            SetMsg(sMsg);

            if (!chkMapAuthor.Checked)
            {
                exSite.TheUsers = new List <SiteExportUser>();
            }

            //itterate author collection and find if in the system
            foreach (SiteExportUser seu in exSite.TheUsers)
            {
                seu.ImportUserID = Guid.Empty;

                MembershipUser usr = null;
                //attempt to find the user in the userbase
                usr = SecurityData.GetUserListByEmail(seu.Email).FirstOrDefault();
                if (usr != null)
                {
                    seu.ImportUserID = new Guid(usr.ProviderUserKey.ToString());
                }
                else
                {
                    usr = SecurityData.GetUserListByName(seu.Login).FirstOrDefault();
                    if (usr != null)
                    {
                        seu.ImportUserID = new Guid(usr.ProviderUserKey.ToString());
                    }
                }

                if (chkAuthors.Checked)
                {
                    if (seu.ImportUserID == Guid.Empty)
                    {
                        usr = Membership.CreateUser(seu.Login, ProfileManager.GenerateSimplePassword(), seu.Email);
                        Roles.AddUserToRole(seu.Login, SecurityData.CMSGroup_Users);
                        seu.ImportUserID = new Guid(usr.ProviderUserKey.ToString());
                    }

                    if (seu.ImportUserID != Guid.Empty)
                    {
                        ExtendedUserData ud = new ExtendedUserData(seu.ImportUserID);
                        if (ud != null)
                        {
                            if (!String.IsNullOrEmpty(seu.FirstName) || !String.IsNullOrEmpty(seu.LastName))
                            {
                                ud.FirstName = seu.FirstName;
                                ud.LastName  = seu.LastName;
                                ud.Save();
                            }
                        }
                        else
                        {
                            throw new Exception(String.Format("Could not find new user: {0} ({1})", seu.Login, seu.Email));
                        }
                    }
                }
            }

            if (chkPages.Checked)
            {
                sMsg        += "<p>Imported Pages</p>";
                sitePageList = site.GetFullSiteFileList();

                int iOrder = 0;

                SiteNav navHome = GetHomePage(site);

                if (navHome != null)
                {
                    iOrder = 2;
                }

                foreach (var impCP in (from c in exSite.ThePages
                                       where c.ThePage.ContentType == ContentPageType.PageType.ContentEntry
                                       orderby c.ThePage.NavOrder, c.ThePage.NavMenuText
                                       select c).ToList())
                {
                    ContentPage cp = impCP.ThePage;
                    cp.Root_ContentID = impCP.NewRootContentID;
                    cp.ContentID      = Guid.NewGuid();
                    cp.SiteID         = site.SiteID;
                    cp.ContentType    = ContentPageType.PageType.ContentEntry;
                    cp.EditDate       = SiteData.CurrentSite.Now;
                    cp.EditUserId     = exSite.FindImportUser(impCP.TheUser);
                    cp.CreateUserId   = exSite.FindImportUser(impCP.TheUser);
                    if (impCP.CreditUser != null)
                    {
                        cp.CreditUserId = exSite.FindImportUser(impCP.CreditUser);
                    }
                    cp.NavOrder     = iOrder;
                    cp.TemplateFile = ddlTemplatePage.SelectedValue;

                    ContentPageExport parent = (from c in exSite.ThePages
                                                where c.ThePage.ContentType == ContentPageType.PageType.ContentEntry &&
                                                c.ThePage.FileName.ToLower() == impCP.ParentFileName.ToLower()
                                                select c).FirstOrDefault();

                    BasicContentData navParent = null;
                    BasicContentData navData   = GetFileInfoFromList(site, cp.FileName);

                    if (parent != null)
                    {
                        cp.Parent_ContentID = parent.NewRootContentID;
                        navParent           = GetFileInfoFromList(site, parent.ThePage.FileName);
                    }

                    //if URL exists already, make this become a new version in the current series
                    if (navData != null)
                    {
                        cp.Root_ContentID = navData.Root_ContentID;

                        impCP.ThePage.RetireDate = navData.RetireDate;
                        impCP.ThePage.GoLiveDate = navData.GoLiveDate;

                        if (navData.NavOrder == 0)
                        {
                            cp.NavOrder = 0;
                        }
                    }
                    //preserve homepage
                    if (navHome != null && navHome.FileName.ToLower() == cp.FileName.ToLower())
                    {
                        cp.NavOrder = 0;
                    }
                    //if the file url in the upload has an existing ID, use that, not the ID from the queue
                    if (navParent != null)
                    {
                        cp.Parent_ContentID = navParent.Root_ContentID;
                    }

                    cp.RetireDate = impCP.ThePage.RetireDate;
                    cp.GoLiveDate = impCP.ThePage.GoLiveDate;

                    cp.SavePageEdit();

                    iOrder++;
                }
            }
            SetMsg(sMsg);

            if (chkPosts.Checked)
            {
                sMsg        += "<p>Imported Posts</p>";
                sitePageList = site.GetFullSiteFileList();

                List <ContentTag>      lstTags       = site.GetTagList();
                List <ContentCategory> lstCategories = site.GetCategoryList();

                foreach (var impCP in (from c in exSite.ThePages
                                       where c.ThePage.ContentType == ContentPageType.PageType.BlogEntry
                                       orderby c.ThePage.CreateDate
                                       select c).ToList())
                {
                    ContentPage cp = impCP.ThePage;
                    cp.Root_ContentID   = impCP.NewRootContentID;
                    cp.ContentID        = Guid.NewGuid();
                    cp.SiteID           = site.SiteID;
                    cp.Parent_ContentID = null;
                    cp.ContentType      = ContentPageType.PageType.BlogEntry;
                    cp.EditDate         = SiteData.CurrentSite.Now;
                    cp.EditUserId       = exSite.FindImportUser(impCP.TheUser);
                    cp.CreateUserId     = exSite.FindImportUser(impCP.TheUser);
                    if (impCP.CreditUser != null)
                    {
                        cp.CreditUserId = exSite.FindImportUser(impCP.CreditUser);
                    }
                    cp.NavOrder     = SiteData.BlogSortOrderNumber;
                    cp.TemplateFile = ddlTemplatePost.SelectedValue;

                    cp.ContentCategories = (from l in lstCategories
                                            join o in impCP.ThePage.ContentCategories on l.CategorySlug.ToLower() equals o.CategorySlug.ToLower()
                                            select l).Distinct().ToList();

                    cp.ContentTags = (from l in lstTags
                                      join o in impCP.ThePage.ContentTags on l.TagSlug.ToLower() equals o.TagSlug.ToLower()
                                      select l).Distinct().ToList();

                    BasicContentData navData = GetFileInfoFromList(site, cp.FileName);

                    //if URL exists already, make this become a new version in the current series
                    if (navData != null)
                    {
                        cp.Root_ContentID = navData.Root_ContentID;

                        impCP.ThePage.RetireDate = navData.RetireDate;
                        impCP.ThePage.GoLiveDate = navData.GoLiveDate;
                    }

                    cp.RetireDate = impCP.ThePage.RetireDate;
                    cp.GoLiveDate = impCP.ThePage.GoLiveDate;

                    cp.SavePageEdit();
                }

                using (ContentPageHelper cph = new ContentPageHelper()) {
                    //cph.BulkBlogFileNameUpdateFromDate(site.SiteID);
                    cph.ResolveDuplicateBlogURLs(site.SiteID);
                    cph.FixBlogNavOrder(site.SiteID);
                }
            }
            SetMsg(sMsg);

            if (chkComments.Checked)
            {
                sMsg        += "<p>Imported Comments</p>";
                sitePageList = site.GetFullSiteFileList();

                foreach (var impCP in (from c in exSite.TheComments
                                       orderby c.TheComment.CreateDate
                                       select c).ToList())
                {
                    int              iCommentCount = -1;
                    PostComment      pc            = impCP.TheComment;
                    BasicContentData navData       = GetFileInfoFromList(site, pc.FileName);
                    if (navData != null)
                    {
                        pc.Root_ContentID   = navData.Root_ContentID;
                        pc.ContentCommentID = Guid.NewGuid();

                        iCommentCount = PostComment.GetCommentCountByContent(site.SiteID, pc.Root_ContentID, pc.CreateDate, pc.CommenterIP, pc.PostCommentText);
                        if (iCommentCount < 1)
                        {
                            iCommentCount = PostComment.GetCommentCountByContent(site.SiteID, pc.Root_ContentID, pc.CreateDate, pc.CommenterIP);
                        }

                        if (iCommentCount < 1)
                        {
                            pc.Save();
                        }
                    }
                }
            }
            SetMsg(sMsg);

            BindData();
        }
Beispiel #37
0
 //--------------------------------starts
 void Awake()
 {
     instance = this;
 }
Beispiel #38
0
 static Nested()
 {
     Current = new ProfileManager();
 }
        public bool Load()
        {
            var absPath = AbsolutePath;

            if (IsLocal && !string.IsNullOrEmpty(ProfileManager.XmlLocation) &&
                ProfileManager.XmlLocation.Equals(absPath, StringComparison.CurrentCultureIgnoreCase))
            {
                return(false);
            }
            try
            {
                // Logging.Write("Cava: {0}", "something");

                PBLog.Debug(
                    "CAVAPB Loading Profile :{0}, previous profile was {1}",
                    Path,
                    ProfileManager.XmlLocation ?? "[No Profile]");
                if (string.IsNullOrEmpty(Path))
                {
                    ProfileManager.LoadEmpty();
                }
                else if (!IsLocal)
                {
                    if (Path.Contains("cavaprofessions"))
                    {
                        var pathtocavasettings = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                                        string.Format(@"Settings\CavaPlugin\Main-Settings.xml"));
                        var servertouse = Getdata(pathtocavasettings, "UseServer");
                        if (servertouse == "0")
                        {
                            Path = "https://cavaprofiles.net/index.php/profiles/profiles-list/" + Path;
                            var url = string.Format("https://cavaprofiles.net/index.php?user={0}&passw={1}",
                                                    Getdata(pathtocavasettings, "CpLogin"), Decrypt(Getdata(pathtocavasettings, "CpPassword")));
                            var request = (HttpWebRequest)WebRequest.Create(url);
                            request.AllowAutoRedirect = false;
                            request.CookieContainer   = new CookieContainer();
                            var response = (HttpWebResponse)request.GetResponse();
                            var cookies  = request.CookieContainer;
                            response.Close();
                            try
                            {
                                request =
                                    (HttpWebRequest)
                                    WebRequest.Create(Path + "/file");
                                request.AllowAutoRedirect = false;
                                request.CookieContainer   = cookies;
                                response = (HttpWebResponse)request.GetResponse();
                                var    data = response.GetResponseStream();
                                string html;
                                // ReSharper disable once AssignNullToNotNullAttribute
                                using (var sr = new StreamReader(data))
                                {
                                    html = sr.ReadToEnd();
                                }
                                response.Close();
                                var profilepath =
                                    new MemoryStream(
                                        Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(Convert.FromBase64String(html))));
                                ProfileManager.LoadNew(profilepath);
                            }
                            catch (Exception ex)
                            {
                                PBLog.Warn(
                                    "CAVAPB Does not have access to Profile {0}. Please check if you have Profession access Error code: {1}",
                                    Path, ex);
                                return(false);
                            }
                        }
                        else
                        {
                            Path = "https://cavaprofiles.org/index.php/cavapages/profiles/profiles-list/" + Path;
                            var url = string.Format("https://cavaprofiles.org/index.php?user={0}&passw={1}",
                                                    Getdata(pathtocavasettings, "CpLogin"), Decrypt(Getdata(pathtocavasettings, "CpPassword")));
                            var request = (HttpWebRequest)WebRequest.Create(url);
                            request.AllowAutoRedirect = false;
                            request.CookieContainer   = new CookieContainer();
                            var response = (HttpWebResponse)request.GetResponse();
                            var cookies  = request.CookieContainer;
                            response.Close();
                            try
                            {
                                request =
                                    (HttpWebRequest)
                                    WebRequest.Create(Path + "/file");
                                request.AllowAutoRedirect = false;
                                request.CookieContainer   = cookies;
                                response = (HttpWebResponse)request.GetResponse();
                                var    data = response.GetResponseStream();
                                string html;
                                // ReSharper disable once AssignNullToNotNullAttribute
                                using (var sr = new StreamReader(data))
                                {
                                    html = sr.ReadToEnd();
                                }
                                response.Close();
                                var profilepath =
                                    new MemoryStream(
                                        Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(Convert.FromBase64String(html))));
                                ProfileManager.LoadNew(profilepath);
                            }
                            catch (Exception ex)
                            {
                                PBLog.Warn(
                                    "CAVAPB Does not have access to Profile {0}. Please check if you have Profession access Error code: {1}",
                                    Path, ex);
                                return(false);
                            }
                        }
                    }
                    else
                    {
                        var req = WebRequest.Create(Path);
                        req.Proxy = null;
                        using (WebResponse res = req.GetResponse())
                        {
                            using (var stream = res.GetResponseStream())
                            {
                                ProfileManager.LoadNew(stream);
                            }
                        }
                    }
                }
                else if (File.Exists(absPath))
                {
                    ProfileManager.LoadNew(absPath);
                }
                else
                {
                    PBLog.Warn("{0}: {1}", "CAVAPB Unable to find profile", Path);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                PBLog.Warn("CAVAPB {0}", ex);
                return(false);
            }
            return(true);
        }
 public MatchController()
 {
     _profileManager = new ProfileManager();
     _matchManager   = new MatchManager();
 }
Beispiel #41
0
    public void Load()
    {
        //See path
        string path = Application.persistentDataPath + "/Profile";

        //Create first if haven't
        if (!File.Exists(path))
        {
            InitialData();
            Save();
        }
        else
        {
            //Load
            s_Instance = (ProfileManager)XmlManager.LoadInstanceAsXml("Profile", typeof(ProfileManager));
        }
    }
 public void goToMenu()
 {
     ProfileManager.goToMainMenu(MenuController.getCurrentPlayer());
 }
Beispiel #43
0
        private static void Main()
        {
            SetupWinForms();
            Cef.EnableHighDPISupport();

            WindowRestoreMessage = NativeMethods.RegisterWindowMessage("TweetDuckRestore");

            if (!FileUtils.CheckFolderWritePermission(StoragePath))
            {
                FormMessage.Warning("Permission Error", "TweetDuck does not have write permissions to the storage folder: " + StoragePath, FormMessage.OK);
                return;
            }

            if (Arguments.HasFlag(Arguments.ArgRestart))
            {
                LockManager.Result lockResult = LockManager.LockWait(10000);

                while (lockResult != LockManager.Result.Success)
                {
                    if (lockResult == LockManager.Result.Fail)
                    {
                        FormMessage.Error("TweetDuck Has Failed :(", "An unknown error occurred accessing the data folder. Please, make sure TweetDuck is not already running. If the problem persists, try restarting your system.", FormMessage.OK);
                        return;
                    }
                    else if (!FormMessage.Warning("TweetDuck Cannot Restart", "TweetDuck is taking too long to close.", FormMessage.Retry, FormMessage.Exit))
                    {
                        return;
                    }

                    lockResult = LockManager.LockWait(5000);
                }
            }
            else
            {
                LockManager.Result lockResult = LockManager.Lock();

                if (lockResult == LockManager.Result.HasProcess)
                {
                    if (!LockManager.RestoreLockingProcess() && FormMessage.Error("TweetDuck is Already Running", "Another instance of TweetDuck is already running.\nDo you want to close it?", FormMessage.Yes, FormMessage.No))
                    {
                        if (!LockManager.CloseLockingProcess())
                        {
                            FormMessage.Error("TweetDuck Has Failed :(", "Could not close the other process.", FormMessage.OK);
                            return;
                        }

                        lockResult = LockManager.Lock();
                    }
                    else
                    {
                        return;
                    }
                }

                if (lockResult != LockManager.Result.Success)
                {
                    FormMessage.Error("TweetDuck Has Failed :(", "An unknown error occurred accessing the data folder. Please, make sure TweetDuck is not already running. If the problem persists, try restarting your system.", FormMessage.OK);
                    return;
                }
            }

            Config.LoadAll();

            if (Arguments.HasFlag(Arguments.ArgImportCookies))
            {
                ProfileManager.ImportCookies();
            }
            else if (Arguments.HasFlag(Arguments.ArgDeleteCookies))
            {
                ProfileManager.DeleteCookies();
            }

            if (Arguments.HasFlag(Arguments.ArgUpdated))
            {
                WindowsUtils.TryDeleteFolderWhenAble(InstallerPath, 8000);
                WindowsUtils.TryDeleteFolderWhenAble(Path.Combine(StoragePath, "Service Worker"), 4000);
                BrowserCache.TryClearNow();
            }

            try{
                ResourceRequestHandlerBase.LoadResourceRewriteRules(Arguments.GetValue(Arguments.ArgFreeze));
            }catch (Exception e) {
                FormMessage.Error("Resource Freeze", "Error parsing resource rewrite rules: " + e.Message, FormMessage.OK);
                return;
            }

            BrowserCache.RefreshTimer();

            CefSharpSettings.WcfEnabled = false;
            CefSharpSettings.LegacyJavascriptBindingEnabled = true;

            CefSettings settings = new CefSettings {
                UserAgent             = BrowserUtils.UserAgentChrome,
                BrowserSubprocessPath = Path.Combine(ProgramPath, BrandName + ".Browser.exe"),
                CachePath             = StoragePath,
                UserDataPath          = CefDataPath,
                LogFile = ConsoleLogFilePath,
                #if !DEBUG
                LogSeverity = Arguments.HasFlag(Arguments.ArgLogging) ? LogSeverity.Info : LogSeverity.Disable
                #endif
            };

            var pluginScheme = new PluginSchemeFactory();

            settings.RegisterScheme(new CefCustomScheme {
                SchemeName           = PluginSchemeFactory.Name,
                IsStandard           = false,
                IsSecure             = true,
                IsCorsEnabled        = true,
                IsCSPBypassing       = true,
                SchemeHandlerFactory = pluginScheme
            });

            CommandLineArgs.ReadCefArguments(Config.User.CustomCefArgs).ToDictionary(settings.CefCommandLineArgs);
            BrowserUtils.SetupCefArgs(settings.CefCommandLineArgs);

            Cef.Initialize(settings, false, new BrowserProcessHandler());

            Win.Application.ApplicationExit += (sender, args) => ExitCleanup();

            FormBrowser mainForm = new FormBrowser(pluginScheme);

            Resources.Initialize(mainForm);
            Win.Application.Run(mainForm);

            if (mainForm.UpdateInstaller != null)
            {
                ExitCleanup();

                if (mainForm.UpdateInstaller.Launch())
                {
                    Win.Application.Exit();
                }
                else
                {
                    RestartWithArgsInternal(Arguments.GetCurrentClean());
                }
            }
        }
Beispiel #44
0
 private void SaveSettings()
 {
     ProfileManager.SaveChanges(Profile);
     DialogResult = true;
     Close();
 }
Beispiel #45
0
 public override void SetProfile(ProfileManager profile)
 {
     (Control as Control_Dota2AbilityLayer).SetProfile(profile);
 }
Beispiel #46
0
 private async void Change_RoR_Button_Click(object sender, RoutedEventArgs e)
 {
     await ProfileManager.ChooseRoRInstallFolder();
 }
Beispiel #47
0
        private void MoveDatabase(object sender, RoutedEventArgs e)
        {
            // var fileDialog = new OpenFileDialog
            // {
            // Title = "Select zip file of exported solution",
            // Multiselect = false,
            // DefaultExt = ".zip"
            // };
            if (this.Databases.SelectedItems.Count == 1)
            {
                string originalFolder = Path.GetDirectoryName(SqlServerManager.Instance.GetDatabaseFileName(this.Databases.SelectedItem.ToString(), ProfileManager.GetConnectionString()));
                var    fileDialog     = new System.Windows.Forms.FolderBrowserDialog()
                {
                    // Title = "Select folder for moving database"
                    SelectedPath = originalFolder
                };

                fileDialog.ShowDialog();
                string folderForRelocation = fileDialog.SelectedPath;

                if (folderForRelocation != originalFolder && !folderForRelocation.IsNullOrEmpty())
                {
                    string dbFileName = Path.GetFileName(SqlServerManager.Instance.GetDatabaseFileName(this.Databases.SelectedItem.ToString(), ProfileManager.GetConnectionString()));
                    string dbName     = this.Databases.SelectedItem.ToString();
                    var    connString = ProfileManager.GetConnectionString();
                    WindowHelper.LongRunningTask(() => this.MoveDatabase(folderForRelocation, originalFolder, dbName, dbFileName, connString), "Move database", this, "The database is being moved", null, true);
                }
                else
                {
                    WindowHelper.ShowMessage("Choose another folder.");
                }
            }
            else if (this.Databases.SelectedItems.Count > 1)
            {
                WindowHelper.ShowMessage("Please select only one database.");
            }
            else
            {
                WindowHelper.ShowMessage("Please select database.");
            }

            this.Refresh();
        }
Beispiel #48
0
 public HomeController()
 {
     _profileManager = new ProfileManager();
 }
        public CopyGuestProfilesToUser(Action afterProfilesImported)
            : base("Close", "Copy Printers to Account")
        {
            var scrollWindow = new ScrollableWidget()
            {
                AutoScroll = true,
                HAnchor    = HAnchor.ParentLeftRight,
                VAnchor    = VAnchor.ParentBottomTop,
            };

            scrollWindow.ScrollArea.HAnchor = HAnchor.ParentLeftRight;
            contentRow.AddChild(scrollWindow);

            var container = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                HAnchor = HAnchor.ParentLeftRight,
            };

            scrollWindow.AddChild(container);

            container.AddChild(new WrappedTextWidget(importMessage, textColor: ActiveTheme.Instance.PrimaryTextColor));

            var byCheckbox = new Dictionary <CheckBox, PrinterInfo>();

            var guestProfileManager = ProfileManager.LoadGuestDB();

            if (guestProfileManager?.Profiles.Count > 0)
            {
                container.AddChild(new TextWidget("Printers to Copy:".Localize())
                {
                    TextColor = ActiveTheme.Instance.PrimaryTextColor,
                    Margin    = new BorderDouble(0, 3, 0, 15),
                });

                foreach (var printerInfo in guestProfileManager.Profiles)
                {
                    var checkBox = new CheckBox(printerInfo.Name)
                    {
                        TextColor = ActiveTheme.Instance.PrimaryTextColor,
                        Margin    = new BorderDouble(5, 0, 0, 0),
                        HAnchor   = HAnchor.ParentLeft,
                        Checked   = true,
                    };
                    checkBoxes.Add(checkBox);
                    container.AddChild(checkBox);

                    byCheckbox[checkBox] = printerInfo;
                }
            }

            var syncButton = textImageButtonFactory.Generate("Copy".Localize());

            syncButton.Click += (s, e) =>
            {
                // do the import
                foreach (var checkBox in checkBoxes)
                {
                    if (checkBox.Checked)
                    {
                        // import the printer
                        var printerInfo = byCheckbox[checkBox];

                        string existingPath = Path.Combine(ProfileManager.GuestDBDirectory, printerInfo.ID + ProfileManager.ProfileExtension);;

                        ProfileManager.Instance.Profiles.Add(printerInfo);
                        guestProfileManager.Profiles.Remove(printerInfo);

                        // PrinterSettings files must actually be copied to the users profile directory
                        if (File.Exists(existingPath))
                        {
                            File.Copy(existingPath, printerInfo.ProfilePath);
                        }
                    }
                }

                guestProfileManager.Save();

                // close the window
                UiThread.RunOnIdle(() =>
                {
                    WizardWindow.Close();

                    // Call back into the original source
                    afterProfilesImported?.Invoke();
                });
            };

            CheckBox rememberChoice = new CheckBox("Don't remind me again".Localize(), ActiveTheme.Instance.PrimaryTextColor);

            contentRow.AddChild(rememberChoice);

            syncButton.Visible   = true;
            cancelButton.Visible = true;

            cancelButton.Click += (s, e) => UiThread.RunOnIdle(() =>
            {
                WizardWindow.Close();
                if (rememberChoice.Checked)
                {
                    afterProfilesImported?.Invoke();
                }
            });

            //Add buttons to buttonContainer
            footerRow.AddChild(syncButton);
            footerRow.AddChild(new HorizontalSpacer());
            footerRow.AddChild(cancelButton);

            footerRow.Visible = true;
        }
Beispiel #50
0
        /// <summary>
        /// default constructor
        /// initializes all the GUI components, initializes the internal objects and makes a default selection for all the GUI dropdowns
        /// In addition, all the jobs and profiles are being loaded from the harddisk
        /// </summary>
        public MeGUIInfo()
        {
            this.codecs = new CodecManager();
            this.gen = new CommandLineGenerator();
            this.path = System.Windows.Forms.Application.StartupPath;
            this.jobs = new Dictionary<string, Job>();
            this.skipJobs = new List<Job>();
            this.logBuilder = new StringBuilder();
            this.jobUtil = new JobUtil(this);
            this.settings = new MeGUISettings();
            this.calc = new BitrateCalculator();
            audioStreams = new AudioStream[2];
            audioStreams[0].path = "";
            audioStreams[0].output = "";
            audioStreams[0].settings = null;
            audioStreams[1].path = "";
            audioStreams[1].output = "";
            audioStreams[1].settings = null;
            this.videoEncoderProvider = new VideoEncoderProvider();
            this.audioEncoderProvider = new AudioEncoderProvider();
            this.profileManager = new ProfileManager(this.path);
            this.profileManager.LoadProfiles(videoProfile, audioProfile);
            this.loadSettings();
            this.loadJobs();
            this.dialogManager = new DialogManager(this);

            int index = menuItem1.MenuItems.Count;
            foreach (IMuxing muxer in PackageSystem.MuxerProviders.Values)
            {
                MenuItem newMenuItem = new MenuItem();
                newMenuItem.Text = muxer.Name;
                newMenuItem.Tag = muxer;
                newMenuItem.Index = index;
                index++;
                menuItem1.MenuItems.Add(newMenuItem);
                newMenuItem.Click += new System.EventHandler(this.mnuMuxer_Click);
            }
            index = mnuTools.MenuItems.Count;
            foreach (ITool tool in PackageSystem.Tools.Values)
            {
                MenuItem newMenuItem = new MenuItem();
                newMenuItem.Text = tool.Name;
                newMenuItem.Tag = tool;
                newMenuItem.Index = index;
                index++;
                mnuTools.MenuItems.Add(newMenuItem);
                newMenuItem.Click += new System.EventHandler(this.mnuTool_Click);
            }
            //MessageBox.Show(String.Join("|", this.GetType().Assembly.GetManifestResourceNames()));
            using (TextReader r = new StreamReader(this.GetType().Assembly.GetManifestResourceStream("MeGUI.Changelog.txt")))
            {
                mainForm.Changelog.Text = r.ReadToEnd();
            }
        }
Beispiel #51
0
        public CloneSettingsPage()
        {
            this.WindowTitle = "Import Printer".Localize();
            this.HeaderText  = "Import Printer".Localize() + ":";
            this.Name        = "Import Printer Window";

            var commonMargin = new BorderDouble(4, 2);

            contentRow.AddChild(new TextWidget("File Path".Localize(), pointSize: theme.DefaultFontSize, textColor: theme.TextColor));

            var pathRow = new FlowLayoutWidget()
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit,
            };

            contentRow.AddChild(pathRow);

            TextButton importButton = null;

            var textEditWidget = new MHTextEditWidget("", theme)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Center,
                Name    = "Profile Path Widget"
            };

            textEditWidget.ActualTextEditWidget.EditComplete += (s, e) =>
            {
                importButton.Enabled = !string.IsNullOrEmpty(textEditWidget.Text) &&
                                       File.Exists(textEditWidget.Text);
            };
            pathRow.AddChild(textEditWidget);

            // Must come before pathButton.Click definition
            RadioButton copyAndCalibrateOption = null;

            var openButton = new IconButton(StaticData.Instance.LoadIcon("fa-folder-open_16.png", 16, 16, theme.InvertIcons), theme)
            {
                BackgroundColor = theme.MinimalShade,
                Margin          = new BorderDouble(left: 8),
                Name            = "Open File Button"
            };

            openButton.Click += (s, e) =>
            {
                AggContext.FileDialogs.OpenFileDialog(
                    new OpenFileDialogParams("settings files|*.ini;*.printer;*.slice;*.fff"),
                    (result) =>
                {
                    if (!string.IsNullOrEmpty(result.FileName) &&
                        File.Exists(result.FileName))
                    {
                        textEditWidget.Text = result.FileName;
                    }

                    importButton.Enabled = !string.IsNullOrEmpty(textEditWidget.Text) &&
                                           File.Exists(textEditWidget.Text);
                });
            };
            pathRow.AddChild(openButton);

            var exactCloneColumn = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit,
                Margin  = new BorderDouble(top: 15)
            };

            contentRow.AddChild(exactCloneColumn);

            var siblingList = new List <GuiWidget>();

            var exactCloneOption = new RadioButton(new RadioButtonViewText("Exact clone".Localize(), theme.TextColor, fontSize: theme.DefaultFontSize))
            {
                HAnchor = HAnchor.Left,
                Margin  = commonMargin,
                Cursor  = Cursors.Hand,
                Name    = "Exact Clone Button",
                Checked = true,
                SiblingRadioButtonList = siblingList
            };

            exactCloneColumn.AddChild(exactCloneOption);
            siblingList.Add(exactCloneOption);

            var exactCloneSummary = new WrappedTextWidget("Copy all settings including hardware calibration".Localize(), pointSize: theme.DefaultFontSize - 1, textColor: theme.TextColor)
            {
                Margin = new BorderDouble(left: 30, bottom: 10, top: 4),
            };

            exactCloneColumn.AddChild(exactCloneSummary);

            var copySettingsColumn = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                HAnchor = HAnchor.Stretch,
                VAnchor = VAnchor.Fit
            };

            contentRow.AddChild(copySettingsColumn);

            // Create export button for each plugin
            copyAndCalibrateOption = new RadioButton(new RadioButtonViewText("Copy and recalibrate".Localize(), theme.TextColor, fontSize: theme.DefaultFontSize))
            {
                HAnchor = HAnchor.Left,
                Margin  = commonMargin,
                Cursor  = Cursors.Hand,
                Name    = "Copy and Calibrate Button",
                SiblingRadioButtonList = siblingList
            };
            copySettingsColumn.AddChild(copyAndCalibrateOption);
            siblingList.Add(copyAndCalibrateOption);

            string summary = string.Format(
                "{0}\r\n{1}",
                "Copy everything but hardware specific calibration settings".Localize(),
                "Ideal for cloning settings across different physical printers".Localize());

            var copySummary = new WrappedTextWidget(summary, pointSize: theme.DefaultFontSize - 1, textColor: theme.TextColor)
            {
                Margin = new BorderDouble(left: 30, bottom: 10, top: 4)
            };

            copySettingsColumn.AddChild(copySummary);

            importButton         = theme.CreateDialogButton("Import".Localize());
            importButton.Enabled = false;
            importButton.Name    = "Import Button";
            importButton.Click  += (s, e) =>
            {
                var filePath = textEditWidget.Text;

                if (ProfileManager.ImportFromExisting(filePath, copyAndCalibrateOption.Checked, out string importedName))
                {
                    string importPrinterSuccessMessage = "You have successfully imported a new printer profile. You can find '{0}' in your list of available printers.".Localize();
                    this.DialogWindow.ChangeToPage(
                        new ImportSucceededPage(
                            importPrinterSuccessMessage.FormatWith(importedName)));
                }
                else
                {
                    StyledMessageBox.ShowMessageBox(
                        string.Format(
                            "Oops! Settings file '{0}' did not contain any settings we could import.".Localize(),
                            Path.GetFileName(filePath)),
                        "Unable to Import".Localize());
                }
            };

            this.AddPageAction(importButton);
        }
Beispiel #52
0
        protected override void OnDestroy()
        {
            base.OnDestroy();

            // Clean up the objects created by EMDK manager
            if (profileManager != null)
            {
                profileManager = null;
            }

            if (emdkManager != null)
            {
                emdkManager.Release();
                emdkManager = null;
            }
        }
Beispiel #53
0
        /// <summary>
        /// Makes a deep copy of deck, duplicating all its cards,
        /// objects, and files, and sets it to be the current deck.
        /// </summary>
        /// <param name="otherDeck">Deck to copy</param>
        /// <returns>Deck object of copy of deck</returns>
        private eFlash.Data.Deck deepCopy(eFlash.Data.Deck otherDeck)
        {
            otherDeck.load();

            _deck = new eFlash.Data.Deck(-1, otherDeck.type, otherDeck.category, otherDeck.subcategory, otherDeck.title, ProfileManager.getCurrentUserID(), ProfileManager.getCurrentNetID());

            // Put deck entry into DB
            saveDeck();

            Card          newCard;
            eObject       newObj;
            CreatorObject newCreatorObj;

            foreach (Card curCard in otherDeck.cardList)
            {
                newCard = new Card(curCard.tag, ProfileManager.getCurrentUserID());

                // Add each card to the DB
                newCard.cardID = dbAccess.insertLocalDB.insertToCards(newCard);
                dbAccess.insertLocalDB.insertToCDRelations(deck.id, newCard.cardID);

                foreach (eObject curObj in curCard.eObjectList)
                {
                    newObj = new eObject(newCard.cardID, curObj.side, curObj.type, curObj.x1, curObj.x2, curObj.y1, curObj.y2, curObj.data);

                    // Make a CreatorObject to let it load up the data file
                    newCreatorObj = CreatorObject.newFromEObject(this, newObj, 0);
                    newCreatorObj.initialize();
                    newObj.actualFilename = newObj.generateFileName();

                    // Save each object to DB and file
                    saveObject(newCreatorObj);
                }
            }

            return(deck);
        }
Beispiel #54
0
 void Start()
 {
     profileManager = GameObject.Find("Navigator").GetComponent<ProfileManager>();
 }
Beispiel #55
0
 private void DatabaseQueryInputKeyUp(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.F5)
     {
         try
         {
             _QueryResults         = SqlServerManager.Instance.GetResultOfQueryExecution(ProfileManager.GetConnectionString(), databaseQueryInput.Text);
             dataGrid1.ItemsSource = _QueryResults.DefaultView;
         }
         catch (Exception ex)
         {
             WindowHelper.ShowMessage(ex.Message);
         }
     }
 }
        public CopyGuestProfilesToUser()
            : base("Close".Localize())
        {
            this.WindowTitle = "Copy Printers".Localize();
            this.HeaderText  = "Copy Printers to Account".Localize();

            var scrollWindow = new ScrollableWidget()
            {
                AutoScroll = true,
                HAnchor    = HAnchor.Stretch,
                VAnchor    = VAnchor.Stretch,
            };

            scrollWindow.ScrollArea.HAnchor = HAnchor.Stretch;
            contentRow.AddChild(scrollWindow);

            var container = new FlowLayoutWidget(FlowDirection.TopToBottom)
            {
                HAnchor = HAnchor.Stretch,
            };

            scrollWindow.AddChild(container);

            container.AddChild(new WrappedTextWidget(importMessage, textColor: ActiveTheme.Instance.PrimaryTextColor));

            var byCheckbox = new Dictionary <CheckBox, PrinterInfo>();

            var guest = ProfileManager.Load("guest");

            if (guest?.Profiles.Count > 0)
            {
                container.AddChild(new TextWidget("Printers to Copy".Localize() + ":")
                {
                    TextColor = ActiveTheme.Instance.PrimaryTextColor,
                    Margin    = new BorderDouble(0, 3, 0, 15),
                });

                foreach (var printerInfo in guest.Profiles)
                {
                    var checkBox = new CheckBox(printerInfo.Name)
                    {
                        TextColor = ActiveTheme.Instance.PrimaryTextColor,
                        Margin    = new BorderDouble(5, 0, 0, 0),
                        HAnchor   = HAnchor.Left,
                        Checked   = true,
                    };
                    checkBoxes.Add(checkBox);
                    container.AddChild(checkBox);

                    byCheckbox[checkBox] = printerInfo;
                }
            }

            var syncButton = theme.CreateDialogButton("Copy".Localize());

            syncButton.Name   = "CopyProfilesButton";
            syncButton.Click += (s, e) =>
            {
                // do the import
                foreach (var checkBox in checkBoxes)
                {
                    if (checkBox.Checked)
                    {
                        // import the printer
                        var printerInfo = byCheckbox[checkBox];

                        string existingPath = guest.ProfilePath(printerInfo);

                        // PrinterSettings files must actually be copied to the users profile directory
                        if (File.Exists(existingPath))
                        {
                            File.Copy(existingPath, printerInfo.ProfilePath);

                            // Only add if copy succeeds
                            ProfileManager.Instance.Profiles.Add(printerInfo);
                        }
                    }
                }

                guest.Save();

                // Close the window and update the PrintersImported flag
                UiThread.RunOnIdle(() =>
                {
                    DialogWindow.Close();

                    ProfileManager.Instance.PrintersImported = true;
                    ProfileManager.Instance.Save();
                });
            };

            rememberChoice = new CheckBox("Don't remind me again".Localize(), ActiveTheme.Instance.PrimaryTextColor);
            contentRow.AddChild(rememberChoice);

            syncButton.Visible = true;

            this.AddPageAction(syncButton);
        }
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(ProfileManager obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
        private IEnumerable <LayoutName> GetAvailableKeyboardNames(InputLanguage inputLanguage)
        {
            IEnumTfInputProcessorProfiles profilesEnumerator;
            string cultureName;
            var    culture = GetCultureInfoFromInputLanguage(inputLanguage, out cultureName);

            if (cultureName == UnknownLanguage)
            {
                Debug.WriteLine($"Error looking up keyboards with layout {inputLanguage.LayoutName} - invalid culture");
                yield break;
            }
            try
            {
                profilesEnumerator = ProfileManager.EnumProfiles((short)culture.KeyboardLayoutId);
            }
            catch
            {
                Debug.WriteLine($"Error looking up keyboards for language {culture.Name} - {(short)culture.KeyboardLayoutId}");
                yield break;
            }

            TfInputProcessorProfile[] profiles = new TfInputProcessorProfile[1];
            bool returnedLanguage = false;

            while (profilesEnumerator.Next(1, profiles) == 1)
            {
                // We only deal with keyboards; skip other input methods
                if (profiles[0].CatId != Guids.Consts.TfcatTipKeyboard)
                {
                    continue;
                }

                if ((profiles[0].Flags & TfIppFlags.Enabled) == 0)
                {
                    continue;
                }

                if (profiles[0].ProfileType == TfProfileType.Illegal)
                {
                    continue;
                }

                LayoutName layoutName;
                if (profiles[0].Hkl == IntPtr.Zero)
                {
                    try
                    {
                        layoutName = new LayoutName(inputLanguage.LayoutName,
                                                    ProcessorProfiles.GetLanguageProfileDescription(ref profiles[0].ClsId, profiles[0].LangId,
                                                                                                    ref profiles[0].GuidProfile), profiles[0]);
                    }
                    catch
                    {
                        // this exception has happened in testing, doesn't seem to be anything we can do
                        // except just ignore this keyboard
                        continue;
                    }
                    returnedLanguage = true;
                    yield return(layoutName);
                }
                else
                {
                    layoutName = WinKeyboardUtils.GetLayoutNameEx(profiles[0].Hkl);
                    if (layoutName.Name != string.Empty)
                    {
                        layoutName.Profile = profiles[0];
                        returnedLanguage   = true;
                        yield return(layoutName);
                    }
                }
            }
            if (!returnedLanguage)
            {
                yield return(new LayoutName(inputLanguage.LayoutName, culture.DisplayName));
            }
        }
 /// <summary>
 /// Deletes the user profile.
 /// </summary>
 /// <param name="userName">Name of the user.</param>
 protected virtual bool DeleteUserProfile(string userName)
 {
     return(ProfileManager.DeleteProfile(userName));
 }
Beispiel #60
0
 void Start()
 {
     this.interaction = new Interaction(this);
     this.profileManager = new ProfileManager(this);
 }