Showing posts with label code. Show all posts
Showing posts with label code. 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

Dec 19, 2019

AWS Lambda Functions

Create Lambda function

Go to AWS Lambda homepage and login to console.
Press "Create Function" button.
Enter function name.
Select a language (environment) from Runtime dropdown. I will use node.js 8.10.
For the first time you can create a new role for permissions. Select "Create a custom role" from Role dropdown box.
A new page will be shown. Select "Create a new IAM Role" from IMA Role dropdown and then give a name. Press "Allow" button.
This will create a new role and browser will return back to "Create function" page.
Press "Create function" button.
It will redirect you to function page.
Initially the page adds a template code which returns success code and a hello message. We will continue with this code.
 

exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

2. AWS CLI to call the function

Download AWS CLI setup to your computer. For Windows download link is here. For other operating systems you can find links at the same page.
After installation go to aws cli folder and run following command to start configuration.
aws configure
We need following info.
AWS Access Key ID [None]: "Your Access Key"
AWS Secret Access Key [None]: "Your Secret Key"
Default region name [None]: 
Default output format [None]: 
To get keys go to AWS console
Click to your name and select "My Security Credentials".
On "Access keys" section click to "Create New Access Key" button to create new keys. You have to save your secret key because it will displayed only once.
Now return back to aws cli console and enter Access Key ID and Secret Access Key.
Enter region name like "us-west-2".
Enter json for default output format.
Now you can run your functions.
We need our function name as a parameter. In lambda function page copy arn.
Run aws command to run function. The lines between "{ }" is the response from our lambda function. You can see hello message inside txt file which we passed as a parameter.
aws lambda invoke --function-name arn:aws:lambda:us-west-2:123456780315:function:FirstLambda "c:\aws.txt"

{
    "StatusCode": 200,
    "ExecutedVersion": "$LATEST"
}
aws.txt file content
{"statusCode":200,"body":"\"Hello from Lambda!\""}

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

Jan 14, 2016

How to send an object and a parameter to an asp.net web api

In this sample we will post an object and a string parameter with ajax from client. Asp.net side will recognize data as form data. We will convert (deserialize) coming object data into corresponding class.

  • Server side: Webapi function


[HttpPost]
public string WebapiPost()
{
    var httpRequest = HttpContext.Current.Request;

    string name = httpRequest.Form["name"];
    string jsonObj = httpRequest.Form["obj"];

    JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
    MyObject obj = jsonSerializer.Deserialize<MyObject>(jsonObj);

    return obj.Key;

}

public class MyObject
{
    public int ID { get; set; }
    public string Key { get; set; }

}

  • Client side: Post function 

function PostDataSample(url, data) {
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: 'html',
        success: function (response) {
            console.log("PostData::success");
            callback(response);
        },
        failure: function (response) {
            console.log("PostData::failure");
            callback(response);
        }
    });

}
Note that "dataType" is "html"

  • Client side: Call post function


var name = "Oktay";
var myObject = {};
myObject.ID = 1;
myObject.Key = "key1";

PostDataSample("/api/postMyobject/WebapiPost", "obj=" + JSON.stringify(myObject) + "&name=" + name, "html");
Note that we used object as JSON.stringify. You can add more parameters.

Nov 27, 2015

Performance Counters on ASP.NET

If you want to use performance counters on your ASP.NET page you can use  System.Diagnostics.PerformanceCounter class. Example below shows running inside a generic handler.


static System.Diagnostics.PerformanceCounter cpuUsage;

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    if (cpuUsage == null)
    {
        cpuUsage = new System.Diagnostics.PerformanceCounter();
        cpuUsage.CategoryName = "Processor";
        cpuUsage.CounterName = "% Processor Time";
        cpuUsage.InstanceName = "_Total";
    }

    context.Response.Write(cpuUsage.NextValue());
}


When you test in Visual Studio you will see you can get CPU usage for every call (except first call, it is 0 for the first time). But when you deploy your code to the server probably you will see the error below.
Access to the registry key 'Global' is denied. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.UnauthorizedAccessException: Access to the registry key 'Global' is denied.
To solve this problem;

1. Check your application pool from the IIS website settings (basic or advance).


2. Go to "Application Pools" section. Right click and select "Advanced Settings".


3. Find "Identity".


4. Go to "Server Manager" > "Local Users and Groups" > "Groups". On the right pane right click to "Performance Monitor Users" > Properties.



5. Add user you saw in the 3rd step (Identity). If you saw "ApplicationPoolIdentity" in the "Identity" then type "IIS APPPool\[Pool name]". In our example pool name is "ASP.NET v4.0".



6. Restart IIS. Now you should see the performance counter page without error.

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.

Nov 21, 2014

Jul 3, 2008

Copy As HTML

When i copied code from Visual Studio and pasted it to my blog, i wasted too much time for formatting. Now i have a tool for copying source code from VS in html format. So i get html code of source exactly what i see in VS. The name of program is Copy as HTML.

After installing the program you can use it in VS. Just select code and right click. You will see Copy as HTML menu item.







When you select it an option window comes. I use options that you see below.













And here result:

1 ' Review the values of the assembly attributes

2
3 <Assembly: AssemblyTitle("")>
4 <Assembly: AssemblyDescription("")>
5 <Assembly: AssemblyCompany("")>
6 <Assembly: AssemblyProduct("")>
7 <Assembly: AssemblyCopyright("")>
8 <Assembly: AssemblyTrademark("")>
9 <Assembly: CLSCompliant(True)>

You see it is useful and very easy to use.