Amazon Kinesis

               

Scenario: Create Amazon Kinesis client to push data stream to AWS

Solution:

      Per Amazon:
      With Amazon Kinesis, you can ingest real-time data such as video, audio, application logs, website        clickstreams, and IoT telemetry data for machine learning, analytics, and other applications.
      

      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
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using Amazon;
    using Amazon.Kinesis;
    using Amazon.Kinesis.Model;
    using Amazon.SecurityToken;
    using Amazon.SecurityToken.Model;
    using Timer = System.Timers.Timer;
    
    namespace ConsoleApplication1
    {
        public abstract class KinesisClient<T> : IKinesisClient where T : class
        {
            private readonly object _lock = new();
            private readonly ReaderWriterLockSlim _lockSlim = new();
            
            public void Publish(object data)
            {
                PublishData((T)data);
            }
            
            private void Send(PutRecordRequest request)
            {
                KinesisConnectionMultiplexer client;
    
                if (_disposed)
                {
                    return;
                }
    
                _lockSlim.EnterReadLock();
    
                try
                {
                    if (TryGetClient(_kinesisClients, out client))
                    {
                        PublishDataStream(client, request);
                        return;
                    }
                }
                finally
                {
                    _lockSlim.ExitReadLock();
                }
    
                _lockSlim.EnterWriteLock();
    
                try
                {
                    if (!TryGetClient(_kinesisClients, out client))
                    {
                        //local
                        if (isLocal)
                        {
                            _kinesisClients = CreateClients(clientsecret, null);
                        }
                        else
                        {
                            //awsTemporaryCredentials.AccessKeyId}
                            //awsTemporaryCredentials.SecretAccessKey}
                            //awsTemporaryCredentials.SessionToken
                            //awsTemporaryCredentials.Expiration }");
    
                            var awsTemporaryCredentials = GetKinesisCredentials();
    
                            _kinesisClients = CreateClients(awsTemporaryCredentials);
                            TryGetClient(_kinesisClients, out client);
                        }
                    }
    
                    PublishDataStream(client, request);
                }
                finally
                {
                    _lockSlim.ExitWriteLock();
                }
            }
            
            private void PublishData(T data)
            {
                Send(new PutRecordRequest
                {
                    StreamName = "OrderStream",
                    Data = new MemoryStream(Encoding.UTF8.GetBytes(json)),
                    PartitionKey = DateTime.Now.ToString("yyyy-MM")
                });
            }
            
            private static KinesisConnectionMultiplexer[] CreateClients(Credentials awsCredentials)
            {
                var clients = new KinesisConnectionMultiplexer[MaxConnections];
    
                for (var i = 0; i < MaxConnections; i++)
                {
                    clients[i] = new KinesisConnectionMultiplexer
                    {
                        Client = !string.IsNullOrEmpty(ClientId)
                            ? new AmazonKinesisClient(ClientId, ClientSecret,
                                RegionEndpoint.GetBySystemName(Region) ?? RegionEndpoint.USEast1)
                            : new AmazonKinesisClient(awsCredentials?.AccessKeyId, awsCredentials?.SecretAccessKey,
                                awsCredentials?.SessionToken, RegionEndpoint.GetBySystemName(Region) ??
                                                             RegionEndpoint.USEast1),
                        ExpiryTime = awsCredentials?.Expiration ?? DateTime.MaxValue
    
                    };
                }
    
                return clients;
            }
    
            public Credentials GetKinesisCredentials()
            {
                var roleArn = $"arn:aws:iam::{IamAccountId}:role/{IamRoleName}";
    
                var request = new AssumeRoleRequest
                {
                    RoleArn = roleArn,
                    RoleSessionName = $"{"Environment"}_kinesis_session",
                    DurationSeconds = ConnectionDuration
                };
    
                var response =
                    new AmazonSecurityTokenServiceClient(RegionEndpoint.GetBySystemName({"Region"}) ??}
                                                         RegionEndpoint.USEast1).AssumeRoleAsync(request);
            
                return response.Result.HttpStatusCode == System.Net.HttpStatusCode.OK ? response.Result.Credentials : null;
            }
    
            public bool TryGetClient(KinesisConnectionMultiplexer[] clients, out KinesisConnectionMultiplexer client)
            {
                if (clients == null || !clients.Any())
                {
                    client = null;
                    return false;
                }
    
                lock (clients)
                {
                    client = clients.Where(k => DateTime.Now.AddSeconds(10) <= k.ExpiryTime).Min(client => client);
                }
    
                if (client == null)
                {
                    return false;
                }
    
                Interlocked.Increment(ref client.Load);
                return true;
            }
    
            private void PublishDataStream(KinesisConnectionMultiplexer multiplexer, PutRecordRequest putRecordRequest)
            {
                ProcessPutRecordsRequest(multiplexer, putRecordRequest);
            }
    
            private void ProcessPutRecordsRequest(KinesisConnectionMultiplexer multiplexer,
                PutRecordRequest putRecordRequest)
            {
                var client = multiplexer.Client;
                var cts = new CancellationTokenSource();
                var ct = cts.Token;
                var task = client.PutRecordAsync(putRecordRequest, ct).Result;
    
                Interlocked.Decrement(ref multiplexer.Load);
            }
        }
    }

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 objectit 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; }
        }
    }

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