GeistHaus
log in · sign up

https://goldytech.wordpress.com/feed

rss
0 posts
Polling state
Status active
Last polled May 18, 2026 22:32 UTC
Next poll May 19, 2026 22:32 UTC
Poll interval 86400s
Last-Modified Thu, 26 Feb 2026 17:55:20 GMT

Posts

Understanding Log4J vulnerability
SecurityLog4J
Log4j has recently created chaos in the IT world, and all security and operation engineers are busy patching their servers. No wonder that this is critical severity with a CVSS score of 10/10This blog post will discuss why the entire security industry and the internet are in a frenzy over application security log4J. What is …

Continue reading Understanding Log4J vulnerability

Show full content

Log4j has recently created chaos in the IT world, and all security and operation engineers are busy patching their servers. No wonder that this is critical severity with a CVSS score of 10/10
This blog post will discuss why the entire security industry and the internet are in a frenzy over application security log4J.

What is Log4J

Log4J is a logging framework in Java; basically, those in development and security try to do good by logging things in their applications. It helps the developers and security analysts. Developers will use this as troubleshooting to find problems with the application, and security analysts will use this to find anomalies within that traffic. So let’s say you are developing an application and you want to do good by logging these kinds of things. Now, instead of writing all the code to support that, logging, that’s where log4j comes into play. It’s an open-source, free framework/library that you can wrap into your code-friendly and easy. And it does all the hard work for you.

How can an attacker exploit this

Unfortunately, a bug in this library allows for a vulnerability; we’re calling log4 shell. It will enable an attacker to send a message to a vulnerable application to execute potentially malicious code. We’ve seen reports of log4 shell being called the worst software vulnerability ever. It is widespread, and it can exploit many applications using this library. Millions of enterprise applications use Log4J; it includes cloud services and manufacturers, including even IoT devices. It’s literally on mars; the mars 2020 drone ingenuity is logging data with log4J. The vulnerability is so widespread. The fact that it’s difficult to pinpoint all the places it exists and the vulnerability being so extremely easy to exploit this perfect storm. All an attacker needs to do is prepare a malicious file, place it on a server they control, and send some modified text to a field logged by the application server. Once the server logs this string, log4J will retrieve and execute the malicious code from the attacker’s server. An attacker’s potential to control the application and move elsewhere within an organization’s network is very real. Does this mean that every piece of software using log4J is vulnerable to this exploit? Not at all. The caveat is that your application would need to be logging the field that an attacker could send that modified text to think of it like this, you have a Java application that allows your users to log in with an account. Do you want to log all the user names that are being attempted? Probably yes, But that’s also a great example of a field the attacker could use to submit that modified code instead of a username.

Steps need to be taken by security teams

The first step any organization should take is to assess their systems and determine where the library containing log4J is being used. It is more complicated than it sounds. Third-party vendors, open-source software, any application on your network can include an extension that uses a Java library; then having to drill down to whether those libraries using log4J can be a lot of work. Keep in Mind one of the reasons Java is so widespread is because it works everywhere. It isn’t limited to standard Windows domains or even a specific industry. After the difficult task of a security team or dev team discovering and confirming that it’s being used on their systems, they want to patch where possible immediately.
In some cases, they may run into a situation where they are at the vendor’s mercy to push out the patch. Now actually finding those instances can be accomplished in a variety of ways., Apache has released an update. Simply patching log4J is a little bit more complicated than doing a simple sweep across the network and calling it good Since Log4J is used as an open-source logging plugin for thousands. If not millions of applications, organizations will need to figure out what applications within their network are using it. Everyone should assume compromise if they have any Java applications as part of their environment monitoring. Network traffic is extra critical now to watch for any abnormal network activity. Enterprises will need to invest heavily in their incident response and security analytics if they intend to stay clear of becoming compromised. As more and more information is released, this vulnerability is vulnerable to evolve. Reports of a second sister vulnerability have already been released. This new vulnerability that has been released has been known to cause dDoS attacks.

Where can I find help and more information

Official CISA Guidance & Resources: https://github.com/cisagov/log4j-affected-db

Log4Shell detector: https://github.com/Neo23x0/log4shell-detector

List of Vulnerable Packages: https://github.com/NCSC-NL/log4shell/tree/main/software

security logo
goldytech
http://goldytech.wordpress.com/?p=558
Extensions
Performance Booster with System.IO.Pipelines in C#
.NETC#CoreHow ToUncategorizedperformance
As our industry has embraced the new strategies for handling the production workloads which include containers (Read as K8s) or Serverless (Read as Functions As A Service), the developers don’t have the luxury of unlimited computing resources on the production environments. Those days are gone where it was easy to acquire a large virtual machine …

Continue reading Performance Booster with System.IO.Pipelines in C#

Show full content

As our industry has embraced the new strategies for handling the production workloads which include containers (Read as K8s) or Serverless (Read as Functions As A Service), the developers don’t have the luxury of unlimited computing resources on the production environments. Those days are gone where it was easy to acquire a large virtual machine with many cores and high memory for application deployment needs. As a .net developer though you are working with managed code and you rely on GC (Garbage collector) to do the job, the onus is now on you to write highly performant code which can run anywhere right from docker containers to IoT devices. With advent of C#8 and .NET core , Microsoft .NET team has been very cognizant of memory allocations. Every new version comes with modern APIs that can increase the performance of the application to X times more compared with older version of traditional APIs. In this blog post I will be showcasing the file I/O operations with 3 different techniques and will benchmark each technique. From the benchmarks results it will be pretty evident that System.IO.Pipelines wins by a considerable margin both in the time of execution and memory allocation.

The Challenge

We will be experimenting with reading a large csv file (100,000 records with 5 fields) of employee data. I’m sure you must encounter this challenge many times in your career where you have to parse a large csv file. This challenge creates a enough pressure on GC. The considerations around garbage collection are particularly important when thinking about performance. This is because garbage collection takes up CPU time, reducing the time spent on the actual data processing. Not only this, but each time a garbage collection is triggered, much of the work is suspended so that the remaining references can be evaluated. This can drastically effect the amount of time taken to process the data. I’ve chosen three techniques for this challenge.

  1. Using CSVHelper : This is a popular library for parsing csv files in .NET ecosystem.
  2. Using IAsyncEnumerable : This API was introduced from C#8 where a data stream (chunks of data) can be processed instead of whole file.
  3. Using System.IO.Pipelines : This API was shipped with .NET core 2.1 and is internally used by Kestrel , web server for AspNET core for high performance to process many requests per second received from the socket. It is available as Nuget package download.David Fowler who has architected these APIs as an excellent post of its introduction.

The source code of this post is available on my Github repo. The repo also consists of tests which has benchmarks results.

So let’s dive straight into the code

#nullable enable
using System;
using System.Buffers;
using System.IO;
using System.IO.Pipelines;
using System.Text;
using System.Threading.Tasks;

namespace FileIO
{
    public class WithPipeLines
    {
        /// <summary>
        /// Process the file using System.IO.Pipelines
        /// </summary>
        /// <param name="filePath">The file path </param>
        /// <param name="employeeRecords">The Employee Array in which file data will be processed.</param>
        /// <returns>PipeReader Sequence Position</returns>
        public async Task<int> ProcessFileAsync(string filePath, Employee[] employeeRecords)
        {
            var position = 0;
            if (!File.Exists(filePath)) return position;
            await using var fileStream = File.OpenRead(filePath);
            var pipeReader = PipeReader.Create(fileStream);
            while (true)
            {
                var fileData = await pipeReader.ReadAsync();

                // convert to Buffer
                var fileDataBuffer = fileData.Buffer;
                
               
                var sequencePosition = ParseLines(employeeRecords, ref fileDataBuffer, ref position);

                pipeReader.AdvanceTo(sequencePosition, fileDataBuffer.End);

                if (fileData.IsCompleted)
                {
                    break;
                }
            }

            await pipeReader.CompleteAsync(); // marking pipereader as Completed
            return position;
        }
        
         private static SequencePosition ParseLines(Employee[] employeeRecords, ref ReadOnlySequence<byte> buffer, ref int position)
        {
            var newLine = Encoding.UTF8.GetBytes(Environment.NewLine).AsSpan();

            var reader = new SequenceReader<byte>(buffer);

            while (!reader.End)
            {
                // Read the whole line till the new line is found
                if (!reader.TryReadToAny(out ReadOnlySpan<byte> line, newLine, true))
                {
                    break; // we don't have a delimiter (newline) in the current data
                }

                var parsedLine = LineParser.ParseLine(line); // we have a line to parse

                if (parsedLine is { }) // if the returned value is valid Employee object
                    employeeRecords[position++] = (Employee) parsedLine;
            }

            return reader.Position; // returning the Last position of the reader
        }

        private static class LineParser
        {
            private const byte Coma = (byte) ',';
            private const string ColumnHeaders = "Name,Email,DateOfJoining,Salary,Age";
            public static Employee? ParseLine(ReadOnlySpan<byte> line)
            {
                if (Encoding.UTF8.GetString(line).Contains(ColumnHeaders)) // Ignore the Header row
                {
                    return null;
                }
                var fieldCount = 1;

                var record = new Employee();

                while (fieldCount <= 5) // we have five fields in csv file
                {
                     var comaAt = line.IndexOf(Coma);
                     if (comaAt < 0)
                     {
                         comaAt = line.Length;
                     }

                     switch (fieldCount)
                     {
                         case 1:
                         {
                             var value = Encoding.UTF8.GetString(line[..comaAt]);
                             record.Name = value;
                             break;
                         }
                         case 2:
                         {
                             var value = Encoding.UTF8.GetString(line[..comaAt]);
                             record.Email = value;
                             break;
                         }
                         case 3:
                         {
                             var value = Encoding.UTF8.GetString(line[..comaAt]);
                             record.DateOfJoining = Convert.ToDateTime(value);
                             break;
                         }
                        
                         case 4:
                         {
                             var value = Encoding.UTF8.GetString(line[..comaAt]);
                             record.Salary = Convert.ToDouble(value);
                             break;
                         }
                        
                         case 5:
                         {
                             var value = Encoding.UTF8.GetString(line[..comaAt]);
                             record.Age = Convert.ToInt16(value);
                             return record;
                         }
                     }

                     line = line[(comaAt + 1)..]; // slice past field

                     fieldCount++;
                }

                return record;
            }
        }
    }
}

The entry point public method is ProcessFileAsync , which creates the instance of PipeReader class , it reads that data and converts into buffer, which is of data type of ReadOnlySequence<byte> . This buffer data is then passed to ParseLines method as a ref along with the position of the PipeReader , which has 0 value as it is in the beginning position. ParseLines method tries to navigate the new line using NewLine as a delimiter. This process continue till the end position of PipeReader is reached. After parsing is finish the PipeRead position is moved till the end of the buffer and it is marked as processed (line number 35 and 43).

The actual data processing takes place in the static class LineParser in the ParseLine method, after omitting the header row of csv file it tries to capture the each field data value by finding the "," position , and then try to extract string value with UTF8 Encoding using index offsets and ranges pattern. Each field is processed one by one and it is tracked by fieldCount variable.

Let’s see how we can consume this ProcessFileAsync method

var pool = ArrayPool<Employee>.Shared;
            var employeeRecords = pool.Rent(100000);
            var pipeLinesTest = new WithPipeLines();

            try
            {
                await pipeLinesTest.ProcessFileAsync(_filePath, employeeRecords);
            }
            finally
            {
                pool.Return(employeeRecords, clearArray: true);
            }

Creating an ArrayPool of Employee type . ArrayPool<T> is a high performance pool of managed arrays. It is a thread safe pool with custom max length.

Next thing is to call the Rent method which requires you to specify minimum length of the buffer. Keep in mind, that what Rent returns might be bigger than what you have asked for.

Once you are done using it, you just Return it to the SAME pool. Return method has an overload, which allows you to cleanup the buffer so subsequent consumer via Rent will not see the previous consumer’s content. By default the contents are left unchanged.

Benchmark Results

I’ve used BenchmarkDotNet library to measure the performance.

table { border-collapse: collapse; display: block; width: 100%; overflow: auto; } td, th { padding: 6px 13px; border: 1px solid #ddd; text-align: right; } tr { background-color: #fff; border-top: 1px solid #ccc; } tr:nth-child(even) { background: #f8f8f8; }

BenchmarkDotNet=v0.13.0, OS=macOS Big Sur 11.4 (20F71) [Darwin 20.5.0]
Intel Core i9-9880H CPU 2.30GHz, 1 CPU, 16 logical and 8 physical cores
.NET SDK=5.0.203
  [Host]     : .NET 5.0.6 (5.0.621.22011), X64 RyuJIT
  DefaultJob : .NET 5.0.6 (5.0.621.22011), X64 RyuJIT
MethodMeanErrorStdDevRankGen 0Gen 1Gen 2Allocated PipeLines143.1 ms2.81 ms3.24 ms15500.00002000.0000750.000044 MB AsyncStream223.0 ms4.40 ms8.36 ms28000.00003000.00001000.000064 MB CsvHelper228.5 ms4.51 ms7.29 ms311000.00005000.00003000.000077 MB

As from the result above PipeLines method is clear winner which just took 143.1 milliseconds to process the data and with just 44 MB of memory allocation

goldytech
http://goldytech.wordpress.com/?p=469
Extensions
Understanding Pattern matching with C#8
.NETC#CoreHow To
On September 23rd 2019, Microsoft announce the release of .Net Core 3 and C#8 in a virtual online conference. These two are the major releases. In this post I shall be talking about C#8 enhanced feature of pattern matching, why this because I love functional programming and pattern matching is an important concept in FP …

Continue reading Understanding Pattern matching with C#8

Show full content

On September 23rd 2019, Microsoft announce the release of .Net Core 3 and C#8 in a virtual online conference. These two are the major releases. In this post I shall be talking about C#8 enhanced feature of pattern matching, why this because I love functional programming and pattern matching is an important concept in FP languages. Pattern matching was first introduced in  in C#7. But C#8 is a major leap forward in this direction.C#8 enables new types of patterns and allows us to use those patterns in even more places.  We can now use positional patterns with deconstructors. We can use property patterns to elegantly check the values of multiple properties. Finally we would be seeing how new switch syntax can work with tuples pattern matching.

WHAT IS PATTERN MATCHING

Pattern matching is a functional programming technique to do a type testing. Imagine you receive an anonymous object and you want to identify it type by querying its data. In the below examples you will get the idea of what I’m talking about. But I do encourage you to read this article to get full understanding of this topic.

There are three different types of pattern matching that are introduced in C#8. I will be explaining each of them with examples.

Positional Patterns using Deconstructors

Before we dive into this topic let us first understand our domain model which is in context of HR system. This will help you in better understanding.

.gist table { margin-bottom: 0; } This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters public class Employee { public int Id { get; set; } public string Name { get; set; } public bool IsManager { get; set; } public Department Department { get; set; } } public class Department { public int Id { get; set; } public string Name { get; set; } } view raw Model.cs hosted with ❤ by GitHub

So we have very simple model to work with, Employee and Department. Before we can apply the pattern matching techniques on our model class there is one very important thing to remember. You must add deconstructor to the model. A deconstructor is a void method with the name Deconstruct. It accepts the out parameters that you want to reference with the pattern matching. So now our updated Model will be as follows.

.gist table { margin-bottom: 0; } This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters public class Employee { public int Id { get; set; } public string Name { get; set; } public bool IsManager { get; set; } public Department Department { get; set; } public void Deconstruct(out int id, out string name, out bool isManager, out Department department) { id = Id; name = Name; isManager = IsManager; department = Department; } } public class Department { public int Id { get; set; } public string Name { get; set; } public void Deconstruct(out int id, out string name) { id = Id; name = Name; } } view raw Model.cs hosted with ❤ by GitHub

Now I want to write a method which accepts object as a parameter and I want to determine whether the passed object is of the employee type and also is Manager working for Human Resources department.

My method would be as follows using the Positional patterns

.gist table { margin-bottom: 0; } This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters private static bool IsHrManagerByPositionalPattern(object obj) { return obj is Employee e && e is (_, _ , true, (_, "Human Resources")); } view raw IsHrManager.cs hosted with ❤ by GitHub

The code uses pattern matching in parameters in the same order that were defined in the Deconstruct method. Where there is _ (underscore) those parameters are discarded. If I pass the below object to this method it will return true.

.gist table { margin-bottom: 0; } This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters var employee = new Employee { Id = 1, Department = new Department {Id = 1, Name = "Human Resources"}, Name = "John Doe", IsManager = true }, view raw empobj.cs hosted with ❤ by GitHub

If you find this technique as cryptic and not that friendly as far as code readability is concern then hold on there is another way to achieve the same result. Also you may have question in your mind that why this hard way, I can achieve this with simple If. But remember my friend Functional Programming is all about expressions than statements.

Property Pattern

Continuing with the same domain context, we want to find the Manager who works in Human Resources department but with property pattern technique.

.gist table { margin-bottom: 0; } This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters private static bool IsHrManagerByPropertyPattern(object employee) { return employee is Emp e && e is { IsManager: true, Department: {Name: "Human Resources" } }; } view raw HrManagerByPropertyPattern.cs hosted with ❤ by GitHub

This approach is more cleaner and doesn’t require to create a Deconstruct method. If I pass the same employee object as above to this method it will again return me true. You might find it similar to Linq but it works on different concept.

Tuple Patterns

This pattern brings interesting possibilities on the table which can make your code cleaner and precise. We will see the new switch syntax in action too. Let’s shift our domain context from Human Resources to Contract Lifecycle management , CLM for short. In a CLM the contract / agreement transition through various phases which can be demonstrated by the diagram below.


Clm lifecycle

So we have 3 enums here

  1. Status
  2. Status Category
  3. Transition

The ask for us to find the status of the contract given is current status category and its next transition state

Eg if the contract status category is in Request and if the transition happens to Create Agreement then the desired status of the contract should be of Request.

See the entire code below to get the understanding of it.

.gist table { margin-bottom: 0; } This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters public enum StatusCategory { Request, InSignature, InAuthoring, InEffect, Terminated, Expired } public enum Status { Request, ReadyForSignatures, OtherPartyReview, OtherPartySignatures, Activated, BeingAmended, Terminated, Expired, BeingRenewed, InRenewal, Unknown } public enum Transition { CreateAgreement, GenerateAgreement, SendForReview, SendForSignature, Activate, Amend, Terminate, Expire, Renew, Renewed } public class AgreementLifeCycle { public static Status GetAgreementStatus(StatusCategory statusCategory, Transition transition) { return (statusCategory, transition) switch { (StatusCategory.Request, Transition.CreateAgreement) => Status.Request, (StatusCategory.InSignature, Transition.GenerateAgreement) => Status.ReadyForSignatures, (StatusCategory.InAuthoring, Transition.SendForReview) => Status.OtherPartyReview, (StatusCategory.InSignature, Transition.SendForSignature) => Status.OtherPartySignatures, (StatusCategory.InEffect, Transition.Activate) => Status.Activated, (StatusCategory.InEffect, Transition.Amend) => Status.BeingAmended, (StatusCategory.Terminated, Transition.Terminate) => Status.Terminated, (StatusCategory.Expired, Transition.Expire) => Status.Expired, (StatusCategory.InEffect, Transition.Renew) => Status.BeingRenewed, (StatusCategory.Request, Transition.Renewed) => Status.InRenewal, _ => Status.Unknown }; } } view raw clm.cs hosted with ❤ by GitHub

Notice the change in switch syntax, you won’t find the case keyword. We convert the function input parameters into tuple and then do the tuple pattern matching without the case keyword. Isn’t that cool. You have more expressive code now.

SUMMARY

In this blog post we learned about enhancements that has come in pattern matching feature of C#8. There are also other interesting features released with this version like IAsyncEnumerable, default implementation of methods in interface, Nullable reference types and Static local methods. I encourage you to learn them too and use it in your coding day to day work.

goldytech
Clm lifecycle
http://goldytech.wordpress.com/?p=454
Extensions
Using NLTK data with Serverless Framework in AWS Lambda with Layers
AWSLambdaNLPNLTK
Any technology that let developer to concentrate on what they are good at (coding) without being bogged down by other nuances like deployments and doing baby sitting of the servers. Serverless is such a technology which empowers the developers. I wont go in detail of this as there is a abundance stuff available on web …

Continue reading Using NLTK data with Serverless Framework in AWS Lambda with Layers

Show full content

Any technology that let developer to concentrate on what they are good at (coding) without being bogged down by other nuances like deployments and doing baby sitting of the servers.

Serverless is such a technology which empowers the developers. I wont go in detail of this as there is a abundance stuff available on web about the advantages of going with serverless. Almost every public cloud provider has the serverless offering now , with AWS being the pioneer in it.

Serverless Framework is the icing on the cake with serverless. It makes development and deployment so seamless.

NLTK (Natural Language Toolkit) is the one of oldest library available since 2001 in Python for Natural Language Processing  (NLP). In this blog post I will showcase how you can deploy your NTLK based solution on AWS Lambda with layers using serverless framework.

For NLTK to work it requires  large amount of meta data also known as trained models for all languages supported by NLTK. You can read more about NLTK data over here. This data must be preinstalled on the machine where you are running NLTK based solution. Now when I talked about serverless , though there are servers involved but it is not exposed to us and the cloud provider internally manages it. Hence you cannot SSH or Remote into the computer and install the data. Wouldn’t it be sad serverless story if I end here.

AWS Lambda layers are here to help us. They allow us to pack the additional data along with lambda code deployment package. These layers can be shared across multiple lambda functions or accounts. It was introduced at AWS Reinvent Conference in 2018.

Here is the serverless.yml file

.gist table { margin-bottom: 0; } This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters Show hidden characters # Welcome to Serverless! # # This file is the main config file for your service. # It's very minimal at this point and uses default values. # You can always add more config options for more control. # We've included some commented out config examples here. # Just uncomment any of them to get that config option. # # For full config options, check the docs: # docs.serverless.com # # Happy Coding! service: extractor # NOTE: update this with your service name #app: your-app-name #tenant: your-tenant-name # You can pin your service to only deploy with a specific Serverless version # Check out our docs for more details # frameworkVersion: "=X.X.X" provider: name: aws runtime: python3.7 # you can overwrite defaults here # stage: dev # region: us-east-1 # you can add statements to the Lambda function's IAM Role here # iamRoleStatements: # - Effect: "Allow" # Action: # - "s3:ListBucket" # Resource: { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "ServerlessDeploymentBucket" } ] ] } # - Effect: "Allow" # Action: # - "s3:PutObject" # Resource: # Fn::Join: # - "" # - - "arn:aws:s3:::" # - "Ref" : "ServerlessDeploymentBucket" # - "/*" # you can define service wide environment variables here environment: NLTK_DATA: /opt/nltk_data # you can add packaging information here package: # include: # - include-me.py # - include-me-dir/** exclude: - nltk/** functions: extract: handler: handler.extract # The following are a few example events you can configure # NOTE: Please make sure to change your handler code to work with those events # Check the event documentation for details events: - http: path: extract method: post cors: true layers: - {Ref: NltkLambdaLayer} # - websocket: $connect # - s3: ${env:BUCKET} # - schedule: rate(10 minutes) # - sns: greeter-topic # - stream: arn:aws:dynamodb:region:XXXXXX:table/foo/stream/1970-01-01T00:00:00.000 # - alexaSkill: amzn1.ask.skill.xx-xx-xx-xx # - alexaSmartHome: amzn1.ask.skill.xx-xx-xx-xx # - iot: # sql: "SELECT * FROM 'some_topic'" # - cloudwatchEvent: # event: # source: # - "aws.ec2" # detail-type: # - "EC2 Instance State-change Notification" # detail: # state: # - pending # - cloudwatchLog: '/aws/lambda/hello' # - cognitoUserPool: # pool: MyUserPool # trigger: PreSignUp # Define function environment variables here # environment: # variable2: value2 # you can add CloudFormation resource templates here #resources: # Resources: # NewResource: # Type: AWS::S3::Bucket # Properties: # BucketName: my-new-bucket # Outputs: # NewOutput: # Description: "Description for the output" # Value: "Some output value" layers: nltk: path: nltk name: NltkData # optional, Deployed Lambda layer name description: Nltk corpus data # optional, Description to publish to AWS compatibleRuntimes: # optional, a list of runtimes this layer is compatible with - python3.7 licenseInfo: GPLv3 # optional, a string specifying license information allowedAccounts: # optional, a list of AWS account IDs allowed to access this layer. - '*' retain: false # optional, false by default. If true, layer versions are not deleted as new ones are created plugins: - serverless-python-requirements custom: pythonRequirements: dockerizePip: non-linux view raw serverless.yml hosted with ❤ by GitHub

First thing first. NLTK library looks for environment variable by name NLTK_DATA for the corpora data lookup. This variable is set on the line number 48. By default AWS will store the layers unzip content under the opt directory. I’ve created a sub directory in the my project directory with the name nltk, under this directory is have create nltk_data where the actual data lies. See the project structure for better understanding.

folder structure

Now next comes the important part , the configuration of layers which is done from line # 109 to 118. I’ve commented each property of this layers object for your understanding. The most important and the required property here is , path the value for which should be the path of the folder which will be zipped as lambda layer. In my case the folder name is nltk. Do take a note of it that the max size of lambda layer after unzipping should not exceed more than 250 MB. The corpora of NLTK data is more then 2 GB in size. So you should be selective for which module you plan to use in your solution. In my case I only required stopwords and tokenize which comes around 32 MB. This configured layer is being referenced on line #69. Notice the convention used in the Reference as layer name in PascalCase followed by LambdaLayer.

I’m also using serverless-python-requirements to manage python package dependencies. The full source code of this blogpost is available on my github repo.

Hope this helps.

goldytech
folder structure
http://goldytech.wordpress.com/?p=448
Extensions
Why Azure Kubernetes Service (AKS) ?
AzureKubernetes
Anytime and every time I would be always in favor of opting a managed service from the cloud provider (PaaS => Platform as a Service) rather then me doing a baby sitting of servers and managing hardware on my own (IaaS => Infrastructure as a Service). Recently I was asked why I prefer Azure Kubernetes …

Continue reading Why Azure Kubernetes Service (AKS) ?

Show full content

Anytime and every time I would be always in favor of opting a managed service from the cloud provider (PaaS => Platform as a Service) rather then me doing a baby sitting of servers and managing hardware on my own (IaaS => Infrastructure as a Service). Recently I was asked why I prefer Azure Kubernetes Service rather than any other cloud competitor for that matter not even Google cloud, who are actually inventor of Kubernetes. Before  you read further, just a disclaimer from me that this blog post is not about ranting other cloud service providers who provides managed K8’s service. I’ve worked with most of them and I personally was more satisfied with AKS. There can be always be a difference of opinion.

Why Managed Service

Kubernetes is a great platform to manage your containers environment.You can do this yourselves and manually install Kubernetes master node and a bunch of Kubernetes worker nodes. If you’re deploying this in production, then you also must take care of its high availability, patching, maintaining, adding more nodes if your application requires more compute resources. Doing a deployment of a Kubernetes cluster manually and then making sure that it’s highly available, well, that’s a lot of work. All we want is to take advantage of the amazing Kubernetes platform without going to the unnecessary underlying plumbing to get Kubernetes up and running.

Azure Kubernetes Service (AKS)

Microsoft Azure offers Azure Kubernetes Service that simplifies deployment, management, and operations of Kubernetes. It eliminates the burden of ongoing operations and maintenance by provisioning, upgrading, and scaling resources on demand without taking your applications offline. In other words, just like as Azure App Services abstracts you from the underlying virtual machines used to host your web or API apps, AKS abstracts the complex infrastructure of a Kubernetes cluster using Azure virtual machines as Kubernetes worker nodes. Note that you don’t have to babysit or take care of. In fact, so good is AKS that you don’t even see or have to worry about the master node. That is completely managed by Azure. Trust me, this is indeed a winner. Because if you ever speak to a system administrator whose job is to maintain the high availability of the Kubernetes master node, he will cringe on how daunting that entire process can be. By using AKS, you can take advantage of the enterprise-grade features of Microsoft Azure while still maintaining the application portability through Kubernetes and through Docker. AKS reduces the complexity and operational overhead of managing a Kubernetes cluster by offloading much of the responsibility to Microsoft. As a hosted Kubernetes service, Azure handles the critical tasks such as health monitoring and maintenance for you. In addition, you only pay for the agent nodes within your clusters, not for the masters. Now how cool is that? The goal of Azure Kubernetes Service is to provide a container hosting environment by using open-source tools and technologies that are popular among customers today. With AKS, you can use familiar tools like kubectl to manage and interact with your Kubernetes environment. In fact, you don’t even have to install kubectl. If you use the Azure Cloud Shell, then kubectl is a part of that. Let’s take a look at the key benefits that Azure Kubernetes Service offers. With AKS, you get automated Kubernetes version upgrades and patching, so you don’t have to worry about upgrading to a new version of Kubernetes once it’s released. Microsoft takes care of performing version upgrades and patching so that you can concentrate on your applications and not on the infrastructure. Easy cluster scaling. Do you want to scale your cluster from 1 to 10 worker nodes? Well, that’s easy as a pie with AKS. You can use the Azure CLI or the SDKs to make a simple API call, and, boom, your cluster gets scaled. Self-healing hosted control plane, or masters. As I said earlier, you don’t even see the master nodes, so one less thing to worry about. Cost savings. You only have to pay for the running agent pool nodes. Azure Kubernetes Service, you get the benefits of a managed Kubernetes platform plus the entire portfolio of Azure service offerings. Microsoft has its own microservices orchestration tool call Service Fabric. And also Azure Container Instance (ACI) for containers based deployments.Next, Azure Container Registry. For containers, we obviously need a storage layer to house our Docker images. Well, that’s where Azure Container Registry comes in. Azure Container Registry, or ACR, allows you to store images for all types of container deployments including DC/OS, Docker Swarm, Kubernetes, and Azure services such as the App Service, Batch, Service Fabric, and others. Your DevOps team can manage the configuration of apps isolated from the configuration of the hosting environment.Azure Container Registry, is compatible with open-source Docker Registry version 2 APIs, so you can use the same open-source Docker CLI tools you already are aware of.If you’re like me, I’m pretty sure you must be sold on Azure Kubernetes Service.

goldytech
http://goldytech.wordpress.com/?p=443
Extensions
From Blob Container to SendGrid email as attachment via Azure Functions
AzureAzure FunctionsBlobContainerSendGrid
Serverless is no more a tech buzzword. Many enterprises are embracing it in a BIG way. Microsoft Azure has great offerings of Serverless services in the form of Azure Functions , Azure Durable Functions and Logic Apps. Infact all these offerings from Azure has make life of a developer very easy, you as a developer …

Continue reading From Blob Container to SendGrid email as attachment via Azure Functions

Show full content

Serverless is no more a tech buzzword. Many enterprises are embracing it in a BIG way. Microsoft Azure has great offerings of Serverless services in the form of Azure Functions , Azure Durable Functions and Logic Apps. Infact all these offerings from Azure has make life of a developer very easy, you as a developer doesn’t have to be bothered about any plumbing code. Just decorate your functions with with appropriate trigger attributes and use the output parameter binding to chain the output of one function as an input to the another function. Isn’t that so cool ?

In this blog post I will share with you that how you can use Azure Functions for a scenario where any blob that is getting uploaded into the container, and you want send it as an attachment in the email using SendGrid. Yes you heard it right , Azure Functions also support SendGrid.  In approximately 50 lines of the code this functionality can be achieved , if you try do this in a traditional manner without serverless I’m sure it wouldn’t be so simple. So here is the code

.gist table { margin-bottom: 0; }



This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters





namespace AzFuncAppBlobToSendGrid { using System; using System.IO; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using Microsoft.Extensions.Logging; using SendGrid.Helpers.Mail; public static class GetDocumentFromBlob { [FunctionName("GetDocumentFromBlob")] public static void Run([BlobTrigger("email-attachments/{name}", Connection = "slsAppStorage")]Stream myBlob, string name, ILogger log, [SendGrid(ApiKey = "SendGridApiKey")] out SendGridMessage message) { message = new SendGridMessage(); try { log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes"); var blobBytes = GetBytesFromStream(myBlob); message.AddTo("PutToEmailAddressHere"); message.AddContent("text/html", "This is the attachment <b>email</b>"); message.AddAttachment(name, Convert.ToBase64String(blobBytes), "application/pdf", "attachment"); message.SetFrom(new EmailAddress("PutFromEmailAddressHere")); message.SetSubject("test msg"); } catch (Exception ex) { log.LogError(ex, ex.Message); } } private static byte[] GetBytesFromStream(Stream inputStream) { byte[] result; using (var ms = new MemoryStream()) { inputStream.CopyTo(ms); result = ms.ToArray(); } return result; } } }

view raw

Azurefunctions.cs

hosted with ❤ by GitHub

The code is pretty straight forward. The function is decorated with BlobTrigger attribute and the container name is “email-attachments”. The storage account connection is stored in the local.settings.json file. One thing to keep in mind that SendGrid requires the attachment to be converted / attached in Base64 format. Hence the input blob stream is converted into the bytes and later on converted into required format.

SUMMARY

Azure Functions SDK provides all the nuts and bolts for event based programming model and it is deeply integrated with other Azure services, which helps devs to concentrate on their core business logic and writing clean and efficient code to the point. It also allows the extensibility where by which you can create your own binding parameters and runtime can parse them. Last but not least Serverless offers a saving on your cloud billing as you only pay for the actual usage (Only available in Consumption Plan).

goldytech
http://goldytech.wordpress.com/?p=439
Extensions
Introduction to Asp.net Core 1.0
PresentationsAsp.netDNX
I had a privilege to be invited by Agile Testing Alliance , Vadodara chapter to talk about Asp.net Core 1.0 . It was very interactive sessions and the participants asked some really good questions. Here is the synopsis of my talk What is Asp.net Core ? It is a lean stack from Microsoft to develop …

Continue reading Introduction to Asp.net Core 1.0

Show full content

I had a privilege to be invited by Agile Testing Alliance , Vadodara chapter to talk about Asp.net Core 1.0 . It was very interactive sessions and the participants asked some really good questions.

Here is the synopsis of my talk

What is Asp.net Core ?

It is a lean stack from Microsoft to develop the modern web apps built from ground up and is most revolutionary version since asp.net first was released in 2002
Today it is available RC1 update 1 which comes with golive license so this means that this framework is production ready.

Cross platform

This is a game changer and USP about this framework.  It works seamlessly on Windows, OSX and Linux. The same code base runs directly on the metal, and remember this is different from the Mono Framework. In fact the CoreClr is around 11 meg and is shipped along with your application as a nuget package

Unified programming model

In previous versions of MVC 5 and webapi 2 each API existed in different namespaces but there are now one. So if you remember in previous version of mvc you need to inherit the class from the controller and when you need to develop a webapi you need to inherit from apicontroller. But now everything comes under one controller class. same applies to routing, actions, filters etc.

Modular components

Every feature now is shipped as a single nuget package. So if you want to use mvc features download it and register as middleware, You want identity authentication do the same and you are up and running. ConfigureServices where your register your middleware services and Configure is where you use them.  You can write your own custom middleware too.The sample code below give you fair idea of these methods

.gist table { margin-bottom: 0; }



This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters





// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSingleton<IDataService, DataService>(); services.AddSingleton<IViewModelService, ViewModelService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseMvcWithDefaultRoute(); app.UseStaticFiles(); app.UseStatusCodePages(); }

view raw

Sample Startup.cs

hosted with ❤ by GitHub

Middleware and built in Ioc

In previous versions of aps.net DI and IOC were optional but now it is part of the framework and it comes as a built in feature out of the box. You are free to replace it with your own favourite DI framework too.

Modern tooling

You can take the advantage of all the modern tooling which JavaScript world supports, In fact bower can be used for all client side packages whereas nuget can take care of server side packages and dependencies. Use Gulp or Grunt for task runners. Remember that in the older versions you had bundling and minification feature in mvc this is no more there now and it is replaced by this task runners to care of it

DNX context

 

DNX stands for Dot net Execution. The DNX and middleware works in hand to hand to process the request pipeline. Below diagram represents the complete picture.

image

Actually, when the request is made, it first arrives at the web server,web server then invokes the DNX which will load the CLR and then looks for an entry point, the Main method, in your application and executes it. The main method configures the pipeline by using the Startup class, and the request is pushed through the pipeline, processed by the middleware which will produce the response.

Cloud Optimized

As it has low footprint deployment it is your best choice for cloud based solutions.

Github OSS

 

We all know that Microsoft has embrace the OSS in a big way and asp.net core is no more different. If you wish to contribute to this you can very well do it. Just create a pull request or fork it on Github. There are really some very good contributions from community.

Easy install

get.asp.net site is a single source of truth for asp.net core. Right from documentation to tools everything is available here. It is quite smart to recognize your OS version and suggest the appropriate download link.

Multiple choice of IDEs

Though I gave the demo on Visual studio. You have plethora choice for IDE like Code , Atom and many others.

Presentation materials

The sample demo application and slide decks can be downloaded from my Github repo. I’ve heard that recording has also been done. I would check out with the organizers and will upload later once it is available to me.

goldytech
image
http://goldytech.wordpress.com/?p=432
Extensions
My thoughts on Xamarin Forms
Xamarinmobile
  Xamarin as a product has always delighted me. Imagine writing cross platform native mobile apps with your favorite programming language, C#. As a developer you feel proud that your code is running on more than billion devices world wide. To add icing on the cake frameworks like MvvmCross and CrossLight enables the devs to …

Continue reading My thoughts on Xamarin Forms

Show full content

 

Xamarin as a product has always delighted me. Imagine writing cross platform native mobile apps with your favorite programming language, C#. As a developer you feel proud that your code is running on more than billion devices world wide. To add icing on the cake frameworks like MvvmCross and CrossLight enables the devs to share more than 60% of their codebase across the platforms. These frameworks provides plugins for common scenarios of mobile development like GPS,Camera,Navigation etc. The only code that remain distinct to the platform specific is UI code. and believe me this was tuff task. On Android you have to deal with XML and on iOS it was XCode proprietary drag and drop styles for creating the UI. But when Xamarin came out with version 3.0 things changed at that front also. Among many other cool features released with the latest version my personal favorite was Xamarin Forms. This is the awesome library where by which you can create mobile apps by almost sharing 90% of your code base. Yes and this includes the UI part also. At runtime the library will generate native UI for each platform.

You have two options to share the UI code

  1. Create UI with XAML markup
  2. Create UI with code behind.

Xamarin Forms supports Windows Phone 8 also.

XamForms

The code sharing approach can be achieved via Portable class library (PCL) or Shared Project. If you intend to use XAML for your UI then you need to use PCL only.

The library is fully extensible. If you wish to write any platform specific code then you can use Dependency Service and if you want to render custom UI for any platform then you can use custom renderers for the same.

MVVM pattern is supported out of the box. Just set up your INotifyPropertyChanged interface and you are good to go. It has full support of data binding, Command and Messenger. If you don’t want to use built in classes then you can hook up any MVVM Framework. In fact Laurent Bugnion has a very good post about using MvvmLight Toolkit.

The community is quite actively involved in contributing add-ons for Xamarin Forms . Two projects which I’m following very closely are

  1. Xamarin Forms Labs
  2. Acr-Xamarin Forms
GIVE ME MORE

Xamarin Forms popularity has really shooted up rocket high. But as a developer this is my wish list

  1. Provide Xaml Ui Designer , something very similar to Expression Blend . At the time of writing this post only Xamarin Studio supports bit of intellisense for XAML markup.
  2. Start support for Windows Store apps (Windows 8.1 and Windows Phone 8.1)
  3. Similar to maps and SQLite database , provide support for push notifications for all the platforms via common code base.
  4. Provide a converter tool which can parse XAML and convert to C# code and vice versa.
  5. Provide better code refactoring tools like Resharper for Xamarin Studio.
CONCLUSION

I know I may be quite demanding :). This library has a great potential and can be eventually become a game changer. Let us wait for Evolve conference what announcements Xamarin makes for this great library.

goldytech
XamForms
http://goldytech.wordpress.com/?p=421
Extensions
Understanding Cryptography in WindowsRT
How ToWindows 8Cryptography
Security runs in my blood. After extensively working on cryptography on .net platform and have developed couple of mission critical apps. I was given the other challenge for an LOB app in WinRT platform. One of the requirements of the app was of cryptography. I researched it and learned a lot about it, so thought …

Continue reading Understanding Cryptography in WindowsRT

Show full content

crypto

Security runs in my blood. After extensively working on cryptography on .net platform and have developed couple of mission critical apps. I was given the other challenge for an LOB app in WinRT platform. One of the requirements of the app was of cryptography. I researched it and learned a lot about it, so thought let me share the my knowledge with the community.

WHAT PLATFORM HAS TO OFFER

Let the readers get this straight, the WinRT platform is still under evolution , hence it does not offer the same number of apis that are available under .net platform. The platform will become more mature in future and you will see more convergence between the two platforms. There are two main api’s available which does most of heavy weight lifting. They are IBuffer, which marshal out the data. I would term it as an alternative to byte array available in .net and the other one is the static class CryptographicBuffer. I shall be talking about three aspects of cryptography

  1. Hashing
  2. Random Data
  3. Symmetric Encryption
HASHING

WinRT support MD5, SHA-1,SHA-256, SHA-384 and SHA-512 hashing algorithms. The code is pretty simple.

   1: private async void BtnHashConvertTapped(object sender, TappedRoutedEventArgs e)

   2:        {

   3:            if (string.IsNullOrEmpty(this.TxtInput.Text))

   4:            {

   5:                return;

   6:            }

   7:  

   8:            // get the raw input string

   9:            var textToBeHashed = this.TxtInput.Text;

  10:                

  11:            // convert string into binary

  12:            var inputBuffer = CryptographicBuffer.ConvertStringToBinary(textToBeHashed, BinaryStringEncoding.Utf8);

  13:  

  14:            // declare sha512

  15:            var sha512Hash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha512);

  16:                

  17:            // hash the binary data using SHA512 algorithm

  18:            var hashedData = sha512Hash.HashData(inputBuffer);

  19:  

  20:            // encode the hashdata to Base64 format

  21:            var encodeToBase64String = CryptographicBuffer.EncodeToBase64String(hashedData);

  22:            var msgDialog = new MessageDialog(encodeToBase64String);

  23:                

  24:            // show the output in message dialog

  25:            var msg = await msgDialog.ShowAsync();

  26:        }

After conversion of plain input string into binary, we select the algorithm that needs to be applied. The output of which is hashData which is of IBuffer type. And finally converting it back to Base64 format.

RANDOM DATA

It is quite common need of the enterprise apps to generate the random data. In WinRT platform this can be classified in two sections

  • Generating Random Number
   1: /// <summary>

   2:         /// The generate random number.

   3:         /// </summary>

   4:         /// <param name="sender">

   5:         /// The sender.

   6:         /// </param>

   7:         /// <param name="e">

   8:         /// The e.

   9:         /// </param>

  10:         private async void GenerateRandomNumber(object sender, TappedRoutedEventArgs e)

  11:         {

  12:             // generate random number and show it is message dialog.

  13:             var msgDialog = new MessageDialog(CryptographicBuffer.GenerateRandomNumber().ToString());

  14:             var msg = await msgDialog.ShowAsync();

  15:             

  16:         }

The GenerateRandomNumber method returns a 32 bit unsigned integer value.

  • Generating Random Byte Array
   1: /// <summary>

   2:         /// Generates the random byte array

   3:         /// </summary>

   4:         /// <param name="sender">The sender</param>

   5:         /// <param name="e">The EventArgs</param>

   6:         void GenerateRandomArray(object sender, TappedRoutedEventArgs e)

   7:         {

   8:             uint len;

   9:             if (uint.TryParse(this.TxtLength.Text, out len))

  10:             {

  11:                 // generate the random byte array of specified length.

  12:                 var buffer = CryptographicBuffer.GenerateRandom(len);

  13:  

  14:                 // convert the buffer (byte array) into hexadecimal format and show it in message dialog

  15:                 var msgDialog = new MessageDialog(CryptographicBuffer.EncodeToHexString(buffer));

  16:                 msgDialog.ShowAsync();

  17:             }

  18:             else

  19:             {

  20:                 // user inputted invalid number show the message and set back the focus

  21:                 new MessageDialog("Invalid number").ShowAsync();

  22:                 this.TxtLength.Focus(FocusState.Keyboard);

  23:             }

  24:         }

The above code demonstrates to generate random byte array of the specified length and converts back into hexadecimal format.

SYMMETERIC ENCRYPTION

In this type of encryption we have only one key for encryption and decryption. So we should have a key before hand. Apart from the key we also require the Initialization Vector , which does the job of randomizer. In our case we will be using 1024 bit key and 16 bit for IV. Again we will be using the GenerateRandom method to generate these values. Both these binary values will be converted back to Hex format. Let us dive in code and see it in action.

   1: /// <summary>

   2:         /// Generates a random 1024 bit key

   3:         /// </summary>

   4:         /// <returns>A Hex format key</returns>

   5:         private static string GetKey()

   6:         {

   7:             // generate 1024 bits key

   8:             var buffer = CryptographicBuffer.GenerateRandom(1024);

   9:             return CryptographicBuffer.EncodeToHexString(buffer);

  10:         }

  11:  

  12:         /// <summary>

  13:         /// The get initialization vector.

  14:         /// </summary>

  15:         /// <returns>

  16:         /// The <see cref="string"/>.

  17:         /// </returns>

  18:         private static string GetInitializationVector()

  19:         {

  20:             // a 16 bit random binary value

  21:             var buffer = CryptographicBuffer.GenerateRandom(16);

  22:             return CryptographicBuffer.EncodeToHexString(buffer);

  23:         }

Code to Encrypt

   1: /// <summary>

   2:        /// The encrypt.

   3:        /// </summary>

   4:        /// <param name="sender">

   5:        /// The sender.

   6:        /// </param>

   7:        /// <param name="e">

   8:        /// The e.

   9:        /// </param>

  10:        private void Encrypt(object sender, TappedRoutedEventArgs e)

  11:        {

  12:            if (string.IsNullOrEmpty(this.TxtPlain.Text))

  13:            {

  14:                return;

  15:            }

  16:  

  17:            // convert plain text to binary

  18:            var input = CryptographicBuffer.ConvertStringToBinary(this.TxtPlain.Text, BinaryStringEncoding.Utf8);

  19:            var iv = CryptographicBuffer.DecodeFromBase64String(this.IV);

  20:  

  21:            // select the appropriate algorithm

  22:            var encryptor = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

  23:            

  24:            // get the key

  25:            var key = encryptor.CreateSymmetricKey(CryptographicBuffer.DecodeFromBase64String(this.symmetricKey));

  26:            

  27:            // do the encryption

  28:            var encryptedText = CryptographicEngine.Encrypt(key, input, iv);

  29:  

  30:            // convert the encrypted text into hex format and show it in textbox

  31:            this.TxtCipher.Text = CryptographicBuffer.EncodeToHexString(encryptedText);

  32:        }

Code to Decrypt

   1: /// <summary>

   2:         /// The decrypt.

   3:         /// </summary>

   4:         /// <param name="sender">

   5:         /// The sender.

   6:         /// </param>

   7:         /// <param name="e">

   8:         /// The e.

   9:         /// </param>

  10:         private void Decrypt(object sender, TappedRoutedEventArgs e)

  11:         {

  12:             if (!string.IsNullOrEmpty(this.TxtCipher.Text))

  13:             {

  14:                 // as the encrypted string is in hex format decode it and convert back to binary

  15:                 var input = CryptographicBuffer.DecodeFromHexString(this.TxtCipher.Text);

  16:  

  17:                 // decode the initialization vector

  18:                 var iv = CryptographicBuffer.DecodeFromBase64String(this.IV);

  19:  

  20:                 // specify the algorithm use the same one which was used with encryption

  21:                 var decryptor = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

  22:                 

  23:                 // get the key , same should be used which was used for encryption

  24:                 var key = decryptor.CreateSymmetricKey(CryptographicBuffer.DecodeFromBase64String(this.symmetricKey));

  25:  

  26:                 // Do the decryption

  27:                 var decryptedText = CryptographicEngine.Decrypt(key, input, iv);

  28:                 this.TxtPlain.Text = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedText);

  29:             }

  30:             else

  31:             {

  32:                 new MessageDialog("First encrypt").ShowAsync();

  33:             }

  34:         }

CLOSURE

I talked about using the cryptography methods when you are developing a WinRT app. Apart from this operating system also has a built in support for bit locker (Only available in Pro and Enterprise versions) which helps to preserve the enterprise data and can be remotely wiped off with the Mobile Device Management Software like Windows InTune. Last but not least when your app depends on the web services it is always good practice to invoke them securely over SSL. The source code accompanying this post article is available on my GitHub account. Do share your valuable feedback.

goldytech
crypto
http://goldytech.wordpress.com/?p=417
Extensions
Lessons learned with LightSwitch HTML Client project
How ToLightSwitchHTML5
  INTRODUCTION LightSwitch as a technology/tool  has always impressed me.I was quite fascinated that how this super cool technology enables us to avoid all that plumbing code and concentrate on the real core business logic. In a true sense it supports Rapid Application Development. I was already familiar with the Silverlight Client and had developed …

Continue reading Lessons learned with LightSwitch HTML Client project

Show full content

 

INTRODUCTION

LightSwitch as a technology/tool  has always impressed me.I was quite fascinated that how this super cool technology enables us to avoid all that plumbing code and concentrate on the real core busineslessons learneds logic. In a true sense it supports Rapid Application Development. I was already familiar with the Silverlight Client and had developed complete ERP application. LightSwitch team recently shipped the HTML  Client with Visual Studio 2012 Update 2. When I first read about it , the first thought that came to my mind was that it can be a game changer of building LOB apps on mobile.It fully supports adaptive rendering and it based on the Single Page Application concept. I immediately decided that I will try my hands on it but wanted to do some real project rather than some small examples. I decided that I will try to convert one of my modules that were written in Silverlight client to HTML client. So I started the conversion. During the development phase I got stuck up but thanks to Huy Nguyen , from MS who helped me with it. So in this post I share the code snippets of the common scenarios that are required for any LOB apps. I assume if you are reading this post then you are already aware of the basics of LightSwitch client , if not then I recommend you to learn first and revisit this post.

SETTING FOCUS ON FIRST TEXTBOX IN THE FORM

It is one of the common requirements that when the form loads, to increase the usability of the application the cursor should be focused on the first element of the form. This will avoid the user an extra click of focusing the cursor on the control and he/she can immediately start typing. Here you need to target the post_render event of the textbox , of which you need to set focus. One important thing to note in the code snippet is that we are calling the focus method under settimeout method. This is just to ensure that the all the required elements are loaded in DOM.

 

  1. myapp.AddEditCustomer.CustomerName_postRender = function (element, contentItem) {
  2.     // Write code here.
  3.     
  4.     var $firstTextBox;
  5.     $firstTextBox = $("input", $(element)); //get the input tag
  6.     setTimeout(function() {
  7.         $firstTextBox.focus(); //set the focus
  8.     }, 2);
  9. };

PROCESSING BASED ON THE DATABASE LOOKUP VALUES

Imagine you are developing an order data entry screen , You have customer dropdown in this screen and every customer has a fixed percentage of discount associated to it. Now whenever the dropdown value changes you need to retrieve the discount value from the selected customer and do the processing of the discount calculations and update the final price read-only textbox on the screen. Let us see how you can achieve this.

 

  1. myapp.AddEditOrder.created = function (screen) {
  2.     var order = screen.Orders;
  3.  
  4.     function updateTotal() {
  5.         var price;
  6.         var discount = 0;
  7.  
  8.         price = order.Item.Price;
  9.         //if selected customer on order screen is not null
  10.         if (order.Customer) {
  11.             discount = order.Customer.DiscountType;
  12.         }
  13.  
  14.         order.Total = price * (1 – discount / 100);
  15.     }
  16.  
  17.     // When the order's Customer changes, update its total by attaching the change event listener.
  18.     order.addChangeListener("Customer", updateTotal);
  19. };

 

AUTO REFRESH OF PARENT SCREEN

You have the screen of unapproved orders which is data binded to your custom query (where isApproved==false) of Orders entity. All this orders are displayed as Tiles. When any tile is selected a new screen(AddEditOrder) from where the user can set the approved flag equals true. When this screen closes the accepted behaviour should be that the parent screen should no more show that order, unfortunately LightSwitch cannot handle this automatically. And we need to write the custom code for this to get achieved. You cannot use the default EditSelected on the ItemTap event but write your own custom code for it.

  1. myapp.ApproveOrders.Orders_ItemTap_execute = function (screen) {
  2.     // Write code here.
  3.     myapp.showApproveOrdersScreen(screen.UnApprovedOrders.selectedItem, {
  4.         afterClosed: function () {
  5.             screen.UnApprovedOrders.load(); // manual refresh
  6.         }
  7.     });
  8. };

 

OTHER GREAT RESOURCES OF LIGHTSWITCH

Cheers and Keep learning new stuff 🙂

goldytech
lessons learned
http://goldytech.wordpress.com/?p=410
Extensions