Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Friday, 2 July 2021

Using variables in multiline Verbatim String in C#

Hi All,

I had a requirement to pass a json payload to HttpRequest. Json payload was expected to be dynamic in nature, so that it can be utilized for creating multiple HTTP requests.

It took me some time to figure out the answer so here I am writing this blog to help others like me.

Sample Json payload given below. Requirement was to pass variable to ServerName and to some other fields in the payload (I have not mentioned them all here to keep this example simple and neat)

string createTicketJson =
@"[
    {
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Title"",
        ""Value"": ""Server 1234: Shutdown Request""
    },
    {
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Description"",
        ""Value"": ""Please shutdown Server 1234. Ticket can be closed after completion of request.""
    },
    {
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Severity"",
        ""Value"": ""3""
    },
    {
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Requester"",
        ""Value"": ""Sonam""
    },
    {
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Notifications"",
        ""Value"": ""sonam@xyz.com""
    }
]";

A static Json payload will look like below. I have shown the payload in a MessageBox for readability purpose.

Solution

With C# 6, string interpolation can be used. So I added a $ sign in front of createTicketJson variable and replaced hardcoded value of Server Name ‘1234’ with variable serverName in curly brackets {serverName}.

This gave me a compilation error and I realized that my single curly bracket { is giving this error since it expects a single line value (variable) inside it.

To resolve this issue and treat curly bracket as text (instead of variable holder), it needs to be duplicated like below and TADA you have the dynamic version ready for json payload.

Final payload will look like below

string createTicketJson =
$@"[
    {{
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Title"",
        ""Value"": ""Server {serverName}: Shutdown Request""
    }},
    {{
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Description"",
        ""Value"": ""Please shutdown Server {serverName}. Ticket can be closed after completion of request.""
    }},
    {{
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Severity"",
        ""Value"": ""3""
    }},
    {{
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Requester"",
        ""Value"": ""Sonam""
    }},
    {{
        ""op"": ""Add"",
        ""Path"": ""/fields/System.Notifications"",
        ""Value"": ""sonam@xyz.com""
    }}
]";

Hope this was helpful. Happy Coding!!!

Friday, 2 June 2017

Encode in C# and Decode in PowerShell

I had a requirement to read some data in C# windows application, store it in database  and then later use it in a PowerShell script.
It was also required that some data like ‘Keys’ should not be saved directly in database i.e. should not be visible directly to other database users.
One approach is to use complex encryption decryption logic when high data security is a requirement. Read more about Encryption and Decryption of Data here.
Another approach is to use Base64 encoding and decoding approach where very high data security is not a requirement. More about Base64 encoding here and decoding here.
I opted out for Base64 encoding approach as data was not getting shared with external sources where data security is very important and my applications and database were in the same network.
Here comes the coding blog ðŸ™‚ !!!
1. Encode in C# :-
   1: public string EncodeKey(string txtKey)
   2: {
   3:     byte[] passBytes = System.Text.Encoding.Unicode.GetBytes(txtKey);
   4:     string encodedKey = Convert.ToBase64String(passBytes);
   5:     return encodedKey;
   6: }
2. Decode in PowerShell :-
   1: Function ReadData
   2: {
   3:     $ConnectionString = "Data Source='';Initial Catalog='';Integrated Security=SSPI;"
   4:     $con = New-Object "System.Data.SqlClient.SQLConnection"
   5:     $con.ConnectionString = $ConnectionString
   6:     $con.Open()
   7:  
   8:     $sqlcmd = New-Object "System.Data.SqlClient.SqlCommand"
   9:     $sqlcmd.connection = $con
  10:  
  11:     $sqlcmd.CommandText = “Select Key from MyDemoTable where KeyIndex = 'FirstKey'
  12:     $ds = New-Object System.Data.DataSet
  13:     $da = New-Object System.Data.SqlClient.SqlDataAdapter($sqlcmd)
  14:     $return = $da.fill($ds)
  15:     
  16:     $encodedKeyFromDb = $ds.Tables[0].Rows[0][0]
  17:     $originalKey = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($encodedKeyFromDb))
  18:  
  19:     ## Use the Key for Further Code ##
  20: }
Please note that Base64String encoding is very simple to reverse and do not involves any private or public key concept. In situations where data security is a requirement, Encryption Decryption approach should be followed.
Happy Coding!!!