Saturday, November 20, 2010

configuration management database (CMDB)

Hey Guys,

Before sometime writing to this post i was also among you people about what is CMDB, but after doing some research i came to know that it is very helpful for Enterprise Level Applications and Infrastructure projects.

Here i am sharing some basics with you to familiar with CMDB

DEFINITION -
A configuration management database (CMDB) is a database that contains all relevant information about the components of the information system used in an organization's IT services and the relationships between those components. A CMDB provides an organized view of data and a means of examining that data from any desired perspective. Within this context, components of an information system are referred to as configuration items (CI). A CI can be any conceivable IT component, including software, hardware, documentation, and personnel, as well as any combination of them. The processes of configuration management seek to specify, control, and track configuration items and any changes made to them in a comprehensive and systematic fashion.


The IT Infrastructure Library (ITIL) best practices standards include specifications for configuration management. According to ITIL specifications, the four major tasks of configuration management are:

(1)Identification of configuration items to be included in the CMDB
(2)Control of data to ensure that it can only be changed by authorized individuals
(3)Status maintenance, which involves ensuring that current status of any CI is consistently recorded and kept updated
(4)Verification, through audits and reviews of the data to ensure that it is accurate.

Guys i am sharing only basics of what CMDB is and duties it performs. i am sure you will go far than me and explore more...!!!

Happy Coding

C# program that interfaces with MS Access: Store data (text, image) in an Access database file

1. Open a new Visual C# .NET windows application. Name the project CreateDatabase.

2. Design a form. Add three Textboxes and two Buttons

3. Set Name property of Textboxes to “txtDatabase”, “txtStudentName” and “txtStudentPicture”.

4. Set Name property of Buttons to “btnCreateTable” with text property “Create Table” and “btnSave” with text property “Save”.

5. In the code file add namespace:

using System.Text;

using System.Data.OleDb;

6. Double click on the Button “Create Table” and pest the following code into the “btnCreateTable_Click” event.



OleDbCommand Cmd;
string SQL = "";
OleDbCommand objCmd = new OleDbCommand();

OleDbConnection Con = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;data
source=" + txtDatabase.Text + "");

SQL = "CREATE
TABLE tblStudentInfo ([StudentID] COUNTER, [StudentName] TEXT(50), [Picture]
OLEObject)";
Cmd = new
OleDbCommand(SQL, Con);

Con.Open();
objCmd = new OleDbCommand(SQL,
Con);

objCmd.ExecuteNonQuery();
Con.Close();
7. Double click on the Button “btnSave” and pest the following code into the “btnSave_Click” event.

StoreData(ImageToStream(txtStudentPicture.Text));
8. Add the following modules to the code file.

private byte[] ImageToStream(string fileName)

{
Bitmap image = new Bitmap(fileName);
MemoryStream stream = new
MemoryStream();

image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
return stream.ToArray();
}

private void
StoreData(byte[] content)
{

OleDbConnection
conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;data source="
+ txtDatabase.Text + "");

conn.Open();

if (conn.State.Equals(ConnectionState.Closed))

conn.Open();
try
{
OleDbCommand insert = new OleDbCommand("Insert into tblStudentInfo (StudentName,Picture)
values(@StudentName,@image)", conn);

OleDbParameter
picParameter = insert.Parameters.Add("@StudentName",
OleDbType.VarChar );

picParameter.Value = txtStudentName.Text;

picParameter.Size = 50;
OleDbParameter
imageParameter = insert.Parameters.Add("@image", SqlDbType.Binary);

imageParameter.Value = content;

imageParameter.Size = content.Length;

insert.ExecuteNonQuery();
MessageBox.Show("Data
Stored successfully");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
MessageBox.Show(ex.StackTrace.ToString());
}
finally
{

conn.Close();
}
}
9. Press F5 to build and run the project.

Put your database name with location like c:\MyAccessDB in the text box “txtDatabase”, put student name in the text box “txtStudentName” and put student picture path in the text box “txtStudentPicture” then press the “Create Table” Button and after that press “Save” button to save the student information to the database table.

Saturday, March 20, 2010

Solution to search suggestions with permutition

Hi All,

In one of requirement i need to show the all possible combinitation of text provided in input to show possible search suggestions, i started thinking like school student of permutition and i found the solution, here is my code i have solved with Javascript

permute = function(v, m){ //v1.0
for(var p = -1, j, k, f, r, l = v.length, q = 1, i = l + 1; --i; q *= i);
for(x = [new Array(l), new Array(l), new Array(l), new Array(l)], j = q, k = l + 1, i = -1;
++i < l; x[2][i] = i, x[1][i] = x[0][i] = j /= --k);
for(r = new Array(q); ++p < q;)
for(r[p] = new Array(l), i = -1; ++i < l; !--x[1][i] && (x[1][i] = x[0][i],
x[2][i] = (x[2][i] + 1) % l), r[p][i] = m ? x[3][i] : v[x[3][i]])
for(x[3][i] = x[2][i], f = 0; !f; f = !f)
for(j = i; j; x[3][--j] == x[2][i] && (x[3][i] = x[2][i] = (x[2][i] + 1) % l, f = 1));
return r;
};

function callPermute()
{
var a = ["A","B","C"], j = permute(a);
document.write("< h2 >", a.join(" "), " = ", j.length, "< /h2 >",j.join("< br / >"));
}

you can call the method callPermute() to show the require result

Happy Coding :)

Sunday, January 31, 2010

AssociatedControlID of Asp.Label control in Asp.net

Hi All,

Today i have found one interesting part of Asp.Net Label control. Label server control have one property AssociatedControlID.

Problem : without asssigning the AssociatedControlID property a Asp.net Label server control rendered as "span" which is not satisfied the client requirement of 'it should render as label for accessibility'

Here is the output before and after,

Before,

span id="form_103_lblFirst_Name">First Name /span

Assigned "AssociatedControlID" property and Result after,

  123 lblTitle.AssociatedControlID = txtName.ID;



label id="form_103_lblFirst_Name" for="form_103_First_Name">First Name /label

Solution : I have assigned the AssociatedControlID to the Asp.net Label server control to the textbox.ID to which it refering to. and found that it is rendered to "label" html tag which i required it also includes 'for' property which references the ID of Associated Control.

Happy Coding :)

Wednesday, January 27, 2010

New keyword 'dynamic' in framework 4.0,Difference between var and dynamic/ object and dynamic.

Hi All,

C# 4.0 introduces a new keyword called 'Dynamic'. It can consume any object anything. Let's see some examples for that.


dynamic intExample = 1;
Console.Write(intExample);

dynamic floatExample = 3.6;
Console.Write(floatExample);

dynamic stringExample = "SharpFour";
Console.Write(stringExample);


will print 13.6SharpFour

I know you will all have one question in mind that,It could be also done with var keyword . Yes, you can do same thing with var but dynamic keyword is slightly different then var keyword.

Main Diffrence between var and dynamic :

var keyword will know the value assigned to it at compile time while dynamic keyword will resolve value assigned to it at run time. I know you guys don't believe me without example. So let's take example of string.

string s = "this is test string";
var varstring=s;
Console.Write(varstring.MyMethodCall());


while compiling above code it will not compile and it gives a error that 'string' does not contain a definition for 'MethodDoesnotExist' and no extension method 'MethodDoesnotExist' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?'. So var keyword knows that what value or object or anything assigned to it. Now lets try to compile same code with dynamic example like following.


string s = "this is test string";
dynamic varstring=s;
Console.Write(varstring.MyMethodCall());


Above line of code get compile. So it is the difference between dynamic and var keyword. With dynamic keyword anything assigned to it like property,objects operators anything that will be determined at compile time. It can be useful while we are doing programming with com,JavaScript which can have runtime properties.

similar thing is applied to the keyword type 'object'. we will discuss more on 'dynamic' keyword and 'object' keyword in my next post.

Happy Coding :-)

Sunday, January 24, 2010

Variable Methods and use of "params" in C#.

Hi All,

Recently in one of my requirements i require do make some method which will accepts n numbers of parameters, here i am not sure howmany parameters as argument will required.

I come up with solution with "params" keyword. below is a sample example of how i am able to solve it,i have used the console application to show how the "params" keyword will be used.



    6 public static void Main()


    7     {


    8         Console.Clear();


    9         Console.WriteLine("Hello World");


   10         Console.ReadLine();


   11         paramsExample(" vikas", 10, 11, " Aks");


   12     }


   13     public static void paramsExample(params object[] arglist)


   14     {


   15         foreach (object obj in arglist)


   16         {


   17             Console.Write("Hi{0}", obj);


   18         }


   19     }





The output of the above code will simply shows the,

"Hi vikas", "Hi 10","Hi 11","Hi Aks".

Hope you could be easily understand the code and use of "params" keyword.

Happy Coding :)

Sunday, January 17, 2010

Handling Exceptions in Using Expression Tree in C#

Hi All,

In my previous post i have explained how we can work with Expression Tree to access the Properties easily. The major consideration which we have to take here using Lambda Expressions is Expressions are failed if inputs are given wrong.

So here with this post i come up with the solution of Manage possible Exceptions, I have made some corrections in my previous post method named "GetName".

    8 public static string GetName<T>(Expression<Func<T>> e)

    9 {

   10     var member = e.Body as MemberExpression;

   11 

   12     // If the method gets a lambda expression

   13     // that is not a member access,

   14     // for example, () => FirstName + LastName, an exception is thrown.

   15     if (member != null)

   16         return member.Member.Name;

   17     else

   18         throw new ArgumentException(

   19             "'" + e +

   20             "': is not a valid expression for this method");

   21 }



Now code looks safer to show proper exception whenever wrong inputs are given to it.

Happy Coding :)

Using Expression Tree in C#

Hi All,

In my previous post i have explained the solution how to work around the Reflections to access the Property of class object. By analyzing code with different scenario my solution of Reflections get fails in case of ProeprtyName changed ( i.e suppose your User class previous have Surname afterword changed it with Lastname).

By digging more features availabes in .net framework i come up with the solution of using the Expression Tree instead of Reflections.

The Expression Tree classes are implemented in System.Query.dll and their namespace System.Linq.Expressions(might be change as product matures).

So say for example below is my sample class, with two property "FirstName" and "LastName"

    8 public class ExpressionTest

    9 {

   10     public string FirstName { get; set; }

   11     public string LastName { get; set; }

   12 }



and i want to show the name of property in my console application, so before that i will introduce the Expression Tree usage in this scenerio,

   13 public static string GetName<T>(Expression<Func<T>> e)

   14     {

   15         var member = (MemberExpression)e.Body;

   16         return member.Member.Name;

   17     }



Now to call this method and get the names of class properties we defined above we can call the Lambda Expression as given,

   18 ExpressionTest testsample = new ExpressionTest();

   19     Console.WriteLine("{0}", GetName(() => testsample.FirstName));

   20     // prints FirstName



So here is area of interest is utilization of Expression Tree classes with help of C# 3.0 onwards.

Happy Coding :)

Monday, January 11, 2010

Using Reflection to Access the Properties

Hi All,

In one of my coding requirement i need to map database fields to fields which user have been created self. I think a bit more on this and come with finally solution get gain of Reflection for fulfilling the requirement.

Here is how i get the list of Properties which i can map easily to User table to database, i used the GetProperties() method to achieve this things, then i do the Sorting on them to show in Sorted order, below is code snippet for this,

   39 User objUser = new User();

   40         Type t = objUser.GetType();

   41         PropertyInfo[] pi = t.GetProperties();

   42         Array.Sort(pi,

   43         delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)

   44         { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });

   45 

   46         UserProperties = new List<string>();

   47         foreach (MemberInfo mi in pi)

   48         {

   49             UserProperties.Add(mi.Name);

   50         }



here User is my class which contains the properties of "User" table in database.

Reflections provides vast collections of Methods which we can utilize to access within code.

Happy Coding :)

Friday, January 8, 2010

Open Source solution for Code Analysis in VS 2008

Hi All,

Microsoft Visual Studio Team System 2008 provides the inbuilt functionality with Code Matrices. Considering the cost factor VSTS-2008 is not affordable to developers like me, so i started to finding the some good tool which fulfill my requirement with no cost.

I found one nice application developed by Campwood Software named Source Monitor.

http://www.campwoodsw.com

Positive Points :

-Supports C++, C, C#, VB.NET, Java, Delphi, Visual Basic (VB6) or HTML.
-Displays and prints metrics in tables and charts
-Saves metrics in checkpoints for comparison during software development projects
-Exports metrics to XML or CSV files for further processing with other tools

Using this one can verify their own self the depth and quality of source written.

Hope this would help who looking for Code Analysis, Matrices.

Happy Coding :)

Thursday, January 7, 2010

Composite Controls and Compare Validator control

Hi All,

While working with Asp.net validators for Custom controls i have found one issue of Microsoft ASP.NET validations controls.

Problem : I need to validate one composite control with value of other composite control/ Web control. I decided to go with CompareValidator control provided by ASP.NET default. Problem comes on ControlTovalidate and ControlToCompare properties, i assigned this properties as usual, here i assigned email.ID(where email is my composite control object).

By doing this i got the error like following,

"Control 'Contact_Email' referenced by the ControlToCompare property of 'cvContact_Email' cannot be validated."

Solution : By spending many hours finally i come out with solution to this. to achieve goal we need to require expose one public property of that Control's Child control( Textbox in my case). Now and on page you can assign UniqueId property to ControlToCompare property.

Here is code snippet for same,
cvConfirm is a CompareValidator object which i am creating runtime,

  276 cvConfirm.ControlToValidate = txtconfirm.UniqueID;

  277                                 cvConfirm.ControlToCompare = email.Refemailbox.UniqueID;



Here is a property which i have exposed within composite control,

   73 /// <summary>

   74         /// Gets the reference of this control.

   75         /// </summary>

   76         /// <value>The refemailbox.</value>

   77         [Bindable(true)]

   78         [Category("Appearance")]

   79         [DefaultValue("")]

   80         [Localizable(true)]       

   81         public TextBox Refemailbox

   82         {

   83             get

   84             {

   85                 EnsureChildControls();

   86                 return this._emailTextBox;

   87             }           

   88         }



I hope this would help those who faced same situation.

Happy Coding :)