public async Task<Stream> HandleFileRequest(FileRequest request)
        {
            Console.WriteLine("Call to HandleRequest");
            var requestType = request.GetType();

            var isValidRequest = requestType.GetInterfaces().Any(x =>
                x.IsGenericType &&
                (typeof(IAsyncRequest<>).IsAssignableFrom(x.GetGenericTypeDefinition())
                || typeof(IRequest<>).IsAssignableFrom(x.GetGenericTypeDefinition()))
                );

            if (!isValidRequest)
            {
                throw new ArgumentException("Unprocessable request");
            }

            //var isAsyncRequest = requestType.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IAsyncRequest<>));

            var responseStream = new MemoryStream();
            request.SetStream(responseStream);

            //if (isAsyncRequest)
            //{
            //    await _mediator.SendAsync(request);
            //}

            _mediator.Send(request);
            responseStream.Position = 0;
            return responseStream;
        }
Exemplo n.º 2
0
        /// <summary>
        /// Metodo per l'aggiunta degli allegati ad un documento
        /// </summary>
        /// <param name="docNumber">Numero del documento cui aggiungere gli allegati</param>
        /// <param name="attachments">Informazioni sugli allegati da creare</param>
        /// <param name="userInfo">Informazioni sull'utente utilizzato per la creazione del predisposto in ingresso</param>
        /// <param name="senderAdministrationId">Id dell'amministrazione mittente della richiesta di interoperabilità</param>
        /// <param name="senderFileManagerUrl">Url del file manager per il download dell'eventuale file associato ad un allegato</param>
        private static void AddAttachments(String docNumber, List <DocumentInfo> attachments, InfoUtente userInfo, String senderAdministrationId, String senderFileManagerUrl)
        {
            int i = 0;

            foreach (DocumentInfo attachment in attachments)
            {
                // Creazione dell'oggetto allegato
                Allegato a = new Allegato();

                // Impostazione delle proprietà dell'allegato
                if (String.IsNullOrEmpty(attachment.Name))
                {
                    a.descrizione = String.Format("Allegato {0}", i);
                }
                else
                {
                    a.descrizione = attachment.Name;
                }

                a.docNumber    = docNumber;
                a.fileName     = InteroperabilitaSegnatura.getFileName(attachment.FileName);
                a.version      = "0";
                a.numeroPagine = attachment.NumberOfPages;

                // Aggiunta dell'allegato al documento principale
                try
                {
                    a = AllegatiManager.aggiungiAllegato(userInfo, a);
                }
                catch (Exception ex)
                {
                    SimplifiedInteroperabilityLogAndRegistryManager.InsertItemInLog(
                        docNumber,
                        true,
                        String.Format("Errore durante l'aggiunta dell'allegato '{0}'. Messaggio eccezione: {1}",
                                      a.descrizione,
                                      ex.Message));

                    throw new CreatingDocumentException(
                              String.Format("Errore durante l'aggiunta dell'allegato '{0}'", attachment.Name));
                }
                string errPutFile = "";
                try
                {
                    // Associazione dell'immagine all'allegato
                    FileRequest request = a as FileRequest;
                    if (!String.IsNullOrEmpty(attachment.FileName))
                    {
                        SimplifiedInteroperabilityFileManager.DownloadFile(
                            attachment,
                            senderAdministrationId,
                            request,
                            userInfo,
                            senderFileManagerUrl,
                            out errPutFile);
                    }

                    if (!string.IsNullOrEmpty(errPutFile))
                    {
                        throw new Exception("Errore durante l'associazione dell'immagine al documento principale");
                    }
                }
                catch (Exception e)
                {
                    SimplifiedInteroperabilityLogAndRegistryManager.InsertItemInLog(
                        a.docNumber,
                        true,
                        String.Format("Errore durante l'associazione dell'immagine per l'allegato '{0}'. Messaggio eccezione: {1}",
                                      a.descrizione,
                                      e.Message));
                    if (!string.IsNullOrEmpty(errPutFile) && errPutFile.Contains("formato file"))
                    {
                        throw new DownloadDocumentException(
                                  String.Format("Errore durante l'associazione dell'immagine all'allegato '{0}'. {1} destinataria.", attachment.Name, errPutFile));
                    }
                    else
                    {
                        throw new DownloadDocumentException(
                                  String.Format("Errore durante l'associazione dell'immagine all'allegato '{0}'", attachment.Name));
                    }
                }
                i++;
            }
        }
Exemplo n.º 3
0
        public async Task <DataRespond> insertFileAsync([FromForm] FileRequest filerq)
        {
            DataRespond data = new DataRespond();

            try
            {
                Files   file  = new Files();
                Boolean boole = true;
                if (filerq.fileid != -1)
                {
                    boole = true;
                    file  = m_fileResponsitory.findFileById(filerq.fileid);
                }
                else
                {
                    boole          = false;
                    file.createday = DateTime.Now;
                }
                if (filerq.avatar != null)
                {
                    var x = deleteFileImg(file.avatar);
                    file.avatar = await uploadFileImg(filerq.avatar);
                }
                // file.fileid = filerq.fileid;
                file.usid  = filerq.usid;
                file.donvi = filerq.donvi;
                DateTime bd = DateTime.ParseExact(filerq.ngaythangnamsinh, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                file.ngaythangnamsinh = bd;
                file.hotendangdung    = filerq.hotendangdung;
                file.hotenkhaisinh    = filerq.hotenkhaisinh;
                file.gioitinh         = filerq.gioitinh == 0 ? true : false;
                file.dantoc           = filerq.dantoc;
                file.tongiao          = filerq.tongiao;
                file.nghenghiep       = filerq.nghenghiep;
                DateTime ngayvaodangct = DateTime.ParseExact(filerq.ngayvaodangct, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                file.ngayvaodangct = ngayvaodangct;
                DateTime ngayvaodangdb = DateTime.ParseExact(filerq.ngayvaodangdb, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                file.ngayvaodangdb = ngayvaodangdb;
                DateTime ngayvaodangdoan = DateTime.ParseExact(filerq.ngayvaodoan, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                file.ngayvaodoan   = ngayvaodangdoan;
                file.trinhdovanhoa = filerq.trinhdovanhoa;
                file.chuyenmon     = filerq.chuyenmon;
                file.quequan       = filerq.quequan;
                file.noicutru      = filerq.noicutru;
                file.matp          = filerq.matp;
                file.maqh          = filerq.maqh;
                file.xaid          = filerq.xaid;
                file.solylich      = filerq.solylich;
                file.updateday     = DateTime.Now;
                file.sdt           = filerq.sdt;
                file.email         = filerq.email;
                file.cmnd          = filerq.cmnd;
                file.noicapcmnd    = filerq.noicapcmnd;
                DateTime ngaycmnd = DateTime.ParseExact(filerq.daycmnd, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                file.daycmnd         = ngaycmnd;
                file.hokhauthuongtru = filerq.hokhauthuongtru;
                file.honnhan         = filerq.honnhan == 0 ? true : false;
                file.suckhoe         = filerq.suckhoe;

                m_fileResponsitory.updateFile(file, boole);
                data.success = true;
                data.message = "Update success!";
            }
            catch (Exception e)
            {
                data.error   = e;
                data.message = e.Message;
                data.success = false;
            }

            return(data);
        }
Exemplo n.º 4
0
 public static IEnumerator Load(string filename, UnityAction <List <MobilityMode> > callback, UnityAction errCallback)
 {
     yield return(FileRequest.GetText(filename, (sr) => callback(Parse(sr)), errCallback));
 }
Exemplo n.º 5
0
        /// <summary>
        /// Metodo per il download di un file
        /// </summary>
        /// <param name="request">Informazioni sul file da scricare</param>
        /// <returns>Informazioni sul file scaricato e riferimento all'oggetto responsabile della gestione dello streaming dati</returns>
        RemoteFileInfo IFileManager.DownloadFile(SendFileRequest request)
        {
            logger.Debug("BEGIN");
            DocsPaVO.utente.InfoUtente infoUtente = new DocsPaVO.utente.InfoUtente()
            {
                idAmministrazione = request.AdministrationId
            };
            FileRequest fr = new FileRequest()
            {
                docServerLoc = request.DocumentServerLocation,
                path         = request.FilePath,
                fileName     = request.FileName,
                docNumber    = request.DocumentNumber,
                versionId    = request.VersionId,
                versionLabel = request.VersionLabel,
                version      = request.Version
            };

            byte[] lastTSR = null;
            try
            {
                lastTSR = BusinessLogic.Interoperabilità.InteroperabilitaUtils.GetTSRForDocument(infoUtente, fr);
            }
            catch
            { }

            FileDocumento docFile = BusinessLogic.Documenti.FileManager.getFileFirmato(
                fr,
                infoUtente,
                false);

            if (lastTSR != null)
            {
                logger.Debug("TSR presente, incapsulo in TSDiS");
                //controllo il match
                if (!BusinessLogic.Interoperabilità.InteroperabilitaUtils.MatchTSR(lastTSR, docFile.content))
                {
                    lastTSR = null;
                }

                //Gestione TSDis (DOC+TSR)
                //Siccome non si possono mandare piu file allo stesso tempo, ne è possibile alterare la struttura
                //si è pensato:

                //In fase di invio, in caso di documenti con TSR associato, l'invio dello stesso un formato
                //TSD, come marca verrà presa l'ultima disponibile, e unita al documento, creadno un file con estensione TSDis

                //In fase di ricezione il TsdIs, sarà poi spacchettato, il TSR messo in DPA_TIMESTAMP dopo verifica hash e
                //infine il payload messo in documentale con la putfile.



                //tsr presente, combino il tutto per creare un TSDis
                if (lastTSR != null)
                {
                    try
                    {
                        BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.tsd        tsdMgr = new BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.tsd();
                        BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.CryptoFile file   = new BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.CryptoFile {
                            Content = docFile.content, Name = docFile.name, MessageFileType = BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.fileType.Binary
                        };
                        List <BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.CryptoFile> tsrLst  = new List <BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.CryptoFile>();
                        BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.CryptoFile        tsrfile = new BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.CryptoFile {
                            Content = lastTSR, MessageFileType = BusinessLogic.Documenti.DigitalSignature.PKCS_Utils.fileType.Binary
                        };
                        tsrLst.Add(tsrfile);
                        docFile.content  = tsdMgr.create(file, tsrLst.ToArray()).Content;
                        request.FileName = request.FileName + ".TSDis";
                    }
                    catch (Exception e)
                    {
                        logger.ErrorFormat("Error creating TSDID {0} {1}", e.Message, e.StackTrace);
                        //Manca il logger pdpdpdpdp
                    }
                }
            }
            //FileDocumento docFile = BusinessLogic.Documenti.FileManager.getFileFirmato(
            //    new FileRequest()
            //    {
            //        docServerLoc = request.DocumentServerLocation,
            //        path = request.FilePath,
            //        fileName = request.FileName,
            //        docNumber = request.DocumentNumber,
            //        versionId = request.VersionId,
            //        versionLabel = request.VersionLabel
            //    },
            //    new DocsPaVO.utente.InfoUtente()
            //    {
            //        idAmministrazione = request.AdministrationId
            //    },
            //    false);
            logger.Debug("END");
            return(new RemoteFileInfo
            {
                FileData = new MemoryStream(docFile.content, false),
                FileTransferInfo = new FileTransferInfo()
                {
                    FileName = request.FileName,
                    FileLength = docFile.content.Length
                }
            });
        }
Exemplo n.º 6
0
        public ActionResult Handle([FromBody] FileRequest req)
        {
            List <object> list   = new List <object>();
            var           prefix = CommonHelper.SystemSettings["PathRoot"].Trim('\\', '/');

            switch (req.Action)
            {
            case "list":
                string   path  = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + req.Path : prefix + req.Path;  //_hostingEnvironment.WebRootPath + (req.Path);
                string[] dirs  = Directory.GetDirectories(path);
                string[] files = Directory.GetFiles(path);
                dirs.ForEach(s =>
                {
                    DirectoryInfo dirinfo = new DirectoryInfo(s);
                    list.Add(new FileList()
                    {
                        date   = dirinfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        name   = dirinfo.Name,
                        rights = "drwxrwxrwx",
                        size   = 0,
                        type   = "dir"
                    });
                });
                files.ForEach(s =>
                {
                    FileInfo info = new FileInfo(s);
                    list.Add(new FileList()
                    {
                        name   = info.Name,
                        rights = "-rw-rw-rw-",
                        size   = info.Length,
                        date   = info.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        type   = "file"
                    });
                });
                break;

            case "remove":
                req.Items.ForEach(s =>
                {
                    s = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + s : prefix + s;
                    try
                    {
                        System.IO.File.Delete(s);
                    }
                    catch
                    {
                        Directory.Delete(s, true);
                    }
                });
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "rename":
            case "move":
                path = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + req.Item : prefix + req.Item;
                var newpath = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + req.NewItemPath : prefix + req.NewItemPath;
                if (!string.IsNullOrEmpty(req.Item))
                {
                    try
                    {
                        System.IO.File.Move(path, newpath);
                    }
                    catch
                    {
                        Directory.Move(path, newpath);
                    }
                }
                else
                {
                    newpath = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + req.NewPath : prefix + req.NewPath;
                    req.Items.ForEach(s =>
                    {
                        try
                        {
                            System.IO.File.Move(string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (s) : prefix + s, Path.Combine(newpath, Path.GetFileName(s)));
                        }
                        catch
                        {
                            Directory.Move(string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (s) : prefix + s, Path.Combine(newpath, Path.GetFileName(s)));
                        }
                    });
                }
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "copy":
                path    = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (req.Item) : prefix + req.Item;
                newpath = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (req.NewItemPath) : prefix + req.NewItemPath;
                //newpath = _hostingEnvironment.WebRootPath + (req.NewItemPath);
                if (!string.IsNullOrEmpty(req.Item))
                {
                    System.IO.File.Copy(path, newpath);
                }
                else
                {
                    newpath = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (req.NewPath) : prefix + req.NewPath;
                    //_hostingEnvironment.WebRootPath + (req.NewPath);
                    req.Items.ForEach(s => System.IO.File.Copy(string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (s) : prefix + s, !string.IsNullOrEmpty(req.SingleFilename) ? Path.Combine(newpath, req.SingleFilename) : Path.Combine(newpath, Path.GetFileName(s))));
                }
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "edit":
                path = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (req.Item) : prefix + req.Item;
                //path = _hostingEnvironment.WebRootPath + (req.Item);
                string content = req.Content;
                System.IO.File.WriteAllText(path, content, Encoding.UTF8);
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "getContent":
                path = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (req.Item) : prefix + req.Item;
                //path = _hostingEnvironment.WebRootPath + (req.Item);
                content = System.IO.File.ReadAllText(path, Encoding.UTF8);
                return(Json(new
                {
                    result = content
                }));

            case "createFolder":
                string dir = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (req.NewPath) : prefix + req.NewPath;
                //string dir = _hostingEnvironment.WebRootPath + (req.NewPath);
                var directoryInfo = Directory.CreateDirectory(dir);
                list.Add(new
                {
                    success = directoryInfo.Exists.ToString()
                });
                break;

            case "changePermissions":
                break;

            case "compress":
                string filename = Path.Combine(string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (req.Destination) : prefix + req.Destination, Path.GetFileNameWithoutExtension(req.CompressedFilename) + ".zip");
                _sevenZipCompressor.Zip(req.Items.Select(s => string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (s) : prefix + s).ToList(), filename);

                list.Add(new
                {
                    success = "true"
                });
                break;

            case "extract":
                string folder = Path.Combine(string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (req.Destination) : prefix + req.Destination, req.FolderName.Trim('/', '\\'));
                string zip    = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? _hostingEnvironment.WebRootPath + (req.Item) : prefix + req.Item;
                _sevenZipCompressor.Extract(zip, folder);
                list.Add(new
                {
                    success = "true"
                });
                break;
            }
            return(Json(new
            {
                result = list
            }));
        }
Exemplo n.º 7
0
        public ActionResult Handle(FileRequest req)
        {
            List <object> list   = new List <object>();
            var           prefix = CommonHelper.GetSettings("PathRoot").Trim('\\', '/');

            switch (req.Action)
            {
            case "list":
                string   path  = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.Path) : prefix + req.Path;  //Server.MapPath(req.Path);
                string[] dirs  = Directory.GetDirectories(path);
                string[] files = Directory.GetFiles(path);
                dirs.ForEach(s =>
                {
                    DirectoryInfo dirinfo = new DirectoryInfo(s);
                    list.Add(new FileList()
                    {
                        date   = dirinfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        name   = dirinfo.Name,
                        rights = "drwxrwxrwx",
                        size   = 0,
                        type   = "dir"
                    });
                });
                files.ForEach(s =>
                {
                    FileInfo info = new FileInfo(s);
                    list.Add(new FileList()
                    {
                        name   = info.Name,
                        rights = "-rw-rw-rw-",
                        size   = info.Length,
                        date   = info.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        type   = "file"
                    });
                });
                break;

            case "remove":
                req.Items.ForEach(s =>
                {
                    s = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(s) : prefix + s;
                    try
                    {
                        System.IO.File.Delete(s);
                    }
                    catch
                    {
                        Directory.Delete(s, true);
                    }
                });
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "rename":
            case "move":
                path = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.Item) : prefix + req.Item;
                var newpath = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.NewItemPath) : prefix + req.NewItemPath;
                if (!string.IsNullOrEmpty(req.Item))
                {
                    try
                    {
                        System.IO.File.Move(path, newpath);
                    }
                    catch
                    {
                        Directory.Move(path, newpath);
                    }
                }
                else
                {
                    newpath = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.NewPath) : prefix + req.NewPath;
                    req.Items.ForEach(s =>
                    {
                        try
                        {
                            System.IO.File.Move(string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(s) : prefix + s, Path.Combine(newpath, Path.GetFileName(s)));
                        }
                        catch
                        {
                            Directory.Move(string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(s) : prefix + s, Path.Combine(newpath, Path.GetFileName(s)));
                        }
                    });
                }
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "copy":
                path    = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.Item) : prefix + req.Item;
                newpath = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.NewItemPath) : prefix + req.NewItemPath;
                //newpath = Server.MapPath(req.NewItemPath);
                if (!string.IsNullOrEmpty(req.Item))
                {
                    System.IO.File.Copy(path, newpath);
                }
                else
                {
                    newpath = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.NewPath) : prefix + req.NewPath;
                    //Server.MapPath(req.NewPath);
                    req.Items.ForEach(s => System.IO.File.Copy(string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(s) : prefix + s, !string.IsNullOrEmpty(req.SingleFilename) ? Path.Combine(newpath, req.SingleFilename) : Path.Combine(newpath, Path.GetFileName(s))));
                }
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "edit":
                path = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.Item) : prefix + req.Item;
                //path = Server.MapPath(req.Item);
                string content = req.Content;
                System.IO.File.WriteAllText(path, content, Encoding.UTF8);
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "getContent":
                path = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.Item) : prefix + req.Item;
                //path = Server.MapPath(req.Item);
                content = System.IO.File.ReadAllText(path, Encoding.UTF8);
                return(Json(new
                {
                    result = content
                }, JsonRequestBehavior.AllowGet));

            case "createFolder":
                string dir = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.NewPath) : prefix + req.NewPath;
                //string dir = Server.MapPath(req.NewPath);
                var directoryInfo = Directory.CreateDirectory(dir);
                list.Add(new
                {
                    success = directoryInfo.Exists.ToString()
                });
                break;

            case "changePermissions":
                break;

            case "compress":
                string filename = Path.Combine(string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.Destination) : prefix + req.Destination, Path.GetFileNameWithoutExtension(req.CompressedFilename) + ".zip");
                using (FileStream fs = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    List <string> items = req.Items;
                    MemoryStream  ms    = new MemoryStream();
                    byte[]        buffer;
                    using (ZipFile f = ZipFile.Create(ms))
                    {
                        f.BeginUpdate();
                        string dirname = null;
                        items.ForEach(s =>
                        {
                            s = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(s) : prefix + s;
                            if (Directory.Exists(s))
                            {
                                GetFilesRecurs(s);
                            }
                            else
                            {
                                FileList.Add(s);
                                dirname = Path.GetDirectoryName(s);
                            }
                        });
                        if (string.IsNullOrEmpty(dirname))
                        {
                            dirname = Directory.GetParent(FileList[0]).FullName;
                        }
                        f.NameTransform = new ZipNameTransform(dirname);     //通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。
                        FileList.ForEach(s =>
                        {
                            f.Add(s);
                        });
                        f.CommitUpdate();
                        buffer      = new byte[ms.Length];
                        ms.Position = 0;
                        ms.Read(buffer, 0, buffer.Length);
                    }
                    fs.Write(buffer, 0, buffer.Length);
                }
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "extract":
                string folder = Path.Combine(string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.Destination) : prefix + req.Destination, req.FolderName.Trim('/', '\\'));
                string zip    = string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.Item) : prefix + req.Item;
                ClassZip.UnZip(zip, folder);
                list.Add(new
                {
                    success = "true"
                });
                break;

            default:
                var httpfiles = Request.Files;
                if (httpfiles.Count > 0)
                {
                    for (var i = 0; i < httpfiles.Count; i++)
                    {
                        path = Path.Combine(string.IsNullOrEmpty(prefix) && !Directory.Exists(prefix) ? Server.MapPath(req.Destination) : prefix + req.Destination, httpfiles[i].FileName);
                        httpfiles[i].SaveAs(path);
                    }
                }
                break;
            }
            return(Json(new
            {
                result = list
            }, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Metodo per il download di un file associato ad un documento
        /// </summary>
        /// <param name="documentInfo">Informazioni sul documento</param>
        /// <param name="senderAdministrationId">Id dell'amministrazione</param>
        /// <param name="fileRequest">Informazioni sul file richiesto</param>
        /// <param name="userInfo">Informazioni sull'utente con cui recuperare il file</param>
        /// <param name="senderFileManagerUrl">Url del servizio per la gestione dei file</param>
        public static void DownloadFile(DocumentInfo documentInfo, String senderAdministrationId, FileRequest fileRequest, InfoUtente userInfo, String senderFileManagerUrl, out string errPutFile)
        {
            logger.Debug("BEGIN");
            // Reperimento del file
            InteroperabilityController interoperabilityController = new InteroperabilityController();

            Interoperability.Service.Library.FileServiceReference.RemoteFileInfo fileResponse = interoperabilityController.DownloadFile(
                new Interoperability.Service.Library.FileServiceReference.SendFileRequest(
                    senderAdministrationId,
                    documentInfo.DocumentNumber,
                    documentInfo.DocumentServerLocation,
                    documentInfo.FileName,
                    documentInfo.FilePath,
                    documentInfo.Version,
                    documentInfo.VersionId,
                    documentInfo.VersionLabel),
                senderFileManagerUrl);

            // Caricamento del file in DocsPa
            byte[] documentContent = ReadFileContent(fileResponse.FileData, (int)fileResponse.FileTransferInfo.FileLength);

            FileDocumento fileDocument = new FileDocumento()
            {
                content = documentContent,
                length  = (int)fileResponse.FileTransferInfo.FileLength,
                name    = fileResponse.FileTransferInfo.FileName
            };

            String err = String.Empty;

            //Gestione TSDis (DOC+TSR)
            //Siccome non si possono mandare piu file allo stesso tempo, ne è possibile alterare la struttura
            //si è pensato in fase di invio, in caso di documenti con TSR associato, l'invio dello stesso un formato
            //TSD, come marca verrà presa l'ultima disponibile, e unita al documento, creadno un file con estensione TSDis
            //In fase di ricezione il TsdIs, sarà poi spacchettato, il TSR messo in DPA_TIMESTAMP dopo verifica hash e
            //infine il payload messo in documentale con la putfile.


            DocsPaVO.areaConservazione.OutputResponseMarca resultMarca = null;
            if (Path.GetExtension(fileDocument.name) == ".TSDis")
            {
                try
                {
                    Documenti.DigitalSignature.PKCS_Utils.tsd tsdMgr = new Documenti.DigitalSignature.PKCS_Utils.tsd();
                    tsdMgr.explode(fileDocument.content);
                    fileDocument.content = tsdMgr.Data.Content;
                    fileDocument.length  = (int)fileDocument.content.Length;
                    fileDocument.name    = fileDocument.name.Replace(".TSDis", string.Empty);
                    Documenti.DigitalSignature.VerifyTimeStamp vts = new Documenti.DigitalSignature.VerifyTimeStamp();
                    byte[] tsrFile = tsdMgr.TSR.FirstOrDefault().Content;
                    if (vts.machTSR(tsrFile, fileDocument.content))
                    {
                        resultMarca = vts.Verify(fileDocument.content, tsrFile);
                    }
                }
                catch (Exception e)
                {
                    logger.ErrorFormat("Errore gestendo il TSDis {0} {1}", e.Message, e.StackTrace);
                    //manca il loggher pdpdpdpdp
                }
            }

            FileManager.putFile(ref fileRequest, fileDocument, userInfo, out errPutFile, false);
            if (resultMarca != null && resultMarca.esito == "OK")
            {
                DocsPaDB.Query_DocsPAWS.TimestampDoc timestampDoc = new DocsPaDB.Query_DocsPAWS.TimestampDoc();
                timestampDoc.saveTSR(userInfo, resultMarca, fileRequest);
            }

            logger.Debug("END");
        }
Exemplo n.º 9
0
 public static IEnumerator LoadCsv(string filename, PatchDataLoadedCallback <GraphData> callback)
 {
     yield return(FileRequest.GetText(filename, (sr) => callback(ParseCsv(sr))));
 }
Exemplo n.º 10
0
        private static async Task <FileRequest> UpdateFileRequest(DropboxClient client, FileRequest fileRequest, DateTime?deadline = null, string path = null, bool?isOpen = null, string title = null)
        {
            UpdateFileRequestDeadline frDeadline = null;

            if (deadline != null)
            {
                frDeadline = new UpdateFileRequestDeadline.Update(new FileRequestDeadline((DateTime)deadline));
            }

            UpdateFileRequestArgs args = new UpdateFileRequestArgs(fileRequest.Id, title, path, frDeadline, isOpen);

            try
            {
                return(await client.FileRequests.UpdateAsync(args));
            }
            catch
            {
                //TODO: Add error handling
                return(null);
            }
        }
Exemplo n.º 11
0
    public static IEnumerator LoadBin(this GraphData graph, string filename, PatchDataLoadedCallback <GraphData> callback)
    {
        yield return(FileRequest.GetBinary(filename, (br) => ParseBin(br, graph)));

        callback(graph);
    }
Exemplo n.º 12
0
 public static IEnumerator Load(string filename, OnConfigLoadedCallback callback)
 {
     yield return(FileRequest.GetText(filename, (sr) => callback(Parse(sr))));
 }
Exemplo n.º 13
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            bool   retValue      = false;
            bool   isContent     = false;
            bool   issocket      = false;
            string idDocument    = string.Empty;
            string base64content = string.Empty;

            // Put user code to initialize the page here
            try
            {
                this.startUp();
                this.ErrorPage = "";
                if (Request.QueryString["tipofirma"] != null)
                {
                    if (!Request.QueryString["tipofirma"].Equals(""))
                    {
                        tipofirma = Request.QueryString["tipofirma"];
                    }
                }
                if (tipofirma.Equals("cosign"))
                {
                    firmabool = true;
                }
                else
                {
                    firmabool = false;
                }


                if (Request.QueryString["iscontent"] != null)
                {
                    bool.TryParse(Request.QueryString["iscontent"], out isContent);
                }

                if (Request.QueryString["issocket"] != null)
                {
                    bool.TryParse(Request.QueryString["issocket"], out issocket);
                }

                if (Request.QueryString["idDocumento"] != null)
                {
                    idDocument = Request.QueryString["idDocumento"].ToString();
                }

                byte[] ba = null;

                if (!issocket)
                {
                    ba = Request.BinaryRead(Request.ContentLength);
                }
                else
                {
                    string contentFile = Request["contentFile"];
                    //Stream stream=Request.InputStream;
                    if (!String.IsNullOrEmpty(contentFile))
                    {
                        contentFile = contentFile.Replace(' ', '+');
                        contentFile = contentFile.Trim();
                        NttDataWA.Utils.FileJSON file = JsonConvert.DeserializeObject <NttDataWA.Utils.FileJSON>(contentFile);
                        ba = Convert.FromBase64String(file.content);
                    }
                }
                DocsPaWR.DocsPaWebService DocsPaWS = ProxyManager.GetWS();
                DocsPaWR.FileDocumento    fd       = new NttDataWA.DocsPaWR.FileDocumento();
                //fd.content=ba;

                ASCIIEncoding ae = new ASCIIEncoding();
                if (!isContent)
                {
                    base64content = ae.GetString(ba);
                }

                if (UIManager.UserManager.getBoolDocSalva(this) == null)
                {
                    if (!IsPostBack)
                    {
                        //	string prova=base64content.Replace(base64content.Substring(4,2),"Ds");
                        FileRequest fr = null;
                        DocsPaWR.SchedaDocumento schedaDocumento = null;

                        if (string.IsNullOrEmpty(idDocument))
                        {
                            fr = UIManager.FileManager.getSelectedFile();
                        }
                        else
                        {
                            fr = UIManager.FileManager.getSelectedMassSignature(idDocument).fileRequest;
                            FirmaDigitaleMng mmg = new FirmaDigitaleMng();
                            schedaDocumento = mmg.GetSchedaDocumento(idDocument);
                        }

                        if (!string.IsNullOrEmpty(Request.QueryString["signedAsPdf"]))
                        {
                            // Se il file è in formato pdf, viene modificato il nome del file
                            bool signedAsPdf;
                            bool.TryParse(Request.QueryString["signedAsPdf"], out signedAsPdf);
                            if (signedAsPdf)
                            {
                                fr.fileName += ".PdF_convertito"; //SERVE PER IL BACKEND NON MODIFICARLO!!!
                            }
                        }

                        fr.dataInserimento = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");

                        if (fr.GetType().Equals(typeof(DocsPaWR.Allegato)))
                        {
                            // Creazione di un nuovo allegato per il file firmato
                            DocsPaWR.Allegato currentAllegato = (DocsPaWR.Allegato)fr;

                            DocsPaWR.Allegato newAllegato = new DocsPaWR.Allegato();
                            newAllegato.descrizione       = currentAllegato.descrizione;
                            newAllegato.numeroPagine      = currentAllegato.numeroPagine;
                            newAllegato.fileName          = fr.fileName;
                            newAllegato.firmatari         = currentAllegato.firmatari;
                            newAllegato.docNumber         = currentAllegato.docNumber;
                            newAllegato.version           = "0";
                            newAllegato.cartaceo          = false;
                            newAllegato.repositoryContext = UIManager.DocumentManager.GetSelectedAttachment().repositoryContext;

                            fr = newAllegato;
                        }

                        if (isContent)
                        {
                            retValue = DocsPaWS.AppendContentFirmato(ba, firmabool, ref fr, UIManager.UserManager.GetInfoUser());
                        }
                        else
                        {
                            retValue = DocsPaWS.AppendDocumentoFirmato(base64content, firmabool, ref fr, UIManager.UserManager.GetInfoUser());
                        }

                        if (!retValue)
                        {
                            throw new Exception();
                        }

                        UIManager.FileManager.setSelectedFile(fr);
                        if (schedaDocumento == null)
                        {
                            schedaDocumento = UIManager.DocumentManager.getSelectedRecord();
                        }

                        List <DocsPaWR.Allegato> attachments = new List <DocsPaWR.Allegato>(schedaDocumento.allegati);

                        if (UIManager.DocumentManager.getSelectedAttachId() != null)
                        {
                            //attachments.Add((Allegato)fr);
                            //schedaDocumento.allegati = attachments.ToArray();
                            int      index = schedaDocumento.allegati.Select((item, i) => new { obj = item, index = i }).First(item => item.obj.versionId.Equals(UIManager.DocumentManager.GetSelectedAttachment().versionId)).index;
                            Allegato a     = new Allegato();
                            a.applicazione          = fr.applicazione;
                            a.daAggiornareFirmatari = fr.daAggiornareFirmatari;
                            a.dataInserimento       = fr.dataInserimento;
                            a.descrizione           = fr.descrizione;
                            a.docNumber             = fr.docNumber;
                            a.docServerLoc          = fr.docServerLoc;
                            a.fileName          = fr.fileName;
                            a.fileSize          = fr.fileSize;
                            a.firmatari         = fr.firmatari;
                            a.firmato           = fr.firmato;
                            a.idPeople          = fr.idPeople;
                            a.path              = fr.path;
                            a.subVersion        = fr.version;
                            a.version           = fr.version;
                            a.versionId         = fr.versionId;
                            a.versionLabel      = schedaDocumento.allegati[index].versionLabel;
                            a.cartaceo          = fr.cartaceo;
                            a.repositoryContext = fr.repositoryContext;
                            a.TypeAttachment    = 1;
                            //a.numeroPagine = (fr as Allegato).numeroPagine;
                            // modifica necessaria per FILENET (A.B.)
                            if ((fr.fNversionId != null) && (fr.fNversionId != ""))
                            {
                                a.fNversionId = fr.fNversionId;
                            }
                            schedaDocumento.allegati[index] = a;

                            UIManager.DocumentManager.setSelectedAttachId(fr.versionId);
                            UIManager.DocumentManager.setSelectedNumberVersion(a.version);
                            //schedaDocumento.allegati = UIManager.DocumentManager.AddAttachment((Allegato)fr);
                        }
                        else
                        {
                            //fr = UIManager.DocumentManager.AddVersion(fr, false);
                            schedaDocumento.documenti = UIManager.DocumentManager.addVersion(schedaDocumento.documenti, (Documento)fr);
                            UIManager.DocumentManager.setSelectedNumberVersion(fr.version);
                        }

                        UIManager.DocumentManager.setSelectedRecord(schedaDocumento);
                        UIManager.UserManager.setBoolDocSalva(this, "salvato");
                    }
                }
            }
            catch (Exception es)
            {
                ErrorManager.setError(this, es);
            }
        }
Exemplo n.º 14
0
 public static IEnumerator LoadCsv(string filename, PatchDataLoadedCallback <PointData> callback)
 {
     yield return(FileRequest.GetText(filename, (sr) => PatchDataIO.ParseAsync(sr, filename, ParseCsv, callback)));
 }
Exemplo n.º 15
0
        private string CheckSign(SchedaDocumento schedaDoc)
        {
            string msgError = string.Empty;

            FileRequest fileReq    = schedaDoc.documenti[0];
            bool        isPdf      = (FileManager.getEstensioneIntoSignedFile(fileReq.fileName).ToUpper() == "PDF");
            string      estenxione = FileManager.getEstensioneIntoSignedFile(fileReq.fileName).ToLowerInvariant();

            #region FILE NON ACQUISITO
            if (string.IsNullOrEmpty(fileReq.fileSize) || int.Parse(fileReq.fileSize) == 0)
            {
                msgError = "Il file non risulta acquisito, quindi non è possibile applicare la firma HSM.";
                return(msgError);
            }
            #endregion

            #region DOCUMENTO ANNULLATO

            if (schedaDoc.protocollo != null && schedaDoc.protocollo.protocolloAnnullato != null && !string.IsNullOrEmpty(schedaDoc.protocollo.protocolloAnnullato.dataAnnullamento))
            {
                msgError = "Il file non è stato firmato in quanto il protocollo risulta annullato.";
                return(msgError);
            }

            #endregion

            #region DOCUMENTO IN CESTINO

            if (schedaDoc.inCestino != null && schedaDoc.inCestino == "1")
            {
                msgError = "Il file non è stato firmato in quanto il documento è stato rimosso.";
                return(msgError);
            }

            #endregion

            #region DOCUMENTO CONSOLIDATO

            if (schedaDoc.ConsolidationState != null && schedaDoc.ConsolidationState.State != DocsPaWR.DocumentConsolidationStateEnum.None)
            {
                msgError = "Il file non è stato firmato in quanto il documento è consolidato.";
                return(msgError);
            }

            #endregion

            #region DOCUMENTO IN CHECKOUT

            if (schedaDoc.checkOutStatus != null && !string.IsNullOrEmpty(schedaDoc.checkOutStatus.ID))
            {
                msgError = "Il file non è stato firmato in quanto il documento è bloccato.";
                return(msgError);
            }

            #endregion

            #region DOCUMENTO IN SOLA LETTURA

            if (Convert.ToInt32(schedaDoc.accessRights) == Convert.ToInt32(HMdiritti.HMdiritti_Read))
            {
                msgError = "Il file non è stato firmato in quanto il documento è in sola lettura.";
                return(msgError);
            }

            #endregion

            #region DOCUMENTO IN ATTESA DI ACCETTAZIONE

            if (Convert.ToInt32(schedaDoc.accessRights) == Convert.ToInt32(HMdiritti.HDdiritti_Waiting))
            {
                msgError = "Il file non è stato firmato in quanto il documento è in attesa di accettazione.";
                return(msgError);
            }

            #endregion

            #region VERFICA SE è OBBLIGATORIA LA CONVERSIONE IN PDF DEL FILE
            if (!isPdf)
            {
                msgError = "Non è stato possibile firmare il documento. Effettuare la conversione in PDF del file.";
                return(msgError);
            }

            #endregion

            return(msgError);
        }
Exemplo n.º 16
0
 public static IEnumerator LoadBin(this PointData pointData, string filename, PatchDataLoadedCallback <PointData> callback)
 {
     yield return(FileRequest.GetBinary(filename, (br) => callback(ParseBin(br, filename, pointData))));
 }
Exemplo n.º 17
0
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="request">下载请求</param>
        /// <param name="responseStream">文件写入流</param>
        /// <param name="context">站点上下文</param>
        /// <returns></returns>
        public override async Task DownloadFile(FileRequest request, IServerStreamWriter <FileReply> responseStream, ServerCallContext context)
        {
            List <string> lstSuccFiles = new List <string>(); //传输成功的文件
            int           chunkSize    = 1024 * 1024 * 10;    //每次读取的数据
            var           buffer       = new byte[chunkSize]; //数据缓冲区
            FileStream    fs           = null;                //文件流

            try
            {
                for (int i = 0; i < request.FileNames.Count; i++)
                {
                    string    fileName = request.FileNames[i];
                    string    filePath = $"{AppContext.BaseDirectory}\\{Config.Options.JobDirectory}\\{fileName}".Replace('\\', Path.DirectorySeparatorChar);
                    FileReply reply    = new FileReply
                    {
                        FileName = fileName,
                        Mark     = request.Mark
                    };
                    Console.WriteLine($"{request.Mark},下载文件:{filePath}");
                    if (File.Exists(filePath))
                    {
                        fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, chunkSize, useAsync: true);

                        int readTimes = 0;//读取次数
                        while (true)
                        {
                            int readSise = fs.Read(buffer, 0, buffer.Length);
                            if (readSise > 0)
                            {
                                reply.Block   = ++readTimes;
                                reply.Content = Google.Protobuf.ByteString.CopyFrom(buffer, 0, readSise);
                                await responseStream.WriteAsync(reply);
                            }
                            else
                            {
                                reply.Block   = 0;//没有数据了,读取完了
                                reply.Content = Google.Protobuf.ByteString.Empty;
                                await responseStream.WriteAsync(reply);

                                lstSuccFiles.Add(fileName);
                                Console.WriteLine($"{request.Mark},完成发送文件:{filePath}");
                                break;
                            }
                        }
                        fs?.Close();
                    }
                    else
                    {
                        Console.WriteLine($"文件【{filePath}】不存在。");
                        reply.Block = -1;//-1的标记为文件不存在
                        await responseStream.WriteAsync(reply);
                    }
                }
                //告诉客户端,文件传输完成
                await responseStream.WriteAsync(new FileReply
                {
                    FileName = string.Empty,
                    Block    = -2,
                    Content  = Google.Protobuf.ByteString.Empty,
                    Mark     = request.Mark
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{request.Mark},发生异常({ex.GetType()}):{ex.Message}");
            }
            finally
            {
                fs?.Dispose();
            }
            Console.WriteLine($"{request.Mark},文件传输完成。共计【{lstSuccFiles.Count / request.FileNames.Count}】");
        }
Exemplo n.º 18
0
        /// <summary>
        /// Aggiornamento abilitazione / disabilitazione funzioni di checkin - checkout
        /// </summary>
        private void RefreshButtons()
        {
            this.DisableAllButtons();

            DocsPaWR.SchedaDocumento currentScheda = this.CurrentSchedaDocumento;

            if (currentScheda != null)
            {
                FileRequest selectedFile = FileManager.getSelectedFile();

                // Verifica stato consolidamento del documento (solo se non consolidato, si può fare checkout)
                if (currentScheda.ConsolidationState == null ||
                    (currentScheda.ConsolidationState != null && currentScheda.ConsolidationState.State == DocsPaWR.DocumentConsolidationStateEnum.None))
                {
                    if (!string.IsNullOrEmpty(currentScheda.systemId) && (currentScheda.tipoProto != "R" && currentScheda.tipoProto != "C"))
                    {
                        // NB: Nei casi in cui l'utente non è abilitato per l'utilizzo della funzione di checkin / checkout,
                        // le uniche funzionalità non disponibili saranno quelle relative al checkin e all'undocheckout.
                        // In ogni caso potrà vedere lo stato del documento e chi l'ha posto in checkout.

                        // Verifica se il documento non è né cestinato né annullato
                        if (!this.IsDocumentoInCestino && !this.IsDocumentoAnnullato)
                        {
                            CheckOutStatus status = CheckInOutServices.GetCheckOutDocumentStatus();

                            if (status != null)
                            {
                                // Il documento risulta bloccato, reperimento del proprietario del blocco
                                string ownerUser       = status.UserName.ToUpper();
                                bool   isOwnerCheckOut = (ownerUser == UserManager.getInfoUtente().userId.ToUpper());

                                if (this.UserEnabled && isOwnerCheckOut)
                                {
                                    // Documento bloccato dall'utente corrente: funzioni di rilascio abilitate
                                    this.btnCheckIn.Enabled            = true;
                                    this.btnOpenCheckedOutFile.Enabled = true;
                                    this.btnUndoCheckOut.Enabled       = true;

                                    if (DocsPAWA.UserManager.isFiltroAooEnabled(this.Page))
                                    {
                                        DocsPaWR.Registro[] userRegistri = DocsPAWA.UserManager.getListaRegistri(this.Page);
                                        this.btnCheckIn.Enabled            = UserManager.verifyRegNoAOO(currentScheda, userRegistri);
                                        this.btnOpenCheckedOutFile.Enabled = UserManager.verifyRegNoAOO(currentScheda, userRegistri);
                                        this.btnUndoCheckOut.Enabled       = UserManager.verifyRegNoAOO(currentScheda, userRegistri);
                                    }
                                }

                                this.btnShowCheckOutStatus.Enabled = true;
                                this.btnShowCheckOutStatus.Visible = true;
                                this.btnShowCheckOutStatus.ToolTip = "Il documento risulta bloccato dall'utente " + ownerUser;

                                //Verifico che il documento è bloccato per una richiesta di conversione pdf lato server
                                //In caso affermativo disabilito l'apertura del file ed il rilascia sen
                                if (status.InConversionePdf)
                                {
                                    this.btnOpenCheckedOutFile.Enabled = false;
                                    this.btnCheckIn.Enabled            = false;

                                    // Se il documento è in stato di conversione pdf,
                                    // il pulsante di annullamento è abilitato solo se l'owner
                                    // del blocco è l'utente stesso
                                    this.btnUndoCheckOut.Enabled = isOwnerCheckOut;
                                }
                            }
                            else
                            {
                                //modifica
                                DocsPAWA.DocsPaWR.DocsPaWebService ws = new DocsPAWA.DocsPaWR.DocsPaWebService();

                                string idAmm = UserManager.getInfoUtente().idAmministrazione;
                                //DocsPAWA.DocsPaWR.CacheConfig info = ws.getConfigurazioneCache(idAmm);
                                if (ws.isActiveCache(idAmm))
                                {
                                    bool inCache = ws.inCache(currentScheda.docNumber, currentScheda.documenti[currentScheda.documenti.Length - 1].versionId, idAmm);

                                    if (inCache)
                                    {
                                        string pathComponents = ws.recuperaPathComponents(currentScheda.docNumber, currentScheda.documenti[currentScheda.documenti.Length - 1].versionId);
                                        if (string.IsNullOrEmpty(pathComponents))
                                        {
                                            this.btnCheckOut.Enabled = false;
                                        }
                                        else
                                        {
                                            this.btnCheckOut.Enabled = true;
                                        }

                                        if (IsTimeStampedFile)
                                        {
                                            this.btnCheckOut.Enabled = false;
                                        }
                                    }
                                }
                                else
                                //fine mofidica
                                if (Session["docInRisposta"] == null && Session["docInRisposta2"] == null)
                                {
                                    if (!this.IsEnabledProfilazioneAllegati &&
                                        this.IsSelectedTabAllegati && selectedFile.GetType() == typeof(DocsPaWR.Allegato))
                                    {
                                        // La funzione di checkout esplicita da tab allegati è disabilitata se la profilazione allegati è disabilitata
                                        this.btnCheckOut.Enabled = false;
                                    }
                                    else
                                    {
                                        this.btnCheckOut.Enabled = this.UserEnabled;

                                        if (IsTimeStampedFile)
                                        {
                                            this.btnCheckOut.Enabled = false;
                                        }

                                        if (DocsPAWA.UserManager.isFiltroAooEnabled(this.Page))
                                        {
                                            if (btnCheckOut.Enabled)
                                            {
                                                DocsPaWR.Registro[] userRegistri = DocsPAWA.UserManager.getListaRegistri(this.Page);
                                                btnCheckOut.Enabled = UserManager.verifyRegNoAOO(currentScheda, userRegistri);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    this.btnCheckOut.Enabled = false;
                                    if (Session["docInRisposta"] != null)
                                    {
                                        Session.Remove("docInRisposta");
                                    }
                                    else
                                    if (Session["docInRisposta2"] != null)
                                    {
                                        Session.Remove("docInRisposta2");
                                    }
                                }
                            }
                        }
                    }
                }

                // Abilitazione / disabilitazione pulsante salva file,
                // che viene comunque abilitato (se file presente)
                // indipendentemente dalle regole di abilitazione del checkin / checkout

                int size;
                if (selectedFile != null && Int32.TryParse(selectedFile.fileSize, out size))
                {
                    this.btnSave.Enabled = (size > 0);
                }
            }
        }
Exemplo n.º 19
0
        public Model.FileInfo GetFileInfo(FileRequest fileRequest)
        {
            var proxy = _fileService.CreateProxy();

            return(proxy.GetFileInfo(fileRequest));
        }
Exemplo n.º 20
0
 public static IEnumerator Load(string filename, UnityAction <API[]> callback)
 {
     yield return(FileRequest.GetText(filename, (stream) => callback(ParseAPIConfigFile(stream, filename))));
 }
Exemplo n.º 21
0
        public void DeleteFile(FileRequest fileRequest)
        {
            var proxy = _fileService.CreateProxy();

            proxy.DeleteFile(fileRequest);
        }
Exemplo n.º 22
0
        private string CheckSign(FileRequest fileReq, bool isPdf)
        {
            string msgError = string.Empty;

            #region FIRMA PADES

            //Controllo che il file che stò firmando è un PDF
            //if(this.HsmRadioSign.Checked)
            if (this.optFirma.Checked)
            {
                if (!isPdf && this.HsmLitPades.Checked && !this.HsmCheckConvert.Checked)
                {
                    msgError = "WarningHsmSignPDF";
                    return(msgError);
                }
            }

            System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileReq.fileName);
            bool isCadesSign            = (fileInfo != null && !String.IsNullOrEmpty(fileInfo.Extension) && fileInfo.Extension.ToLower().Equals(".p7m"));
            //bool isCadesSign = (!String.IsNullOrEmpty(fileReq.tipoFirma) && fileReq.tipoFirma.Equals(TipoFirma.CADES)) || (fileInfo != null && !String.IsNullOrEmpty(fileInfo.Extension) && fileInfo.Extension.ToLower().Equals(".p7m"));

            if (this.HsmLitPades.Checked && isCadesSign)
            {
                msgError = "WarningHsmSignPades";
                return(msgError);
            }
            #endregion

            #region COFIRMA
            //Non posso firmare parallelemente un file firmato PADES con CADES, quindi impongo firma annidata
            //La cofirma può essere solo di tipo CADES e applicabile so su file firmato CADES

            //if (this.HsmRadioCoSign.Checked)
            //if (this.optCofirma.Checked)
            //{
            //    //Non posso cofirmare PADES
            //    if (this.HsmLitPades.Checked)
            //    {
            //        msgError = "WarningHsmCoSignPades";
            //        return msgError;
            //    }
            //    else if(this.HsmLitP7M.Checked && (System.IO.Path.GetExtension(fileReq.fileName).ToLower().Equals(".pdf")))
            //    {
            //        //Non posso firmare CADES un file firmato PADES :se l'estensione del file è PDF, il file è stato firmato PADES
            //        msgError = "WarningHsmCoSignCades";
            //        return msgError;
            //    }
            //}

            #endregion

            #region FORMATO AMMESSO ALLA FIRMA

            if (!this.HsmCheckConvert.Checked && UIManager.FileManager.IsEnabledSupportedFileTypes())
            {
                string extensionFile = (fileReq.fileName.Split('.').Length > 1) ? (fileReq.fileName.Split('.'))[fileReq.fileName.Split('.').Length - 1] : string.Empty;
                this.FileTypes = UIManager.FileManager.GetSupportedFileTypes(Int32.Parse(UIManager.UserManager.GetInfoUser().idAmministrazione));

                bool retVal = true;

                int count = FileTypes.Count(e => e.FileExtension.ToLowerInvariant() == extensionFile.ToLowerInvariant() &&
                                            e.FileTypeUsed && e.FileTypeSignature);

                retVal = (count > 0);
                if (!retVal)
                {
                    msgError = "WarningFormatoNonAmmessoAllaFirma";
                }
            }


            #endregion



            return(msgError);
        }
Exemplo n.º 23
0
        public File DownloadFile(FileRequest fileRequest)
        {
            var proxy = _fileService.CreateProxy();

            return(proxy.DownloadFile(fileRequest));
        }
Exemplo n.º 24
0
        public ActionResult Handle([FromBody] FileRequest req)
        {
            var list = new List <object>();
            var root = Path.Combine(HostEnvironment.ContentRootPath, CommonHelper.SystemSettings["PathRoot"].TrimStart('\\', '/'));

            switch (req.Action)
            {
            case "list":
                var path  = Path.Combine(root, req.Path.TrimStart('\\', '/'));
                var dirs  = Directory.GetDirectories(path);
                var files = Directory.GetFiles(path);
                list.AddRange(dirs.Select(s => new DirectoryInfo(s)).Select(dirinfo => new FileList
                {
                    date = dirinfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    name = dirinfo.Name,
                    size = 0,
                    type = "dir"
                }).Union(files.Select(s => new FileInfo(s)).Select(info => new FileList
                {
                    name = info.Name,
                    size = info.Length,
                    date = info.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    type = "file"
                })));
                break;

            case "remove":
                req.Items.ForEach(s =>
                {
                    s = Path.Combine(root, s.TrimStart('\\', '/'));
                    try
                    {
                        System.IO.File.Delete(s);
                    }
                    catch
                    {
                        Directory.Delete(s, true);
                    }
                });
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "rename":
            case "move":
                string newpath;
                if (!string.IsNullOrEmpty(req.Item))
                {
                    newpath = Path.Combine(root, req.NewItemPath?.TrimStart('\\', '/'));
                    path    = Path.Combine(root, req.Item.TrimStart('\\', '/'));
                    try
                    {
                        System.IO.File.Move(path, newpath);
                    }
                    catch
                    {
                        Directory.Move(path, newpath);
                    }
                }
                else
                {
                    newpath = Path.Combine(root, req.NewPath.TrimStart('\\', '/'));
                    req.Items.ForEach(s =>
                    {
                        try
                        {
                            System.IO.File.Move(Path.Combine(root, s.TrimStart('\\', '/')), Path.Combine(newpath, Path.GetFileName(s)));
                        }
                        catch
                        {
                            Directory.Move(Path.Combine(root, s.TrimStart('\\', '/')), Path.Combine(newpath, Path.GetFileName(s)));
                        }
                    });
                }
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "copy":
                if (!string.IsNullOrEmpty(req.Item))
                {
                    System.IO.File.Copy(Path.Combine(root, req.Item.TrimStart('\\', '/')), Path.Combine(root, req.NewItemPath.TrimStart('\\', '/')));
                }
                else
                {
                    newpath = Path.Combine(root, req.NewPath.TrimStart('\\', '/'));
                    req.Items.ForEach(s => System.IO.File.Copy(Path.Combine(root, s.TrimStart('\\', '/')), !string.IsNullOrEmpty(req.SingleFilename) ? Path.Combine(newpath, req.SingleFilename) : Path.Combine(newpath, Path.GetFileName(s))));
                }
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "edit":
                System.IO.File.WriteAllText(Path.Combine(root, req.Item.TrimStart('\\', '/')), req.Content, Encoding.UTF8);
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "getContent":
                return(Json(new
                {
                    result = System.IO.File.ReadAllText(Path.Combine(root, req.Item.TrimStart('\\', '/')), Encoding.UTF8)
                }));

            case "createFolder":
                list.Add(new
                {
                    success = Directory.CreateDirectory(Path.Combine(root, req.NewPath.TrimStart('\\', '/'))).Exists.ToString()
                });
                break;

            case "changePermissions":
                //todo:文件权限修改
                break;

            case "compress":
                var filename = Path.Combine(Path.Combine(root, req.Destination.TrimStart('\\', '/')), Path.GetFileNameWithoutExtension(req.CompressedFilename) + ".zip");
                SevenZipCompressor.Zip(req.Items.Select(s => Path.Combine(root, s.TrimStart('\\', '/'))).ToList(), filename);
                list.Add(new
                {
                    success = "true"
                });
                break;

            case "extract":
                var folder = Path.Combine(Path.Combine(root, req.Destination.TrimStart('\\', '/')), req.FolderName.Trim('/', '\\'));
                var zip    = Path.Combine(root, req.Item.TrimStart('\\', '/'));
                SevenZipCompressor.Extract(zip, folder);
                list.Add(new
                {
                    success = "true"
                });
                break;
            }
            return(Json(new
            {
                result = list
            }));
        }
Exemplo n.º 25
0
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="fileNames">需要下载的文件集合</param>
        /// <param name="mark">标记</param>
        /// <param name="saveDirectoryPath">保存路径</param>
        /// <param name="cancellationToken">异步取消命令</param>
        /// <returns>下载任务(是否成功、原因、失败文件名)</returns>
        public static async Task <TransferResult <List <string> > > FileDownload(List <string> fileNames, string mark, string saveDirectoryPath, System.Threading.CancellationToken cancellationToken = new System.Threading.CancellationToken())
        {
            var result = new TransferResult <List <string> >()
            {
                Message = $"文件保存路径不正确:{saveDirectoryPath}"
            };

            if (!System.IO.Directory.Exists(saveDirectoryPath))
            {
                return(await Task.Run(() => result));//文件路径不存在
            }
            if (fileNames.Count == 0)
            {
                result.Message = "未包含任何文件";
                return(await Task.Run(() => result));//文件路径不存在
            }
            result.Message = "未能连接到服务器";
            FileRequest request = new FileRequest()
            {
                Mark = mark
            };                                         //请求数据

            request.FileNames.AddRange(fileNames);     //将需要下载的文件名赋值
            var    lstSuccFiles = new List <string>(); //传输成功的文件
            string savePath     = string.Empty;        //保存路径

            System.IO.FileStream fs = null;
            Channel channel         = null;//申明通信频道

            GrpcService.FileTransfer.FileTransferClient client = null;
            DateTime startTime = DateTime.Now;

            try
            {
                (channel, client) = GetClient();
                using (var call = client.FileDownload(request))
                {
                    List <FileReply> lstContents = new List <FileReply>();//存放接收的数据
                    var reaponseStream           = call.ResponseStream;
                    //reaponseStream.Current.Block数字的含义是服务器和客户端约定的
                    while (await reaponseStream.MoveNext(cancellationToken))//开始接收数据
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            break;
                        }
                        if (reaponseStream.Current.Block == -2)//说明文件已经传输完成了
                        {
                            result.Message      = $"完成下载任务【{lstSuccFiles.Count}/{fileNames.Count}】,耗时:{DateTime.Now - startTime}";
                            result.IsSuccessful = true;
                            break;
                        }
                        else if (reaponseStream.Current.Block == -1)                          //当前文件传输错误
                        {
                            Console.WriteLine($"文件【{reaponseStream.Current.FileName}】传输失败!"); //写入日志
                            lstContents.Clear();
                            fs?.Close();                                                      //释放文件流
                            if (!string.IsNullOrEmpty(savePath) && File.Exists(savePath))     //如果传输不成功,删除该文件
                            {
                                File.Delete(savePath);
                            }
                            savePath = string.Empty;
                        }
                        else if (reaponseStream.Current.Block == 0) //当前文件传输完成
                        {
                            if (lstContents.Any())                  //如果还有数据,就写入文件
                            {
                                lstContents.OrderBy(c => c.Block).ToList().ForEach(c => c.Content.WriteTo(fs));
                                lstContents.Clear();
                            }
                            lstSuccFiles.Add(reaponseStream.Current.FileName); //传输成功的文件
                            fs?.Close();                                       //释放文件流
                            savePath = string.Empty;
                        }
                        else//有文件数据过来
                        {
                            if (string.IsNullOrEmpty(savePath))//如果字节流为空,则说明时新的文件数据来了
                            {
                                savePath = Path.Combine(saveDirectoryPath, reaponseStream.Current.FileName);
                                fs       = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite);
                            }
                            lstContents.Add(reaponseStream.Current); //加入链表
                            if (lstContents.Count() >= 20)           //每个包1M,20M为一个集合,一起写入数据。
                            {
                                lstContents.OrderBy(c => c.Block).ToList().ForEach(c => c.Content.WriteTo(fs));
                                lstContents.Clear();
                            }
                        }
                    }
                }
                fs?.Close();                                                                          //释放文件流
                if (!result.IsSuccessful && !string.IsNullOrEmpty(savePath) && File.Exists(savePath)) //如果传输不成功,那么久删除该文件
                {
                    File.Delete(savePath);
                }
            }
            catch (Exception ex)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    fs?.Close();//释放文件流
                    result.IsSuccessful = false;
                    result.Message      = $"用户取消下载。已完成下载【{lstSuccFiles.Count}/{fileNames.Count}】,耗时:{DateTime.Now - startTime}";
                }
                else
                {
                    result.Message = $"文件传输发生异常:{ex.Message}";
                }
            }
            finally
            {
                fs?.Dispose();
            }
            result.Tag = fileNames.Except(lstSuccFiles).ToList();//获取失败文件集合
            //关闭通信、并返回结果
            return(await channel?.ShutdownAsync().ContinueWith(t => result));
        }
Exemplo n.º 26
0
        /***************************************************/

        public IEnumerable <object> Read(FileRequest fr, PullConfig pullConfig)
        {
            // Convert to the most generic type of Request.
            return(Read((FileDirRequest)fr, pullConfig));
        }
Exemplo n.º 27
0
        public async Task RequestFiles()
        {
            var client = new CITSService.CITSServiceClient();
            client.ClientCredentials.UserName.UserName = CLIENT_USERNAME;
            client.ClientCredentials.UserName.Password = CLIENT_PASSWORD;

            var requestMessage = new FileRequest()
            {
                items = new FileURL[]
                {
                    new FileURL() { url = "http://host:12345//documents/fulfillment/ABCDEFGH-1234-ABCD-1234-000000000001" },
                    new FileURL() { url = "http://host:12345//documents/banking/ABCDEFGH-1234-ABCD-1234-000000000002" }
                }
            };

            var response = await client.ProcessFileRequestsAsync(requestMessage);

            Assert.IsTrue(response.ProcessFileRequestsResult != null);
            Assert.IsTrue(response.ProcessFileRequestsResult.itemsField.Length == 2);
            byte[] fileArray = response.ProcessFileRequestsResult.itemsField[0].byteArray;
            Assert.IsTrue(fileArray.Length > 0);

            string path = null;
            using (var file = System.IO.File.Create(response.ProcessFileRequestsResult.itemsField[0].filename))
            {
                path = file.Name;
                file.Write(fileArray, 0, fileArray.Length);
            }

            Assert.IsTrue(System.IO.File.Exists(path));

            /* Serialize */
            CITSHelper.SerializeMessage(requestMessage);
            CITSHelper.SerializeMessage(response.ProcessFileRequestsResult);
        }
        /// <summary>
        /// Download the specified file asynchroniously
        /// </summary>
        /// <param name="sender">sender of the request</param>
        /// <param name="userState">user state - can be null</param>
        /// <param name="ssUri">uri to the file to download</param>
        /// <param name="callback">callback to call when download is complete - can be null if you just want to download it in the background</param>
        /// <param name="pathToStore">directory where the file should be stored</param>
        /// <param name="fileName">filename of the file. If null then MD5 hash is computed from the uri and used as a filename - good to cache images</param>
        public void DownloadFileAsync(object sender, object userState, SmallUri ssUri, SaveFileAsyncCallback callback, string pathToStore, string fileName = null)
        {
            if (_disposed)
            {
                callback(this, new SaveFileCompletedEventArgs(new ObjectDisposedException("this"), false, userState));
                return;
            }

            if (default(SmallUri) == ssUri)
            {
                if (callback != null)
                    callback(this, new SaveFileCompletedEventArgs(new ArgumentException("The requested image doesn't exist.", "ssUri"), false, userState));
                return;
            }

            if (String.IsNullOrEmpty(fileName))
                fileName = ComputeUrlHash(ssUri.GetString());

            string destinationFullPath = Path.Combine(pathToStore, fileName);
            if (File.Exists(destinationFullPath))
            {
                callback(this, new SaveFileCompletedEventArgs(destinationFullPath, userState, ssUri));
                return;
            }

            // Make asynchronous request to download the image and get the local path.
            var fileRequest = new FileRequest
            {
                Sender = sender,
                UserState = userState,
                SmallUri = ssUri,
                Callback = callback,
                DestinationFileName = Path.Combine(pathToStore, fileName)
            };

            bool needToQueue = false;
            lock (_webLock)
            {
                needToQueue = !_asyncWebRequestPool.HasPendingRequests;
                if (callback != null)
                    _activeWebRequests.Enqueue(fileRequest);
                else
                    _passiveWebRequests.Enqueue(fileRequest);
            }

            if (needToQueue)
                _asyncWebRequestPool.QueueRequest(_ProcessNextWebRequest, null);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Creazione del documento nel sistema
        /// </summary>
        /// <param name="settings">Impostazioni relative al registro su cui creare il documento</param>
        /// <param name="senderInfo">Informazioni sul mittente della richiesta</param>
        /// <param name="interoperabilityMessage">Messaggio con le informazioni sulla richiesta di interoperabilità</param>
        /// <param name="userRole">Ruolo dell'utente da utilizzare per la creazione del documento</param>
        /// <param name="user">Utente da utilizzare per la creazione del documento</param>
        /// <returns>Scheda del documento creato</returns>
        private static SchedaDocumento CreateDocument(InteroperabilitySettings settings, Corrispondente senderInfo, InteroperabilityMessage interoperabilityMessage, Ruolo userRole, Utente user, String messageId)
        {
            // Recupero delle informazioni sull'utente da utilizzare come creatore del documento
            InfoUtente userInfo = UserManager.GetInfoUtente(user, userRole);

            // Creazione della scheda documento da restituire
            SchedaDocumento document = DocManager.NewSchedaDocumento(userInfo);

            // Recupero del registro su cui creare il predisposto
            Registro registry = RegistriManager.getRegistro(settings.RegistryId);

            // Recupero del mezzo di spedizione
            MezzoSpedizione channel = InfoDocManager.GetMezzoSpedizioneDaCodice("SIMPLIFIEDINTEROPERABILITY");

            // Impostazione delle proprietà del documento
            try
            {
                if (!String.IsNullOrEmpty(interoperabilityMessage.MainDocument.FileName))
                {
                    document.appId = InteroperabilitaSegnatura.getApp(interoperabilityMessage.MainDocument.FileName).application;
                }
            }
            catch (Exception e) {}

            document.idPeople = user.idPeople;
            document.userId   = user.userId;
            document.oggetto  = new Oggetto()
            {
                descrizione = interoperabilityMessage.Record.Subject
            };
            document.predisponiProtocollazione = true;
            document.registro            = registry;
            document.tipoProto           = "A";
            document.typeId              = "SIMPLIFIEDINTEROPERABILITY";
            document.mezzoSpedizione     = channel.IDSystem;
            document.descMezzoSpedizione = channel.Descrizione;
            document.interop             = "S";
            document.protocollatore      = new Protocollatore(userInfo, userRole);
            document.privato             = interoperabilityMessage.IsPrivate ? "1" : "0";

            // Se la gestione dell'interoperabilità è manuale con mantenimento
            // del documento pendente, il documento viene creato privato e subito dopo
            // la creazione viene rimarcato come non privato
            if (settings.ManagementMode == ManagementType.M && settings.KeepPrivate)
            {
                document.privato = "1";
            }

            // Preparazione dell'oggetto protocollo entrata
            ProtocolloEntrata proto = new ProtocolloEntrata();

            proto.mittente = senderInfo;
            proto.dataProtocolloMittente        = interoperabilityMessage.Record.RecordDate.ToString("dd/MM/yyyy HH:mm:ss");
            proto.descrizioneProtocolloMittente = String.Format("{0}{1}{2}",
                                                                interoperabilityMessage.Record.AOOCode,
                                                                DocsPaDB.Utils.Personalization.getInstance(registry.idAmministrazione).getSepSegnatura(),
                                                                interoperabilityMessage.Record.RecordNumber);
            document.protocollo = proto;

            // Se per l'amministrazione è configurata l'aggiunta di una nota visibile a tutti,
            // ne viene aggiunta una
            String value = DocsPaUtils.Configuration.InitConfigurationKeys.GetValue("0", "BE_NOTE_IN_SEGNATURA");

            if (!String.IsNullOrEmpty(value) && value == "1" && !String.IsNullOrEmpty(interoperabilityMessage.Note))
            {
                document.noteDocumento = new List <DocsPaVO.Note.InfoNota>()
                {
                    new DocsPaVO.Note.InfoNota(interoperabilityMessage.Note, userInfo.idPeople, userInfo.idGruppo, DocsPaVO.Note.TipiVisibilitaNotaEnum.Tutti, String.Empty)
                    {
                        DaInserire = true
                    }
                }
            }
            ;

            // Salvataggio del documento
            try
            {
                document = DocSave.addDocGrigia(document, userInfo, userRole);

                // Associazione del canale di spedizione al documento
                ProtoManager.collegaMezzoSpedizioneDocumento(userInfo, channel.IDSystem, document.systemId);
            }
            catch (Exception e)
            {
                SimplifiedInteroperabilityLogAndRegistryManager.InsertItemInLog(String.Empty, true, e.Message + " Id messaggio: " + messageId);
                throw new CreatingDocumentException("Errore durante la creazione del documento");
            }
            // Se tutto è andato bene, la scheda documento ha ora il campo system id popolato, quindi viene aggiunta
            // una voce al log e viene aggiornato l'id profile per la voce nel registro dei messaggi ricevuti
            SimplifiedInteroperabilityLogAndRegistryManager.InsertItemInLog(document.systemId, false,
                                                                            String.Format("Documento relativo alla richiesta con id {0}, creato correttamente.", messageId));
            SimplifiedInteroperabilityLogAndRegistryManager.SetIdProfileForMessage(messageId, document.systemId);

            // Impostazione delle informazioni aggiuntive e salvataggio del documento
            ((Documento)document.documenti[0]).dataArrivo = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
            bool toUpdate;

            document = DocSave.save(userInfo, document, false, out toUpdate, userRole);
            string errPutFile = "";

            try
            {
                // Associazione dell'immagine al documento
                String      err     = String.Empty;
                FileRequest request = document.documenti[0] as FileRequest;
                logger.DebugFormat("IS - Associa documento. Versionid {0}, Versionlabel {1}, version {2}",
                                   request.versionId, request.versionLabel, request.version);

                if (!String.IsNullOrEmpty(interoperabilityMessage.MainDocument.FileName))
                {
                    SimplifiedInteroperabilityFileManager.DownloadFile(
                        interoperabilityMessage.MainDocument,
                        interoperabilityMessage.Sender.AdministrationId,
                        request,
                        userInfo,
                        interoperabilityMessage.Sender.FileManagerUrl,
                        out errPutFile);
                }
                if (!string.IsNullOrEmpty(errPutFile))
                {
                    throw new Exception("Errore durante l'associazione dell'immagine al documento principale");
                }
            }
            catch (Exception e)
            {
                SimplifiedInteroperabilityLogAndRegistryManager.InsertItemInLog(
                    document.systemId,
                    true,
                    String.Format("Errore durante l'associazione dell'immagine per il documento principale. Messaggio eccezione: {0}",
                                  e.Message));
                if (!string.IsNullOrEmpty(errPutFile) && errPutFile.Contains("formato file"))
                {
                    throw new DownloadDocumentException("Errore durante l'associazione dell'immagine al documento principale." + errPutFile + " destinataria.");
                }
                else
                {
                    throw new DownloadDocumentException("Errore durante l'associazione dell'immagine al documento principale");
                }
            }
            AddAttachments(document.docNumber, interoperabilityMessage.Attachments, userInfo, interoperabilityMessage.Sender.AdministrationId, interoperabilityMessage.Sender.FileManagerUrl);
            // Restituzione del documento salvato
            return(document);
        }