Example #1
0
        public UploadFileResponse UploadAttachFileToTemp(BLL.AttachFilesIAS.AttachFile attachFile, Stream fileStream)
        {
            String brokenRuleString = ThrowExceptionIfUploadInvalid(attachFile);

            if (!String.IsNullOrEmpty(brokenRuleString))
            {
                throw new ApplicationException(brokenRuleString);
            }
            UploadFileResponse response = new UploadFileResponse();

            using (FileService.FileTransferServiceClient svc = new FileService.FileTransferServiceClient())
            {
                String fs_container = String.Format(@"{0}\{1}", TempFileContainer, attachFile.REGISTRATION_ID);

                String filename = String.Format("{0}{1}", IAS.BLL.Helpers.GenerateIdHelper.GetGenAutoId(), attachFile.EXTENSION);

                UploadFileResponse res = svc.UploadFile(new UploadFileRequest()
                {
                    TargetContainer = fs_container,
                    TargetFileName  = filename,
                    FileStream      = fileStream
                });

                return(res);

                //if (response.Code != "0000")
                //    throw new IOException(response.Message);

                //attachFile.ATTACH_FILE_PATH = response.TargetFullName;
            }
            return(response);
        }
        public static UploadFileResponse Unmarshall(UnmarshallerContext context)
        {
            UploadFileResponse uploadFileResponse = new UploadFileResponse();

            uploadFileResponse.HttpResponse = context.HttpResponse;
            uploadFileResponse.Code         = context.StringValue("UploadFile.Code");
            uploadFileResponse.Message      = context.StringValue("UploadFile.Message");
            uploadFileResponse.RequestId    = context.StringValue("UploadFile.RequestId");

            UploadFileResponse.UploadFile_Data data = new UploadFileResponse.UploadFile_Data();

            List <UploadFileResponse.UploadFile_Data.UploadFile_OssPath> data_records = new List <UploadFileResponse.UploadFile_Data.UploadFile_OssPath>();

            for (int i = 0; i < context.Length("UploadFile.Data.Records.Length"); i++)
            {
                UploadFileResponse.UploadFile_Data.UploadFile_OssPath ossPath = new UploadFileResponse.UploadFile_Data.UploadFile_OssPath();
                ossPath.OssPath  = context.StringValue("UploadFile.Data.Records[" + i + "].OssPath");
                ossPath.SourceId = context.StringValue("UploadFile.Data.Records[" + i + "].SourceId");

                data_records.Add(ossPath);
            }
            data.Records            = data_records;
            uploadFileResponse.Data = data;

            return(uploadFileResponse);
        }
Example #3
0
        //public DTO.PersonAttatchFile SaveToEditAttachFilePath(DTO.PersonAttatchFile newAttachFile, DTO.PersonAttatchFile oldAttachFile, Stream fileSteam)
        //{
        //    DTO.RegistrationAttatchFile _newAttachFile =  new DTO.RegistrationAttatchFile();
        //    DTO.RegistrationAttatchFile _oldAttachFile = new DTO.RegistrationAttatchFile();
        //    newAttachFile.MappingToEntity<DTO.RegistrationAttatchFile>(_newAttachFile);
        //    oldAttachFile.MappingToEntity<DTO.RegistrationAttatchFile>(_oldAttachFile);

        //    using (FileService.FileTransferServiceClient svc = new FileService.FileTransferServiceClient())
        //    {

        //        String findString = "_"+oldAttachFile.ATTACH_FILE_TYPE.ToInt().ToString("00");
        //        String newfileName = oldAttachFile.ATTACH_FILE_PATH.Replace(findString, findString + IAS.BLL.Helpers.GenerateIdHelper.GetGenAutoId());


        //        MoveFileResponse moveResponse = svc.MoveFile("", oldAttachFile.ATTACH_FILE_PATH, "", newfileName);
        //        if (moveResponse.Code != "0000")
        //            throw new IOException(moveResponse.Message);

        //        DeleteFileResponse deleteResponse = svc.DeleteFile(oldAttachFile.ATTACH_FILE_PATH);
        //        if (deleteResponse.Code != "0000")
        //            throw new IOException(deleteResponse.Message);

        //        UploadFileResponse uploadResponse = svc.UploadFile("", oldAttachFile.ATTACH_FILE_PATH, fileSteam);
        //        if (uploadResponse.Code != "0000")
        //            throw new IOException(uploadResponse.Message);



        //        _newAttachFile.ATTACH_FILE_PATH = uploadResponse.TargetFullName;

        //    }
        //    _newAttachFile.MappingToEntity<DTO.RegistrationAttatchFile, DTO.PersonAttatchFile>(newAttachFile);
        //    return newAttachFile;

        //}

        public DTO.RegistrationAttatchFile SaveToAttachFilePath(DTO.RegistrationAttatchFile attachFile, Stream fileSteam)
        {
            using (FileService.FileTransferServiceClient svc = new FileService.FileTransferServiceClient())
            {
                UploadFileResponse response     = new UploadFileResponse();
                String             fs_container = String.Format(@"{0}\{1}", AttachFileContainer, attachFile.TempFilePath);

                //String newFileName = this.ID_CARD_NO + "_"
                //                                    + Convert.ToInt32(attachFile.ATTACH_FILE_TYPE).ToString("00")
                //                                    + "." + GetExtensionFile(attachFile.FileName);

                response = svc.UploadFile(new UploadFileRequest()
                {
                    TargetContainer = fs_container,
                    TargetFileName  = attachFile.FileName,
                    FileStream      = fileSteam
                });
                if (response.Code != "0000")
                {
                    throw new IOException(response.Message);
                }

                attachFile.ATTACH_FILE_PATH = response.TargetFullName;
            }

            return(attachFile);
        }
Example #4
0
        UploadTo(Stream fileUploadStream, string localFileName, string targetFolder, string targetFileName, string fsFolder)
        {
            var res = new DTO.ResponseService <string>();
            //var resMsg = new FileService.FileUploadMessage();
            UploadFileResponse response = new UploadFileResponse();

            try
            {
                //resMsg.FileByteStream = fileUploadStream;
                //resMsg.Metadata = new FileService.FileMetaData
                //{
                //    localFilename = localFileName,
                //    remoteFilename = targetFileName,
                //    targetFolder = string.Format(fsFolder + @"\{0}\", targetFolder),
                //};

                response = svc.UploadFile(new UploadFileRequest()
                {
                    TargetContainer = String.Format(fsFolder + @"\{0}\", targetFolder),
                    TargetFileName  = targetFileName,
                    FileStream      = fileUploadStream
                });
                //svc.UploadFile(ref resMsg.Metadata, ref fileUploadStream);

                res.DataResponse = response.Message; // resMsg.Metadata.resMsg;
            }
            catch (Exception ex)
            {
                res.ErrorMsg = "กรุณาติดต่อผู้ดูแลระบบ"; // +resMsg.Metadata.resMsg;
            }
            return(res);
        }
Example #5
0
        private void EscribeServidor2(StringBuilder registros)
        {
            string strFileName     = "ListaNegra.txt";
            string _tipoArchivoDir = "";

            _tipoArchivoDir = "PLD";
            string strType    = "txt";
            string directorio = Repositorio + _tipoArchivoDir + @"\";

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();


            byte[] hfc = (byte[])encoding.GetBytes(registros.ToString());
            IwsDocumentHandlingClient proxy    = new IwsDocumentHandlingClient();
            RemoteFileInfoRequest     request  = new RemoteFileInfoRequest();
            UploadFileResponse        response = new UploadFileResponse();

            long length = (long)hfc.Length;

            byte[] buffer2 = hfc;
            request.data          = buffer2;
            request.FileName      = strFileName;
            request.Length        = length;
            request.strServerPath = directorio;
            response = proxy.UploadFile(request);
        }
Example #6
0
        public UploadFileResponse SendUploadFileRequest(UploadFileRequest request)
        {
            UploadFileResponse response = new UploadFileResponse();

            var rpcClient  = new XmlRpcRestClient(config.RequestUrl);
            var rpcRequest = new XmlRpcRestRequest(request.RequestUrl)
            {
                Method = Method.POST
            };

            // Add request parameters
            //rpcRequest.XmlSerializer = new XmlRpcSerializer("",false);
            rpcRequest.AddXmlRpcBody(config.BlogID, config.Username, config.Password, request.FileRequestStruct, "true", "false");

            try
            {
                // Get response
                var rpcResponse = rpcClient.Execute <RpcResponseValue <string> >(rpcRequest);

                // Find and fill members in
                XmlMemberSearcher searcher = new XmlMemberSearcher(rpcResponse.Content);
                response.FileResponseStruct.Id       = Convert.ToInt32(searcher.GetValueOfMember("id"));
                response.FileResponseStruct.Url      = searcher.GetValueOfMember("url");
                response.FileResponseStruct.File     = searcher.GetValueOfMember("file");
                response.FileResponseStruct.FileType = searcher.GetValueOfMember("type");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(null);
            }

            return(response);
        }
Example #7
0
        private void AddAttechFile(DTO.AttachFile attachFile)
        {
            if (((List <DTO.AttachFile>)Session["AttachFiles"]).Where(a => a.AttechType == attachFile.AttechType).Count() > 0)
            {
                throw new ApplicationException(Resources.errorTestUploadData_002);
            }
            else
            {
                using (svc = new FileService.FileTransferServiceClient()) {
                    UploadFileResponse response  = new UploadFileResponse();
                    Stream             fileStrem = fUpload.PostedFile.InputStream;
                    response = svc.UploadFile(new UploadFileRequest()
                    {
                        TargetContainer = attachFile.TargetContainer,
                        TargetFileName  = attachFile.TargetFileName,
                        FileStream      = fileStrem
                    });

                    attachFile.TargetFullName = CryptoBase64.Encryption(response.TargetFullName);
                    ((List <DTO.AttachFile>)Session["AttachFiles"]).Add(attachFile);
                    gv.DataSource = ((List <DTO.AttachFile>)Session["AttachFiles"]);
                    gv.DataBind();
                }
            }
        }
Example #8
0
        public virtual void AddAttach(DTO.PersonAttatchFile attachFile, Stream fileSteam)
        {
            if (_attachFiles.Where(a => a.REGISTRATION_ID == attachFile.REGISTRATION_ID && a.ATTACH_FILE_TYPE == attachFile.ATTACH_FILE_TYPE).Count() > 0)
            {
                throw new PersonalIssueException(Resources.errorBasePersonal_001);
            }
            using (FileService.FileTransferServiceClient svc = new FileService.FileTransferServiceClient())
            {
                UploadFileResponse response = new UploadFileResponse();

                String fs_Attach = String.Format(@"{0}\{1}", AttachFileContainer, attachFile.REGISTRATION_ID);

                String newFileName = this.ID_CARD_NO + "_"
                                     + Convert.ToInt32(attachFile.ATTACH_FILE_TYPE).ToString("00")
                                     + "." + GetExtensionFile(attachFile.FileName);
                //response = svc.UploadFile(new UploadFileRequest() {
                //                                TargetContainer = fs_Attach,
                //                                TargetFileName = newFileName,
                //                                FileStream = fileSteam
                //                            });
                if (response.Code != "0000")
                {
                    throw new PersonalIssueException(response.Message);
                }

                attachFile.ATTACH_FILE_PATH = response.TargetFullName;
                attachFile.ID = IAS.BLL.Helpers.GenerateIdHelper.GetGenAutoId();
                _attachFiles.Add(attachFile);
            }
        }
Example #9
0
        public DTO.PersonAttatchFile SaveEditAttachFileTemp(DTO.PersonAttatchFile attachFile, Stream fileSteam)
        {
            using (FileService.FileTransferServiceClient svc = new FileService.FileTransferServiceClient())
            {
                UploadFileResponse response     = new UploadFileResponse();
                String             fs_container = String.Format(@"{0}\{1}", TempFileContainer, attachFile.TempFilePath);

                String filename = String.Format("{0}.{1}", IAS.BLL.Helpers.GenerateIdHelper.GetGenAutoId(), attachFile.FileName.Split('.')[attachFile.FileName.Split('.').Length - 1]);
                response = svc.UploadFile(new UploadFileRequest()
                {
                    TargetContainer = fs_container,
                    TargetFileName  = filename,
                    FileStream      = fileSteam
                });

                if (response.Code != "0000")
                {
                    throw new IOException(response.Message);
                }

                attachFile.ATTACH_FILE_PATH = response.TargetFullName;
                attachFile.FILE_STATUS      = "W";
            }

            return(attachFile);
        }
Example #10
0
        public async Task <IActionResult> UploadFile([FromBody] UploadFileModel model)
        {
            #region Validation

            if (!ModelState.IsValid)
            {
                return(BadRequest(ErrorResponse.Create(ModelState)));
            }

            #endregion

            try
            {
                var fileData = Convert.FromBase64String(model.FileData);
                var fileId   = await _service.UploadFileAsync(model.FileName, fileData, model.ParentFolderGoogleId);

                var response = new UploadFileResponse()
                {
                    GoogleId = fileId
                };

                return(Ok(response));
            }
            catch (Exception ex)
            {
                await _log.WriteErrorAsync("GoogleDriveController", nameof(UploadFile), string.Empty, ex);

                return(StatusCode(500, ErrorResponse.Create(ex.Message)));
            }
        }
Example #11
0
        public override async Task <UploadFileResponse> UploadFile(
            IAsyncStreamReader <UploadFileRequest> requestStream, ServerCallContext context)
        {
            UploadFileResponse transferStatusMessage = new UploadFileResponse();

            transferStatusMessage.Status = TransferStatus.Success;
            // var filename = string.Format("{0}_{1}_{2}", requestStream.Current.Username, requestStream.Current.Info.Id , requestStream.Current.Info.Name);
            var    tmpFile    = Path.Combine(Path.GetTempPath(), string.Format("tmp_{0}", Guid.NewGuid().ToString()));
            string targetFile = string.Empty;

            try
            {
                await Task.Run(
                    async() =>
                {
                    CancellationToken cancellationToken = context.CancellationToken;
                    await using (Stream fs = File.OpenWrite(tmpFile))
                    {
                        await foreach (UploadFileRequest uploadFileRequest in
                                       requestStream.ReadAllAsync(cancellationToken).ConfigureAwait(false))
                        {
                            if (string.IsNullOrWhiteSpace(targetFile))
                            {
                                transferStatusMessage.Id = uploadFileRequest.Info.Id;
                                targetFile = string.Format("{0}_{1}_{2}", requestStream.Current.Username, requestStream.Current.Info.Id, requestStream.Current.Info.Name);
                            }
                            fs.Write(uploadFileRequest.ChunkData.ToByteArray());
                        }
                    }
                }).ConfigureAwait(false);
            }
            // Is thrown on cancellation -> ignore
            catch (OperationCanceledException)
            {
                transferStatusMessage.Status = TransferStatus.Cancelled;
            }
            catch (RpcException rpcEx)
            {
                if (rpcEx.StatusCode == StatusCode.Cancelled)
                {
                    transferStatusMessage.Status = TransferStatus.Cancelled;
                }
                else
                {
                    _logger.LogError($"Exception while processing image file '{tmpFile}'. Exception: '{requestStream}'");
                    transferStatusMessage.Status = TransferStatus.Failure;
                }
            }
            // Delete incomplete file
            if (transferStatusMessage.Status != TransferStatus.Success)
            {
                File.Delete(tmpFile);
            }
            else
            {
                File.Move(tmpFile, Path.Combine(_filePath, targetFile));
            }
            return(transferStatusMessage);
        }
    public void UploadFile(string FileName, long Length, System.IO.Stream FileByteStream)
    {
        RemoteFileInfo inValue = new RemoteFileInfo();

        inValue.FileName       = FileName;
        inValue.Length         = Length;
        inValue.FileByteStream = FileByteStream;
        UploadFileResponse retVal = ((IStreamService)(this)).UploadFile(inValue);
    }
Example #13
0
        public virtual void AddAttach(FileInfo fileInfo, String attachType)
        {
            if (_attachFiles.Where(a => a.ATTACH_FILE_TYPE == attachType).Count() > 0)
            {
                throw new RegistrationException(Resources.errorBasePersonal_001);
            }
            if (!fileInfo.Exists)
            {
                throw new RegistrationException(Resources.errorBaseRegistration_003);
            }

            // ------------ Init Data --------------
            String container = String.Format(@"{0}\{1}", TempFileContainer, this.ID);

            String   fileName = String.Format("{0}_{1:00}{2}", this.ID_CARD_NO, Convert.ToInt32(attachType), fileInfo.Extension);
            DateTime curDate  = DateTime.Now;

            AttachFilesIAS.AttachFile attachFile = new AttachFilesIAS.AttachFile()
            {
                ID = IAS.BLL.Helpers.GenerateIdHelper.GetGenAutoId(),
                ATTACH_FILE_TYPE = attachType,
                REGISTRATION_ID  = this.ID,
                CREATED_BY       = this.ID_CARD_NO,
                CREATED_DATE     = curDate,
                UPDATED_BY       = this.ID_CARD_NO,
                UPDATED_DATE     = curDate,
                FILE_STATUS      = AttachFileStatus.Active.Value(),
                ATTACH_FILE_PATH = String.Format(@"{0}\{1}", container, fileName)
            };
            //-----------------------------------------



            // -------------- Upload File To Temp--------------------------------
            using (FileService.FileTransferServiceClient svc = new FileService.FileTransferServiceClient())
            {
                UploadFileResponse response = new UploadFileResponse();


                //response = svc.UploadFile(new UploadFileRequest() {
                //                                TargetContainer = attachFile.ATTACH_CONTAINER,
                //                                TargetFileName = attachFile.ATTACH_FILE_NAME,
                //                                FileStream = fileInfo.Create()
                //                            });
                if (response.Code != "0000")
                {
                    throw new RegistrationException(response.Message);
                }

                attachFile.ATTACH_FILE_PATH = response.TargetFullName;
                _attachFiles.Add(attachFile);
            }
            // ------------------------------------------------------------------
        }
        public static UploadFileResponse Unmarshall(UnmarshallerContext context)
        {
            UploadFileResponse uploadFileResponse = new UploadFileResponse();

            uploadFileResponse.HttpResponse = context.HttpResponse;
            uploadFileResponse.Code         = context.StringValue("UploadFile.Code");
            uploadFileResponse.Data         = context.StringValue("UploadFile.Data");
            uploadFileResponse.Message      = context.StringValue("UploadFile.Message");
            uploadFileResponse.RequestId    = context.StringValue("UploadFile.RequestId");

            return(uploadFileResponse);
        }
Example #15
0
        /// <summary>
        /// 上传文件请求回调
        /// </summary>
        /// <param name="obj"></param>
        private void OnUploadFileResponse(UploadFileResponse msg)
        {
            btnUploadFile.Enabled = true;

            if (msg == null)
            {
                return;
            }

            MessageBoxEx.Show(msg.Result.Code == 1 ? "上传成功" : msg.Result.Msg);
            SendGetFileListCMD();
        }
Example #16
0
        //#region Member Variable

        //private NASDrive nasDrive;
        //string netDrive = ConfigurationManager.AppSettings["DEFAULT_NET_DRIVE"];
        //string userNetDrive = ConfigurationManager.AppSettings["USER_NET_DRIVE"];
        //string passNetDrive = ConfigurationManager.AppSettings["PASS_NET_DRIVE"];

        //#endregion

        //#region Member Method

        //public void Dispose()
        //{
        //    if (nasDrive != null)
        //    {
        //        nasDrive.Dispose();
        //        nasDrive = null;
        //    }
        //}
        //private void ConnectNetDrive()
        //{
        //    this.nasDrive = new NASDrive(netDrive, userNetDrive, passNetDrive);
        //}

        //private void DisConnectNetDrive()
        //{
        //    if (this.nasDrive != null)
        //    {
        //        this.nasDrive.Dispose();
        //    }
        //}

        //private string GetContentType(string fileExtension)
        //{
        //    if (string.IsNullOrEmpty(fileExtension))
        //        return string.Empty;

        //    string contentType = string.Empty;
        //    switch (fileExtension)
        //    {
        //        case ".htm":
        //        case ".html":
        //            contentType = "text/HTML";
        //            break;

        //        case ".txt":
        //            contentType = "text/plain";
        //            break;

        //        case ".doc":
        //        case ".rtf":
        //        case ".docx":
        //            contentType = "Application/msword";
        //            break;

        //        case ".xls":
        //        case ".xlsx":
        //            contentType = "Application/x-msexcel";
        //            break;

        //        case ".jpg":
        //        case ".jpeg":
        //            contentType = "image/jpeg";
        //            break;

        //        case ".gif":
        //            contentType = "image/GIF";
        //            break;

        //        case ".pdf":
        //            contentType = "application/pdf";
        //            break;
        //    }

        //    return contentType;
        //}

        //#endregion


        /// <summary>
        /// Upload File
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public UploadFileResponse UploadFile(UploadFileRequest request)
        {
            UploadFileResponse response = new UploadFileResponse();

            try
            {
                response = FileManagerService.RemoteFileCommand(request).Action();
            }
            catch (Exception e)
            {
                response.Message = e.Message;
            }

            return(response);
        }
Example #17
0
        /// <summary>
        /// Publishes a SNS message, when a user uploads a file.
        /// </summary>
        /// <param name="uploadFileResponse"></param>
        private static async Task <PublishResponse> PublishMessageToAws(UploadFileResponse uploadFileResponse)
        {
            var accessKeyId = AppSettings["IAMUser.AccessKeyId"];
            var secretKey   = AppSettings["IAMUser.SecretKey"];
            var sns         = AWSClientFactory.CreateAmazonSimpleNotificationServiceClient(accessKeyId, secretKey,
                                                                                           RegionEndpoint.EUWest1);
            var topicArn   = AppSettings["SNS.Topic.ARN"];
            var snsPayload = new SnsPayload
            {
                Email       = "*****@*****.**", // Normally here we should pass user email.
                DocumentId  = uploadFileResponse.Id,
                DocumentUrl = uploadFileResponse.Url
            };
            var awsRequest = new PublishRequest(topicArn, JsonConvert.SerializeObject(snsPayload));

            return(await sns.PublishAsync(awsRequest));
        }
Example #18
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        public ResultObject <UploadFileResponse> Uploadfile(IFormFile formFile)
        {
            if (formFile == null || formFile.Length == 0)
            {
                return(new ResultObject <UploadFileResponse>("文件不能为空"));
            }
            if (formFile.Length > _appSettings.Upload.LimitSize)
            {
                return(new ResultObject <UploadFileResponse>("文件超过了最大限制"));
            }
            var ext = Path.GetExtension(formFile.FileName).ToLower();

            if (!_appSettings.Upload.AllowExts.Contains(ext))
            {
                return(new ResultObject <UploadFileResponse>("文件类型不允许"));
            }
            //上传逻辑
            var now      = DateTime.Now;
            var yy       = now.ToString("yyyy");
            var mm       = now.ToString("MM");
            var dd       = now.ToString("dd");
            var fileName = Guid.NewGuid().ToString("n") + ext;

            var folder = Path.Combine(_appSettings.Upload.UploadPath, yy, mm, dd);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            var filePath = Path.Combine(folder, fileName);

            using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                formFile.CopyTo(fileStream);
                fileStream.Flush(true);
            }

            var fileUrl  = $"{_appSettings.RootUrl}{_appSettings.Upload.RequestPath}/{yy}/{mm}/{dd}/{fileName}";
            var response = new UploadFileResponse {
                Url = fileUrl
            };

            return(new ResultObject <UploadFileResponse>(response));
        }
Example #19
0
        public UploadFileResponse Action()
        {
            UploadFileResponse response = new UploadFileResponse();

            try
            {
                using (FileStream outfile = new FileStream(Path.Combine(DefaultNetDrive, _targetPath), FileMode.Create))
                {
                    const int bufferSize = 1165536; // 64K
                    // 65536
                    Byte[] buffer = new Byte[bufferSize];

                    int bytesRead = _streamAttech.Read(buffer, 0, bufferSize);

                    if (bytesRead > 2147483647)
                    {
                        response.Code    = "0002";
                        response.Message = Resources.errorUploadFile_001;
                        return(response);
                    }
                    while (bytesRead > 0)
                    {
                        outfile.Write(buffer, 0, bytesRead);
                        bytesRead = _streamAttech.Read(buffer, 0, bufferSize);
                    }

                    response.Code           = "0000";
                    response.Message        = Resources.infoAmendFile_Success; // "Success Save at " + serverFileName;
                    response.TargetFullName = _targetPath;
                }
            }
            catch (Exception ex)
            {
                response.Code    = "0001";
                response.Message = ex.Message;
                throw new ApplicationException(ex.Message);
            }
            finally {
                DisConnectNetDrive();
            }


            return(response);
        }
Example #20
0
        public IActionResult upload(string token)
        {
            var user = tokenSerivce.GetUserByToken(token);

            if (user == null)
            {
                Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                return(Content("401"));
            }

            string             msg  = null;
            var                data = UploadImagesOrAttach(user.UserId, out msg);
            UploadFileResponse uploadFileResponse = new UploadFileResponse()
            {
                data = data
            };

            return(Json(uploadFileResponse, MyJsonConvert.GetSimpleOptions()));
        }
Example #21
0
        public async Task <UploadFileResponse> Post([FromForm] IFormFile file)
        {
            var response = new UploadFileResponse();

            if (file == null || file.Length == 0)
            {
                response.Message   = string.Concat("File not selected!");
                response.isSuccess = false;

                return(response);
            }



            var extension = file.FileName.Split('.');
            var fileName  = Helper.Helper.GetHashString(string.Concat(file.FileName + DateTime.UtcNow));

            var path = Path.Combine(
                Directory.GetCurrentDirectory(),
                string.Concat(fileName, ".", extension[extension.Length - 1]));

            response.FileName = string.Concat(fileName, ".", extension[extension.Length - 1]);

            try
            {
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                response.Message   = string.Concat("File successfully uploaded.");
                response.isSuccess = true;
            }
            catch (Exception ex)
            {
                response.Message   = ex.ToString();
                response.isSuccess = false;
            }


            return(response);
        }
Example #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="actionId"></param>
        /// <param name="fileNameWithExtension"></param>
        /// <param name="uploadFileResponse"></param>
        /// <param name="parentFolderId">May be <see langword="null"/> or empty, in which case the document will be stored at the root of the matter.</param>
        public ActionDocument(int actionId, string fileNameWithExtension, UploadFileResponse uploadFileResponse, string parentFolderId)
        {
            if (string.IsNullOrEmpty(fileNameWithExtension))
            {
                throw new ArgumentException(Helper.NullOrEmptyParameterString, nameof(fileNameWithExtension));
            }
            if (uploadFileResponse is null)
            {
                throw new ArgumentNullException(nameof(uploadFileResponse));
            }

            Id    = actionId;
            Name  = fileNameWithExtension;
            File  = $"{uploadFileResponse.File.Id};{fileNameWithExtension}";
            Links = new Link()
            {
                Action = actionId.ToString(CultureInfo.InvariantCulture),
                Folder = parentFolderId
            };
        }
Example #23
0
            public async Task <ActionstepDocument> Handle(ActionstepSavePDFCommand message, CancellationToken token)
            {
                if (message is null)
                {
                    throw new ArgumentNullException(nameof(message));
                }

                ValidationResult result = _validator.Validate(message);

                if (!result.IsValid)
                {
                    throw new ValidationException("Invalid input.", result.Errors);
                }

                TokenSetQuery tokenSetQuery = new TokenSetQuery(message.AuthenticatedUser?.Id, message.OrgKey);

                var actionResponse = await _actionstepService.Handle <GetActionResponse>(new GetActionRequest(tokenSetQuery, message.MatterId));

                string fileName = $"{message.MatterId}_Settlement Statement_{DateTime.UtcNow.ToString("_yyyy-MM-dd hh-mm", CultureInfo.InvariantCulture)}.pdf";

                UploadFileResponse file = await _actionstepService.UploadFile(tokenSetQuery, fileName, message.FilePath);

                #region Check Documents Folder
                ActionFolder             actionFolder   = new ActionFolder(actionResponse.Action.Id);
                GetActionFolderRequest   folderRequest  = new GetActionFolderRequest(tokenSetQuery, actionFolder);
                ListActionFolderResponse folderResponse = await _actionstepService.Handle <ListActionFolderResponse>(folderRequest);

                var parentFolderId = folderResponse.ActionFolders.Where(af => af.Name == "Documents").Select(af => af.Id).FirstOrDefault();
                #endregion

                ActionDocument            document    = new ActionDocument(actionResponse.Action.Id, fileName, file, parentFolderId);
                SaveActionDocumentRequest saveRequest = new SaveActionDocumentRequest(tokenSetQuery, document);

                var saveResponse = await _actionstepService.Handle <SaveActionDocumentResponse>(saveRequest);

                var fileUrl = new Uri(saveResponse.ActionDocument.SharepointUrl);

                string documentUrl = $"https://{fileUrl.Host}/mym/asfw/workflow/documents/views/action_id/{actionResponse.Action.Id}#mode=browse&view=list&folder={parentFolderId}&drive=DL";

                return(new ActionstepDocument(fileUrl, fileName, new Uri(documentUrl)));
            }
Example #24
0
 /// <summary>
 /// Upload a file to RootFolder/Mainfolder+subfolder on Filesanywhere account
 /// </summary>
 /// <param name="MainForlder"></param>
 /// <param name="Subfolder"></param>
 /// <param name="Filepath"></param>
 /// <returns></returns>
 private static bool Upload_File(string MainForlder, string Subfolder, string Filepath)
 {
     try
     {
         // Creating object for uploadFileRequest for uploading a requested file
         UploadFileRequest req = new UploadFileRequest()
         {
             FileData = File.ReadAllBytes(Filepath),
             Path     = objAccount.GetRootFolder() + "/" + MainForlder + "/" + Subfolder + "/" + Path.GetFileName(Filepath),
             Token    = objAccount.GetLogintoken()
         };
         FAWAPI.FAWAPIv2Soap obj       = new FAWAPIv2SoapClient();
         UploadFileResponse  _response = obj.UploadFile(req);
         return(_response.UploadFileResult.Uploaded);
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error occured in uploading file " + Path.GetFileName(Filepath) + " :- " + ex.Message);
         throw ex;
     }
 }
Example #25
0
        public async Task <FTAttachment> Handle(SavePolicyPDFToActionstepCommand request, CancellationToken cancellationToken)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            // Get Actionstep matter info
            var tokenSetQuery = new TokenSetQuery(request.AuthenticatedUser?.Id, request.ActionstepOrg);

            var actionResponse = await _actionstepService.Handle <GetActionResponse>(new GetActionRequest(tokenSetQuery, request.MatterId));

            UploadFileResponse file = await _actionstepService.UploadFile(tokenSetQuery, request.FileName, request.FilePath);

            #region Check Documents Folder
            ActionFolder             actionFolder   = new ActionFolder(actionResponse.Action.Id);
            GetActionFolderRequest   folderRequest  = new GetActionFolderRequest(tokenSetQuery, actionFolder);
            ListActionFolderResponse folderResponse = await _actionstepService.Handle <ListActionFolderResponse>(folderRequest);

            var parentFolderId = folderResponse.ActionFolders.Where(af => af.Name == "Documents").Select(af => af.Id).FirstOrDefault();
            #endregion

            ActionDocument            document    = new ActionDocument(actionResponse.Action.Id, request.FileName, file, parentFolderId);
            SaveActionDocumentRequest saveRequest = new SaveActionDocumentRequest(tokenSetQuery, document);

            var saveResponse = await _actionstepService.Handle <SaveActionDocumentResponse>(saveRequest);

            var fileUrl = new Uri(saveResponse.ActionDocument.SharepointUrl);

            string documentUrl = $"https://{fileUrl.Host}/mym/asfw/workflow/documents/views/action_id/{actionResponse.Action.Id}#mode=browse&view=list&folder={parentFolderId}&drive=DL";

            return(new FTAttachment()
            {
                FileName = request.FileName,
                FileUrl = documentUrl
            });
        }
Example #26
0
        public async Task <Item> AddItemAsync(Item item)
        {
            var client = getClient();

            UploadFileResponse uploadResponse = null;

            if (!string.IsNullOrWhiteSpace(item.File))
            {
                using (var stream = File.OpenRead(item.File))
                {
                    uploadResponse = client.PostFile <UploadFileResponse>("UploadFile", stream, Path.GetFileName(item.File), "image/jpg");
                }
            }

            Record record = new Record();

            record.RecordType = new RecordTypeRef()
            {
                Uri = 2
            };
            record.Title      = item.Description;
            record.Properties = recordProperties;

            record.FilePath = uploadResponse?.FilePath;

            var response = await client.PostAsync <RecordsResponse>(record);

            var newRecord = response.Results[0];

            items.Insert(0, new Item()
            {
                Id = newRecord.Uri.ToString(), Text = newRecord.Number, Description = newRecord.Title
            });

            return(await Task.FromResult(new Item(newRecord)));
        }
Example #27
0
        public DTO.RegistrationAttatchFile SaveAttachToTemp(DTO.RegistrationAttatchFile attachFile, Stream fileSteam)
        {
            using (FileService.FileTransferServiceClient svc = new FileService.FileTransferServiceClient())
            {
                UploadFileResponse response     = new UploadFileResponse();
                String             fs_container = String.Format(@"{0}\{1}", TempFileContainer, attachFile.TempFilePath);


                response = svc.UploadFile(new UploadFileRequest()
                {
                    TargetContainer = fs_container,
                    TargetFileName  = attachFile.FileName,
                    FileStream      = fileSteam
                });
                if (response.Code != "0000")
                {
                    throw new IOException(response.Message);
                }

                attachFile.ATTACH_FILE_PATH = response.TargetFullName;
            }

            return(attachFile);
        }
        public async Task <IActionResult> UploadFileToKnownLocation(
            [FromForm] UploadFileRequest fileData,
            [FromRoute] string directoryId,
            [FromQuery(Name = "revisionNr")] uint?revisionNumber)
        {
            try
            {
                var uploadMetadata = await writeApi.ObjectApi.UploadFile(
                    directoryId,
                    fileData.File.OpenReadStream(),
                    fileData.PlaintextKey,
                    fileData.EncryptedKey,
                    fileData.DocumentLanguage,
                    fileData.FileExtension);

                var responseObject = new UploadFileResponse(uploadMetadata);
                return(Ok(responseObject));
            }
            catch (Exception e)
            {
                Console.Write(e);
                return(BadRequest());
            }
        }
Example #29
0
        UploadData(string pathFileName, DTO.UserProfile userProfile, string petitionTypeCode, string licenseTypeCode, Stream fileSteam, string replaceType, string approveCom)
        {
            var res = new DTO.ResponseService <DTO.SummaryReceiveLicense>();

            res.DataResponse = new DTO.SummaryReceiveLicense();
            UploadFileResponse response = new UploadFileResponse();

            try
            {
                //String attachFilePath = "";
                using (FileService.FileTransferServiceClient svcFile = new FileService.FileTransferServiceClient())
                {
                    String fileName  = String.Format(@"{0}.{1}", IAS.BLL.Helpers.GenerateIdHelper.GetGenAutoId(), pathFileName.Split('.')[pathFileName.Split('.').Length - 1]);;
                    String container = String.Format(@"{0}\{1}", TempFileContainer, IAS.BLL.Helpers.GenerateIdHelper.GetGenAutoId());

                    response = svcFile.UploadFile(new UploadFileRequest()
                    {
                        TargetContainer = container,
                        TargetFileName  = fileName,
                        FileStream      = fileSteam
                    });


                    if (response.Code != "0000")
                    {
                        res.ErrorMsg = response.Message;
                        return(res);
                    }
                    //FileService.UploadFileResponse resUpload = svcFile.UploadFile(new UploadFileRequest()
                    //{
                    //    TargetContainer = container,
                    //    TargetFileName = fileName,
                    //    FileStream = fileSteam
                    //});

                    //if (resUpload.Code != "0000")
                    //{
                    //    res.ErrorMsg = resUpload.Message;
                    //    return res;
                    //}
                    //pathFileName = resUpload.TargetFullName;
                    pathFileName = response.TargetFullName;
                }

                DTO.DataLicenseRequest request = new DTO.DataLicenseRequest()
                {
                    FileName          = pathFileName,
                    LicenseTypeCode   = licenseTypeCode,
                    PettitionTypeCode = petitionTypeCode,
                    UserProfile       = userProfile,
                    ReplaceType       = replaceType,
                    ApproveCom        = approveCom
                };


                res = svc.UploadDataLicense(request);
            }
            catch (IOException ioEx)
            {
                res.ErrorMsg = Resources.errorLicenseBiz_001;
            }
            catch (Exception ex)
            {
                res.ErrorMsg = Resources.errorLicenseBiz_001;
            }
            return(res);
        }
Example #30
0
        protected override async Task <SendResult> Send(IWin32Window Owner, Output Output, ImageData ImageData)
        {
            try
            {
                HttpBindingBase binding;
                if (Output.Url.StartsWith("https", StringComparison.InvariantCultureIgnoreCase))
                {
                    binding = new BasicHttpsBinding();
                }
                else
                {
                    binding = new BasicHttpBinding();
                }
                binding.MaxBufferSize          = int.MaxValue;
                binding.MaxReceivedMessageSize = int.MaxValue;

                WorkItemSoapClient informUp = new WorkItemSoapClient(binding, new EndpointAddress(Output.Url + "/Services/WorkItem.asmx"));


                string fileName = AttributeHelper.ReplaceAttributes(Output.FileName, ImageData);


                // Show send window
                Send send = new Send(Output.Url, Output.LastItemType, Output.LastItemID, fileName);

                var sendOwnerHelper = new System.Windows.Interop.WindowInteropHelper(send);
                sendOwnerHelper.Owner = Owner.Handle;

                if (!send.ShowDialog() == true)
                {
                    return(new SendResult(Result.Canceled));
                }


                string userName            = Output.UserName;
                string password            = Output.Password;
                bool   showLogin           = string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password);
                bool   rememberCredentials = false;

                while (true)
                {
                    if (showLogin)
                    {
                        // Show credentials window
                        Credentials credentials = new Credentials(Output.Url, userName, password, rememberCredentials);

                        var credentialsOwnerHelper = new System.Windows.Interop.WindowInteropHelper(credentials);
                        credentialsOwnerHelper.Owner = Owner.Handle;

                        if (credentials.ShowDialog() != true)
                        {
                            return(new SendResult(Result.Canceled));
                        }

                        userName            = credentials.UserName;
                        password            = credentials.Password;
                        rememberCredentials = credentials.Remember;
                    }

                    string itemType = null;
                    int    itemID;

                    if (send.CreateNewItem)
                    {
                        itemType = send.ItemType;

                        AddWorkItemResponse addWorkItemResult = await informUp.AddWorkItemAsync(userName, password, send.ItemType, send.ItemTitle, send.Description);

                        if (!int.TryParse(addWorkItemResult.Body.AddWorkItemResult, out itemID))
                        {
                            if (addWorkItemResult.Body.AddWorkItemResult.Equals("Login or Password is incorrect", StringComparison.InvariantCultureIgnoreCase))
                            {
                                showLogin = true;
                                continue;
                            }
                            else
                            {
                                return(new SendResult(Result.Failed, addWorkItemResult.Body.AddWorkItemResult));
                            }
                        }
                    }
                    else
                    {
                        itemType = Output.LastItemType;
                        itemID   = send.ItemID;
                    }

                    IFileFormat fileFormat = FileHelper.GetFileFormat(Output.FileFormatID);

                    string fullFileName = String.Format("{0}.{1}", send.FileName, fileFormat.FileExtension);
                    byte[] fileBytes    = FileHelper.GetFileBytes(Output.FileFormatID, ImageData);

                    UploadFileResponse uploadFileResult = await informUp.UploadFileAsync(userName, password, fileBytes, fullFileName, itemID);

                    if (!uploadFileResult.Body.UploadFileResult.Equals("OK", StringComparison.InvariantCultureIgnoreCase))
                    {
                        return(new SendResult(Result.Failed, uploadFileResult.ToString()));
                    }


                    // Open item in browser
                    if (Output.OpenItemInBrowser)
                    {
                        WebHelper.OpenUrl(String.Format("{0}/Main.aspx?ID={1}&Window=PopupItem", Output.Url, itemID));
                    }

                    return(new SendResult(Result.Success,
                                          new Output(Output.Name,
                                                     Output.Url,
                                                     (rememberCredentials) ? userName : Output.UserName,
                                                     (rememberCredentials) ? password : Output.Password,
                                                     Output.FileName,
                                                     Output.FileFormatID,
                                                     Output.OpenItemInBrowser,
                                                     itemType,
                                                     itemID)));
                }
            }
            catch (Exception ex)
            {
                return(new SendResult(Result.Failed, ex.Message));
            }
        }
Example #31
0
        /// <summary>
        /// Adds files to the specified folder
        /// </summary>
        /// <param name="files">Paths to files to upload</param>
        /// <param name="destinationFolderID">ID of the destination folder</param>
        /// <param name="isFilesShared">Indicates if uploaded files should be marked as shared</param>
        /// <param name="message">Text of the message to send in a notification email to all addresses in the <paramref name="emailsToNotify"/> list</param>
        /// <param name="emailsToNotify">List of email addresses to notify about newly uploaded files</param>
        /// <returns>Operation status</returns>
        public UploadFileResponse AddFiles(
            string[] files,
            long destinationFolderID,
            bool isFilesShared,
            string message,
            string[] emailsToNotify)
        {
            MultipartWebRequest request = new MultipartWebRequest(string.Format(UPLOAD_FILE_URI_TEMPLATE, _token, destinationFolderID), Proxy);
            UploadFileResponse response;

            try
            {
                string serverResponse = request.SubmitFiles(files, isFilesShared, message, emailsToNotify);
                response = MessageParser.Instance.ParseUploadResponseMessage(serverResponse);
            }
            catch (Exception ex)
            {
                response = new UploadFileResponse
                           	{
                           		Error = ex,
                           		Status = UploadFileStatus.Failed,
                           		UploadedFileStatus = new Dictionary<File, UploadFileError>()
                           	};
            }

            response.FolderID = destinationFolderID;

            return response;
        }
        internal UploadFileResponse ParseUploadResponseMessage(string message)
        {
            UploadFileResponse response = new UploadFileResponse();
            XDocument doc = XDocument.Parse(message);

            XElement filesElement = GetFilesElement(doc.Root);
            XElement statusElement = GetStatusElement(doc.Root);

            IEnumerable<XElement> fileElements = GetFileElements(filesElement);

            File file;
            UploadFileError error;
            foreach (XElement fileElement in fileElements)
            {
                ParseFileElement(fileElement, out file, out error);

                response.UploadedFileStatus.Add(file, error);
            }

            response.Status = ParseUploadStatus(statusElement.Value);

            return response;
        }
Example #33
0
        private void EscribeServidor2(StringBuilder registros)
        {
            
            string strFileName = "ListaNegra.txt";
            string _tipoArchivoDir = "";
            _tipoArchivoDir = "PLD";
            string strType = "txt";
            string directorio = Repositorio + _tipoArchivoDir + @"\";

            System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
            

            byte[] hfc =(byte[]) encoding.GetBytes(registros.ToString());
            IwsDocumentHandlingClient proxy = new IwsDocumentHandlingClient();
            RemoteFileInfoRequest request = new RemoteFileInfoRequest();
            UploadFileResponse response = new UploadFileResponse();

            long length = (long)hfc.Length;
            byte[] buffer2 = hfc;
            request.data = buffer2;
            request.FileName = strFileName;
            request.Length = length;
            request.strServerPath = directorio;
            response = proxy.UploadFile(request);
        }
Example #34
0
        public object Any(UploadFile request)
        {
            var response = new UploadFileResponse
            {
                Name = request.Name,
            };

            if (base.Request.Files.Length > 0)
            {
                var file = base.Request.Files[0];
                response.FileSize = file.ContentLength;
            }

            return response;
        }