Showing posts with label csharp. Show all posts
Showing posts with label csharp. Show all posts

May 17, 2023

How to stream image from generic handler

This article provides an example of streaming images from a generic handler in .NET.

If you store your images in a database table as byte[] then you can utilize a handler to display them in a data grid.

The process involves sending a request to the handler (.ashx) page, retrieving the image, and then displaying it.

In the given example, we have a grid that stores IDs in one column and displays the corresponding images in another column using an asp:ImageField.

Create a generic handler that streams image. In this example ImageField requests image from getFaceImage.ashx by DataImageUrlField parameter in DataImageUrlFormatString format

public void ProcessRequest(HttpContext context)
{
    int id;

    if (context.Request.QueryString["id"] != null)
    {
        id = Convert.ToInt32(context.Request.QueryString["id"]);

        if (id > 0)
        {
            context.Response.ContentType = "image/jpeg";

            Stream strm = new MemoryStream();
            GetImage(id).Save(strm, ImageFormat.Jpeg);
            strm.Position = 0;

            byte[] buffer = new byte[4096];
            int byteSeq = strm.Read(buffer, 0, 4096);
            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
            }
        }
    }
    else
        return;
}

public Image GetImage(int id)
{
    //Make appropriate calls for image according to id
    //...

    //return the image
    return new Bitmap("");
}

May 8, 2021

[Tips] Random string generators C#

Testing 2 different Random string generators.

void Main()
{
 for(int i=0;i<10;i++){
  Console.WriteLine("GetRandomString: " + GetRandomString(8));
 }
 for(int i=0;i<10;i++){
  Console.WriteLine("GetRandomFileName: " + GetRandomFileName());
 } 
}

public static string GetRandomString(int length)
{
    Random random = new Random();
    const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    return new string(Enumerable.Repeat(chars, length)
      .Select(s => s[random.Next(s.Length)]).ToArray());
}

public static string GetRandomFileName()
{
    string path = Path.GetRandomFileName();
    path = path.Replace(".", ""); // Remove period.
    return path;
}

Result
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomString: tpZIDi0C
GetRandomFileName: smb1u03pvyf
GetRandomFileName: 2ccre5kihis
GetRandomFileName: 24thz5is1pj
GetRandomFileName: ni0z42lexag
GetRandomFileName: 1u11tcvd3qv
GetRandomFileName: vtiqp2sevwy
GetRandomFileName: y2jhumy1hcx
GetRandomFileName: 5o0gsyronpk
GetRandomFileName: m0zva3mhdfn
GetRandomFileName: 2a2dzcdkpbl

Mar 16, 2020

Dynamic Assembly Loading (C# Reflection)

We will achieve following task with dynamic assembly loading in C#.

using System.Net.Http;
using System;
using System.Linq;

var client = new HttpClient();
client.BaseAddress = new Uri("http://api.open-notify.org/astros.json");
string result = client.GetStringAsync("").Result;


Don't add System.Net.Http dll to your reference list. It will be automatically loaded from GAC.

using System;
using System.Linq;
using System.Reflection;

//We don't have "using System.Net.Http" 

//Load System.Net.Http
string name1 = "System.Net.Http,Version=4.0.0.0," + "Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a";
Assembly a1 = Assembly.Load(name1);

//Create HttpClient instance
Type clientType = a1.GetTypes().Where(t => t.Name.Equals("HttpClient")).Single();
object client = Activator.CreateInstance(clientType);

//Set BaseAddress on client
PropertyInfo propertyBaseAddress = clientType.GetProperties().Where(p => p.Name == "BaseAddress").Single();
Uri url = new Uri("http://api.open-notify.org/astros.json");
propertyBaseAddress.SetValue(client, url);

//Test property value
var BaseAddressValue = propertyBaseAddress.GetValue(client);

//Get HttpResponseMessage Task
var methodGetStringAsync = clientType.GetMethod("GetStringAsync", new Type[] { typeof(Uri) });
var responseTask = methodGetStringAsync.Invoke(client, new string[] { null });

//Get HttpResponseMessage result from Task
var responseType = responseTask.GetType();
PropertyInfo propResponse = responseType.GetProperties().Where(p => p.Name == "Result").Single();

var responseResult = propResponse.GetValue(responseTask);  //This is the string result


Bonus: List your loaded assemblies

Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();

foreach (Assembly a in assemblies)
{
     Console.WriteLine(a.GetName());
}


Output
mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
System.Net.Http is displayed here even not referenced in Visual Studio.

Sep 20, 2019

Upload file to Console Webapi (Owin)

Upload a file to a console based webapi host (owin).

Method 1: MultipartFormDataStreamProvider

 

[HttpPost]
public async Task PostFile()
{
 string root = AppDomain.CurrentDomain.BaseDirectory + "Uploads"; 

 var provider = new MultipartFormDataStreamProvider(root);
 await Request.Content.ReadAsMultipartAsync(provider);
 foreach (var file in provider.FileData)
 {
  var buffer = File.ReadAllBytes(file.LocalFileName);  
 }
 return new HttpResponseMessage() { Content = new StringContent("OK") };
}

Postman Post Sample

Select form-data for Body. Enter key name and select a file for the value.
POST /api/file/PostByteArrayAsync HTTP/1.1
Host: 127.0.0.1:5000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Length: 15143
Connection: keep-alive
cache-control: no-cache


Content-Disposition: form-data; name="file"; filename="/C:/Users/oktay/logs.txt


------WebKitFormBoundary7MA4YWxkTrZu0gW--

Method 2: ReadAsByteArrayAsync

This method requires filename in header. Add key/value for "filename".
 

[HttpPost]
public string PostFile()
{
 string fileName = Request.Headers.GetValues("filename").ElementAt(0);

 string root = AppDomain.CurrentDomain.BaseDirectory + "Uploads\\";
 var filePath = root + fileName;

 var fc = Request.Content.ReadAsByteArrayAsync().Result;
 File.WriteAllBytes(filePath, fc);

 return "uploaded";
}

Jan 22, 2019

Decryption function (dotnet & nodejs)

In "Encryption function (dotnet & nodejs)" post I described encryption functions.
In this post you can see decrypt functions.

Nodejs uses "crypto-js" package.
Dotnet uses "System.Security.Cryptography" namespace.

Dotnet

 

public static string Decrypt(string encryptedBase64)
{
 byte[] rawSecretKey = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };  
 string PassPhrase = "passPhrase";

 MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
 byte[] data = Encoding.ASCII.GetBytes(PassPhrase);
 data.Dump("data");
 
 byte[] passwordKey = x.ComputeHash(data);
 
 RijndaelManaged rijndael = new RijndaelManaged();
 ICryptoTransform rijndaelDecryptor = rijndael.CreateDecryptor(passwordKey, rawSecretKey);
 try
 {
  byte[] encryptedData = Convert.FromBase64String(encryptedBase64);
  byte[] newClearData = rijndaelDecryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
  return Encoding.ASCII.GetString(newClearData);
 }
 catch (Exception ex)
 {
  return null;
 }
}

Node.js

 

 var bytes = CryptoJS.AES.decrypt(encrypted, myRijndaelKey, {
        iv: ivCodeWords,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
 var plaintext = bytes.toString(CryptoJS.enc.Utf8);
 console.log("decrypted text: " + plaintext);

Nov 14, 2018

Web Api Post Types (C#)

You can find some implementations of Web Api Post types here.
Model

public class Model
{
 public string Name { get; set; }
 public string Id { get; set; }

 public string Save()
 {
  return "Saved";
 }
}

1. Post Raw

Web Api

[HttpPost]
public async Task PostRaw()
{
 string json = await Request.Content.ReadAsStringAsync();

 Model model = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

 return model.Save();
}
Request
POST http://localhost:63693/api/test/PostRaw HTTP/1.1
Content-Type: application/json

{"Id":"1","Name":"Model1"}

2. FromBody

Web Api

[HttpPost]
public string PostFromBody([FromBody]string body)
{
 Model model = Newtonsoft.Json.JsonConvert.DeserializeObject(body);

 return model.Save();
}
Request
Escape json: "{\"Id\":\"1\",\"Name\":\"Model1\"}"
POST http://localhost:63693/api/test/PostModel HTTP/1.1
Content-Type: application/json

"{\"Id\":\"1\",\"Name\":\"Model1\"}"
or
POST http://localhost:63693/api/test/PostFromBody HTTP/1.1
Content-Type: application/x-www-form-urlencoded

%7B%22body%22=%7B%22Id%22%3A%221%22%2C%22Name%22%3A%22Model1%22%7D%7D

3. Class parameter

Web Api

[HttpPost]
public string PostModel(Model model)
{
 return model.Save();
}
Request
POST http://localhost:63693/api/test/PostModel HTTP/1.1
Content-Type: application/json

{"Id":"1","Name":"Model1"}

4. String parameter + Request.Content

Web Api

[HttpPost]
public string PostModelJson(string key)
{
 //You may check key here...

 var contentType = Request.Content.Headers.ContentType.MediaType;
 var body = Request.Content.ReadAsStringAsync().Result;

 Model model = null;

 if (contentType == "application/json")
 {
  model = Newtonsoft.Json.JsonConvert.DeserializeObject(body);

  return model.Save();
 }
 else
  throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
Request
POST http://localhost:63693/api/test/PostModelJson?key=1 HTTP/1.1
Content-Type: application/json

{"Id":"1","Name":"Model1"}

5. Post uri parameter

Web Api

[HttpPost]
public string PostModelFromUri([FromUri]Model model)
{
 return model.Save();
}
Request
POST http://localhost:63693/api/test/PostModelFromUri?id=1&name=Model1 HTTP/1.1

6. Multipart Form Data

Web Api

[HttpPost]
public string PostMultipart()
{
 var contentType = Request.Content.Headers.ContentType.MediaType;

 if (contentType == "multipart/form-data")
 {
  var parts = Request.Content.ReadAsMultipartAsync().Result;

  var contents = parts.Contents;
  Model model = new Model();

  foreach (StreamContent item in contents)
  {
   if (item.Headers.ContentDisposition.Name.Trim('"') == "Id")
    model.Id = item.ReadAsStringAsync().Result;
   else if (item.Headers.ContentDisposition.Name.Trim('"') == "Name")
    model.Name = item.ReadAsStringAsync().Result;
  }

  return model.Save();
 }
 else
  throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);            
}
Request
POST http://localhost:63693/api/test/PostMultipart HTTP/1.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryrKvJKnAHtuVvEERM

------WebKitFormBoundaryrKvJKnAHtuVvEERM
Content-Disposition: form-data; name="Id"

1
------WebKitFormBoundaryrKvJKnAHtuVvEERM
Content-Disposition: form-data; name="Name"

Model1
------WebKitFormBoundaryrKvJKnAHtuVvEERM--

Oct 15, 2018

Encryption function (dotnet & nodejs)

Following functions give same result on dotnet and nodejs platforms.
Nodejs uses "crypto-js" package.
Dotnet uses "System.Security.Cryptography" namespace.

Dotnet


void Main()  
 {  
     string clearText = "oktay";  
     Console.WriteLine("clearText: " + clearText);  
     string encrypted = Crypto.EncryptToBase64(clearText);  
     Console.WriteLine("encrypted: " + encrypted);  
 }  
 public static class Crypto  
 {  
   public static string EncryptToBase64(string decryptedText)  
   {  
     byte[] rawSecretKey = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };  
     string PassPhrase = "passPhrase";  
     MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();  
     byte[] data = Encoding.UTF8.GetBytes(PassPhrase);  
         byte[] passwordKey = x.ComputeHash(data);  
         Console.WriteLine("key: " + BitConverter.ToString(passwordKey).Replace("-", ""));  
         Console.WriteLine("iv : " + BitConverter.ToString(rawSecretKey).Replace("-", ""));  
         RijndaelManaged rijndael = new RijndaelManaged();  
     ICryptoTransform rijndaelEncryptor = rijndael.CreateEncryptor(passwordKey, rawSecretKey);  
     try  
     {  
       byte[] decryptedData = Encoding.UTF8.GetBytes(decryptedText);  
       byte[] newClearData = rijndaelEncryptor.TransformFinalBlock(decryptedData, 0, decryptedData.Length);  
       return Convert.ToBase64String(newClearData, 0, newClearData.Length);  
     }  
     catch (Exception ex)  
     {  
       throw ex;  
     }  
   }  
 }  

Node.js

 
 var CryptoJS = require("crypto-js");  
 function byteArrayToHexString(byteArray) {  
  return Array.prototype.map  
   .call(byteArray, function(byte) {  
    return ("0" + (byte & 0xff).toString(16)).slice(-2);  
   })  
   .join("");  
 }  

 function EncryptToBase64(password) {
  console.log("clearText: " + password); 
  var PassPhrase = "passPhrase";  
  var rawSecretKey = [ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 ];
  
  var myRijndaelKeyBytes = CryptoJS.enc.Utf8.parse(PassPhrase);  
  var myRijndaelKey = CryptoJS.MD5(CryptoJS.enc.Utf8.parse(PassPhrase));  
  console.log("key: " + myRijndaelKey);  
  var myRijndaelIV = byteArrayToHexString(rawSecretKey);  
  var ivCodeWords = CryptoJS.enc.Hex.parse(myRijndaelIV);  
  console.log("iv: " + ivCodeWords);  
  var encrypted = CryptoJS.AES.encrypt(  
   CryptoJS.enc.Utf8.parse(password),  
   myRijndaelKey,  
   {  
    iv: ivCodeWords,  
    mode: CryptoJS.mode.CBC,  
    padding: CryptoJS.pad.Pkcs7  
   }  
  );  
  var base64 = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);  
  console.log("encrypted: " + base64);  
 }  
 EncryptToBase64("oktay");  
 return;  

Result

clearText: oktay
key: C6CEC8C6CAA9A579644664F0575DB2F5
iv : 01010101010101010101010101010101
encrypted: S+6CSoMM6no9atihmfyayQ==

Feb 5, 2015

Query samples on a self referenced table (Part-4)

In previous post we joined tables but there was a problem. We can not see "Help" menu which has not any sub menu. To solve the problem we will use Outer Join.

Linq

var menus = from t in Menus
  where t.MenuType==1
  join s in Menus on t.MenuID equals s.MenuParent into Subs
  from ss in Subs.DefaultIfEmpty()
  select new {
   TopMenu = t.Title,
   SubMenu = ss == null ? null : ss.Title
  };

Lambda

Menus
   .Where (t => (t.MenuType == 1))
   .GroupJoin (
      Menus, 
      t => (t.MenuID), 
      s => s.MenuParent, 
      (t, Subs) => 
         new  
         {
            t = t, 
            Subs = Subs
         }
   )
   .SelectMany (
      temp0 => temp0.Subs.DefaultIfEmpty (), 
      (temp0, ss) => 
         new  
         {
            TopMenu = temp0.t.Title, 
            SubMenu = (ss == null) ? null : ss.Title
         }
   )

SQL

DECLARE @p0 Int = 1

SELECT [t0].[Title] AS [TopMenu], 
    (CASE 
        WHEN [t2].[test] IS NULL THEN NULL
        ELSE CONVERT(NVarChar(MAX),[t2].[Title])
     END) AS [SubMenu]
FROM [Menu] AS [t0]
LEFT OUTER JOIN (
    SELECT 1 AS [test], [t1].[Title], [t1].[MenuParent]
    FROM [Menu] AS [t1]
    ) AS [t2] ON ([t0].[MenuID]) = [t2].[MenuParent]
WHERE [t0].[MenuType] = @p0

Jan 23, 2015

Query samples on a self referenced table (Part-3)

In previous post we queried tables.
In this post we will join the tables. This will show Top Menu title and Sub Menu title in a row.

Linq

var menus = from t in Menus
  where t.MenuType == 1
  join s in Menus on t.MenuID equals s.MenuParent
  select new {
   TopMenu = t.Title,
   SubMenu = s.Title
  };

Lambda

Menus
   .Where (t => (t.MenuType == 1))
   .Join (
      Menus, 
      t => (Int32?)(t.MenuID), 
      s => s.MenuParent, 
      (t, s) => 
         new  
         {
            TopMenu = t.Title, 
            SubMenu = s.Title
         }
   )

SQL

DECLARE @p0 Int = 1

SELECT [t0].[Title] AS [TopMenu], [t1].[Title] AS [SubMenu]
FROM [Menu] AS [t0]
INNER JOIN [Menu] AS [t1] ON ([t0].[MenuID]) = [t1].[MenuParent]
WHERE [t0].[MenuType] = @p0

Jan 13, 2015

Query samples on a self referenced table (Part-2)

In previous post we created a database table, filled it with sample data and saw some basic queries.
In this post we will query the table in { Menu.Title, IEnumerable<menu> } form. This will show Top menu title and sub menu items in a row.

Linq

var menus = from t in Menus 
 where t.MenuType==1 
 select new {
  t.Title,
  SubMenus = from s in Menus
  where t.MenuType==1 && t.MenuID==s.MenuParent
  select s
 };

Lambda

Menus
   .Where (t => (t.MenuType == 1))
   .Select (
      t => 
         new  
         {
            Title = t.Title, 
            SubMenus = Menus
               .Where (s => ((t.MenuType == 1) && ((Int32?)(t.MenuID) == s.MenuParent)))
         }
   )

SQL

DECLARE @p0 Int = 1
DECLARE @p1 Int = 1

SELECT [t0].[Title], [t1].[MenuID], [t1].[Title] AS [Title2], [t1].[Url], [t1].[MenuParent], [t1].[MenuType], (
    SELECT COUNT(*)
    FROM [Menu] AS [t2]
    WHERE ([t0].[MenuType] = @p0) AND (([t0].[MenuID]) = [t2].[MenuParent])
    ) AS [value]
FROM [Menu] AS [t0]
LEFT OUTER JOIN [Menu] AS [t1] ON ([t0].[MenuType] = @p0) AND (([t0].[MenuID]) = [t1].[MenuParent])
WHERE [t0].[MenuType] = @p1


Jan 11, 2015

Query samples on a self referenced table (Part-1)

I will give you some query examples in Linq, Lambda Expression and SQL syntax.
Examples are build on one table that includes self referenced data. We will create a menu table on the database and fill it with some sample data. Some menu items are top menus and the others are subs. Sub menu items has a parent id which is referenced another menu item on the same table.

Step 1: Create menu table on SQL Server.
CREATE TABLE [dbo].Menu(
 [MenuID] [int] IDENTITY(1,1) NOT NULL,
 [Title] [nvarchar](50) NULL,
 [Url] [nvarchar](100) NULL,
 [MenuParent] [int] NULL, --If has parent fill this column with MenuID 
 [MenuType] [int] NULL --1: Top menu, 2:Sub menu
)

Step 2: Insert some data
INSERT INTO [dbo].[Menu] ([Title], [Url], [MenuParent], [MenuType]) VALUES ('Accounts', '.aspx', 0, 1) --ID=1

INSERT INTO [dbo].[Menu] ([Title], [Url], [MenuParent], [MenuType]) VALUES ('Users', '.aspx', 1, 2) --ID=2

INSERT INTO [dbo].[Menu] ([Title], [Url], [MenuParent], [MenuType]) VALUES ('Customers', '.aspx', 1, 2) --ID=3

INSERT INTO [dbo].[Menu] ([Title], [Url], [MenuParent], [MenuType]) VALUES ('Settings', '.aspx', 0, 1) --ID=4

INSERT INTO [dbo].[Menu] ([Title], [Url], [MenuParent], [MenuType]) VALUES ('App', '.aspx', 4, 2) --ID=5

INSERT INTO [dbo].[Menu] ([Title], [Url], [MenuParent], [MenuType]) VALUES ('Web', '.aspx', 4, 2) --ID=6

INSERT INTO [dbo].[Menu] ([Title], [Url], [MenuParent], [MenuType]) VALUES ('Service', '.aspx', 4, 2) --ID=7

INSERT INTO [dbo].[Menu] ([Title], [Url], [MenuParent], [MenuType]) VALUES ('Parameters', '.aspx', 0, 1) --ID=8

INSERT INTO [dbo].[Menu] ([Title], [Url], [MenuParent], [MenuType]) VALUES ('Account Type', '.aspx', 8, 2) --ID=9

INSERT INTO [dbo].[Menu] ([Title], [Url], [MenuParent], [MenuType]) VALUES ('Help', '.aspx', 0, 1) --ID=10

Step 3: Query table. In this example we will see some basic queries.

Basic Queries

Queries below selects top menus and sub menus.

Linq

var topMenus = from f in Menus where f.MenuType==1 select f;
var subMenus = from f in Menus where f.MenuType==2 select f;

Lambda

Menus
   .Where (f => (f.MenuType == 1))

Menus
   .Where (f => (f.MenuType == 2))

SQL

DECLARE @p0 Int = 1
SELECT [t0].[MenuID], [t0].[Title], [t0].[Url], [t0].[MenuParent], [t0].[MenuType]
FROM [Menu] AS [t0]
WHERE [t0].[MenuType] = @p0
GO

DECLARE @p1 Int = 2
SELECT [t0].[MenuID], [t0].[Title], [t0].[Url], [t0].[MenuParent], [t0].[MenuType]
FROM [Menu] AS [t0]
WHERE [t0].[MenuType] = @p1
GO

See Part-2 for the other queries.