Ref vs Out parameter

              

Scenario: Difference between Ref vs Out parameter

Solution:

      While creating a new object two things get created:
  1. The block of memory that holds data for the object.
  2. A reference  or pointer to that block of data.
      When the object is sent through a method without ref it copies the reference pointer but not 
       the data. So If we modify a property on an object, it will affect the same data pointed to by the               earlier reference. If we set the reference to null or point it to new data it will not affect the earlier        reference and also not the data referenced by it

      When it is passed with ref keyword to a method then the actual reference to the object gets                     sent to the method and so now there only one reference to the data:

    using System;
    
    namespace ConsoleAppCore
    {
        public class Program
        {
            static void Main(string[] args)
            {
                var profile = new Profile
                {
                    Id = 1,
                    Name = "Test User",
                    Address = "Los Angeles"
                };
    
                Console.WriteLine(
                    $"Outside the Method Profile (Before Method call): {profile.Id} - {profile.Name}, {profile.Addrress}");
    
                ChangeAddress(profile);
    
                Console.WriteLine(
                $"Outside the Method Profile (After Method call w/o ref): {profile.Id} - {profile.Name}, {profile.Addrress}");
                Console.ReadLine();
    
                ChangeAddressRef(ref profile);
    
                Console.WriteLine(
                    $"Outside the Method Profile (After Method call w/ ref): {profile.Id} - {profile.Name}, {profile.Addrress}");
                Console.ReadLine();
            }
    
            private static bool ChangeAddress(Profile data)
            {
                //data.Addrress = "New York";
                //Console.WriteLine(
                //    $"Outside the Method Profile (Before Method call): {data.Id} - {data.Name}, {data.Addrress}");
    
                data = null;
    
                return true;
            }
    
            private static bool ChangeAddressRef(ref Profile data)
            {
                //data.Addrress = "New York";
                //Console.WriteLine(
                //    $"Outside the Method Profile (Before Method call): {data.Id} - {data.Name}, {data.Addrress}");
    
                data = new Profile();
    
                return true;
            }
        }
    
        public class Profile
        {
            public int Id{ get; set; }
            public string Name { get; set; }
            public string Address { get; set; }
        }
    }

    SQL query XML - Modify XML column

                  

    Scenario: Modify attribute of SQL table XML column

    Solution:

      DECLARE @temp TABLE
            (
               ID INT,
               [data] XML
            );
      
          INSERT INTO @temp
          SELECT tuc.ID,
                 CAST(uc.[data] AS XML)
          FROM   UserConfig tuc
          WHERE  Config = 'validattion'
                 AND CAST(tuc.[data] AS XML).value('(//user/validation/validator[@type="UserDataValidator"]/@enabled[contains(.,"true")])[1]', 'nvarchar(100)') = 'true'
      
          UPDATE @temp
          SET    [Data].modify('replace value of (//user/validation/validator[@type="UserDataValidator"]/@enabled[contains(.,"true")])[1] with "false"')
      
          UPDATE uc
          SET    uc.[data] = CAST(tuc.[Data] AS VARCHAR(MAX))
          FROM   [Admin].dbo.UserConfig uc
                 JOIN @temp tuc
      		        uc.ID = tuc.ID
                      AND uc.Config = tuc.Config

    Dependency Injection

     

    Scenario:

    Handle class dependencies in project.

    Solution:

    Inject Dependencies using Ninject framework.

    1. It solves dependency resolver & testability (DI pattern) using containers ( Inversion of Control - Giving responsibility of instantiation of class from one actor to other in this case DI container) and makes applications loosely coupled.
    2. Using DI you can inject different classes in the main project and different like mock in Rest projects as for Unit testing you need to isolate the units to test.
    3. This means that control is now inverted; instead of given class deciding which implementation to use, the calling code does.
    4. There are different DI containers like Ninject, AutoFac, Unity etc. : In case of Ninject, each assembly has a Ninject Module class which registers the available interface-to-implementation bindings. 
        public class Bindings : NinjectModule
        	{
        		 public override void Load()
        		 {
        			 Bind<IMailSender>().To<MailSender>();
        			 Bind<IMailSender>().To<MockMailSender>();
        		 }
        	}
            5. In Program.cs
        var kernel = new AspNetCoreKernel(settings,
        	    new NinjectModule());
        
        
        kernel.Load(typeof(AspNetCoreHostConfiguration).Assembly);
        
        
        var serviceProviderFactory = new NinjectServiceProviderFactory(kernel);
        
        
        var startup = new Startup(serviceProviderFactory);
        
        
        startup.ConfigureServices(builder.Services);
            6. One of the common way is to use  Constructor injection and procedural registration (i.e. through                 code, other way is config). Ninject does not need to register Concrete  classes (without interface),             some  other DI  do. If the. If the is nested dependency, it first instantiates the inner most objects                 and then keeps coming back till it has 
            7. Singleton scope
      • Bind<ILogger>().To<Log4netLogger>().InSingletonScope();
      • If we want to change the dependecy based on web.config:
        • Bind<ICache>().To<MemoryCache>().InSingletonScope().WithMetadata("Cache", typeof(MemoryCache).FullName);
        • Bind<ICache>().To<RedisCache>().InSingletonScope().WithMetadata("Cache", typeof(RedisCache).FullName);
        •  Test project  Web.config - <appSettings file="user.appSettings.config">
        •   <add key="Cache" value="MemoryCache" />
        •  Web Web.config - <appSettings file="user.appSettings.config">
        •  <add key="Cache" value="RedisCache" />
        • The controller would look like:
                          public  AuthService( [AppSettingsBinding(Name = "Cache")]     ICache cache)
                        {
           cache…
                      }
        • To use without constructor injection:
          • private readonly IKernel _kernel;
          • var logger = _kernel.Get(type) --type = ILogger
    8. Self Binding scope
      1. The ToSelf() binding is equivalent to Bind<Foo>().To<Foo>().
      2. Bind<MapperUtils>().ToSelf().InSingletonScope();
      3. Good for:
        • Caching service
        • Global Configurations
        • Business rules
        • Http Client
            9. Transient scope
      1. New instance is created for each request..
      2.  Bind(typeof(IDataRepo<>)).To(typeof(AdoRepo<>)).InTransientScope().Named("AdoRepo");
      3. Transient for services depends on the service, you don't want your Memory Cache to be transient, otherwise it will get wiped after you are finished using it.
      4. Good for:
        • Database Access
        • File Access
        • Services that should dispose of their state
         10. InRequest scope
      1. New instance is created for each HttpContext. 
      2. Database Context opens a connection which you don't want to persist if there is no data  going over the wire. Make this Scoped incase many services use the context at the same time, you don't have to re-open the connection.
      3. If we use transient scoped dependency for DbContext then it passed to 2 different services would be distinct references. This leads to problems where Service A calls another service to retrieve entities that it wants to associate with an entity it loaded and is trying to update. These entities are associated to a different DbContext resulting in errors or issues like duplicate data being created.
      4. Making your DbContext a Singleton and reusing it throughout the application can cause problems like concurrency and memory leak issues.
      5. For Web apps bind both context and repository in the scope of an HttpRequest. This means that only the current request thread will be able to save changes..
      6. Good for:
        • Persist state through the request.
          11. ToMethod 
      1. When a class implements 2 or more interfaces
        Bind<ScheduleService>().ToSelf().InSingletonScope();
        Bind<IScheduleService>().ToMethod(ctx => ctx.Kernel.Get<ScheduleService>()).InSingletonScope();
        Bind<IJobService>().ToMethod(ctx => ctx.Kernel.Get<ScheduleService>()).InSingleton();

    SQL query XML

                 

    Scenario: Retrieve the User(s) & their latest Addresses (address details stored as XML)

    Solution:


       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      SELECT DISTINCT Address.Details.value('@sequence', 'VARCHAR(max)') AS [Address ID],
             Detail
      FROM   [User]
             CROSS APPLY [details].nodes('//*[@city="Mumbai"]/details') AS Address(Details)
             JOIN (SELECT a.AddressID,
                          Detail
                   FROM   Address a
                          JOIN (SELECT DISTINCT AddressID,
                                                (SELECT MAX([ver])
                                                 FROM   Address b
                                                 WHERE  c.AddressID = b.AddressID
                                                 GROUP  BY AddressID
                                                 HAVING c.[ver] <= MAX(b.[ver])) AS [ver]
                                FROM   Admin.dbo.Address c) d
                            ON d.AddressID = a.AddressID
                               AND d.[Version] = a.[ver]) e
               ON e.AddressID = Address.Details.value('@sequence', 'VARCHAR(max)')

    Burp - Repeater

                

    Scenario: Intercept web site and modify headers

    Solution:

    Use Burp suite to Intercept traffic and submit the request multiple times with modified values

    Burp Suite is an integrated platform for performing security testing of web applications.
    1. Burp tool -> Proxy -> Open Browser.
    2. Navigate to the site.
    3. Burp tool -> Intercept On.
    4. Navigate to the page which you want to intercept.
    5. The request would be intercepted.
    6. Navigate to Http History tab -> Right click on the request you want to repeat -> Send to Repeater.
    7. On Repeater tab you will see Request & Response (which initially would be blank).
    8. You can now change the Request, like change Http Method from POST -> GET etc -> then click Send button.
    9. The response based on modified request would be rendered.

    Burp Intercept

               

    Scenario: Intercept web site and modify headers

    Solution:

    Use Burp suite to Intercept traffic

    Burp Suite is an integrated platform for performing security testing of web applications.
    1. Burp Suite -> Proxy -> Open Browser.
    2. Navigate to the site .
    3. Set Intercept toggle to On.
    4. Navigate to the page which you want to intercept.
    5. The request would be intercepted.
    6. Now you can go to tool and change Request Headers/Parameters etc.
    7. Then click on Forward button to submit the modified request or to continue.

    Burp SSL Scanner

               

    Scenario: Scan your website for SSL vulnerabilities

    Solution:

    Use Burp suite to run SSL Scanner

    Burp Suite is an integrated platform for performing security testing of web applications.

    Below are the steps to run a SSL scan.

    Prerequisites:
    1.  Install Jython:
    • Navigate to https://www.jython.org/download.html and download the latest Jython standalone JAR file.
    • Burp Suite -> Extender -> Options. In Python Environment section add the downloaded file from #1.
     2. Install Burp SSL Scanner:
    • Navigate to Extender -> BApp Store- > find SSL Scanner or manually install [by downloading from their site]
    • Once installed it would appear in Extender -> Extensions.
    1. Now SSL Scanner - > Target = {Your WebSite} -> Start Scanning
    2. Once complete it will show the report. If Offer TLS1.0 etc is Yes then it is still using old version else it would be No.

    Move Github Sub Repository back to main repo

     -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...