How to read mp3 tag info using c#

Mp3 tag  consists of attaching a fixed block size of 128 bytes at the end of the file in question. This block contains the following tags: A header that identifies the presence of block ID3 and version. Specifically, said header comprises TAG characters.

Title: 30 characters.
Artist: 30 characters.
Album: 30 characters.
Year: 4 characters.
Comment: 30 characters.
Genre (music): a character.

How to encrypt Bitmap image in c#


In this post I will show you how to encrypt bitmap image in c#.The technique is very simple.First we extract header from the image and then encrypt the rest byte data and then combined the header with this encrypted data.


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Enc
{
    class Program
    {
        static string FILENAME = @"D:\ub.bmp";
        static string ENCFILENAME = @"D:\enc.bmp";
        static void Main(string[] args)
        {
            //Create instance of DES
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            //Generate IV and Key
            des.GenerateIV();
            des.GenerateKey();
            //Set Encryption mode
            des.Mode = CipherMode.ECB;
            //Read
            FileStream fileStream = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
            MemoryStream ms = new MemoryStream();
            fileStream.CopyTo(ms);
            //Store header in byte array (we will used this after encryption)
            var header = ms.ToArray().Take(54).ToArray();
            //Take rest from stream
            var imageArray = ms.ToArray().Skip(54).ToArray();
            //Create encryptor
            var enc = des.CreateEncryptor();
            //Encrypt image
            var encimg = enc.TransformFinalBlock(imageArray, 0, imageArray.Length);
            //Combine header and encrypted image
            var image = Combine(header, encimg);
            //Write encrypted image to disk
            File.WriteAllBytes(ENCFILENAME, image);


        }
        public static byte[] Combine(byte[] first, byte[] second)
        {
            byte[] ret = new byte[first.Length + second.Length];
            Buffer.BlockCopy(first, 0, ret, 0, first.Length);
            Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
            return ret;
        }
    }
}

How to post array of hashes in wcf

In this post I will show you how to post json array hashes in wcf rest service.Before going to code snippet let's discuss some basic terminology.

What is Array of Hashes
Array of hashes is a data structure in which each record itself contains key/value pairs. Arrays of hashes are used less frequently than the other structures.Below is example of array of hashes
AoH = (
    {
       husband  => "barney",
       wife     => "betty",
       son      => "bamm bamm",
    },
    {
       husband => "george",
       wife    => "jane",
       son     => "elroy",
    },

    {
       husband => "homer",
       wife    => "marge",
       son     => "bart",
    },
  );
JSON String

When we enclosed the json data into quote then we called this string is JSON string
var jsonString='[{ "x": 10, "y": 20, "z": 30 }, { "x": 12, "y": 21, "z": 33 }, { "x": 13, "y": 23, "z": 35}]';

Object literal
When we don't enclosed string in quote then we called this as JSON object literals
var jsonObject= [{ "x": 10, "y": 20, "z": 30 }, { "x": 12, "y": 21, "z": 33 }, { "x": 13, "y": 23, "z": 35}];

For this demo I am going to use JSON.NET library.First go to nuget package manager and install json lib.After that create a simple REST service shown as below.
https://images-blogger-opensocial.googleusercontent.com/gadgets/proxy?url=http://3.bp.blogspot.com/-pxgGPGCnpAE/UfqRQKBLOMI/AAAAAAAACis/VwfcmWb2BWc/s640/newton.png&container=blogger&gadget=a&rewriteMime=image/*

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Newtonsoft.Json;
namespace WcfService2
{

    public class Service1 : IService1
    {
        public string GetData(string value)
        {
            StringBuilder stringBuilder = new StringBuilder();
            dynamic data = JsonConvert.DeserializeObject(value);
            foreach (var item in data)
            {
                stringBuilder.Append(item.x);
            }
            return stringBuilder.ToString();
        }

    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService2
{

    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "POST")]
        string GetData(string value);

    }

}

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WcfService2.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-2.0.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#id").click(function () {
                var d = '[{ "x": 10, "y": 20, "z": 30 }, { "x": 12, "y": 21, "z": 33 }, { "x": 13, "y": 23, "z": 35}]';
                $.ajax({
                    type: 'POST',
                    url: "http://localhost:1449/Service1.svc/GetData",
                    data: JSON.stringify(d),
                    contentType: "application/json",
                    success: function (data) {
                    },
                    complete: function () {
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" value="S" id="id" />
    </div>
    </form>
</body>
</html>

Low level bit hacks

I came across a very interesting article on Peteris Krumin’s blog on how to use boolean operators to perform really useful low level bit hacks.

Most people are used to just using AND and OR operators on integers, but this article goes into much more detail, explaining good – and fast – ways to manipulate integers at a bit level.

It is well worth it to go and check it out.

How to stream video in asp.net using WCF rest service

In this post I will show you how to stream video in asp.net using WCF rest service.The techniques used here is as we don't know the exact content lenght of the data so we used Content-Encoding transfer encoding allows a server to maintain an HTTP persistent connection for dynamically generated content. In this case the HTTP Content-Length header cannot be used to delimit the content and the next HTTP request/response, as the content size is as yet unknown. Chunked encoding has the benefit that it is not necessary to generate the full content before writing the header, as it allows streaming of content as chunks and explicitly signaling the end of the content, making the connection available for the next HTTP request/response..
  • Open visual studio and create a simple wcf service.
  • Add a new class and add following code into it

How to create custom config section in asp.net

You can extend ASP.NET configuration settings with XML configuration elements of
your own. To do this, you create a custom configuration section handler.
The handler must be a .NET Framework class that inherits from 
the System.Configuration.ConfigurationSection class. The section handler 
interprets and processes the settings that are defined in XML configuration 
elements in a specific section of a Web.config file. You can read and write 
these settings through the handler's properties.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace CustomConfigSection
{
    public class LoginRedirectByRoleSection : ConfigurationSection
    {
        [ConfigurationProperty("roleRedirects")]
    public RoleRedirectCollection RoleRedirects
        {
    get
            {
    return (RoleRedirectCollection)this["roleRedirects"];
            }
    set
            {
    this["roleRedirects"] = value;
            }
        }
    }
    public class RoleRedirect : ConfigurationElement
    {
        [ConfigurationProperty("role", IsRequired = true)]
    public string Role
        {
    get
            {
    return (string)this["role"];
            }
    set
            {
    this["role"] = value;
            }
        }
        [ConfigurationProperty("url", IsRequired = true)]
    public string Url
        {
    get
            {
    return (string)this["url"];
            }
    set
            {
    this["url"] = value;
            }
        }
    }
    public class RoleRedirectCollection : ConfigurationElementCollection
    {
    public RoleRedirect this[int index]
        {
    get
            {
    return (RoleRedirect)BaseGet(index);
            }
        }
    public RoleRedirect this[object key]
        {
    get
            {
    return (RoleRedirect)BaseGet(key);
            }
        }
    protected override ConfigurationElement CreateNewElement()
        {
    return new RoleRedirect();
        }
    protected override object GetElementKey(ConfigurationElement element)
        {
    return ((RoleRedirect)element).Role;
        }
    }
}

<configSections>
    <section name="loginRedirectByRole" type="CustomConfigSection.LoginRedirectByRoleSection,CustomConfigSection" allowLocation="true" allowDefinition="Everywhere" />
    </configSections>
    <loginRedirectByRole>
    <roleRedirects>
    <add role="Administrator" url="~/Admin/Default.aspx" />
    <add role="User" url="~/User/Default.aspx" />
    </roleRedirects>
    </loginRedirectByRole>

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using CustomConfigSection;
namespace CustomConfigSection
{
    public partial class WebForm1 : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
        {
           LoginRedirectByRoleSection roleRedirectSection = (LoginRedirectByRoleSection)ConfigurationManager.GetSection("loginRedirectByRole");
    foreach (RoleRedirect roleRedirect in roleRedirectSection.RoleRedirects)
            {
    if (Roles.IsUserInRole("", roleRedirect.Role))
                {
                    Response.Redirect(roleRedirect.Url);
                }
            }
        }
    }
}

How to read webpage asynchronously in c#

most programming languages a called method is executed synchronously, i.e. in the thread of execution from which it is invoked. If the method needs a long time to completion, e.g. because it is loading data over the internet, the calling thread is blocked until the method has finished. When this is not desired, it is possible to start a "worker thread" and invoke the method from there. In most programming environments this requires many lines of code, especially if care is taken to avoid the overhead that may be caused by creating many threads. AMI solves this problem in that it augments a potentially long-running ("synchronous") object method with an "asynchronous" variant that returns immediately, along with additional methods that make it easy to receive notification of completion, or to wait for completion at a later time.




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
namespace AsyncDemo
{
class Program
    {
static void Main(string[] args)
        {
string url = @"http://microsoft.com";
            DownloadAsync(url);
            Console.WriteLine("Doing Some more work in main");
            Console.ReadLine();
        }
private static void DownloadAsync(string url)
        {
var httpwebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpwebRequest.BeginGetResponse(ar =>
                {
var webResponse = httpwebRequest.EndGetResponse(ar);
using (var responseStream = webResponse.GetResponseStream())
                    {
var manulaResetEvent = new ManualResetEvent(false);
//Set the buffer size
byte[] buffer = new byte[1024];
//Callback
                        AsyncCallback readCallback = null;
                        readCallback = ir =>
                            {
var bytesRead = responseStream.EndRead(ir);
if (bytesRead > 0)
                                {
                                    Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, buffer.Length));
                                    responseStream.BeginRead(buffer, 0, buffer.Length, readCallback, null);
                                }
else
                                {
//Alowing waiting thread to proceed
                                    manulaResetEvent.Set();
                                }
                            };
                        responseStream.BeginRead(buffer, 0, buffer.Length, readCallback, null);
//Block the current thread
                        manulaResetEvent.WaitOne();
                    }
                }, null);
        }
    }
}