public static void HandleSyntaxTree(SyntaxTreeAnalysisContext context, StyleCopSettings settings)
            {
                var syntaxRoot = context.Tree.GetRoot(context.CancellationToken);

                var firstTypeDeclaration = GetFirstTypeDeclaration(syntaxRoot);

                if (firstTypeDeclaration == null)
                {
                    return;
                }

                if (firstTypeDeclaration.Modifiers.Any(SyntaxKind.PartialKeyword))
                {
                    return;
                }

                string suffix;
                var    fileName         = FileNameHelpers.GetFileNameAndSuffix(context.Tree.FilePath, out suffix);
                var    expectedFileName = FileNameHelpers.GetConventionalFileName(firstTypeDeclaration, settings.DocumentationRules.FileNamingConvention);

                if (string.Compare(fileName, expectedFileName, StringComparison.OrdinalIgnoreCase) != 0)
                {
                    if (settings.DocumentationRules.FileNamingConvention == FileNamingConvention.StyleCop &&
                        string.Compare(fileName, FileNameHelpers.GetSimpleFileName(firstTypeDeclaration), StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        return;
                    }

                    var properties = ImmutableDictionary.Create <string, string>()
                                     .Add(ExpectedFileNameKey, expectedFileName + suffix);

                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, firstTypeDeclaration.Identifier.GetLocation(), properties));
                }
            }
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();
            if (sMessage == "")
            {
                return(GetMessage(500, string.Format("{0} needs a paramter", Command)));
            }

            string dirToMake = GetPath(FileNameHelpers.AppendDirTag(sMessage));

            // check directory name
            if (!FileNameHelpers.IsValid(dirToMake))
            {
                return(GetMessage(553, string.Format("\"{0}\": Invalid directory name", sMessage)));
            }

            // check whether directory already exists
            if (ConnectionObject.FileSystemObject.DirectoryExists(dirToMake))
            {
                return(GetMessage(553, string.Format("Directory \"{0}\" already exists", sMessage)));
            }

            // create directory
            if (!ConnectionObject.FileSystemObject.CreateDirectory(dirToMake))
            {
                return(GetMessage(550, string.Format("Couldn't create directory. ({0})", sMessage)));
            }

            return(GetMessage(257, string.Format("{0} successful \"{1}\".", Command, dirToMake)));
        }
예제 #3
0
        protected override async Task <string> OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();
            if (sMessage == "")
            {
                return(GetMessage(501, string.Format("{0} needs a parameter", Command)));
            }

            string sFile = GetPath(sMessage);

            if (!FileNameHelpers.IsValid(sFile))
            {
                return(GetMessage(553, string.Format("\"{0}\" is not a valid file name", sMessage)));
            }

            var socketData = new FtpDataSocket(ConnectionObject);

            if (!socketData.Loaded)
            {
                return(GetMessage(425, "Unable to establish the data connection"));
            }

            SocketHelpers.Send(ConnectionObject.Socket, GetMessage(150, "Opening connection for data transfer."), ConnectionObject.Encoding);

            if (!ConnectionObject.FileSystemObject.AppendFile(sFile, socketData.Socket.GetStream()).Result)
            {
                return(GetMessage(553, string.Format("{0} error", Command)));
            }

            // remove the orginal blob ContentMD5
            await ConnectionObject.FileSystemObject.SetFileMd5(sFile, string.Empty);

            return(GetMessage(250, string.Format("{0} successful", Command)));
        }
예제 #4
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();
            if (sMessage == "")
            {
                return(GetMessage(501, string.Format("{0} needs a parameter", Command)));
            }

            string dirToRemove = GetPath(FileNameHelpers.AppendDirTag(sMessage));

            // check whether directory exists
            if (!ConnectionObject.FileSystemObject.DirectoryExists(dirToRemove))
            {
                return(GetMessage(550, string.Format("Directory \"{0}\" does not exist", dirToRemove)));
            }

            // can not delete root directory
            if (dirToRemove == "/")
            {
                return(GetMessage(553, "Can not remove root directory"));
            }

            // delete directory
            if (ConnectionObject.FileSystemObject.DeleteDirectory(dirToRemove))
            {
                return(GetMessage(250, string.Format("{0} successful.", Command)));
            }
            else
            {
                return(GetMessage(550, string.Format("Couldn't remove directory ({0}).", dirToRemove)));
            }
        }
예제 #5
0
        protected override async Task <string> OnProcess(string sMessage)
        {
            if (ConnectionObject.FileToRename.Length == 0)
            {
                return(GetMessage(503, "RNTO must be preceded by a RNFR."));
            }

            string sOldFileName = ConnectionObject.FileToRename;

            ConnectionObject.FileToRename = ""; // note:

            sMessage = sMessage.Trim();
            string sNewFileName = GetPath(sMessage);

            // check whether the new filename is valid
            if (!FileNameHelpers.IsValid(sNewFileName) || sNewFileName.EndsWith(@"/"))
            {
                return(GetMessage(553, string.Format("\"{0}\" is not a valid file name", sMessage)));
            }

            // check whether the new filename exists
            // note: azure allows file&virtualdir has the same name
            if (await ConnectionObject.FileSystemObject.FileExists(sNewFileName))
            {
                return(GetMessage(553, string.Format("File already exists ({0}).", sMessage)));
            }

            if (!await ConnectionObject.FileSystemObject.Move(sOldFileName, sNewFileName))
            {
                return(GetMessage(553, "Rename failed"));
            }

            return(GetMessage(250, "Renamed file successfully."));
        }
            public bool HasExtension(string extension)
            {
                Argument.IsNotNull(nameof(extension), extension);
                Argument.IsValid(nameof(extension), extension, extension.Length >= 2 && extension[0] == '.');

                return(FileNameHelpers.HasExtension(CurrentPath, extension));
            }
예제 #7
0
        private static void HandleSyntaxTree(SyntaxTreeAnalysisContext context, StyleCopSettings settings)
        {
            var syntaxRoot = context.Tree.GetRoot(context.CancellationToken);

            var typeNodes = GetTopLevelTypeDeclarations(syntaxRoot, settings);

            string suffix;
            var    fileName          = FileNameHelpers.GetFileNameAndSuffix(context.Tree.FilePath, out suffix);
            var    preferredTypeNode = typeNodes.FirstOrDefault(n => FileNameHelpers.GetConventionalFileName(n, settings.DocumentationRules.FileNamingConvention) == fileName) ?? typeNodes.FirstOrDefault();

            if (preferredTypeNode == null)
            {
                return;
            }

            var foundTypeName = NamedTypeHelpers.GetNameOrIdentifier(preferredTypeNode);
            var isPartialType = NamedTypeHelpers.IsPartialDeclaration(preferredTypeNode);

            foreach (var typeNode in typeNodes)
            {
                if (typeNode == preferredTypeNode || (isPartialType && foundTypeName == NamedTypeHelpers.GetNameOrIdentifier(typeNode)))
                {
                    continue;
                }

                var location = NamedTypeHelpers.GetNameOrIdentifierLocation(typeNode);
                if (location != null)
                {
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, location));
                }
            }
        }
예제 #8
0
 public bool HasExtension(string extension)
 {
     // All these 3 assertions have been checked by contract!
     Debug.Assert(extension != null);
     Debug.Assert(extension.Length >= 2);
     Debug.Assert(extension[0] == '.');
     return(FileNameHelpers.HasExtension(m_PathString, extension));
 }
예제 #9
0
        string[] FilterOutRequiredReqFile(string[] filesWithPath)
        {
            List <string> result = new List <string>();

            foreach (string filename in filesWithPath)
            {
                if (FileNameHelpers.GetFileName(filename) != "required.req")
                {
                    result.Add(filename);
                }
            }

            return(result.ToArray());
        }
예제 #10
0
        // Convert a string instance of a URI to a relative FTP path
        // Return the file name or the folder name
        public static string ToFtpPath(string s)
        {
            bool isDir = s.EndsWith(@"/");

            if (isDir)
            {
                // Note: append the directory end tag "/"
                return(FileNameHelpers.GetDirectoryName(s) + "/");
            }
            // the path is a file
            else
            {
                return(FileNameHelpers.GetFileName(s));
            }
        }
예제 #11
0
        protected override async Task <string> OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();

            // Get the file/dir to list
            string targetToList = GetPath(sMessage);

            // checks the file/dir name
            if (!FileNameHelpers.IsValid(targetToList))
            {
                return(GetMessage(501, string.Format("\"{0}\" is not a valid file/directory name", sMessage)));
            }

            bool targetIsFile = await ConnectionObject.FileSystemObject.FileExists(targetToList);

            bool targetIsDir = await ConnectionObject.FileSystemObject.DirectoryExists(FileNameHelpers.AppendDirTag(targetToList));

            if (!targetIsFile && !targetIsDir)
            {
                return(GetMessage(550, string.Format("\"{0}\" not exists", sMessage)));
            }

            SocketHelpers.Send(ConnectionObject.Socket, string.Format("250- MLST {0}\r\n", targetToList), ConnectionObject.Encoding);

            StringBuilder response = new StringBuilder();

            if (targetIsFile)
            {
                response.Append(" ");
                var fileInfo = await ConnectionObject.FileSystemObject.GetFileInfo(targetToList);

                response.Append(GenerateEntry(fileInfo));
                response.Append("\r\n");
            }

            if (targetIsDir)
            {
                response.Append(" ");
                var dirInfo = await ConnectionObject.FileSystemObject.GetDirectoryInfo(FileNameHelpers.AppendDirTag(targetToList));

                response.Append(GenerateEntry(dirInfo));
                response.Append("\r\n");
            }

            SocketHelpers.Send(ConnectionObject.Socket, response.ToString(), ConnectionObject.Encoding);

            return(GetMessage(250, "MLST successful"));
        }
        private static void HandleDifferentCourses(IEnumerable <ICourseLink> differentCourses)
        {
            foreach (var course in differentCourses)
            {
                var dirName = FileNameHelpers.FullyPrepareDirectory(course.Name.TrimInnerSpaces(), true);

                var linksWithinThisCourse =
                    SharedVars.DownloadQueue
                    .Where(link => link.ParentSection.ParentCourse == course)
                    .ToList();

                AdjustExtraPaths(linksWithinThisCourse, courseDirName: dirName, null);

                HandleDifferentSections(linksWithinThisCourse);
            }
        }
예제 #13
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();
            if (sMessage.Length == 0)
            {
                return(GetMessage(501, string.Format("Syntax error. {0} needs a parameter", Command)));
            }

            // append the final '/' char
            string sMessageFull = FileNameHelpers.AppendDirTag(sMessage);

            #region change to the parent dir
            if (sMessageFull == @"../")
            {
                // get the parent directory
                string parentDir = GetParentDir();
                if (parentDir == null)
                {
                    return(GetMessage(550, "Root directory, cannot change to the parent directory"));
                }

                ConnectionObject.CurrentDirectory = parentDir;
                FtpServer.LogWrite(this, sMessage, 200, 0);
                return(GetMessage(200, string.Format("{0} Successful ({1})", Command, parentDir)));
            }
            #endregion

            if (!FileNameHelpers.IsValid(sMessageFull))
            {
                FtpServer.LogWrite(this, sMessage, 550, 0);
                return(GetMessage(550, string.Format("\"{0}\" is not a valid directory string.", sMessage)));
            }

            // get the new directory path
            string newDirectory = GetPath(sMessageFull);

            // checks whether the new directory exists
            if (!ConnectionObject.FileSystemObject.DirectoryExists(newDirectory))
            {
                FtpServer.LogWrite(this, sMessage, 550, 0);
                return(GetMessage(550, string.Format("\"{0}\" no such directory.", sMessage)));
            }

            ConnectionObject.CurrentDirectory = newDirectory;
            FtpServer.LogWrite(this, sMessage, 250, 0);
            return(GetMessage(250, string.Format("{0} Successful ({1})", Command, newDirectory)));
        }
예제 #14
0
        protected override string OnProcess(string message)
        {
            message = message.Replace('/', '\\');

            if (!FileNameHelpers.IsValid(message))
            {
                return(GetMessage(550, "Not a valid directory string."));
            }

            var dir = GetPath(message);

            if (!ConnectionObject.FileSystemObject.DirectoryExists(dir))
            {
                return(GetMessage(550, "Not a valid directory."));
            }

            ConnectionObject.CurrentDirectory = Path.Combine(ConnectionObject.CurrentDirectory, message);
            return(GetMessage(250, string.Format("CWD Successful ({0})", ConnectionObject.CurrentDirectory.Replace("\\", "/"))));
        }
예제 #15
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Replace('/', '\\');

            if (!FileNameHelpers.IsValid(sMessage))
            {
                return(this.GetMessage(550, "Not a valid directory string."));
            }

            string sDirectory = this.GetPath(sMessage);

            if (!this.ConnectionObject.FileSystemObject.DirectoryExists(sDirectory))
            {
                return(this.GetMessage(550, "Not a valid directory."));
            }

            this.ConnectionObject.CurrentDirectory = Path.Combine(this.ConnectionObject.CurrentDirectory, sMessage);
            return(this.GetMessage(250, string.Format("CWD Successful ({0})", this.ConnectionObject.CurrentDirectory.Replace("\\", "/"))));
        }
예제 #16
0
        protected override string OnProcess(string sMessage)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            if (ConnectionObject.FileToRename.Length == 0)
            {
                FtpServer.LogWrite(this, sMessage, 503, 0);
                return(GetMessage(503, "RNTO must be preceded by a RNFR."));
            }

            string sOldFileName = ConnectionObject.FileToRename;

            ConnectionObject.FileToRename = ""; // note:

            sMessage = sMessage.Trim();
            string sNewFileName = GetPath(sMessage);

            // check whether the new filename is valid
            if (!FileNameHelpers.IsValid(sNewFileName) || sNewFileName.EndsWith(@"/"))
            {
                FtpServer.LogWrite(this, sMessage, 553, 0);
                return(GetMessage(553, string.Format("\"{0}\" is not a valid file name", sMessage)));
            }

            // check whether the new filename exists
            // note: azure allows file&virtualdir has the same name
            if (ConnectionObject.FileSystemObject.FileExists(sNewFileName))
            {
                FtpServer.LogWrite(this, sMessage, 553, sw.ElapsedMilliseconds);
                return(GetMessage(553, string.Format("File already exists ({0}).", sMessage)));
            }

            if (!ConnectionObject.FileSystemObject.Move(sOldFileName, sNewFileName))
            {
                FtpServer.LogWrite(this, sMessage, 553, sw.ElapsedMilliseconds);
                return(GetMessage(553, "Rename failed"));
            }

            FtpServer.LogWrite(this, sMessage, 250, sw.ElapsedMilliseconds);
            return(GetMessage(250, "Renamed file successfully."));
        }
예제 #17
0
        protected string GenerateEntry(IFileInfo info)
        {
            StringBuilder entry = new StringBuilder();

            bool isDirectory = info.IsDirectory();

            if (isDirectory)
            {
                entry.Append("Type=dir; ");
                string dirName = FileNameHelpers.GetDirectoryName(info.Path());
                entry.Append(dirName);
            }
            else
            {
                entry.Append(string.Format("Type=file;Size={0};Modify={1}; ", info.GetSize(), info.GetModifiedTime().ToString("yyyyMMddHHmmss")));
                entry.Append(FileNameHelpers.GetFileName(info.Path()));
            }

            return(entry.ToString());
        }
예제 #18
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();
            if (sMessage == "")
            {
                return(GetMessage(501, string.Format("{0} needs a parameter", Command)));
            }

            string sFile = GetPath(sMessage);

            Stopwatch sw = new Stopwatch();

            sw.Start();
            if (!FileNameHelpers.IsValid(sFile))
            {
                FtpServer.LogWrite(this, sMessage, 553, sw.ElapsedMilliseconds);
                return(GetMessage(553, string.Format("\"{0}\" is not a valid file name", sMessage)));
            }

            var socketData = new FtpDataSocket(ConnectionObject);

            if (!socketData.Loaded)
            {
                return(GetMessage(425, "Unable to establish the data connection"));
            }

            SocketHelpers.Send(ConnectionObject.Socket, GetMessage(150, "Opening connection for data transfer."), ConnectionObject.Encoding);

            if (!ConnectionObject.FileSystemObject.AppendFile(sFile, socketData.Socket.GetStream()))
            {
                FtpServer.LogWrite(this, sMessage, 553, sw.ElapsedMilliseconds);
                return(GetMessage(553, string.Format("{0} error", Command)));
            }

            // remove the orginal blob ContentMD5
            ConnectionObject.FileSystemObject.SetFileMd5(sFile, string.Empty);

            sw.Stop();
            FtpServer.LogWrite(this, sMessage, 250, sw.ElapsedMilliseconds);
            return(GetMessage(250, string.Format("{0} successful", Command)));
        }
예제 #19
0
        // build short list reply, only list the file names
        protected string BuildShortReply(string[] asFiles, string[] asDirectories)
        {
            var stringBuilder = new StringBuilder();

            if (asFiles != null)
            {
                foreach (string filePath in asFiles)
                {
                    stringBuilder.Append(string.Format("{0}\r\n", FileNameHelpers.GetFileName(filePath)));
                }
            }

            if (asDirectories != null)
            {
                foreach (string dirPath in asDirectories)
                {
                    stringBuilder.Append(string.Format("{0}\r\n", FileNameHelpers.GetDirectoryName(dirPath)));
                }
            }

            return(stringBuilder.ToString());
        }
        private static void HandleSyntaxTree(SyntaxTreeAnalysisContext context, StyleCopSettings settings)
        {
            var syntaxRoot = context.Tree.GetRoot(context.CancellationToken);

            var descentNodes = syntaxRoot.DescendantNodes(descendIntoChildren: node => node != null && !node.IsKind(SyntaxKind.ClassDeclaration));
            var classNodes   = from descentNode in descentNodes
                               where descentNode.IsKind(SyntaxKind.ClassDeclaration)
                               select descentNode as ClassDeclarationSyntax;

            string suffix;
            var    fileName           = FileNameHelpers.GetFileNameAndSuffix(context.Tree.FilePath, out suffix);
            var    preferredClassNode = classNodes.FirstOrDefault(n => FileNameHelpers.GetConventionalFileName(n, settings.DocumentationRules.FileNamingConvention) == fileName) ?? classNodes.FirstOrDefault();

            if (preferredClassNode == null)
            {
                return;
            }

            string foundClassName = null;
            bool   isPartialClass = false;

            foundClassName = preferredClassNode.Identifier.Text;
            isPartialClass = preferredClassNode.Modifiers.Any(SyntaxKind.PartialKeyword);

            foreach (var classNode in classNodes)
            {
                if (classNode == preferredClassNode || (isPartialClass && foundClassName == classNode.Identifier.Text))
                {
                    continue;
                }

                var location = NamedTypeHelpers.GetNameOrIdentifierLocation(classNode);
                if (location != null)
                {
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, location));
                }
            }
        }
        private static void HandleDifferentSections(ICollection <IDownloadableLink> commonParentLinks)
        {
            var differentSections =
                commonParentLinks
                .Select(link => link.ParentSection)
                .Distinct()
                .ToList();

            if (differentSections.Count > 1)
            {
                foreach (var section in differentSections)
                {
                    var dirName = FileNameHelpers.FullyPrepareDirectory(section.Header.Name, true);

                    var linksWithinThisSection =
                        commonParentLinks
                        .Where(link => link.ParentSection == section)
                        .ToList();

                    AdjustExtraPaths(linksWithinThisSection, null, dirName);
                }
            }
        }
예제 #22
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Replace('/', '\\');

            if (!FileNameHelpers.IsValid(sMessage))
            {
                return(GetMessage(550, "Not a valid directory string."));
            }

            string sDirectory = GetPath(sMessage);

            if (!ConnectionObject.FileSystemObject.DirectoryExists(sDirectory))
            {
                return(GetMessage(550, "Not a valid directory."));
            }

            // Process the current path and remove the last child directory
            string current = ConnectionObject.CurrentDirectory.Replace(@"\", @"/");

            if (current == @"/")
            {
                return(GetMessage(550, "Not a valid directory."));
            }

            int lastDirectoryDelim = current.LastIndexOf(@"/");

            if (lastDirectoryDelim > -1)
            {
                current = current.Remove(lastDirectoryDelim, current.Length - lastDirectoryDelim);
            }


            ConnectionObject.CurrentDirectory = current;
            return(GetMessage(250,
                              string.Format("CWD Successful ({0})", ConnectionObject.CurrentDirectory.Replace("\\", "/"))));
        }
예제 #23
0
        public async Task Download(string[] middlePath)
        {
            await CoursesClient.LazyRefresh();

            await GetNameFromUrlNow();

            string filename;

            switch (SharedVars.NamingMethod)
            {
            case NamingMethod.CoursesName:
                filename = FileFromCourses.FileNameAndExtensionOnly;
                break;

            case NamingMethod.UrlName:
                filename = FileFromUrl.FileNameAndExtensionOnly;
                break;

            default:
                filename = FileFromUrl.FileNameAndExtensionOnly;
                break;
            }

            var filepath = FileNameHelpers.FullyPrepareFile(filename, middlePath);

            FileFromUrl.FullPathAndFileAndExtension = FileFromCourses.FullPathAndFileAndExtension = filepath;

            var fileInfo = new FileInfo(filepath);

            if (!fileInfo.Directory?.Exists ?? false)
            {
                fileInfo.Directory.Create();
            }

            await GetAndSaveFile(filepath);
        }
예제 #24
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();

            if (sMessage == "")
            {
                return(GetMessage(211, "Server status: OK"));
            }

            // if no parameter is given, STAT works as LIST
            // but won't use data connection
            string[] asFiles       = null;
            string[] asDirectories = null;

            // Get the file/dir to list
            string targetToList = GetPath(sMessage);

            // checks the file/dir name
            if (!FileNameHelpers.IsValid(targetToList))
            {
                return(GetMessage(501, string.Format("\"{0}\" is not a valid file/directory name", sMessage)));
            }

            // two vars indicating different list results
            bool targetIsFile = false;
            bool targetIsDir  = false;

            // targetToList ends with '/', must be a directory
            if (targetToList.EndsWith(@"/"))
            {
                targetIsFile = false;
                if (ConnectionObject.FileSystemObject.DirectoryExists(targetToList))
                {
                    targetIsDir = true;
                }
            }
            else
            {
                // check whether the target to list is a directory
                if (ConnectionObject.FileSystemObject.DirectoryExists(FileNameHelpers.AppendDirTag(targetToList)))
                {
                    targetIsDir = true;
                }
                // check whether the target to list is a file
                if (ConnectionObject.FileSystemObject.FileExists(targetToList))
                {
                    targetIsFile = true;
                }
            }

            if (targetIsFile)
            {
                asFiles = new string[1] {
                    targetToList
                };
                if (targetIsDir)
                {
                    asDirectories = new string[1] {
                        FileNameHelpers.AppendDirTag(targetToList)
                    }
                }
                ;
            }
            // list a directory
            else if (targetIsDir)
            {
                targetToList  = FileNameHelpers.AppendDirTag(targetToList);
                asFiles       = ConnectionObject.FileSystemObject.GetFiles(targetToList);
                asDirectories = ConnectionObject.FileSystemObject.GetDirectories(targetToList);
            }
            else
            {
                return(GetMessage(550, string.Format("\"{0}\" not exists", sMessage)));
            }

            // generate the response
            string sFileList = BuildReply(asFiles, asDirectories);

            SocketHelpers.Send(ConnectionObject.Socket, string.Format("213-Begin STAT \"{0}\":\r\n", sMessage), ConnectionObject.Encoding);

            SocketHelpers.Send(ConnectionObject.Socket, sFileList, ConnectionObject.Encoding);

            return(GetMessage(213, string.Format("{0} successful.", Command)));
        }
예제 #25
0
        protected override async Task <string> OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();
            if (sMessage == "")
            {
                return(GetMessage(501, string.Format("{0} needs a parameter", Command)));
            }

            string sFile = GetPath(sMessage);

            if (!FileNameHelpers.IsValid(sFile) || sFile.EndsWith(@"/"))
            {
                return(GetMessage(553, string.Format("\"{0}\" is not a valid file name", sMessage)));
            }

            if (await ConnectionObject.FileSystemObject.FileExists(sFile))
            {
                return(GetMessage(553, string.Format("File \"{0}\" already exists.", sMessage)));
            }

            var socketData = new FtpDataSocket(ConnectionObject);

            if (!socketData.Loaded)
            {
                return(GetMessage(425, "Unable to establish the data connection"));
            }

            IFile file = await ConnectionObject.FileSystemObject.OpenFile(sFile, true);

            if (file == null)
            {
                socketData.Close();// close data socket
                return(GetMessage(550, "Couldn't open file"));
            }

            SocketHelpers.Send(ConnectionObject.Socket, GetMessage(150, "Opening connection for data transfer."), ConnectionObject.Encoding);

            string md5Value = string.Empty;

            // TYPE I, default
            if (ConnectionObject.DataType == DataType.Image)
            {
                // md5 hash function
                MD5 md5Hash = MD5.Create();

                var abData = new byte[m_nBufferSize];

                int nReceived = socketData.Receive(abData);

                while (nReceived > 0)
                {
                    int writeSize = file.Write(abData, nReceived);
                    // maybe error
                    if (writeSize != nReceived)
                    {
                        file.Close();
                        socketData.Close();
                        return(GetMessage(451, "Write data to Azure error!"));
                    }
                    md5Hash.TransformBlock(abData, 0, nReceived, null, 0);
                    nReceived = socketData.Receive(abData);
                }
                md5Hash.TransformFinalBlock(new byte[1], 0, 0);
                md5Value = BytesToStr(md5Hash.Hash);
            }
            // TYPE A
            // won't compute md5, because read characters from client stream
            else if (ConnectionObject.DataType == DataType.Ascii)
            {
                int readSize = SocketHelpers.CopyStreamAscii(socketData.Socket.GetStream(), file.BlobStream, m_nBufferSize);
                FtpServerMessageHandler.SendMessage(ConnectionObject.Id, string.Format("Use ascii type success, read {0} chars!", readSize));
            }
            else
            { // mustn't reach
                file.Close();
                socketData.Close();
                return(GetMessage(451, "Error in transfer data: invalid data type."));
            }

            // upload notification
            await ConnectionObject.FileSystemObject.Log4Upload(sFile);

            file.Close();
            socketData.Close();

            // record md5
            await ConnectionObject.FileSystemObject.SetFileMd5(sFile, md5Value);

            return(GetMessage(226, string.Format("{0} successful", Command)));
        }
예제 #26
0
        private static async Task <Solution> GetTransformedSolutionAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxNode node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true);

            if (!(node is MemberDeclarationSyntax memberDeclarationSyntax))
            {
                return(document.Project.Solution);
            }

            DocumentId extractedDocumentId = DocumentId.CreateNewId(document.Project.Id);
            string     suffix;

            FileNameHelpers.GetFileNameAndSuffix(document.Name, out suffix);
            var    settings = document.Project.AnalyzerOptions.GetStyleCopSettings(root.SyntaxTree, cancellationToken);
            string extractedDocumentName = FileNameHelpers.GetConventionalFileName(memberDeclarationSyntax, settings.DocumentationRules.FileNamingConvention) + suffix;

            List <SyntaxNode> nodesToRemoveFromExtracted = new List <SyntaxNode>();
            SyntaxNode        previous = node;

            for (SyntaxNode current = node.Parent; current != null; previous = current, current = current.Parent)
            {
                foreach (SyntaxNode child in current.ChildNodes())
                {
                    if (child == previous)
                    {
                        continue;
                    }

                    switch (child.Kind())
                    {
                    case SyntaxKind.NamespaceDeclaration:
                    case SyntaxKind.ClassDeclaration:
                    case SyntaxKind.StructDeclaration:
                    case SyntaxKind.InterfaceDeclaration:
                    case SyntaxKind.EnumDeclaration:
                    case SyntaxKind.DelegateDeclaration:
                        nodesToRemoveFromExtracted.Add(child);
                        break;

                    default:
                        break;
                    }
                }
            }

            // Add the new file
            SyntaxNode extractedDocumentNode = root.RemoveNodes(nodesToRemoveFromExtracted, SyntaxRemoveOptions.KeepUnbalancedDirectives);
            Solution   updatedSolution       = document.Project.Solution.AddDocument(extractedDocumentId, extractedDocumentName, extractedDocumentNode, document.Folders);

            // Make sure to also add the file to linked projects
            foreach (var linkedDocumentId in document.GetLinkedDocumentIds())
            {
                DocumentId linkedExtractedDocumentId = DocumentId.CreateNewId(linkedDocumentId.ProjectId);
                updatedSolution = updatedSolution.AddDocument(linkedExtractedDocumentId, extractedDocumentName, extractedDocumentNode, document.Folders);
            }

            // Remove the type from its original location
            updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, root.RemoveNode(node, SyntaxRemoveOptions.KeepUnbalancedDirectives));

            return(updatedSolution);
        }
예제 #27
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();

            string[] asFiles       = null;
            string[] asDirectories = null;

            // Get the file/dir to list
            string targetToList = GetPath(sMessage);

            // checks the file/dir name
            if (!FileNameHelpers.IsValid(targetToList))
            {
                return(GetMessage(501, string.Format("\"{0}\" is not a valid file/directory name", sMessage)));
            }

            // two vars indicating different list results
            bool targetIsFile = false;
            bool targetIsDir  = false;

            // targetToList ends with '/', must be a directory
            if (targetToList.EndsWith(@"/"))
            {
                targetIsFile = false;
                if (ConnectionObject.FileSystemObject.DirectoryExists(targetToList))
                {
                    targetIsDir = true;
                }
            }
            else
            {
                // check whether the target to list is a directory
                if (ConnectionObject.FileSystemObject.DirectoryExists(FileNameHelpers.AppendDirTag(targetToList)))
                {
                    targetIsDir = true;
                }
                // check whether the target to list is a file
                if (ConnectionObject.FileSystemObject.FileExists(targetToList))
                {
                    targetIsFile = true;
                }
            }

            if (targetIsFile)
            {
                asFiles = new string[1] {
                    targetToList
                };
                if (targetIsDir)
                {
                    asDirectories = new string[1] {
                        FileNameHelpers.AppendDirTag(targetToList)
                    }
                }
                ;
            }
            // list a directory
            else if (targetIsDir)
            {
                targetToList  = FileNameHelpers.AppendDirTag(targetToList);
                asFiles       = ConnectionObject.FileSystemObject.GetFiles(targetToList);
                asDirectories = ConnectionObject.FileSystemObject.GetDirectories(targetToList);
            }
            else
            {
                return(GetMessage(550, string.Format("\"{0}\" not exists", sMessage)));
            }

            var socketData = new FtpDataSocket(ConnectionObject);

            if (!socketData.Loaded)
            {
                return(GetMessage(425, "Unable to establish the data connection"));
            }

            // prepare to write response to data channel
            SocketHelpers.Send(ConnectionObject.Socket, string.Format("150 Opening data connection for {0}\r\n", Command), ConnectionObject.Encoding);

            // generate the response
            string sFileList = BuildReply(asFiles, asDirectories);

            // ToDo, send response according to ConnectionObject.DataType, i.e., Ascii or Binary
            socketData.Send(sFileList, Encoding.UTF8);
            socketData.Close();

            return(GetMessage(226, string.Format("{0} successful.", Command)));
        }
예제 #28
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();

            // Get the dir to list
            string targetToList = GetPath(sMessage);

            // checks the dir name
            if (!FileNameHelpers.IsValid(targetToList))
            {
                return(GetMessage(501, $"\"{sMessage}\" is not a valid directory name"));
            }

            // specify the directory tag
            targetToList = FileNameHelpers.AppendDirTag(targetToList);

            bool targetIsDir = ConnectionObject.FileSystemObject.DirectoryExists(targetToList);

            if (!targetIsDir)
            {
                return(GetMessage(550, $"Directory \"{targetToList}\" not exists"));
            }

            #region Generate response

            StringBuilder response = new StringBuilder();

            string[] files       = ConnectionObject.FileSystemObject.GetFiles(targetToList);
            string[] directories = ConnectionObject.FileSystemObject.GetDirectories(targetToList);

            if (files != null && files.Any())
            {
                foreach (var file in files)
                {
                    var fileInfo = ConnectionObject.FileSystemObject.GetFileInfo(file);

                    response.Append(GenerateEntry(fileInfo));

                    response.Append("\r\n");
                }
            }

            if (directories != null && directories.Any())
            {
                foreach (var dir in directories)
                {
                    var dirInfo = ConnectionObject.FileSystemObject.GetDirectoryInfo(dir);

                    response.Append(GenerateEntry(dirInfo));

                    response.Append("\r\n");
                }
            }

            #endregion

            #region Write response

            var socketData = new FtpDataSocket(ConnectionObject);

            if (!socketData.Loaded)
            {
                return(GetMessage(425, "Unable to establish the data connection"));
            }

            SocketHelpers.Send(ConnectionObject.Socket, $"150 {ConnectionObject.DataType} Opening data connection for MLSD {targetToList}\r\n", ConnectionObject.Encoding);

            try
            {
                // ToDo, send response according to ConnectionObject.DataType, i.e., Ascii or Binary
                socketData.Send(response.ToString(), ConnectionObject.Encoding);
            }
            finally
            {
                socketData.Close();
            }

            #endregion

            return(GetMessage(226, "MLSD successful"));
        }
예제 #29
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();
            if (sMessage == "")
            {
                return(GetMessage(501, string.Format("{0} needs a parameter", Command)));
            }

            string sFile = GetPath(sMessage);

            if (!FileNameHelpers.IsValid(sFile) || sFile.EndsWith(@"/"))
            {
                return(GetMessage(553, string.Format("\"{0}\" is not a valid file name", sMessage)));
            }

            if (ConnectionObject.FileSystemObject.FileExists(sFile))
            {
                // 2015-11-24 cljung : RFC959 says STOR commands overwrite files, so delete if exists
                if (!StorageProviderConfiguration.FtpOverwriteFileOnSTOR)
                {
                    return(GetMessage(553, string.Format("File \"{0}\" already exists.", sMessage)));
                }
                Trace.TraceInformation(string.Format("STOR {0} - Deleting existing file", sFile));
                if (!ConnectionObject.FileSystemObject.DeleteFile(sFile))
                {
                    return(GetMessage(550, string.Format("Delete file \"{0}\" failed.", sFile)));
                }
            }

            var socketData = new FtpDataSocket(ConnectionObject);

            if (!socketData.Loaded)
            {
                return(GetMessage(425, "Unable to establish the data connection"));
            }

            Trace.TraceInformation(string.Format("STOR {0} - BEGIN", sFile));

            IFile file = ConnectionObject.FileSystemObject.OpenFile(sFile, true);

            if (file == null)
            {
                socketData.Close();// close data socket
                return(GetMessage(550, "Couldn't open file"));
            }

            SocketHelpers.Send(ConnectionObject.Socket, GetMessage(150, "Opening connection for data transfer."), ConnectionObject.Encoding);

            string md5Value = string.Empty;

            Stopwatch sw = new Stopwatch();

            sw.Start();

            // TYPE I, default
            if (ConnectionObject.DataType == DataType.Image)
            {
                // md5 hash function
                MD5 md5Hash = MD5.Create();

                var abData = new byte[m_nBufferSize];

                int nReceived = socketData.Receive(abData);

                while (nReceived > 0)
                {
                    int writeSize = file.Write(abData, nReceived);
                    // maybe error
                    if (writeSize != nReceived)
                    {
                        file.Close();
                        socketData.Close();
                        FtpServer.LogWrite(this, sMessage, 451, sw.ElapsedMilliseconds);
                        return(GetMessage(451, "Write data to Azure error!"));
                    }
                    md5Hash.TransformBlock(abData, 0, nReceived, null, 0);
                    nReceived = socketData.Receive(abData);
                }
                md5Hash.TransformFinalBlock(new byte[1], 0, 0);
                md5Value = BytesToStr(md5Hash.Hash);
            }
            // TYPE A
            // won't compute md5, because read characters from client stream
            else if (ConnectionObject.DataType == DataType.Ascii)
            {
                int readSize = SocketHelpers.CopyStreamAscii(socketData.Socket.GetStream(), file.BlobStream, m_nBufferSize);
                FtpServerMessageHandler.SendMessage(ConnectionObject.Id, string.Format("Use ascii type success, read {0} chars!", readSize));
            }
            else   // mustn't reach
            {
                file.Close();
                socketData.Close();
                FtpServer.LogWrite(this, sMessage, 451, sw.ElapsedMilliseconds);
                return(GetMessage(451, "Error in transfer data: invalid data type."));
            }

            sw.Stop();
            Trace.TraceInformation(string.Format("STOR {0} - END, Time {1} ms", sFile, sw.ElapsedMilliseconds));

            // upload notification
            ConnectionObject.FileSystemObject.Log4Upload(sFile);

            file.Close();
            socketData.Close();

            // record md5
            ConnectionObject.FileSystemObject.SetFileMd5(sFile, md5Value);

            FtpServer.LogWrite(this, sMessage, 226, sw.ElapsedMilliseconds);
            return(GetMessage(226, string.Format("{0} successful. Time {1} ms", Command, sw.ElapsedMilliseconds)));
        }
예제 #30
0
        private string GetLongProperty(IFileInfo info)
        {
            if (info == null)
            {
                return(null);
            }

            var stringBuilder = new StringBuilder();

            // permissions
            string sAttributes = info.GetAttributeString();

            stringBuilder.Append(sAttributes);
            stringBuilder.Append(" 1 owner group");

            // check whether info is directory
            bool isDirectory = info.IsDirectory();

            // size
            string sFileSize = info.GetSize().ToString(); // if info is directory, the size will be 1

            stringBuilder.Append(TextHelpers.RightAlignString(sFileSize, 13, ' '));
            stringBuilder.Append(" ");

            // modify time
            DateTimeOffset fileDate = info.GetModifiedTime(); //if info is directory, the modify time will be the current time

            // month
            stringBuilder.Append(TextHelpers.Month(fileDate.Month));
            stringBuilder.Append(" ");
            // day
            string sDay = fileDate.Day.ToString();

            if (sDay.Length == 1)
            {
                stringBuilder.Append(" ");
            }
            stringBuilder.Append(sDay);
            stringBuilder.Append(" ");
            // year or hour:min
            if (fileDate.Year < DateTime.Now.Year)
            {
                stringBuilder.Append(" " + fileDate.Year);
            }
            else
            {
                stringBuilder.Append(string.Format("{0:hh}:{1:mm}", fileDate, fileDate));
            }
            stringBuilder.Append(" ");

            // filename
            string path = info.Path();

            if (isDirectory)
            {
                stringBuilder.Append(FileNameHelpers.GetDirectoryName(path));
            }
            else
            {
                stringBuilder.Append(FileNameHelpers.GetFileName(path));
            }

            // end
            stringBuilder.Append("\r\n");

            return(stringBuilder.ToString());
        }