How do you reference code in ASP.NET Web Application Packages folder?

David Anderson 206 Reputation points
2021-10-03T11:35:51.533+00:00

I have used the NuGet Package Manager in Visual Studio 2019 to install PayPal's Checkout SDK (PaypalCheckoutSdk) in a new ASP.NET Web Application project. PaypalCheckoutSdk was stored by default in the Packages folder of this project, as shown below. As instructed in Set up PayPal SDK, I also copied PayPal's .NET code for "setting up the environment" and pasted it into a new file I chose to call PayPalAPI.cs, which was stored in that same folder.

…\packages\PayPalCheckoutSdk.1.0.4\lib\netstandard2.0\

A copy of PayPalAPI.cs is shown at the end of this post. Note that it defines a public class of PayPalClient. With the guidance at Create PayPal Order, I then used VS 2019 to create a new PayPalOrder.cs page in the root of my .NET project containing PayPal's sample code for creating an order (as shown below).

My problem is that VS 2019 highlights several errors in PayPalOrder.cs.

  • Line 30: ­ The name 'PayPalClient' does not exist in the current context
  • Line 59: ­ 'OrderRequest' does not contain a definition for 'Intent'
  • Line 75: ­ 'PurchaseUnitRequest' does not contain a definition for 'Amount'
  • Line 79: ­ 'AmountWithBreakdown' does not contain a definition for 'Breakdown'
  • Line 147: ­ 'PurchaseUnitRequest' does not contain a definition for 'Shipping'
  • Line 147: ­ The type or namespace name 'ShippingDetails' could not be found

Interestingly, I found that a copy of PayPalOrder.cs placed in the same folder as the SDK itself did not display any of these errors. However, that is not a practical location for my code, as the Packages folder is not normally accessible via Visual Studio’s Solution Explorer.

I would be very grateful for any guidance on how to fix these errors, which probably all result from the inability of PayPalOrder.cs to reference the PayPalClient class defined in PayPalAPI.cs.

PayPalOrder.cs

using System;  
using System.Collections.Generic;  
using System.Threading.Tasks;  
//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.  
using PayPalCheckoutSdk.Core;  
using PayPalCheckoutSdk.Orders;  
  
// Added by me to eliminate an Http error  
using PayPalHttp;  
  
namespace Samples.CaptureIntentExamples  
{  
    public class CreateOrderSample  
    {  
  
        //2. Set up your server to receive a call from the client  
        /*  
          Method to create order  
  
          @param debug true = print response data  
          @return HttpResponse<Order> response received from API  
          @throws IOException Exceptions from API if any  
        */  
        public async static Task<HttpResponse> CreateOrder(bool debug = false)  
        {  
            var request = new OrdersCreateRequest();  
            request.Prefer("return=representation");  
            request.RequestBody(BuildRequestBody());  
            //3. Call PayPal to set up a transaction  
            var response = await PayPalClient.client().Execute(request);  
  
            if (debug)  
            {  
                var result = response.Result<Order>();  
                Console.WriteLine("Status: {0}", result.Status);  
                Console.WriteLine("Order Id: {0}", result.Id);  
                Console.WriteLine("Intent: {0}", result.Intent);  
                Console.WriteLine("Links:");  
                foreach (LinkDescription link in result.Links)  
                {  
                    Console.WriteLine("\t{0}: {1}\tCall Type: {2}", link.Rel, link.Href, link.Method);  
                }  
                AmountWithBreakdown amount = result.PurchaseUnits[0].Amount;  
                Console.WriteLine("Total Amount: {0} {1}", amount.CurrencyCode, amount.Value);  
            }  
  
            return response;  
        }  
  
        /*  
          Method to generate sample create order body with CAPTURE intent  
  
          @return OrderRequest with created order request  
         */  
        private static OrderRequest BuildRequestBody()  
        {  
            OrderRequest orderRequest = new OrderRequest()  
            {  
                Intent = "CAPTURE",  
  
                ApplicationContext = new ApplicationContext  
                {  
                    BrandName = "EXAMPLE INC",  
                    LandingPage = "BILLING",  
                    UserAction = "CONTINUE",  
                    ShippingPreference = "SET_PROVIDED_ADDRESS"  
                },  
                PurchaseUnits = new List<PurchaseUnitRequest>  
        {  
          new PurchaseUnitRequest{  
            ReferenceId =  "PUHF",  
            Description = "Sporting Goods",  
            CustomId = "CUST-HighFashions",  
            SoftDescriptor = "HighFashions",  
            Amount = new AmountWithBreakdown  
            {  
              CurrencyCode = "USD",  
              Value = "230.00",  
              Breakdown = new AmountBreakdown  
              {  
                ItemTotal = new Money  
                {  
                  CurrencyCode = "USD",  
                  Value = "180.00"  
                },  
                Shipping = new Money  
                {  
                  CurrencyCode = "USD",  
                  Value = "30.00"  
                },  
                Handling = new Money  
                {  
                  CurrencyCode = "USD",  
                  Value = "10.00"  
                },  
                TaxTotal = new Money  
                {  
                  CurrencyCode = "USD",  
                  Value = "20.00"  
                },  
                ShippingDiscount = new Money  
                {  
                  CurrencyCode = "USD",  
                  Value = "10.00"  
                }  
              }  
            },  
            Items = new List<Item>  
            {  
              new Item  
              {  
                Name = "T-shirt",  
                Description = "Green XL",  
                Sku = "sku01",  
                UnitAmount = new Money  
                {  
                  CurrencyCode = "USD",  
                  Value = "90.00"  
                },  
                Tax = new Money  
                {  
                  CurrencyCode = "USD",  
                  Value = "10.00"  
                },  
                Quantity = "1",  
                Category = "PHYSICAL_GOODS"  
              },  
              new Item  
              {  
                Name = "Shoes",  
                Description = "Running, Size 10.5",  
                Sku = "sku02",  
                UnitAmount = new Money  
                {  
                  CurrencyCode = "USD",  
                  Value = "45.00"  
                },  
                Tax = new Money  
                {  
                  CurrencyCode = "USD",  
                  Value = "5.00"  
                },  
                Quantity = "2",  
                Category = "PHYSICAL_GOODS"  
              }  
            },  
            Shipping = new ShippingDetails  
            {  
              Name = new Name  
              {  
                FullName = "John Doe"  
              },  
              AddressPortable = new AddressPortable  
              {  
                AddressLine1 = "123 Townsend St",  
                AddressLine2 = "Floor 6",  
                AdminArea2 = "San Francisco",  
                AdminArea1 = "CA",  
                PostalCode = "94107",  
                CountryCode = "US"  
              }  
            }  
          }  
        }  
            };  
  
            return orderRequest;  
        }  
  
        /*  
           This is the driver function that invokes the createOrder function  
           to create a sample order.  
        */  
        static void Main(string[] args)  
        {  
            CreateOrder(true).Wait();  
        }  
    }  
}  

PayPalAPI.cs

using System;  
using PayPalCheckoutSdk.Core;  
using PayPalHttp;  
  
using System.IO;  
using System.Text;  
using System.Runtime.Serialization.Json;  
  
namespace Samples  
{  
    public class PayPalClient  
    {  
        /**  
            Set up PayPal environment with sandbox credentials.  
            In production, use LiveEnvironment.  
         */  
        public static PayPalEnvironment environment()  
        {  
            return new SandboxEnvironment("PAYPAL-SANDBOX-CLIENT-ID","PAYPAL-SANDBOX-CLIENT-SECRET");  
        }  
  
        /**  
            Returns PayPalHttpClient instance to invoke PayPal APIs.  
         */  
        public static HttpClient client()  
        {  
            return new PayPalHttpClient(environment());  
        }  
  
        public static HttpClient client(string refreshToken)  
        {  
            return new PayPalHttpClient(environment(), refreshToken);  
        }  
  
        /**  
            Use this method to serialize Object to a JSON string.  
        */  
        public static String ObjectToJSONString(Object serializableObject)  
        {  
            MemoryStream memoryStream = new MemoryStream();  
            var writer = JsonReaderWriterFactory.CreateJsonWriter(  
                        memoryStream, Encoding.UTF8, true, true, "  ");  
            DataContractJsonSerializer ser = new DataContractJsonSerializer(serializableObject.GetType(), new DataContractJsonSerializerSettings{UseSimpleDictionaryFormat = true});  
            ser.WriteObject(writer, serializableObject);  
            memoryStream.Position = 0;  
            StreamReader sr = new StreamReader(memoryStream);  
            return sr.ReadToEnd();  
        }  
    }  
}  
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,405 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,284 questions
{count} votes

1 answer

Sort by: Most helpful
  1. David Anderson 206 Reputation points
    2021-10-05T09:06:47.4+00:00

    @AgaveJoe
    PayPal's instructions in Set up PayPal SDK provide code for "setting up the environment", which they clearly state should be placed in the same directory as the SDK (which in my case means within the solution Packages folder). However, all attempts to access the PayPalClient class defined in that code have failed. I am now of the opinion that PayPal's advice is wrong and that this code should be located within the root of the project folder. There is then no problem in accessing the PayPalClient class.

    I still have the other errors listed in my OP, but if I can't fix those I will raise a new question.