Wednesday, July 7, 2010

Create a key in the registry using C#

Introduction

Microsoft.win32 Namespace is containing register class; Register class is used to manipulate the system registry. It represents a Key level node in the windows registry.

The registry acts as information for the operating system and application on a computer. Register keys are the base unit of registry. Each key have multiple values alone with it.

C# Code for creates a key in the register.

CreateSubKey method to creates a new subkey or opens an existing subkey for write access


Example:
Microsoft.Win32.RegistryKey mykey;
mykey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(“Muhil Software”);

To set a value for the particular key is setValue method

Example:

mykey.SetValue(“Muhil”, “12345789”);


Some time exceptions will occur due to the name of the key is null or the user does not have permissions to create registry key or they key name exceeds the limit or if the key is closed or the register key is read only.


More secure to write data into register use Microsoft.Win32.Registry.CurrentUser instead of Microsoft.Win32.Registry.LocalMachine.
Complete listing for create a key.

Microsoft.Win32.RegistryKey mykey;
mykey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(“Muhil Software”);
mykey.SetValue(“Muhil”, “12345789”);
mykey.close();


Retrieve Registry key information.

RegistryKey.GetValue Method retrieves the value in a specified name. If returns null the name does not exist in the registry and it will return as a object.
Example:

key.GetValue(“Muhil”);

Complete listing to retrieve the registry key

Microsoft.Win32.RegistryKey key;
key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Muhil Software");
String s = (String)key.GetValue("Muhil");

OpenSubKey method is used to open the register under {HKEY_CURRENT_USER\Muhil Software}. GetValue method return the object associated with name.

Hash Algorithm

Introduction

Hash Algorithm is one of cryptographic hash functions introduced by the national institute of standards and technology. There are few of secure hash algorithm are SAH1, MD5, SHA256, SHA384 and SHA512.

The hash is used, as a unique value of fixed size representing a large amount of data and the hashes of two sets of data should match if the corresponding data also matches. Small changes to the data result in large.

.Net
In .Net System.Security.Cryptography name-space provides the cryptographic services for secure encoding and decoding of data. It will provide the hashing, random number generation and message authentication.

.Net Framework supports the following hash algorithms.

· SHA1 is the secure hash algorithm (SHA). SHA! Uses 160 bits to encrypt the data
· MD5 is an algorithm gets an input of length and output digested. MD5 uses 128 bits to encrypt the data
· SHA256 is the SHA that uses 256 bits to encrypt the data
· SHA384 is the SHA that uses 384 bits to encrypt the data.
· SHA512 is the SHA that uses 512 bits to encrypt the data

Sha1 is the most widely used for the existing SHA hash functions and widely used for security applications and protocols
SHA1 Hashing Algorithm

System.Security.Cryptography namespace to write in top of using block and SHA1CryptoServiceProvider class is to assign with SHA1 Algorithm to be used

Example
Using System.Secuity.Cryptography;
SHA1 sha;

sha=new SHA1CryptoServiceProvider

ComputeHash method compute the hash value for the specified bytes
ComputeHash(System.Text.Encoding.UTF8.GetBytes("GivenString")

Complete Listing of SHA1 Algorithm
byte[] result = new byte[100];
SHA1 sha;

string FinalStr = "180066666password",sSignature;
sha = new SHA1CryptoServiceProvider();

result = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(FinalStr));

sSignature = Convert.ToBase64String(result);

Create instance of the SHA1CryptoServiceProvider and use Compute Hash to computes the hash value for the specified byte array. Again result converts into base64string method.

Output: K6DLPjiaIvN5JLQFQHaYLcUBAug=

Sunday, July 4, 2010

Bill Gates’ 10 advices to young people

Before retiring in July 2008, Bill Gates gave the following advices to high school students. Who knows you will become a second Bill Gates after learning from these valuable advices?


1. “Life is not fair - get used to it.”
-> The world is never fair. You know this? You can never change the whole world. Injustice still exists in the current society, so you should try to adapt.

2. “The world won't care about your self-esteem. The world will expect you to accomplish something BEFORE you feel good about yourself.”
-> Your extreme self-esteem may make your job inconvenient. Don't attach too much significance on your self-esteem as people care about your achievements rather than it.

3. “You will NOT make 40 thousand dollars a year right out of high school. You won't be a vice president with car phone, until you earn both.”
-> Normally you can't be rich if you have just finished high school. However to become an executive, you need to obtain both: a high school certificate and the money.

4. “If you think your teacher is tough, wait till you get a boss. He doesn't have tenure.”
-> Don’t complain that your boss is tough. When you are at school, your teachers always stand by you whenever you meet problems. However if you have thought that all your problems really come from the hard requirements of your teachers, you shouldn't look for a job. Simply if there aren't strict demands from your company, you will do nothing and quickly become unemployed. Then nobody will give you a hand.

5. “If you mess up, it's not your parents' fault, so don't whine about your mistakes, learn from them.”
-> Don't blame your failure on your destiny. All you need now is to stay calm and start from scratch.

6. “Before you were born, your parents weren't as boring as they are now. They got that way from paying your bills, cleaning your clothes and listening to you talk about how cool you are. So before you save the rain forest from the parasites of your parent's generation, try delousing the closet in your own room.”
-> You should show your gratefulness to your parents for spending most of their lives for your living and growth. All the “outdated” of your parents today is the price they have to pay for your growth.

7. “Your school may have done away with winners and losers, but life may not. In some schools they have abolished failing grades and they'll give you as many times as you want to get the right answer. This doesn't bear the slightest resemblance to ANYTHING in real life.”
-> Keep in mind that you can always become a leader, so that you will have more motivation to strive for your career.

8. “Life is not divided into semesters. You don't get summers off and very few employers are interested in helping you find yourself. Do that on your own time.”
-> Don’t always wait for holidays or you will be left behind your colleagues. That backwardness means elimination and unemployment.

9. “Television is NOT real life. In real life people actually have to leave the coffee shop and go to jobs.”
-> Everybody likes watching TV, but you shouldn't watch it too much. As that actually isn't your life and your thinking will be influenced. You yourself have to determine your own life.

10. “Be nice to nerds. Chances are you'll end up working for one.”
-> You should be nice to everyone. Life has happenings you could never expect. Be open to your boss, don’t say bad things behind his back as it will bring you nowhere.

Friday, June 25, 2010

Embed a True Type Font on your web page.

How to embed a True Type Font on your web page.

You may have an interesting or weird font type that you want on your web page, but in order for other people to be able to see this font you will need to embed it on your web page. Why? Because when a visitor views a web site, the only fonts that will display are those installed on the visitors system!

So if you want either a weird gothic font or an old Celtic font such as in the main logo of my site (which is actually an image) you will need to either display the font in an image or embed the font in your web page.

NOTE:: Although this guide is new it is based on old information. I will try to update it as soon as I have time.


Embedding the font:

To embed a font type on a Web page first select the font you want to embed, either from your hard drive or download it from the Internet.
Then create an embedded font file. And lastly attach the font to your style sheet.
Creating the Embedded File

You need to download software to create an embedded font file which can be in two formats .pfr or .eot.
Portable Font Resources (.pfr):
TrueDoc for Nav 4.0+ and IE 4.0+ on Windows, Mac, and Unix platforms.
Download from http://Bitstream.com


Embeddable Open Type[/b] (.eot):
Compatible only with Explorer 4.0+ on the Windows platform.
Download from http://www.microsoft.com/typography/web/embedding/weft3/default.htm



Next we need to embed the file using CSS.

Into the HEAD section of your document insert:

Example with True Type



To work in IE4 and above, you need to add a pointer to an ActiveX control immediately after the LINK tag OR ELSE create an OpenType file for Explorer and refer to both on your page.

TrueDoc fonts stay within the browser: you can't download them to your system

Example with Open Type




This method works in IE5 & IE6 but is not supported by Firefox/Opera.

Wednesday, March 3, 2010

Windows Workflow Foundation

Windows Workflow Foundation
Workflow is one of the new core capabilities (along with WPF aka Avalon and WCF aka Indigo) being added in the .NET Framework 3.0 release later this year. It provides an in-process workflow engine to process rules, a designer for VS 2005 to enable both developers and non-developers to define custom workflow processes graphically, and a new Workflow namespace to integrate these within code

ASP.NET and Workflows

A workflow built on Windows Workflow Foundation is a component that requires an ad hoc runtime environment to function. The workflow runtime environment is represented by the Workflow Runtime class. To host a workflow library, you create and configure an instance of the Workflow Runtime class to operate on a particular workflow type. For performance reasons, you normally create the runtime environment only once in the application lifetime and make it serves all incoming requests. In a Windows Forms application, you initialize the workflow runtime in the form's constructor and destroy it with the form when the application shuts down. So how does this work if you're using ASP.NET?
Once you have a workflow component up and running, calling it from within a Web app or Windows Forms shouldn't be an issue. As far as Windows Workflow Foundation-based workflows are concerned, ASP.NET developers have only a few small issues to face that are mostly related to the nature of Web applications.
Just like in Windows Forms, with ASP.NET you need to have just one instance of the workflow runtime created when the application starts. Unlike Windows Forms applications, though, a Web application works by accepting and processing requests. Requests are treated individually and don't know anything about each other. That leads to issues related to workflow persistence and threading.

WF (Windows Workflow Foundation) Features:-

· WF (Windows Workflow Foundation) supports sequential or state machine workflows. Sequential workflows usually co-ordinate activities that have a well-defined order and particular business rules and decision-making logic controls the flow between activities. Sequential workflows can contain purely automated processing, or can wait for external input from humans or external system events. State machine workflows allow the workflow to respond to external events that trigger further processing and transitions to other states.

· Developers / programmers use the Workflow Designer mixed with their associated Visual Studio environment to organize activities into a workflow definition that meets business requirements. Business users can review the resulting workflow design to see the implementation and verify that it meets their requirements.

· With use of workflow, complex business rules can be decoupled from application code making them easily to create, change & maintain. The WF (Windows Workflow Foundation) designer offers a way to specify business rules separate from other workflow logic.

· Workflows (WF) can encapsulate details for a complex business process including decision-making logic and business rules that can impact flow of communication, error handling, and compensating activities.

· Developers can easily encapsulate common workflow logic for the business domain into custom activities that can be reused across workflows and hide the complexity of a particular subset of logically related activities. Higher level, domain specific activities can also become building blocks for business analysts to design workflow definitions.

· The state of a long running workflow can be managed and traced with built-in services WF (Windows Workflow Foundation) offers for persistence and tracking.

· Human workflow can be integrated such that different applications and users can act with a particular workflow illustrate at different stages of execution.

Regard
Prateek Bhatnagar

Friday, February 19, 2010

Microsoft .NET Framework 4.0


Microsoft .NET Framework


The Microsoft .NET Framework is a software framework that can be installed on computers running Microsoft Windows operating systems. It includes a large library of coded solutions to common programming problems and a virtual machine that manages the execution of programs written specifically for the framework. The .NET Framework is a Microsoft offering and is intended to be used by most new applications created for the Windows platform.


In this articles we talk about Microsoft .NET Framework 4.0


What’s new in .NET Framework 4.0?


1. Next versions of Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) will provide better support for Web 2.0 technologies like REST, POX, and ATOM.


2. Performance and Scalability of WCF and WF are expected to increase by minimum 10X.


3. New workflow models.


4. Seamless integration between WCF and WF including a new Visual Designer.


5. Parallel Programming framework using PLINQ, Task Parallel Library and Coordination Data Structures to better utilize power of multi-processor and multi-core machines.


6. Build declarative applications with WF, WCF and WPF using XAML. So, XAML is no more only for WPF and WF.


7. WCF enhancements:


1. RESTful enhancements


1. Simplifying the building of REST Singleton & Collection Services, ATOM Feed and Publishing Protocol Services, and HTTP Plain XML Services using WCF


2. WCF REST Starter Kit to be released on Codeplex to get early feedback


2. Messaging enhancements


1. Transports - UDP, MQ, Local in-process


2. Protocols - SOAP over UDP, WS-Discovery, WS-Business Activity, WS-I BP 1.2


3. Duplex durable messaging


3. Correlation enhancements


1. Content and context driven, One-way support


4. Declarative Workflow Services


1. Seamless integration between WF and WCF and unified XAML model


2. Build entire application in XAML, from presentation to data to services to workflow


8. WF enhancements:


1. Significant improvements in performance and scalability


1. Ten-fold improvement in performance


2. New workflow flow-control models and pre-built activities


1. Flowcharts, rules


2. Expanded built-in activities – Power Shell, database, messaging, etc.


3. Enhancements in workflow modeling


1. Persistence control, transaction flow, compensation support, data binding and scoping


2. Rules composable and seamlessly integrated with workflow engine


4. Updated visual designer


1. Easier to use by end-users


2. Easier to rehost by ISVs


3. Ability to debug XAML


 


Regard


Prateek Bhatnagar


Wednesday, February 3, 2010

Upload Image in Database and Display Image

upload images.. first i created a database table with the following columns...

Id --> int (identity column, and primary key)

firstname -->varchar(50)

lastname -->varchar(50)

image -->varchar(50)

and under my web site root directory i have created a folder with name..(images)

here is the code.. to upload the image....



using System.IO;
using System.Data.SqlClient;
using System.Web.Configuration;

protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExt = Path.GetExtension(FileUpload1.FileName).ToLower();
string fileName = Path.GetFileName(FileUpload1.FileName);
string dbfilePath = @"~/images/" + fileName;
if (fileName != string.Empty)
{
try
{
if (fileExt == ".jpg" || fileExt == ".gif")
{
FileUpload1.SaveAs(Server.MapPath(@"~/images/") + fileName);
}
else
{
Response.Write("You can upload only JPG or GIF files...");
}
}
catch (Exception ex)
{
throw ex;
}
}
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("insert into images values(@firstname,@lastname,@image)",con);
cmd.Parameters.AddWithValue("@firstname",TextBox1.Text);
cmd.Parameters.AddWithValue("@lastname",TextBox2.Text);
cmd.Parameters.AddWithValue("@image",dbfilePath);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i > 0)
{
Response.Write("Uploaded");
}
}

}


Display Image in Repeater

his is how you can display the images in Repeater control....

Html...









CodeBehind...
using System.Data.SqlClient;
using System.Web.Configuration;

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from images",con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Repeater1.DataSource = dt;
Repeater1.DataBind();
}

Regard
Prateek