Esempio n. 1
0
        /// <summary>
        /// Enumerates all instructions and eliminates floating point constants from them.
        /// </summary>
        /// <param name="ctx">The context.</param>
        /// <param name="ctxEpilogue">The context of the epilogue.</param>
        private void ProcessInstructions(Context ctx, Context ctxEpilogue)
        {
            // Current constant operand
            ConstantOperand co = null;

            for (; !ctx.EndOfInstruction; ctx.GotoNext())
            {
                // A constant may only appear on the right side of an expression, so we ignore constants in
                // result - there should never be one there.
                foreach (Operand op in ctx.Operands)
                {
                    co = op as ConstantOperand;
                    if (co != null && IsLargeConstant(co))
                    {
                        // Move the constant out of the code stream and place it right after the code.
                        ctxEpilogue.AppendInstruction(CPUx86.Instruction.LiteralInstruction);
                        ctxEpilogue.LiteralData = new IR.LiteralData(ctx.Label, co.Type, co.Value);

                        op.Replace(((ctxEpilogue.Instruction) as CPUx86.LiteralInstruction).CreateOperand(ctxEpilogue), InstructionSet);

                        _constantRemoved = true;
                    }
                }
            }
        }
        /// <summary>
        /// Replaces the instrinsic call site
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="typeSystem">The type system.</param>
        public void ReplaceIntrinsicCall(Context context, ITypeSystem typeSystem)
        {
            Context         loadContext = new Context(context.InstructionSet, context.Operand1.Definitions[0]);
            ConstantOperand op1         = loadContext.Operand1 as ConstantOperand;

            if (op1 == null)
            {
                throw new InvalidOperationException();
            }

            int irq = -1;

            object obj = op1.Value;

            if ((obj is int) || (obj is uint))
            {
                irq = (int)obj;
            }
            else if (obj is sbyte)
            {
                irq = (sbyte)obj;
            }

            if ((irq > 256) || (irq < 0))
            {
                throw new InvalidOperationException();
            }

            SigType PTR = new SigType(CilElementType.Ptr);

            context.SetInstruction(IR.Instruction.MoveInstruction, context.Result, new SymbolOperand(PTR, @"Mosa.Tools.Compiler.LinkerGenerated.<$>InterruptISR" + irq.ToString() + "()"));
        }
        /// <summary>
        /// Determines whether the value is zero.
        /// </summary>
        /// <param name="cilElementType">Type of the cil element.</param>
        /// <param name="constantOperand">The constant operand.</param>
        /// <returns>
        ///     <c>true</c> if the value is zero; otherwise, <c>false</c>.
        /// </returns>
        private static bool IsValueZero(Metadata.CilElementType cilElementType, ConstantOperand constantOperand)
        {
            switch (cilElementType)
            {
            case Metadata.CilElementType.Char: goto case Metadata.CilElementType.U2;

            case Metadata.CilElementType.U1: return((byte)(constantOperand.Value) == 0);

            case Metadata.CilElementType.U2: return((ushort)(constantOperand.Value) == 0);

            case Metadata.CilElementType.U4: return((int)(constantOperand.Value) == 0);

            case Metadata.CilElementType.I1: return((sbyte)(constantOperand.Value) == 0);

            case Metadata.CilElementType.I2: return((short)(constantOperand.Value) == 0);

            case Metadata.CilElementType.I4: return((int)(constantOperand.Value) == 0);

            case Metadata.CilElementType.R4: return((float)(constantOperand.Value) == 0);

            case Metadata.CilElementType.R8: return((double)(constantOperand.Value) == 0);

            case Metadata.CilElementType.I: goto case Metadata.CilElementType.I4;

            case Metadata.CilElementType.U: goto case Metadata.CilElementType.U4;

            default: goto case Metadata.CilElementType.I4;
            }
        }
        /// <summary>
        /// Creates a CustomerFeed that will associate the data holder's Feed with
        /// the ad customizer placeholder type.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="dataHolder">The data holder that contains metadata about
        /// the customizer Feed.</param>
        private static void CreateCustomerFeed(AdWordsUser user, CustomizersDataHolder dataHolder)
        {
            // Get the CustomerFeedService.
            CustomerFeedService customerFeedService = (CustomerFeedService)user.GetService(
                AdWordsService.v201406.CustomerFeedService);

            CustomerFeed customerFeed = new CustomerFeed();

            customerFeed.feedId           = dataHolder.FeedId;
            customerFeed.placeholderTypes = new int[] { PLACEHOLDER_AD_CUSTOMIZER };

            // Create a matching function that will always evaluate to true.
            Function        customerMatchingFunction = new Function();
            ConstantOperand constOperand             = new ConstantOperand();

            constOperand.type                   = ConstantOperandConstantType.BOOLEAN;
            constOperand.booleanValue           = true;
            customerMatchingFunction.lhsOperand = new FunctionArgumentOperand[] { constOperand };
            customerMatchingFunction.@operator  = FunctionOperator.IDENTITY;
            customerFeed.matchingFunction       = customerMatchingFunction;

            // Create an operation to add the customer feed.
            CustomerFeedOperation customerFeedOperation = new CustomerFeedOperation();

            customerFeedOperation.operand   = customerFeed;
            customerFeedOperation.@operator = Operator.ADD;

            CustomerFeed addedCustomerFeed = customerFeedService.mutate(
                new CustomerFeedOperation[] { customerFeedOperation }).value[0];

            Console.WriteLine("Customer feed for feed ID {0} was added.", addedCustomerFeed.feedId);
        }
Esempio n. 5
0
 public override bool Equals(object obj)
 {
     return(obj switch
     {
         T value => this.Equals(value),
         ConstantOperand <T> operand => this.Equals(operand),
         _ => false,
     });
Esempio n. 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="emitter"></param>
        protected override void Emit(Context ctx, MachineCodeEmitter emitter)
        {
            OpCode opCode = ComputeOpCode(ctx.Result, ctx.Operand1, ctx.Operand2);

            if (ctx.Operand2 is ConstantOperand)
            {
                ConstantOperand op = ctx.Operand2 as ConstantOperand;
                op = new ConstantOperand(new Mosa.Runtime.Metadata.Signatures.SigType(Mosa.Runtime.Metadata.CilElementType.U1), op.Value);
                emitter.Emit(opCode, ctx.Result, ctx.Operand1, op);
            }
            else
            {
                emitter.Emit(opCode, ctx.Result, ctx.Operand1, ctx.Operand2);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Performs stage specific processing on the compiler context.
        /// </summary>
        public void Run()
        {
            bool remove = false;

            foreach (BasicBlock block in BasicBlocks)
            {
                for (Context ctx = new Context(InstructionSet, block); !ctx.EndOfInstruction; ctx.GotoNext())
                {
                    if (ctx.Instruction is IR.MoveInstruction || ctx.Instruction is CIL.StlocInstruction)
                    {
                        if (ctx.Operand1 is ConstantOperand)
                        {
                            // HACK: We can't track a constant through a register, so we keep those moves
                            if (ctx.Result is StackOperand)
                            {
                                Debug.Assert(ctx.Result.Definitions.Count == 1, @"Operand defined multiple times. Instruction stream not in SSA form!");
                                ctx.Result.Replace(ctx.Operand1, InstructionSet);
                                remove = true;
                            }
                        }
                    }
                    else if (ctx.Instruction is IR.PhiInstruction)
                    {
                        IR.PhiInstruction phi    = (IR.PhiInstruction)ctx.Instruction;
                        ConstantOperand   co     = ctx.Operand2 as ConstantOperand;
                        List <BasicBlock> blocks = ctx.Other as List <BasicBlock>;                              // FIXME PG / ctx has moved
                        if (co != null && blocks.Count == 1)
                        {
                            // We can remove the phi, as it is only defined once
                            // HACK: We can't track a constant through a register, so we keep those moves
                            if (!ctx.Result.IsRegister)
                            {
                                Debug.Assert(ctx.Result.Definitions.Count == 1, @"Operand defined multiple times. Instruction stream not in SSA form!");
                                ctx.Result.Replace(co, InstructionSet);
                                remove = true;
                            }
                        }
                    }

                    // Shall we remove this instruction?
                    if (remove)
                    {
                        ctx.Remove();
                        remove = false;
                    }
                }
            }
        }
        /// <summary>
        /// This function emits a constant variable into the read-only data section.
        /// </summary>
        /// <param name="op">The operand to emit as a constant.</param>
        /// <returns>An operand, which represents the reference to the read-only constant.</returns>
        /// <remarks>
        /// This function checks if the given operand needs to be moved into the read-only data
        /// section of the executable. For x86 this concerns only floating point operands, as these
        /// can't be specified in inline assembly.<para/>
        /// This function checks if the given operand needs to be moved and rewires the operand, if
        /// it must be moved.
        /// </remarks>
        protected Operand EmitConstant(Operand op)
        {
            ConstantOperand cop = op as ConstantOperand;

            if (cop != null && (cop.StackType == StackTypeCode.F || cop.StackType == StackTypeCode.Int64))
            {
                int size, alignment;
                architecture.GetTypeRequirements(cop.Type, out size, out alignment);

                string name = String.Format("C_{0}", Guid.NewGuid());
                using (Stream stream = methodCompiler.Linker.Allocate(name, SectionKind.ROData, size, alignment))
                {
                    byte[] buffer;

                    switch (cop.Type.Type)
                    {
                    case CilElementType.R4:
                        buffer = LittleEndianBitConverter.GetBytes((float)cop.Value);
                        break;

                    case CilElementType.R8:
                        buffer = LittleEndianBitConverter.GetBytes((double)cop.Value);
                        break;

                    case CilElementType.I8:
                        buffer = LittleEndianBitConverter.GetBytes((long)cop.Value);
                        break;

                    case CilElementType.U8:
                        buffer = LittleEndianBitConverter.GetBytes((ulong)cop.Value);
                        break;

                    default:
                        throw new NotSupportedException();
                    }

                    stream.Write(buffer, 0, buffer.Length);
                }

                // FIXME: Attach the label operand to the linker symbol
                // FIXME: Rename the operand to SymbolOperand
                // FIXME: Use the provided name to link
                LabelOperand lop = new LabelOperand(cop.Type, name);
                op = lop;
            }
            return(op);
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="gmbEmailAddress">The email address for Google My Business
        /// account.</param>
        /// <param name="gmbAccessToken">The OAuth2 access token for Google
        /// My Business account.</param>
        /// <param name="businessAccountIdentifier">The account identifier for
        /// Google My Business account.</param>
        public void Run(AdWordsUser user, string gmbEmailAddress, string gmbAccessToken,
                        string businessAccountIdentifier)
        {
            FeedService feedService = (FeedService)user.GetService(AdWordsService.v201502.FeedService);

            CustomerFeedService customerFeedService = (CustomerFeedService)user.GetService(
                AdWordsService.v201502.CustomerFeedService);

            // Create a feed that will sync to the Google My Business account
            // specified by gmbEmailAddress. Do not add FeedAttributes to this object,
            // as AdWords will add them automatically because this will be a
            // system generated feed.
            Feed gmbFeed = new Feed();

            gmbFeed.name = String.Format("Google My Business feed #{0}",
                                         ExampleUtilities.GetRandomString());

            PlacesLocationFeedData feedData = new PlacesLocationFeedData();

            feedData.emailAddress = gmbEmailAddress;
            feedData.businessAccountIdentifier = businessAccountIdentifier;

            OAuthInfo oAuthInfo = new OAuthInfo();

            oAuthInfo.httpMethod = "GET";

            // Permissions for the AdWords API scope will also cover GMB.
            oAuthInfo.httpRequestUrl          = user.Config.GetDefaultOAuth2Scope();
            oAuthInfo.httpAuthorizationHeader = string.Format("Bearer {0}", gmbAccessToken);
            feedData.oAuthInfo = oAuthInfo;

            gmbFeed.systemFeedGenerationData = feedData;

            // Since this feed's feed items will be managed by AdWords,
            // you must set its origin to ADWORDS.
            gmbFeed.origin = FeedOrigin.ADWORDS;

            // Create an operation to add the feed.
            FeedOperation feedOperation = new FeedOperation();

            feedOperation.operand   = gmbFeed;
            feedOperation.@operator = Operator.ADD;

            try {
                // Add the feed. Since it is a system generated feed, AdWords will
                // automatically:
                // 1. Set up the FeedAttributes on the feed.
                // 2. Set up a FeedMapping that associates the FeedAttributes of the
                //    feed with the placeholder fields of the LOCATION placeholder
                //    type.
                FeedReturnValue addFeedResult = feedService.mutate(new FeedOperation[] { feedOperation });
                Feed            addedFeed     = addFeedResult.value[0];
                Console.WriteLine("Added GMB feed with ID {0}", addedFeed.id);

                // Add a CustomerFeed that associates the feed with this customer for
                // the LOCATION placeholder type.
                CustomerFeed customerFeed = new CustomerFeed();
                customerFeed.feedId           = addedFeed.id;
                customerFeed.placeholderTypes = new int[] { PLACEHOLDER_LOCATION };

                // Create a matching function that will always evaluate to true.
                Function        customerMatchingFunction = new Function();
                ConstantOperand constOperand             = new ConstantOperand();
                constOperand.type                   = ConstantOperandConstantType.BOOLEAN;
                constOperand.booleanValue           = true;
                customerMatchingFunction.lhsOperand = new FunctionArgumentOperand[] { constOperand };
                customerMatchingFunction.@operator  = FunctionOperator.IDENTITY;
                customerFeed.matchingFunction       = customerMatchingFunction;

                // Create an operation to add the customer feed.
                CustomerFeedOperation customerFeedOperation = new CustomerFeedOperation();
                customerFeedOperation.operand   = customerFeed;
                customerFeedOperation.@operator = Operator.ADD;

                // After the completion of the Feed ADD operation above the added feed
                // will not be available for usage in a CustomerFeed until the sync
                // between the AdWords and GMB accounts completes.  The loop below
                // will retry adding the CustomerFeed up to ten times with an
                // exponential back-off policy.
                CustomerFeed addedCustomerFeed = null;

                AdWordsAppConfig config = new AdWordsAppConfig();
                config.RetryCount = 10;

                ErrorHandler errorHandler = new ErrorHandler(config);
                do
                {
                    try {
                        CustomerFeedReturnValue customerFeedResult =
                            customerFeedService.mutate(new CustomerFeedOperation[] { customerFeedOperation });
                        addedCustomerFeed = customerFeedResult.value[0];

                        Console.WriteLine("Added CustomerFeed for feed ID {0} and placeholder type {1}",
                                          addedCustomerFeed.feedId, addedCustomerFeed.placeholderTypes[0]);
                        break;
                    } catch (AdWordsApiException e) {
                        ApiException apiException = (ApiException)e.ApiException;
                        foreach (ApiError error in apiException.errors)
                        {
                            if (error is CustomerFeedError)
                            {
                                if ((error as CustomerFeedError).reason ==
                                    CustomerFeedErrorReason.MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE)
                                {
                                    errorHandler.DoExponentialBackoff();
                                    errorHandler.IncrementRetriedAttempts();
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                    }
                } while (errorHandler.HaveMoreRetryAttemptsLeft());

                // OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at
                // the Campaign level.  This will be similar to the CampaignFeed in the
                // AddSiteLinks example, except you can also filter based on the
                // business name and category of each FeedItem by using a
                // FeedAttributeOperand in your matching function.

                // OPTIONAL: Create an AdGroupFeed for even more fine grained control
                // over which feed items are used at the AdGroup level.
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to create customer feed.", e);
            }
        }
Esempio n. 10
0
 public bool Equals(ConstantOperand <T> other) => other != null && object.Equals(this.Value, other.Value);
Esempio n. 11
0
        /// <summary>
        /// Decodes the specified instruction.
        /// </summary>
        /// <param name="ctx">The context.</param>
        /// <param name="decoder">The instruction decoder, which holds the code stream.</param>
        public override void Decode(Context ctx, IInstructionDecoder decoder)
        {
            // Decode base classes first
            base.Decode(ctx, decoder);

            ConstantOperand constantValueOperand;

            // Opcode specific handling
            switch (opcode)
            {
            case OpCode.Ldc_i4:
            {
                int i = decoder.DecodeInt();
                constantValueOperand = new ConstantOperand(new SigType(CilElementType.I4), i);
            }
            break;

            case OpCode.Ldc_i4_s:
            {
                sbyte sb = decoder.DecodeSByte();
                constantValueOperand = new ConstantOperand(new SigType(CilElementType.I4), sb);
            }
            break;

            case OpCode.Ldc_i8:
            {
                long l = decoder.DecodeLong();
                constantValueOperand = new ConstantOperand(new SigType(CilElementType.I8), l);
            }
            break;

            case OpCode.Ldc_r4:
            {
                float f = decoder.DecodeFloat();
                constantValueOperand = new ConstantOperand(new SigType(CilElementType.R4), f);
            }
            break;

            case OpCode.Ldc_r8:
            {
                double d = decoder.DecodeDouble();
                constantValueOperand = new ConstantOperand(new SigType(CilElementType.R8), d);
            }
            break;

            case OpCode.Ldnull:
                constantValueOperand = ConstantOperand.GetNull();
                break;

            case OpCode.Ldc_i4_0:
                constantValueOperand = ConstantOperand.FromValue(0);
                break;

            case OpCode.Ldc_i4_1:
                constantValueOperand = ConstantOperand.FromValue(1);
                break;

            case OpCode.Ldc_i4_2:
                constantValueOperand = ConstantOperand.FromValue(2);
                break;

            case OpCode.Ldc_i4_3:
                constantValueOperand = ConstantOperand.FromValue(3);
                break;

            case OpCode.Ldc_i4_4:
                constantValueOperand = ConstantOperand.FromValue(4);
                break;

            case OpCode.Ldc_i4_5:
                constantValueOperand = ConstantOperand.FromValue(5);
                break;

            case OpCode.Ldc_i4_6:
                constantValueOperand = ConstantOperand.FromValue(6);
                break;

            case OpCode.Ldc_i4_7:
                constantValueOperand = ConstantOperand.FromValue(7);
                break;

            case OpCode.Ldc_i4_8:
                constantValueOperand = ConstantOperand.FromValue(8);
                break;

            case OpCode.Ldc_i4_m1:
                constantValueOperand = ConstantOperand.FromValue(-1);
                break;

            default:
                throw new System.NotImplementedException();
            }

            ctx.Operand1 = constantValueOperand;
            ctx.Result   = decoder.Compiler.CreateTemporary(constantValueOperand.Type);
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="campaignId">Id of the campaign to which targeting criteria
        /// are added.</param>
        /// <param name="feedId">ID of a feed that has been configured for location
        /// targeting, meaning it has an ENABLED FeedMapping with criterionType of
        /// 77. Feeds linked to a GMB account automatically have this FeedMapping.
        /// If you don't have such a feed, set this value to null.</param>
        public void Run(AdWordsUser user, long campaignId, long?feedId)
        {
            // Get the CampaignCriterionService.
            CampaignCriterionService campaignCriterionService =
                (CampaignCriterionService)user.GetService(
                    AdWordsService.v201506.CampaignCriterionService);

            // Create language criteria.
            // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html
            // for a detailed list of language codes.
            Language language1 = new Language();

            language1.id = 1002; // French
            CampaignCriterion languageCriterion1 = new CampaignCriterion();

            languageCriterion1.campaignId = campaignId;
            languageCriterion1.criterion  = language1;

            Language language2 = new Language();

            language2.id = 1005; // Japanese
            CampaignCriterion languageCriterion2 = new CampaignCriterion();

            languageCriterion2.campaignId = campaignId;
            languageCriterion2.criterion  = language2;

            // Target Tier 3 income group near Miami, Florida.
            LocationGroups incomeLocationGroups = new LocationGroups();

            IncomeOperand incomeOperand = new IncomeOperand();

            // Tiers are numbered 1-10, and represent 10% segments of earners.
            // For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc.
            // Tiers 6 through 10 are grouped into TIER_6_TO_10.
            incomeOperand.tier = IncomeTier.TIER_3;

            GeoTargetOperand geoTargetOperand1 = new GeoTargetOperand();

            geoTargetOperand1.locations = new long[] { 1015116 }; // Miami, FL.

            incomeLocationGroups.matchingFunction            = new Function();
            incomeLocationGroups.matchingFunction.lhsOperand =
                new FunctionArgumentOperand[] { incomeOperand };
            incomeLocationGroups.matchingFunction.@operator  = FunctionOperator.AND;
            incomeLocationGroups.matchingFunction.rhsOperand =
                new FunctionArgumentOperand[] { geoTargetOperand1 };

            CampaignCriterion locationGroupCriterion1 = new CampaignCriterion();

            locationGroupCriterion1.campaignId = campaignId;
            locationGroupCriterion1.criterion  = incomeLocationGroups;

            // Target places of interest near Downtown Miami, Florida.
            LocationGroups interestLocationGroups = new LocationGroups();

            PlacesOfInterestOperand placesOfInterestOperand = new PlacesOfInterestOperand();

            placesOfInterestOperand.category = PlacesOfInterestOperandCategory.DOWNTOWN;

            GeoTargetOperand geoTargetOperand2 = new GeoTargetOperand();

            geoTargetOperand2.locations = new long[] { 1015116 }; // Miami, FL.

            interestLocationGroups.matchingFunction            = new Function();
            interestLocationGroups.matchingFunction.lhsOperand =
                new FunctionArgumentOperand[] { placesOfInterestOperand };
            interestLocationGroups.matchingFunction.@operator  = FunctionOperator.AND;
            interestLocationGroups.matchingFunction.rhsOperand =
                new FunctionArgumentOperand[] { geoTargetOperand2 };

            CampaignCriterion locationGroupCriterion2 = new CampaignCriterion();

            locationGroupCriterion2.campaignId = campaignId;
            locationGroupCriterion2.criterion  = interestLocationGroups;

            CampaignCriterion locationGroupCriterion3 = new CampaignCriterion();

            if (feedId.HasValue)
            {
                // Distance targeting. Area of 10 miles around targets above.
                ConstantOperand radius = new ConstantOperand();
                radius.type        = ConstantOperandConstantType.DOUBLE;
                radius.unit        = ConstantOperandUnit.MILES;
                radius.doubleValue = 10.0;
                LocationExtensionOperand distance = new LocationExtensionOperand();
                distance.radius = radius;

                LocationGroups radiusLocationGroups = new LocationGroups();
                radiusLocationGroups.matchingFunction            = new Function();
                radiusLocationGroups.matchingFunction.@operator  = FunctionOperator.IDENTITY;
                radiusLocationGroups.matchingFunction.lhsOperand =
                    new FunctionArgumentOperand[] { distance };

                // FeedID should be the ID of a feed that has been configured for location
                // targeting, meaning it has an ENABLED FeedMapping with criterionType of
                // 77. Feeds linked to a GMB account automatically have this FeedMapping.
                radiusLocationGroups.feedId = feedId.Value;

                locationGroupCriterion3.campaignId = campaignId;
                locationGroupCriterion3.criterion  = radiusLocationGroups;
            }

            // Create location criteria.
            // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
            // for a detailed list of country codes.
            Location location1 = new Location();

            location1.id = 2840; // USA
            CampaignCriterion locationCriterion1 = new CampaignCriterion();

            locationCriterion1.campaignId = campaignId;
            locationCriterion1.criterion  = location1;

            Location location2 = new Location();

            location2.id = 2392; // Japan
            CampaignCriterion locationCriterion2 = new CampaignCriterion();

            locationCriterion2.campaignId = campaignId;
            locationCriterion2.criterion  = location2;

            // Add a negative campaign keyword.
            NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();

            negativeCriterion.campaignId = campaignId;

            Keyword keyword = new Keyword();

            keyword.matchType = KeywordMatchType.BROAD;
            keyword.text      = "jupiter cruise";

            negativeCriterion.criterion = keyword;

            List <CampaignCriterion> criteria = new List <CampaignCriterion>(
                new CampaignCriterion[] { languageCriterion1,
                                          languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion,
                                          locationGroupCriterion1, locationGroupCriterion2 });

            if (feedId.HasValue)
            {
                criteria.Add(locationGroupCriterion3);
            }

            List <CampaignCriterionOperation> operations = new List <CampaignCriterionOperation>();

            foreach (CampaignCriterion criterion in criteria)
            {
                CampaignCriterionOperation operation = new CampaignCriterionOperation();
                operation.@operator = Operator.ADD;
                operation.operand   = criterion;
                operations.Add(operation);
            }

            try {
                // Set the campaign targets.
                CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray());

                if (retVal != null && retVal.value != null)
                {
                    // Display campaign targets.
                    foreach (CampaignCriterion criterion in retVal.value)
                    {
                        Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                                          " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
                    }
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to set Campaign criteria.", ex);
            }
        }
Esempio n. 13
0
 public void StoreField(ConstantOperand<string> operand)
 {
     Emit(new Instruction(InstructionType.StFld, operand));
 }
Esempio n. 14
0
 public void LoadField(ConstantOperand<string> operand)
 {
     Emit(new Instruction(InstructionType.LdFld, operand));
 }
Esempio n. 15
0
 /// <summary>
 /// Determines if the given constant operand is a large constant.
 /// </summary>
 /// <remarks>
 /// Only constants, which have special types or do not fit into an immediate argument
 /// are large and are moved to memory.
 /// </remarks>
 /// <param name="co">The constant operand to check.</param>
 /// <returns>True if the constant is large and needs to be moved to a literal.</returns>
 private static bool IsLargeConstant(ConstantOperand co)
 {
     return(Array.IndexOf <CilElementType> (_largeCilTypes, co.Type.Type) != -1);
 }
        /// <summary>
        /// Add a CustomerFeed that associates the feed with this customer for
        /// the LOCATION placeholder type.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="feed">The GMB feed.</param>
        void AddCustomerFeed(AdWordsUser user, Feed feed)
        {
            using (CustomerFeedService customerFeedService = (CustomerFeedService)user.GetService(
                       AdWordsService.v201710.CustomerFeedService)) {
                // Add a CustomerFeed that associates the feed with this customer for
                // the LOCATION placeholder type.
                CustomerFeed customerFeed = new CustomerFeed();
                customerFeed.feedId           = feed.id;
                customerFeed.placeholderTypes = new int[] { PLACEHOLDER_LOCATION };

                // Create a matching function that will always evaluate to true.
                Function        customerMatchingFunction = new Function();
                ConstantOperand constOperand             = new ConstantOperand();
                constOperand.type                   = ConstantOperandConstantType.BOOLEAN;
                constOperand.booleanValue           = true;
                customerMatchingFunction.lhsOperand = new FunctionArgumentOperand[] { constOperand };
                customerMatchingFunction.@operator  = FunctionOperator.IDENTITY;
                customerFeed.matchingFunction       = customerMatchingFunction;

                // Create an operation to add the customer feed.
                CustomerFeedOperation customerFeedOperation = new CustomerFeedOperation();
                customerFeedOperation.operand   = customerFeed;
                customerFeedOperation.@operator = Operator.ADD;

                // After the completion of the Feed ADD operation above the added feed
                // will not be available for usage in a CustomerFeed until the sync
                // between the AdWords and GMB accounts completes.  The loop below
                // will retry adding the CustomerFeed up to ten times with an
                // exponential back-off policy.
                CustomerFeed addedCustomerFeed = null;

                AdWordsAppConfig config = new AdWordsAppConfig();
                config.RetryCount = 10;

                ErrorHandler errorHandler = new ErrorHandler(config);
                try {
                    do
                    {
                        try {
                            CustomerFeedReturnValue customerFeedResult =
                                customerFeedService.mutate(
                                    new CustomerFeedOperation[] { customerFeedOperation });
                            addedCustomerFeed = customerFeedResult.value[0];

                            Console.WriteLine("Added CustomerFeed for feed ID {0} and placeholder type {1}",
                                              addedCustomerFeed.feedId, addedCustomerFeed.placeholderTypes[0]);
                            break;
                        } catch (AdWordsApiException e) {
                            ApiException apiException = (ApiException)e.ApiException;
                            foreach (ApiError error in apiException.errors)
                            {
                                if (error is CustomerFeedError)
                                {
                                    if ((error as CustomerFeedError).reason ==
                                        CustomerFeedErrorReason.MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE)
                                    {
                                        errorHandler.DoExponentialBackoff();
                                        errorHandler.IncrementRetriedAttempts();
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                            }
                        }
                    } while (errorHandler.HaveMoreRetryAttemptsLeft());
                    // OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at
                    // the Campaign level.  This will be similar to the CampaignFeed in the
                    // AddSiteLinks example, except you can also filter based on the
                    // business name and category of each FeedItem by using a
                    // FeedAttributeOperand in your matching function.

                    // OPTIONAL: Create an AdGroupFeed for even more fine grained control
                    // over which feed items are used at the AdGroup level.
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to create customer feed.", e);
                }
            }
        }
    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="campaignId">Id of the campaign to which targeting criteria
    /// are added.</param>
    /// <param name="feedId">ID of a feed that has been configured for location
    /// targeting, meaning it has an ENABLED FeedMapping with criterionType of
    /// 77. Feeds linked to a GMB account automatically have this FeedMapping.
    /// If you don't have such a feed, set this value to null.</param>
    public void Run(AdWordsUser user, long campaignId, long? feedId) {
      // Get the CampaignCriterionService.
      CampaignCriterionService campaignCriterionService =
          (CampaignCriterionService) user.GetService(
              AdWordsService.v201509.CampaignCriterionService);

      // Create language criteria.
      // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html
      // for a detailed list of language codes.
      Language language1 = new Language();
      language1.id = 1002; // French
      CampaignCriterion languageCriterion1 = new CampaignCriterion();
      languageCriterion1.campaignId = campaignId;
      languageCriterion1.criterion = language1;

      Language language2 = new Language();
      language2.id = 1005; // Japanese
      CampaignCriterion languageCriterion2 = new CampaignCriterion();
      languageCriterion2.campaignId = campaignId;
      languageCriterion2.criterion = language2;

      // Target Tier 3 income group near Miami, Florida.
      LocationGroups incomeLocationGroups = new LocationGroups();

      IncomeOperand incomeOperand = new IncomeOperand();
      // Tiers are numbered 1-10, and represent 10% segments of earners.
      // For example, TIER_1 is the top 10%, TIER_2 is the 80-90%, etc.
      // Tiers 6 through 10 are grouped into TIER_6_TO_10.
      incomeOperand.tier = IncomeTier.TIER_3;

      GeoTargetOperand geoTargetOperand1 = new GeoTargetOperand();
      geoTargetOperand1.locations = new long[] { 1015116 }; // Miami, FL.

      incomeLocationGroups.matchingFunction = new Function();
      incomeLocationGroups.matchingFunction.lhsOperand =
          new FunctionArgumentOperand[] { incomeOperand };
      incomeLocationGroups.matchingFunction.@operator = FunctionOperator.AND;
      incomeLocationGroups.matchingFunction.rhsOperand =
          new FunctionArgumentOperand[] { geoTargetOperand1 };

      CampaignCriterion locationGroupCriterion1 = new CampaignCriterion();
      locationGroupCriterion1.campaignId = campaignId;
      locationGroupCriterion1.criterion = incomeLocationGroups;

      // Target places of interest near Downtown Miami, Florida.
      LocationGroups interestLocationGroups = new LocationGroups();

      PlacesOfInterestOperand placesOfInterestOperand = new PlacesOfInterestOperand();
      placesOfInterestOperand.category = PlacesOfInterestOperandCategory.DOWNTOWN;

      GeoTargetOperand geoTargetOperand2 = new GeoTargetOperand();
      geoTargetOperand2.locations = new long[] { 1015116 }; // Miami, FL.

      interestLocationGroups.matchingFunction = new Function();
      interestLocationGroups.matchingFunction.lhsOperand =
          new FunctionArgumentOperand[] { placesOfInterestOperand };
      interestLocationGroups.matchingFunction.@operator = FunctionOperator.AND;
      interestLocationGroups.matchingFunction.rhsOperand =
          new FunctionArgumentOperand[] { geoTargetOperand2 };

      CampaignCriterion locationGroupCriterion2 = new CampaignCriterion();
      locationGroupCriterion2.campaignId = campaignId;
      locationGroupCriterion2.criterion = interestLocationGroups;

      CampaignCriterion locationGroupCriterion3 = new CampaignCriterion();

      if (feedId.HasValue) {
        // Distance targeting. Area of 10 miles around targets above.
        ConstantOperand radius = new ConstantOperand();
        radius.type = ConstantOperandConstantType.DOUBLE;
        radius.unit = ConstantOperandUnit.MILES;
        radius.doubleValue = 10.0;
        LocationExtensionOperand distance = new LocationExtensionOperand();
        distance.radius = radius;

        LocationGroups radiusLocationGroups = new LocationGroups();
        radiusLocationGroups.matchingFunction = new Function();
        radiusLocationGroups.matchingFunction.@operator = FunctionOperator.IDENTITY;
        radiusLocationGroups.matchingFunction.lhsOperand =
            new FunctionArgumentOperand[] { distance };

        // FeedID should be the ID of a feed that has been configured for location
        // targeting, meaning it has an ENABLED FeedMapping with criterionType of
        // 77. Feeds linked to a GMB account automatically have this FeedMapping.
        radiusLocationGroups.feedId = feedId.Value;

        locationGroupCriterion3.campaignId = campaignId;
        locationGroupCriterion3.criterion = radiusLocationGroups;
      }

      // Create location criteria.
      // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
      // for a detailed list of country codes.
      Location location1 = new Location();
      location1.id = 2840; // USA
      CampaignCriterion locationCriterion1 = new CampaignCriterion();
      locationCriterion1.campaignId = campaignId;
      locationCriterion1.criterion = location1;

      Location location2 = new Location();
      location2.id = 2392; // Japan
      CampaignCriterion locationCriterion2 = new CampaignCriterion();
      locationCriterion2.campaignId = campaignId;
      locationCriterion2.criterion = location2;

      // Add a negative campaign keyword.
      NegativeCampaignCriterion negativeCriterion = new NegativeCampaignCriterion();
      negativeCriterion.campaignId = campaignId;

      Keyword keyword = new Keyword();
      keyword.matchType = KeywordMatchType.BROAD;
      keyword.text = "jupiter cruise";

      negativeCriterion.criterion = keyword;

      List<CampaignCriterion> criteria = new List<CampaignCriterion>(
          new CampaignCriterion[] {languageCriterion1,
          languageCriterion2, locationCriterion1, locationCriterion2, negativeCriterion,
          locationGroupCriterion1, locationGroupCriterion2});

      if (feedId.HasValue) {
        criteria.Add(locationGroupCriterion3);
      }

      List<CampaignCriterionOperation> operations = new List<CampaignCriterionOperation>();

      foreach (CampaignCriterion criterion in criteria) {
        CampaignCriterionOperation operation = new CampaignCriterionOperation();
        operation.@operator = Operator.ADD;
        operation.operand = criterion;
        operations.Add(operation);
      }

      try {
        // Set the campaign targets.
        CampaignCriterionReturnValue retVal = campaignCriterionService.mutate(operations.ToArray());

        if (retVal != null && retVal.value != null) {
          // Display campaign targets.
          foreach (CampaignCriterion criterion in retVal.value) {
            Console.WriteLine("Campaign criteria of type '{0}' was set to campaign with" +
                " id = '{1}'.", criterion.criterion.CriterionType, criterion.campaignId);
          }
        }
      } catch (Exception e) {
        throw new System.ApplicationException("Failed to set Campaign criteria.", e);
      }
    }
Esempio n. 18
0
        /// <summary>
        /// Emits an immediate operand.
        /// </summary>
        /// <param name="op">The immediate operand to emit.</param>
        public void EmitImmediate(Operand op)
        {
            byte[] imm = null;
            if (op is LocalVariableOperand)
            {
                // Add the displacement
                StackOperand so = (StackOperand)op;
                imm = LittleEndianBitConverter.GetBytes(so.Offset.ToInt32());
            }
            else if (op is LabelOperand)
            {
                _literals.Add(new Patch((op as LabelOperand).Label, _codeStream.Position));
                imm = new byte[4];
            }
            else if (op is MemoryOperand)
            {
                // Add the displacement
                MemoryOperand mo = (MemoryOperand)op;
                imm = LittleEndianBitConverter.GetBytes(mo.Offset.ToInt32());
            }
            else if (op is ConstantOperand)
            {
                // Add the immediate
                ConstantOperand co = (ConstantOperand)op;
                switch (op.Type.Type)
                {
                case CilElementType.I:
                    try
                    {
                        imm = LittleEndianBitConverter.GetBytes(Convert.ToInt32(co.Value));
                    }
                    catch (OverflowException)
                    {
                        imm = LittleEndianBitConverter.GetBytes(Convert.ToUInt32(co.Value));
                    }
                    break;

                case CilElementType.I1:
                    //imm = LittleEndianBitConverter.GetBytes(Convert.ToSByte(co.Value));
                    imm = new byte[1] {
                        Convert.ToByte(co.Value)
                    };
                    break;

                case CilElementType.I2:
                    imm = LittleEndianBitConverter.GetBytes(Convert.ToInt16(co.Value));
                    break;

                case CilElementType.I4: goto case CilElementType.I;

                case CilElementType.U1:
                    //imm = LittleEndianBitConverter.GetBytes(Convert.ToByte(co.Value));
                    imm = new byte[1] {
                        Convert.ToByte(co.Value)
                    };
                    break;

                case CilElementType.Char:
                    goto case CilElementType.U2;

                case CilElementType.U2:
                    imm = LittleEndianBitConverter.GetBytes(Convert.ToUInt16(co.Value));
                    break;

                case CilElementType.U4:
                    imm = LittleEndianBitConverter.GetBytes(Convert.ToUInt32(co.Value));
                    break;

                case CilElementType.I8:
                    imm = LittleEndianBitConverter.GetBytes(Convert.ToInt64(co.Value));
                    break;

                case CilElementType.U8:
                    imm = LittleEndianBitConverter.GetBytes(Convert.ToUInt64(co.Value));
                    break;

                case CilElementType.R4:
                    imm = LittleEndianBitConverter.GetBytes(Convert.ToSingle(co.Value));
                    break;

                case CilElementType.R8: goto default;

                default:
                    throw new NotSupportedException();
                }
            }
            else if (op is RegisterOperand)
            {
                // Nothing to do...
            }
            else
            {
                throw new NotImplementedException();
            }

            // Emit the immediate constant to the code
            if (null != imm)
            {
                _codeStream.Write(imm, 0, imm.Length);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Decodes the specified instruction.
        /// </summary>
        /// <param name="ctx">The context.</param>
        /// <param name="decoder">The instruction decoder, which holds the code stream.</param>
        public override void Decode(Context ctx, IInstructionDecoder decoder)
        {
            // Decode base classes first
            base.Decode(ctx, decoder);

            SigType type;
            object  value;

            // Opcode specific handling
            switch (_opcode)
            {
            case OpCode.Ldc_i4: {
                int i;
                decoder.Decode(out i);
                type  = new SigType(CilElementType.I4);
                value = i;
            }
            break;

            case OpCode.Ldc_i4_s: {
                sbyte sb;
                decoder.Decode(out sb);
                type  = new SigType(CilElementType.I4);
                value = sb;
            }
            break;

            case OpCode.Ldc_i8: {
                long l;
                decoder.Decode(out l);
                type  = new SigType(CilElementType.I8);
                value = l;
            }
            break;

            case OpCode.Ldc_r4: {
                float f;
                decoder.Decode(out f);
                type  = new SigType(CilElementType.R4);
                value = f;
            }
            break;

            case OpCode.Ldc_r8: {
                double d;
                decoder.Decode(out d);
                type  = new SigType(CilElementType.R8);
                value = d;
            }
            break;

            case OpCode.Ldnull:
                ctx.Result = ConstantOperand.GetNull();
                return;

            case OpCode.Ldc_i4_0:
                ctx.Result = ConstantOperand.FromValue(0);
                return;

            case OpCode.Ldc_i4_1:
                ctx.Result = ConstantOperand.FromValue(1);
                return;

            case OpCode.Ldc_i4_2:
                ctx.Result = ConstantOperand.FromValue(2);
                return;

            case OpCode.Ldc_i4_3:
                ctx.Result = ConstantOperand.FromValue(3);
                return;

            case OpCode.Ldc_i4_4:
                ctx.Result = ConstantOperand.FromValue(4);
                return;

            case OpCode.Ldc_i4_5:
                ctx.Result = ConstantOperand.FromValue(5);
                return;

            case OpCode.Ldc_i4_6:
                ctx.Result = ConstantOperand.FromValue(6);
                return;

            case OpCode.Ldc_i4_7:
                ctx.Result = ConstantOperand.FromValue(7);
                return;

            case OpCode.Ldc_i4_8:
                ctx.Result = ConstantOperand.FromValue(8);
                return;

            case OpCode.Ldc_i4_m1:
                ctx.Result = ConstantOperand.FromValue(-1);
                return;

            default:
                throw new NotImplementedException();
            }

            ctx.Result = new ConstantOperand(type, value);
            ctx.Ignore = true;
        }
Esempio n. 20
0
        private static void createSiteLinksCampaignFeed(AdWordsUser user,
                                                        SiteLinksDataHolder siteLinksData, long campaignId)
        {
            // Get the CampaignFeedService.
            CampaignFeedService campaignFeedService =
                (CampaignFeedService)user.GetService(AdWordsService.v201406.CampaignFeedService);

            // Map the feed item ids to the campaign using an IN operation.
            RequestContextOperand feedItemRequestContextOperand = new RequestContextOperand();

            feedItemRequestContextOperand.contextType = RequestContextOperandContextType.FEED_ITEM_ID;

            List <FunctionArgumentOperand> feedItemOperands = new List <FunctionArgumentOperand>();

            foreach (long feedItemId in siteLinksData.SiteLinkFeedItemIds)
            {
                ConstantOperand feedItemOperand = new ConstantOperand();
                feedItemOperand.longValue = feedItemId;
                feedItemOperand.type      = ConstantOperandConstantType.LONG;
                feedItemOperands.Add(feedItemOperand);
            }

            Function feedItemfunction = new Function();

            feedItemfunction.lhsOperand = new FunctionArgumentOperand[] { feedItemRequestContextOperand };
            feedItemfunction.@operator  = FunctionOperator.IN;
            feedItemfunction.rhsOperand = feedItemOperands.ToArray();

            // Optional: to target to a platform, define a function and 'AND' it with
            // the feed item ID link:
            RequestContextOperand platformRequestContextOperand = new RequestContextOperand();

            platformRequestContextOperand.contextType = RequestContextOperandContextType.DEVICE_PLATFORM;

            ConstantOperand platformOperand = new ConstantOperand();

            platformOperand.stringValue = "Mobile";
            platformOperand.type        = ConstantOperandConstantType.STRING;

            Function platformFunction = new Function();

            platformFunction.lhsOperand = new FunctionArgumentOperand[] { platformRequestContextOperand };
            platformFunction.@operator  = FunctionOperator.EQUALS;
            platformFunction.rhsOperand = new FunctionArgumentOperand[] { platformOperand };

            // Combine the two functions using an AND operation.
            FunctionOperand feedItemFunctionOperand = new FunctionOperand();

            feedItemFunctionOperand.value = feedItemfunction;

            FunctionOperand platformFunctionOperand = new FunctionOperand();

            platformFunctionOperand.value = platformFunction;

            Function combinedFunction = new Function();

            combinedFunction.@operator  = FunctionOperator.AND;
            combinedFunction.lhsOperand = new FunctionArgumentOperand[] {
                feedItemFunctionOperand, platformFunctionOperand
            };

            CampaignFeed campaignFeed = new CampaignFeed();

            campaignFeed.feedId           = siteLinksData.SiteLinksFeedId;
            campaignFeed.campaignId       = campaignId;
            campaignFeed.matchingFunction = combinedFunction;
            // Specifying placeholder types on the CampaignFeed allows the same feed
            // to be used for different placeholders in different Campaigns.
            campaignFeed.placeholderTypes = new int[] { PLACEHOLDER_SITELINKS };

            CampaignFeedOperation operation = new CampaignFeedOperation();

            operation.operand   = campaignFeed;
            operation.@operator = Operator.ADD;
            CampaignFeedReturnValue result =
                campaignFeedService.mutate(new CampaignFeedOperation[] { operation });

            foreach (CampaignFeed savedCampaignFeed in result.value)
            {
                Console.WriteLine("Campaign with ID {0} was associated with feed with ID {1}",
                                  savedCampaignFeed.campaignId, savedCampaignFeed.feedId);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="gmbEmailAddress">The email address for Google My Business
        /// account.</param>
        /// <param name="gmbAccessToken">The OAuth2 access token for Google
        /// My Business account.</param>
        /// <param name="businessAccountIdentifier">The account identifier for
        /// Google My Business account.</param>
        public void Run(AdWordsUser user, string gmbEmailAddress, string gmbAccessToken,
        string businessAccountIdentifier)
        {
            FeedService feedService = (FeedService) user.GetService(AdWordsService.v201601.FeedService);

              CustomerFeedService customerFeedService = (CustomerFeedService) user.GetService(
              AdWordsService.v201601.CustomerFeedService);

              // Create a feed that will sync to the Google My Business account
              // specified by gmbEmailAddress. Do not add FeedAttributes to this object,
              // as AdWords will add them automatically because this will be a
              // system generated feed.
              Feed gmbFeed = new Feed();
              gmbFeed.name = String.Format("Google My Business feed #{0}",
              ExampleUtilities.GetRandomString());

              PlacesLocationFeedData feedData = new PlacesLocationFeedData();
              feedData.emailAddress = gmbEmailAddress;
              feedData.businessAccountIdentifier = businessAccountIdentifier;

              // Optional: specify labels to filter Google My Business listings. If
              // specified, only listings that have any of the labels set are
              // synchronized into FeedItems.
              feedData.labelFilters = new string[] { "Stores in New York City" };

              OAuthInfo oAuthInfo = new OAuthInfo();
              oAuthInfo.httpMethod = "GET";

              // Permissions for the AdWords API scope will also cover GMB.
              oAuthInfo.httpRequestUrl = user.Config.GetDefaultOAuth2Scope();
              oAuthInfo.httpAuthorizationHeader = string.Format("Bearer {0}", gmbAccessToken);
              feedData.oAuthInfo = oAuthInfo;

              gmbFeed.systemFeedGenerationData = feedData;

              // Since this feed's feed items will be managed by AdWords,
              // you must set its origin to ADWORDS.
              gmbFeed.origin = FeedOrigin.ADWORDS;

              // Create an operation to add the feed.
              FeedOperation feedOperation = new FeedOperation();
              feedOperation.operand = gmbFeed;
              feedOperation.@operator = Operator.ADD;

              try {
            // Add the feed. Since it is a system generated feed, AdWords will
            // automatically:
            // 1. Set up the FeedAttributes on the feed.
            // 2. Set up a FeedMapping that associates the FeedAttributes of the
            //    feed with the placeholder fields of the LOCATION placeholder
            //    type.
            FeedReturnValue addFeedResult = feedService.mutate(new FeedOperation[] { feedOperation });
            Feed addedFeed = addFeedResult.value[0];
            Console.WriteLine("Added GMB feed with ID {0}", addedFeed.id);

            // Add a CustomerFeed that associates the feed with this customer for
            // the LOCATION placeholder type.
            CustomerFeed customerFeed = new CustomerFeed();
            customerFeed.feedId = addedFeed.id;
            customerFeed.placeholderTypes = new int[] { PLACEHOLDER_LOCATION };

            // Create a matching function that will always evaluate to true.
            Function customerMatchingFunction = new Function();
            ConstantOperand constOperand = new ConstantOperand();
            constOperand.type = ConstantOperandConstantType.BOOLEAN;
            constOperand.booleanValue = true;
            customerMatchingFunction.lhsOperand = new FunctionArgumentOperand[] { constOperand };
            customerMatchingFunction.@operator = FunctionOperator.IDENTITY;
            customerFeed.matchingFunction = customerMatchingFunction;

            // Create an operation to add the customer feed.
            CustomerFeedOperation customerFeedOperation = new CustomerFeedOperation();
            customerFeedOperation.operand = customerFeed;
            customerFeedOperation.@operator = Operator.ADD;

            // After the completion of the Feed ADD operation above the added feed
            // will not be available for usage in a CustomerFeed until the sync
            // between the AdWords and GMB accounts completes.  The loop below
            // will retry adding the CustomerFeed up to ten times with an
            // exponential back-off policy.
            CustomerFeed addedCustomerFeed = null;

            AdWordsAppConfig config = new AdWordsAppConfig();
            config.RetryCount = 10;

            ErrorHandler errorHandler = new ErrorHandler(config);
            do {
              try {
            CustomerFeedReturnValue customerFeedResult =
                customerFeedService.mutate(new CustomerFeedOperation[] { customerFeedOperation });
            addedCustomerFeed = customerFeedResult.value[0];

            Console.WriteLine("Added CustomerFeed for feed ID {0} and placeholder type {1}",
                addedCustomerFeed.feedId, addedCustomerFeed.placeholderTypes[0]);
            break;
              } catch (AdWordsApiException e) {
            ApiException apiException = (ApiException) e.ApiException;
            foreach (ApiError error in apiException.errors) {
              if (error is CustomerFeedError) {
                if ((error as CustomerFeedError).reason ==
                    CustomerFeedErrorReason.MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE) {
                  errorHandler.DoExponentialBackoff();
                  errorHandler.IncrementRetriedAttempts();
                } else {
                  throw;
                }
              }
            }
              }
            } while (errorHandler.HaveMoreRetryAttemptsLeft());

            // OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at
            // the Campaign level.  This will be similar to the CampaignFeed in the
            // AddSiteLinks example, except you can also filter based on the
            // business name and category of each FeedItem by using a
            // FeedAttributeOperand in your matching function.

            // OPTIONAL: Create an AdGroupFeed for even more fine grained control
            // over which feed items are used at the AdGroup level.
              } catch (Exception e) {
            throw new System.ApplicationException("Failed to create customer feed.", e);
              }
        }