예제 #1
0
        public void ReportPatternStats()
        {
            if (Engine.Transactions.Count() == 0)
            {
                Engine.MaxProfit = 0;
                Engine.MinProfit = 0;
            }
            string[] stats =
            {
                Symbol,
                Name,
                Interval,
                Retention.ToString(),
                Threshold.ToString(),
                DefaultStopLossThreshold.ToString(),
                DynamicStopLossThreshold.ToString(),
                (Engine.TradeResults.Sum()).ToString(),
                Engine.TradeResults.Count().ToString(),
                Engine.MaxProfit.ToString(),
                Engine.MinProfit.ToString(),
                Engine.FirstTransactionTime.ToString(),
                Engine.LastTransactionTime.ToString(),
            };
            string msg = string.Join(",", stats);

            logger.Stats(msg);
        }
예제 #2
0
        public async Task <IActionResult> PostContextAsync([FromBody] Retention param)
        {
            var retention = await Progress.Client.GetContextAsync(param.Code);

            var now = DateTime.Now;

            if (string.IsNullOrEmpty(retention.LastDate) == false && retention.LastDate.Substring(0, 6).Equals(now.ToString("yyMMdd")) ||
                string.IsNullOrEmpty(retention.Code) == false && retention.LastDate == null ||
                Progress.Company is 'X' && string.IsNullOrEmpty(retention.Code) == false && string.IsNullOrEmpty(retention.LastDate))
            {
                return(Ok());
            }

            try
            {
                if (retention.Code.Length == 6)
                {
                    if (Progress.Consensus.GrantAccess)
                    {
                        Queue <ConvertConsensus>   queue;
                        Queue <FinancialStatement> context = null;

                        for (int i = 0; i < retention.Code.Length / 3; i++)
                        {
                            queue = await Progress.Consensus.GetContextAsync(i, retention.Code);

                            int status = int.MinValue;

                            if (queue != null && queue.Count > 0)
                            {
                                status = await Progress.Client.PostContextAsync(queue);

                                if (i == 0)
                                {
                                    context = new Client.Summary(Progress.Key.Security).GetContext(retention.Code, now.Day);
                                }

                                if (i == 1 && context != null)
                                {
                                    status = await Progress.Client.PostContextAsync(context);
                                }
                            }
                            Base.SendMessage(retention.Code, status, GetType());
                        }
                    }
                    else if (await Progress.Client.GetContextAsync(new IncorporatedStocks {
                        Market = 'P'
                    }) is int next &&
                             await Progress.Client.PostContextAsync(new Client.IncorporatedStocks(Progress.Key.Security).OnReceiveSequentially(next)) != 0xC8)
                    {
                        Base.SendMessage(retention.Code, next, GetType());
                    }
                }
            }
            catch (Exception ex)
            {
                Base.SendMessage(ex.StackTrace, GetType());
            }
            return(Ok(retention));
        }
예제 #3
0
        public async Task <Retention> GetContext(Retention retention)
        {
            try
            {
                if (string.IsNullOrEmpty(retention.Code) == false)
                {
                    var response = await client.ExecuteAsync(new RestRequest(security.RequestCode(retention), Method.GET), source.Token);

                    if (response != null && response.RawBytes != null && response.RawBytes.Length > 0)
                    {
                        Coin += security.GetSettleTheFare(response.RawBytes.Length);
                        SendMessage(Coin);
                    }
                    return(JsonConvert.DeserializeObject <Retention>(response.Content));
                }
            }
            catch (Exception ex)
            {
                SendMessage(ex.StackTrace);
            }
            return(new Retention
            {
                Code = null,
                LastDate = null
            });
        }
예제 #4
0
        /// <summary>
        /// Generate a valuation request for a market and portfolio
        /// Include any scenarios requested
        /// </summary>
        /// <param name="portfolioId"></param>
        /// <param name="marketName"></param>
        /// <param name="baseParty"></param>
        /// <param name="irScenarios">Optional array of IR Stress Scenario names</param>
        /// <param name="fxScenarios">optional array of FX Stress Scenario names</param>
        /// <returns></returns>
        private static PortfolioValuationRequest CreateRequest(string portfolioId, string marketName, string baseParty, string[] irScenarios = null, string[] fxScenarios = null)
        {
            // create portfolio valuation request
            Guid requestId = Guid.NewGuid();
            var  request   = new PortfolioValuationRequest
            {
                BaseDate           = TestBaseDate,
                RequestId          = requestId.ToString(),
                Retention          = Retention.ToString(),
                SubmitTime         = DateTimeOffset.Now.ToString("o"),
                RequestDescription = "PV Regression Test",
                RequesterId        = new UserIdentity
                {
                    Name        = Engine.Cache.ClientInfo.Name,
                    DisplayName = "Unit Test Agent"
                },
                PortfolioId       = portfolioId,
                MarketDate        = null,
                MarketName        = marketName,
                ReportingCurrency = "AUD",
                BaseParty         = baseParty,
                IRScenarioNames   = irScenarios,
                FXScenarioNames   = fxScenarios
            };

            return(request);
        }
예제 #5
0
 public void ClearInstallTime()
 {
     if (LionKit.IsInitialized)
     {
         Retention.ClearInstallTime();
         UpdateInstallTime();
     }
 }
예제 #6
0
 public override int GetHashCode()
 {
     return(DB.GetHashCode() ^
            Retention.GetHashCode() ^
            DBUri.GetHashCode() ^
            Password.GetHashCode() ^
            User.GetHashCode());
 }
예제 #7
0
 public void ClearLastLoginTime()
 {
     if (LionKit.IsInitialized)
     {
         Retention.ClearLastLoginTime();
         UpdateLastLoginTime();
     }
 }
예제 #8
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        static async Task <Retention> ObjectReadRetention(S3Context ctx)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            Console.WriteLine("ObjectReadRetention: " + ctx.Request.Bucket + "/" + ctx.Request.Key);

            Retention ret = new Retention("GOVERNANCE", DateTime.Now.AddDays(100));

            return(ret);
        }
예제 #9
0
        private static void SelectProject(Retention releaseRetention)
        {
            Console.WriteLine("Enter project name e.g. 'Project-1' or 'Project-2'.");
            var projectName = Convert.ToString(Console.ReadLine());

            _selectedProject = releaseRetention.Projects.FirstOrDefault(x => x.Id == projectName);
            Console.WriteLine();
            Console.WriteLine();
        }
예제 #10
0
 /// <summary>
 /// Adds the options to the list.
 /// </summary>
 public virtual void AddToOptionList(OptionList options)
 {
     options.Clear();
     options["WritingMode"]   = WritingMode.ToString();
     options["WritingPeriod"] = WritingPeriod.ToString();
     options["WritingUnit"]   = WritingUnit.ToString();
     options["PullToPeriod"]  = PullToPeriod.ToString();
     options["Retention"]     = Retention.ToString();
     options["LogEnabled"]    = LogEnabled.ToLowerString();
 }
        public void ProjectSetup_PopulateWithTestData_TheCorrectNumberOfProjectsIsReturned()
        {
            //Arrange
            var projects = CreateTestData(out var environments, out var releases, out var deployments);

            //Act
            var results = new Retention(projects, environments, releases, deployments);

            //Assert
            Assert.AreEqual(projects.Count, results.Projects.Count);
        }
        public void InsertRetention(RetentionViewModel ovm)
        {
            Retention newRecord = new Retention
            {
                RET_Id                = ovm.Id,
                RET_BasedOnCode       = ovm.BasedOnCode,
                RET_BaseOnDescription = ovm.BaseOnDescription
            };

            context.Retentions.Add(newRecord);
            context.SaveChanges();
        }
예제 #13
0
        public TesterOutput()
        {
            retention          = new Retention();
            threshold          = new Threshold();
            defaultSLThreshold = new DefaultSLThreshold();
            dynamicSLThreshold = new DynamicSLThreshold();
            Patterns           = new Dictionary <string, bool>();

            Patterns.Add("TrendIncline", false);
            Patterns.Add("TrendShift", false);
            Patterns.Add("Spring", false);
            Patterns.Add("Streak", false);
        }
        public void DeleteRetention(RetentionViewModel ovm)
        {
            Retention newRecord = new Retention
            {
                RET_Id                = ovm.Id,
                RET_BasedOnCode       = ovm.BasedOnCode,
                RET_BaseOnDescription = ovm.BaseOnDescription
            };

            context.Retentions.Attach(newRecord);
            context.Retentions.Remove(newRecord);
            context.SaveChanges();
        }
        public void UpdateRetention(RetentionViewModel ovm)
        {
            Retention newRecord = new Retention
            {
                RET_Id                = ovm.Id,
                RET_BasedOnCode       = ovm.BasedOnCode,
                RET_BaseOnDescription = ovm.BaseOnDescription
            };

            context.Retentions.Attach(newRecord);
            context.Entry(newRecord).State = EntityState.Modified;
            context.SaveChanges();
        }
예제 #16
0
        static void Main(string[] args)
        {
            _projects     = ConstructTestData.GetProjectsData();
            _environments = ConstructTestData.GetEnvironmentsData();
            _releases     = ConstructTestData.GetReleasesData();
            _deployments  = ConstructTestData.GetDeploymentsData();

            var releaseRetention = new Retention(_projects, _environments, _releases, _deployments);

            MainMenu();

            bool quitNow = false;

            while (!quitNow)
            {
                switch (Console.ReadLine())
                {
                case "1":
                    SelectProject(releaseRetention);
                    MainMenu();
                    break;

                case "2":
                    DisplayProjectReleaseRetention();
                    MainMenu();
                    break;

                case "3":
                    UpdateReleaseRetention();
                    MainMenu();
                    break;

                case "4":
                    DisplayRetainedReleases();
                    MainMenu();
                    break;

                case "5":
                    ResetData();
                    MainMenu();
                    break;

                case "6":
                    Console.WriteLine($"Shutting down releas retention");
                    quitNow = true;
                    break;
                }
            }
        }
예제 #17
0
    public void UpdateLastLoginTime()
    {
        if (!LionKit.IsInitialized)
        {
            return;
        }
        if (lastLoginTimeText != null)
        {
            string time = Retention.GetLastLoginTime();
            if (string.IsNullOrEmpty(time))
            {
                time = new System.DateTime().ToString();
            }

            lastLoginTimeText.text = string.Format(loginTimePrefix, time);
        }
    }
예제 #18
0
        public bool KeepForever(BasicAuthentication authentication, string project, string buildNumber, bool keepForever, bool verbose = true)
        {
            var callSucceeded = false;

            try
            {
                var restHttpClient = new RestHttpClient();
                var url            = $"{authentication.AccountUrl}/{project}/_apis/build/builds?api-version=2.0&buildNumber={buildNumber}";

                // Call the Build API to obtain details for the specified build number
                var results = restHttpClient.GetAsync <CollectionResult <BuildResult> >(authentication, url);

                // Return false if no match was found
                callSucceeded = (results != null && results.Result != null && results.Result.Count > 0);

                if (callSucceeded)
                {
                    var buildId = results.Result.Value[0].id;

                    if (verbose)
                    {
                        Console.WriteLine($"Build Number {buildNumber} mapped to Build ID {buildId}");
                    }

                    // Now we need to make a PATCH call to set the retention accordingly
                    url = $"{authentication.AccountUrl}/{project}/_apis/build/builds/{buildId}?api-version=2.0";

                    // Setup the input to the API call
                    var model = new Retention {
                        keepForever = keepForever
                    };

                    var result = restHttpClient.PatchAsync <BuildResult, Retention>(authentication, url, model).Result;

                    callSucceeded = (result != null);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                callSucceeded = false;
            }

            return(callSucceeded);
        }
        public void ProjectSetup_PopulateWithTestData_TheCorrectNumberOfEnvrionmentsIsReturned()
        {
            //Arrange
            var projects = CreateTestData(out var environments, out var releases, out var deployments);

            var releaseRetention = new Retention(projects, environments, releases, deployments);

            //Act
            var expected             = environments.Count;
            var project1Environments =
                releaseRetention.Projects.Where(x => x.Id == "Project-1").SelectMany(x => x.Environments).Count();

            var project2Environments =
                releaseRetention.Projects.Where(x => x.Id == "Project-2").SelectMany(x => x.Environments).Count();

            //Assert
            Assert.AreEqual(expected, project1Environments);
            Assert.AreEqual(expected, project2Environments);
        }
        public void ProjectSetup_PopulateWithTestData_TheCorrectNumberOfDeploymentsIsReturned()
        {
            //Arrange
            var projects = CreateTestData(out var environments, out var releases, out var deployments);

            var releaseRetention = new Retention(projects, environments, releases, deployments);

            //Act
            var project1ExpectedDeployments = 3;             //Deployment-4 is for an incorrect EnvironmentId
            var project1Deployments         =
                releaseRetention.Projects.Where(x => x.Id == "Project-1").SelectMany(x => x.Deployments).Count();

            var project2ExpectedDeployments = 5;             //Deployment-8 is for release with invalid ProjectId
            var project2Deployments         =
                releaseRetention.Projects.Where(x => x.Id == "Project-2").SelectMany(x => x.Deployments).Count();

            Assert.AreEqual(project1ExpectedDeployments, project1Deployments);
            Assert.AreEqual(project2ExpectedDeployments, project2Deployments);
        }
예제 #21
0
        public async void GetVehicleByEmail(int clientId)
        {
            Retention vehicle = new Retention()
            {
                IDClient = clientId,
            };
            var json    = JsonConvert.SerializeObject(vehicle);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            HttpClient client = new HttpClient();


            var response = await client.GetStringAsync(string.Concat("http://192.168.0.53:45455/Api/Retention?ClientID=", clientId));

            //var response = await client.GetStringAsync(string.Concat("http://192.168.0.53:45455/Api/Vehicle?EmailAdddress=" + clientId/*, "&Password="******"[" + response + "]");

            ListCliam.ItemsSource = vehicles;
        }
        public void ProjectSetup_PopulateWithTestData_TheCorrectNumberOfReleasesIsReturned()
        {
            //Arrange
            var projects = CreateTestData(out var environments, out var releases, out var deployments);

            var releaseRetention = new Retention(projects, environments, releases, deployments);

            //Act
            var project1ExpectedReleases = 3;
            var project1Releases         =
                releaseRetention.Projects.Where(x => x.Id == "Project-1").SelectMany(x => x.Releases).Count();

            var project2ExpectedReleases = 4;
            var project2Releases         =
                releaseRetention.Projects.Where(x => x.Id == "Project-2").SelectMany(x => x.Releases).Count();

            //Assert, One release was discounted because it was for 'Project-3'
            Assert.AreEqual(project1ExpectedReleases, project1Releases);
            Assert.AreEqual(project2ExpectedReleases, project2Releases);
        }
예제 #23
0
        public RetentionForm(int?id)
        {
            InitializeComponent();

            //загрузка фильтра преподавателей
            var teachers = from teach in db.Workers
                           join depart in db.Departments on teach.DepartmentId equals depart.Id
                           where teach.IsRemoved == false
                           orderby teach.Lastname, teach.Firstname, teach.Middlename
                select new
            {
                Id      = teach.Id,
                Teacher = teach.Lastname + " " + teach.Firstname.Substring(0, 1) + "." + teach.Middlename.Substring(0, 1) + ".  (" + depart.Name + ")",
                RoleId  = teach.RoleId
            };

            cbTeachers.DataSource    = teachers.OrderBy(a => a.Teacher).ToList();
            cbTeachers.DisplayMember = "Teacher";
            cbTeachers.ValueMember   = "Id";
            cbTeachers.SelectedIndex = -1;

            //загрузка оснований начислений/удержаний
            var bases = db.Bases.OrderBy(a => a.Name).ToList();

            cbBase.DataSource    = bases;
            cbBase.DisplayMember = "Name";
            cbBase.ValueMember   = "Id";

            if (id != null)
            {
                retention = db.Retentions.Find(id);
            }
            else
            {
                retention = new Retention();
            }
        }
예제 #24
0
        async void OnSubStatusChosen(object sender, EventArgs e)
        {
            HttpClient client    = new HttpClient();
            Retention  retention = new Retention()
            {
                RetentionType = txtStatus1.SelectedItem.ToString()
            };



            var json    = JsonConvert.SerializeObject(retention);
            var content = new StringContent(json, Encoding.UTF8, "application/json");



            var response = await client.PostAsync(string.Concat("http://192.168.0.53:45455/Api/Retention?RetentionType=" + txtStatus1.SelectedItem.ToString()), content);

            var results         = response.Content.ReadAsStringAsync().Result;
            var retentionStatus = JsonConvert.DeserializeObject <List <Retention> >(results);

            //listClaims.ItemsSource = currentUser;

            txtStatus.ItemsSource = retentionStatus;
        }
예제 #25
0
        public async Task <string> Handle(CreateRetentionCommand request, CancellationToken cancellationToken)
        {
            var entity = new Retention
            {
                ClientName        = request.ClientName,
                CustomerID        = request.CustomerID,
                ContactNumber     = request.ContactNumber,
                CurrentProject    = request.CurrentProject,
                CurrentUnitNumber = request.CurrentUnitNumber,
                Price             = request.Price,
                GP                  = request.GP,
                GPValue             = request.GPValue,
                SIMAH               = request.SIMAH,
                TypeOfCounterOffers = request.TypeOfCounterOffers,
                Description         = request.Description,
                VAS                 = request.VAS,
                RefNo               = request.RefNo
            };

            _context.Retentions.Add(entity);
            await _context.SaveChangesAsync(cancellationToken);

            return(entity.Id);
        }
예제 #26
0
        public static RetentionPolicy[] ToRetentionPolicies(this ResultSet resultSet)
        {
            var result = resultSet.ToMultiValuedDictionary();

            List <object> policyNameObjects;
            List <object> durationObjects;
            List <object> replicationObjects;

            if (!result.TryGetValue("name", out policyNameObjects) || !result.TryGetValue("duration", out durationObjects) || !result.TryGetValue("replicaN", out replicationObjects))
            {
                throw new InfluxException("The result set does not have the expected structure.");
            }

            if (policyNameObjects.Count != durationObjects.Count || durationObjects.Count != replicationObjects.Count)
            {
                throw new InfluxException("The result set is unexpectedly jagged.  This is likely an InfluxDB bug.");
            }

            var policyNames  = policyNameObjects.Select(x => x.ToString()).ToArray();
            var durations    = durationObjects.Select(x => Retention.Parse(x.ToString())).ToArray();
            var replications = replicationObjects.Select(x => int.Parse(x.ToString())).ToArray();

            return(policyNames.Select((policyName, idx) => new RetentionPolicy(policyName, durations[idx], replications[idx])).ToArray());
        }
예제 #27
0
파일: Painter.cs 프로젝트: fealty/Frost
        protected abstract void OnBegin(
			Canvas.ResolvedContext target, Retention retention);
예제 #28
0
파일: Painter.cs 프로젝트: fealty/Frost
        public void Begin(Canvas target, Retention retention = Retention.ClearData)
        {
            Contract.Requires(Thread.CurrentThread == BoundThread);
            Contract.Requires(ActiveTarget == null);
            Contract.Requires(target != null);

            bool isTargetEmpty = target.Region.IsEmpty;

            _IsAntialiasingInvalid = true;
            _IsDashCapInvalid = true;
            _IsLineStyleInvalid = true;
            _IsMiterLimitInvalid = true;
            _IsStrokeCapInvalid = true;
            _IsStrokeJoinInvalid = true;
            _IsStrokeWidthInvalid = true;
            _IsTransformationInvalid = true;

            _ActiveTarget = target;

            ResetState();

            if(!isTargetEmpty)
            {
                var targetContext = _Device2D.Resources.ResolveCanvas(target);

                _TargetDelta = targetContext.Region.Location;

                OnBegin(targetContext, retention);
            }
            else
            {
                // permit only nop and state operations on empty targets
                _TargetDelta = Size.Empty;
            }

            _IsTargetEmpty = isTargetEmpty;
        }
예제 #29
0
        private void OnReceiveTrData(object sender, _DKHOpenAPIEvents_OnReceiveTrDataEvent e)
        {
            var temp = axAPI.GetCommDataEx(e.sTrCode, e.sRQName);

            if (temp != null)
            {
                string[,] ts = new string[((object[, ])temp).GetUpperBound(0) + 1, ((object[, ])temp).GetUpperBound(1) + 1];
                int x, y, lx = ((object[, ])temp).GetUpperBound(0), ly = ((object[, ])temp).GetUpperBound(1);

                for (x = 0; x <= lx; x++)
                {
                    sb = new StringBuilder(64);

                    for (y = 0; y <= ly; y++)
                    {
                        ts[x, y] = (string)((object[, ])temp)[x, y];

                        if (ts[x, y].Length > 13 && !e.sTrCode.Equals("opt50001") && Retention.Equals(ts[x, y].Substring(2)))
                        {
                            sb          = new StringBuilder(it);
                            e.sPrevNext = "0";

                            break;
                        }
                        sb.Append(ts[x, y]);

                        if (y != ly)
                        {
                            sb.Append(",");
                        }
                    }
                    if (!e.sTrCode.Equals("opt50001") && sb.ToString() != it)
                    {
                        SendMemorize?.Invoke(this, new Memorize(sb));

                        continue;
                    }
                    if (sb.ToString() == it)
                    {
                        break;
                    }

                    if (e.sTrCode.Equals("opt50001"))
                    {
                        Remaining = axAPI.GetCommData(e.sTrCode, e.sRQName, 0, "잔존일수").Trim();

                        return;
                    }
                }
                if (e.sPrevNext.Equals("2") && !e.sTrCode.Equals("opt50001"))
                {
                    request.RequestTrData(new Task(() => InputValueRqData(new Opt50028 {
                        Value = Code, RQName = Code + Retention, PrevNext = 2
                    })));

                    return;
                }
                if (e.sPrevNext.Equals("0") && !e.sTrCode.Equals("opt50001"))
                {
                    SendMemorize?.Invoke(this, new Memorize(e.sPrevNext));
                }
            }
        }
예제 #30
0
        private async Task RequestHandler(HttpContext ctx)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException(nameof(ctx));
            }
            DateTime  startTime = DateTime.Now;
            S3Context s3ctx     = null;

            try
            {
                s3ctx = new S3Context(ctx, _BaseDomains, null, (Logging.S3Requests ? Logger : null));
                s3ctx.Response.Headers.Add("x-amz-request-id", s3ctx.Request.RequestId);
                s3ctx.Response.Headers.Add("x-amz-id-2", s3ctx.Request.RequestId);
            }
            catch (Exception e)
            {
                if (Logging.Exceptions)
                {
                    Logger?.Invoke(_Header + "Exception:" + Environment.NewLine + Common.SerializeJson(e, true));
                }

                return;
            }

            bool                    success           = false;
            bool                    exists            = false;
            S3Object                s3obj             = null;
            ObjectMetadata          md                = null;
            AccessControlPolicy     acp               = null;
            LegalHold               legalHold         = null;
            Retention               retention         = null;
            Tagging                 tagging           = null;
            ListAllMyBucketsResult  buckets           = null;
            ListBucketResult        listBucketResult  = null;
            ListVersionsResult      listVersionResult = null;
            LocationConstraint      location          = null;
            BucketLoggingStatus     bucketLogging     = null;
            VersioningConfiguration versionConfig     = null;
            WebsiteConfiguration    wc                = null;
            DeleteMultiple          delMultiple       = null;
            DeleteResult            delResult         = null;

            try
            {
                if (Logging.HttpRequests)
                {
                    Logger?.Invoke(_Header + "HTTP request: " + Environment.NewLine + s3ctx.Http.ToJson(true));
                }

                if (Logging.S3Requests)
                {
                    Logger?.Invoke(_Header + "S3 request: " + Environment.NewLine + s3ctx.Request.ToJson(true));
                }

                if (PreRequestHandler != null)
                {
                    success = await PreRequestHandler(s3ctx).ConfigureAwait(false);

                    if (success)
                    {
                        await s3ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                }

                switch (s3ctx.Request.RequestType)
                {
                    #region Service

                case S3RequestType.ListBuckets:
                    if (Service.ListBuckets != null)
                    {
                        buckets = await Service.ListBuckets(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(buckets)).ConfigureAwait(false);

                        return;
                    }
                    break;

                    #endregion

                    #region Bucket

                case S3RequestType.BucketDelete:
                    if (Bucket.Delete != null)
                    {
                        await Bucket.Delete(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketDeleteTags:
                    if (Bucket.DeleteTagging != null)
                    {
                        await Bucket.DeleteTagging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketDeleteWebsite:
                    if (Bucket.DeleteWebsite != null)
                    {
                        await Bucket.DeleteWebsite(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketExists:
                    if (Bucket.Exists != null)
                    {
                        exists = await Bucket.Exists(s3ctx).ConfigureAwait(false);

                        if (exists)
                        {
                            ctx.Response.StatusCode  = 200;
                            ctx.Response.ContentType = "text/plain";
                            await ctx.Response.Send().ConfigureAwait(false);
                        }
                        else
                        {
                            ctx.Response.StatusCode  = 404;
                            ctx.Response.ContentType = "text/plain";
                            await ctx.Response.Send().ConfigureAwait(false);
                        }
                        return;
                    }
                    break;

                case S3RequestType.BucketRead:
                    if (Bucket.Read != null)
                    {
                        listBucketResult = await Bucket.Read(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(listBucketResult)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadAcl:
                    if (Bucket.ReadAcl != null)
                    {
                        acp = await Bucket.ReadAcl(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(acp)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadLocation:
                    if (Bucket.ReadLocation != null)
                    {
                        location = await Bucket.ReadLocation(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(location)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadLogging:
                    if (Bucket.ReadLogging != null)
                    {
                        bucketLogging = await Bucket.ReadLogging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(bucketLogging)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadTags:
                    if (Bucket.ReadTagging != null)
                    {
                        tagging = await Bucket.ReadTagging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(tagging)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadVersioning:
                    if (Bucket.ReadVersioning != null)
                    {
                        versionConfig = await Bucket.ReadVersioning(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(versionConfig)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadVersions:
                    if (Bucket.ReadVersions != null)
                    {
                        listVersionResult = await Bucket.ReadVersions(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(listVersionResult)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketReadWebsite:
                    if (Bucket.ReadWebsite != null)
                    {
                        wc = await Bucket.ReadWebsite(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(wc)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWrite:
                    if (Bucket.Write != null)
                    {
                        await Bucket.Write(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteAcl:
                    if (Bucket.WriteAcl != null)
                    {
                        try
                        {
                            acp = Common.DeserializeXml <AccessControlPolicy>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteAcl(s3ctx, acp).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteLogging:
                    if (Bucket.WriteLogging != null)
                    {
                        try
                        {
                            bucketLogging = Common.DeserializeXml <BucketLoggingStatus>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteLogging(s3ctx, bucketLogging).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteTags:
                    if (Bucket.WriteTagging != null)
                    {
                        try
                        {
                            tagging = Common.DeserializeXml <Tagging>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteTagging(s3ctx, tagging).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteVersioning:
                    if (Bucket.WriteVersioning != null)
                    {
                        try
                        {
                            versionConfig = Common.DeserializeXml <VersioningConfiguration>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteVersioning(s3ctx, versionConfig).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.BucketWriteWebsite:
                    if (Bucket.WriteWebsite != null)
                    {
                        try
                        {
                            wc = Common.DeserializeXml <WebsiteConfiguration>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Bucket.WriteWebsite(s3ctx, wc).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                    #endregion

                    #region Object

                case S3RequestType.ObjectDelete:
                    if (Object.Delete != null)
                    {
                        await Object.Delete(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectDeleteMultiple:
                    if (Object.DeleteMultiple != null)
                    {
                        try
                        {
                            delMultiple = Common.DeserializeXml <DeleteMultiple>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        delResult = await Object.DeleteMultiple(s3ctx, delMultiple).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(delResult)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectDeleteTags:
                    if (Object.DeleteTagging != null)
                    {
                        await Object.DeleteTagging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 204;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectExists:
                    if (Object.Exists != null)
                    {
                        md = await Object.Exists(s3ctx).ConfigureAwait(false);

                        if (md != null)
                        {
                            if (!String.IsNullOrEmpty(md.ETag))
                            {
                                ctx.Response.Headers.Add("ETag", md.ETag);
                            }
                            ctx.Response.Headers.Add("Last-Modified", md.LastModified.ToString());
                            ctx.Response.Headers.Add("x-amz-storage-class", md.StorageClass);
                            ctx.Response.StatusCode    = 200;
                            ctx.Response.ContentLength = md.Size;
                            ctx.Response.ContentType   = md.ContentType;
                            await ctx.Response.Send(md.Size).ConfigureAwait(false);
                        }
                        else
                        {
                            ctx.Response.StatusCode = 404;
                            await ctx.Response.Send().ConfigureAwait(false);
                        }
                        return;
                    }
                    break;

                case S3RequestType.ObjectRead:
                    if (Object.Read != null)
                    {
                        s3obj = await Object.Read(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode    = 200;
                        ctx.Response.ContentType   = s3obj.ContentType;
                        ctx.Response.ContentLength = s3obj.Size;
                        await ctx.Response.Send(s3obj.Size, s3obj.Data).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadAcl:
                    if (Object.ReadAcl != null)
                    {
                        acp = await Object.ReadAcl(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(acp)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadLegalHold:
                    if (Object.ReadLegalHold != null)
                    {
                        legalHold = await Object.ReadLegalHold(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(legalHold)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadRange:
                    if (Object.ReadRange != null)
                    {
                        s3obj = await Object.ReadRange(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode    = 200;
                        ctx.Response.ContentType   = s3obj.ContentType;
                        ctx.Response.ContentLength = s3obj.Size;
                        await ctx.Response.Send(s3obj.Size, s3obj.Data).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadRetention:
                    if (Object.ReadRetention != null)
                    {
                        retention = await Object.ReadRetention(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(retention)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectReadTags:
                    if (Object.ReadTagging != null)
                    {
                        tagging = await Object.ReadTagging(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "application/xml";
                        await ctx.Response.Send(Common.SerializeXml(tagging)).ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWrite:
                    if (Object.Write != null)
                    {
                        await Object.Write(s3ctx).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWriteAcl:
                    if (Object.WriteAcl != null)
                    {
                        try
                        {
                            acp = Common.DeserializeXml <AccessControlPolicy>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Object.WriteAcl(s3ctx, acp).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWriteLegalHold:
                    if (Object.WriteLegalHold != null)
                    {
                        try
                        {
                            legalHold = Common.DeserializeXml <LegalHold>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Object.WriteLegalHold(s3ctx, legalHold).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWriteRetention:
                    if (Object.WriteRetention != null)
                    {
                        try
                        {
                            retention = Common.DeserializeXml <Retention>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Object.WriteRetention(s3ctx, retention).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                case S3RequestType.ObjectWriteTags:
                    if (Object.WriteTagging != null)
                    {
                        try
                        {
                            tagging = Common.DeserializeXml <Tagging>(s3ctx.Request.DataAsString);
                        }
                        catch (InvalidOperationException ioe)
                        {
                            ioe.Data.Add("Context", s3ctx);
                            ioe.Data.Add("RequestBody", s3ctx.Request.DataAsString);
                            Logger?.Invoke(_Header + "XML exception: " + Environment.NewLine + Common.SerializeJson(ioe, true));
                            await s3ctx.Response.Send(S3Objects.ErrorCode.MalformedXML).ConfigureAwait(false);

                            return;
                        }

                        await Object.WriteTagging(s3ctx, tagging).ConfigureAwait(false);

                        ctx.Response.StatusCode  = 200;
                        ctx.Response.ContentType = "text/plain";
                        await ctx.Response.Send().ConfigureAwait(false);

                        return;
                    }
                    break;

                    #endregion
                }

                if (DefaultRequestHandler != null)
                {
                    await DefaultRequestHandler(s3ctx).ConfigureAwait(false);

                    return;
                }

                await s3ctx.Response.Send(S3Objects.ErrorCode.InvalidRequest).ConfigureAwait(false);

                return;
            }
            catch (S3Exception s3e)
            {
                if (Logging.Exceptions)
                {
                    Logger?.Invoke(_Header + "S3 exception:" + Environment.NewLine + Common.SerializeJson(s3e, true));
                }

                await s3ctx.Response.Send(s3e.Error).ConfigureAwait(false);

                return;
            }
            catch (Exception e)
            {
                if (Logging.Exceptions)
                {
                    Logger?.Invoke(_Header + "exception:" + Environment.NewLine + Common.SerializeJson(e, true));
                }

                await s3ctx.Response.Send(S3Objects.ErrorCode.InternalError).ConfigureAwait(false);

                return;
            }
            finally
            {
                if (Logging.HttpRequests)
                {
                    Logger?.Invoke(
                        _Header +
                        "[" +
                        ctx.Request.Source.IpAddress + ":" +
                        ctx.Request.Source.Port +
                        "] " +
                        ctx.Request.Method.ToString() + " " +
                        ctx.Request.Url.RawWithoutQuery + " " +
                        s3ctx.Response.StatusCode +
                        " [" + Common.TotalMsFrom(startTime) + "ms]");
                }

                if (PostRequestHandler != null)
                {
                    await PostRequestHandler(s3ctx).ConfigureAwait(false);
                }
            }
        }
예제 #31
0
파일: Painter.cs 프로젝트: fealty/Frost
        protected override void OnBegin(Canvas.ResolvedContext target, Retention retention)
        {
            Contract.Assert(_ActiveBrush == null);

            _Watch.Reset();
            _Watch.Start();

            _IsBrushInvalid = true;

            _TargetSurface = (Surface2D)target.Surface2D;

            _TargetSurface.AcquireLock();

            _Drawer.Begin(target);

            OnSetBrush(Color.Black);
        }
예제 #32
0
        protected internal override void OnReceiveData(string szTrCode)
        {
            var enumerable = GetOutBlocks();
            var list       = new List <string[]>();
            var index      = int.MinValue;
            var code       = string.Empty;

            while (enumerable.Count > 0)
            {
                var param = enumerable.Dequeue();

                switch (enumerable.Count)
                {
                case int count when count > 0x1C:
                    var block = InBlock.First(o => o.Field.Equals(param.Field));
                    SetFieldData(block.Block, block.Field, block.Occurs, block.Data);
                    continue;

                case int count when count < 7 || count == 7 && Decompress(param.Block) > 0:
                    var bCount = GetBlockCount(param.Block);
                    var array  = new string[bCount];

                    for (int i = 0; i < bCount; i++)
                    {
                        array[i] = GetFieldData(param.Block, param.Field, i);
                    }

                    list.Add(array);
                    break;

                case int count when count == 0xD || count == 0xC:
                    var data    = GetFieldData(param.Block, param.Field, 0);
                    var refresh = InBlock.First(o => o.Field.Equals(param.Field));
                    SetFieldData(refresh.Block, refresh.Field, refresh.Occurs, data);
                    continue;

                case 0x1A:
                    var temp = InBlock.First(o => o.Field.Equals(param.Field));
                    SetFieldData(temp.Block, temp.Field, temp.Occurs, temp.Data);
                    continue;

                case 0x19:
                    code = GetFieldData(param.Block, param.Field, 0);
                    continue;

                case 8:
                    if (int.TryParse(GetFieldData(param.Block, param.Field, 0), out int rCount))
                    {
                        index = rCount;
                    }

                    continue;
                }
            }
            var span = WaitForTheLimitTime(GetTRCountRequest(szTrCode));

            SendMessage(span);

            if (span.TotalSeconds > 0xC5 && span.TotalSeconds < 0xC8)
            {
                Milliseconds = (int)span.TotalMilliseconds;
            }

            else
            {
                Milliseconds = 0x3EB / GetTRCountPerSec(szTrCode);
            }

            if (index > 0)
            {
                for (int i = index - 1; i >= 0; i--)
                {
                    var temp = string.Concat(list[0][i].Substring(2), list[1][i].Substring(0, 6));

                    if (string.IsNullOrEmpty(Retention) || string.Compare(temp, Retention) > 0)
                    {
                        Charts.Push(string.Concat(temp, ";", list[5][i], ";", list[6][i]));
                    }

                    else
                    {
                        new Task(() =>
                        {
                            Thread.Sleep(Milliseconds);
                            Send?.Invoke(this, new SendSecuritiesAPI(code, Charts));
                        }).Start();
                        return;
                    }
                }
            }
            new Task(() =>
            {
                Thread.Sleep(Milliseconds);

                if (IsNext && Array.Exists(Retention.ToCharArray(), o => char.IsLetter(o)) == false)
                {
                    SendErrorMessage(GetType().Name, Request(IsNext));
                }

                else
                {
                    Send?.Invoke(this, new SendSecuritiesAPI(code, Charts));
                }
            }).Start();
        }
예제 #33
0
        IEstructuraXml IDocumentoXml.Generar(IDocumentoElectronico request)
        {
            var documento = (DocumentoRetencion)request;
            var retention = new Retention
            {
                Id        = documento.IdDocumento,
                IssueDate = documento.FechaEmision,
                Signature = new SignatureCac
                {
                    Id             = documento.IdDocumento,
                    SignatoryParty = new SignatoryParty
                    {
                        PartyIdentification = new PartyIdentification
                        {
                            Id = new PartyIdentificationId
                            {
                                Value = documento.Emisor.NroDocumento
                            }
                        },
                        PartyName = new PartyName
                        {
                            Name = documento.Emisor.NombreLegal
                        }
                    },
                    DigitalSignatureAttachment = new DigitalSignatureAttachment
                    {
                        ExternalReference = new ExternalReference
                        {
                            Uri = $"{documento.Emisor.NroDocumento}-{documento.IdDocumento}"
                        }
                    }
                },
                AgentParty = new AgentParty
                {
                    PartyIdentification = new PartyIdentification
                    {
                        Id = new PartyIdentificationId
                        {
                            SchemeId = documento.Emisor.TipoDocumento,
                            Value    = documento.Emisor.NroDocumento
                        }
                    },
                    PartyName = new PartyName
                    {
                        Name = documento.Emisor.NombreComercial
                    },
                    PostalAddress = new PostalAddress
                    {
                        Id                  = documento.Emisor.Ubigeo,
                        StreetName          = documento.Emisor.Direccion,
                        CitySubdivisionName = documento.Emisor.Urbanizacion,
                        CountrySubentity    = documento.Emisor.Departamento,
                        CityName            = documento.Emisor.Provincia,
                        District            = documento.Emisor.Distrito,
                        Country             = new Country {
                            IdentificationCode = "PE"
                        }
                    },
                    PartyLegalEntity = new PartyLegalEntity
                    {
                        RegistrationName = documento.Emisor.NombreLegal
                    }
                },
                ReceiverParty = new AgentParty
                {
                    PartyIdentification = new PartyIdentification
                    {
                        Id = new PartyIdentificationId
                        {
                            SchemeId = documento.Emisor.TipoDocumento,
                            Value    = documento.Emisor.NroDocumento
                        }
                    },
                    PartyName = new PartyName
                    {
                        Name = documento.Emisor.NombreComercial
                    },
                    PostalAddress = new PostalAddress
                    {
                        Id                  = documento.Emisor.Ubigeo,
                        StreetName          = documento.Emisor.Direccion,
                        CitySubdivisionName = documento.Emisor.Urbanizacion,
                        CountrySubentity    = documento.Emisor.Departamento,
                        CityName            = documento.Emisor.Provincia,
                        District            = documento.Emisor.Distrito,
                        Country             = new Country {
                            IdentificationCode = "PE"
                        }
                    },
                    PartyLegalEntity = new PartyLegalEntity
                    {
                        RegistrationName = documento.Emisor.NombreLegal
                    }
                },
                SunatRetentionSystemCode = documento.RegimenRetencion,
                SunatRetentionPercent    = documento.TasaRetencion,
                Note = documento.Observaciones,
                TotalInvoiceAmount = new PayableAmount
                {
                    CurrencyId = documento.Moneda,
                    Value      = documento.ImporteTotalRetenido
                },
                TotalPaid = new PayableAmount
                {
                    CurrencyId = documento.Moneda,
                    Value      = documento.ImporteTotalPagado
                }
            };

            foreach (var relacionado in documento.DocumentosRelacionados)
            {
                retention.SunatRetentionDocumentReference.Add(new SunatRetentionDocumentReference
                {
                    Id = new PartyIdentificationId
                    {
                        SchemeId = relacionado.TipoDocumento,
                        Value    = relacionado.NroDocumento
                    },
                    IssueDate          = relacionado.FechaEmision,
                    TotalInvoiceAmount = new PayableAmount
                    {
                        CurrencyId = relacionado.MonedaDocumentoRelacionado,
                        Value      = relacionado.ImporteTotal
                    },
                    Payment = new Payment
                    {
                        IdPayment  = relacionado.NumeroPago,
                        PaidAmount = new PayableAmount
                        {
                            CurrencyId = relacionado.MonedaDocumentoRelacionado,
                            Value      = relacionado.ImporteSinRetencion
                        },
                        PaidDate = relacionado.FechaPago
                    },
                    SunatRetentionInformation = new SunatRetentionInformation
                    {
                        SunatRetentionAmount = new PayableAmount
                        {
                            CurrencyId = documento.Moneda,
                            Value      = relacionado.ImporteRetenido
                        },
                        SunatRetentionDate = relacionado.FechaRetencion,
                        SunatNetTotalPaid  = new PayableAmount
                        {
                            CurrencyId = documento.Moneda,
                            Value      = relacionado.ImporteTotalNeto
                        },
                        ExchangeRate = new ExchangeRate
                        {
                            SourceCurrencyCode = relacionado.MonedaDocumentoRelacionado,
                            TargetCurrencyCode = documento.Moneda,
                            CalculationRate    = relacionado.TipoCambio,
                            Date = relacionado.FechaTipoCambio
                        }
                    }
                });
            }

            return(retention);
        }
예제 #34
0
 public DataportDescription(string dataformat)
 {
     format = dataformat;
     preprocess= new object[]{};
     retention = new Retention();
 }