Ejemplo n.º 1
0
        /// <summary>
        /// Rename function in scope of parentElement.
        /// </summary>
        /// <param name="element">Element to rename.</param>
        /// <param name="parentElement">Containing element.</param>
        /// <param name="elementType">Type of element.</param>
        /// <param name="oldName">Old name of element.</param>
        /// <param name="newName">New name of element.</param>
        public override IRenameResult RenameSymbols(CodeElement element, LuaCodeClass parentElement, 
            vsCMElement elementType, string oldName, string newName)
        {
            renameResult = new RenameResult(oldName, newName);
            changedCodeElements = new List<CodeElement>();

            //Function without parent element could not be renamed
            if (element is LuaCodeFunction && parentElement == null)
            {
                var ex = new InvalidCodeElementException(Resources.InvalidFunctionParentMessage, parentElement);
                Trace.WriteLine(ex);
                throw ex;
            }
            //Rename function, function calls or null element by its name
            if (element is LuaCodeFunction || element is LuaCodeElement<FunctionCall> || element == null)
            {
                renameResult = Rename(element, parentElement, oldName, newName);
            }
            else
            {
                throw new InvalidCodeElementException(
                    Resources.InvalidFunctionElementMessage, parentElement);
            }

            //Set RenameReferences flag to indicates that rename is local or not
            renameResult.RenameReferences = !IsLocalDeclaration;
            renameResult.ChangedElements = changedCodeElements;

            renameResult.Success = true;

            return renameResult;
        }
Ejemplo n.º 2
0
 public async Task <RenameResult> RenameAsync(RenameParams parameters)
 {
     using (var response = await Api.CallAsync(HttpMethod.Post, Api.ApiUrlImgUpV.Action("rename").BuildUrl(), parameters.ToParamsDictionary(), null, null))
     {
         return(await RenameResult.Parse(response));
     }
 }
Ejemplo n.º 3
0
        private static RenameResult RenameRecipeImage(string recipeImageURL, string parentCategory, string childCategory = null)
        {
            Cloudinary cloudinaryRename = new Cloudinary(cloudinaryAccount);

            recipeImageURL = recipeImageURL.Substring(0, recipeImageURL.LastIndexOf('.'));
            string imageName = Path.GetFileNameWithoutExtension(recipeImageURL);
            string oldName   = recipeImageURL.Substring(recipeImageURL.IndexOf("Recipes"));

            oldName = HttpUtility.UrlDecode(oldName);

            string newName = "";

            if (childCategory != null)
            {
                newName = String.Format(@"Recipes/{0}/{1}/{2}", parentCategory, childCategory, imageName);
            }
            else
            {
                newName = String.Format(@"Recipes/{0}/{1}", parentCategory, imageName);
            }
            if (!oldName.Equals(newName))
            {
                RenameResult renameResult = cloudinaryRename.Rename(oldName, newName, true);
                return(renameResult);
            }

            return(null);
        }
Ejemplo n.º 4
0
        public RenameResult RenameDeclarations(SyntaxNode containerNode)
        {
            SyntaxNode   currentNode;
            var          newNode               = containerNode;
            RenameResult renamingResult        = null;
            RenameResult workingRenamingResult = null;

            do
            {
                currentNode           = newNode;
                workingRenamingResult = RenameDeclarationNodeOfContainerNode(currentNode);

                if (workingRenamingResult != null)
                {
                    renamingResult = workingRenamingResult;
                    if (workingRenamingResult.Node != null)
                    {
                        newNode         = renamingResult.Node;
                        WorkingDocument = renamingResult.Document;
                        _semanticModel  = renamingResult.Document.GetSemanticModelAsync().Result;
                    }
                }
            }while (workingRenamingResult != null && newNode != currentNode);

            return(renamingResult);
        }
Ejemplo n.º 5
0
 public static RenameResult ToRenameResult(this RenameRequest.Result data)
 {
     var res = new RenameResult
     {
         IsSuccess = data.status == 200
     };
     return res;
 }
Ejemplo n.º 6
0
        public static RenameResult ToRenameResult(this YadResponceModel <YadMoveRequestData, YadMoveRequestParams> data)
        {
            var res = new RenameResult
            {
                IsSuccess = true
            };

            return(res);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Changes public identifier of a file.
        /// </summary>
        /// <param name="parameters">Operation parameters.</param>
        /// <returns></returns>
        public RenameResult Rename(RenameParams parameters)
        {
            string uri = m_api.ApiUrlImgUpV.Action("rename").BuildUrl();

            using (HttpWebResponse response = m_api.Call(HttpMethod.POST, uri, parameters.ToParamsDictionary(), null))
            {
                return(RenameResult.Parse(response));
            }
        }
Ejemplo n.º 8
0
        public static RenameResult ToRenameResult(this CommonOperationResult <string> data)
        {
            var res = new RenameResult
            {
                IsSuccess = data.Status == 200
            };

            return(res);
        }
Ejemplo n.º 9
0
        public static RenameResult ToRenameResult(this MoveRequest.Result data)
        {
            var res = new RenameResult
            {
                IsSuccess = true
            };

            return(res);
        }
Ejemplo n.º 10
0
        public static ItemOperation ToItemOperation(this RenameResult data)
        {
            var res = new ItemOperation
            {
                DateTime = data.DateTime,
                Path     = data.Path
            };

            return(res);
        }
Ejemplo n.º 11
0
        public static RenameResult ToRenameResult(this YadResponseModel <YadMoveRequestData, YadMoveRequestParams> data)
        {
            var res = new RenameResult
            {
                IsSuccess = null == data.Data.Error,
                DateTime  = DateTime.Now,
                Path      = data.Params.Src.Remove(0, "/disk".Length)
            };

            return(res);
        }
Ejemplo n.º 12
0
        public async Task <RenameResult> Rename(string fullPath, string newName)
        {
            string target = WebDavPath.Combine(WebDavPath.Parent(fullPath), newName);

            await new MoveRequest(HttpSettings, Authent, _metaServer.Value.Url, fullPath, target)
            .MakeRequestAsync();
            var res = new RenameResult {
                IsSuccess = true
            };

            return(res);
        }
Ejemplo n.º 13
0
        public void RenameImage()
        {
            Cloudinary cloudinary = TestUtilities.GetCloudinary();

            TestUtilities.UploadImageWithName("renameSample", "https://c.pxhere.com/images/2c/4a/a103357d600dd68d0b28ca6b5135-1432179.jpg!d");

            /*By default, Cloudinary prevents renaming to an already taken public ID.
             * You can set the overwrite parameter to true to delete the image that has
             * the target public ID and replace it with the image being renamed:*/
            RenameResult renameResult = cloudinary.Rename("renameSample", "bee", true);

            TestUtilities.LogAndWrite(renameResult, "RenameResult.txt");
        }
Ejemplo n.º 14
0
        private void DataGrid_OnDoubleClickRow(object _sender, MouseButtonEventArgs _e)
        {
            DataGridRow row = _sender as DataGridRow;

            Debug.Assert(row != null);

            RenameResult renameResult = row.DataContext as RenameResult;

            Debug.Assert(renameResult != null);

            string fullName = renameResult.ProposedFile;

            Debug.Assert(!string.IsNullOrWhiteSpace(fullName));

            OpenInExplorer.Open(fullName);
        }
Ejemplo n.º 15
0
        public void AddEntry(RenameResult _result)
        {
            Debug.Assert(_result != null);

            //todo do existing find/replace
            RenameResult existing = Entries.Find(_entry => string.Equals(_entry.ProposedFileName, _result.ProposedFileName, StringComparison.OrdinalIgnoreCase));

            //remove existing and add updated
            if (existing != null)
            {
                Entries.Remove(existing);
            }

            Entries.Add(_result);

            Save();
        }
Ejemplo n.º 16
0
        internal static RenameResult AddTrackNumsToFileNames(string directory)
        {
            bool validFilesExist = false;

            TagLib.File tagFile;

            try
            {
                DirectoryInfo d     = new DirectoryInfo(@directory);
                FileInfo[]    infos = d.GetFiles();
                foreach (FileInfo f in infos)
                {
                    if (ValidAudioFileExtensions.Contains(f.Extension))
                    {
                        validFilesExist = true;
                        tagFile         = TagLib.File.Create(@directory + "\\" + f.Name);
                        AddTrackNumToFileName(f, tagFile.Tag.Track);
                    }
                }
                RenameResult result = new RenameResult
                {
                    Success = true,
                    Message = "Success!!!"
                };

                if (!validFilesExist)
                {
                    result.Success = false;
                    result.Message = "Umm, no mp3 files can be found...";
                }

                return(result);
            }
            catch (Exception e)
            {
                RenameResult result = new RenameResult
                {
                    Success = false,
                    Message = "ERROR: Ugh, something went wrong - {0}" + e.Message
                };

                return(result);
            }
        }
Ejemplo n.º 17
0
        private void BtnProcess_Click(object sender, EventArgs e)
        {
            lblResult.ForeColor = WarningColour;
            var result = new RenameResult();

            if (!string.IsNullOrEmpty(txtBxDirectory.Text))
            {
                // Modify the file names by removing or replacing the string entered
                if (chkbxShorten.Checked)
                {
                    result = FileHelper.RemoveStringsWithinFileNames(txtBxDirectory.Text, txtBxToDelete.Text, txtBxReplacementStr.Text);

                    if (!result.Success)
                    {
                        lblResult.Text = result.Message;
                        return;
                    }
                }

                // Add track numbers to file names
                if (chkbxAddTrackNo.Checked)
                {
                    result = FileHelper.AddTrackNumsToFileNames(txtBxDirectory.Text);

                    if (!result.Success)
                    {
                        lblResult.Text = result.Message;
                        return;
                    }
                }
                if (result.Success)
                {
                    lblResult.Text      = "Files were successfully renamed!";
                    lblResult.ForeColor = SuccessColour;
                }
            }
            else
            {
                lblResult.Text = "Please select directory";
            }
        }
Ejemplo n.º 18
0
        public static RenameResult Rename(string _line, DateTime _dateTime)
        {
            const string testPrefix  = TEST_RENAME + " ";
            const string movePrefix  = MOVE_RENAME + " ";
            const string xattrPrefix = XATTR_RENAME + " ";

            string[] splitString = null;

            string trimmed = "";

            if (_line.StartsWith(testPrefix))
            {
                trimmed     = _line.Replace(testPrefix, "");
                splitString = new[] { "] to [" };
            }
            else if (_line.StartsWith(movePrefix))
            {
                trimmed     = _line.Replace(movePrefix, "");
                splitString = new[] { "] to [" };
            }
            else if (_line.StartsWith(xattrPrefix))
            {
                trimmed     = _line.Replace(xattrPrefix, "");
                splitString = new[] { "] => [" };
            }
            else
            {
                Debug.Fail("rename prefix not supported!");
            }

            string[] split = trimmed.Split(splitString, StringSplitOptions.None);
            Debug.Assert(split.Length == 2);

            string source      = split[0].TrimStart('[');
            string destination = split[1].TrimEnd(']');

            RenameResult result = new RenameResult(Filebot.ActionType.TEST, source, destination, _line, _dateTime);

            return(result);
        }
Ejemplo n.º 19
0
        RenameResult RenameDeclarationNodeOfContainerNode(SyntaxNode containerNode)
        {
            var filteredItemsToRenmae = GetItemsToRename(containerNode).Where(i => VisitedTokens.Contains(i.ValueText) == false);

            foreach (var identifierToRename in filteredItemsToRenmae)
            {
                var currentName = identifierToRename.ValueText;
                var newNames    = GetNewName(currentName);

                if (newNames == null)
                {
                    continue;
                }

                var          selectedName = currentName;
                RenameResult result       = null;

                foreach (var newName in newNames)
                {
                    var renameResult = RenameIdentifierOfContainerNode(containerNode, identifierToRename, newName);

                    if (renameResult == null)
                    {
                        continue;
                    }

                    result       = renameResult.Value.Key;
                    selectedName = renameResult.Value.Value;
                }

                VisitedTokens.Add(selectedName);

                if (result != null)
                {
                    return(result);
                }
            }

            return(null);
        }
Ejemplo n.º 20
0
        private void RecursiveRename(RenamerInfo root, string oldName, string newName, IProgress <RenamerProgress> progressReport, ILogger logger)
        {
            if (root.IsIncluded)
            {
                // IMPORTANT TO DO DEPTH-FIRST TRAVERSAL!
                // first loop through the children, renaming there
                foreach (var item in root.Children)
                {
                    RecursiveRename(item, oldName, newName, progressReport, logger);
                }

                // _now_ can do the root
                RenameResult result = GetRenameStrategy(root.FileType).Rename(root, oldName, newName);
                progressReport.Report(new RenamerProgress(result.Message, UpTheCount(0.7, 0.3), logger, !result.IsSuccess));
            }
            else
            {
                progressReport.Report(new RenamerProgress($"{root.Path}: Skipped.", UpTheCount(0.7, 0.3), logger, false));
            }

            Task.Delay(1).Wait(); // TODO: find a better way of pumping through the updates to the UI
        }
Ejemplo n.º 21
0
        KeyValuePair <RenameResult, string>?RenameIdentifierOfContainerNode(SyntaxNode containerNode, SyntaxToken identifierToRename, string newVarName)
        {
            RenameResult result = null;

            var currentName  = identifierToRename.ValueText;
            var selectedName = currentName;

            if (string.Compare(newVarName, currentName, false) == 0)
            {
                return(null);
            }
            if (ValidateNewName(newVarName) == false)
            {
                return(null);
            }

            var identifierDeclarationNode = identifierToRename.Parent;

            var identifierSymbol = _semanticModel.GetDeclaredSymbol(identifierDeclarationNode);

            var validateNameResult = RenameHelper.IsValidNewMemberNameAsync(_semanticModel, identifierSymbol, newVarName).Result;

            if (validateNameResult == false)
            {
                return(null);
            }

            result = RenameSymbol(WorkingDocument, WorkingDocument.GetSyntaxRootAsync().Result, containerNode, identifierDeclarationNode, newVarName);

            if (result != null)
            {
                selectedName = newVarName;
            }

            return(new KeyValuePair <RenameResult, string>(result, selectedName));
        }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            Console.WriteLine("Generating format...");

            #region Params

            var p_copy = new CopyParam
            {
                CurrentFolderPath    = "/",
                SourceDirectory      = "/",
                DestinationDirectory = "/",
                Overwrite            = false,
                Targets = new System.Collections.Generic.List <BaseActionTarget>
                {
                    new BaseActionTarget
                    {
                        IsFile = true,
                        Name   = "sample.txt"
                    }
                }
            };

            var p_move = new MoveParam
            {
                CurrentFolderPath    = "/",
                SourceDirectory      = "/",
                DestinationDirectory = "/",
                Overwrite            = false,
                Targets = new System.Collections.Generic.List <BaseActionTarget>
                {
                    new BaseActionTarget
                    {
                        IsFile = true,
                        Name   = "sample.txt"
                    }
                }
            };

            var p_createFolder = new CreateFolderParam
            {
                CurrentFolderPath = "/",
                Name = "new folder name"
            };

            var p_delete = new DeleteParam
            {
                CurrentFolderPath = "/",
                Targets           = new System.Collections.Generic.List <string>
                {
                    "itemNameToDelete"
                }
            };

            var p_folderStruct = new FolderStructParam
            {
                CurrentFolderPath = "/",
                FileExtensions    = new string[] { ".txt" }
            };

            var p_rename = new RenameParam
            {
                CurrentFolderPath = "/",
                Targets           = new System.Collections.Generic.List <RenameActionTarget>
                {
                    new RenameActionTarget
                    {
                        IsFile  = true,
                        Name    = "new name",
                        OldName = "old name"
                    }
                }
            };

            #endregion

            #region Results

            var r_copy = new CopyResult
            {
                Errors = new System.Collections.Generic.List <string>
                {
                    "Error message."
                }
            };

            var r_move = new MoveResult
            {
                Errors = new System.Collections.Generic.List <string>
                {
                    "Error message."
                }
            };

            var r_createFolder = new CreateFolderResult
            {
                Errors = new System.Collections.Generic.List <string>
                {
                    "Error message."
                }
            };

            var r_delete = new DeleteResult
            {
                Affected = 0,
                Errors   = new System.Collections.Generic.List <string>
                {
                    "Error message."
                }
            };

            var r_folderStruct = new FolderStructResult
            {
                Errors = new System.Collections.Generic.List <string>
                {
                    "Error message."
                },
                Files = new System.Collections.Generic.List <FileInfoProxy>
                {
                    new FileInfoProxy
                    {
                        Name       = "file.name",
                        Properties = new System.Collections.Generic.Dictionary <string, string>
                        {
                            { "Property", "Value" }
                        }
                    }
                },
                Folders = new System.Collections.Generic.List <FileInfoProxy>
                {
                    new FileInfoProxy
                    {
                        Name       = "folder name",
                        Properties = new System.Collections.Generic.Dictionary <string, string>
                        {
                            { "Property", "Value" }
                        }
                    }
                }
            };

            var r_rename = new RenameResult
            {
                Affected = 0,
                Errors   = new System.Collections.Generic.List <string>
                {
                    "Error message."
                },
                RenamedObjects = new System.Collections.Generic.List <RenameActionTarget>()
                {
                    new RenameActionTarget
                    {
                        IsFile  = true,
                        Name    = "new name",
                        OldName = "old name"
                    }
                }
            };

            #endregion

            SaveFormat("p_copy.json", p_copy);
            SaveFormat("p_move.json", p_move);
            SaveFormat("p_createFolder.json", p_createFolder);
            SaveFormat("p_delete.json", p_delete);
            SaveFormat("p_folderStruct.json", p_folderStruct);
            SaveFormat("p_rename.json", p_rename);

            SaveFormat("r_copy.json", r_copy);
            SaveFormat("r_move.json", r_move);
            SaveFormat("r_createFolder.json", r_createFolder);
            SaveFormat("r_delete.json", r_delete);
            SaveFormat("r_folderStruct.json", r_folderStruct);
            SaveFormat("r_rename.json", r_rename);
        }
Ejemplo n.º 23
0
        public static bool UpdateUserApp(UserApplication updateUser, HtmlInputFile imageUploader)
        {
            bool isSuccsesfullyUpdate          = false;
            bool isSuccsesfullyUpdateUsername  = false;
            bool isSuccsesfullyRenameImage     = false;
            bool isSuccsesfullyUploadNewImage  = false;
            bool isSuccsesfullyDeleteUserRoles = false;
            bool isSuccsesfullyAddUserRoles    = false;
            bool isSuccsesfullyUpdateUserRoles = false;

            string        oldUserName         = updateUser.OldUsernameForUpdate;
            string        newUserName         = updateUser.NewUsernameForUpdate;
            string        applicationName     = updateUser.AppName;
            string        profileImageVersion = null;
            string        resetPassword       = updateUser.ResetUserPassword;
            List <string> userRoles           = updateUser.UserRoles;

            Membership.ApplicationName = applicationName;
            Roles.ApplicationName      = applicationName;

            //UpdateUsername
            if (!oldUserName.Equals(newUserName))
            {
                isSuccsesfullyUpdateUsername = UsersAppsDAL.UpdateUserName(oldUserName, newUserName);

                if (imageUploader.PostedFile == null || imageUploader.PostedFile.FileName == "")
                {
                    Cloudinary cloudinary = new Cloudinary(cloudinaryAccount);

                    string       oldProfileImageName = String.Format(@"{0}/{1}/{2}", cloudinaryAccountsFolder, applicationName, oldUserName);
                    string       newProfileImageName = String.Format(@"{0}/{1}/{2}", cloudinaryAccountsFolder, applicationName, newUserName);
                    RenameResult result = cloudinary.Rename(oldProfileImageName, newProfileImageName, true);
                    profileImageVersion = "v" + result.Version;

                    isSuccsesfullyRenameImage = true;
                }
            }

            //UploadNewImage
            if (imageUploader.PostedFile != null && imageUploader.PostedFile.FileName != "")
            {
                DeleteCloudinaryProfileImage(oldUserName, applicationName);

                profileImageVersion          = UploadCloudinaryProfileImage(imageUploader, applicationName, newUserName);
                isSuccsesfullyUploadNewImage = true;
            }

            //ResetPassword
            if (!String.IsNullOrEmpty(resetPassword))
            {
                if (!oldUserName.Equals(newUserName))
                {
                    ResetUserPassword(newUserName, resetPassword);
                }
                else
                {
                    ResetUserPassword(oldUserName, resetPassword);
                }
            }

            //UpdateUserRoles
            if (oldUserName.Equals(newUserName))
            {
                foreach (string oldRole in Roles.GetRolesForUser(oldUserName))
                {
                    foreach (string newRole in userRoles)
                    {
                        if (!oldRole.Equals(newRole))
                        {
                            Roles.RemoveUserFromRole(oldUserName, oldRole);
                            isSuccsesfullyDeleteUserRoles = true;
                        }
                    }
                }
            }
            else
            {
                foreach (string oldRole in Roles.GetRolesForUser(newUserName))
                {
                    foreach (string newRole in userRoles)
                    {
                        if (!oldRole.Equals(newRole))
                        {
                            Roles.RemoveUserFromRole(newUserName, oldRole);
                            isSuccsesfullyDeleteUserRoles = true;
                        }
                    }
                }
            }

            foreach (string role in userRoles)
            {
                if (!userRoles[0].Equals("The user isn't in roles"))
                {
                    if (oldUserName.Equals(newUserName))
                    {
                        if (!Roles.IsUserInRole(oldUserName, role))
                        {
                            Roles.AddUserToRole(oldUserName, role);
                        }
                    }
                    else
                    {
                        if (!Roles.IsUserInRole(newUserName, role))
                        {
                            Roles.AddUserToRole(newUserName, role);
                        }
                    }
                    isSuccsesfullyAddUserRoles = true;
                }
            }
            isSuccsesfullyUpdateUserRoles = (isSuccsesfullyDeleteUserRoles || isSuccsesfullyAddUserRoles);


            if (((isSuccsesfullyUpdateUsername && isSuccsesfullyRenameImage) || isSuccsesfullyUploadNewImage) || isSuccsesfullyUpdateUserRoles)
            {
                isSuccsesfullyUpdate = true;
            }

            MembershipUser currentUser = Membership.GetUser(newUserName);

            currentUser.Comment = profileImageVersion;
            Membership.UpdateUser(currentUser);
            Membership.ApplicationName = "ShopHelperAsp";
            Roles.ApplicationName      = "ShopHelperAsp";

            return(isSuccsesfullyUpdate);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Rename element in scope of parentElement.
        /// </summary>
        /// <param name="element">Element to rename.</param>
        /// <param name="parentElement">Containing element.</param>
        /// <param name="elementType">Type of element.</param>
        /// <param name="oldName">Old name of element.</param>
        /// <param name="newName">New name of element.</param>
        public override IRenameResult RenameSymbols(CodeElement element, LuaCodeClass parentElement,
            vsCMElement elementType, string oldName, string newName)
        {
            CodeElement declaration;
            renameResult = new RenameResult(oldName, newName);
            changedCodeElements = new List<CodeElement>();
            isFunctionParameter = false;

            if (element == null) //Declaration is in other lua file or not recognized by caller.
            {
                //Get declaration of the Variable.
                declaration = GetDeclaration(oldName, parentElement);
                if (declaration != null && !IsLocalDeclaration)
                {
                    RenameVariableDeclaration(declaration, oldName, newName);
                }
                //If declaration is global then rename elements in all referenced files
                if (!IsLocalDeclaration)
                {
                    //Rename all references in scope of class
                    renameResult.Success = RenameMemberVariableReferences(parentElement, elementType, oldName, newName);
                }
                renameResult.Success = true;
            }
            else
            {
                //Get declaration of the Variable.
                declaration = GetDeclaration(element, parentElement);

                //Get parent of the Variable declaration.
                if (declaration != null)
                {
                    variableParent = ((ICodeDomElement) declaration).ParentElement;
                    if (!(variableParent is LuaCodeFunction) || (variableParent is LuaCodeClass))
                    {
                        variableParent = LuaCodeDomNavigator.GetParentElement((ICodeDomElement) declaration);
                    }
                }
                else
                {
                    variableParent = ((ICodeDomElement) element).ParentElement;
                }

                //Rename CodeElements and all references.
                if (variableParent is LuaCodeClass) //CodeElement is global declared variable.
                {
                    //Rename member variable
                    if (RenameVariableDeclaration(declaration, oldName, newName))
                    {
                        //Rename all references in scope of current class.
                        renameResult.Success = RenameMemberVariableReferences(parentElement, oldName, newName);
                    }
                }
                else if (variableParent is LuaCodeFunction)//CodeElement is local declared variable.
                {
                    //Rename local variable.
                    if (RenameVariableDeclaration(declaration, oldName, newName))
                    {
                        if (IsLocalDeclaration)
                        {
                            //Rename all references in scope of Function
                            renameResult.Success = RenameMemberVariableReferencesInScope(oldName, newName);
                        }
                        else
                        {
                            //Rename all references in scope of Class.
                            renameResult.Success = RenameMemberVariableReferences(parentElement, oldName, newName);
                        }
                    }
                }
                else if (variableParent == null)
                {
                    throw new InvalidCodeElementException(
                        Resources.InvalidElementParentMessage, parentElement);
                }
                else
                {
                    Trace.WriteLine("Trace:Unrecognized variable...");
                    RenameSymbols(null, parentElement, elementType, oldName, newName);
                }
            }
            renameResult.ChangedElements = changedCodeElements;
            renameResult.RenameReferences = !IsLocalDeclaration;

            renameResult.Success = true;

            return renameResult;
        }
Ejemplo n.º 25
0
        }                                   // 0x007D6D00-0x007D6E00

        private void GuideUpdate(RenameResult type)
        {
        }                                         // 0x007D7AB0-0x007D7B10
Ejemplo n.º 26
0
        public RenameResult GetMenuItem() => default;         // 0x007D6F70-0x007D6F80

        private void WindowInit(GameObject windowObj, RenameResult type)
        {
        }                                                                           // 0x007D7130-0x007D7AB0
Ejemplo n.º 27
0
        }                                     // 0x007D6710-0x007D6780

        // Methods
        public void Init(GameObject root, RenameResult initRes)
        {
        }                                                     // 0x007D6780-0x007D6A90
Ejemplo n.º 28
0
    }                              // 0x007D6620-0x007D6710

    public void Init(RenameResult initRes)
    {
    }                                             // 0x007D17A0-0x007D1880
Ejemplo n.º 29
0
        /// <summary>
        /// Calls rename file and counts rename retries.
        /// </summary>
        /// <param name="process">Running process.</param>
        /// <param name="renameResult">Rename result.</param>
        /// <returns>Returns new FileWatcherEventArgs with new renamed file path or null
        /// if the process is re-queued or rename fails or is canceled.</returns>
        private FileWatcherEventArgs CallRenameFile(FileWatcherEventArgs process,
                                                    out RenameResult renameResult)
        {
            // If file is a directory.
            if (Directory.Exists(process.FullPath))
            {
                renameResult = RenameResult.Cancel;
                return null;
            }
            // Check if file exists.
            if (!File.Exists(process.FullPath))
            {
                renameResult = RenameResult.Cancel;
                return null;
            }
            // Check retries count if to continue.
            if (_tryRenameFile.ContainsKey(process.Id))
            {
                if (process.ConfigurationKeyValuePair.Value.TryRenameFileRetries == _tryRenameFile[process.Id])
                {
                    renameResult = RenameResult.Cancel;
                    return null;
                }
            }

            // Try to rename the file.
            FileWatcherEventArgs fileWatcherEventArgs = TryRenameFile(process,
                                                                      out renameResult);

            // If to re-enqueue.
            if (renameResult == RenameResult.Retry)
            {
                // Add or increment counter.
                if (!_tryRenameFile.ContainsKey(process.Id))
                {
                    _tryRenameFile.Add(process.Id, 0);
                }
                else
                {
                    _tryRenameFile[process.Id]++;
                }
            }
            else // Remove counter.
            {
                if (_tryRenameFile.ContainsKey(process.Id))
                {
                    _tryRenameFile.Remove(process.Id);
                }
            }

            // Return original process or a new process with renamed file path.
            return fileWatcherEventArgs;
        }
Ejemplo n.º 30
0
        private static IEnumerable <RenameResult> Run(DirectoryInfo dir, RenameRule rule)
        {
            if (!dir.Exists)
            {
                yield break;
            }

            var files = dir
                        .EnumerateFiles()
                        .Where(f => Regex.IsMatch(f.Name, rule.Contains, RegexOptions.IgnoreCase))
                        .ToArray();

            var format = rule.Format;

            foreach (var file in files)
            {
                var regex = new Regex(rule.Pattern, RegexOptions.IgnoreCase);
                var m     = regex.Match(file.Name);
                if (m.Success)
                {
                    var groups = m.Groups.OfType <Group>().ToList();
                    var values = new Dictionary <int, object>();

                    var names = regex.GetGroupNames();
                    foreach (var name in names)
                    {
                        var group      = m.Groups[name];
                        var index      = groups.IndexOf(group);
                        var token      = $"${name}";
                        var tokenIndex = format.IndexOf(token);
                        if (tokenIndex >= 0)
                        {
                            var formatIndex = $"{{{index}}}";
                            var afterToken  = tokenIndex + token.Length;
                            if (afterToken < format.Length && format[afterToken] == '#')
                            {
                                // this is a number!
                                values[index] = $"{int.Parse(group.Value):000}";
                                token         = $"{token}#";
                            }
                            format = format.Replace(token, formatIndex);
                        }
                    }

                    var args = groups
                               .Select((g, i) => values.TryGetValue(i, out object value) ? value : g.Value)
                               .ToArray();

                    var filename = string.Format(format, args);
                    var filepath = Path.Combine(file.Directory.FullName, filename);
                    var result   = new RenameResult(file.Name, filename);
                    try
                    {
                        file.MoveTo(filepath);
                    }
                    catch
                    {
                        continue;
                    }
                    yield return(result);
                }
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Tries to rename file.
        /// </summary>
        /// <param name="process">Running process.</param>
        /// <param name="renameResult">Rename result.</param>
        /// <returns>Returns new FileWatcherEventArgs with new renamed file path or null
        /// if the process is re-queued or rename fails or is canceled.</returns>
        private static FileWatcherEventArgs TryRenameFile(FileWatcherEventArgs process,
                                                          out RenameResult renameResult)
        {
            string fileName = Path.GetFileName(process.FullPath);

            if (fileName == null)
            {
                renameResult = RenameResult.Cancel;
                return null;
            }

            const string FileNameFormat = @"{0}.{{{1}}}.process";

            string newFileName = String.Format(CultureInfo.CurrentCulture,
                                               FileNameFormat,
                                               fileName,
                                               process.Id);

            string newFullPath = process.FullPath.Remove(process.FullPath.Length - fileName.Length,
                                                         fileName.Length) + newFileName;

            try
            {
                // Rename file.
                File.Move(process.FullPath, newFullPath);
                renameResult = RenameResult.Success;
            }
            catch (PathTooLongException)
            {
                renameResult = RenameResult.Cancel;
                return null;
            }
            catch (DirectoryNotFoundException)
            {
                renameResult = RenameResult.Cancel;
                return null;
            }
            catch (FileNotFoundException)
            {
                renameResult = RenameResult.Cancel;
                return null;
            }
            catch (UnauthorizedAccessException)
            {
                renameResult = RenameResult.Cancel;
                return null;
            }
            catch (NotSupportedException)
            {
                renameResult = RenameResult.Cancel;
                return null;
            }
            catch (ArgumentException)
            {
                renameResult = RenameResult.Cancel;
                return null;
            }
            catch (IOException) // File can be locked by another process or something else goes wrong.
            {
                // Retry renaming.
                renameResult = RenameResult.Retry;
                return null;
            }

            // Return new process with renamed file information.
            return new FileWatcherEventArgs(process.ConfigurationKeyValuePair,
                                            process.ChangeType,
                                            newFileName,
                                            newFullPath,
                                            process.FullPath,
                                            process.Id);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Rename elements in all referenced lua files.
        /// </summary>
        /// <param name="elementType">Type of element.</param>
        /// <param name="oldName">Old name of element.</param>
        /// <param name="newName">New name of element.</param>
        /// <param name="result">Rename result.</param>
        private IRenameResult RenameAllReferences(vsCMElement elementType, string oldName, string newName,
            IRenameResult result)
        {
            Trace.WriteLine("RenameAllReferences started...");
            try
            {
                var multiResult = new MultiRenameResult(oldName, newName);
                Project currentProject = DTE.ActiveDocument.ProjectItem.ContainingProject;
                ProjectItem activeProjectItem = DTE.ActiveDocument.ProjectItem;
                string activeProjectFileName = activeProjectItem.get_FileNames(1);
                List<ProjectItem> projectItems = GetLuaProjectItems(currentProject);

                foreach (ProjectItem projectItem in projectItems)
                {
                    string fileName = projectItem.get_FileNames(1);
                    if (!string.IsNullOrEmpty(fileName))
                    {
                        //If projectItem is the active then merge changes into MultiRenameResult
                        if (activeProjectFileName == fileName)
                        {
                            multiResult.MergeChanges(projectItem, result);
                        }
                        else
                        {
                            if (IsLuaFile(fileName))
                            {
                                LuaFileCodeModel fileCodeModel = GetFileCodeModel(projectItem);
                                if (fileCodeModel != null)
                                {
                                    CodeElement root = GetRootElement(fileCodeModel);
                                    IRenameResult renameResult;
                                    //Rename references in Lua file.
                                    if (root != null)
                                    {
                                        renameResult = refactoringService.Rename(null, root, elementType, oldName, newName);
                                        renameResult.Parents.Add(fileCodeModel);
                                    }
                                    else
                                    {
                                        string message = String.Format(Resources.RootElementCannotBeFoundMessage, fileName);
                                        renameResult = new RenameResult(false, message);
                                        Trace.WriteLine(message);
                                    }
                                    multiResult.MergeChanges(projectItem, renameResult);
                                }
                            }
                        }
                    }
                }
                return multiResult;
            }
            catch (Exception e)
            {
                Trace.WriteLine(e);
                throw;
            }
        }
Ejemplo n.º 33
0
        //For POST Edit Action
        private Recipe ParseRecipeVMToRecipeModel_Update(Recipe recipeModel, AdminRecipeViewModel recipeVM)
        {
            Recipe            recipeForEdit         = recipeModel;
            ImageUploadResult recipeImgUploadResult = new ImageUploadResult();
            //var recipeForEdit = this.db.Recipes.All()
            //            .Include(r => r.Categories)
            //            .Include(r => r.RecipeItems)
            //            .FirstOrDefault(r => r.RecipeID == recipeVM.RecipeID);
            HMLToRTFConverter converter = new HMLToRTFConverter();

            recipeForEdit.Title = recipeVM.Title;

            //recipeForEdit.ImageURL = "null_image.png";
            Category newRecipeParentCategory = this.db.Categories.GetById(recipeVM.SelectedParentCategory);

            recipeForEdit.Categories.Clear();
            recipeForEdit.Categories.Add(newRecipeParentCategory);
            Category newRecipeChildrenCategory = null;

            if (recipeVM.SelectedChildrenCategory != null)
            {
                newRecipeChildrenCategory = this.db.Categories.GetById((int)(recipeVM.SelectedChildrenCategory));
                recipeForEdit.Categories.Add(newRecipeChildrenCategory);
            }
            if (recipeVM.Image != null && (recipeVM.Image.FileName != "null_image.png" || recipeVM.Image.FileName != "null_image"))
            {
                if (newRecipeChildrenCategory == null)
                {
                    DeleteRecipeImage(recipeVM.ImageURL);
                    recipeImgUploadResult = UploadRecipeImage(recipeVM.Image, recipeVM.Title, newRecipeParentCategory.Name, null);
                }
                else
                {
                    DeleteRecipeImage(recipeVM.ImageURL);
                    recipeImgUploadResult = UploadRecipeImage(recipeVM.Image, recipeVM.Title, newRecipeParentCategory.Name, newRecipeChildrenCategory.Name);
                }
                recipeForEdit.ImageVersion = "v" + recipeImgUploadResult.Version;
                recipeForEdit.ImageURL     = "http://res.cloudinary.com" + recipeImgUploadResult.Uri.AbsolutePath;
                //newRecipe.ImageURL = recipeVM.Title.Replace(" ", "-") + ".jpg";
            }
            else
            {
                RenameResult renameResult = null;
                if (newRecipeChildrenCategory != null)
                {
                    renameResult = RenameRecipeImage(recipeVM.ImageURL, newRecipeParentCategory.Name, newRecipeChildrenCategory.Name);
                }
                else
                {
                    renameResult = RenameRecipeImage(recipeVM.ImageURL, newRecipeParentCategory.Name);
                }
                if (renameResult != null)
                {
                    recipeForEdit.ImageURL = HttpUtility.UrlDecode(renameResult.Url);
                }
            }
            recipeForEdit.PreparationTime = recipeVM.SelectedPrepTimeHours * 60 + recipeVM.SelectedPrepTimeMinutes;
            recipeForEdit.CookingTime     = recipeVM.SelectedCookTimeHours * 60 + recipeVM.SelectedCookTimeMinutes;
            recipeForEdit.Serves          = recipeVM.SelectedServes;
            recipeForEdit.Rating          = recipeVM.SelectedRating;
            recipeForEdit.Source          = this.db.Sources.GetById(recipeVM.SelectedSource);
            if (recipeVM.SelectedRecommendation == "Да")
            {
                recipeForEdit.Recommended = (bool?)true;
            }
            //if (recipeVM.SelectedRecommendation == "Не")
            else
            {
                recipeForEdit.Recommended = (bool?)false;
            }
            recipeForEdit.Date        = recipeVM.PublishedDate;
            recipeForEdit.Description = converter.ConvertHTMLToRTF(recipeVM.Description);
            //recipeForEdit.RecipeItems = recipeVM.RecipeItems;
            foreach (var recipeItem in recipeVM.RecipeItems)
            {
                RecipeItem newRecipeItem = new RecipeItem();
                newRecipeItem.RecipeItemName = recipeItem.RecipeItemName;
                foreach (var recipeItem_ingredient in recipeItem.RecipeItems_Ingredients)
                {
                    RecipeItems_Ingredients newRecipeItem_ingredient = new RecipeItems_Ingredients();
                    Unit       newUnit       = this.db.Units.GetById(recipeItem_ingredient.Unit.UnitID);
                    Ingredient newIngredient = this.db.Ingredients.GetById(recipeItem_ingredient.Ingredient.IngredientID);
                    newRecipeItem_ingredient.Quantity   = recipeItem_ingredient.Quantity;
                    newRecipeItem_ingredient.Unit       = newUnit;
                    newRecipeItem_ingredient.Ingredient = newIngredient;
                    newRecipeItem.RecipeItems_Ingredients.Add(newRecipeItem_ingredient);
                }
                foreach (var step in recipeItem.Steps)
                {
                    newRecipeItem.Steps.Add(step);
                }

                recipeForEdit.RecipeItems.Add(newRecipeItem);
            }

            //newRecipe.RecipeItems = recipeVM.RecipeItems;

            return(recipeForEdit);
        }