Ejemplo n.º 1
0
        public virtual int Receive(byte[] buf, int off, int len, int waitMillis)
        {
            long currentTimeMillis = DateTimeUtilities.CurrentUnixMs();

            Timeout timeout = Timeout.ForWaitMillis(waitMillis, currentTimeMillis);

            byte[] record = null;

            while (waitMillis >= 0)
            {
                if (mRetransmitTimeout != null && mRetransmitTimeout.RemainingMillis(currentTimeMillis) < 1)
                {
                    mRetransmit        = null;
                    mRetransmitEpoch   = null;
                    mRetransmitTimeout = null;
                }

                int receiveLimit = System.Math.Min(len, GetReceiveLimit()) + RECORD_HEADER_LENGTH;
                if (record == null || record.Length < receiveLimit)
                {
                    record = new byte[receiveLimit];
                }

                int received  = ReceiveRecord(record, 0, receiveLimit, waitMillis);
                int processed = ProcessRecord(received, record, buf, off);
                if (processed >= 0)
                {
                    return(processed);
                }

                currentTimeMillis = DateTimeUtilities.CurrentUnixMs();
                waitMillis        = Timeout.GetWaitMillis(timeout, currentTimeMillis);
            }

            return(-1);
        }
Ejemplo n.º 2
0
        /// <summary>Return a V3 signature object containing the current signature state.</summary>
        public PgpSignature Generate()
        {
            long creationTime = DateTimeUtilities.CurrentUnixMs() / 1000L;

            byte[] hData = new byte[]
            {
                (byte)signatureType,
                (byte)(creationTime >> 24),
                (byte)(creationTime >> 16),
                (byte)(creationTime >> 8),
                (byte)creationTime
            };

            sig.BlockUpdate(hData, 0, hData.Length);
            dig.BlockUpdate(hData, 0, hData.Length);

            byte[] sigBytes    = sig.GenerateSignature();
            byte[] digest      = DigestUtilities.DoFinal(dig);
            byte[] fingerPrint = new byte[] { digest[0], digest[1] };

            MPInteger[] sigValues;
            if (keyAlgorithm == PublicKeyAlgorithmTag.RsaSign ||
                keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral)
            // an RSA signature
            {
                sigValues = new MPInteger[] { new MPInteger(new BigInteger(1, sigBytes)) };
            }
            else
            {
                sigValues = PgpUtilities.DsaSigToMpi(sigBytes);
            }

            return(new PgpSignature(
                       new SignaturePacket(3, signatureType, privKey.KeyId, keyAlgorithm,
                                           hashAlgorithm, creationTime * 1000L, fingerPrint, sigValues)));
        }
    public PgpSignature Generate()
    {
        long num = DateTimeUtilities.CurrentUnixMs() / 1000;

        byte[] array = new byte[5]
        {
            (byte)signatureType,
            (byte)(num >> 24),
            (byte)(num >> 16),
            (byte)(num >> 8),
            (byte)num
        };
        sig.BlockUpdate(array, 0, array.Length);
        dig.BlockUpdate(array, 0, array.Length);
        byte[] encoding    = sig.GenerateSignature();
        byte[] array2      = DigestUtilities.DoFinal(dig);
        byte[] fingerprint = new byte[2]
        {
            array2[0],
            array2[1]
        };
        MPInteger[] signature = (keyAlgorithm == PublicKeyAlgorithmTag.RsaSign || keyAlgorithm == PublicKeyAlgorithmTag.RsaGeneral) ? PgpUtilities.RsaSigToMpi(encoding) : PgpUtilities.DsaSigToMpi(encoding);
        return(new PgpSignature(new SignaturePacket(3, signatureType, privKey.KeyId, keyAlgorithm, hashAlgorithm, num * 1000, fingerprint, signature)));
    }
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The DFP user object running the code example.</param>
        public override void Run(DfpUser user)
        {
            // Get the LineItemService.
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201511.LineItemService);

            // Set the order that all created line items will belong to and the
            // video ad unit ID to target.
            long   orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));
            string targetedVideoAdUnitId = _T("INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE");

            // Set the custom targeting value ID representing the metadata
            // on the content to target. This would typically be from a key representing
            // a "genre" and a value representing something like "comedy". The value must
            // be from a key in a content metadata key hierarchy.
            long contentCustomTargetingValueId =
                long.Parse(_T("INSERT_CONTENT_CUSTOM_TARGETING_VALUE_ID_HERE"));

            // Create content targeting.
            ContentMetadataKeyHierarchyTargeting contentMetadataTargeting =
                new ContentMetadataKeyHierarchyTargeting();

            contentMetadataTargeting.customTargetingValueIds =
                new long[] { contentCustomTargetingValueId };

            ContentTargeting contentTargeting = new ContentTargeting();

            contentTargeting.targetedContentMetadata =
                new ContentMetadataKeyHierarchyTargeting[] { contentMetadataTargeting };

            // Create inventory targeting.
            InventoryTargeting inventoryTargeting = new InventoryTargeting();
            AdUnitTargeting    adUnitTargeting    = new AdUnitTargeting();

            adUnitTargeting.adUnitId           = targetedVideoAdUnitId;
            adUnitTargeting.includeDescendants = true;
            inventoryTargeting.targetedAdUnits = new AdUnitTargeting[] { adUnitTargeting };

            // Create video position targeting.
            VideoPosition videoPosition = new VideoPosition();

            videoPosition.positionType = VideoPositionType.PREROLL;
            VideoPositionTarget videoPositionTarget = new VideoPositionTarget();

            videoPositionTarget.videoPosition = videoPosition;
            VideoPositionTargeting videoPositionTargeting = new VideoPositionTargeting();

            videoPositionTargeting.targetedPositions = new VideoPositionTarget[] { videoPositionTarget };

            // Create targeting.
            Targeting targeting = new Targeting();

            targeting.contentTargeting       = contentTargeting;
            targeting.inventoryTargeting     = inventoryTargeting;
            targeting.videoPositionTargeting = videoPositionTargeting;

            // Create local line item object.
            LineItem lineItem = new LineItem();

            lineItem.name          = "Video line item - " + this.GetTimeStamp();
            lineItem.orderId       = orderId;
            lineItem.targeting     = targeting;
            lineItem.lineItemType  = LineItemType.SPONSORSHIP;
            lineItem.allowOverbook = true;

            // Set the environment type to video.
            lineItem.environmentType = EnvironmentType.VIDEO_PLAYER;

            // Set the creative rotation type to optimized.
            lineItem.creativeRotationType = CreativeRotationType.OPTIMIZED;

            // Create the master creative placeholder.
            CreativePlaceholder creativeMasterPlaceholder = new CreativePlaceholder();
            Size size1 = new Size();

            size1.width                    = 400;
            size1.height                   = 300;
            size1.isAspectRatio            = false;
            creativeMasterPlaceholder.size = size1;

            // Create companion creative placeholders.
            CreativePlaceholder companionCreativePlaceholder1 = new CreativePlaceholder();
            Size size2 = new Size();

            size2.width         = 300;
            size2.height        = 250;
            size2.isAspectRatio = false;
            companionCreativePlaceholder1.size = size2;

            CreativePlaceholder companionCreativePlaceholder2 = new CreativePlaceholder();
            Size size3 = new Size();

            size3.width         = 728;
            size3.height        = 90;
            size3.isAspectRatio = false;
            companionCreativePlaceholder2.size = size3;

            // Set companion creative placeholders.
            creativeMasterPlaceholder.companions = new CreativePlaceholder[] {
                companionCreativePlaceholder1, companionCreativePlaceholder2
            };

            // Set the size of creatives that can be associated with this line item.
            lineItem.creativePlaceholders = new CreativePlaceholder[] { creativeMasterPlaceholder };

            // Set delivery of video companions to optional.
            lineItem.companionDeliveryOption = CompanionDeliveryOption.OPTIONAL;

            // Set the line item to run for one month.
            lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
            lineItem.endDateTime       =
                DateTimeUtilities.FromDateTime(System.DateTime.Now.AddMonths(1), "America/New_York");

            // Set the cost per day to $1.
            lineItem.costType = CostType.CPD;
            Money money = new Money();

            money.currencyCode   = "USD";
            money.microAmount    = 1000000L;
            lineItem.costPerUnit = money;

            // Set the percentage to be 100%.
            Goal goal = new Goal();

            goal.goalType        = GoalType.DAILY;
            goal.unitType        = UnitType.IMPRESSIONS;
            goal.units           = 100;
            lineItem.primaryGoal = goal;

            try {
                // Create the line item on the server.
                LineItem[] createdLineItems = lineItemService.createLineItems(new LineItem[] { lineItem });

                foreach (LineItem createdLineItem in createdLineItems)
                {
                    Console.WriteLine("A line item with ID \"{0}\", belonging to order ID \"{1}\", and " +
                                      "named \"{2}\" was created.", createdLineItem.id, createdLineItem.orderId,
                                      createdLineItem.name);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create line items. Exception says \"{0}\"",
                                  e.Message);
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (ForecastService forecastService =
                       (ForecastService)user.GetService(DfpService.v201802.ForecastService)) {
                // Set the placement that the prospective line item will target.
                long[] targetPlacementIds = new long[] { long.Parse(_T("INSERT_PLACEMENT_ID_HERE")) };

                // Set the ID of the advertiser (company) to forecast for. Setting an advertiser
                // will cause the forecast to apply the appropriate unified blocking rules.
                long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE"));

                // Create prospective line item.
                LineItem lineItem = new LineItem();

                lineItem.targeting = new Targeting();
                lineItem.targeting.inventoryTargeting = new InventoryTargeting();
                lineItem.targeting.inventoryTargeting.targetedPlacementIds = targetPlacementIds;

                Size size = new Size();
                size.width  = 300;
                size.height = 250;

                // Create the creative placeholder.
                CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
                creativePlaceholder.size = size;

                lineItem.creativePlaceholders = new CreativePlaceholder[] { creativePlaceholder };

                lineItem.lineItemType      = LineItemType.SPONSORSHIP;
                lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;

                // Set the line item to run for one month.
                lineItem.endDateTime =
                    DateTimeUtilities.FromDateTime(System.DateTime.Now.AddMonths(1), "America/New_York");

                // Set the cost type to match the unit type.
                lineItem.costType = CostType.CPM;
                Goal goal = new Goal();
                goal.goalType        = GoalType.DAILY;
                goal.unitType        = UnitType.IMPRESSIONS;
                goal.units           = 50L;
                lineItem.primaryGoal = goal;

                try {
                    // Get availability forecast.
                    AvailabilityForecastOptions options = new AvailabilityForecastOptions();
                    options.includeContendingLineItems        = true;
                    options.includeTargetingCriteriaBreakdown = true;
                    ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem();
                    prospectiveLineItem.advertiserId = advertiserId;
                    prospectiveLineItem.lineItem     = lineItem;
                    AvailabilityForecast forecast =
                        forecastService.getAvailabilityForecast(prospectiveLineItem, options);

                    // Display results.
                    long   matched          = forecast.matchedUnits;
                    double availablePercent = (double)(forecast.availableUnits / (matched * 1.0)) * 100;
                    String unitType         = forecast.unitType.ToString().ToLower();
                    Console.WriteLine("{0} {1} matched.\n{2}% {3} available.", matched, unitType,
                                      availablePercent, unitType);

                    if (forecast.possibleUnitsSpecified)
                    {
                        double possiblePercent = (double)(forecast.possibleUnits / (matched * 1.0)) * 100;
                        Console.WriteLine("{0}% {1} possible.\n", possiblePercent, unitType);
                    }
                    Console.WriteLine("{0} contending line items.", (forecast.contendingLineItems != null) ?
                                      forecast.contendingLineItems.Length : 0);
                } catch (Exception e) {
                    Console.WriteLine("Failed to get forecast. Exception says \"{0}\"", e.Message);
                }
            }
        }
Ejemplo n.º 6
0
 public static void RenderDatePicker(TextWriter writer, string id, ExDateTime selectedDate, DatePicker.Features datePickerFeatures, bool isEnabled)
 {
     DatePickerDropDownCombo.RenderDatePicker(writer, id, selectedDate, DateTimeUtilities.GetLocalTime(), datePickerFeatures, isEnabled);
 }
        public void TestCreateLineItems()
        {
            // Create inventory targeting.
            InventoryTargeting inventoryTargeting = new InventoryTargeting();

            inventoryTargeting.targetedPlacementIds = new long[] { placementId };

            // Create geographical targeting.
            GeoTargeting geoTargeting = new GeoTargeting();

            // Include the US and Quebec, Canada.
            Location countryLocation = new Location();

            countryLocation.id = 2840L;

            Location regionLocation = new Location();

            regionLocation.id = 20123L;
            geoTargeting.targetedLocations = new Location[] { countryLocation, regionLocation };

            // Exclude Chicago and the New York metro area.
            Location cityLocation = new Location();

            cityLocation.id = 1016367L;

            Location metroLocation = new Location();

            metroLocation.id = 200501L;
            geoTargeting.excludedLocations = new Location[] { cityLocation, metroLocation };

            // Exclude domains that are not under the network's control.
            UserDomainTargeting userDomainTargeting = new UserDomainTargeting();

            userDomainTargeting.domains  = new String[] { "usa.gov" };
            userDomainTargeting.targeted = false;

            // Create day-part targeting.
            DayPartTargeting dayPartTargeting = new DayPartTargeting();

            dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER;

            // Target only the weekend in the browser's timezone.
            DayPart saturdayDayPart = new DayPart();

            saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201602.DayOfWeek.SATURDAY;

            saturdayDayPart.startTime        = new TimeOfDay();
            saturdayDayPart.startTime.hour   = 0;
            saturdayDayPart.startTime.minute = MinuteOfHour.ZERO;

            saturdayDayPart.endTime        = new TimeOfDay();
            saturdayDayPart.endTime.hour   = 24;
            saturdayDayPart.endTime.minute = MinuteOfHour.ZERO;

            DayPart sundayDayPart = new DayPart();

            sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201602.DayOfWeek.SUNDAY;

            sundayDayPart.startTime        = new TimeOfDay();
            sundayDayPart.startTime.hour   = 0;
            sundayDayPart.startTime.minute = MinuteOfHour.ZERO;

            sundayDayPart.endTime        = new TimeOfDay();
            sundayDayPart.endTime.hour   = 24;
            sundayDayPart.endTime.minute = MinuteOfHour.ZERO;

            dayPartTargeting.dayParts = new DayPart[] { saturdayDayPart, sundayDayPart };


            // Create technology targeting.
            TechnologyTargeting technologyTargeting = new TechnologyTargeting();

            // Create browser targeting.
            BrowserTargeting browserTargeting = new BrowserTargeting();

            browserTargeting.isTargeted = true;

            // Target just the Chrome browser.
            Technology browserTechnology = new Technology();

            browserTechnology.id                 = 500072L;
            browserTargeting.browsers            = new Technology[] { browserTechnology };
            technologyTargeting.browserTargeting = browserTargeting;

            // Create an array to store local line item objects.
            LineItem[] lineItems = new LineItem[2];

            for (int i = 0; i < lineItems.Length; i++)
            {
                LineItem lineItem = new LineItem();
                lineItem.name      = "Line item #" + new TestUtils().GetTimeStamp();
                lineItem.orderId   = orderId;
                lineItem.targeting = new Targeting();

                lineItem.targeting.inventoryTargeting  = inventoryTargeting;
                lineItem.targeting.geoTargeting        = geoTargeting;
                lineItem.targeting.userDomainTargeting = userDomainTargeting;
                lineItem.targeting.dayPartTargeting    = dayPartTargeting;
                lineItem.targeting.technologyTargeting = technologyTargeting;

                lineItem.lineItemType  = LineItemType.STANDARD;
                lineItem.allowOverbook = true;

                // Set the creative rotation type to even.
                lineItem.creativeRotationType = CreativeRotationType.EVEN;

                // Set the size of creatives that can be associated with this line item.
                Size size = new Size();
                size.width         = 300;
                size.height        = 250;
                size.isAspectRatio = false;

                // Create the creative placeholder.
                CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
                creativePlaceholder.size = size;

                lineItem.creativePlaceholders = new CreativePlaceholder[] { creativePlaceholder };

                // Set the line item to run for one month.
                lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
                lineItem.endDateTime       =
                    DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1), "America/New_York");

                // Set the cost per unit to $2.
                lineItem.costType    = CostType.CPM;
                lineItem.costPerUnit = new Money();
                lineItem.costPerUnit.currencyCode = "USD";
                lineItem.costPerUnit.microAmount  = 2000000L;

                // Set the number of units bought to 500,000 so that the budget is
                // $1,000.
                Goal goal = new Goal();
                goal.units           = 500000L;
                goal.unitType        = UnitType.IMPRESSIONS;
                lineItem.primaryGoal = goal;

                lineItems[i] = lineItem;
            }

            LineItem[] localLineItems = null;

            Assert.DoesNotThrow(delegate() {
                localLineItems = lineItemService.createLineItems(lineItems);
            });

            Assert.NotNull(localLineItems);
            Assert.AreEqual(localLineItems.Length, 2);

            Assert.AreEqual(localLineItems[0].name, lineItems[0].name);
            Assert.AreEqual(localLineItems[0].orderId, lineItems[0].orderId);

            Assert.AreEqual(localLineItems[1].name, lineItems[1].name);
            Assert.AreEqual(localLineItems[1].orderId, lineItems[1].orderId);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (ReportService reportService =
                       (ReportService)user.GetService(DfpService.v201802.ReportService))
            {
                // Set the file path where the report will be saved.
                String filePath = _T("INSERT_FILE_PATH_HERE");

                long orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));

                // Create report job.
                ReportJob reportJob = new ReportJob();
                reportJob.reportQuery            = new ReportQuery();
                reportJob.reportQuery.dimensions = new Dimension[]
                {
                    Dimension.ORDER_ID,
                    Dimension.ORDER_NAME
                };
                reportJob.reportQuery.dimensionAttributes = new DimensionAttribute[]
                {
                    DimensionAttribute.ORDER_TRAFFICKER,
                    DimensionAttribute.ORDER_START_DATE_TIME,
                    DimensionAttribute.ORDER_END_DATE_TIME
                };
                reportJob.reportQuery.columns = new Column[]
                {
                    Column.AD_SERVER_IMPRESSIONS,
                    Column.AD_SERVER_CLICKS,
                    Column.AD_SERVER_CTR,
                    Column.AD_SERVER_CPM_AND_CPC_REVENUE,
                    Column.AD_SERVER_WITHOUT_CPD_AVERAGE_ECPM
                };

                // Set a custom date range for the last 8 days
                reportJob.reportQuery.dateRangeType = DateRangeType.CUSTOM_DATE;
                System.DateTime endDateTime = System.DateTime.Now;
                reportJob.reportQuery.startDate = DateTimeUtilities
                                                  .FromDateTime(endDateTime.AddDays(-8), "America/New_York").date;
                reportJob.reportQuery.endDate = DateTimeUtilities
                                                .FromDateTime(endDateTime, "America/New_York").date;

                // Create statement object to filter for an order.
                StatementBuilder statementBuilder = new StatementBuilder().Where("ORDER_ID = :id")
                                                    .AddValue("id", orderId);
                reportJob.reportQuery.statement = statementBuilder.ToStatement();

                try
                {
                    // Run report job.
                    reportJob = reportService.runReportJob(reportJob);

                    ReportUtilities reportUtilities =
                        new ReportUtilities(reportService, reportJob.id);

                    // Set download options.
                    ReportDownloadOptions options = new ReportDownloadOptions();
                    options.exportFormat                  = ExportFormat.CSV_DUMP;
                    options.useGzipCompression            = true;
                    reportUtilities.reportDownloadOptions = options;

                    // Download the report.
                    using (ReportResponse reportResponse = reportUtilities.GetResponse())
                    {
                        reportResponse.Save(filePath);
                    }

                    Console.WriteLine("Report saved to \"{0}\".", filePath);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to run delivery report. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(AdManagerUser user, long proposalId)
        {
            using (ProposalLineItemService proposalLineItemService =
                       user.GetService <ProposalLineItemService>())

                using (NetworkService networkService = user.GetService <NetworkService>())
                {
                    ProposalLineItem proposalLineItem = new ProposalLineItem();
                    proposalLineItem.name = "Programmatic proposal line item #" +
                                            new Random().Next(int.MaxValue);
                    proposalLineItem.proposalId   = proposalId;
                    proposalLineItem.lineItemType = LineItemType.STANDARD;

                    // Set required Marketplace information.
                    proposalLineItem.marketplaceInfo = new ProposalLineItemMarketplaceInfo()
                    {
                        adExchangeEnvironment = AdExchangeEnvironment.DISPLAY
                    };

                    // Get the root ad unit ID used to target the whole site.
                    String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

                    // Create inventory targeting.
                    InventoryTargeting inventoryTargeting = new InventoryTargeting();

                    // Create ad unit targeting for the root ad unit (i.e. the whole network).
                    AdUnitTargeting adUnitTargeting = new AdUnitTargeting();
                    adUnitTargeting.adUnitId           = rootAdUnitId;
                    adUnitTargeting.includeDescendants = true;

                    inventoryTargeting.targetedAdUnits = new AdUnitTargeting[]
                    {
                        adUnitTargeting
                    };

                    // Create targeting.
                    Targeting targeting = new Targeting();
                    targeting.inventoryTargeting = inventoryTargeting;
                    proposalLineItem.targeting   = targeting;

                    // Create creative placeholder.
                    Size size = new Size()
                    {
                        width         = 300,
                        height        = 250,
                        isAspectRatio = false
                    };
                    CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
                    creativePlaceholder.size = size;

                    proposalLineItem.creativePlaceholders = new CreativePlaceholder[]
                    {
                        creativePlaceholder
                    };

                    // Set the length of the proposal line item to run.
                    proposalLineItem.startDateTime =
                        DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(7),
                                                       "America/New_York");
                    proposalLineItem.endDateTime =
                        DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(30),
                                                       "America/New_York");

                    // Set delivery specifications for the proposal line item.
                    proposalLineItem.deliveryRateType = DeliveryRateType.EVENLY;

                    // Set pricing for the proposal line item for 1000 impressions at a CPM of $2
                    // for a total value of $2.
                    proposalLineItem.goal = new Goal()
                    {
                        unitType = UnitType.IMPRESSIONS,
                        units    = 1000L
                    };
                    proposalLineItem.netCost = new Money()
                    {
                        currencyCode = "USD",
                        microAmount  = 2000000L
                    };
                    proposalLineItem.netRate = new Money()
                    {
                        currencyCode = "USD",
                        microAmount  = 2000000L
                    };
                    proposalLineItem.rateType = RateType.CPM;

                    try
                    {
                        // Create the proposal line item on the server.
                        ProposalLineItem[] proposalLineItems =
                            proposalLineItemService.createProposalLineItems(new ProposalLineItem[]
                        {
                            proposalLineItem
                        });

                        foreach (ProposalLineItem createdProposalLineItem in proposalLineItems)
                        {
                            Console.WriteLine(
                                "A programmatic proposal line item with ID \"{0}\" " +
                                "and name \"{1}\" was created.", createdProposalLineItem.id,
                                createdProposalLineItem.name);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(
                            "Failed to create programmatic proposal line items. " +
                            "Exception says \"{0}\"", e.Message);
                    }
                }
        }
Ejemplo n.º 10
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            this.infobar.SetInfobarClass("infobarEdit");
            this.infobar.SetShouldHonorHideByDefault(true);
            this.calendarItemBase = base.Initialize <CalendarItemBase>(false, new PropertyDefinition[]
            {
                CalendarItemBaseSchema.CalendarItemType,
                StoreObjectSchema.EffectiveRights
            });
            if (this.calendarItemBase != null)
            {
                if (string.Equals(base.OwaContext.FormsRegistryContext.Action, "Open", StringComparison.OrdinalIgnoreCase))
                {
                    this.newItemType = NewItemType.ExplicitDraft;
                }
                else
                {
                    this.newItemType         = NewItemType.ImplicitDraft;
                    base.DeleteExistingDraft = true;
                }
            }
            else
            {
                this.calendarItemBase = Utilities.CreateDraftMeetingRequestFromQueryString(base.UserContext, base.Request, new PropertyDefinition[]
                {
                    StoreObjectSchema.EffectiveRights
                });
                if (this.calendarItemBase != null)
                {
                    this.newItemType         = NewItemType.ImplicitDraft;
                    base.DeleteExistingDraft = true;
                    base.Item = this.calendarItemBase;
                }
            }
            if (this.calendarItemBase != null)
            {
                this.isMeeting = this.calendarItemBase.IsMeeting;
                this.startTime = this.calendarItemBase.StartTime;
                this.endTime   = this.calendarItemBase.EndTime;
                if (this.calendarItemBase.IsAllDayEvent && !this.IsRecurringMaster)
                {
                    this.endTime = this.endTime.IncrementDays(-1);
                }
                this.recipientWell       = new CalendarItemRecipientWell(this.calendarItemBase);
                this.bodyMarkup          = BodyConversionUtilities.GetBodyFormatOfEditItem(this.calendarItemBase, this.newItemType, base.UserContext.UserOptions);
                this.toolbar             = new EditCalendarItemToolbar(this.calendarItemBase, this.isMeeting, this.bodyMarkup, this.IsPublicItem);
                this.toolbar.ToolbarType = (base.IsPreviewForm ? ToolbarType.Preview : ToolbarType.Form);
                this.isBeingCanceled     = (Utilities.GetQueryStringParameter(base.Request, "c", false) != null);
                string queryStringParameter = Utilities.GetQueryStringParameter(base.Request, "er", false);
                if (queryStringParameter != null)
                {
                    if (this.calendarItemBase.CalendarItemType != CalendarItemType.RecurringMaster || !(this.calendarItemBase is CalendarItem))
                    {
                        throw new OwaInvalidRequestException("Invalid calendar item type.  Only recurring masters support specifying an end range");
                    }
                    this.endRange = ExDateTime.MinValue;
                    try
                    {
                        this.endRange = DateTimeUtilities.ParseIsoDate(queryStringParameter, base.UserContext.TimeZone);
                    }
                    catch (OwaParsingErrorException)
                    {
                        ExTraceGlobals.CalendarDataTracer.TraceDebug <string>((long)this.GetHashCode(), "Invalid end range provided on URL '{0}'", queryStringParameter);
                        throw new OwaInvalidRequestException(string.Format("Invalid end range provided on URL '{0}'", queryStringParameter));
                    }
                    if (this.endRange != ExDateTime.MinValue)
                    {
                        CalendarItem calendarItem = (CalendarItem)this.calendarItemBase;
                        this.occurrenceCount = MeetingUtilities.CancelRecurrence(calendarItem, this.endRange);
                        if (this.occurrenceCount == 0)
                        {
                            this.isBeingCanceled = true;
                        }
                    }
                }
                string queryStringParameter2 = Utilities.GetQueryStringParameter(base.Request, "od", false);
                if (queryStringParameter2 != null)
                {
                    try
                    {
                        this.occurrenceDate = DateTimeUtilities.ParseIsoDate(queryStringParameter2, base.UserContext.TimeZone).Date;
                        goto IL_303;
                    }
                    catch (OwaParsingErrorException)
                    {
                        ExTraceGlobals.CalendarDataTracer.TraceDebug <string>((long)this.GetHashCode(), "Invalid occurrence date specified on URL '{0}'", queryStringParameter2);
                        throw new OwaInvalidRequestException(string.Format("Invalid occurrence date provided on URL '{0}'", queryStringParameter2));
                    }
                }
                this.occurrenceDate = DateTimeUtilities.GetLocalTime().Date;
IL_303:
                CalendarUtilities.AddCalendarInfobarMessages(this.infobar, this.calendarItemBase, null, base.UserContext);
                if (this.isBeingCanceled)
                {
                    this.infobar.AddMessage(SanitizedHtmlString.FromStringId(1328030972), InfobarMessageType.Informational);
                }
                this.disableOccurrenceReminderUI = MeetingUtilities.CheckShouldDisableOccurrenceReminderUI(this.calendarItemBase);
                if (this.disableOccurrenceReminderUI && !this.IsPublicItem)
                {
                    this.infobar.AddMessage(SanitizedHtmlString.FromStringId(-891369593), InfobarMessageType.Informational);
                }
                if (!(this.calendarItemBase is CalendarItem))
                {
                    this.recurrenceUtilities = new RecurrenceUtilities(null, base.SanitizingResponse);
                    return;
                }
                if (0 < this.occurrenceCount)
                {
                    EndDateRecurrenceRange range = new EndDateRecurrenceRange(((CalendarItem)this.calendarItemBase).Recurrence.Range.StartDate, this.endRange.IncrementDays(-1));
                    this.recurrenceUtilities = new RecurrenceUtilities(new Recurrence(((CalendarItem)this.calendarItemBase).Recurrence.Pattern, range), base.SanitizingResponse);
                    return;
                }
                this.recurrenceUtilities = new RecurrenceUtilities(((CalendarItem)this.calendarItemBase).Recurrence, base.SanitizingResponse);
                return;
            }
            else
            {
                this.isMeeting = (Utilities.GetQueryStringParameter(base.Request, "mr", false) != null);
                if (this.isMeeting && this.IsPublicItem)
                {
                    throw new OwaInvalidRequestException("Can't create meeting in Owa Public Folders");
                }
                this.isAllDayEvent = (Utilities.GetQueryStringParameter(base.Request, "evt", false) != null);
                bool   flag = Utilities.GetQueryStringParameter(base.Request, "tm", false) != null || this.isAllDayEvent;
                string queryStringParameter3 = Utilities.GetQueryStringParameter(base.Request, "st", false);
                if (queryStringParameter3 != null)
                {
                    try
                    {
                        this.startTime = DateTimeUtilities.ParseIsoDate(queryStringParameter3, base.UserContext.TimeZone);
                    }
                    catch (OwaParsingErrorException)
                    {
                        ExTraceGlobals.CalendarDataTracer.TraceDebug <string>((long)this.GetHashCode(), "Invalid start date provided on URL '{0}'", queryStringParameter3);
                        throw new OwaInvalidRequestException(string.Format("Invalid start date provided on URL '{0}'", queryStringParameter3));
                    }
                }
                if (flag || this.startTime == ExDateTime.MinValue)
                {
                    ExDateTime localTime = DateTimeUtilities.GetLocalTime();
                    if (this.startTime == ExDateTime.MinValue)
                    {
                        this.startTime = new ExDateTime(base.UserContext.TimeZone, localTime.Year, localTime.Month, localTime.Day, localTime.Hour, localTime.Minute, 0);
                    }
                    else
                    {
                        this.startTime = new ExDateTime(base.UserContext.TimeZone, this.startTime.Year, this.startTime.Month, this.startTime.Day, localTime.Hour, localTime.Minute, 0);
                    }
                    if (this.isAllDayEvent && this.startTime.Hour == 23)
                    {
                        if (this.startTime.Minute >= 30)
                        {
                            this.startTime = this.startTime.Date;
                        }
                        else
                        {
                            this.startTime = new ExDateTime(base.UserContext.TimeZone, this.startTime.Year, this.startTime.Month, this.startTime.Day, 23, 0, 0);
                            this.endTime   = new ExDateTime(base.UserContext.TimeZone, this.startTime.Year, this.startTime.Month, this.startTime.Day, 23, 30, 0);
                        }
                    }
                    else if (this.startTime.Minute != 0 && this.startTime.Minute != 30)
                    {
                        this.startTime = this.startTime.AddMinutes((double)(30 - this.startTime.Minute % 30));
                    }
                }
                if (this.endTime == ExDateTime.MinValue)
                {
                    this.endTime = this.startTime.AddMinutes(60.0);
                }
                this.recipientWell       = new CalendarItemRecipientWell();
                this.bodyMarkup          = base.UserContext.UserOptions.ComposeMarkup;
                this.toolbar             = new EditCalendarItemToolbar(null, this.isMeeting, this.bodyMarkup, this.IsPublicItem);
                this.toolbar.ToolbarType = (base.IsPreviewForm ? ToolbarType.Preview : ToolbarType.Form);
                this.recurrenceUtilities = new RecurrenceUtilities(null, base.SanitizingResponse);
                return;
            }
        }
        private double RandMult(SecureRandom random, ECPoint g, BigInteger n)
        {
            BigInteger[] ks = new BigInteger[128];
            for (int i = 0; i < ks.Length; ++i)
            {
                ks[i] = new BigInteger(n.BitLength - 1, random);
            }

            int     ki = 0;
            ECPoint p  = g;

            {
                long startTime = DateTimeUtilities.CurrentUnixMs();
                long goalTime  = startTime + MILLIS_WARMUP;

                do
                {
                    BigInteger k = ks[ki];
                    p = g.Multiply(k);
                    if ((ki & 1) != 0)
                    {
                        g = p;
                    }
                    if (++ki == ks.Length)
                    {
                        ki = 0;
                    }
                }while (DateTimeUtilities.CurrentUnixMs() < goalTime);
            }

            double minRate = Double.MaxValue, maxRate = Double.MinValue, totalRate = 0.0;

            for (int i = 1; i <= NUM_ROUNDS; i++)
            {
                long startTime = DateTimeUtilities.CurrentUnixMs();
                long goalTime = startTime + MILLIS_PER_ROUND;
                long count = 0, endTime;

                do
                {
                    ++count;

                    for (int j = 0; j < MULTS_PER_CHECK; ++j)
                    {
                        BigInteger k = ks[ki];
                        p = g.Multiply(k);
                        if ((ki & 1) != 0)
                        {
                            g = p;
                        }
                        if (++ki == ks.Length)
                        {
                            ki = 0;
                        }
                    }

                    endTime = DateTimeUtilities.CurrentUnixMs();
                }while (endTime < goalTime);

                double roundElapsed = (double)(endTime - startTime);
                double roundRate    = count * MULTS_PER_CHECK * 1000L / roundElapsed;

                minRate    = System.Math.Min(minRate, roundRate);
                maxRate    = System.Math.Max(maxRate, roundRate);
                totalRate += roundRate;
            }

            return((totalRate - minRate - maxRate) / (NUM_ROUNDS - 2));
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (LineItemService lineItemService = user.GetService <LineItemService>())
            {
                // Set the order that all created line items will belong to and the
                // video ad unit ID to target.
                long   orderId = long.Parse(_T("INSERT_ORDER_ID_HERE"));
                string targetedVideoAdUnitId = _T("INSERT_TARGETED_VIDEO_AD_UNIT_ID_HERE");

                // Set the content bundle to target
                long contentBundleId =
                    long.Parse(_T("INSERT_CONTENT_BUNDLE_ID_HERE"));

                // Set the CMS metadata value to target
                long cmsMetadataValueId =
                    long.Parse(_T("INSERT_CMS_METADATA_VALUE_ID_HERE"));

                // Create content targeting.
                ContentTargeting contentTargeting = new ContentTargeting()
                {
                    targetedVideoContentBundleIds = new long[] { contentBundleId }
                };

                // Create inventory targeting.
                InventoryTargeting inventoryTargeting = new InventoryTargeting()
                {
                    targetedAdUnits = new AdUnitTargeting[] {
                        new AdUnitTargeting()
                        {
                            adUnitId           = targetedVideoAdUnitId,
                            includeDescendants = true
                        }
                    }
                };

                // Create video position targeting.
                VideoPositionTargeting videoPositionTargeting = new VideoPositionTargeting()
                {
                    targetedPositions = new VideoPositionTarget[] {
                        new VideoPositionTarget()
                        {
                            videoPosition = new VideoPosition()
                            {
                                positionType = VideoPositionType.PREROLL
                            }
                        }
                    }
                };

                // Target only video platforms
                RequestPlatformTargeting requestPlatformTargeting = new RequestPlatformTargeting()
                {
                    targetedRequestPlatforms = new RequestPlatform[] {
                        RequestPlatform.VIDEO_PLAYER
                    }
                };

                // Create custom criteria set
                CustomCriteriaSet customCriteriaSet = new CustomCriteriaSet()
                {
                    logicalOperator = CustomCriteriaSetLogicalOperator.AND,
                    children        = new CustomCriteriaNode[] {
                        new CmsMetadataCriteria()
                        {
                            cmsMetadataValueIds = new long[] { cmsMetadataValueId },
                            @operator           = CmsMetadataCriteriaComparisonOperator.EQUALS
                        }
                    }
                };

                // Create targeting.
                Targeting targeting = new Targeting()
                {
                    contentTargeting         = contentTargeting,
                    inventoryTargeting       = inventoryTargeting,
                    videoPositionTargeting   = videoPositionTargeting,
                    requestPlatformTargeting = requestPlatformTargeting,
                    customTargeting          = customCriteriaSet
                };

                // Create local line item object.
                LineItem lineItem = new LineItem()
                {
                    name                 = "Video line item - " + this.GetTimeStamp(),
                    orderId              = orderId,
                    targeting            = targeting,
                    lineItemType         = LineItemType.SPONSORSHIP,
                    allowOverbook        = true,
                    environmentType      = EnvironmentType.VIDEO_PLAYER,
                    creativeRotationType = CreativeRotationType.OPTIMIZED
                };


                // Create the master creative placeholder.
                CreativePlaceholder creativeMasterPlaceholder = new CreativePlaceholder()
                {
                    size = new Size()
                    {
                        width         = 400,
                        height        = 300,
                        isAspectRatio = false
                    }
                };

                // Create companion creative placeholders.
                CreativePlaceholder companionCreativePlaceholder1 = new CreativePlaceholder()
                {
                    size = new Size()
                    {
                        width         = 300,
                        height        = 250,
                        isAspectRatio = false
                    }
                };

                CreativePlaceholder companionCreativePlaceholder2 = new CreativePlaceholder()
                {
                    size = new Size()
                    {
                        width         = 728,
                        height        = 90,
                        isAspectRatio = false
                    }
                };

                // Set companion creative placeholders.
                creativeMasterPlaceholder.companions = new CreativePlaceholder[]
                {
                    companionCreativePlaceholder1,
                    companionCreativePlaceholder2
                };

                // Set the size of creatives that can be associated with this line item.
                lineItem.creativePlaceholders = new CreativePlaceholder[]
                {
                    creativeMasterPlaceholder
                };

                // Set delivery of video companions to optional.
                lineItem.companionDeliveryOption = CompanionDeliveryOption.OPTIONAL;

                // Set the line item to run for one month.
                lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
                lineItem.endDateTime       =
                    DateTimeUtilities.FromDateTime(System.DateTime.Now.AddMonths(1),
                                                   "America/New_York");

                // Set the cost per day to $1.
                lineItem.costType    = CostType.CPD;
                lineItem.costPerUnit = new Money()
                {
                    currencyCode = "USD",
                    microAmount  = 1000000L
                };

                // Set the percentage to be 100%.
                lineItem.primaryGoal = new Goal()
                {
                    goalType = GoalType.DAILY,
                    unitType = UnitType.IMPRESSIONS,
                    units    = 100
                };

                try
                {
                    // Create the line item on the server.
                    LineItem[] createdLineItems = lineItemService.createLineItems(new LineItem[]
                    {
                        lineItem
                    });

                    foreach (LineItem createdLineItem in createdLineItems)
                    {
                        Console.WriteLine(
                            "A line item with ID \"{0}\", belonging to order ID \"{1}\", and " +
                            "named \"{2}\" was created.", createdLineItem.id,
                            createdLineItem.orderId, createdLineItem.name);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to create line items. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Ejemplo n.º 13
0
        public void GeneraListado()
        {
            oWord = new Application();
            oDoc  = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            oDoc.PageSetup.Orientation = WdOrientation.wdOrientPortrait;


            try
            {
                //Insert a paragraph at the beginning of the document.
                Paragraph oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
                //oPara1.Range.ParagraphFormat.Space1;
                oPara1.Range.Text = "SUPREMA CORTE DE JUSTICIA DE LA NACIÓN";

                oPara1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                oPara1.Range.Font.Bold   = 1;
                oPara1.Range.Font.Size   = 10;
                oPara1.Range.Font.Name   = "Arial";
                oPara1.Format.SpaceAfter = 0;    //24 pt spacing after paragraph.
                oPara1.Range.InsertParagraphAfter();
                oPara1.Range.InsertParagraphAfter();
                oPara1.Range.Text = "COORDINACIÓN DE COMPILACIÓN Y ";
                oPara1.Range.InsertParagraphAfter();
                oPara1.Range.Text = "SISTEMATIZACIÓN DE TESIS";
                oPara1.Range.InsertParagraphAfter();
                oPara1.Range.InsertParagraphAfter();
                oPara1.Range.Text = "RELACIÓN DE TESIS PARA PUBLICAR EN EL SEMANARIO JUDICIAL DE LA FEDERACIÓN Y EN SU GACETA";
                oPara1.Range.InsertParagraphAfter();
                oPara1.Range.InsertParagraphAfter();
                oPara1.Range.Text = String.Format("(AL {0})", DateTimeUtilities.ToLongDateFormat(fechaEnvio).ToUpper());
                oPara1.Range.InsertParagraphAfter();
                oPara1.Range.Text = String.Format("TOTAL:   {0} TESIS", tesisImprimir.Count());
                oPara1.Range.InsertParagraphAfter();
                oPara1.Range.InsertParagraphAfter();


                //Tesis de jurisprudencia del Pleno
                List <Tesis> imprime = this.GetPrintableSectionTesis(100, 10006, 1);
                this.PrintTable(imprime, 100, 10006, 1);

                //Tesis Aisladas del Pleno
                imprime = this.GetPrintableSectionTesis(100, 10006, 0);
                this.PrintTable(imprime, 100, 10006, 0);

                //Tesis de jurisprudencia de la Primera Sala
                imprime = this.GetPrintableSectionTesis(100, 10001, 1);
                this.PrintTable(imprime, 100, 10001, 1);

                //Tesis aisladas de la Primera Sala
                imprime = this.GetPrintableSectionTesis(100, 10001, 0);
                this.PrintTable(imprime, 100, 10001, 0);

                //Tesis de jurisprudencia de la Segunda Sala
                imprime = this.GetPrintableSectionTesis(100, 10002, 1);
                this.PrintTable(imprime, 100, 10002, 1);

                //Tesis aisladas de la Segunda Sala
                imprime = this.GetPrintableSectionTesis(100, 10002, 0);
                this.PrintTable(imprime, 100, 10002, 0);

                //Tesis de jurisprudencia de Plenos de Circuito
                imprime = this.GetPrintableSectionTesis(4, 0, 1);
                this.PrintTable(imprime, 4, 0, 1);

                //Tesis aisladas de Plenos de Circuito
                imprime = this.GetPrintableSectionTesis(4, 0, 0);
                this.PrintTable(imprime, 4, 0, 0);

                //Tesis de jurisprudencia de Tribunales Colegiados de Circuito
                imprime = this.GetPrintableSectionTesis(1, 0, 1);
                this.PrintTable(imprime, 1, 0, 1);

                //Tesis aisladas de Tribunales Colegiados de Circuito
                imprime = this.GetPrintableSectionTesis(1, 0, 0);
                this.PrintTable(imprime, 1, 0, 0);


                foreach (Section wordSection in oDoc.Sections)
                {
                    object pagealign = WdPageNumberAlignment.wdAlignPageNumberRight;
                    object firstpage = true;
                    wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].PageNumbers.Add(ref pagealign, ref firstpage);
                }

                oWord.ActiveDocument.SaveAs(filepath);
                oWord.ActiveDocument.Saved = true;
            }
            catch (Exception ex)
            {
                string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                ErrorUtilities.SetNewErrorMessage(ex, methodName + " Exception,Listado", "ListadoDeTesis");
            }
            finally
            {
                oWord.Visible = true;
                //oDoc.Close();
            }
        }
Ejemplo n.º 14
0
        internal SignaturePacket(
            BcpgInputStream bcpgIn)
        {
            version = bcpgIn.ReadByte();

            if (version == 3 || version == 2)
            {
//                int l =
                bcpgIn.ReadByte();

                signatureType = bcpgIn.ReadByte();
                creationTime  = (((long)bcpgIn.ReadByte() << 24) | ((long)bcpgIn.ReadByte() << 16)
                                 | ((long)bcpgIn.ReadByte() << 8) | (uint)bcpgIn.ReadByte()) * 1000L;

                keyId |= (long)bcpgIn.ReadByte() << 56;
                keyId |= (long)bcpgIn.ReadByte() << 48;
                keyId |= (long)bcpgIn.ReadByte() << 40;
                keyId |= (long)bcpgIn.ReadByte() << 32;
                keyId |= (long)bcpgIn.ReadByte() << 24;
                keyId |= (long)bcpgIn.ReadByte() << 16;
                keyId |= (long)bcpgIn.ReadByte() << 8;
                keyId |= (uint)bcpgIn.ReadByte();

                keyAlgorithm  = (PublicKeyAlgorithmTag)bcpgIn.ReadByte();
                hashAlgorithm = (HashAlgorithmTag)bcpgIn.ReadByte();
            }
            else if (version == 4)
            {
                signatureType = bcpgIn.ReadByte();
                keyAlgorithm  = (PublicKeyAlgorithmTag)bcpgIn.ReadByte();
                hashAlgorithm = (HashAlgorithmTag)bcpgIn.ReadByte();

                int    hashedLength = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte();
                byte[] hashed       = new byte[hashedLength];

                bcpgIn.ReadFully(hashed);

                //
                // read the signature sub packet data.
                //
                SignatureSubpacketsParser sIn = new SignatureSubpacketsParser(
                    new MemoryStream(hashed, false));

                ArrayList          v = new ArrayList();
                SignatureSubpacket sub;
                while ((sub = sIn.ReadPacket()) != null)
                {
                    v.Add(sub);
                }

                hashedData = new SignatureSubpacket[v.Count];

                for (int i = 0; i != hashedData.Length; i++)
                {
                    SignatureSubpacket p = (SignatureSubpacket)v[i];
                    if (p is IssuerKeyId)
                    {
                        keyId = ((IssuerKeyId)p).KeyId;
                    }
                    else if (p is SignatureCreationTime)
                    {
                        creationTime = DateTimeUtilities.DateTimeToUnixMs(
                            ((SignatureCreationTime)p).GetTime());
                    }

                    hashedData[i] = p;
                }

                int    unhashedLength = (bcpgIn.ReadByte() << 8) | bcpgIn.ReadByte();
                byte[] unhashed       = new byte[unhashedLength];

                bcpgIn.ReadFully(unhashed);

                sIn = new SignatureSubpacketsParser(new MemoryStream(unhashed, false));

                v.Clear();

                while ((sub = sIn.ReadPacket()) != null)
                {
                    v.Add(sub);
                }

                unhashedData = new SignatureSubpacket[v.Count];

                for (int i = 0; i != unhashedData.Length; i++)
                {
                    SignatureSubpacket p = (SignatureSubpacket)v[i];
                    if (p is IssuerKeyId)
                    {
                        keyId = ((IssuerKeyId)p).KeyId;
                    }
                    else if (p is SignatureCreationTime)
                    {
                        creationTime = DateTimeUtilities.DateTimeToUnixMs(
                            ((SignatureCreationTime)p).GetTime());
                    }

                    unhashedData[i] = (SignatureSubpacket)p;
                }
            }
            else
            {
                throw new Exception("unsupported version: " + version);
            }

            fingerprint = new byte[2];
            bcpgIn.ReadFully(fingerprint);

            switch (keyAlgorithm)
            {
            case PublicKeyAlgorithmTag.RsaGeneral:
            case PublicKeyAlgorithmTag.RsaSign:
                MPInteger v = new MPInteger(bcpgIn);
                signature = new MPInteger[] { v };
                break;

            case PublicKeyAlgorithmTag.Dsa:
                MPInteger r = new MPInteger(bcpgIn);
                MPInteger s = new MPInteger(bcpgIn);
                signature = new MPInteger[] { r, s };
                break;

            case PublicKeyAlgorithmTag.ElGamalEncrypt:     // yep, this really does happen sometimes.
            case PublicKeyAlgorithmTag.ElGamalGeneral:
                MPInteger p = new MPInteger(bcpgIn);
                MPInteger g = new MPInteger(bcpgIn);
                MPInteger y = new MPInteger(bcpgIn);
                signature = new MPInteger[] { p, g, y };
                break;

            default:
                throw new IOException("unknown signature key algorithm: " + keyAlgorithm);
            }
        }
Ejemplo n.º 15
0
        protected void RenderData(CalendarViewBase view, OwaStoreObjectId selectedItemId)
        {
            bool flag = true;
            int  num  = 0;

            if (view.RemovedItemCount > 0)
            {
                this.itemIndex = new Hashtable();
            }
            else
            {
                this.itemIndex = null;
            }
            this.selectedItemIndex = -1;
            TimeSpan       t = TimeSpan.MinValue;
            PositionInTime positionInTime = PositionInTime.None;
            int            num2           = 0;

            for (int i = 0; i < view.DataSource.Count; i++)
            {
                if (!view.IsItemRemoved(i))
                {
                    bool             flag2  = false;
                    OwaStoreObjectId itemId = view.DataSource.GetItemId(i);
                    if (view.DataSource.SharedType != SharedType.None)
                    {
                        flag2 = view.DataSource.IsPrivate(i);
                    }
                    if (!flag)
                    {
                        this.output.Write(",");
                    }
                    flag = false;
                    num2++;
                    if (this.itemIndex != null)
                    {
                        this.itemIndex[i] = num;
                        num++;
                    }
                    ExDateTime startTime = view.DataSource.GetStartTime(i);
                    ExDateTime endTime   = view.DataSource.GetEndTime(i);
                    if (flag2)
                    {
                        this.RenderPrivateAppointmentData(startTime, endTime);
                    }
                    else
                    {
                        this.RenderAppointmentData(view, i, startTime, endTime);
                    }
                    if (!flag2)
                    {
                        if (selectedItemId != null)
                        {
                            if (selectedItemId.Equals(itemId))
                            {
                                this.selectedItemIndex = ((this.itemIndex != null) ? ((int)this.itemIndex[i]) : i);
                            }
                        }
                        else
                        {
                            bool           flag3     = false;
                            TimeSpan       timeSpan  = TimeSpan.MinValue;
                            ExDateTime     localTime = DateTimeUtilities.GetLocalTime();
                            PositionInTime positionInTime2;
                            if (endTime < localTime)
                            {
                                positionInTime2 = PositionInTime.Past;
                            }
                            else if (startTime > localTime)
                            {
                                positionInTime2 = PositionInTime.Future;
                            }
                            else
                            {
                                positionInTime2 = PositionInTime.Present;
                            }
                            if (positionInTime2 == PositionInTime.Past)
                            {
                                timeSpan = localTime - endTime;
                                if (positionInTime == PositionInTime.Past)
                                {
                                    if (timeSpan < t)
                                    {
                                        flag3 = true;
                                    }
                                }
                                else if (positionInTime == PositionInTime.None)
                                {
                                    flag3 = true;
                                }
                            }
                            else if (positionInTime2 == PositionInTime.Present)
                            {
                                timeSpan = endTime - localTime;
                                if (positionInTime == PositionInTime.Present)
                                {
                                    if (timeSpan < t)
                                    {
                                        flag3 = true;
                                    }
                                }
                                else
                                {
                                    flag3 = true;
                                }
                            }
                            else if (positionInTime2 == PositionInTime.Future)
                            {
                                timeSpan = startTime - localTime;
                                if (positionInTime == PositionInTime.Future)
                                {
                                    timeSpan = startTime - localTime;
                                    if (timeSpan < t)
                                    {
                                        flag3 = true;
                                    }
                                }
                                else if (positionInTime == PositionInTime.Past || positionInTime == PositionInTime.None)
                                {
                                    flag3 = true;
                                }
                            }
                            if (flag3)
                            {
                                this.selectedItemIndex = ((this.itemIndex != null) ? ((int)this.itemIndex[i]) : i);
                                t = timeSpan;
                                positionInTime = positionInTime2;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 16
0
 internal static Timeout ForWaitMillis(int waitMillis)
 {
     return(ForWaitMillis(waitMillis, DateTimeUtilities.CurrentUnixMs()));
 }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (ForecastService forecastService = user.GetService <ForecastService>())
                using (NetworkService networkService = user.GetService <NetworkService>())
                {
                    // Set the ID of the advertiser (company) to forecast for. Setting an advertiser
                    // will cause the forecast to apply the appropriate unified blocking rules.
                    long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE"));

                    String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

                    System.DateTime tomorrow = System.DateTime.Now.AddDays(1);

                    // Create prospective line item.
                    LineItem lineItem = new LineItem()
                    {
                        targeting = new Targeting()
                        {
                            inventoryTargeting = new InventoryTargeting()
                            {
                                targetedAdUnits = new AdUnitTargeting[] {
                                    new AdUnitTargeting()
                                    {
                                        adUnitId           = rootAdUnitId,
                                        includeDescendants = true
                                    }
                                }
                            }
                        },
                        creativePlaceholders = new CreativePlaceholder[] {
                            new CreativePlaceholder()
                            {
                                size = new Size()
                                {
                                    width  = 300,
                                    height = 250
                                }
                            }
                        },
                        lineItemType = LineItemType.SPONSORSHIP,
                        // Set the line item to run for 5 days.
                        startDateTime = DateTimeUtilities.FromDateTime(
                            tomorrow, "America/New_York"),
                        endDateTime = DateTimeUtilities.FromDateTime(
                            tomorrow.AddDays(5), "America/New_York"),
                        // Set the cost type to match the unit type.
                        costType    = CostType.CPM,
                        primaryGoal = new Goal()
                        {
                            goalType = GoalType.DAILY,
                            unitType = UnitType.IMPRESSIONS,
                            units    = 50L
                        }
                    };

                    try
                    {
                        // Get availability forecast.
                        AvailabilityForecastOptions options = new AvailabilityForecastOptions()
                        {
                            includeContendingLineItems = true,
                            // Targeting criteria breakdown can only be included if breakdowns
                            // are not speficied.
                            includeTargetingCriteriaBreakdown = false,
                            breakdown = new ForecastBreakdownOptions
                            {
                                timeWindows = new DateTime[] {
                                    lineItem.startDateTime,
                                    DateTimeUtilities.FromDateTime(tomorrow.AddDays(1),
                                                                   "America/New_York"),
                                    DateTimeUtilities.FromDateTime(tomorrow.AddDays(2),
                                                                   "America/New_York"),
                                    DateTimeUtilities.FromDateTime(tomorrow.AddDays(3),
                                                                   "America/New_York"),
                                    DateTimeUtilities.FromDateTime(tomorrow.AddDays(4),
                                                                   "America/New_York"),
                                    lineItem.endDateTime
                                },
                                targets = new ForecastBreakdownTarget[] {
                                    new ForecastBreakdownTarget()
                                    {
                                        // Optional name field to identify this breakdown
                                        // in the response.
                                        name      = "United States",
                                        targeting = new Targeting()
                                        {
                                            inventoryTargeting = new InventoryTargeting()
                                            {
                                                targetedAdUnits = new AdUnitTargeting[] {
                                                    new AdUnitTargeting()
                                                    {
                                                        adUnitId           = rootAdUnitId,
                                                        includeDescendants = true
                                                    }
                                                }
                                            },
                                            geoTargeting = new GeoTargeting()
                                            {
                                                targetedLocations = new Location[] {
                                                    new Location()
                                                    {
                                                        id = 2840L
                                                    }
                                                }
                                            }
                                        }
                                    }, new ForecastBreakdownTarget()
                                    {
                                        // Optional name field to identify this breakdown
                                        // in the response.
                                        name      = "Geneva",
                                        targeting = new Targeting()
                                        {
                                            inventoryTargeting = new InventoryTargeting()
                                            {
                                                targetedAdUnits = new AdUnitTargeting[] {
                                                    new AdUnitTargeting()
                                                    {
                                                        adUnitId           = rootAdUnitId,
                                                        includeDescendants = true
                                                    }
                                                }
                                            },
                                            geoTargeting = new GeoTargeting()
                                            {
                                                targetedLocations = new Location[] {
                                                    new Location()
                                                    {
                                                        id = 20133L
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        };
                        ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem()
                        {
                            advertiserId = advertiserId,
                            lineItem     = lineItem
                        };
                        AvailabilityForecast forecast =
                            forecastService.getAvailabilityForecast(prospectiveLineItem, options);

                        // Display results.
                        long   matched          = forecast.matchedUnits;
                        double availablePercent =
                            (double)(forecast.availableUnits / (matched * 1.0)) * 100;
                        String unitType = forecast.unitType.ToString().ToLower();
                        Console.WriteLine($"{matched} {unitType} matched.");
                        Console.WriteLine($"{availablePercent}% {unitType} available.");

                        if (forecast.possibleUnitsSpecified)
                        {
                            double possiblePercent =
                                (double)(forecast.possibleUnits / (matched * 1.0)) * 100;
                            Console.WriteLine($"{possiblePercent}% {unitType} possible.");
                        }
                        var contendingLineItems =
                            forecast.contendingLineItems ?? new ContendingLineItem[] { };
                        Console.WriteLine($"{contendingLineItems.Length} contending line items.");

                        if (forecast.breakdowns != null)
                        {
                            foreach (ForecastBreakdown breakdown in forecast.breakdowns)
                            {
                                Console.WriteLine("Forecast breakdown for {0} to {1}",
                                                  DateTimeUtilities.ToString(breakdown.startTime, "yyyy-MM-dd"),
                                                  DateTimeUtilities.ToString(breakdown.endTime, "yyyy-MM-dd"));
                                foreach (ForecastBreakdownEntry entry in breakdown.breakdownEntries)
                                {
                                    Console.WriteLine($"\t{entry.name}");
                                    long breakdownMatched = entry.forecast.matched;
                                    Console.WriteLine($"\t\t{breakdownMatched} {unitType} matched.");
                                    if (breakdownMatched > 0)
                                    {
                                        long   breakdownAvailable        = entry.forecast.available;
                                        double breakdownAvailablePercent =
                                            (double)(breakdownAvailable / (breakdownMatched * 1.0)) * 100;
                                        Console.WriteLine(
                                            $"\t\t{breakdownAvailablePercent}% {unitType} available");
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Failed to get forecast. Exception says \"{0}\"", e.Message);
                    }
                }
        }
Ejemplo n.º 18
0
        private void RenderDays(TextWriter writer, SuggestionDayResult[] dayResults, bool?workingHoursOnly)
        {
            Calendar         calendar        = new GregorianCalendar();
            DayOfWeek        weekStartDay    = this.owaContext.UserContext.UserOptions.WeekStartDay;
            CalendarWeekRule firstWeekOfYear = this.owaContext.UserContext.FirstWeekOfYear;
            DayOfWeek        dayOfWeek       = (weekStartDay + 6) % (DayOfWeek)7;
            int      num       = 0;
            int      num2      = this.dates.Length / 7;
            DateTime dateTime  = calendar.AddMonths(this.selectedDate, -1);
            DateTime dateTime2 = calendar.AddMonths(this.selectedDate, 1);
            bool     flag      = false;

            if (workingHoursOnly != null)
            {
                flag = true;
            }
            if (!flag)
            {
                this.GetFreeBusy();
            }
            int      num3 = -1;
            DateTime t    = calendar.AddDays(this.selectedDate, 6);

            if (dayResults != null)
            {
                num3 = (dayResults[0].Date - this.startDate).Days;
            }
            bool flag2 = false;

            for (int i = 0; i < num2; i++)
            {
                writer.Write("<tr>");
                if (this.showWeekNumbers)
                {
                    int weekOfYear = calendar.GetWeekOfYear(this.dates[num], firstWeekOfYear, weekStartDay);
                    writer.Write("<td align=\"center\" class=\"wk");
                    if (i == num2 - 1)
                    {
                        writer.Write(" lst");
                    }
                    writer.Write("\">");
                    writer.Write(weekOfYear);
                    writer.Write("</td>");
                }
                for (int j = 0; j < 7; j++)
                {
                    writer.Write("<td align=\"center\"");
                    bool flag3 = true;
                    if (flag)
                    {
                        if (num3 == -1 || num < num3)
                        {
                            DatePicker.RenderClass(writer, ref flag3, DatePicker.SuggestionQualityStyles[4]);
                        }
                        else
                        {
                            SuggestionDayResult suggestionDayResult = dayResults[num - num3];
                            if (suggestionDayResult != null)
                            {
                                Suggestion[]      suggestionArray = suggestionDayResult.SuggestionArray;
                                SuggestionQuality suggestionQuality;
                                if (0 < suggestionArray.Length)
                                {
                                    suggestionQuality = suggestionArray[0].SuggestionQuality;
                                }
                                else if (!this.owaContext.UserContext.WorkingHours.IsWorkDay(dayResults[num - num3].Date.DayOfWeek))
                                {
                                    suggestionQuality = (SuggestionQuality)4;
                                }
                                else
                                {
                                    suggestionQuality = SuggestionQuality.Poor;
                                }
                                DatePicker.RenderClass(writer, ref flag3, DatePicker.SuggestionQualityStyles[(int)suggestionQuality]);
                            }
                        }
                    }
                    else if (this.freeBusyData[num] != '0')
                    {
                        DatePicker.RenderClass(writer, ref flag3, "fb");
                    }
                    if (this.indexMonthStart > num || this.indexMonthEnd < num)
                    {
                        DatePicker.RenderClass(writer, ref flag3, "pn");
                    }
                    if (this.dates[num].ToShortDateString() == this.currentDate.ToShortDateString())
                    {
                        DatePicker.RenderClass(writer, ref flag3, "td");
                    }
                    if (!flag)
                    {
                        if (this.dates[num].Date == this.selectedDate.Date)
                        {
                            DatePicker.RenderClass(writer, ref flag3, "sd");
                        }
                    }
                    else if (this.dates[num] >= this.selectedDate && this.dates[num] <= t)
                    {
                        if (workingHoursOnly != null && workingHoursOnly == true)
                        {
                            if (this.owaContext.UserContext.WorkingHours.IsWorkDay(this.dates[num].DayOfWeek) || num == 0)
                            {
                                if (!flag2)
                                {
                                    DatePicker.RenderClass(writer, ref flag3, "sd");
                                    DatePicker.RenderClass(writer, ref flag3, "tb");
                                    flag2 = true;
                                }
                                else
                                {
                                    DatePicker.RenderClass(writer, ref flag3, "tb");
                                }
                            }
                            if (this.dates[num].ToShortDateString() == t.ToShortDateString() && flag2)
                            {
                                DatePicker.RenderClass(writer, ref flag3, "tb");
                                DatePicker.RenderClass(writer, ref flag3, "r");
                                flag2 = false;
                            }
                            if ((!this.owaContext.UserContext.WorkingHours.IsWorkDay(calendar.AddDays(this.dates[num], 1).DayOfWeek) || j == 6) && flag2)
                            {
                                DatePicker.RenderClass(writer, ref flag3, "tb");
                                DatePicker.RenderClass(writer, ref flag3, "r");
                                flag2 = false;
                            }
                        }
                        else
                        {
                            if (!flag2)
                            {
                                DatePicker.RenderClass(writer, ref flag3, "sd");
                                DatePicker.RenderClass(writer, ref flag3, "tb");
                                flag2 = true;
                            }
                            else
                            {
                                DatePicker.RenderClass(writer, ref flag3, "tb");
                            }
                            if (this.dates[num].ToShortDateString() == t.ToShortDateString() && flag2)
                            {
                                DatePicker.RenderClass(writer, ref flag3, "tb");
                                DatePicker.RenderClass(writer, ref flag3, "r");
                                flag2 = false;
                            }
                            if (this.dates[num].DayOfWeek == dayOfWeek)
                            {
                                DatePicker.RenderClass(writer, ref flag3, "tb");
                                DatePicker.RenderClass(writer, ref flag3, "r");
                                flag2 = false;
                            }
                        }
                    }
                    if (!flag3)
                    {
                        writer.Write("\"");
                    }
                    writer.Write("><a href=\"#\" onClick=\"return onClkD(");
                    if (this.indexMonthStart > num)
                    {
                        writer.Write("{0},{1},", dateTime.Year, dateTime.Month);
                    }
                    else if (this.indexMonthEnd < num)
                    {
                        writer.Write("{0},{1},", dateTime2.Year, dateTime2.Month);
                    }
                    else
                    {
                        writer.Write("{0},{1},", this.selectedDate.Year, this.selectedDate.Month);
                    }
                    writer.Write("{0})\">", this.dates[num].Day);
                    string daysFormat = DateTimeUtilities.GetDaysFormat(this.owaContext.UserContext.UserOptions.DateFormat);
                    writer.Write(this.dates[num].ToString(daysFormat ?? "%d"));
                    writer.Write("</a></td>");
                    num++;
                }
                writer.Write("</tr>");
            }
        }
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (ProposalLineItemService proposalLineItemService =
                       user.GetService <ProposalLineItemService>())

                using (NetworkService networkService = user.GetService <NetworkService>())
                {
                    long proposalId = long.Parse(_T("INSERT_PROPOSAL_ID_HERE"));
                    long rateCardId = long.Parse(_T("INSERT_RATE_CARD_ID_HERE"));
                    long productId  = long.Parse(_T("INSERT_PRODUCT_ID_HERE"));

                    // Get the root ad unit ID used to target the whole site.
                    String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;

                    // Create inventory targeting.
                    InventoryTargeting inventoryTargeting = new InventoryTargeting();

                    // Create ad unit targeting for the root ad unit (i.e. the whole network).
                    AdUnitTargeting adUnitTargeting = new AdUnitTargeting();
                    adUnitTargeting.adUnitId           = rootAdUnitId;
                    adUnitTargeting.includeDescendants = true;

                    inventoryTargeting.targetedAdUnits = new AdUnitTargeting[]
                    {
                        adUnitTargeting
                    };

                    // Create targeting.
                    Targeting targeting = new Targeting();
                    targeting.inventoryTargeting = inventoryTargeting;

                    // Create a proposal line item.
                    ProposalLineItem proposalLineItem = new ProposalLineItem();
                    proposalLineItem.name =
                        "Proposal line item #" + new Random().Next(int.MaxValue);

                    proposalLineItem.proposalId = proposalId;
                    proposalLineItem.rateCardId = rateCardId;
                    proposalLineItem.productId  = productId;
                    proposalLineItem.targeting  = targeting;

                    // Set the length of the proposal line item to run.
                    proposalLineItem.startDateTime =
                        DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(7),
                                                       "America/New_York");
                    proposalLineItem.endDateTime =
                        DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(30),
                                                       "America/New_York");

                    // Set delivery specifications for the proposal line item.
                    proposalLineItem.deliveryRateType     = DeliveryRateType.EVENLY;
                    proposalLineItem.creativeRotationType = CreativeRotationType.OPTIMIZED;

                    // Set billing specifications for the proposal line item.
                    proposalLineItem.billingCap    = BillingCap.CAPPED_CUMULATIVE;
                    proposalLineItem.billingSource = BillingSource.THIRD_PARTY_VOLUME;

                    // Set pricing for the proposal line item for 1000 impressions at a CPM of $2
                    // for a total value of $2.
                    proposalLineItem.goal = new Goal()
                    {
                        unitType = UnitType.IMPRESSIONS,
                        units    = 1000L
                    };
                    proposalLineItem.netCost = new Money()
                    {
                        currencyCode = "USD",
                        microAmount  = 2000000L
                    };
                    proposalLineItem.netRate = new Money()
                    {
                        currencyCode = "USD",
                        microAmount  = 2000000L
                    };
                    proposalLineItem.rateType = RateType.CPM;

                    try
                    {
                        // Create the proposal line item on the server.
                        ProposalLineItem[] proposalLineItems =
                            proposalLineItemService.createProposalLineItems(new ProposalLineItem[]
                        {
                            proposalLineItem
                        });

                        foreach (ProposalLineItem createdProposalLineItem in proposalLineItems)
                        {
                            Console.WriteLine(
                                "A proposal line item with ID \"{0}\" and name \"{1}\" was " +
                                "created.",
                                createdProposalLineItem.id, createdProposalLineItem.name);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(
                            "Failed to create proposal line items. Exception says \"{0}\"",
                            e.Message);
                    }
                }
        }
Ejemplo n.º 20
0
        public LineItem CreateLineItem(DfpUser user, long orderId, string adUnitId)
        {
            LineItemService lineItemService =
                (LineItemService)user.GetService(DfpService.v201306.LineItemService);

            long placementId = CreatePlacement(user, new string[] { adUnitId }).id;

            // Create inventory targeting.
            InventoryTargeting inventoryTargeting = new InventoryTargeting();

            inventoryTargeting.targetedPlacementIds = new long[] { placementId };

            // Create geographical targeting.
            GeoTargeting geoTargeting = new GeoTargeting();

            // Include the US and Quebec, Canada.
            Location countryLocation = new Location();

            countryLocation.id = 2840L;

            Location regionLocation = new Location();

            regionLocation.id = 20123L;
            geoTargeting.targetedLocations = new Location[] { countryLocation, regionLocation };

            // Exclude Chicago and the New York metro area.
            Location cityLocation = new Location();

            cityLocation.id = 1016367L;

            Location metroLocation = new Location();

            metroLocation.id = 200501L;
            geoTargeting.excludedLocations = new Location[] { cityLocation, metroLocation };

            // Exclude domains that are not under the network's control.
            UserDomainTargeting userDomainTargeting = new UserDomainTargeting();

            userDomainTargeting.domains  = new String[] { "usa.gov" };
            userDomainTargeting.targeted = false;

            // Create day-part targeting.
            DayPartTargeting dayPartTargeting = new DayPartTargeting();

            dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER;

            // Target only the weekend in the browser's timezone.
            DayPart saturdayDayPart = new DayPart();

            saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201306.DayOfWeek.SATURDAY;

            saturdayDayPart.startTime        = new TimeOfDay();
            saturdayDayPart.startTime.hour   = 0;
            saturdayDayPart.startTime.minute = MinuteOfHour.ZERO;

            saturdayDayPart.endTime        = new TimeOfDay();
            saturdayDayPart.endTime.hour   = 24;
            saturdayDayPart.endTime.minute = MinuteOfHour.ZERO;

            DayPart sundayDayPart = new DayPart();

            sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201306.DayOfWeek.SUNDAY;

            sundayDayPart.startTime        = new TimeOfDay();
            sundayDayPart.startTime.hour   = 0;
            sundayDayPart.startTime.minute = MinuteOfHour.ZERO;

            sundayDayPart.endTime        = new TimeOfDay();
            sundayDayPart.endTime.hour   = 24;
            sundayDayPart.endTime.minute = MinuteOfHour.ZERO;

            dayPartTargeting.dayParts = new DayPart[] { saturdayDayPart, sundayDayPart };


            // Create technology targeting.
            TechnologyTargeting technologyTargeting = new TechnologyTargeting();

            // Create browser targeting.
            BrowserTargeting browserTargeting = new BrowserTargeting();

            browserTargeting.isTargeted = true;

            // Target just the Chrome browser.
            Technology browserTechnology = new Technology();

            browserTechnology.id                 = 500072L;
            browserTargeting.browsers            = new Technology[] { browserTechnology };
            technologyTargeting.browserTargeting = browserTargeting;

            LineItem lineItem = new LineItem();

            lineItem.name      = "Line item #" + new TestUtils().GetTimeStamp();
            lineItem.orderId   = orderId;
            lineItem.targeting = new Targeting();

            lineItem.targeting.inventoryTargeting  = inventoryTargeting;
            lineItem.targeting.geoTargeting        = geoTargeting;
            lineItem.targeting.userDomainTargeting = userDomainTargeting;
            lineItem.targeting.dayPartTargeting    = dayPartTargeting;
            lineItem.targeting.technologyTargeting = technologyTargeting;

            lineItem.lineItemType  = LineItemType.STANDARD;
            lineItem.allowOverbook = true;

            // Set the creative rotation type to even.
            lineItem.creativeRotationType = CreativeRotationType.EVEN;

            // Set the size of creatives that can be associated with this line item.
            Size size = new Size();

            size.width         = 300;
            size.height        = 250;
            size.isAspectRatio = false;

            // Create the creative placeholder.
            CreativePlaceholder creativePlaceholder = new CreativePlaceholder();

            creativePlaceholder.size = size;

            lineItem.creativePlaceholders = new CreativePlaceholder[] { creativePlaceholder };

            // Set the length of the line item to run.
            //lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
            lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
            lineItem.endDateTime       = DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1));

            // Set the cost per unit to $2.
            lineItem.costType    = CostType.CPM;
            lineItem.costPerUnit = new Money();
            lineItem.costPerUnit.currencyCode = "USD";
            lineItem.costPerUnit.microAmount  = 2000000L;

            // Set the number of units bought to 500,000 so that the budget is
            // $1,000.
            lineItem.unitsBought = 500000L;
            lineItem.unitType    = UnitType.IMPRESSIONS;

            return(lineItemService.createLineItem(lineItem));
        }
        // Token: 0x06001F51 RID: 8017 RVA: 0x000B43CC File Offset: 0x000B25CC
        private void RenderConversationMetaDataExpandos(TextWriter writer, int globalCount, IList <StoreObjectId> itemIds)
        {
            base.InternalRenderItemMetaDataExpandos(writer);
            int itemProperty = this.DataSource.GetItemProperty <int>(ConversationItemSchema.ConversationUnreadMessageCount, 0);

            writer.Write(" ");
            writer.Write("iUC");
            writer.Write("=");
            writer.Write(itemProperty);
            int itemProperty2 = this.DataSource.GetItemProperty <int>(ConversationItemSchema.ConversationMessageCount, 0);

            writer.Write(" ");
            writer.Write("iTC");
            writer.Write("=");
            writer.Write(itemProperty2);
            writer.Write(" ");
            writer.Write("iGC");
            writer.Write("=");
            writer.Write(globalCount);
            if (itemIds.Count > 0)
            {
                writer.Write(" ");
                writer.Write("sMID");
                writer.Write("=\"");
                Utilities.HtmlEncode(Utilities.GetItemIdString(itemIds[0], this.parentFolderId), writer);
                writer.Write("\"");
            }
            if (globalCount == 1)
            {
                string[] itemProperty3 = this.DataSource.GetItemProperty <string[]>(ConversationItemSchema.ConversationGlobalMessageClasses, null);
                if (base.UserContext.DraftsFolderId.Equals(this.parentFolderId.StoreObjectId))
                {
                    writer.Write(" ");
                    writer.Write("sMS");
                    writer.Write("=\"Draft\"");
                }
                writer.Write(" ");
                writer.Write("sMT");
                writer.Write("=\"");
                Utilities.HtmlEncode(itemProperty3[0], writer);
                writer.Write("\"");
                if (ObjectClass.IsMeetingRequest(itemProperty3[0]))
                {
                    writer.Write(" fMR=1");
                    writer.Write(" fRR=1");
                }
            }
            if (itemProperty > 0)
            {
                writer.Write(" ");
                writer.Write("read");
                writer.Write("=\"0\"");
            }
            FlagStatus itemProperty4 = (FlagStatus)this.DataSource.GetItemProperty <int>(ConversationItemSchema.ConversationFlagStatus, 0);

            if (itemProperty4 != FlagStatus.NotFlagged)
            {
                ExDateTime itemProperty5 = this.DataSource.GetItemProperty <ExDateTime>(ConversationItemSchema.ConversationFlagCompleteTime, ExDateTime.MinValue);
                if (itemProperty5 != ExDateTime.MinValue)
                {
                    writer.Write(" sFlgDt=\"");
                    writer.Write(DateTimeUtilities.GetJavascriptDate(itemProperty5));
                    writer.Write("\"");
                }
                FlagAction flagActionForItem = FlagContextMenu.GetFlagActionForItem(base.UserContext, itemProperty5, itemProperty4);
                writer.Write(" sFA=");
                writer.Write((int)flagActionForItem);
            }
            if (this.RenderLastModifiedTime)
            {
                base.RenderLastModifiedTimeExpando(writer);
            }
        }
        public void TestGetAvailabilityForecast()
        {
            TestUtils utils = new TestUtils();

            LineItem lineItem = new LineItem();

            lineItem.name = string.Format("Line item #{0}", utils.GetTimeStamp());

            lineItem.orderId = orderId;

            lineItem.targeting = new Targeting();
            lineItem.targeting.inventoryTargeting = new InventoryTargeting();
            lineItem.targeting.inventoryTargeting.targetedPlacementIds = new long[] { placementId };

            Size size1 = new Size();

            size1.width  = 300;
            size1.height = 250;

            Size size2 = new Size();

            size2.width  = 120;
            size2.height = 600;

            // Create the creative placeholders.
            CreativePlaceholder creativePlaceholder1 = new CreativePlaceholder();

            creativePlaceholder1.size = size1;

            CreativePlaceholder creativePlaceholder2 = new CreativePlaceholder();

            creativePlaceholder1.size = size2;

            lineItem.creativePlaceholders =
                new CreativePlaceholder[] { creativePlaceholder1, creativePlaceholder2 };

            lineItem.lineItemType = LineItemType.STANDARD;

            // Set start date time and end date time.
            lineItem.startDateTime =
                DateTimeUtilities.FromDateTime(System.DateTime.Today.AddDays(1), "America/New_York");
            lineItem.endDateTime =
                DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1), "America/New_York");

            lineItem.costType    = CostType.CPM;
            lineItem.costPerUnit = new Money();
            lineItem.costPerUnit.currencyCode = "USD";
            lineItem.costPerUnit.microAmount  = 2000000;

            lineItem.creativeRotationType = CreativeRotationType.EVEN;
            lineItem.discountType         = LineItemDiscountType.PERCENTAGE;

            Goal goal = new Goal();

            goal.units           = 500000;
            goal.unitType        = UnitType.IMPRESSIONS;
            lineItem.primaryGoal = goal;

            ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem();

            prospectiveLineItem.lineItem = lineItem;

            AvailabilityForecast forecast = null;

            Assert.DoesNotThrow(delegate() {
                forecast = forecastService.getAvailabilityForecast(prospectiveLineItem,
                                                                   new AvailabilityForecastOptions());
            });
            Assert.NotNull(forecast);
            Assert.AreEqual(forecast.orderId, orderId);
            Assert.AreEqual(forecast.unitType, lineItem.primaryGoal.unitType);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(DfpUser user)
        {
            using (LineItemService lineItemService =
                       (LineItemService)user.GetService(DfpService.v201705.LineItemService)) {
                // Set the order that all created line items will belong to and the
                // placement ID to target.
                long   orderId            = long.Parse(_T("INSERT_ORDER_ID_HERE"));
                long[] targetPlacementIds = new long[] { long.Parse(_T("INSERT_PLACEMENT_ID_HERE")) };

                // Create inventory targeting.
                InventoryTargeting inventoryTargeting = new InventoryTargeting();
                inventoryTargeting.targetedPlacementIds = targetPlacementIds;

                // Create geographical targeting.
                GeoTargeting geoTargeting = new GeoTargeting();

                // Include the US and Quebec, Canada.
                Location countryLocation = new Location();
                countryLocation.id = 2840L;

                Location regionLocation = new Location();
                regionLocation.id = 20123L;
                geoTargeting.targetedLocations = new Location[] { countryLocation, regionLocation };

                Location postalCodeLocation = new Location();
                postalCodeLocation.id = 9000093;

                // Exclude Chicago and the New York metro area.
                Location cityLocation = new Location();
                cityLocation.id = 1016367L;

                Location metroLocation = new Location();
                metroLocation.id = 200501L;
                geoTargeting.excludedLocations = new Location[] { cityLocation, metroLocation };

                // Exclude domains that are not under the network's control.
                UserDomainTargeting userDomainTargeting = new UserDomainTargeting();
                userDomainTargeting.domains  = new String[] { "usa.gov" };
                userDomainTargeting.targeted = false;

                // Create day-part targeting.
                DayPartTargeting dayPartTargeting = new DayPartTargeting();
                dayPartTargeting.timeZone = DeliveryTimeZone.BROWSER;

                // Target only the weekend in the browser's timezone.
                DayPart saturdayDayPart = new DayPart();
                saturdayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201705.DayOfWeek.SATURDAY;

                saturdayDayPart.startTime        = new TimeOfDay();
                saturdayDayPart.startTime.hour   = 0;
                saturdayDayPart.startTime.minute = MinuteOfHour.ZERO;

                saturdayDayPart.endTime        = new TimeOfDay();
                saturdayDayPart.endTime.hour   = 24;
                saturdayDayPart.endTime.minute = MinuteOfHour.ZERO;

                DayPart sundayDayPart = new DayPart();
                sundayDayPart.dayOfWeek = Google.Api.Ads.Dfp.v201705.DayOfWeek.SUNDAY;

                sundayDayPart.startTime        = new TimeOfDay();
                sundayDayPart.startTime.hour   = 0;
                sundayDayPart.startTime.minute = MinuteOfHour.ZERO;

                sundayDayPart.endTime        = new TimeOfDay();
                sundayDayPart.endTime.hour   = 24;
                sundayDayPart.endTime.minute = MinuteOfHour.ZERO;

                dayPartTargeting.dayParts = new DayPart[] { saturdayDayPart, sundayDayPart };


                // Create technology targeting.
                TechnologyTargeting technologyTargeting = new TechnologyTargeting();

                // Create browser targeting.
                BrowserTargeting browserTargeting = new BrowserTargeting();
                browserTargeting.isTargeted = true;

                // Target just the Chrome browser.
                Technology browserTechnology = new Technology();
                browserTechnology.id                 = 500072L;
                browserTargeting.browsers            = new Technology[] { browserTechnology };
                technologyTargeting.browserTargeting = browserTargeting;

                // Create an array to store local line item objects.
                LineItem[] lineItems = new LineItem[5];

                for (int i = 0; i < 5; i++)
                {
                    LineItem lineItem = new LineItem();
                    lineItem.name      = "Line item #" + i;
                    lineItem.orderId   = orderId;
                    lineItem.targeting = new Targeting();

                    lineItem.targeting.inventoryTargeting  = inventoryTargeting;
                    lineItem.targeting.geoTargeting        = geoTargeting;
                    lineItem.targeting.userDomainTargeting = userDomainTargeting;
                    lineItem.targeting.dayPartTargeting    = dayPartTargeting;
                    lineItem.targeting.technologyTargeting = technologyTargeting;

                    lineItem.lineItemType  = LineItemType.STANDARD;
                    lineItem.allowOverbook = true;

                    // Set the creative rotation type to even.
                    lineItem.creativeRotationType = CreativeRotationType.EVEN;

                    // Set the size of creatives that can be associated with this line item.
                    Size size = new Size();
                    size.width         = 300;
                    size.height        = 250;
                    size.isAspectRatio = false;

                    // Create the creative placeholder.
                    CreativePlaceholder creativePlaceholder = new CreativePlaceholder();
                    creativePlaceholder.size = size;

                    lineItem.creativePlaceholders = new CreativePlaceholder[] { creativePlaceholder };

                    // Set the line item to run for one month.
                    lineItem.startDateTimeType = StartDateTimeType.IMMEDIATELY;
                    lineItem.endDateTime       =
                        DateTimeUtilities.FromDateTime(System.DateTime.Today.AddMonths(1),
                                                       "America/New_York");

                    // Set the cost per unit to $2.
                    lineItem.costType    = CostType.CPM;
                    lineItem.costPerUnit = new Money();
                    lineItem.costPerUnit.currencyCode = "USD";
                    lineItem.costPerUnit.microAmount  = 2000000L;

                    // Set the number of units bought to 500,000 so that the budget is
                    // $1,000.
                    Goal goal = new Goal();
                    goal.goalType        = GoalType.LIFETIME;
                    goal.unitType        = UnitType.IMPRESSIONS;
                    goal.units           = 500000L;
                    lineItem.primaryGoal = goal;

                    lineItems[i] = lineItem;
                }

                try {
                    // Create the line items on the server.
                    lineItems = lineItemService.createLineItems(lineItems);

                    if (lineItems != null)
                    {
                        foreach (LineItem lineItem in lineItems)
                        {
                            Console.WriteLine("A line item with ID \"{0}\", belonging to order ID \"{1}\", and" +
                                              " named \"{2}\" was created.", lineItem.id, lineItem.orderId, lineItem.name);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No line items created.");
                    }
                } catch (Exception e) {
                    Console.WriteLine("Failed to create line items. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Ejemplo n.º 24
0
        // Token: 0x06002FD7 RID: 12247 RVA: 0x001170C4 File Offset: 0x001152C4
        public static void RenderCancelRecurrenceCalendarItemDialog(TextWriter output, bool showCancelOccurrence, bool isMeeting, bool isPermanentDelete, bool showWarningAttendeesWillNotBeNotified)
        {
            output.Write("<div id=\"divCRMsg\" style=\"display:none\" sTtl=\"");
            if (isMeeting)
            {
                output.Write(SanitizedHtmlString.FromStringId(-2063563644));
            }
            else
            {
                output.Write(SanitizedHtmlString.FromStringId(78467316));
            }
            output.Write("\" sOk=\"");
            output.Write(SanitizedHtmlString.FromStringId(2041362128));
            output.Write("\" sCncl=\"");
            output.Write(SanitizedHtmlString.FromStringId(-1936577052));
            output.Write("\">");
            if (showWarningAttendeesWillNotBeNotified)
            {
                output.Write("<div class=\"w\">");
                output.Write(SanitizedHtmlString.FromStringId(-1626455311));
                output.Write("</div>");
            }
            if (showCancelOccurrence)
            {
                output.Write("<div class=\"cancelRcrRow\">");
                output.Write("<div class=\"fltBefore cancelRcrInput\"><input type=\"radio\" name=\"rdoCncl\" id=\"rdoCnclO\"></div>");
                output.Write("<div class=\"fltBefore\"><label for=\"rdoCnclO\">");
                if (isPermanentDelete)
                {
                    output.Write(SanitizedHtmlString.FromStringId(-897929905));
                }
                else
                {
                    output.Write(SanitizedHtmlString.FromStringId(-673339501));
                }
                output.Write("</label></div><div class=\"clear\"></div></div>");
            }
            output.Write("<div class=\"cancelRcrRow\">");
            output.Write("<div class=\"fltBefore cancelRcrInput\"><input type=\"radio\" name=\"rdoCncl\" id=\"rdoCnclD\"></div>");
            output.Write("<div class=\"fltBefore\"><label for=\"rdoCnclD\">");
            StringBuilder stringBuilder = new StringBuilder();

            using (SanitizingStringWriter <OwaHtml> sanitizingStringWriter = new SanitizingStringWriter <OwaHtml>(stringBuilder))
            {
                sanitizingStringWriter.Write("&nbsp;</label></div><div class=\"fltBefore dtPkerAd\">");
                DatePickerDropDownCombo.RenderDatePicker(sanitizingStringWriter, "divRecurrenceDate", DateTimeUtilities.GetLocalTime());
                sanitizingStringWriter.Write("</div><div class=\"fltBefore\"><label for=\"rdoCnclD\">");
                sanitizingStringWriter.Close();
            }
            if (isPermanentDelete)
            {
                output.Write(SanitizedHtmlString.Format(LocalizedStrings.GetHtmlEncoded(-1487900473), new object[]
                {
                    SanitizedHtmlString.GetSanitizedStringWithoutEncoding(stringBuilder.ToString())
                }));
            }
            else
            {
                output.Write(SanitizedHtmlString.Format(LocalizedStrings.GetHtmlEncoded(-1062918861), new object[]
                {
                    SanitizedHtmlString.GetSanitizedStringWithoutEncoding(stringBuilder.ToString())
                }));
            }
            output.Write("</label></div><div class=\"clear\"></div></div>");
            output.Write("<div class=\"cancelRcrRow\">");
            output.Write("<div class=\"fltBefore cancelRcrInput\"><input type=\"radio\" name=\"rdoCncl\" id=\"rdoCnclA\"></div>");
            output.Write("<div class=\"fltBefore\"><label for=\"rdoCnclA\">");
            if (isPermanentDelete)
            {
                output.Write(SanitizedHtmlString.FromStringId(817420711));
            }
            else
            {
                output.Write(SanitizedHtmlString.FromStringId(1631668395));
            }
            output.Write("</label></div>");
            output.Write("</div>");
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Run the code examples.
        /// </summary>
        public void Run(DfpUser user, long proposalId, long rateCardId, long productId)
        {
            // Get the ProposalLineItemService.
            ProposalLineItemService proposalLineItemService =
                (ProposalLineItemService)user.GetService(DfpService.v201608.ProposalLineItemService);

            // Create a proposal line item.
            ProposalLineItem proposalLineItem = new ProposalLineItem();

            proposalLineItem.name =
                "Programmatic proposal line item #" + new Random().Next(int.MaxValue);
            proposalLineItem.proposalId = proposalId;
            proposalLineItem.rateCardId = rateCardId;
            proposalLineItem.productId  = productId;

            // Set the Marketplace information.
            proposalLineItem.marketplaceInfo = new ProposalLineItemMarketplaceInfo()
            {
                adExchangeEnvironment = AdExchangeEnvironment.DISPLAY
            };

            // Set the length of the proposal line item to run.
            proposalLineItem.startDateTime =
                DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(7), "America/New_York");
            proposalLineItem.endDateTime =
                DateTimeUtilities.FromDateTime(System.DateTime.Now.AddDays(30), "America/New_York");

            // Set pricing for the proposal line item for 1000 impressions at a CPM of $2
            // for a total value of $2.
            proposalLineItem.goal = new Goal()
            {
                unitType = UnitType.IMPRESSIONS,
                units    = 1000L
            };
            proposalLineItem.netCost = new Money()
            {
                currencyCode = "USD", microAmount = 2000000L
            };
            proposalLineItem.netRate = new Money()
            {
                currencyCode = "USD", microAmount = 2000000L
            };
            proposalLineItem.rateType = RateType.CPM;

            try {
                // Create the proposal line item on the server.
                ProposalLineItem[] proposalLineItems = proposalLineItemService.createProposalLineItems(
                    new ProposalLineItem[] { proposalLineItem });

                foreach (ProposalLineItem createdProposalLineItem in proposalLineItems)
                {
                    Console.WriteLine("A programmatic proposal line item with ID \"{0}\" "
                                      + "and name \"{1}\" was created.",
                                      createdProposalLineItem.id,
                                      createdProposalLineItem.name);
                }
            } catch (Exception e) {
                Console.WriteLine("Failed to create proposal line items. Exception says \"{0}\"",
                                  e.Message);
            }
        }
Ejemplo n.º 26
0
        // Token: 0x06002FD0 RID: 12240 RVA: 0x00116600 File Offset: 0x00114800
        public static void AddCalendarInfobarMessages(Infobar infobar, CalendarItemBase calendarItemBase, MeetingMessage meetingMessage, UserContext userContext)
        {
            if (infobar == null)
            {
                throw new ArgumentNullException("infobar");
            }
            if (calendarItemBase == null)
            {
                throw new ArgumentNullException("calendarItemBase");
            }
            if (userContext == null)
            {
                throw new ArgumentNullException("userContext");
            }
            bool       flag      = calendarItemBase.IsOrganizer() && calendarItemBase.IsMeeting;
            ExDateTime localTime = DateTimeUtilities.GetLocalTime();
            bool       flag2     = false;

            if (calendarItemBase.IsMeeting && calendarItemBase.IsCancelled)
            {
                infobar.AddMessage(-161808760, InfobarMessageType.Informational);
            }
            if (calendarItemBase.CalendarItemType == CalendarItemType.RecurringMaster)
            {
                CalendarItem calendarItem = (CalendarItem)calendarItemBase;
                if (calendarItem.Recurrence != null && !(calendarItem.Recurrence.Range is NoEndRecurrenceRange))
                {
                    OccurrenceInfo lastOccurrence = calendarItem.Recurrence.GetLastOccurrence();
                    if (lastOccurrence != null && lastOccurrence.EndTime < localTime)
                    {
                        infobar.AddMessage(-2124392108, InfobarMessageType.Informational);
                        flag2 = true;
                    }
                }
            }
            else if (calendarItemBase.EndTime < localTime)
            {
                flag2 = true;
                if (calendarItemBase.CalendarItemType != CalendarItemType.RecurringMaster)
                {
                    infobar.AddMessage(-593429293, InfobarMessageType.Informational);
                }
            }
            InfobarMessageBuilder.AddFlag(infobar, calendarItemBase, userContext);
            if (flag)
            {
                if (calendarItemBase.MeetingRequestWasSent)
                {
                    CalendarUtilities.AddAttendeeResponseCountMessage(infobar, calendarItemBase);
                }
                else
                {
                    infobar.AddMessage(613373695, InfobarMessageType.Informational);
                }
            }
            if (!calendarItemBase.IsOrganizer() && calendarItemBase.IsMeeting)
            {
                bool           flag3          = false;
                MeetingRequest meetingRequest = meetingMessage as MeetingRequest;
                if (meetingRequest != null)
                {
                    flag3 = (meetingRequest.MeetingRequestType == MeetingMessageType.PrincipalWantsCopy);
                }
                if (calendarItemBase.ResponseType != ResponseType.NotResponded)
                {
                    Strings.IDs?ds  = null;
                    Strings.IDs?ds2 = null;
                    switch (calendarItemBase.ResponseType)
                    {
                    case ResponseType.Tentative:
                        ds  = new Strings.IDs?(-1859761232);
                        ds2 = new Strings.IDs?(1365345389);
                        break;

                    case ResponseType.Accept:
                        ds  = new Strings.IDs?(-700793833);
                        ds2 = new Strings.IDs?(-1153967082);
                        break;

                    case ResponseType.Decline:
                        ds  = new Strings.IDs?(-278420592);
                        ds2 = new Strings.IDs?(2009978813);
                        break;
                    }
                    if (ds != null)
                    {
                        ExDateTime property = ItemUtility.GetProperty <ExDateTime>(calendarItemBase, CalendarItemBaseSchema.AppointmentReplyTime, ExDateTime.MinValue);
                        string     text     = Strings.None;
                        string     text2    = string.Empty;
                        if (property != ExDateTime.MinValue)
                        {
                            text  = property.ToString(userContext.UserOptions.DateFormat);
                            text2 = property.ToString(userContext.UserOptions.TimeFormat);
                        }
                        string property2 = ItemUtility.GetProperty <string>(calendarItemBase, CalendarItemBaseSchema.AppointmentReplyName, string.Empty);
                        SanitizedHtmlString messageHtml;
                        if (string.Compare(property2, userContext.ExchangePrincipal.MailboxInfo.DisplayName, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            messageHtml = SanitizedHtmlString.Format(LocalizedStrings.GetHtmlEncoded(ds.Value), new object[]
                            {
                                text,
                                text2
                            });
                        }
                        else
                        {
                            messageHtml = SanitizedHtmlString.Format(LocalizedStrings.GetHtmlEncoded(ds2.Value), new object[]
                            {
                                property2,
                                text,
                                text2
                            });
                        }
                        infobar.AddMessage(messageHtml, InfobarMessageType.Informational);
                        return;
                    }
                }
                else if (!flag2 && !calendarItemBase.IsCancelled)
                {
                    if (!flag3)
                    {
                        bool property3 = ItemUtility.GetProperty <bool>(calendarItemBase, ItemSchema.IsResponseRequested, true);
                        if (property3)
                        {
                            infobar.AddMessage(919273049, InfobarMessageType.Informational);
                        }
                        else
                        {
                            infobar.AddMessage(1602295502, InfobarMessageType.Informational);
                        }
                    }
                    else
                    {
                        infobar.AddMessage(-200304859, InfobarMessageType.Informational);
                    }
                    CalendarUtilities.GetConflictingAppointments(infobar, calendarItemBase, userContext);
                }
            }
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (PublisherQueryLanguageService pqlService =
                       user.GetService <PublisherQueryLanguageService>())
            {
                // First day of last month.
                System.DateTime lastMonth = System.DateTime.Now
                                            .AddDays(1 - System.DateTime.Now.Day)
                                            .AddMonths(-1);

                // Create statement to select MCM earnings for the prior month.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Select("Month, ChildName, ChildNetworkCode, TotalEarningsCurrencyCode,"
                                                            + " TotalEarningsMicros, ParentPaymentCurrencyCode, ParentPaymentMicros,"
                                                            + " ChildPaymentCurrencyCode, ChildPaymentMicros, DeductionsMicros")
                                                    .From("Mcm_Earnings")
                                                    .Where("Month = :month")
                                                    .OrderBy("ChildNetworkCode")
                                                    .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
                                                    .AddValue("month",
                                                              DateTimeUtilities.FromDateTime(lastMonth, "America/New_York").date);

                int        resultSetSize = 0;
                List <Row> allRows       = new List <Row>();
                ResultSet  resultSet;

                try
                {
                    do
                    {
                        // Get earnings information.
                        resultSet = pqlService.select(statementBuilder.ToStatement());

                        // Collect all data from each page.
                        allRows.AddRange(resultSet.rows);

                        // Display results.
                        Console.WriteLine(PqlUtilities.ResultSetToString(resultSet));

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                        resultSetSize = resultSet.rows == null ? 0 : resultSet.rows.Length;
                    } while (resultSetSize == StatementBuilder.SUGGESTED_PAGE_LIMIT);

                    Console.WriteLine("Number of results found: " + allRows.Count);

                    // Optionally, save all rows to a CSV.
                    // Get a string array representation of the data rows.
                    resultSet.rows = allRows.ToArray();
                    List <String[]> rows = PqlUtilities.ResultSetToStringArrayList(resultSet);

                    // Write the contents to a csv file.
                    CsvFile file = new CsvFile();
                    file.Headers.AddRange(rows[0]);
                    file.Records.AddRange(rows.GetRange(1, rows.Count - 1).ToArray());
                    file.Write("Earnings_Report_" + this.GetTimeStamp() + ".csv");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to get MCM earnings. Exception says \"{0}\"",
                                      e.Message);
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(DfpUser user)
        {
            // Get the PublisherQueryLanguageService.
            PublisherQueryLanguageService pqlService =
                (PublisherQueryLanguageService)user.GetService(
                    DfpService.v201702.PublisherQueryLanguageService);

            // Create statement to select recent changes. Change_History only supports ordering by
            // descending ChangeDateTime. Offset is not supported. To page, use the change ID of the
            // earliest change as a pagination token. A date time range is required
            // when querying this table.
            System.DateTime endDateTime   = System.DateTime.Now;
            System.DateTime startDateTime = endDateTime.AddDays(-1);

            StatementBuilder statementBuilder = new StatementBuilder()
                                                .Select("Id, ChangeDateTime, EntityId, EntityType, Operation, UserId")
                                                .From("Change_History")
                                                .Where("ChangeDateTime < :endDateTime AND ChangeDateTime > :startDateTime")
                                                .OrderBy("ChangeDateTime DESC")
                                                .AddValue("startDateTime",
                                                          DateTimeUtilities.FromDateTime(startDateTime, "America/New_York"))
                                                .AddValue("endDateTime",
                                                          DateTimeUtilities.FromDateTime(endDateTime, "America/New_York"))
                                                .Limit(StatementBuilder.SUGGESTED_PAGE_LIMIT);

            int        resultSetSize = 0;
            List <Row> allRows       = new List <Row>();
            ResultSet  resultSet;

            do
            {
                resultSet = pqlService.select(statementBuilder.ToStatement());

                if (resultSet.rows != null && resultSet.rows.Length > 0)
                {
                    // Get the earliest change ID in the result set.
                    Row    lastRow = resultSet.rows[resultSet.rows.Length - 1];
                    string lastId  = (string)PqlUtilities.GetValue(lastRow.values[0]);

                    // Collect all changes from each page.
                    allRows.AddRange(resultSet.rows);

                    // Display results.
                    Console.WriteLine(PqlUtilities.ResultSetToString(resultSet));

                    // Use the earliest change ID in the result set to page.
                    statementBuilder
                    .Where("Id < :id AND ChangeDateTime < :endDateTime AND ChangeDateTime > :startDateTime")
                    .AddValue("id", lastId);
                }
                resultSetSize = resultSet.rows == null ? 0 : resultSet.rows.Length;
            } while (resultSetSize == StatementBuilder.SUGGESTED_PAGE_LIMIT);

            Console.WriteLine("Number of results found: " + allRows.Count);

            // Optionally, save all rows to a CSV.
            // Get a string array representation of the data rows.
            resultSet.rows = allRows.ToArray();
            List <String[]> rows = PqlUtilities.ResultSetToStringArrayList(resultSet);

            // Write the contents to a csv file.
            CsvFile file = new CsvFile();

            file.Headers.AddRange(rows[0]);
            file.Records.AddRange(rows.GetRange(1, rows.Count - 1).ToArray());
            file.Write("recent_changes_" + this.GetTimeStamp() + ".csv");
        }
Ejemplo n.º 29
0
 public virtual DateTime GetTime()
 {
     return(DateTimeUtilities.UnixMsToDateTime(time * 1000L));
 }
Ejemplo n.º 30
0
 internal Timeout(long durationMillis)
     : this(durationMillis, DateTimeUtilities.CurrentUnixMs())
 {
 }