Thursday, February 29, 2024

Ups oauth2.0 in c# get rates list || ups api integration c# || c# oauth 2.0 client example

 using Newtonsoft.Json.Linq;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Text;

using System.Threading.Tasks;


namespace Ups1

{

    public class Program

    {


        static void Main()

        {


            string client_id = "clientid";

            string client_secret = "clientSecret";

        

            string ups_account_number = "AccountNumber"; 


            // ***** SHIPPING SERVICE AVAILABLE OPTIONS *****

            // Domestic

            // 14 = UPS Next Day Air Early

            // 01 = UPS Next Day Air

            // 13 = UPS Next Day Air Saver

            // 59 = UPS 2nd Day Air A.M.

            // 02 = UPS 2nd Day Air

            // 12 = UPS 3 Day Select

            // 03 = UPS Ground

            // International

            // 11 = UPS Standard

            // 07 = UPS Worldwide Express

            // 54 = UPS Worldwide Express Plus

            // 08 = UPS Worldwide Expedited

            // 65 = UPS Worldwide Saver

            // 96 = UPS Worldwide Express Freight

            // 82 = UPS Today Standard

            // 83 = UPS Today Dedicated Courier

            // 84 = UPS Today Intercity

            // 85 = UPS Today Express

            // 86 = UPS Today Express Saver

            // 70 = UPS Access Point Economy


            // ***** PACKAGE TYPE AVAILABLE OPTIONS *****

            // 01 = Bag, 

            // 02 = Box, 

            // 03 = Carton/Piece, 

            // 04 = Crate, 

            // 05 = Drum, 

            // 06 = Pallet/Skid, 

            // 07 = Roll, 

            // 08 = Tube, 


            // PACKAGE


            // var packages = new List<Package>();

           // packages.Add(new Package(0M, 0M, 0M, 60, 0M));


            var package_info = new

            {

                service = "59",

                package_type = "02",

                Weight = "10",

                length = "7",

                width = "4",

                height = "2",

            };


            // SHIPPER

            var shipper_info = new

            {

                account_number = ups_account_number,

                name = "fromaddressname",

                address1 = "addr1",

                address2 = "addr2",

                address3 = "",

                city = "city",

                state = "state",

                zip = "zipcode",

                country = "us",

            };


            // FROM ADDRESS

            var from_address_info = new

            {

                name = "fromaddressname",

                address1 = "addr1",

                address2 = "addr2",

                address3 = "",

                city = "city",

                state = "state",

                zip = "zipcode",

                country = "US",

            };


            // TO ADDRESS

            var to_address_info = new

            {

                name = "Thomas Jefferson",

                address1 = "931 Thomas Jefferson Parkway",

                address2 = "",

                address3 = "",

                city = "Charlottesville",

                state = "CO",

                zip = "80125",

                country = "US",

            };


            // Get Token

            var accessToken = GetToken(client_id, client_secret);

             // Use API to get price

            var totalCharges = GetShippingCost(accessToken, shipper_info, to_address_info, from_address_info, package_info);


            // Show Price

            Console.WriteLine("Total Charges: $" + totalCharges);

        }


        //static string GetToken(string client_id, string client_secret)

        //{

        //    var combineUserAndPassword = client_id + ":" + client_secret;

        //    var payload = "grant_type=client_credentials";

        //    var authorizationHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(combineUserAndPassword));


        //    using (var client = new HttpClient())

        //    {

        //        //client.DefaultRequestHeaders.Add("Content-Type", "application/json");

        //        client.DefaultRequestHeaders.Add("x-merchant-id", "string");

        //        client.DefaultRequestHeaders.Add("Authorization", authorizationHeader);


        //        var response = client.PostAsync("https://wwwcie.ups.com/security/v1/oauth/token", new StringContent(payload, Encoding.UTF8, "application/json")).Result;

        //        var result = response.Content.ReadAsStringAsync().Result;


        //        // Convert the JSON response string to an associative array

        //        var responseArray = JObject.Parse(result);


        //        // Extract the access token

        //        var accessToken = responseArray["access_token"].ToString();

        //        return accessToken;

        //    }

        //}

        static string GetToken(string client_id, string client_secret)

        {

            var combineUserAndPassword = client_id + ":" + client_secret;

            var payload = "grant_type=client_credentials";

            var authorizationHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(combineUserAndPassword));


            using (var client = new HttpClient())

            {

                client.DefaultRequestHeaders.Add("x-merchant-id", "string");

                client.DefaultRequestHeaders.Add("Authorization", authorizationHeader);


                var content = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded");

                var response = client.PostAsync("https://wwwcie.ups.com/security/v1/oauth/token", content).Result;

                var result = response.Content.ReadAsStringAsync().Result;


                // Check if the request was successful

                if (!response.IsSuccessStatusCode)

                {

                    // Handle error, log, or throw an exception

                    Console.WriteLine("Token request failed: " + result);

                    return null;

                }


                // Convert the JSON response string to an associative array

                var responseArray = JObject.Parse(result);


                // Explicitly check for null before extracting the access token

                var accessTokenTokenProperty = responseArray["access_token"];

                var accessToken = accessTokenTokenProperty != null ? accessTokenTokenProperty.ToString() : null;


                return accessToken;

            }

        }


        static decimal GetShippingCost(string accessToken, dynamic shipper_info, dynamic to_address_info, dynamic from_address_info, dynamic package_info)

        {

            var version = "v1601";

            var requestOption = "Shop";

            var query = new System.Collections.Generic.Dictionary<string, string>();


            using (var client = new HttpClient())

            {

                var payload = new

                {

                    RateRequest = new

                    {

                        Request = new

                        {

                            TransactionReference = new

                            {

                                CustomerContext = "CustomerContext"//,

                                //TransactionIdentifier = "TransactionIdentifier"

                            }

                        },

                        Shipment = new

                        {

                            Shipper = new

                            {

                                Name = shipper_info.name,

                                ShipperNumber = shipper_info.account_number,

                                Address = new

                                {

                                    AddressLine = new[]

                                {

                                    shipper_info.address1,

                                    shipper_info.address2,

                                    shipper_info.address3

                                },

                                    City = shipper_info.city,

                                    StateProvinceCode = shipper_info.state,

                                    PostalCode = shipper_info.zip,

                                    CountryCode = shipper_info.country

                                }

                            },

                            ShipTo = new

                            {

                                Name = to_address_info.name,

                                Address = new

                                {

                                    AddressLine = new[]

                                {

                                    to_address_info.address1,

                                    to_address_info.address1,

                                    to_address_info.address1

                                },

                                    City = to_address_info.city,

                                    StateProvinceCode = to_address_info.state,

                                    PostalCode = to_address_info.zip,

                                    CountryCode = to_address_info.country

                                }

                            },

                            ShipFrom = new

                            {

                                Name = from_address_info.name,

                                Address = new

                                {

                                    AddressLine = new[]

                                {

                                    from_address_info.address1,

                                    from_address_info.address2,

                                    from_address_info.address3

                                },

                                    City = from_address_info.city,

                                    StateProvinceCode = from_address_info.state,

                                    PostalCode = from_address_info.zip,

                                    CountryCode = from_address_info.country

                                }

                            },

                            PaymentDetails = new

                            {

                                ShipmentCharge = new

                                {

                                    Type = "01",

                                    BillShipper = new

                                    {

                                        AccountNumber = shipper_info.account_number

                                    }

                                }

                            },

                            Service = new

                            {

                                Code = package_info.service,

                                Description = "ground"

                            },

                            NumOfPieces = "1",

                            Package = new

                            {

                                PackagingType = new

                                {

                                    Code = package_info.package_type,

                                    Description = "Packaging"

                                },

                                Dimensions = new

                                {

                                    UnitOfMeasurement = new

                                    {

                                        Code = "IN",

                                        Description = "Inches"

                                    },

                                    Length = package_info.length,

                                    Width = package_info.width,

                                    Height = package_info.height

                                },

                                PackageWeight = new

                                {

                                    UnitOfMeasurement = new

                                    {

                                        Code = "LBS",

                                        Description = "Pounds"

                                    },

                                    Weight = package_info.Weight

                                }

                            }

                        }

                    }

                };


                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

                //client.DefaultRequestHeaders.Add("Content-Type", "application/json");

                client.DefaultRequestHeaders.Add("transId", "string");

                client.DefaultRequestHeaders.Add("transactionSrc", "testing");


                var response = client.PostAsync("https://wwwcie.ups.com/api/rating/v1/Rate?{ToQueryString(query)}", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json")).Result;

                //var response = client.PostAsync("https://wwwcie.ups.com/api/rating/{version}/{requestOption}?{ToQueryString(query)}", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json")).Result;

                var result = response.Content.ReadAsStringAsync().Result;


                // Convert the JSON response string to an associative array

                var responseArray = JObject.Parse(result);


                // Extract the total charges

                var totalCharges = Convert.ToDecimal(responseArray["RateResponse"]["RatedShipment"]["TotalCharges"]["MonetaryValue"]);

                return totalCharges;

            }

        }


        static string ToQueryString(System.Collections.Generic.Dictionary<string, string> query)

        {

            var array = query.Select(kvp => "{Uri.EscapeDataString(kvp.Key)}={Uri.EscapeDataString(kvp.Value)}").ToArray();

            return "?" + string.Join("&", array);

        }

    }

}


Note : Change your client id , Account Number and client secret and add the correct  from and to address in the above program

After token expire we will get 

this error First = {"response": {

  "errors": [

    {

      "code": "250002",

      "message": "Invalid Authentication Information."

    }

  ]

}}

Monday, February 19, 2024

boxing and unboxing

In C#, boxing and unboxing are concepts related to converting value types (such as int, char, etc.) to reference types (such as object). Let’s explore both concepts with examples:

  1. Boxing:

    • Boxing is the process of converting a value type to the type object or any interface type implemented by that value type.
    • When the Common Language Runtime (CLR) boxes a value type, it wraps the value inside an object instance and stores it on the managed heap.
    • Here’s an example of boxing:
      int i = 123; // The following line boxes 'i'.
      object o = i;
      
    • In this example, the integer variable i is boxed and assigned to the object variable o.
  2. Unboxing:

    • Unboxing is the process of extracting the value type from an object.
    • It converts the object back to its original value type.
    • Example of unboxing:
      o = 123; // Unboxing: extract the value from 'o' and assign it to 'i'.
      int unboxedValue = (int)o;
      
  3. Practical Example:

    • Let’s create a heterogeneous collection using an ArrayList (a dynamically sized array of objects):
      ArrayList mixedList = new ArrayList();
      mixedList.Add("First Group:"); // Add a string element
      for (int j = 1; j < 5; j++)
      {
          mixedList.Add(j); // Add integers (boxing occurs)
      }
      mixedList.Add("Second Group:");
      for (int j = 5; j < 10; j++)
      {
          mixedList.Add(j);
      }
      
      // Display the elements in the list
      foreach (var item in mixedList)
      {
          Console.WriteLine(item);
      }
      
      // Calculate the sum of squares of the first group of integers
      var sum = 0;
      for (var j = 1; j < 5; j++)
      {
          sum += (int)mixedList[j] * (int)mixedList[j]; // Unboxing
      }
      Console.WriteLine($"Sum: {sum}"); // Output: Sum: 30
      
    • In this example, we box integers when adding them to the ArrayList and unbox them during the sum calculation.

Remember that boxing and unboxing have performance implications, so use them judiciously.

Sunday, February 18, 2024

what is asp.net mvc framework

 The ASP.NET MVC (Model-View-Controller) framework is an architectural and design pattern used for developing web applications. Let’s break down what it entails:

  1. Model: The Model component represents the data-related logic in the application. It handles data retrieval, storage, and manipulation. For instance, it can interact with a database or manage business logic.

  2. View: The View component is responsible for the user interface (UI) logic. It generates the visual representation that users interact with. Views are created based on data provided by the Model, but they communicate with the Controller.

  3. Controller: The Controller acts as an intermediary between the Model and the View. It processes incoming requests, manipulates data using the Model, and instructs the View on how to render the final output. The Controller doesn’t handle data logic directly; instead, it orchestrates the flow.

Here are some key points about ASP.NET MVC:

  • Clean Separation: ASP.NET MVC promotes a clean separation of concerns. By dividing the application into distinct components (Model, View, and Controller), developers can manage complexity more effectively.

  • Scalability and Extensibility: It’s a powerful framework for building scalable and extensible projects. Developers can create robust web applications that are easy to maintain.

  • URL Control: ASP.NET MVC provides control over URLs, making it straightforward to design web application architectures with comprehensible and searchable URLs.

  • Test Driven Development (TDD): The framework supports TDD, allowing developers to write tests for their code and ensure its correctness.

Overall, ASP.NET MVC is widely used in industry-standard web development and is also suitable for designing mobile apps.

Thursday, February 15, 2024

Interface

  1. What Is an Interface in C#?

    • An interface in C# is a fully unimplemented class used for declaring a set of operations or methods that an object must provide.
    • It serves as a pure abstract class, allowing us to define only abstract methods (methods without a body).
    • Interfaces are used to achieve multiple inheritances, which classes cannot achieve directly.
    • They also ensure full abstraction because interface methods cannot have a method body.
    • In C#, an interface is a fundamental concept defining a contract or a set of rules that a class must adhere to.
    • It specifies a list of methods, properties, events, or indexers that a class implementing the interface must provide.
    • Interfaces allow you to define a common set of functionality that multiple classes can share, promoting code reusability and ensuring a consistent structure for related classes.
  2. Differences Between Concrete Class, Abstract Class, and Interface in C#:

    • Concrete Class:
      • Contains only non-abstract methods (methods with a method body).
    • Abstract Class:
      • Contains both non-abstract methods and abstract methods (methods without a method body).
    • Interface:
      • Contains only abstract methods (methods without a method body).
  3. Real-World Example: Library Management System

    • Imagine building a Library Management System where you need to handle different types of library items (books, DVDs, etc.).

    • We can define an interface called ILibraryItem to specify common behavior for all library items:

      interface ILibraryItem
      {
          string Title { get; set; }
          void CheckOut(string borrower);
          void Return();
      }
      
    • Now, let’s implement this interface for specific library items:

      • Book:

        class Book : ILibraryItem
        {
            public string Title { get; set; }
        
            public void CheckOut(string borrower)
            {
                // Logic for checking out a book
            }
        
            public void Return()
            {
                // Logic for returning a book
            }
        }
        
      • DVD:

        class DVD : ILibraryItem
        {
            public string Title { get; set; }
        
            public void CheckOut(string borrower)
            {
                // Logic for checking out a DVD
            }
        
            public void Return()
            {
                // Logic for returning a DVD
            }
        }
        
    • By using the ILibraryItem interface, we ensure that all library items adhere to the same contract, allowing consistent handling across different types of items.

    • Interfaces promote code reusability, maintainability, and a consistent structure for related classes. 

Remember, interfaces provide a powerful way to define contracts and encourage good design practices in your C# code!

Tuesday, February 6, 2024

Introduction to C#

 Certainly! C# (pronounced “C-Sharp”) is a powerful and versatile programming language created by Microsoft. Let’s explore some key points about C#:

  1. What is C#?

    • C# is an object-oriented programming language that runs on the .NET Framework.
    • It has its roots in the C family of languages and shares similarities with C++, Java, and JavaScript.
    • The first version of C# was released in 2002, and the latest version (C# 12) arrived in November 2023.
    • C# is used for a wide range of applications, including:
      • Mobile applications
      • Desktop applications
      • Web applications
      • Web services
      • Games
      • Database applications
      • And much more!
  2. Why Use C#?

    • Popularity: C# is one of the most popular programming languages globally.
    • Ease of Learning: It is easy to learn and has a straightforward syntax.
    • Community Support: C# has a large and active community.
    • Object-Oriented: C# provides a clear structure to programs, allowing code reuse and lowering development costs.
    • Familiarity: If you know C, C++, or Java, transitioning to C# is relatively straightforward.
  3. Getting Started:

    • You don’t need prior programming experience to learn C#.
    • Explore tutorials, videos, and interactive lessons to grasp the basics of C#.
    • Whether you’re building web apps, desktop software, or games, C# offers a robust foundation for your projects.

Happy coding! 🚀 If you’re ready to dive in, you can start learning C# through resources like W3SchoolsMicrosoft’s .NET Learn, or Microsoft Learn’s C# tutorials

AVS settings Authorize.Net account

Certainly! Configuring the Address Verification Service (AVS) settings in your Authorize.Net account is essential for fraud prevention and ensuring secure credit card transactions. Let’s walk through the steps:

  1. Log In to the Merchant Interface:

    • Access the Authorize.Net Merchant Interface using your credentials.
  2. Navigate to AVS Settings:

    • Once logged in, follow these steps:
      • Click on Account.
      • Under Basic Fraud Settings, select Address Verification Service.
  3. Review and Adjust AVS Response Codes:

    • You’ll see a list of AVS response codes. These codes indicate the results of matching the billing address provided by the cardholder with the address on file at the credit card issuing bank.
    • Here are some common AVS response codes:
      • B: Address information not submitted in the transaction.
      • E: Invalid AVS data or AVS not allowed for the card type.
      • R: AVS unavailable during transaction processing (retry later).
      • G: Non-U.S. card issuing bank (does not support AVS).
      • U: Address information not available for the customer’s credit card.
      • S: U.S. card issuing bank does not support AVS.
      • N: Neither street address nor 5-digit ZIP code matches.
      • A: Street address matches, but ZIP code does not.
      • Z: First 5 digits of ZIP code match, but street address does not.
      • W: 9-digit ZIP code matches, but street address does not.
      • Y: Street address and first 5 digits of ZIP code match perfectly.
  4. Configure Your AVS Rejection Settings:

    • Decide which AVS response codes you want to use for rejecting transactions.
    • Follow these steps:
      • Click the checkbox next to each AVS response code you want to reject.
      • Click Submit to apply your settings.
      • A confirmation message will indicate that your changes have been successfully applied.
  5. Important Considerations:

    • AVS is not foolproof and should not be solely relied upon for absolute protection against suspicious transactions.
    • Be aware that some legitimate transactions may be declined due to AVS settings.
    • Carefully assess your business’s risk level when configuring AVS mismatch rejection settings.

Remember that AVS helps enhance security, but it’s essential to strike a balance between fraud prevention and customer experience. Most banks and Merchant Service Providers recommend using AVS to avoid non-qualified transaction surcharges. Happy configuring! 🛡️🔒