public static void Run()
        {
            // ExStart:AttachFileAndSetIcon
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_Attachments();

            // Create an object of the Document class
            Document doc = new Document();

            // Initialize Page class object
            Aspose.Note.Page page = new Aspose.Note.Page(doc);
            // Initialize Outline class object
            Outline outline = new Outline(doc);
            // Initialize OutlineElement class object
            OutlineElement outlineElem = new OutlineElement(doc);
            // Initialize AttachedFile class object and also pass its icon path
            AttachedFile attachedFile = new AttachedFile(doc, dataDir + "attachment.txt", File.OpenRead(dataDir + "icon.jpg"), ImageFormat.Jpeg);

            // Add attached file
            outlineElem.AppendChild(attachedFile);
            // Add outline element node
            outline.AppendChild(outlineElem);
            // Add outline node
            page.AppendChild(outline);
            // Add page node
            doc.AppendChild(page);

            dataDir = dataDir + "AttachFileAndSetIcon_out.one";
            doc.Save(dataDir);
            // ExEnd:AttachFileAndSetIcon

            Console.WriteLine("\nFile attached and it's icon setup successfully.\nFile saved at " + dataDir);
        }
示例#2
0
        private void ViewJobCard(MaintenanceDirective selectedMpd, AttachedFile attachedFile)
        {
            if (attachedFile == null)
            {
                MessageBox.Show("Not set Job Card File", (string)new GlobalTermsProvider()["SystemName"],
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }

            try
            {
                string message;
                GlobalObjects.CasEnvironment.OpenFile(attachedFile, out message);
                if (message != "")
                {
                    MessageBox.Show(message, (string)new GlobalTermsProvider()["SystemName"],
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
                                    MessageBoxDefaultButton.Button1);
                }
            }
            catch (Exception ex)
            {
                var errorDescriptionSctring = $"Error while Open Attached File for {selectedMpd}, id {selectedMpd.ItemId}. \nFileId {attachedFile.ItemId}";
                Program.Provider.Logger.Log(errorDescriptionSctring, ex);
            }
        }
示例#3
0
 public AttachedFileViewModel(AttachedFile file)
 {
     Id       = file.Id;
     FullName = file.RelativePath;
     Name     = Path.GetFileName(FullName);
     //Size =
 }
示例#4
0
        public void ImportAdTAskCArd()
        {
            var env = GetEnviroment();

            var itemRelationCore = new ItemsRelationsDataAccess(env);
            var directiveCore    = new DirectiveCore(env.NewKeeper, env.NewLoader, env.Keeper, env.Loader, itemRelationCore);

            var aircraft = env.NewLoader.GetObject <AircraftDTO, Aircraft>(new Filter("ItemId", 2348));

            var directiveList = directiveCore.GetDirectives(aircraft, DirectiveType.AirworthenessDirectives);

            var d     = new DirectoryInfo(@"H:\CRJ200 27.02.18 AD");
            var files = d.GetFiles();

            foreach (var mpd in directiveList)
            {
                var file = files.FirstOrDefault(f => mpd.Title.Contains(f.Name.Replace(" ", "").Replace(".pdf", "")));
                if (file != null)
                {
                    var _fileData    = UsefulMethods.GetByteArrayFromFile(file.FullName);
                    var attachedFile = new AttachedFile
                    {
                        FileData = _fileData,
                        FileName = file.Name,
                        FileSize = _fileData.Length
                    };
                    mpd.ADNoFile = attachedFile;
                    env.NewKeeper.Save(mpd);
                }
            }
        }
示例#5
0
        public void SaveAsFile(AttachedFile attachedFile, string filePath, out string message)
        {
            message = "";

            if (attachedFile.FileData == null)
            {
                attachedFile = _newLoader.GetObjectById <AttachedFileDTO, AttachedFile>(attachedFile.ItemId, true);

                if (attachedFile.FileData == null)
                {
                    return;
                }
            }

            try
            {
                var fileStreamBack = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                fileStreamBack.Write(attachedFile.FileData, 0, attachedFile.FileData.Length);
                fileStreamBack.Close();
            }
            catch (IOException ioException)
            {
                message = ioException.Message;
            }
        }
示例#6
0
        public void ImportAdTAskCArdOrCrateNew()
        {
            var env = GetEnviroment();

            var itemRelationCore = new ItemsRelationsDataAccess(env);
            var aircraftCore     = new AircraftsCore(env.Loader, env.NewKeeper, null);
            var directiveCore    = new DirectiveCore(env.NewKeeper, env.NewLoader, env.Keeper, env.Loader, itemRelationCore);
            var componentCore    = new ComponentCore(env, env.Loader, env.NewLoader, env.NewKeeper, aircraftCore, itemRelationCore);

            var aircraftId = 2336;

            var aircraft = env.NewLoader.GetObject <AircraftDTO, Aircraft>(new Filter("ItemId", aircraftId));

            var directiveList = directiveCore.GetDirectives(aircraft, DirectiveType.AirworthenessDirectives);
            var bd            = componentCore.GetAicraftBaseComponents(aircraftId, BaseComponentType.Frame.ItemId).LastOrDefault();

            var d     = new DirectoryInfo(@"D:\Work\doc\ALL AD 757 13 Feb 2019 1111\FAA 757");
            var files = d.GetFiles();

            foreach (var file in files)
            {
                var name      = file.Name.Replace(" ", "").Replace(".pdf", "");
                var directive = directiveList.FirstOrDefault(i => i.Title.Contains(name));

                if (directive != null)
                {
                    var _fileData    = UsefulMethods.GetByteArrayFromFile(file.FullName);
                    var attachedFile = new AttachedFile
                    {
                        FileData = _fileData,
                        FileName = file.Name,
                        FileSize = _fileData.Length
                    };
                    directive.ADNoFile = attachedFile;
                    env.NewKeeper.Save(directive);
                }
                else
                {
                    var newDirective = new Directive
                    {
                        Title               = name,
                        DirectiveType       = DirectiveType.AirworthenessDirectives,
                        ADType              = ADType.Airframe,
                        HiddenRemarks       = "NEW",
                        IsApplicability     = true,
                        ParentBaseComponent = bd
                    };

                    var _fileData    = UsefulMethods.GetByteArrayFromFile(file.FullName);
                    var attachedFile = new AttachedFile
                    {
                        FileData = _fileData,
                        FileName = file.Name,
                        FileSize = _fileData.Length
                    };
                    newDirective.ADNoFile = attachedFile;
                    env.NewKeeper.Save(newDirective);
                }
            }
        }
示例#7
0
        private void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBarLoad.Visible = false;
            progressBarLoad.Value   = 0;

            string message;

            if (_file != null)
            {
                _fileName = _file.FileName;
                _fileData = _file.FileData;
                _fileSize = _file.FileData != null ? _file.FileData.Length : _file.FileSize;

                GlobalObjects.CasEnvironment.OpenFile(_file, out message);
            }
            else
            {
                AttachedFile temp = new AttachedFile();

                temp.FileName = _fileName;
                temp.FileData = _fileData;
                temp.FileSize = _fileSize;

                GlobalObjects.CasEnvironment.OpenFile(temp, out message);
            }
            if (message != "")
            {
                MessageBox.Show(message, (string)new GlobalTermsProvider()["SystemName"],
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }
        }
示例#8
0
        /// <summary>
        /// Возвращает список параметров, которые могут использоваться в запросах
        /// </summary>
        public static SqlParameter[] GetParameters(AttachedFile item)
        {
            List <SqlParameter> parameters = new List <SqlParameter>();

            parameters.Add(new SqlParameter("@IsDeleted", DbTypes.DbObject(item.IsDeleted)));
            parameters.Add(new SqlParameter("@ItemID", DbTypes.DbObject(item.ItemId)));
            parameters.Add(new SqlParameter("@FileName", DbTypes.DbObject(item.FileName)));
            //parameters.Add(new SqlParameter("@FileData", DbTypes.DbObject(item.FileData)));

            object       dbvalue   = DbTypes.DbObject(item.FileData);
            SqlParameter parameter = new SqlParameter();

            if (dbvalue == DBNull.Value)
            {
                parameter.IsNullable    = true;
                parameter.ParameterName = "@FileData";
                parameter.SqlDbType     = SqlDbType.VarBinary;
                parameter.SqlValue      = dbvalue;
            }
            else
            {
                parameter.IsNullable    = false;
                parameter.ParameterName = "@FileData";
                parameter.Value         = dbvalue;
            }
            parameters.Add(parameter);

            return(parameters.ToArray());
        }
示例#9
0
        private void ListView3SelectedIndexChanged(object sender, EventArgs e)
        {
            if (m_ListView3.SelectedItems.Count > 0)
            {
                m_ListBox1.Items.Clear();
                m_ListBox2.Items.Clear();

                var reportId = (int)m_ListView3.SelectedItems[0].Tag;
                Dictionary <string, string> customProperties = m_AllReports[reportId].GetCustomProperties();

                foreach (string propertyName in customProperties.Keys)
                {
                    string propertyValue = customProperties[propertyName];
                    m_ListBox1.Items.Add(propertyName + "=" + propertyValue);
                }

                Dictionary <string, AttachedFile> attachedFiles = m_AllReports[reportId].GetAttachedFiles();

                foreach (string key in attachedFiles.Keys)
                {
                    AttachedFile attachedFile = attachedFiles[key];
                    m_ListBox2.Items.Add(attachedFile);
                }
            }
        }
示例#10
0
        /// <summary>
        /// Заполняет поля
        /// </summary>
        /// <param name="row"></param>
        public static AttachedFile Fill(DataRow row)
        {
            if (DbTypes.ToString(row["FileName"]) == "" ||
                DbTypes.ToInt32(row["FileSize"]) <= 4)
            {
                return(null);
            }

            AttachedFile item = new AttachedFile();

            item.IsDeleted = DbTypes.ToBool(row["IsDeleted"]);
            item.ItemId    = DbTypes.ToInt32(row["ItemID"]);
            item.FileName  = DbTypes.ToString(row["FileName"]);

            try  // если не грузим FileData из базы
            {
                item.FileData = DbTypes.ToBytes(row["FileData"]);
            }
            catch
            {
                item.FileData = null;
            }

            item.FileSize = DbTypes.ToInt32(row["FileSize"]);
            return(item);
        }
        public static void Run()
        {
            // ExStart:AttachFileByPath
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_Attachments();

            // Create an object of the Document class
            Document doc = new Document();

            // Initialize Page class object
            Aspose.Note.Page page = new Aspose.Note.Page(doc);
            // Initialize Outline class object
            Outline outline = new Outline(doc);
            // Initialize OutlineElement class object
            OutlineElement outlineElem = new OutlineElement(doc);
            // Initialize AttachedFile class object
            AttachedFile attachedFile = new AttachedFile(doc, dataDir + "attachment.txt");

            // Add attached file
            outlineElem.AppendChild(attachedFile);
            // Add outline element node
            outline.AppendChild(outlineElem);
            // Add outline node
            page.AppendChild(outline);
            // Add page node
            doc.AppendChild(page);
            dataDir = dataDir + "AttachFileByPath_out.one";
            doc.Save(dataDir);
            // ExEnd:AttachFileByPath

            Console.WriteLine("\nFile by path attached successfully.\nFile saved at " + dataDir);
        }
示例#12
0
 public FileBO(AttachedFile entity)
 {
     FileId = entity.Id;
     Name   = entity.Name;
     Link   = entity.Link;
     TaskId = entity.TaskId;
     NoteId = entity.NoteId;
 }
 private void linkLabelRemove_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     file = null;
     UpdateInfo();
     if (FileChanged != null)
     {
         FileChanged("");
     }
 }
 /// <summary>
 /// Создает элемент управления для отображения информации о прикрепленном файле в формах редактирования чего-либо
 /// </summary>
 /// <param name="file">Сам файл</param>
 /// <param name="filter">Фильтр в OpenFileDialog</param>
 /// <param name="description1">Описание 1</param>
 /// <param name="description2">Описание 2</param>
 /// <param name="icon">Иконка файла</param>
 public WindowsFormAttachedFileControl(AttachedFile file, string filter, string description1, string description2, Image icon)
 {
     this.file         = file;
     this.filter       = filter;
     this.description1 = description1;
     this.description2 = description2;
     this.icon         = icon;
     InitializeComponent();
     UpdateInfo();
 }
示例#15
0
        public AttachedFile GetAttachedFileById(int id)
        {
            AttachedFile attachedFile = null;

            if (id > 0)
            {
                attachedFile = GetObject <AttachedFileDTO, AttachedFile>(new Filter("ItemId", id));
            }

            return(attachedFile);
        }
示例#16
0
 /// <summary>
 /// Конструктор создает объект с параметрами по умолчанию
 /// </summary>
 public TemplateDamageChart()
 {
     IsDeleted     = false;
     ItemId        = -1;
     ChartName     = "";
     AircraftModel = new AircraftModel {
         ItemId = -1
     };
     FileId       = -1;
     AttachedFile = null;
 }
        private void ToolStripMenuShowTaskCard_Click(object sender, EventArgs e)
        {
            if (_directivesViewer.SelectedItems == null ||
                _directivesViewer.SelectedItems.Count == 0)
            {
                return;
            }
            var o = _directivesViewer.SelectedItems[0].ParentObject;

            AttachedFile attachedFile = null;


            if (o is NextPerformance)
            {
                var np = o as NextPerformance;
                attachedFile = GetItemFile(np.Parent);
            }
            else if (o is AbstractPerformanceRecord)
            {
                var apr = o as AbstractPerformanceRecord;
                attachedFile = GetItemFile(apr.Parent);
            }
            else
            {
                attachedFile = GetItemFile(o);
            }

            if (o != null && attachedFile == null)
            {
                MessageBox.Show("Not set Task Card File", (string)new GlobalTermsProvider()["SystemName"],
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
                                MessageBoxDefaultButton.Button1);
                return;
            }

            try
            {
                string message;
                GlobalObjects.CasEnvironment.OpenFile(attachedFile, out message);
                if (message != "")
                {
                    MessageBox.Show(message, (string)new GlobalTermsProvider()["SystemName"],
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
                                    MessageBoxDefaultButton.Button1);
                }
            }
            catch (Exception ex)
            {
                string errorDescriptionSctring =
                    $"Error while Open Attached File for {o}, id {o.ItemId}. \nFileId {attachedFile.ItemId}";
                Program.Provider.Logger.Log(errorDescriptionSctring, ex);
            }
        }
示例#18
0
        /// <summary>
        /// Проверяем есть ли файл в Бд(если есть возвращаем его fileId, если нет то ноль)
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private int FindFileId(AttachedFile file)
        {
            int fileId = 0;
            var ds     = _environment.Execute(AttachedFileQueries.GetSelectQueryByNameAndSize(file.FileName, Convert.ToInt32(file.FileSize)));

            if (ds.Tables[0].Rows.Count > 0)
            {
                fileId = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            }

            return(fileId);
        }
示例#19
0
        /// <summary>
        /// Применить к объекту сделанные изменения на контроле.
        /// Если не все данные удовлетворяют формату ввода (например при вводе чисел), свойства объекта не изменяются, возвращается false
        /// Вызов base.ApplyChanges() обязателен
        /// </summary>
        /// <returns></returns>
        public void ApplyChanges()
        {
            if (_file == null)
            {
                _file = new AttachedFile();
            }

            _file.FileData = null;

            _file.FileName = _fileName;
            _file.FileData = _fileData;
            _file.FileSize = _fileSize;
        }
        ///<summary>
        /// Создает экземпляр класса для отображения информации о директиве
        ///</summary>
        ///<param name="currentDirective"></param>
        public DirectiveInformationControl(Directive currentDirective)
        {
            if (null == currentDirective)
            {
                throw new ArgumentNullException("currentDirective", "Argument cannot be null");
            }
            _directive = currentDirective;
            InitializeComponent();
            ataChapterComboBox.UpdateInformation();

            AttachedFile adNofile = null;

            if (currentDirective.ADNoFile != null)
            {
                adNofile = currentDirective.ADNoFile;
            }
            fileControlADNo.UpdateInfo(adNofile, "Adobe PDF Files|*.pdf",
                                       "This record does not contain a file proving the AD No. Enclose PDF file to prove the compliance.",
                                       "Attached file proves the AD No.");

            AttachedFile sBfile = null;

            if (currentDirective.ServiceBulletinFile != null)
            {
                sBfile = currentDirective.ServiceBulletinFile;
            }
            fileControlSB.UpdateInfo(sBfile, "Adobe PDF Files|*.pdf",
                                     "This record does not contain a file proving the Service bulletin. Enclose PDF file to prove the compliance.",
                                     "Attached file proves the Service bulletin.");

            AttachedFile stcfile = null;

            if (currentDirective.STCFile != null)
            {
                stcfile = currentDirective.STCFile;
            }
            attachedFileControlSTC.UpdateInfo(stcfile, "Adobe PDF Files|*.pdf",
                                              "This record does not contain a file proving the Service bulletin. Enclose PDF file to prove the compliance.",
                                              "Attached file proves the Service bulletin.");
            AttachedFile eOfile = null;

            if (currentDirective.EngineeringOrderFile != null)
            {
                eOfile = currentDirective.EngineeringOrderFile;
            }
            fileControlEO.UpdateInfo(eOfile, "Adobe PDF Files|*.pdf",
                                     "This record does not contain a file proving the Engineering order. Enclose PDF file to prove the compliance.",
                                     "Attached file proves the Engineering order.");
        }
示例#21
0
        public EASAControl(AbstractDetail detail, string filter, string description1, string description2, Image icon)
        {
            currentDetail = detail;
            AttachedFile attachedFile = new AttachedFile();

            attachedFile.FileData = currentDetail.EASAdata;
            attachedFile.FileName = "EASA Form 8330.pdf";
            AttachedFile          = attachedFile;
            this.filter           = filter;
            this.description1     = description1;
            this.description2     = description2;
            this.icon             = icon;
            InitializeComponent();
            UpdateInformation();
        }
示例#22
0
        /// <summary>
        /// Заполняет поля
        /// </summary>
        /// <param name="row"></param>
        /// <param name="item"></param>
        public static void Fill(DataRow row, AttachedFile item)
        {
            item.IsDeleted = DbTypes.ToBool(row["IsDeleted"]);
            item.ItemId    = DbTypes.ToInt32(row["ItemID"]);
            item.FileName  = DbTypes.ToString(row["FileName"]);

            try  // если не грузим FileData из базы
            {
                item.FileData = DbTypes.ToBytes(row["FileData"]);
            }
            catch
            {
                item.FileData = null;
            }

            item.FileSize = DbTypes.ToInt32(row["FileSize"]);
        }
示例#23
0
        /// <summary>
        /// Создает воздушное судно без дополнительной информации
        /// </summary>
        public ComponentLLPCategoryChangeRecord(ComponentLLPCategoryChangeRecord toCopy) : this()
        {
            if (toCopy == null)
            {
                return;
            }

            _file             = toCopy.AttachedFile;
            _onLifelength     = new Lifelength(toCopy.OnLifelength);
            ParentComponent   = toCopy.ParentComponent;
            _parentId         = toCopy.ParentId;
            _parentType       = toCopy.ParentType;
            _performanceNum   = toCopy.PerformanceNum;
            _remarks          = toCopy.Remarks;
            ToCategory        = toCopy.ToCategory;
            _wpId             = toCopy.DirectivePackageId;
            _directivePackage = toCopy.DirectivePackage;
        }
        protected void btnSend_Click(object sender, EventArgs e)
        {
            // Initialize the SDK using the API key and secret in the web.config file
            var appSettings = ConfigurationManager.AppSettings;

            Global.Init(appSettings["apiKey"], appSettings["apiSecret"]);

            List <AttachedFile> filesToAttach = null;

            if (FileUpload1.HasFile)
            {
                AttachedFile fileToAttach = new AttachedFile();
                fileToAttach.FileContents = FileUpload1.FileBytes;
                fileToAttach.FullFileName = FileUpload1.FileName;
                filesToAttach             = new List <AttachedFile>();
                filesToAttach.Add(fileToAttach);
            }

            try
            {
                TT.Win.SDK.Model.MessageEventData messageSent = null;
                if (string.IsNullOrEmpty(txtOrg.Text))
                {
                    messageSent = Message.SendMessage(this.txtMessage.Text, this.txtRecipient.Text, filesToAttach);
                }
                else
                {
                    messageSent = Message.SendMessage(this.txtMessage.Text, this.txtRecipient.Text, txtOrg.Text, filesToAttach);
                }

                if (messageSent.message_id != null)
                {
                    ShowResult(true, "Message sent successfully.  MessageId is " + messageSent.message_id + ".  <a href=\"MessageDetail.aspx?message_id=" + messageSent.message_id + "\">Click here</a> to view message detail and status.");
                }
                else
                {
                    ShowResult(false, "Send Message failed.");
                }
            }
            catch (Exception ex)
            {
                ShowResult(false, ex.Message);
            }
        }
示例#25
0
        private void ButtonLoadClick(object sender, EventArgs e)
        {
            try
            {
                foreach (ListViewItem listViewItem in listViewFiles.SelectedItems)
                {
                    AttachedFile file = new AttachedFile();
                    file.FileData = UsefulMethods.GetByteArrayFromFile(listViewItem.SubItems[2].Text);
                    file.FileName = listViewItem.SubItems[0].Text;
                    file.FileSize = file.FileData.Length;

                    GlobalObjects.NewKeeper.Save(file);
                }
            }
            catch (Exception ex)
            {
                Program.Provider.Logger.Log("Error while save attached file", ex);
            }
        }
示例#26
0
        private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            if (_file == null || _file.ItemId <= 0 || _fileData != null)
            {
                return;
            }

            backgroundWorker.ReportProgress(50);

            try
            {
                _file = GlobalObjects.CasEnvironment.NewLoader.GetObjectById <AttachedFileDTO, AttachedFile>(_file.ItemId, true);
            }
            catch (Exception ex)
            {
                Program.Provider.Logger.Log("Error while set Attached File Fields", ex);
            }

            backgroundWorker.ReportProgress(100);
        }
        private void linkLabelBrowse_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Filter = filter;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                if (file == null)
                {
                    file = new AttachedFile();
                }
                file.FileData = UsefulMethods.GetByteArrayFromFile(dialog.FileName);
                file.FileName = dialog.FileName.Substring(dialog.FileName.LastIndexOf('\\') + 1);
                UpdateInfo();
                if (FileChanged != null)
                {
                    FileChanged(file.FileName.Substring(0, file.FileName.LastIndexOf('.')));
                }
            }
        }
        public FileInfoDisplayModel AttachFileToWorkItem(int workItemId, string fullPath, Stream inputStream)
        {
            var fileManager = this._fileSystemManagerProvider.GetManagerForPath(fullPath);

            if (fileManager == null)
            {
                throw new PmsException("Указанный путь не поддерживается");
            }
            var storageFolder = this._settingsProvider.GetSettingValue(SettingType.FileStoragePath);

            if (storageFolder == null)
            {
                throw new PmsException("Не указан путь для сохранения. Поправьте настройки");
            }
            string relativePath;

            if (fullPath.StartsWith(storageFolder))
            {
                relativePath = fullPath.Remove(0, storageFolder.Length);
            }
            else
            {
                relativePath = Path.GetFileName(fullPath);
                var savingPath = Path.Combine(storageFolder, relativePath);
                fileManager.SaveStreamToFile(inputStream, savingPath);
            }
            var file = new AttachedFile
            {
                RelativePath = relativePath,
                WorkItemId   = workItemId
            };

            return(new FileInfoDisplayModel
            {
                Id = file.Id,
                Name = Path.GetFileName(file.RelativePath),
                FullPath = Path.Combine(storageFolder, file.RelativePath),
                Size = inputStream.Length / 1024 + "KB"
            });
        }
示例#29
0
    private void HandleFileAttachments()
    {
        if (!Request.Form.AllKeys.Contains("ibgMatchField") || string.IsNullOrEmpty(Request.Form["ibgMatchField"]))
        {
            return;
        }

        var matchValue = Request.Form["ibgMatchField"];

        if (string.IsNullOrEmpty(matchValue))
        {
            return;
        }

        var client = new SDataClient(SDataUrl)
        {
            UserName = SDataUser,
            Password = SDataPassword
        };

        foreach (string fileKey in Request.Files)
        {
            var file = Request.Files[fileKey];
            if (file == null || file.ContentLength == 0)
            {
                continue;
            }

            var attachment = new AttachedFile(null, file.FileName, file.InputStream);
            client.Execute(new SDataParameters
            {
                Method  = HttpMethod.Post,
                Path    = "attachments",
                Content = new CrmAttachment {
                    Description = matchValue
                },
                Files = { attachment }
            });
        }
    }
示例#30
0
        private async Task FillBlockFile(Request request, Argument argument)
        {
            var documents    = request.Documents.Where(d => _allCodes.Contains(d.Document.Type.Code) && d.Document.AdditionalAttachments.Any());
            var attachedFile = new List <AttachedFile>();

            foreach (var requestDocument in documents)
            {
                BlockFileAttachedFileFile fileFile = null;
                if (requestDocument.Document.AdditionalAttachments.Any())
                {
                    var att = requestDocument.Document.AdditionalAttachments.First();

                    var file = Convert.ToBase64String(await _fileStorage.GetAsync(
                                                          att.BucketName,
                                                          att.OriginalName));
                    fileFile = new BlockFileAttachedFileFile
                    {
                        Name     = att.ValidName,
                        Content  = file,
                        ShepFile = null
                    };
                }

                var attach = new AttachedFile
                {
                    Type = new BlockFileAttachedFileType
                    {
                        UID  = (requestDocument.Document.Type.ExternalId ?? requestDocument.Document.Type.Id).ToString(),
                        Note = requestDocument.Document.Type.NameRu
                    },
                    PageCount = requestDocument.Document.PageCount.ToString(),
                    File      = fileFile
                };
                attachedFile.Add(attach);
            }

            argument.BlockFile = new BlockFile();
            argument.BlockFile.AddRange(attachedFile);
        }