/// <summary>
        /// Checks for the updated information for the given mod.
        /// </summary>
        /// <param name="mod">The mod for which to check for updates.</param>
        /// <returns>The latest information available for the given mod,
        /// or <c>null</c> if no information is available.</returns>
        private IModInfo CheckForUpdate(IMod mod)
        {
            IModInfo modInfo = null;

            if (!ModRepository.IsOffline)
            {
                //get mod info
                for (var i = 0; i <= 2; i++)
                {
                    if (!string.IsNullOrEmpty(mod.Id))
                    {
                        modInfo = ModRepository.GetModInfo(mod.Id);
                    }

                    if (modInfo == null)
                    {
                        modInfo = ModRepository.GetModInfoForFile(mod.Filename);
                    }

                    if (modInfo != null)
                    {
                        break;
                    }

                    Thread.Sleep(1000);
                }
            }

            return(modInfo);
        }
Exemple #2
0
        private int GetClientId()
        {
            var acctName = RouteData.Values["account"] as string;

            if (String.IsNullOrWhiteSpace(acctName))
            {
                throw new ArgumentException("Conta não encontrada.");
            }

            var acct = ModRepository.GetAccountByName(acctName);

            if (acct == null)
            {
                throw new ArgumentException("Conta não encontrada.");
            }

            using (var db = new CloudTalkModuleEntities()) {
                var entry = db.StaticModule_CloudTalk.FirstOrDefault(c => c.AccountId == acct.Id);

                if (entry == null)
                {
                    throw new ArgumentException("Dados de atendimento não encontrados.");
                }

                return(entry.CloudTalkId);
            }
        }
        /// <summary>
        /// Attempt to login to the mod repository.
        /// </summary>
        /// <returns><c>true</c> if the login was successful;
        /// <c>false</c> otherwise.</returns>
        public bool Login()
        {
            ErrorMessage = null;
            EnvironmentInfo.Settings.RepositoryUsernames[ModRepository.Id] = Username;
            Dictionary <string, string> dicAuthTokens = null;

            try
            {
                if (!ModRepository.Login(Username, Password, out dicAuthTokens))
                {
                    ErrorMessage = "Invalid login. Either your firewall is blocking NMM or the login server is down.";
                    return(false);
                }
            }
            catch (RepositoryUnavailableException e)
            {
                ErrorMessage = e.Message;
                return(false);
            }
            if (StayLoggedIn)
            {
                EnvironmentInfo.Settings.RepositoryAuthenticationTokens[ModRepository.Id] = new KeyedSettings <string>(dicAuthTokens);
            }
            else
            {
                EnvironmentInfo.Settings.RepositoryAuthenticationTokens.Remove(ModRepository.Id);
            }
            EnvironmentInfo.Settings.Save();
            return(true);
        }
Exemple #4
0
        /// <summary>
        /// Attempt to login to the mod repository.
        /// </summary>
        /// <returns><c>true</c> if the login was successful;
        /// <c>false</c> otherwise.</returns>
        public bool Login()
        {
            ErrorMessage = null;
            EnvironmentInfo.Settings.RepositoryUsernames[ModRepository.Id] = Username;
            Dictionary <string, string> dicAuthTokens = null;

            try
            {
                if (!ModRepository.Login(Username, Password, out dicAuthTokens))
                {
                    ErrorMessage = "The given login information is invalid.";
                    return(false);
                }
            }
            catch (RepositoryUnavailableException e)
            {
                ErrorMessage = e.Message;
                return(false);
            }
            if (StayLoggedIn)
            {
                EnvironmentInfo.Settings.RepositoryAuthenticationTokens[ModRepository.Id] = new KeyedSettings <string>(dicAuthTokens);
            }
            else
            {
                EnvironmentInfo.Settings.RepositoryAuthenticationTokens.Remove(ModRepository.Id);
            }
            EnvironmentInfo.Settings.Save();
            return(true);
        }
        public ActionResult Edit(int id)
        {
            var modToEdit = ModRepository.GetModuleById(id,
                                                        m => m.Fields.Include <Field, FieldDataType>(f => f.FieldDataType),
                                                        m => m.Fields.Include <Field, FieldMetadata>(f => f.Metadata));

            if (modToEdit == null)
            {
                TempData["Message"] = "Módulo não encontrado.";
                return(RedirectToAction("Index", "Home"));
            }

            ModulesViewModel model = new ModulesViewModel()
            {
                Id           = modToEdit.Id,
                DisplayName  = modToEdit.DisplayName,
                DataTypeList = GetDataTypeList(),
                Type         = modToEdit.ModuleType
            };

            model.Fields.AddRange(
                modToEdit.Fields.ToList().Select(f => new ModuleField {
                ID               = f.ID,
                IsRequired       = f.IsRequired,
                IsReadOnly       = f.IsReadOnly,
                DataType         = f.FieldDataType.Name,
                FieldDisplayName = f.DisplayName,
                ShowInListMode   = f.ShowInListMode,
                Metadata         = f.Metadata.FirstOrDefault() != null ? f.Metadata.FirstOrDefault().Value : null                 // *1
            }));

            // *1 TODO: Despite the field-metadata relationship is 1-N, we're passing only the first entry to the view for now.
            // This will probably change in the future when we have multiple metadata entries for each field.
            return(View(model));
        }
Exemple #6
0
        public ActionResult ListAccounts()
        {
            var model = new Dictionary <int, string>();

            // sysadmin can see all system users
            if (Roles.IsUserInRole("sysadmin"))
            {
                foreach (var acct in ModRepository.GetAllAccounts())
                {
                    model.Add(acct.Id, acct.Name);
                }
            }
            else if (Roles.IsUserInRole("administrators"))
            {
                var userId   = (Guid)Membership.GetUser().ProviderUserKey;
                var accounts = ModRepository.GetUserAccounts(userId);

                foreach (var acct in accounts)
                {
                    model.Add(acct.Id, acct.Name);
                }
            }

            return(View(model));
        }
Exemple #7
0
        public ActionResult EditAccount(string id)
        {
            Account acct = null;

            if (Roles.IsUserInRole("sysadmin"))
            {
                acct = ModRepository.GetAccountByName(id);
            }
            else if (Roles.IsUserInRole("administrators"))
            {
                var userId = (Guid)Membership.GetUser().ProviderUserKey;
                acct = ModRepository.GetUserAccounts(userId).FirstOrDefault(acc => acc.SubdomainName == id);
            }

            if (acct == null)
            {
                TempData["Message"] = "Conta não encontrada.";
                return(RedirectToAction("Index", "Home"));
            }

            return(View(new AccountViewModel {
                Id = acct.Id,
                Logo = acct.Logo,
                Name = acct.Name,
                Subdomain = acct.SubdomainName,
                Users = acct.Users.Select(u => u.UserName).ToList()
            }));
        }
Exemple #8
0
        public ActionResult EditAccount(AccountViewModel acct)
        {
            if (!ModelState.IsValid)
            {
                return(View(acct));
            }

            var dbAcct = ModRepository.GetAccountById(acct.Id);

            if (dbAcct == null)
            {
                TempData["Message"] = "Conta não encontrada.";
                return(RedirectToAction("Index", "Home"));
            }

            dbAcct.Name          = acct.Name;
            dbAcct.SubdomainName = acct.Subdomain;

            if (Request.Files.Count > 0 &&
                Request.Files[0].ContentLength > 0)
            {
                var user    = Membership.GetUser() as UACUser;
                var imgInfo = user.SaveImage(Request.Files[0]);
                dbAcct.Logo = imgInfo.FullRelativePath;
            }

            ModRepository.Save();

            TempData["Message"] = "Dados salvos com sucesso!";
            return(RedirectToAction("ListAccounts"));
        }
Exemple #9
0
        public ActionResult Login()
        {
            var subdomain = Request.Url.GetSubDomain();

            if (!String.IsNullOrWhiteSpace(subdomain) && subdomain != "www")
            {
                var acct = ModRepository.GetAccountByName(subdomain);

                if (acct == null)
                {
                    ModelState.AddModelError("_FORM", "Conta não encontrada.");
                    return(View("Login"));
                }

                if (!String.IsNullOrWhiteSpace(acct.Logo))
                {
                    ViewData["accountlogo"] = Url.Content(acct.Logo);
                }
            }

            if (TempData["_FORM"] != null)
            {
                ModelState.AddModelError("_FORM", TempData["_FORM"].ToString());
            }

            return(View("Login"));
        }
Exemple #10
0
        /// <summary>
        /// Checks for the updated information for the given mod.
        /// </summary>
        /// <param name="p_modMod">The mod for which to check for updates.</param>
        /// <returns>The lastest informaiton available for the given mod,
        /// or <c>null</c> if no information is available.</returns>
        private IModInfo CheckForUpdate(IMod p_modMod)
        {
            IModInfo mifInfo = null;

            try
            {
                if (!ModRepository.IsOffline)
                {
                    //get mod info
                    for (int i = 0; i <= 2; i++)
                    {
                        if (!String.IsNullOrEmpty(p_modMod.Id))
                        {
                            mifInfo = ModRepository.GetModInfo(p_modMod.Id);
                        }
                        if (mifInfo == null)
                        {
                            mifInfo = ModRepository.GetModInfoForFile(p_modMod.Filename);
                        }
                        if (mifInfo != null)
                        {
                            break;
                        }

                        Thread.Sleep(1000);
                    }
                    if (mifInfo == null)
                    {
                        string strSearchTerms = p_modMod.ModName;
                        if (String.IsNullOrEmpty(strSearchTerms))
                        {
                            strSearchTerms = Path.GetFileNameWithoutExtension(p_modMod.Filename).Replace("_", " ").Replace("-", " ");
                        }
                        //use heuristics to find info
                        if (!String.IsNullOrEmpty(strSearchTerms))
                        {
                            string[] strTerms        = strSearchTerms.Split(' ', '-', '_');
                            string   strSearchString = strTerms.OrderByDescending(s => s.Length).FirstOrDefault();
                            string   strAuthor       = p_modMod.Author;
                            if (!String.IsNullOrEmpty(strSearchString) && !String.IsNullOrEmpty(strAuthor) && (strAuthor.Length >= 3))
                            {
                                mifInfo = ModRepository.FindMods(strSearchString, strAuthor, true).FirstOrDefault();
                            }
                        }
                    }
                }
                if (mifInfo == null)
                {
                    return(null);
                }
                return(mifInfo);
            }
            catch (RepositoryUnavailableException)
            {
                //the repository is not available, so don't bother
                return(null);
            }
        }
Exemple #11
0
        /// <summary>
        /// Toggles the endorsement for the given mod.
        /// </summary>
        /// <param name="p_modMod">The mod to endorse/unendorse.</param>
        public void ToggleModEndorsement(IMod p_modMod)
        {
            bool?   booEndorsementState = ModRepository.ToggleEndorsement(p_modMod.Id, p_modMod.IsEndorsed == true ? 1 : (p_modMod.IsEndorsed == false ? -1 : 0));
            ModInfo mifUpdatedMod       = new ModInfo(p_modMod);

            mifUpdatedMod.IsEndorsed           = booEndorsementState;
            mifUpdatedMod.HumanReadableVersion = String.IsNullOrEmpty(mifUpdatedMod.LastKnownVersion) ? mifUpdatedMod.HumanReadableVersion : mifUpdatedMod.LastKnownVersion;
            AddNewVersionNumberForMod(p_modMod, (IModInfo)mifUpdatedMod);
            p_modMod.UpdateInfo((IModInfo)mifUpdatedMod, false);
        }
Exemple #12
0
        public ActionResult Create(ModulesViewModel _model)
        {
            if (!ModelState.IsValid)
            {
                _model.DataTypeList = GetDataTypeList();
                return(View(_model));
            }

            if (_model.Fields.Count(f => f.ShowInListMode) == 0)
            {
                TempData["Message"] = "Pelo menos um dos campos deve ser visível na listagem.";
                _model.DataTypeList = GetDataTypeList();
                return(View(_model));
            }

            // retrieve the current account name and associate with the newly created module
            var acctName = RouteData.Values["account"] as string;

            if (String.IsNullOrWhiteSpace(acctName))
            {
                TempData["Message"] = "Conta não encontrada.";
                return(View(_model));
            }

            Module newModule = new Module()
            {
                DisplayName = _model.DisplayName,
                ModuleName  = _model.DisplayName.EscapeName(),
                User        = ModRepository.GetUserByName(Membership.GetUser().UserName), // associate the module with the current logged in user
                Account     = ModRepository.GetAccountByName(acctName),
                ModuleType  = _model.Type
            };

            _model.Fields.ToList().ForEach(f => {
                var newField = new Field {
                    DisplayName    = f.FieldDisplayName,
                    FieldName      = f.FieldDisplayName.EscapeName(),
                    FieldDataType  = ModRepository.GetDataTypeByName(f.DataType),
                    IsReadOnly     = f.IsReadOnly,
                    IsRequired     = f.IsRequired,
                    ShowInListMode = f.ShowInListMode
                };

                if (f.Metadata != null)
                {
                    newField.AddMetadata(f.Metadata);
                }
                newModule.Fields.Add(newField);
            });

            ModRepository.AddModule(newModule);

            TempData["Message"] = "Módulo salvo com sucesso.";
            return(RedirectToAction("Index", "Home"));
        }
Exemple #13
0
        private SelectList GetDataTypeList()
        {
            var dataTypes = ModRepository.GetFieldDataTypes()
                            .OrderBy(f => f.FriendlyName)
                            .Select(f => new {
                Name  = f.FriendlyName,
                Value = f.Name
            });

            return(new SelectList(dataTypes, "Value", "Name", null));
        }
Exemple #14
0
    public string LoadMainMenu()
    {
        ModRepository modRepo = new ModRepository();
        StringBuilder str     = new StringBuilder();

        foreach (var item in modRepo.GetModByBoxCode("MainMenu"))
        {
            string active = item.Mod_ID == modid ? "active" : "";
            str.Append("<li><a class=\"" + active + "\" href=\"/" + item.Mod_Url + ".htm\">" + item.Mod_Name + "</a></li>");
        }
        return(str.ToString());
    }
Exemple #15
0
    public string GetAboutMenu()
    {
        ModRepository modRepo = new ModRepository();
        StringBuilder str     = new StringBuilder();

        str.Append("<ul>");
        foreach (var item in modRepo.GetModByBoxCode("ve-cong-ty-2"))
        {
            str.Append("<li><a href=\"/" + item.Mod_Url + ".htm\">" + item.Mod_Name + "</a></li>");
        }
        str.Append("</ul>");
        return(str.ToString());
    }
        static void Main(string[] args)
        {
            var baseCulture   = "english";
            var targetCulture = "german";

            if (args.Length >= 1)
            {
                baseCulture = args[0];
            }

            if (args.Length >= 2)
            {
                targetCulture = args[1];
            }

            var basePath = ".";

            if (args.Length >= 3)
            {
                basePath = args[2];
            }

            var modRepository = new ModRepository(@basePath);

            var modsWithoutGerman = modRepository
                                    .GetAllMods()
                                    .Where(it =>
                                           it.LocalizationFiles.Count > 0 &&
                                           !it.LocalizationFiles.Any(lf =>
                                                                     lf.FileName.Contains(targetCulture, StringComparison.OrdinalIgnoreCase)));

            var zip = new ZipService();

            foreach (var mod in modsWithoutGerman)
            {
                System.Console.WriteLine("--------------");
                System.Console.WriteLine($"{mod.ID} - {mod.Name}");
                foreach (var localizationFile in mod.LocalizationFiles)
                {
                    System.Console.WriteLine($"\t{localizationFile.FileName}");
                }

                var tempFolder = Path.Combine(Path.GetDirectoryName(mod.Location), "temp");
                zip.Extract(mod.Location, tempFolder);
                new TranslationService().Multiply(tempFolder, baseCulture, new [] { targetCulture });
                zip.Compress(tempFolder, mod.Location, ZipService.CompressMode.Backup);

                Directory.Delete(tempFolder, true);
                System.Console.WriteLine("--------------");
            }
        }
Exemple #17
0
        public ActionResult DeleteAccount(int id)
        {
            try {
                ModRepository.DeleteAccount(id);
                ModRepository.Save();
            }
            catch (Exception e) {
                TempData["Message"] = "Erro ao remover a conta: " + e.Message;
                return(RedirectToAction("ListAccounts"));
            }

            TempData["Message"] = "Conta removida com sucesso.";
            return(RedirectToAction("ListAccounts"));
        }
Exemple #18
0
        public ActionResult Query(int moduleid, string modulename, int?id)
        {
            var doverApi = new ModuleApi(ModRepository);

            var module = ModRepository.GetModuleById(moduleid,
                                                     m => m.Fields.Include <Field, FieldDataType>(f => f.FieldDataType),
                                                     m => m.Rows.Include <Row, Cell>(r => r.Cells));

            var data = doverApi.GetModuleData(module, id, Request.QueryString);

            ModRepository.IncrementModuleRequestCount(module.Id);

            return(View(data));
        }
 /// <summary>
 /// Logs out of all mod repositories.
 /// </summary>
 private void Logout()
 {
     lock (ModRepository)
         if (ModRepository.IsOffline)
         {
             ModManager.Login();
         }
         else
         {
             ModRepository.Logout();
             ModManager.Logout();
             EnvironmentInfo.Settings.RepositoryAuthenticationTokens.Remove(ModRepository.Id);
             EnvironmentInfo.Settings.Save();
         }
 }
Exemple #20
0
        /// <summary>
        /// The method that is called to start the backgound task.
        /// </summary>
        /// <param name="args">Arguments to for the task execution.</param>
        /// <returns>Always <c>null</c>.</returns>
        protected override object DoWork(object[] args)
        {
            var ModList    = new List <string>();
            var ModCheck   = new List <IMod>();
            var camConfirm = (ConfirmActionMethod)args[0];

            var ModInstallDirectory = CurrentGameModeModDirectory.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;

            OverallMessage          = "Updating categories info: setup search..";
            OverallProgress         = 0;
            OverallProgressStepSize = 1;
            ShowItemProgress        = false;
            OverallProgressMaximum  = 2;

            OverallMessage = "Retrieving the categories list... 1/2";
            StepOverallProgress();
            try
            {
                var lstCategories = ModRepository.GetCategories(ModRepository.GameDomainName);

                var i = 1;

                if (lstCategories.Count > 0)
                {
                    foreach (var category in lstCategories)
                    {
                        OverallMessage = "Saving the categories list... " + i + "/" + lstCategories.Count();
                        StepOverallProgress();

                        var modCategory = CategoryManager.FindCategory(category.Id);
                        if (modCategory != null && modCategory.Id != 0)
                        {
                            CategoryManager.RenameCategory(modCategory.Id, category.Name);
                        }
                        else
                        {
                            CategoryManager.AddCategory(new ModCategory(category.Id, category.Name, category.Name));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }

            return(null);
        }
Exemple #21
0
        public ActionResult Delete(int id)
        {
            var modToDelete = ModRepository.GetModuleById(id);

            if (modToDelete == null)
            {
                TempData["Message"] = "Módulo não encontrado.";
                return(RedirectToAction("Index", "Home"));
            }

            ModRepository.DeleteObject(modToDelete);
            ModRepository.Save();

            TempData["Message"] = "Módulo removido com sucesso.";
            return(RedirectToAction("Index", "Home"));
        }
Exemple #22
0
        public ActionResult PersistRowOrder(FormCollection form)
        {
            int i = 0;

            foreach (string s in form["ids[]"].Split(",".ToCharArray()))
            {
                int id;
                if (Int32.TryParse(s, out id))
                {
                    var row = ModRepository.GetRowById(id);
                    row.SortIndex = i++;
                }
            }

            ModRepository.Save();

            return(Json(new { }));
        }
Exemple #23
0
        public ActionResult Delete(int id)
        {
            Row row = ModRepository.GetRowById(id);

            if (row == null)
            {
                TempData["Message"] = "Registro não encontrado.";

                return(RedirectToAction("List"));
            }

            ModRepository.DeleteObject(row);

            ModRepository.Save();

            TempData["Message"] = "Registro removido com sucesso.";
            return(RedirectToAction("List"));
        }
        /// <summary>
        /// Toggles the endorsement for the given mod.
        /// </summary>
        /// <param name="mod">The mod to endorse/unendorse.</param>
        public void ToggleModEndorsement(IMod mod)
        {
            var booEndorsementState = ModRepository.ToggleEndorsement(mod.Id, mod.IsEndorsed == true ? 1 : mod.IsEndorsed == false ? -1 : 0, mod.HumanReadableVersion);

            if (booEndorsementState == null)
            {
                MessageBox.Show($"Could not change endorsement status of \"{mod.ModName}\".", "Endorsement toggle error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            var mifUpdatedMod = new ModInfo(mod)
            {
                IsEndorsed = booEndorsementState
            };

            mifUpdatedMod.HumanReadableVersion = string.IsNullOrEmpty(mifUpdatedMod.LastKnownVersion) ? mifUpdatedMod.HumanReadableVersion : mifUpdatedMod.LastKnownVersion;
            AddNewVersionNumberForMod(mod, mifUpdatedMod);
            mod.UpdateInfo(mifUpdatedMod, false);
        }
Exemple #25
0
        public ActionResult module(int moduleid, DynamicModuleViewModel _entryToCreate)
        {
            var doverApi     = new ModuleApi(ModRepository);
            var module       = ModRepository.GetModuleById(moduleid, m => m.Fields);
            var result       = String.Empty;
            var filteredList = new DynamicModuleFieldList();

            filteredList.AddRange(_entryToCreate.Fields.Where(f => CheckFieldExistency(f)));
            _entryToCreate.Fields = filteredList;

            try {
                doverApi.CreateModule(module, _entryToCreate);
                result = "<result>Success</result>";
            }
            catch (CreateModuleFailedException) {
                result = "<result>Failure</result>";
            }

            return(Content(result, "text/xml", Encoding.UTF8));
        }
Exemple #26
0
        public ActionResult module(int moduleid, int?id, DynamicModuleViewModel _entryToEdit)
        {
            var result = String.Empty;

            try {
                var doverApi     = new ModuleApi(ModRepository);
                var module       = ModRepository.GetModuleById(moduleid, m => m.Rows.Include <Row, Cell>(r => r.Cells), m => m.Fields);
                var filteredList = new DynamicModuleFieldList();

                filteredList.AddRange(_entryToEdit.Fields.Where(f => CheckFieldExistency(f)));
                _entryToEdit.Fields = filteredList;

                doverApi.SetModuleData(module, id, _entryToEdit, true);
                result = "<result>Success</result>";
            }
            catch (Exception e) {
                result = "<result>Failure</result>";
            }

            return(Content(result, "text/xml", Encoding.UTF8));
        }
Exemple #27
0
        public ActionResult Login(string username, string password, bool rememberMe, string returnUrl)
        {
            if (!ValidateLogOn(username, password))
            {
                return(Login());
            }

            // Make sure we have the username with the right capitalization
            // since we do case sensitive checks for OpenID Claimed Identifiers later.
            username = this.MembershipService.GetCanonicalUsername(username);

            // if the user is logging in using the pattern http://<accountname>.dovercms.com,
            // we'll check
            var subdomain = Request.Url.GetSubDomain();

            if (!String.IsNullOrWhiteSpace(subdomain))
            {
                var acct = ModRepository.GetAccountByName(subdomain);
                var user = acct.Users.FirstOrDefault(a => a.UserName == username);

                if (user == null)
                {
                    ModelState.AddModelError("_FORM", "Nome de usuário ou senha incorreta.");
                    return(Login());
                }
            }

            FormsAuth.SignIn(username, rememberMe);

            TempData["Message"] = "Bem vindo(a), " + username + ".";

            if (!String.IsNullOrEmpty(returnUrl))
            {
                return(Redirect(returnUrl));
            }

            return(RedirectToAction("Index", "Home"));
        }
Exemple #28
0
        public ActionResult Edit(string id)
        {
            MembershipUser     user = Membership.GetUser(id);
            UserProfileManager pMgr = new UserProfileManager(user);

            var userModules = ModRepository.GetUserModules((Guid)user.ProviderUserKey);
            var allModules  = new List <IModule>();          //ModRepository.GetAllStaticModules();

            EditUserViewModel viewModel = new EditUserViewModel()
            {
                UserId      = (Guid)user.ProviderUserKey,
                Email       = user.Email,
                UserProfile = pMgr.UserProfile,
                UserModules = userModules,
                AllModules  = allModules.Where(module => userModules.FirstOrDefault(mod => mod.Id == module.Id) == null)
            };

            // add the list with all available database types
            // TODO: Move this code to the profile-related namespace
            List <object> databaseTypes = new List <object>();

            return(View(viewModel));
        }
Exemple #29
0
        public ActionResult Register(string userName, string email, string password, string confirmPassword)
        {
            if (!CreateNewUser(userName, email, password, confirmPassword))
            {
                return(View());
            }

            var acctName = RouteData.Values["account"] as string;

            // associate the created user with the current account
            if (!String.IsNullOrWhiteSpace(acctName))
            {
                var createdUser = ModRepository.GetUserByName(userName);
                var acct        = ModRepository.GetAccountByName(acctName);

                acct.Users.Add(createdUser);

                ModRepository.Save();
            }

            TempData["Message"] = "Usuário " + userName + " criado com sucesso.";
            return(RedirectToAction("Index", "Home"));
        }
Exemple #30
0
        public ActionResult List()
        {
            var model = new List <KeyValuePair <string, string> >();

            // sysadmin can see all system users
            if (Roles.IsUserInRole("sysadmin"))
            {
                foreach (var user in ModRepository.GetAllUsers())
                {
                    var sb = new StringBuilder();
                    foreach (var acc in user.Accounts.Select(a => a.Name))
                    {
                        sb.Append(acc + ", ");
                    }
                    model.Add(new KeyValuePair <string, string>(
                                  sb.ToString().TrimEnd(", ".ToCharArray()),
                                  user.UserName));
                }
            }
            else if (Roles.IsUserInRole("administrators"))
            {
                var userId   = (Guid)Membership.GetUser().ProviderUserKey;
                var accounts = ModRepository.GetUserAccounts(userId);

                foreach (var acct in accounts)
                {
                    foreach (var user in ModRepository.GetAccountUsers(acct.Id))
                    {
                        model.Add(new KeyValuePair <string, string>(
                                      acct.Name,
                                      user.UserName));
                    }
                }
            }

            return(View(model));
        }