Thursday, March 21, 2024

.net core

11. **What is Entity Framework Core?**

    - Entity Framework Core is like a helper that makes it easier to talk to databases in a program. It helps the program store and get information from databases without needing to write a lot of complicated code.


12. **Difference between Code First and Database First in Entity Framework Core?**

    - Code First is like building a house from scratch based on a drawing, while Database First is like making a drawing of a house based on one that's already built. Code First starts with writing code to describe the database, while Database First starts with the existing database and creates code from it.


13. **Difference between eager loading and lazy loading in Entity Framework Core?**

    - Eager loading is like getting all the groceries you need in one trip to the store, while lazy loading is like going to the store only when you need something. Eager loading loads all the related information upfront, while lazy loading loads it only when necessary.


14. **Difference between a DbSet and a DbContext in Entity Framework Core?**

    - A DbSet is like a table in a database where you keep things, while a DbContext is like the room where you manage everything related to the database. DbSet is where you store specific types of data, while DbContext is the overall manager for dealing with the database.


15. **What is LINQ?**

    - LINQ is like a special language that helps talk to databases or lists of things in a program. It makes it easier to search, filter, or sort data without writing lots of complicated code.


16. **What is a Lambda expression in .NET Core?**

    - A Lambda expression is like a quick and simple way of writing down a small piece of code to do something specific. It's like writing a tiny recipe for a task in the program.


17. **Purpose of the using statement in C#?**

    - The using statement is like a reminder to clean up after yourself in the program. It makes sure that when you're done using something, it's put away neatly and not left lying around, which keeps the program running smoothly.


18. **Difference between an abstract class and an interface in C#?**

    - An abstract class is like a template that can do some things by itself, while an interface is like a promise to do certain things without saying how. An abstract class can do some work, while an interface just says what needs to be done.


19. **What is a delegate in C#?**

    - A delegate is like a messenger that helps different parts of the program talk to each other. It's used to pass around actions or messages between different pieces of code.


20. **Purpose of the async/await keywords in C#?**

    - The async/await keywords are like helpers that keep the program running smoothly even when it's doing something that takes a long time. They make sure the program can do other things while waiting for something to finish.


21. **What is a generic type in C#?**

    - A generic type is like a container that can hold different kinds of things inside. It's a way of making code more flexible so it can work with different types of data without being too specific.


22. **What is a nullable type in C#?**

    - A nullable type is like a box that can hold a value or nothing at all. It's used when something might not have a value and needs to be treated carefully in the program.


23. **Difference between a struct and a class in C#?**

    - A struct is like a small, simple container that holds data directly inside, while a class is like a bigger, more complex container that holds a reference to the data somewhere else. Structs are used for small, simple things, while classes are used for bigger, more complicated things.


24. **Purpose of the const keyword in C#?**

    - The const keyword is like a promise that something will never change. It's used for values that are known from the start and won't ever need to be different during the program's run.


25. **Difference between a static class and a non-static class in C#?**

    - A static class is like a clubhouse where everyone can hang out, but there's only one of them and nobody can change it. A non-static class is like a clubhouse where each person has their own space and can make changes to it.


26. **Purpose of the lock keyword in C#?**

    - The lock keyword is like a security guard that keeps track of who's using something important in the program. It makes sure that only one thing can use it at a time to avoid problems.


27. **Difference between the StringBuilder and String classes in C#?**

    - StringBuilder is like a special tool for building big, complicated strings quickly and efficiently, while String is like a box that holds a string but can't be changed once it's made.


28. **Purpose of the yield keyword in C#?**

    - The yield keyword is like a magician's trick for making a list of things appear one by one as needed. It helps generate a sequence of items without having to create them all at once.


29. **What is garbage collection in .NET Core?**

    - Garbage collection is like a cleanup crew that goes around the program, picking up things that are no longer needed and making sure everything stays tidy and efficient.


30. **Difference between a value type and a reference type in .NET Core?**

    - A value type is like a box that holds something directly inside, while a reference type is like a signpost that points to where something is stored. Value types are usually smaller and faster, while reference types are more flexible.


31. **Purpose of the using directive in C#?**

    - The using directive is like a shortcut that tells the program where to find certain things it needs. It helps avoid writing long, complicated names for things every time they're used.


32. **What is a try-catch block in C#?**

    - A try-catch block is like a safety net that catches mistakes before they cause big problems. It lets the program try something risky, but if it goes wrong, it's ready to handle the situation without crashing.


33. **Purpose of the finally block in a try-catch-finally statement in C#?**

    - The finally block is like a cleanup crew that always shows up, no matter what happened before. It's used to make sure everything is put back the way it should be, even if something went wrong.


34. **What is a lambda expression in C#?**

    - A lambda expression is like a secret code that describes a small, specific task in the program. It's a quick way of writing down what needs to be done without making a big fuss about it.


35. **What is an extension method in C#?**

    - An extension method is like a special tool that adds extra functionality to something that already exists. It's used to make existing things more useful without changing them directly.


36. **Difference between a synchronous and asynchronous method in C#?**

    - A synchronous method is like doing things step by step, one after the other, while an asynchronous method is like doing multiple things at once, without waiting for each one to finish before starting the next.



What is .NET Core

1. **What is .NET Core?**

   - .NET Core is like a toolbox that helps build modern computer programs that can work on different types of computers, like Windows, Mac, or Linux.


2. **Advantages of .NET Core?**

   - It's like using a super handy tool that makes building programs easier because it works on different types of computers, it's fast, open to everyone, easy to update, and lots of people know how to use it.


3. **Difference between .NET Framework and .NET Core?**

   - Think of .NET Framework as a tool that only works on Windows computers, while .NET Core is like a more flexible tool that works on Windows, Mac, and Linux. .NET Core also doesn't need as much stuff to run as .NET Framework.


4. **Difference between ASP.NET and ASP.NET Core?**

   - ASP.NET is an older way of making websites, like using an older tool, while ASP.NET Core is a newer, more modern way that's faster and works on different computers.


5. **How does dependency injection work in .NET Core?**

   - Dependency injection is like having a friend who gives you exactly what you need when you need it. In .NET Core, it's a way for parts of a program to get what they need without having to ask for it directly.


6. **Role of the Startup.cs file in .NET Core?**

   - The Startup.cs file is like the boss who decides what tools the program needs and how they should be used. It gets things ready when the program starts.


7. **Difference between middleware and filters in .NET Core?**

   - Middleware is like a helper that stands between the program and the outside world, while filters are like special helpers that change things when information goes in or out of the program.


8. **Purpose of appsettings.json file in .NET Core?**

   - It's like a list of rules and settings for the program, such as what to do when connecting to a database or what secret codes to use.


9. **Purpose of the wwwroot folder in .NET Core?**

   - It's like a storage room for files that the program needs, like pictures or styles, that anyone using the program can access easily.


10. **Difference between Razor Pages and MVC in .NET Core?**

    - Razor Pages is like an easy way of making simple websites, while MVC is a bit more complex and good for bigger projects.


Wednesday, March 6, 2024

different type of collections in c#

In C#, collections provide a flexible way to work with groups of objects. Let’s explore the different types of collections:

  1. Indexed-Based Collections:

    • These collections allow you to access elements by their index (position). Some common indexed-based collection types include:
      • Array: A fixed-size collection of elements of the same type.
      • ArrayList: A dynamically resizable collection that can hold elements of different types.
      • List<T>: A generic list that provides type safety and dynamic resizing.
      • Queue: A first-in-first-out (FIFO) collection.
      • ConcurrentQueue<T>: A thread-safe version of the queue.
      • Stack: A last-in-first-out (LIFO) collection.
      • ConcurrentStack<T>: A thread-safe version of the stack.
      • LinkedList<T>: A doubly linked list.
  2. Key-Value Pair Collections:

    • These collections store elements as key-value pairs. Each element has both a key and a value. Common key-value pair collection types include:
      • Hashtable: A non-generic collection that uses hash codes for fast lookups.
      • SortedList: A sorted version of the Hashtable.
      • SortedList<TKey, TValue>: A generic sorted collection.
      • Dictionary<TKey, TValue>: A generic dictionary with fast key-based access.
      • ConcurrentDictionary<TKey, TValue>: A thread-safe version of the dictionary.
  3. Specialized Collections:

    • These collections serve specific purposes and have unique features:
      • KeyedCollection<TKey, TItem>: Combines list and dictionary behavior, allowing access by both index and key.
      • ReadOnlyCollectionBase: Provides a base class for creating read-only collections.
      • CollectionBase: A base class for creating strongly typed collections.
      • DictionaryBase: A base class for creating custom dictionaries.
  4. Strong Typing and Generics:

    • Generic collections (such as List<T>, Dictionary<TKey, TValue>, etc.) are the best solution for strong typing. They ensure type safety at compile time.
    • If your language does not support generics, you can extend abstract base classes (like CollectionBase) to create strongly typed collections.
  5. LINQ with Collection Types:

    • LINQ (Language Integrated Query) allows concise and powerful querying of in-memory objects.
    • LINQ queries can filter, order, and group data, improving performance.
    • Use LINQ with any type that implements IEnumerable or IEnumerable<T>.

Remember to choose the appropriate collection type based on your specific requirements! 

Tuesday, March 5, 2024

What is Interface

 Definition:

"An interface in object-oriented programming is a collection of abstract methods. It defines a contract for classes that implement it, specifying the methods that must be present in those classes. Unlike classes, an interface doesn't provide any implementation for the methods; it only declares their signatures. Classes that implement an interface must provide concrete implementations for all the methods declared in the interface."

Key Points:

  1. Abstract Methods:

    • "Interfaces consist of abstract methods, which are methods without a body. These methods serve as a blueprint for any class that implements the interface."
  2. Contract:

    • "An interface establishes a contract between the interface and the implementing classes. It specifies what methods the implementing classes must have, but it doesn't dictate how these methods should be implemented."
  3. Multiple Inheritance:

    • "One significant advantage of interfaces is that a class can implement multiple interfaces. This supports a form of multiple inheritance, allowing a class to inherit the method signatures from multiple sources."
  4. Example:

    • "For instance, consider an interface Drawable with a method draw(). Any class that implements this interface must provide its own implementation of the draw() method. This ensures a consistent way of drawing for various objects."

Use in Programming:

  • "Interfaces are used to achieve abstraction and ensure code consistency in large codebases."
  • "They are crucial in scenarios where multiple classes need to share a common set of methods without having a common base class."

When to Use Interfaces:

  • "Use interfaces when you want to define a contract that multiple classes can adhere to without specifying the implementation details."
  • "Interfaces are beneficial in scenarios where you want to achieve loose coupling between components in your system."

What is MVC

 Definition:

"MVC stands for Model-View-Controller, which is a design pattern widely used in software development to organize and structure code in a way that enhances modularity, maintainability, and scalability."

Breakdown of Components:

  1. Model:

    • "The Model represents the application's data and business logic. It encapsulates the data-related operations and responds to requests for information from the View or updates from the Controller."
  2. View:

    • "The View is responsible for presenting the data to the user. It displays the information from the Model and gathers user inputs. Views can be graphical user interfaces, web pages, or any other output representation."
  3. Controller:

    • "The Controller acts as an intermediary between the Model and the View. It receives user inputs from the View, processes them by interacting with the Model, and updates the View accordingly. It manages the flow of data between the Model and the View."

Benefits:

  • "MVC promotes the separation of concerns, making the codebase more modular and easier to maintain."
  • "It enhances code reusability and scalability, allowing for easier updates and additions to the application."
  • "Facilitates collaboration among developers, as different team members can focus on specific components without affecting others."

Real-world Example:

  • "For instance, in a web application, the Model could be responsible for handling database interactions, the View for rendering HTML pages, and the Controller for managing user requests and coordinating the interaction between the Model and the View."

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.