Lazy Logger

Scenario:

Logger with Lazy loading

Solution:

  • Loading Logger when needed
    using System.Collections;
    namespace Web.Models
    {
        public static class Class
        {
            private static readonly Lazy<Logger> Logger;
    
            public static Class()
            {
                Logger = new Lazy<Logger>(() =>
                   Get<ILoggerFactory>().GetLogger()));
            }
            public bool Validate()
            {
                Logger.Value.Error(e, $"Error")
            }
        }
    }

Regular Expressions

Scenario:

Various regular expression scenarios

Solution:

  • Hex Character
    1. var rex = new Regex("[0-9,A-F,a-f]{2}");
  • Line Breaks 
    1. var rex = new Regex(@"[\r\n\t]");
  • File name "${RND:###}-${TS:yyyyMMdd}.${RND:#}.csv";
    1. var fileFormat = new Regex(@"\${(?<type>(RANDOM|TIMESTAMP)):(?<format>[^}]+)}",
                  RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
  • Replace
    1. var regex = new Regex(@"""(\d+\.\d)""", RegexOptions.Compiled);
      
      response = regex.Replace(response, @"""percent$1""");
  • "fieldName[]"
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    using System.Text.RegularExpressions;
    
    namespace Web.Models
    {
        public class Class
        {
            public bool Validate()
            {
                var value = "fieldName[]";
                var regex = new Regex(@"^fieldName\[.*?\]$",
                       RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
    
                if (regex.IsMatch(value))
                {
                    return true;
                }
                return false;
            }
        }
    }

Validate query string and value based on if query string is present

Scenario:

Validate query string for null or empty if only it exists

Solution:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
     public bool validate()
            {
                if (queryStringCollection.AllKeys.Any(k => k.StartsWith("field_name")))
                {
                    fieldValue = queryStringCollection.Get("field_name");
                    if (string.IsNullOrWhiteSpace(fieldValue) )
                    {
                        throw customeError;
                    }
                }
            }  

Identify the correct w3wp process to attach while debugging in Visual Studio

Scenario:

Identify the correct w3wp process to attach while debugging in Visual Studio

Solution:

  • Open command prompt and run below command. Find the ID (number) of your application pool and look for that ID while attaching w3wp in VS.
    1
    2
    3
    cd C:\Windows\System32\inetsrv\
    
    appcmd.exe list wp

Ignore Ssl validation error while connecting to https endpoint

Scenario:

Ignore Ssl validation error while connecting to https endpoint.

Solution:

  • Ignore ssl validaton errors and continue. In cases where the endpoints are internal only and so CA(Certificating Authority) wont verify and issue a SSL. In such cases certificate used is self-signed one. Below is setting at instance level. Add this before creating HttpClient.
    1. 1
      2
      3
      4
      5
      6
      7
      var handler = new HttpClientHandler();
      
                          handler.SslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
                          handler.ServerCertificateCustomValidationCallback = delegate { return true; };
      
                      
      var httpClient= new HttpClient(handler);
  • Ignore ssl validaton errors and continue. In cases where the endpoints are internal only and so CA(Certificating Authority) wont verify and issue a SSL. In such cases certificate used is self-signed one. Below is the global change. Add this before creating HttpClient.
    1
    2
    3
    4
    5
    // wrap this in config
    
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    ServicePointManager.ServerCertificateValidationCallback +=
                        (sender, cert, chain, sslPolicyErrors) => true;

Add Certificate to mmc

Scenario:

Add a Certificate to mmc.

Solution:

  • Windows -> run -> mmc
  • File -> Add Remove snap-ins -> Certificates -> Add -> Ok
  • Expand Certificates -> Intermediate Certification Authority -> right click -> All Tasks -> import.
  • In menu -> Next -> Browse to certificate -> Next -> Finish.
  • To add/look at permission: Select certificate -> more actions -> all tasks.
  • In IIS, go to site -> Server Certificates -> 
The Certificate should be added under Intermediate Certification Authority/Personal now.

Configure LogStash on docker

Scenario:

Configure LogStash on docker.

Solution:

  • Access and login to core os, in command line
  • ls
  • cd elasticsearch
  • cd logstashpipeline
  • vim api.confg (longstash configuration file)
input {
  redis {
    codec => "json"
    data_type => "list"
    host => "redis"
    key => "api"
    port => "6379"
    tags => ["local"]
    add_field => {"origin" => "myapp-api-local"}
  }
}

output {
  if " myapp-api-local " in [origin] {
    elasticsearch {
      action => "index"
      hosts => ["http://elasticsearch:9200"]
      index => "logstash-myapp-api-%{+YYYY.MM.dd}"
    }
  }
}
~
  • :wq 
  • cd ..
  • cat stop.sh
  • ./stop.sh
  • ./start.sh
  • git status
  • git add *
  • git status
  • git commit -a -m "Comments"
  • git push
In Vim

Hit the Esc key to enter Normal mode and type : for Command line mode.
·        :q - quit
·        :q! - quit
·        :wq - write and quit
·        qa – quit instance
·        i – insert mode
·        dd to delete line
·        dw to delete single word
·        Delete key to delete characters

Jump servers


Scenario:

You are not able to connect to a host, you can use aws etc to jump servers to access the sites/endpoints.

Solution:

  • Open PuTTY
  • Session -> Create new (amazon core os host name) -> Host Name [amazon host name] -> Save
  • Session -> Select: amazon -> Load -> Left nav -> SSH -> Tunnels
  • Add Source port & Destination combinations (IIS should not have any site running on 80/443, else stop that), e.g.:
    • 5601 , 10.20.20.20:5601
    • 443 , 10.20.20.20:443
    • 80 , 10.20.20.20:80
  • Go to host file (as administrator), add entries for site with i/p: 10.20.20.20 replaced with 127.01.0.1 -> Save.
  • PuTTY -> Session -> select: amazon -> double click
  • Provide login & password

Now you should be able to navigate to endpoints as before, this is jumping servers.

Floccus bookmarks


Scenario:

To share bookmarks with team members, Floccus provides self hosted solution.

Solution:

  • DNS to hosts.
  • Install floccus extension for Chrome: https://chrome.google.com/webstore/detail/floccus-bookmarks-sync/fnaicdffflnofjppbagibeoednhnbjhg?hl=en
  • Add a new folder to the bookmark bar
  • Configuration:
    • Add account
    • Select Nextclould Bookmarks
    • Nextcloud URL: http://nextcloud.mpls.digitalriver.com
      • Username: {user}
      • Password: {password}
    • Local folder: Choose Folder -> newly created folder above
    • Save
    • Enabled is checked
    • Click Sync

Push data to Redis - test using docker container

Scenario:

Follow below steps:


  1. Portainer host -> local -> Containers -> Container -> Redis
  2. Redis command prompt
  3. cd /usr/local/bin enter
  4. ls enter
  5. redis-cli  -h hostname -p port
  6. KEYS *
    1. All Keys still in queue or stuck to be consumed
  7. LLEN keyname
    1. If there are any still in queue or stuck to be consumed
To connect without redis-cli use below:
  • ncat -v --ssl redisendpoint 6379 --if not on ssl, remove ssl option
  • To close connection ctrl + D
DELETE Key
  • DEL KeyName

Redis ConnectionMultiplexer


Scenario:

Stackexchange.Redis.ConnectionMultiplexer hides the details of multiple servers and  shared and reused between callers. It is thread-safe and ready for this usage.

Solution:


  1.  
    1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    private TResult SendData<TResult>(Func<ConnectionMultiplexer, TResult> call)
            {
                _lock.EnterReadLock();
                try
                {
                    if (_redis != null)
                    {
                        return call(_redis);
                    }
                }
                finally
                {
                    _lock.ExitReadLock();
                }
    
                _lock.EnterWriteLock();
                try
                {
                    if (_redis != null)
                    {
                        return call(_redis);
                    }
    
                    _redis =
                        ConnectionMultiplexer.Connect(
                            $"{string.Join(",", Servers.Select(c => $"{c.Server}:{c.Port}"))}{(string.IsNullOrWhiteSpace(ServerOptions) ? "" : $",{.ServerOptions}")}");
                    
                    _redis.PreserveAsyncOrder = false;
    
                    return call(_redis);
                }
                finally
                {
                    _lockSlim.ExitWriteLock();
                }
            }

Access properties of model on Generic method


Scenario:

We want to edit model before further processing. The model is passed to a Generic method. Also name of Datamember of the model has to be different than property name.

Solution:


  1.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
            public interface IModel
            {
                string Filename { get; set; }
            }
    
            public class Model : IModel
            {
                [DataMember(Name = "fileName")]
                public string FileName { get; set; }
            }


  2.  
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
        public abstract class Client<T> : IClient where T : class
        {
            private void Process(T model)
            {
                if (model is IModel model)
                {
                    model.Filename = application.FileName;
                }
            }
        }

HttpClient connect with basic authentication


Scenario:

Connect to service using login/password

Solution:

  1. Connect using basic authentication and send message
  2. 1
    2
    3
    4
    5
    6
    7
    8
    9
                var client = new HttpClient();
    
                var bytearray = Encoding.ASCII.GetBytes($"{userName}:{password}");
                client.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytearray));
    
                var response = client.SendAsync(message).Result;
    
                var statusCode = response.StatusCode;

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...