Example #1
0
        private string AddJoplinAttachmentMetadata(Attachements attach)
        {
            var sb = new StringBuilder();

            sb.Append($"{attach.ExportFileName}\n");

            var data = new Dictionary <string, string>();

            data["id"]                        = attach.Id;
            data["mime"]                      = MimeTypes.GetMimeType(attach.ExportFilePath);
            data["filename"]                  = attach.FriendlyFileName;
            data["updated_time"]              = attach.Parent.LastModificationDate.ToString("s");
            data["user_updated_time"]         = attach.Parent.LastModificationDate.ToString("s");
            data["created_time"]              = attach.Parent.CreationDate.ToString("s");
            data["user_created_time"]         = attach.Parent.CreationDate.ToString("s");
            data["file_extension"]            = Path.GetExtension(attach.ExportFilePath).Replace(".", "");
            data["encryption_cipher_text"]    = "";
            data["encryption_applied"]        = "0";
            data["encryption_blob_encrypted"] = "0";
            data["size"]                      = new FileInfo(attach.ExportFilePath).Length.ToString();
            data["is_shared"]                 = "0";
            data["type_"]                     = "4";

            foreach (var metadata in data)
            {
                sb.Append($"\n{metadata.Key}: {metadata.Value}");
            }

            return(sb.ToString());
        }
Example #2
0
        internal void SyncAttachments(Attachements item)
        {
            AttachmentsEntity ent = new AttachmentsEntity()
            {
                AttachementId = Convert.ToInt32(item.AttachementId),
                Bezeichnung   = item.Bezeichnung,
                Filename      = item.Filename,
                HauspaketId   = Convert.ToInt32(item.HauspaketId),
                Mimetype      = item.Mimetype,
                Size          = Convert.ToInt32(item.Size)
            };

            switch (item.SyncOperation)
            {
            case "INSERT":
            {
                dataHandler.InsertAttachements(ent);
            }
            break;

            case "UPDATE":
            {
                dataHandler.UpdateAttachements(ent);
            }
            break;

            case "DELETE":
            {
                dataHandler.DeleteAttachements(ent);
            }
            break;
            }
        }
Example #3
0
 protected override void Pack(Packer packer)
 {
     base.Pack(packer);
     packer.Pack(AccountId);
     packer.Pack(ChainId);
     packer.Pack(ChainIndex);
     packer.Pack(KeyIndex);
     Attachements.Pack(packer);
 }
Example #4
0
 public ClientAttachementsRequestMessage(Attachements attachements, short keyIndex, Key accountKey) : this()
 {
     SetRequestCode();
     Attachements = new SignedData <Attachements>(attachements, accountKey);
     KeyIndex     = keyIndex;
     AccountId    = attachements.AccountId;
     ChainId      = attachements.ChainId;
     ChainIndex   = attachements.ChainIndex;
 }
Example #5
0
 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
     if (SelectedItem != null)
     {
         var it = SelectedItem;
         Attachements.Remove(it);
         GAPPSF.Attachement.Manager.Instance.DeleteAttachement(it);
     }
 }
        public string ConsumerScore(string xdsUrl, string cherwellUrl, string cmsUsrName, string cmsUsrPwd,
                                    string xdsUsrName, string xdsUsrPw, string reason, string idNo, string dob, string passportNumber,
                                    string reference, string ticket, string firstName, string lastname,
                                    string productionId, bool attachXml, bool attachPdf, string recId)
        {
            _webService.Url = XdsUrl;
            var myMatch = _webService.ConnectConsumerMatch(ticket, reason, int.Parse(productionId), idNo,
                                                           passportNumber,
                                                           firstName, lastname, dob, reference, string.Empty);

            _enquiryId       = int.Parse(XmlReaders.FindXmlValue(myMatch, "EnquiryID"));
            _enquiryResultId = int.Parse(XmlReaders.FindXmlValue(myMatch, "EnquiryResultID"));

            var xdsResult = _webService.ConnectGetResult(ticket, _enquiryId, _enquiryResultId, int.Parse(productionId),
                                                         string.Empty);

            var attachments = new Attachements();

            if (attachXml)
            {
                attachments.AttachXml(CherwellUrl, cmsUsrName, cmsUsrPwd, recId, xdsResult);
            }

            if (attachPdf)
            {
                attachments.AttachPdf(CherwellUrl, cmsUsrName, cmsUsrPwd, recId, ticket, productionId, _enquiryId, _enquiryResultId);
            }

            var results = new Results
            {
                Score           = XmlReaders.FindXmlValue(xdsResult, "FinalScore"),
                EnquiryID       = _enquiryId.ToString(),
                EnquiryResultID = _enquiryResultId.ToString(),
                Judgements      = XmlReaders.FindJudgements(xdsResult, "JudgmentsCount").ToString()
            };
            var           sw = new StringWriter();
            XmlTextWriter tw = null;

            try
            {
                var serializer = new XmlSerializer(results.GetType());
                tw = new XmlTextWriter(sw);
                serializer.Serialize(tw, results);
            }
            catch (Exception)
            {
                //Handle Exception Code
            }
            finally
            {
                sw.Close();
                tw?.Close();
            }

            return(sw.ToString());
        }
Example #7
0
        public void AddAttachement()
        {
            Attachement attachement = new Attachement();

            attachement.name = "default";
            AttachementViewModel vm = new AttachementViewModel(attachement);

            Attachements.Add(vm);
            _manager.attachements.Add(attachement);
        }
        /// <summary>
        /// Replace PanDoc IMG HTML tag by markdown reference and copy image file into notebook export directory
        /// </summary>
        /// <param name="page">Section page</param>
        /// <param name="mdFileContent">Contennt of the MD file</param>
        /// <param name="resourceFolderPath">The path to the notebook folder where store attachments</param>
        /// <param name="sectionTreeLevel">Level in the page hierarchy of one note, to indent the page title in Joplin</param>
        /// <returns></returns>
        public string ExtractImagesToResourceFolder(Page page, string mdFileContent, string resourceFolderPath, string mdFilePath, bool joplinResourceRef, bool postProcessingMdImgRef)
        {
            // Search of <IMG> tags
            var pageTxtModified = mdFileContent;

            if (postProcessingMdImgRef)
            {
                pageTxtModified = Regex.Replace(mdFileContent, "<img [^>]+/>", delegate(Match match)
                {
                    // Process an <IMG> tag

                    string imageTag = match.ToString();

                    // http://regexstorm.net/tester
                    string regexImgAttributes = "<img src=\"(?<src>[^\"]+)\".* />";

                    MatchCollection matchs = Regex.Matches(imageTag, regexImgAttributes, RegexOptions.IgnoreCase);
                    Match imgMatch         = matchs[0];

                    var padDocImgPath = imgMatch.Groups["src"].Value;

                    var imgAttach = page.ImageAttachements.Where(img => img.PanDocFilePath == padDocImgPath).FirstOrDefault();

                    if (imgAttach == null)
                    {
                        // Add a new attachmeent to current page
                        imgAttach = new Attachements(page)
                        {
                            Type           = AttachementType.Image,
                            PanDocFilePath = padDocImgPath,
                        };

                        imgAttach.ExportFileName = imgAttach.Id + Path.GetExtension(padDocImgPath);
                        imgAttach.ExportFilePath = Path.Combine(resourceFolderPath, imgAttach.ExportFileName);

                        page.Attachements.Add(imgAttach);
                    }

                    var attachRef = joplinResourceRef ?
                                    $":/{imgAttach.Id}" :
                                    GetImgMdReference(Path.GetRelativePath(Path.GetDirectoryName(mdFilePath), resourceFolderPath), imgAttach.ExportFileName);

                    return($"![{imgAttach.Id}]({attachRef})");
                });
            }

            // Move attachements file into output ressource folder and delete tmp file
            foreach (var attach in page.ImageAttachements)
            {
                File.Copy(attach.PanDocFilePath, attach.ExportFilePath);
                File.Delete(attach.PanDocFilePath);
            }

            return(pageTxtModified);
        }
Example #9
0
 private void UpdateView()
 {
     Attachements.Clear();
     if (Core.ApplicationData.Instance.ActiveGeocache != null)
     {
         List <GAPPSF.Attachement.Item> its = GAPPSF.Attachement.Manager.Instance.GetAttachements(Core.ApplicationData.Instance.ActiveGeocache.Code);
         foreach (var it in its)
         {
             Attachements.Add(it);
         }
     }
 }
Example #10
0
 private void newDialog_DialogClosed(object sender, EventArgs e)
 {
     inputDialog.DialogClosed -= newDialog_DialogClosed;
     if (inputDialog.DialogResult)
     {
         string s = inputDialog.InputText.Trim();
         if (_editingForComments != null)
         {
             _editingForComments.Comment = s;
             GAPPSF.Attachement.Manager.Instance.AddAttachement(_editingForComments);
             Attachements.Add(_editingForComments);
             SelectedItem = _editingForComments;
         }
     }
     _editingForComments = null;
 }
        private static void ProcessPageAttachments(XNamespace ns, Page page, XElement xmlPageContent)
        {
            foreach (var xmlInsertedFile in xmlPageContent.Descendants(ns + "InsertedFile"))
            {
                var fileAttachment = new Attachements(page)
                {
                    OneNoteFilePath           = xmlInsertedFile.Attribute("pathCache")?.Value,
                    OneNoteFileSourceFilePath = xmlInsertedFile.Attribute("pathSource")?.Value,
                    FriendlyFileName          = xmlInsertedFile.Attribute("preferredName")?.Value,
                    Type = AttachementType.File
                };

                if (fileAttachment.OneNoteFilePath != null)
                {
                    page.Attachements.Add(fileAttachment);
                }
            }
        }
Example #12
0
        private static string InsertMdFileAttachReferences(string pageMdFileContent, Attachements attach)
        {
            var pageMdFileContentModified = Regex.Replace(pageMdFileContent, "(&lt;){2}(?<fileName>.*)(&gt;){2}", delegate(Match match)
            {
                string refFileName            = match.Groups["fileName"]?.Value ?? "";
                string attachOriginalFileName = Path.GetFileName(attach.OneNoteFileSourceFilePath);

                if (refFileName.Equals(attachOriginalFileName))
                {
                    // reference found is corresponding to the attachment being processed
                    return($"[{attachOriginalFileName}](:/{attach.Id})");
                }
                else
                {
                    // not the current attachmeent, ignore
                    return(match.Value);
                }
            });

            return(pageMdFileContentModified);
        }
Example #13
0
 public Task <HeleusClientResponse> UploadAttachements(Attachements attachements, Action <AttachementDataTransaction> setupCallback)
 {
     return(UploadDataAttachements(attachements, CurrentServiceAccount, setupCallback));
 }
Example #14
0
        // 3 steps: Send UploadRequestMessage, Upload actual data, send transaction
        protected async Task <HeleusClientResponse> UploadDataAttachements(Attachements attachements, KeyStore clientAccount, Action <AttachementDataTransaction> setupCallback)
        {
            if (!await SetTargetChain(attachements.ChainId))
            {
                return(new HeleusClientResponse(HeleusClientResultTypes.EndpointConnectionError));
            }

            var uploadRequest = new ClientAttachementsRequestMessage(attachements, clientAccount.KeyIndex, clientAccount.DecryptedKey);

            Log.Trace($"UploadAttachements: Sending message {uploadRequest.MessageType}.", this);

            var sent = await SendMessage(attachements.AccountId, uploadRequest);

            if (!sent)
            {
                return(new HeleusClientResponse(HeleusClientResultTypes.ConnectionFailed));
            }

            var uploadResponse = await WaitResponse(uploadRequest) as ClientAttachementsResponseMessage;

            if (uploadResponse == null || uploadResponse.ResultType != TransactionResultTypes.Ok)
            {
                if (uploadResponse == null)
                {
                    return(new HeleusClientResponse(HeleusClientResultTypes.EndpointConnectionError));
                }

                Log.Trace($"UploadAttachements: Upload failed {uploadResponse.ResultType}.", this);
                return(new HeleusClientResponse(HeleusClientResultTypes.Ok, uploadResponse.ResultType, uploadResponse.UserCode));
            }

            try
            {
                using (var client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(120);
                    using (var content = new MultipartFormDataContent())
                    {
                        //var length = 0;
                        foreach (var att in attachements.Items)
                        {
                            var data = att.GetData();
                            //length += data.Length;
                            content.Add(new ByteArrayContent(data)
                            {
                                Headers = { ContentLength = data.Length }
                            }, "files", att.Name);
                        }

                        //content.Headers.ContentLength = length;
                        content.Headers.Add("X-Attachements", Convert.ToBase64String(attachements.ToByteArray()));
                        var responseMessage = await client.PostAsync($"{ChainEndPoint.AbsoluteUri}dynamic/datachain/{attachements.ChainId}/{attachements.ChainIndex}/attachements/{uploadResponse.AttachementKey}/upload/", content);

                        var responseText = await responseMessage.Content.ReadAsStringAsync();

                        if (responseMessage.StatusCode != System.Net.HttpStatusCode.OK)
                        {
                            try
                            {
                                var results  = responseText.Split(',');
                                var result   = (TransactionResultTypes)(int.Parse(results[0]));
                                var userCode = long.Parse(results[1]);

                                Log.Trace($"UploadAttachements: Uploaded ({result}, UserCode: {userCode}).", this);

                                return(new HeleusClientResponse(HeleusClientResultTypes.Ok, result, userCode));
                            }
                            catch (Exception ex)
                            {
                                Log.HandleException(ex, this);
                                return(new HeleusClientResponse(HeleusClientResultTypes.InternalError, 0));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.IgnoreException(ex, this);
                return(new HeleusClientResponse(HeleusClientResultTypes.Timeout, 0));
            }

            var transaction = new AttachementDataTransaction(attachements, uploadResponse.AttachementKey);

            setupCallback?.Invoke(transaction);

            return(await SendDataTransaction(transaction, true, clientAccount));
        }
        public async Task <IActionResult> AttachementsUpload(int chainid, long chainIndex, int attachementkey, List <IFormFile> files)
        {
            var userCode = 0L;

            Attachements attachements = null;

            try
            {
                Request.Headers.TryGetValue("X-Attachements", out var attachementsHeader);
                var attachementsData = Convert.FromBase64String(attachementsHeader.ToString());
                attachements = new Attachements(new Unpacker(attachementsData));
            }
            catch (Exception ex)
            {
                Log.IgnoreException(ex, this);
            }

            if (attachements == null || attachements.Items.Count != files.Count || attachements.ChainId != chainid || attachements.ChainIndex != (uint)chainIndex)
            {
                return(BadRequest(GetResultCode(TransactionResultTypes.AttachementsInvalid, userCode)));
            }

            var attachementManager = _node.AttachementManager;
            var info = attachementManager.GetAttachementInfo(attachements.ChainId, attachements.ChainIndex, attachements.Token);

            if (info == null || !info.IsValid(attachements) || info.Expired || info.State != AttachementInfoState.Requested)
            {
                return(BadRequest(GetResultCode(TransactionResultTypes.AttachementsInvalid, userCode)));
            }

            info.SetState(AttachementInfoState.Uploading);

            try
            {
                var tempFiles = new List <AttachementTempFile>();
                foreach (var formFile in files)
                {
                    if (formFile.Length > 0)
                    {
                        var stream = formFile.OpenReadStream();
                        var item   = info.GetAttachementItem(formFile.FileName);

                        if (stream != null && item != null)
                        {
                            tempFiles.Add(new AttachementTempFile(item, stream));
                        }
                    }
                }

                if (tempFiles.Count == info.Attachements.Items.Count)
                {
                    var copyResult = await attachementManager.CheckAndCacheAttachements(info, tempFiles);

                    userCode = copyResult.UserCode;

                    if (copyResult.Result == TransactionResultTypes.Ok)
                    {
                        info.SetState(AttachementInfoState.Uploaded);
                        return(Ok(GetResultCode(TransactionResultTypes.Ok, userCode)));
                    }

                    info.SetState(AttachementInfoState.Requested);
                    return(BadRequest(GetResultCode(TransactionResultTypes.ChainServiceErrorResponse, userCode)));
                }
            }
            catch (Exception ex)
            {
                Log.IgnoreException(ex, this);
            }

            info.SetState(AttachementInfoState.Requested);
            return(BadRequest(GetResultCode(TransactionResultTypes.AttachementsUploadFailed, userCode)));
        }
Example #16
0
 public void RemoveAttachement(AttachementViewModel attachement)
 {
     Attachements.Remove(attachement);
     _manager.attachements.Remove(attachement.Model);
 }