Exemplo n.º 1
0
 public void ProcessPart(FilePart part)
 {
     try
     {
         SafeProcessPart(part);
     }
     catch (Exception ex)
     {
         _exceptionHandler(ex);
     }
 }
Exemplo n.º 2
0
        private static FilePart GetRequestFormsWithMultiPart(string row, HttpMessage httpMessage)
        {
            FilePart filePart = null;

            var sections = row.Split(httpMessage.Boundary, StringSplitOptions.RemoveEmptyEntries);

            if (sections != null)
            {
                foreach (var section in sections)
                {
                    if (section.IndexOf(ConstHelper.CT) > -1)
                    {
                        var arr = section.Split(ConstHelper.ENTER, StringSplitOptions.RemoveEmptyEntries);
                        if (arr != null && arr.Length > 0)
                        {
                            var firsts   = arr[0].Split(";");
                            var name     = firsts[1].Split("=")[1].Replace("\"", "");
                            var fileName = firsts[2].Split("=")[1].Replace("\"", "");
                            var type     = string.Empty;
                            if (arr.Length > 1)
                            {
                                type = arr[1].Split(new[] { ";", ":" }, StringSplitOptions.RemoveEmptyEntries)[1];
                            }
                            filePart = new FilePart(name, fileName, type);
                        }
                    }
                    else
                    {
                        var arr = section.Split(ConstHelper.ENTER, StringSplitOptions.RemoveEmptyEntries);
                        if (arr != null)
                        {
                            if (arr.Length > 0 && arr[0].IndexOf(";") > -1 && arr[0].IndexOf("=") > -1)
                            {
                                var lineArr = arr[0].Split(";");
                                if (lineArr == null)
                                {
                                    continue;
                                }
                                var name  = lineArr[1].Split("=")[1].Replace("\"", "");
                                var value = string.Empty;

                                if (arr.Length > 1)
                                {
                                    value = arr[1];
                                }
                                httpMessage.Forms[name] = value;
                            }
                        }
                    }
                }
            }

            return(filePart);
        }
Exemplo n.º 3
0
 private void SafeProcessPart(FilePart part)
 {
     try
     {
         _part = part;
         ThreadPool.QueueUserWorkItem(Run);
     }
     catch (Exception ex)
     {
         throw new WorkerException("Произошла ошибка в worker", ex);;
     }
 }
Exemplo n.º 4
0
 public void Compress(FilePart part)
 {
     using (var memoryStream = new MemoryStream())
     {
         using (var gzip = new GZipStream(memoryStream, CompressionMode.Compress))
         {
             gzip.Write(part.Source, 0, part.SourceSize);
         }
         part.Source = null;
         part.Result = memoryStream.ToArray();
     }
 }
        internal PostFileDescription(FilePart filepart)
        {
            _name                = filepart.Name;
            _filename            = filepart.FileName;
            _content_disposition = filepart.ContentDisposition;
            _content_type        = filepart.ContentType;
            _content_size        = filepart.Data.Length;

            byte[] buf = new byte[_content_size];
            filepart.Data.Read(buf, 0, (int)_content_size);

            _data = new BinaryDataContext(buf);
        }
Exemplo n.º 6
0
        protected override bool ProcessPart(FilePart part)
        {
            var worker = MakeWorker();

            Logger.Add($"Поток {Thread.CurrentThread.Name} отдал part {part} worker`у {worker.Name}");
            worker.ProcessPart(part);

            // часть последняя - сам поток решает, что ему пора остановиться
            if (part.IsLast)
            {
                SetIsNeedStop();
            }
            return(true);
        }
Exemplo n.º 7
0
        private static FilePart GetRequestFormsWithMultiPart(string row, HttpMessage httpMessage)
        {
            FilePart filePart = null;

            var sections = row.Split(httpMessage.Boundary, StringSplitOptions.RemoveEmptyEntries);

            if (sections != null)
            {
                foreach (var section in sections)
                {
                    if (section.IndexOf(ConstHelper.CT) > -1)
                    {
                        var arr = section.Split(ConstHelper.ENTER, StringSplitOptions.RemoveEmptyEntries);
                        if (arr != null && arr.Length > 0)
                        {
                            var firsts   = arr[0].Split(ConstHelper.SEMICOLON);
                            var name     = firsts[1].Split(ConstHelper.EQUO)[1].Replace("\"", "");
                            var fileName = firsts[2].Split(ConstHelper.EQUO)[1].Replace("\"", "");
                            var type     = string.Empty;
                            if (arr.Length > 1)
                            {
                                type = arr[1].Split(new[] { ConstHelper.SEMICOLON, ConstHelper.COLON }, StringSplitOptions.RemoveEmptyEntries)[1];
                            }
                            filePart = new FilePart(name, fileName, type);
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(section))
                        {
                            var content = section.Trim();

                            var nameLine = content.Substring(0, content.IndexOf(ConstHelper.DENTER));

                            var name = nameLine.Substring(nameLine.IndexOf("=\"") + 2);

                            name = name.Substring(0, name.LastIndexOf(ConstHelper.DOUBLEQUOTES));

                            var value = content.Substring(content.IndexOf(ConstHelper.DENTER) + 2);

                            httpMessage.Forms[name] = value;
                        }
                    }
                }
            }

            return(filePart);
        }
Exemplo n.º 8
0
 private void consumeCompressedFilePart()
 {
     using (ThreadPool threadPool = new ThreadPool()) {
         for (int i = 0; i < m_fileBlocksCount; i++)
         {
             Action compressionJob = () => {
                 m_rawBlockQueue.TryDequeue(out var filePart);
                 var decompressedData     = m_compressor.Decompress(filePart.Data);
                 var decompressedFilePart = new FilePart(decompressedData, filePart.Index);
                 m_processedBlockQueue.Enqueue(decompressedFilePart);
                 m_threadBouncer.Set();
             };
             threadPool.QueueTask(compressionJob);
         }
     }
 }
Exemplo n.º 9
0
        public BlogResponse AddBlog(Stream blogData)
        {
            MultipartFormDataParser dataParser = new MultipartFormDataParser(blogData);

            try
            {
                string   name             = dataParser.GetParameterValue("name");
                string   description      = dataParser.GetParameterValue("description");
                string   titleDescription = dataParser.GetParameterValue("titleDescription");
                FilePart dataParserFile   = dataParser.Files[0];
                string   path             = ServiceHelper.SaveImage(dataParserFile.Data, dataParserFile.FileName);
                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    Blog blog = new Blog
                    {
                        Name             = name,
                        IsDeleted        = false,
                        Description      = description,
                        DateCreated      = DateTime.Now,
                        MediaUrl         = path,
                        TitleDescription = titleDescription
                    };
                    entities.Blogs.Add(blog);
                    entities.SaveChanges();
                    return(new BlogResponse
                    {
                        Name = blog.Name,
                        Description = blog.Description,
                        TitleDescription = blog.TitleDescription,
                        Id = blog.Id,
                        DateCreated = blog.DateCreated.ToLongDateString() + " " + blog.DateCreated.ToLongTimeString(),
                        MediaUrl = blog.MediaUrl
                    });
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = new Dictionary <string, string>
                {
                    { "name", dataParser.GetParameterValue("name") },
                    { "description", dataParser.GetParameterValue("description") },
                    { "titleDescription", dataParser.GetParameterValue("titleDescription") }
                };
                ServiceHelper.LogException(exception, dictionary, ErrorSource.Blog);
                return(new BlogResponse());
            }
        }
Exemplo n.º 10
0
        private void SendFileToQueue(string filePath)
        {
            ConfigurationManager.RefreshSection("appSettings");
            int partSize;

            if (!Int32.TryParse(ConfigurationManager.AppSettings["partSize"], out partSize))
            {
                if (partSize == 0)
                {
                    partSize = 1048576;
                }
            }

            int maxFileSize;

            if (!Int32.TryParse(ConfigurationManager.AppSettings["maxFileSize"], out maxFileSize))
            {
                if (maxFileSize == 0)
                {
                    maxFileSize = 10000000;
                }
            }

            var guid    = Guid.NewGuid();
            var content = File.ReadAllBytes(filePath);

            if (content.Length > maxFileSize)
            {
                throw new InvalidOperationException("File is very large");
            }

            var partCount = content.Length % partSize == 0 ? content.Length / partSize : content.Length / partSize + 1;

            for (int i = 0; i < partCount; i++)
            {
                var bytesToSend = content.Skip(i * partSize).Take(partSize).ToArray();
                var filePart    = new FilePart
                {
                    FileIdentifier = guid,
                    Content        = bytesToSend,
                    FileName       = Path.GetFileName(filePath),
                    Part           = i + 1,
                    IsLastPart     = i + 1 == partCount
                };
                _queueClient.Send(new BrokeredMessage(filePart));
            }
        }
Exemplo n.º 11
0
        public void TestNotFirstTitle()
        {
            var input       = new byte[] { 1, 31, 139, 8, 0, 0, 0, 0, 0, 4, 0 };
            var inputStream = MakeInputStream(input);

            try
            {
                var reader = new ArсhivePartReader(new LoggerDummy());
                reader.Init(inputStream, input.Length);
                var part = new FilePart("dummyName");
                reader.ReadPart(part);
            }
            finally
            {
                inputStream.Close();
            }
        }
Exemplo n.º 12
0
        public override bool ReadPart(FilePart part)
        {
            part.Source = new byte[_strategy.PartSize];
            var count = SourceStream.Read(part.Source, 0, part.Source.Length);

            part.SourceSize = count;

            _totalReadByte = _totalReadByte + count;
            // прочитали всё - у части выставляем признак, что она последняя
            if (_totalReadByte != SourceFileSize)
            {
                return(true);
            }
            part.IsLast = true;
            Logger.Add($"Поток {Thread.CurrentThread.Name} прочитал последнюю часть файла {part} ");
            return(true);
        }
Exemplo n.º 13
0
        private void writeCompressedParts()
        {
            using (var fileStream = new FileStream(m_outputFile, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, c_blockSize)) {
                writeCustomHeader(fileStream);
                int i = 0;
                while (i < m_fileBlocksCount)
                {
                    FilePart minIndexPart = null;
                    // wait while filePart with exact index doesnt come
                    while (minIndexPart == null || minIndexPart.Index != i)
                    {
                        m_threadBouncer.WaitOne();
                        FilePart tempMin = null;
                        try {
                            tempMin = m_processedBlockQueue.MinValue;
                        } catch (InvalidOperationException ex) {
                        }
                        minIndexPart = tempMin;
                    }
                    // Sort all queue after new minValue
                    m_processedBlockQueue.Sort(new Sorters.ShellSort <FilePart>());
                    FilePart currentFilePart = null;
                    do
                    {
                        // Erase item with minimal Index
                        if (!m_processedBlockQueue.TryDequeue(out currentFilePart))
                        {
                            return;
                        }
                        byte[] blockHeader = BitConverter.GetBytes(currentFilePart.Data.Length);
                        // write header
                        fileStream.Write(blockHeader, 0, blockHeader.Length);
                        // write payload
                        fileStream.Write(currentFilePart.Data, 0, currentFilePart.Data.Length);
                        i++;
                        try {
                            currentFilePart = m_processedBlockQueue.GetPeek();
                        } catch (InvalidOperationException ex) {
                        }
                    } while (currentFilePart != null && currentFilePart.Index == i && i < m_fileBlocksCount);

                    m_processedBlockQueue.ForceFindNewMin();
                }
            }
        }
Exemplo n.º 14
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void processMultiPart(javax.servlet.http.HttpServletRequest req, javax.servlet.http.HttpServletResponse resp) throws java.io.IOException
        private void processMultiPart(HttpServletRequest req, HttpServletResponse resp)
        {
            PrintWriter @out = resp.Writer;

            resp.ContentType = "text/plain";
            MultipartParser mp   = new MultipartParser(req, 2048);
            Part            part = null;

            while ((part = mp.readNextPart()) != null)
            {
                string name = part.Name.Trim();
                if (part.Param)
                {
                    // it's a parameter part
                    ParamPart paramPart = (ParamPart)part;
                    string    value     = paramPart.StringValue.Trim();
                    LOG.info("param; name=" + name + ", value=" + value);
                    @out.print("param; name=" + name + ", value=" + value);
                }
                else if (part.File)
                {
                    // it's a file part
                    FilePart filePart = (FilePart)part;
                    string   fileName = filePart.FileName;
                    if (!string.ReferenceEquals(fileName, null))
                    {
                        // the part actually contained a file
                        // StringWriter sw = new StringWriter();
                        // long size = filePart.writeTo(new File(System
                        // .getProperty("java.io.tmpdir")));
                        System.IO.MemoryStream baos = new System.IO.MemoryStream();
                        long size = filePart.writeTo(baos);
                        LOG.info("file; name=" + name + "; filename=" + fileName + ", filePath=" + filePart.FilePath + ", content type=" + filePart.ContentType + ", size=" + size);
                        @out.print(string.Format("{0}: {1}", name, (StringHelperClass.NewString(baos.toByteArray())).Trim()));
                    }
                    else
                    {
                        // the field did not contain a file
                        LOG.info("file; name=" + name + "; EMPTY");
                    }
                    @out.flush();
                }
            }
            resp.Status = HttpServletResponse.SC_OK;
        }
Exemplo n.º 15
0
        public static string getFilePart(FilePart filePart, string fileFolder, string fileName, string filePath = null)
        {
            string path = filePath;

            if (path == null)
            {
                if (fileFolder == null || fileName == null)
                {
                    return(null);
                }
                path = Path.Combine(fileFolder, fileName);
            }
            switch (filePart)
            {
            case FilePart.Path_Name_Extension:
                return(CorrectFilePath(path, true, true));

            case FilePart.RelativePath_Name_Extension:
                path = CorrectFilePath(path, true, true);
                path = StripPrefix(path, ArcadeManager.applicationPath);
                return(path == null ? null : CorrectFilePath(path, true));

            case FilePart.Path:
                return(CorrectFilePath(Path.GetDirectoryName(path), false, true));

            case FilePart.RelativePath:
                path = CorrectFilePath(path, true, true);
                path = StripPrefix(Path.GetDirectoryName(path), ArcadeManager.applicationPath);
                return(path == null ? null : CorrectFilePath(path));

            case FilePart.Name_Extension:
                return(Path.GetFileName(path));

            case FilePart.Name:
                return(Path.GetFileNameWithoutExtension(path));

            case FilePart.Extension:
                return(Path.GetExtension(path));

            default:
                return(null);
            }
        }
Exemplo n.º 16
0
 public PartUploadedEventArgs(
     int resourceId,
     Guid sessionId,
     string fileName,
     FilePart filePart,
     string statusCode,
     int totalFileParts,
     int numPartsUploaded,
     TimeSpan estimatedTimeRemaining)
 {
     this.FileName               = fileName;
     this.FilePart               = filePart;
     this.StatusCode             = statusCode;
     this.TotalFileParts         = totalFileParts;
     this.NumPartsUploaded       = numPartsUploaded;
     this.EstimatedTimeRemaining = estimatedTimeRemaining;
     this.SessionId              = sessionId;
     this.ResourceId             = resourceId;
 }
Exemplo n.º 17
0
        public File SplitStream(Stream stream, int partsCount, string fileName)
        {
            var file         = new File();
            var memoryStream = new MemoryStream();

            stream.CopyTo(memoryStream);
            var bytesArray = memoryStream.ToArray();

            file.FileParts = new List <FilePart>();
            if (partsCount < bytesArray.Length)
            {
                for (int i = 0; i < partsCount; i++)
                {
                    var filePart = new FilePart
                    {
                        Id          = new Guid(),
                        Name        = fileName + i,
                        PartNumber  = i,
                        SummaryInfo = new FileSummaryInfo
                        {
                            FileName  = fileName,
                            FileParts = new List <FilePartInfo>()
                        }
                    };
                    var arraySize = i == partsCount - 1
                        ? bytesArray.Length / partsCount
                        : (int)Math.Round((double)bytesArray.Length / partsCount);
                    var bytesArrayPart = new byte[arraySize];
                    for (int j = 0; j < arraySize; j++)
                    {
                        bytesArrayPart[j] = bytesArray[arraySize * i + j];
                    }
                    filePart.DataBytesArray = bytesArrayPart;
                    file.FileParts.Add(filePart);
                }
            }
            foreach (var filePart in file.FileParts)
            {
                filePart.SummaryInfo.FileParts = new List <FilePartInfo>(file.FileParts.Select(f => f as FilePartInfo));
            }
            return(file);
        }
Exemplo n.º 18
0
        public static string DialogGetFilePart(string fileName, string filePath, FilePart filePart, string fileExtension = "")
        {
            if (filePath == null)
            {
                filePath = Path.Combine(ArcadeManager.applicationPath + "/3darcade~/");
            }
            var extensions = new[] {
                new SFB.ExtensionFilter("extensions", fileExtension.Split(','))
            };

            string[] paths = StandaloneFileBrowser.OpenFilePanel(fileName, filePath, extensions, false);
            string   path  = null;

            if (paths.Length < 1)
            {
                return(path);
            }
            path = paths[0];
            return(getFilePart(filePart, null, null, path));
        }
Exemplo n.º 19
0
        public void SaveFilePart(FilePart part)
        {
            var filePath = CreateLocalFilePath(part);

            TryCreateFile(filePath);

            AddProcessingFile(part, filePath);

            using (var stream = new FileStream(filePath, FileMode.Append))
            {
                stream.Write(part.Content, 0, part.Content.Length);
            }

            if (part.IsLastPart)
            {
                RemoveProcessingFile(part);
                MoveCompletedFile(filePath);
                SaveState();
            }
        }
Exemplo n.º 20
0
 private SerialWorkQueue.Work MakeWork(FilePart filePart)
 {
     return((SerialWorkQueue.Work)(() =>
     {
         try
         {
             if (filePart.Check())
             {
                 Logger.Info(filePart.Path + " is already downloaded");
             }
             else
             {
                 this.DownloadFilePart(filePart);
             }
         }
         catch (Exception ex)
         {
             Logger.Error(ex.ToString());
         }
     }));
 }
Exemplo n.º 21
0
        protected override bool ProcessPart(FilePart part)
        {
            if (_sourceStream == null)
            {
                var fileName = _sourceFileNameProvider.GetFileName();
                _sourceStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                _partReader.Init(_sourceStream, new FileInfo(fileName).Length);
            }
            try
            {
                _processingStopwatch.Reset();
                _processingStopwatch.Start();

                if (_partReader.ReadPart(part))
                {
                    _processingStopwatch.Stop();

                    part.Index = _currentPartIndex;
                    _currentPartIndex++;
                    Logger.Add($"Поток {Thread.CurrentThread.Name} прочитал часть {part} {part.Source.Length} byte за {_processingStopwatch.ElapsedMilliseconds} ms");

                    NextQueue?.Add(part);

                    // часть последняя - сам поток решает, что ему пора остановиться
                    if (part.IsLast)
                    {
                        SetIsNeedStop();
                    }
                    return(true);
                }
                Logger.Add($"!Поток {Thread.CurrentThread.Name} НЕ удалось прочитать часть {part}");
                throw new Exception($"Не удалось прочитать часть {part}");
            }
            catch (Exception)
            {
                Logger.Add($"Поток {Thread.CurrentThread.Name} - ошибка при чтении");
                Close();
                throw;
            }
        }
Exemplo n.º 22
0
        public void TestEmptyStream()
        {
            var input       = new byte[] {};
            var inputStream = new MemoryStream();

            try
            {
                var reader = new ArсhivePartReader(new LoggerDummy());
                reader.Init(inputStream, 0);
                var part = new FilePart("dummyName");
                var res  = reader.ReadPart(part);

                Assert.IsTrue(res, "не удалось проинициализировать part из пустого потока");
                Assert.IsNotNull(part.Source, "у непроинициализированной части source должен быть Null");
                Assert.IsTrue(part.Source.SequenceEqual(input), "part.Source");
                Assert.IsTrue(part.IsLast, "part.IsLast");
            }
            finally
            {
                inputStream.Close();
            }
        }
Exemplo n.º 23
0
 public void Build()
 {
     using (StreamReader streamReader = new StreamReader((Stream)File.OpenRead(this.m_FilePath)))
     {
         string str1;
         while ((str1 = streamReader.ReadLine()) != null)
         {
             string[] strArray = str1.Split(' ');
             string   str2     = strArray[0];
             long     int64    = Convert.ToInt64(strArray[1], (IFormatProvider)CultureInfo.InvariantCulture);
             string   sha1     = strArray[2];
             string   path     = Path.Combine(Path.GetDirectoryName(this.m_FilePath), str2);
             FilePart filePart = new FilePart(str2, int64, sha1, path);
             if (filePart.Check())
             {
                 filePart.DownloadedSize = filePart.Size;
             }
             this.m_FileParts.Add(filePart);
             this.FileSize += int64;
         }
     }
 }
Exemplo n.º 24
0
        public void TestOnlyTitle(int bufferSize)
        {
            var input       = new byte[] { 31, 139, 8, 0, 0, 0, 0, 0, 4, 0 };
            var inputStream = MakeInputStream(input);

            try
            {
                var reader = new ArсhivePartReader(new LoggerDummy());
                reader.Init(inputStream, input.Length);
                reader.BufferSize = bufferSize;
                var part = new FilePart("dummyName");
                var res  = reader.ReadPart(part);

                Assert.IsTrue(res, "не удалось проинициализировать часть");
                Assert.IsNotNull(part.Source, "part.Source = null");
                Assert.IsTrue(input.SequenceEqual(part.Source), "неверный part.Source");
                Assert.IsTrue(part.IsLast, "part.IsLast");
            }
            finally
            {
                inputStream.Close();
            }
        }
Exemplo n.º 25
0
        internal async Task <bool> UploadNew
            (R1Executable localExe, double?maxVolumeSizeMB)
        {
            IsBusy = true;
            Status = "Compressing ...";
            var tmpCopy    = CopyToTemp(localExe.FullPathOrURL);
            var splitParts = new List <R1SplitPart>();
            var partPaths  = await SevenZipper1.Compress(tmpCopy, null, maxVolumeSizeMB, ".data");

            for (int i = 0; i < partPaths.Count; i++)
            {
                Status = $"Uploading part {i + 1} of {partPaths.Count} ...";

                var r1Part = FilePart.ToR1Part(partPaths[i],
                                               localExe, i + 1, partPaths.Count);

                var node = await Create(r1Part,
                                        () => GetSplitPartIDsByHash(r1Part.PartHash));

                if (node == null)
                {
                    return(false);
                }
                splitParts.Add(r1Part);
            }

            var ok = await ValidateDownload(splitParts, localExe.FileHash);

            if (!ok)
            {
                //todo: delete corrupted uploaded parts
                return(Alerter.Warn("Uploaded parts are invalid.", false));
            }

            IsBusy = false;
            return(true);
        }
Exemplo n.º 26
0
        protected virtual FilePart ProcessPart(FilePart filePart)
        {
            if (filePart == null)
            {
                return(null);
            }

            using (var memoryStream = new MemoryStream())
            {
                using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress))
                {
                    gZipStream.Write(filePart.Bytes, 0, filePart.Bytes.Length);
                }

                var compressedBytes = memoryStream.ToArray();
                BitConverter.GetBytes(compressedBytes.Length).CopyTo(compressedBytes, 4);

                return(new FilePart
                {
                    Index = filePart.Index,
                    Bytes = compressedBytes
                });
            }
        }
Exemplo n.º 27
0
 public void Add(FilePart part)
 {
     this.files.Add(part);
 }
Exemplo n.º 28
0
        public ActionResult UpdateUserDetails(Stream userData)
        {
            MultipartFormDataParser dataParser = new MultipartFormDataParser(userData);

            try
            {
                string aboutMe     = dataParser.GetParameterValue("aboutMe");
                string address     = dataParser.GetParameterValue("address");
                string city        = dataParser.GetParameterValue("city");
                string country     = dataParser.GetParameterValue("country");
                string firstName   = dataParser.GetParameterValue("firstName");
                string lastName    = dataParser.GetParameterValue("lastName");
                string token       = dataParser.GetParameterValue("token");
                string phoneNumber = dataParser.GetParameterValue("phonenumber");
                string email       = dataParser.GetParameterValue("email");

                AuthenticationService authenticationService = new AuthenticationService();
                IPrincipal            jwtToken = authenticationService.AuthenticateJwtToken(token);
                string userId = jwtToken.Identity.GetUserId();
                string path   = null;
                if (dataParser.Files.Any())
                {
                    FilePart dataParserFile = dataParser.Files[0];
                    path = ServiceHelper.SaveImage(dataParserFile.Data, dataParserFile.FileName);
                }

                using (ESamhashoEntities entities = new ESamhashoEntities())
                {
                    AspNetUser netUser = entities.AspNetUsers.FirstOrDefault(a => a.Id.Equals(userId));
                    if (netUser != null)
                    {
                        netUser.Email       = String.IsNullOrEmpty(email) ? netUser.Email : email;
                        netUser.PhoneNumber = String.IsNullOrEmpty(phoneNumber) ? netUser.PhoneNumber : phoneNumber;
                    }
                    UserProfile userProfile = entities.UserProfiles.FirstOrDefault(a => a.UserId.Equals(userId));
                    if (userProfile != null)
                    {
                        userProfile.AboutMe        = String.IsNullOrEmpty(aboutMe) ? userProfile.AboutMe : aboutMe;
                        userProfile.Address        = String.IsNullOrEmpty(address) ? userProfile.Address : address;
                        userProfile.City           = String.IsNullOrEmpty(city) ? userProfile.City : city;
                        userProfile.Country        = String.IsNullOrEmpty(country) ? userProfile.Country : country;
                        userProfile.FirstName      = String.IsNullOrEmpty(firstName) ? userProfile.FirstName : firstName;
                        userProfile.LastName       = String.IsNullOrEmpty(lastName) ? userProfile.LastName : lastName;
                        userProfile.ProfilePicture = String.IsNullOrEmpty(path)?userProfile.ProfilePicture:path;
                        userProfile.UserId         = userId;
                    }
                    else
                    {
                        UserProfile addUserProfile = new UserProfile
                        {
                            DateCreated    = DateTime.Now,
                            AboutMe        = aboutMe,
                            Address        = address,
                            City           = city,
                            Country        = country,
                            FirstName      = firstName,
                            LastName       = lastName,
                            ProfilePicture = path,
                            UserId         = userId
                        };
                        entities.UserProfiles.Add(addUserProfile);
                    }
                    entities.SaveChanges();
                    return(new ActionResult
                    {
                        Message = path,
                        Success = true
                    });
                }
            }
            catch (Exception exception)
            {
                Dictionary <string, string> dictionary = new Dictionary <string, string>
                {
                    { "aboutMe", dataParser.GetParameterValue("aboutMe") },
                    { "address", dataParser.GetParameterValue("address") },
                    { "city", dataParser.GetParameterValue("city") },
                    { "country", dataParser.GetParameterValue("country") },
                    { "firstName", dataParser.GetParameterValue("firstName") },
                    { "lastName", dataParser.GetParameterValue("lastName") },
                    { "userId", dataParser.GetParameterValue("userId") }
                };
                ServiceHelper.LogException(exception, dictionary, ErrorSource.User);
                return(new ActionResult
                {
                    Message = "Failed to save profile, try again.",
                    Success = true
                });
            }
        }
Exemplo n.º 29
0
        public void UploadFile(Stream stream, string workflowId_)
        {
            var parser = MultipartFormDataParser.Parse(stream);

            string typology = parser.GetParameterValue("typology");                 //separate by ,
            string clients  = parser.GetParameterValue("clients");                  // separate by ,
            bool   standard = bool.Parse(parser.GetParameterValue("packStandard")); //string "true" "false"

            // Files are stored in a list:
            FilePart file     = parser.Files.First();
            string   FileName = file.FileName;

            int workflowId = int.Parse(workflowId_);

            //EST CE QUE LE DOSSIER TEMP EXISTE
            if (Directory.Exists(ParamAppli.DossierTemporaire) == false)
            {
                Directory.CreateDirectory(ParamAppli.DossierTemporaire);
            }

            string FilePath = Path.Combine(ParamAppli.DossierTemporaire, FileName);

            using (FileStream fileStream = File.Create(FilePath))
            {
                file.Data.Seek(0, SeekOrigin.Begin);
                file.Data.CopyTo(fileStream);
            }

            GereMDBDansBDD gestionMDBdansBDD = new GereMDBDansBDD();

            //AJOUT DU ZIP DE MDB DANS LA BDD
            gestionMDBdansBDD.AjouteZipBDD(FilePath, workflowId, ParamAppli.ConnectionStringBaseAppli);
            string clientToLaunch = "";

            //Bring all client
            if ((String.IsNullOrEmpty(clients) || clients == "undefined") && !String.IsNullOrEmpty(typology))
            {
                //REQUETE
                int typologyId = Int32.Parse(typology);
                IEnumerable <InfoClient> listClient = RequestTool.getClientsWithTypologies(typologyId);
                foreach (InfoClient client in listClient)
                {
                    clientToLaunch = clientToLaunch + client.ID_CLIENT + ",";
                }
                clientToLaunch = clientToLaunch.Remove(clientToLaunch.Length - 1);
            }
            else if (!String.IsNullOrEmpty(clients) && !String.IsNullOrEmpty(typology))
            {
                //Récupérer les clients du front
                clientToLaunch = clients;
            }
            else
            {
                //GENERATE EXCEPTION
                throw new Exception();
            }

            //Launch process
            LaunchProcess(ParamAppli.ProcessControlePacks, workflowId, clientToLaunch);

            //SUPPRESSION DU FICHIER
            File.Delete(FilePath);
        }
Exemplo n.º 30
0
 public Stream OpenEntryStream()
 {
     return(FilePart.GetCompressedStream());
 }
Exemplo n.º 31
0
 public CheckFileResult(ActionResult actionResult, FilePart filePart = null, FileInfo fileInfo = null) {
     this.ActionResult = actionResult;
     this.FilePart = filePart;
     this.FileInfo = fileInfo;
 }