示例#1
0
        public static GeneratedModel Create(CodeGenerationOptions options)
        {
            GeneratedModel model = new GeneratedModel();

            foreach (var kind in options.Kinds)
            {
                //if (kind == Kind.Context || kind == Kind.Supervisor)
                //    continue;

                GeneratedFile modelClassFile          = FileFactory.Create(options, FileType.ModelClass, kind);
                GeneratedFile generatorInterfaceFile  = FileFactory.Create(options, FileType.GeneratorInterface, kind);
                GeneratedFile generatorClassFile      = FileFactory.Create(options, FileType.GeneratorClass, kind);
                GeneratedFile scaffolderInterfaceFile = FileFactory.Create(options, FileType.ScaffolderInterface, kind);
                GeneratedFile scaffolderClassFile     = FileFactory.Create(options, FileType.ScaffolderClass, kind);

                model.Models.Add(modelClassFile);
                model.GeneratorInterfaces.Add(generatorInterfaceFile);
                model.GeneratorClasses.Add(generatorClassFile);
                model.ScaffolderInterfaces.Add(scaffolderInterfaceFile);
                model.ScaffolderClasses.Add(scaffolderClassFile);
            }

            model.ScaffoldedModelClass = FileFactory.Create(options, FileType.ScaffoldedModelClass);
            model.ServicesClassFile    = FileFactory.Create(options, FileType.ServicesClass);
            //model.SupervisorClass = FileFactory.Create(options, FileType.SupervisorClass);
            //model.SupervisorModelClass = FileFactory.Create(options, FileType.SupervisorModelClass);
            //model.SupervisorInterface = FileFactory.Create(options, FileType.SupervisorInterface);
            //model.ContextClass = FileFactory.Create(options, FileType.ContextClass);
            //model.ContextInterface = FileFactory.Create(options, FileType.ContextInterface);
            //model.ContextModelClass = FileFactory.Create(options, FileType.ContextModelClass);
            return(model);
        }
示例#2
0
        public void WillOverwriteExistingFileWhenContentHasChanged()
        {
            var generatedFileOriginal = new GeneratedFile("Original Content", "GeneratedFileWriterTests2.cs", TestEnvironment.TempPath);
            var generatedFileChanged  = new GeneratedFile("Changed Content", "GeneratedFileWriterTests2.cs", TestEnvironment.TempPath);

            try
            {
                var writer = new GeneratedFileWriter();

                writer.WriteFile(generatedFileOriginal);
                var originalTimeStamp = new FileInfo(generatedFileOriginal.GetFullPath()).LastWriteTime.Ticks;

                Thread.Sleep(100);

                writer.WriteFile(generatedFileChanged);
                var newTimestamp = new FileInfo(generatedFileChanged.GetFullPath()).LastWriteTime.Ticks;

                Assert.True(newTimestamp > originalTimeStamp);
            }
            finally
            {
                if (File.Exists(generatedFileOriginal.GetFullPath()))
                {
                    File.Delete(generatedFileOriginal.GetFullPath());
                }
            }
        }
示例#3
0
        public static GeneratedFile Create(CodeGenerationOptions options, FileType type, Kind kind = Kind.None)
        {
            GeneratedFile file = new GeneratedFile();

            file.Path = FilePathHelper.GetFilePath(options.OutputDir, type, kind);
            file.Code = CodeGenerator.Generate(options, type, kind);
            return(file);
        }
示例#4
0
 protected static void CompareModel(
     string fileName,
     string expected,
     GeneratedFile result,
     string subdirectory = "Model")
 {
     Assert.Equal(Path.Combine(subdirectory, fileName), result.Path);
     Assert.Equal(expected, result.Content, ignoreLineEndingDifferences: true);
 }
示例#5
0
        public override void PublishesCsprojGenerated()
        {
            var fileArg = new GeneratedFile(new FileInfo(this.testArgs.CsprojPath), this.testArgs.CsprojContent);

            Assert.That(
                () => this.publisher.PublishCsprojGenerated(this.testArgs.CsprojPath, this.testArgs.CsprojContent),
                Does.RaiseWith <IGeneratedFile>(_ => this.publisher.CsprojGenerated += _)
                .WithArgThat(Is.EqualTo(fileArg).Using(new GeneratedFileEqualityComparer())));
        }
示例#6
0
        public static bool ExistsOnDiskWithSameContent(this GeneratedFile generatedFile)
        {
            if (!File.Exists(generatedFile.GetFullPath()))
            {
                return(false);
            }
            var existingFileText = File.ReadAllText(generatedFile.GetFullPath());

            return(generatedFile.GeneratedCode.Equals(existingFileText));
        }
示例#7
0
        private static void WriteFile(string codegenOutputFolder, GeneratedFile file)
        {
            var generatedFilePath      = Path.Combine(codegenOutputFolder, file.RelativeFilePath);
            var generatedFileDirectory = Path.GetDirectoryName(generatedFilePath);

            if (!Directory.Exists(generatedFileDirectory))
            {
                Directory.CreateDirectory(generatedFileDirectory);
            }

            File.WriteAllText(generatedFilePath, file.Contents, Encoding.UTF8);
        }
 public bool Equals(GeneratedFile obj)
 {
     if (ReferenceEquals(null, obj))
     {
         return(false);
     }
     if (ReferenceEquals(this, obj))
     {
         return(true);
     }
     return(Equals(obj._RawFilename, _RawFilename) && Equals(obj._Filename, _Filename) && Equals(obj._RelativePath, _RelativePath) && Equals(obj._ScriptName, _ScriptName) && Equals(obj._IteratorTypeName, _IteratorTypeName));
 }
示例#9
0
        public static bool ExistsOnDiskWithSameContent(this GeneratedFile generatedFile)
        {
            if (!File.Exists(generatedFile.GetFullPath()))
            {
                return(false);
            }

            var newHash      = Sha3.CalculateHash(generatedFile.GeneratedCode);
            var existingHash = Sha3.CalculateHash(File.ReadAllText(generatedFile.GetFullPath()));

            return(newHash == existingHash);
        }
示例#10
0
        public static void WriteFileToDisk(GeneratedFile generatedFile)
        {
            //soft handling empty code
            if (!string.IsNullOrEmpty(generatedFile.GeneratedCode))
            {
                if (!Directory.Exists(generatedFile.OutputFolder))
                {
                    Directory.CreateDirectory(generatedFile.OutputFolder);
                }

                using (var file = File.CreateText(Path.Combine(generatedFile.OutputFolder, generatedFile.FileName)))
                {
                    file.Write(generatedFile.GeneratedCode);
                    file.Flush();
                }
            }
        }
示例#11
0
        public void WillNotOutputAnEmptyFile(string content)
        {
            var generatedFile = new GeneratedFile(content, "GeneratedFileWriterTests3.cs", TestEnvironment.TempPath);

            try
            {
                var writer = new GeneratedFileWriter();
                writer.WriteFile(generatedFile);
                Assert.False(File.Exists(generatedFile.GetFullPath()));
            }
            finally
            {
                if (File.Exists(generatedFile.GetFullPath()))
                {
                    File.Delete(generatedFile.GetFullPath());
                }
            }
        }
        public void OutBoundInvoices(List <Message> msgs)
        {
            var invoicesReq = msgs.Where(x => x.Entities[0].AttachmentType == AttachmentType.Invoice);

            foreach (var msg in invoicesReq)
            {
                Entity invoice = msg.Entities.FirstOrDefault(i => i.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.Invoice &&
                                                             i.DocumentInfo.RevocationStatus == RevocationStatus.RevocationStatusNone);
                if (invoice == null)
                {
                    continue;
                }
                Entity invoiceReciept = msg.Entities.FirstOrDefault(i => i.ParentEntityId == invoice.EntityId &&
                                                                    i.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.InvoiceConfirmation);

                GeneratedFile invoiceReceipt = api.GenerateInvoiceDocumentReceiptXml(
                    token,
                    box.BoxId,
                    invoice.DocumentInfo.MessageId,
                    invoiceReciept.EntityId,
                    signers.First());

                SignedContent signContentInvoiceReciept = new SignedContent();
                signContentInvoiceReciept.Content = invoiceReceipt.Content;
                signContentInvoiceReciept.SignWithTestSignature = true;

                ReceiptAttachment receiptInvoice = new ReceiptAttachment {
                    ParentEntityId = invoiceReciept.EntityId,
                    SignedContent  = signContentInvoiceReciept
                };

                var patch = new MessagePatchToPost {
                    BoxId     = box.BoxId,
                    MessageId = invoice.DocumentInfo.MessageId
                };
                patch.AddReceipt(receiptInvoice);

                api.PostMessagePatch(token, patch);

                Thread.Sleep(1000);
            }
        }
        public static GeneratedFile ShouldContainXml([NotNull] this GeneratedFile result, string expectedXml)
        {
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }
            if (expectedXml == null)
            {
                throw new ArgumentNullException(nameof(expectedXml));
            }

            if (!File.Exists(result.FullPath))
            {
                throw new SpecificationException($"Could not check file contents for configuration {result.ConfigurationName} as the expected file did not exist: {result.FullPath}");
            }

            File.ReadAllText(result.FullPath).ShouldContainXml(expectedXml);

            return(result);
        }
        public static GeneratedFile ShouldHaveEncoding([NotNull] this GeneratedFile result, [NotNull] Encoding expectedEncoding)
        {
            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }
            if (expectedEncoding == null)
            {
                throw new ArgumentNullException(nameof(expectedEncoding));
            }

            var actual = TextEncodingDetector.GetEncoding(result.FullPath);

            if (actual != expectedEncoding)
            {
                throw new SpecificationException($"Incorrect encoding for configuration '{result.ConfigurationName}'. Expected {expectedEncoding}, but was {actual}.");
            }

            return(result);
        }
示例#15
0
        public async Task Save()
        {
            try {
                BeginAction();
                var patch = Payload.Patch();

                RevocationRequestInfo revinfo = new RevocationRequestInfo();
                revinfo.Comment = Comment.Value;
                revinfo.Signer  = GetSigner();

                GeneratedFile revocationXml = await Async((x) => Payload.Api.GenerateRevocationRequestXml(
                                                              x,
                                                              Payload.BoxId,
                                                              Payload.Message.MessageId,
                                                              Payload.Entity.EntityId,
                                                              revinfo));

                SignedContent revocSignContent = new SignedContent();
                revocSignContent.Content = revocationXml.Content;

                if (!TrySign(revocSignContent))
                {
                    throw new Exception("Ошибка подписи документа TrySign");
                }

                RevocationRequestAttachment revattch = new RevocationRequestAttachment();
                revattch.ParentEntityId = Payload.Entity.EntityId;
                revattch.SignedContent  = revocSignContent;

                patch.AddRevocationRequestAttachment(revattch);
                await Async(x => Payload.Api.PostMessagePatch(x, patch));
                await EndAction();
            }
            catch (Exception e) {
                var error = ErrorHelper.TranslateException(e)
                            ?? "Не удалось выполнить операцию, попробуйте повторить позднее.";
                Manager.Warning(error);
                Log.Error(error, e);
                await EndAction(false);
            }
        }
示例#16
0
        public void WillNotOverwriteExistingFileIfContentIsUnChanged()
        {
            const string content       = @"
using System;

namespace Tests;
public class Class1 
{
    public string Func1() 
    {
        return ""Hello"";
    }
}
";
            var          generatedFile = new GeneratedFile(content, "GeneratedFileWriterTests1.cs", TestEnvironment.TempPath);

            try
            {
                var writer = new GeneratedFileWriter();

                writer.WriteFile(generatedFile);
                var creationTimestamp = new FileInfo(generatedFile.GetFullPath()).LastWriteTime.Ticks;

                Thread.Sleep(100);

                writer.WriteFile(generatedFile);
                var lastUpdateTimestamp = new FileInfo(generatedFile.GetFullPath()).LastWriteTime.Ticks;

                Assert.Equal(creationTimestamp, lastUpdateTimestamp);
            }
            finally
            {
                if (File.Exists(generatedFile.GetFullPath()))
                {
                    File.Delete(generatedFile.GetFullPath());
                }
            }
        }
        /// <summary>
        /// Generates a T-SQL code file (.sql) containing queries for GetByKey, GetAll, Insert, Update, and Delete operations.
        /// </summary>
        /// <param name="tableSpecification">The table specification upon which to base the generated queries.</param>
        /// <returns>A GeneratedFile of type TSql.</returns>
        public GeneratedFile GenerateFile(TableSpecification tableSpecification)
        {
            var keyColumn = FindKeyColumn(tableSpecification);

            var getById = BuildGetByKeyStatement(tableSpecification, keyColumn);

            var getAll = BuildGetAllStatement(tableSpecification);

            var insert = BuildInsertStatement(tableSpecification);

            var update = BuildUpdateStatement(tableSpecification, keyColumn);

            var delete = BuildDeleteStatement(tableSpecification, keyColumn);

            var result = new GeneratedFile
            {
                FileName     = tableSpecification.TableName + ".sql",
                FileContents = string.Format(TemplateLibrary.TSql.QueryFile, getById, getAll, insert, update, delete),
                FileType     = OutputFileType
            };

            return(result);
        }
        public void Revocation(Message revocation)
        {
            RevocationRequestInfo revinfo = new RevocationRequestInfo();

            revinfo.Comment = "АННУЛИРОВНИЕ";
            revinfo.Signer  = signers.First();

            var document = revocation.Entities.First();

            MessagePatchToPost patch = new MessagePatchToPost()
            {
                BoxId     = box.BoxId,
                MessageId = revocation.MessageId
            };

            GeneratedFile revocationXml = api.GenerateRevocationRequestXml(
                token,
                box.BoxId,
                revocation.MessageId,
                document.EntityId,
                revinfo);

            SignedContent revocSignContent = new SignedContent();

            revocSignContent.Content = revocationXml.Content;
            revocSignContent.SignWithTestSignature = true;

            RevocationRequestAttachment revattch = new RevocationRequestAttachment();

            revattch.ParentEntityId = document.EntityId;
            revattch.SignedContent  = revocSignContent;

            patch.AddRevocationRequestAttachment(revattch);

            api.PostMessagePatch(token, patch);
        }
        public static void WriteFileToDisk(GeneratedFile generatedFile)
        {
            //soft handling empty code
            if (string.IsNullOrWhiteSpace(generatedFile.GeneratedCode))
            {
                return;
            }

            if (!Directory.Exists(generatedFile.OutputFolder))
            {
                Directory.CreateDirectory(generatedFile.OutputFolder);
            }

            if (generatedFile.ExistsOnDiskWithSameContent())
            {
                return;
            }

            using (var file = File.CreateText(generatedFile.GetFullPath()))
            {
                file.Write(generatedFile.GeneratedCode);
                file.Flush();
            }
        }
 public static GeneratedFile ShouldHaveExtension([NotNull] this GeneratedFile result, [NotNull] string expectedExtension)
 {
     return(ShouldHaveExtension(new[] { result }, expectedExtension).FirstOrDefault());
 }
        /// <summary>
        /// Generates a C# code file (.cs) containing a class definition matching the given table specification.
        /// </summary>
        /// <param name="tableSpecification">The table specification upon which to base the C# class file.</param>
        /// <returns>A GeneratedFile of type CSharp.</returns>
        public GeneratedFile GenerateFile(TableSpecification tableSpecification)
        {
            tableSpecification.TableName = RemoveInvalidCharacters(tableSpecification.TableName);

            var properties = new StringBuilder();

            var addXmlNameSpace     = false;
            var addSqlTypeNameSpace = false;

            foreach (var col in tableSpecification.ColumnSpecifications)
            {
                col.ColumnName = RemoveInvalidCharacters(col.ColumnName);

                if (properties.Length > 0)
                {
                    properties.Append("\n\n\t\t");
                }

                properties.Append(BuildPropertyString(col, tableSpecification.TableOrigin));

                // There are using statements that potentially need to be added for certain SQL Server column types.
                if (tableSpecification.TableOrigin == SpecificationProvider.SqlServer)
                {
                    if (!addXmlNameSpace && (SqlServerColumnType)col.ColumnType == SqlServerColumnType.Xml)
                    {
                        addXmlNameSpace = true;
                    }

                    if (!addSqlTypeNameSpace &&
                        ((SqlServerColumnType)col.ColumnType == SqlServerColumnType.HierarchyId ||
                         (SqlServerColumnType)col.ColumnType == SqlServerColumnType.Geometry ||
                         (SqlServerColumnType)col.ColumnType == SqlServerColumnType.Geography))
                    {
                        addSqlTypeNameSpace = true;
                    }
                }
            }

            var usings = new StringBuilder();

            _usingStatements.ForEach(u => { if (usings.Length > 0)
                                            {
                                                usings.Append("\n");
                                            }
                                            usings.Append(u); });

            if (addXmlNameSpace)
            {
                usings.Append("\nusing System.Linq.Xml;");
            }

            if (addSqlTypeNameSpace)
            {
                usings.Append("\nusing Microsoft.SqlServer.Types;");
            }

            if (AddAnnotations)
            {
                usings.Append("\nusing System.ComponentModel.DataAnnotations;");
            }

            var result = new GeneratedFile
            {
                FileName     = tableSpecification.TableName + ".cs",
                FileContents = string.Format(TemplateLibrary.CSharp.ClassFile, usings.ToString(), ModelNameSpace, tableSpecification.TableName, properties.ToString()),
                FileType     = OutputFileType
            };

            return(result);
        }
示例#22
0
 public static string GetFullPath(this GeneratedFile generatedFile)
 {
     return(Path.Combine(generatedFile.OutputFolder, generatedFile.FileName));
 }
 public static IEnumerable <GeneratedFile> ShouldHaveFilename([NotNull] this GeneratedFile result, [NotNull] Func <string, string> fileName)
 {
     return(ShouldHaveFilename(new[] { result }, fileName));
 }
示例#24
0
 public void WriteFile(GeneratedFile generatedFile)
 {
     WriteFileToDisk(generatedFile);
 }
        public void Execute(ISession session)
        {
            api = new DiadocApi(/*ConfigurationManager.AppSettings["DiadokApi"]*/ "Analit-988b9e85-1b8e-40a9-b6bd-543790d0a7ec",
                                "https://diadoc-api.kontur.ru", new WinApiCrypt());
            token = api.Authenticate(ddkConfig.sender_login, ddkConfig.sender_passwd);

            box     = api.GetMyOrganizations(token).Organizations[0].Boxes[0];
            signers = new List <Signer>();
            var msgs = GetMessages();

            for (int i = 0; i < msgs.Item1.Count(); i++)
            {
                api.Delete(token, box.BoxId, msgs.Item2[i].MessageId, msgs.Item1[i].EntityId);
            }

            var msg = new MessageToPost();

            NonformalizedAttachment nfa = new NonformalizedAttachment();

            nfa.SignedContent         = new SignedContent();
            nfa.SignedContent.Content = Encoding.GetEncoding(1251).GetBytes("ТЕСТОВЫЙ НЕФОРМАЛИЗИРОВННЫЙ ДОКУМЕНТ");
            nfa.SignedContent.SignWithTestSignature = true;
            nfa.FileName = "НеформализированныйДокумент.txt";
            nfa.NeedRecipientSignature = true;
            nfa.DocumentDate           = DateTime.UtcNow.ToString("dd.MM.yyyy");
            nfa.DocumentNumber         = DateTime.UtcNow.Millisecond.ToString();

            msg.NonformalizedDocuments.Add(nfa);
            msg.NonformalizedDocuments.Add(nfa);
            msg.NonformalizedDocuments.Add(nfa);
            msg.NonformalizedDocuments.Add(nfa);
            msg.NonformalizedDocuments.Add(nfa);
            msg.NonformalizedDocuments.Add(nfa);
            msg.NonformalizedDocuments.Add(nfa);

            XmlDocumentAttachment sii = new XmlDocumentAttachment();

            byte[]      content = Encoding.GetEncoding(1251).GetBytes(DiadokFixtureData.InvoiceXml);
            byte[]      sign    = null;
            InvoiceInfo ii      = api.ParseInvoiceXml(content);

            signers.Add(ii.Signer);
            GeneratedFile iiFile = api.GenerateInvoiceXml(token, ii);

            sii.SignedContent = new SignedContent();
            sii.SignedContent.SignWithTestSignature = true;
            sii.SignedContent.Content   = iiFile.Content;
            sii.SignedContent.Signature = sign;

            msg.Invoices.Add(sii);
            msg.Invoices.Add(sii);
            msg.Invoices.Add(sii);
            msg.Invoices.Add(sii);
            msg.Invoices.Add(sii);
            msg.Invoices.Add(sii);
            msg.Invoices.Add(sii);
            msg.Invoices.Add(sii);

            XmlDocumentAttachment att12 = new XmlDocumentAttachment();

            content = Encoding.GetEncoding(1251).GetBytes(DiadokFixtureData.Torg12Xml);
            Torg12SellerTitleInfo tsti12 = api.ParseTorg12SellerTitleXml(content);

            signers.Add(tsti12.Signer);
            iiFile = api.GenerateTorg12XmlForSeller(token, tsti12, true);
            att12.SignedContent = new SignedContent();
            att12.SignedContent.SignWithTestSignature = true;
            att12.SignedContent.Content   = iiFile.Content;
            att12.SignedContent.Signature = sign;

            msg.AddXmlTorg12SellerTitle(att12);
            msg.AddXmlTorg12SellerTitle(att12);
            msg.AddXmlTorg12SellerTitle(att12);
            msg.AddXmlTorg12SellerTitle(att12);
            msg.AddXmlTorg12SellerTitle(att12);
            msg.AddXmlTorg12SellerTitle(att12);
            msg.AddXmlTorg12SellerTitle(att12);
            msg.AddXmlTorg12SellerTitle(att12);

            msg.FromBoxId = ddkConfig.sender_boxid;
            msg.ToBoxId   = ddkConfig.reciever_boxid;
            // пакет из трех
            api.PostMessage(token, msg);

            Thread.Sleep(TimeSpan.FromSeconds(3));

            msg.NonformalizedDocuments.Clear();
            msg.Invoices.Clear();
            msg.XmlTorg12SellerTitles.Clear();
            // инвойс
            msg.Invoices.Add(sii);
            api.PostMessage(token, msg);

            Thread.Sleep(TimeSpan.FromSeconds(3));

            msg.Invoices.Clear();
            msg.XmlTorg12SellerTitles.Clear();
            //  накладная
            msg.AddXmlTorg12SellerTitle(att12);
            api.PostMessage(token, msg);
        }
示例#26
0
        public async Task Save()
        {
            try {
                BeginAction();
                var patch = Payload.Patch();

                if (ReqRevocationSign)
                {
                    Entity revocreq = Payload.Message.Entities.FirstOrDefault(x =>
                                                                              x.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.RevocationRequest);
                    SignatureRejectionInfo signrejinfo = new SignatureRejectionInfo();
                    signrejinfo.Signer       = GetSigner();
                    signrejinfo.ErrorMessage = Comment.Value;
                    GeneratedFile revocRejectSign = await Async((x) => Payload.Api.GenerateSignatureRejectionXml(
                                                                    x,
                                                                    Payload.BoxId,
                                                                    Payload.Message.MessageId,
                                                                    revocreq.EntityId,
                                                                    signrejinfo));

                    XmlSignatureRejectionAttachment signrejattch = new XmlSignatureRejectionAttachment();
                    signrejattch.ParentEntityId = revocreq.EntityId;
                    SignedContent signcontent = new SignedContent();
                    signcontent.Content = revocRejectSign.Content;
                    if (!TrySign(signcontent))
                    {
                        throw new Exception("Ошибка подписи документа TrySign");
                    }
                    signrejattch.SignedContent = signcontent;
                    patch.AddXmlSignatureRejectionAttachment(signrejattch);
                }
                else
                {
                    var content = new SignedContent();
                    //комментарий должен быть всегда
                    if (!String.IsNullOrEmpty(Comment.Value))
                    {
                        content.Content = Encoding.UTF8.GetBytes(Comment.Value);
                    }
                    else
                    {
                        content.Content = Encoding.UTF8.GetBytes(" ");
                    }

                    if (!TrySign(content))
                    {
                        throw new Exception("Ошибка подписи документа TrySign");
                    }
                    patch.RequestedSignatureRejections.Add(new RequestedSignatureRejection {
                        ParentEntityId = Payload.Entity.EntityId,
                        SignedContent  = content
                    });
                }
                await Async(x => Payload.Api.PostMessagePatch(x, patch));
                await EndAction();
            }
            catch (Exception e) {
                var error = ErrorHelper.TranslateException(e)
                            ?? "Не удалось выполнить операцию, попробуйте повторить позднее.";
                Manager.Warning(error);
                Log.Error(error, e);
                await EndAction(false);
            }
        }
示例#27
0
 public bool Equals(GeneratedFile obj)
 {
     if (ReferenceEquals(null, obj)) return false;
     if (ReferenceEquals(this, obj)) return true;
     return Equals(obj._RawFilename, _RawFilename) && Equals(obj._Filename, _Filename) && Equals(obj._RelativePath, _RelativePath) && Equals(obj._ScriptName, _ScriptName) && Equals(obj._IteratorTypeName, _IteratorTypeName);
 }
示例#28
0
 public GeneratedType(GeneratedFile xaml, GeneratedFile cSharp)
 {
     Xaml   = xaml;
     CSharp = cSharp;
 }
示例#29
0
        public async Task Save()
        {
            try {
                BeginAction();
                MessagePatchToPost patch  = null;
                Signer             signer = GetSigner();
                if (ReqRevocationSign)
                {
                    Entity revocReq = Payload.Message.Entities.FirstOrDefault(x => x.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.RevocationRequest);
                    patch = Payload.Patch();
                    DocumentSignature acceptSignature = new DocumentSignature();
                    acceptSignature.IsApprovementSignature = true;
                    acceptSignature.ParentEntityId         = revocReq.EntityId;
                    byte[] sign = null;
                    if (!TrySign(revocReq.Content.Data, out sign))
                    {
                        throw new Exception("Ошибка подписи документа TrySign");
                    }
                    if (Settings.Value.DebugUseTestSign)
                    {
                        acceptSignature.SignWithTestSignature = true;
                    }
                    acceptSignature.Signature = sign;
                    patch.AddSignature(acceptSignature);
                    await Async(x => Payload.Api.PostMessagePatch(x, patch));
                }
                else
                {
                    if (Payload.Entity.AttachmentType == AttachmentType.Nonformalized)
                    {
                        patch = Payload.Patch();
                        byte[] sign = null;
                        if (!TrySign(Payload.Entity.Content.Data, out sign))
                        {
                            throw new Exception("Ошибка подписи документа TrySign");
                        }
                        var signature = new DocumentSignature {
                            ParentEntityId = Payload.Entity.EntityId,
                            Signature      = sign
                        };
                        if (Settings.Value.DebugUseTestSign)
                        {
                            signature.SignWithTestSignature = true;
                        }
                        patch.AddSignature(signature);
                        await Async(x => Payload.Api.PostMessagePatch(x, patch));
                    }
                    else if (Payload.Entity.AttachmentType == AttachmentType.XmlTorg12)
                    {
                        if (SaveData.Value)
                        {
                            SignTorg12Autosave autosave = new SignTorg12Autosave();
                            autosave.SignerJobTitle = RcvJobTitle.Value;
                            if (LikeReciever.Value)
                            {
                                autosave.LikeReciever = true;
                            }
                            else
                            {
                                autosave.AcptFirstName  = AcptFirstName.Value;
                                autosave.AcptSurename   = AcptSurename.Value;
                                autosave.AcptPatronimic = AcptPatronimic.Value;
                                autosave.AcptJobTitle   = AcptJobTitle.Value;
                            }
                            if (ByAttorney.Value)
                            {
                                autosave.ByAttorney      = true;
                                autosave.AtrNum          = AtrNum.Value;
                                autosave.AtrDate         = AtrDate.Value.Value;
                                autosave.AtrOrganization = AtrOrganization.Value;
                                autosave.AtrJobTitle     = AtrJobTitle.Value;
                                autosave.AtrSurename     = AtrSurename.Value;
                                autosave.AtrFirstName    = AtrFirstName.Value;
                                autosave.AtrPatronymic   = AtrPatronymic.Value;
                                autosave.AtrAddInfo      = AtrAddInfo.Value;
                            }
                            autosave.Comment = Comment.Value;
                            Session.Save(autosave);
                            for (int i = autosave_max - 1; i < SavedData.Value.Count; i++)
                            {
                                Session.Delete(SavedData.Value[i]);
                            }
                        }
                        Official recived  = GetRevicedOfficial();
                        Official accepted = GetAcceptetOfficial();
                        Attorney attorney = GetAttorney();

                        var inf = new Torg12BuyerTitleInfo()
                        {
                            ReceivedBy          = recived,                    //лицо, получившее груз signer
                            AcceptedBy          = accepted,                   //лицо, принявшее груз
                            Attorney            = attorney,
                            AdditionalInfo      = Comment,
                            ShipmentReceiptDate = RcvDate.Value.ToString("dd.MM.yyyy"),
                            Signer = signer
                        };

                        GeneratedFile torg12XmlForBuyer = await Async((x) => Payload.Api.GenerateTorg12XmlForBuyer(
                                                                          x,
                                                                          inf,
                                                                          Payload.BoxId,
                                                                          Payload.Entity.DocumentInfo.MessageId,
                                                                          Payload.Entity.DocumentInfo.EntityId));

                        SignedContent signContent = new SignedContent();
                        signContent.Content = torg12XmlForBuyer.Content;
                        if (!TrySign(signContent))
                        {
                            throw new Exception("Ошибка подписи документа TrySign");
                        }

                        ReceiptAttachment receipt = new ReceiptAttachment {
                            ParentEntityId = Payload.Entity.DocumentInfo.EntityId,
                            SignedContent  = signContent
                        };
                        patch = Payload.PatchTorg12(receipt);
                        await Async(x => Payload.Api.PostMessagePatch(x, patch));

                        Log.Info($"Документ {patch.MessageId} успешно подписан");
                    }
                    else if (Payload.Entity.AttachmentType == AttachmentType.Invoice)
                    {
                        Entity invoice = Payload.Message.Entities.First(i => i.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.Invoice);

                        GeneratedFile invoiceReceipt = await Async((x) => Payload.Api.GenerateInvoiceDocumentReceiptXml(
                                                                       x,
                                                                       Payload.BoxId,
                                                                       Payload.Entity.DocumentInfo.MessageId,
                                                                       invoice.EntityId,
                                                                       signer));

                        SignedContent signContentInvoiceReciept = new SignedContent();
                        signContentInvoiceReciept.Content = invoiceReceipt.Content;
                        if (!TrySign(signContentInvoiceReciept))
                        {
                            throw new Exception("Ошибка подписи документа TrySign");
                        }

                        ReceiptAttachment receiptInvoice = new ReceiptAttachment {
                            ParentEntityId = invoice.EntityId,
                            SignedContent  = signContentInvoiceReciept
                        };

                        Entity        invoiceConfirmation        = Payload.Message.Entities.OrderBy(x => x.CreationTime).First(i => i.AttachmentTypeValue == Diadoc.Api.Com.AttachmentType.InvoiceConfirmation);
                        GeneratedFile invoiceConfirmationReceipt = await Async((x) => Payload.Api.GenerateInvoiceDocumentReceiptXml(
                                                                                   x,
                                                                                   Payload.BoxId,
                                                                                   Payload.Entity.DocumentInfo.MessageId,
                                                                                   invoiceConfirmation.EntityId,
                                                                                   signer));

                        SignedContent signContentInvoiceConfirmationReciept = new SignedContent();
                        signContentInvoiceConfirmationReciept.Content = invoiceReceipt.Content;

                        if (!TrySign(signContentInvoiceConfirmationReciept))
                        {
                            throw new Exception("Ошибка подписи документа TrySign");
                        }

                        ReceiptAttachment invoiceConfirmationreceipt = new ReceiptAttachment {
                            ParentEntityId = invoiceConfirmation.EntityId,
                            SignedContent  = signContentInvoiceConfirmationReciept
                        };

                        patch = Payload.Patch(receiptInvoice, invoiceConfirmationreceipt);

                        await Async(x => Payload.Api.PostMessagePatch(x, patch));

                        Log.Info($"Документ {patch.MessageId} receiptInvoice, invoiceConfirmationreceipt отправлены");

                        Entity invoiceDateConfirmation = await Async((x) => {
                            Message msg        = null;
                            Entity dateConfirm = null;
                            int breaker        = 0;
                            do
                            {
                                msg = Payload.Api.GetMessage(Payload.Token,
                                                             Payload.BoxId,
                                                             Payload.Entity.DocumentInfo.MessageId,
                                                             Payload.Entity.EntityId);
                                dateConfirm = GetDateConfirmationStep7(msg);
                                breaker++;
                                TaskEx.Delay(500).Wait();
                            }while (dateConfirm == null && breaker < 10);
                            if (dateConfirm == null)
                            {
                                throw new TimeoutException("Превышено время ожидания ответа, попробуйте повторить позднее.");
                            }
                            LastPatchStamp = msg.LastPatchTimestamp;
                            return(dateConfirm);
                        });

                        GeneratedFile invoiceOperConfirmationReceipt = await Async((x) => Payload.Api.GenerateInvoiceDocumentReceiptXml(
                                                                                       x,
                                                                                       Payload.BoxId,
                                                                                       Payload.Entity.DocumentInfo.MessageId,
                                                                                       invoiceDateConfirmation.EntityId,
                                                                                       signer));

                        SignedContent signContentOperInvoiceConfrmReciept = new SignedContent();
                        signContentOperInvoiceConfrmReciept.Content = invoiceOperConfirmationReceipt.Content;

                        if (!TrySign(signContentOperInvoiceConfrmReciept))
                        {
                            throw new Exception("Ошибка подписи документа TrySign");
                        }

                        ReceiptAttachment receipt = new ReceiptAttachment {
                            ParentEntityId = invoiceDateConfirmation.EntityId,
                            SignedContent  = signContentOperInvoiceConfrmReciept
                        };
                        patch = Payload.Patch(receipt);
                        await Async(x => Payload.Api.PostMessagePatch(x, patch));

                        Log.Info($"Документ {patch.MessageId} invoiceDateConfirmation отправлен");
                    }
                }
                await EndAction();
            }
            catch (Exception e) {
                var error = ErrorHelper.TranslateException(e)
                            ?? "Не удалось выполнить операцию, попробуйте повторить позднее.";
                Manager.Warning(error);
                Log.Error(error, e);
                await EndAction(false);
            }
        }