A Developer Journey who codes for fun

Daily Dose Of Code

  • Home
  • Dot.Net Basics
    • .Net Basics
      • CTS
      • CLS
      • CLR
      • Strong Vs Weak Ref
      • .Net Framework
      • What is Manifest
    • Memory Management
      • Garbage Collection 1
      • Garbage Collection 2
      • Circular Reference
  • C Sharp
    • Abstract Class in C#
    • Interfaces in C#
    • Value type by Val and By Ref
    • Var keyword
    • Null Coalescing Operator
    • Buit-in code snippets
  • OOPS
    • Abstraction and Encapsulation
    • Polymorphism
    • Inheritence
    • Aggregation
  • Threading
    • Delegates
      • Calling Delegate using Invoke, BeginInvoke
      • Multicast Delegate
      • Exception Handling in Multicast Delegate
      • Action
      • Predicate
      • Func
    • Synchronization
    • Thread Pool
    • Exception Handling
    • TPL
  • Design Pattern
    • Creational Patterns
      • Singleton Pattern
      • Factory Pattern
      • Abstract Factory Pattern
      • Prototype Pattern
      • Builder Pattern
    • Structural Patterns
      • Adapter Pattern
      • Bridge Pattern
      • Composite Pattern
      • Proxy Pattern
      • Facade Pattern
      • Decorator Pattern
      • Flyweight Pattern
    • Behavioral Patterns
      • Command Pattern
      • Interpreter Pattern
      • Iterator Pattern
      • Mediator Pattern
      • Memento Pattern
      • Observer Pattern
      • State Pattern
      • Strategy Pattern
      • Visitor Pattern
      • Chain Of Responsibility Pattern
      • Template Pattern
  • Data Structures
    • Generic List in C#
    • 2d array to 1d array
    • 3d arrayto 1d array
    • Linked List
      • Singly Linked List in C#
    • Queue
      • Dummy Data 1
    • Stack
      • Dummy Data 2
    • Tree
      • Dummy Data 3
    • Graph
      • Dummy Data 4
  • WCF
    • WCF Service using VS 2015
  • Scripts
    • Chrome Extensions
      • Create a Chrome Extension
      • Facebook autologout script
      • Gmail autologout script

Window Controls in ASP.Net

 Unknown     3:12 AM     No comments   

Controls:-----------
Most controls in .NET derive from the System.Windows.Forms.Control class. This class defines the basic functionality of the controls, which is why many properties and events in the controls we'll see are identical. Many of these classes are themselves base classes for other controls, as is the case with the Label and TextBoxBase classes:--


Some controls, named custom or user controls, derive from another class: System.Windows.Forms.UserControl. This class is itself derived from the Control class and provides the functionality we need to create controls ourselves. We'll cover this class in Chapter 14. Incidentally, controls used for designing Web user interfaces derive from yet another class, System.Web.UI.Control.

Properties

All controls have a number of properties that are used to manipulate the behavior of the control. The base class of most controls, Control, has a number of properties that other controls either inherit directly or override to provide some kind of custom behavior.

The table below shows some of the most common properties of the Control class. These properties will be present in most of the controls we'll visit in this chapter, and they will therefore, not be explained in detail again, unless the behavior of the properties is changed for the control in question. Note that this table is not meant to be exhaustive; if you want to see all f the properties in the class, please refer to the MSDN library:

Name Availability Description

Anchor Read/Write Using this property, you can specify how the control

behaves when its container is resized. See below for a detailed explanation of this property.

BackColor Read/Write The background color of a control.

Bottom Read/Write By setting this property, you specify the distance

from the top of the window to the bottom of the control. This is not the same as specifying the height of the control.

Dock Read/Write Allows you to make a control dock to the edges of a

window. See below for a more detailed explanation of this property.

Enabled Read/Write Setting Enabled to true usually means that the control

can receive input from the user. Setting Enabled to false usually means that it cannot.

ForeColor Read/Write The foreground color of the control.

Height Read/Write The distance from the top to the bottom of the control.

Left Read/Write The left edge of the control relative to the left

edge of the window.

Name Read/Write The name of the control. This name can be used to reference the control in code.

Parent Read/Write The parent of the control.

Right Read/Write The right edge of the control relative to the left

edge of the window.

TabIndex Read/Write The number the control has in the tab order of its container.

TabStop Read/Write Specifies whether the control can be accessed by the Tab key.

Tag Read/Write This value is usually not used by the control itself,

and is there for you to store information about the control on the control itself. When this property is assigned a value through the Windows Form designer, you can only assign a string to it.

Top Read/Write The top edge of the control relative to the top of the window.

Visible Read/Write Specifies whether or not the control is visible
at runtime.

Width Read/Write The width of the control.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

An Example to create an UserControl to create a checklist box and how to set default check in ASP.Net Using C#

 Unknown     2:48 AM     No comments   

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace MatrixControl
{
public partial class M42CheckBoxControl : UserControl
{
private static int index = 0;

public M42CheckBoxControl()
{
InitializeComponent();
}
# region Properties
///
/// These are the properties value contains the text string seperated by the seperator
///

private string _value;
public string Value
{
set
{
_value = value;
}
}
///
/// Seperator is also a string by which we will parse the text string.
///

private string _seperator;
public string Seperator
{

set
{
_seperator = value;
}
}
///
/// This is default value means which checkbox will be checked by default.
///

private string _default;
public string Default
{
set
{
_default = value;
}
}

# endregion

#region private

///
/// This event will fire when checkBox will checked or unchecked.
///

///
///
private void checkedListBox1_SelectedValueChanged(object sender, EventArgs e)
{
//Creates an array of strings upto the number of check boxes avaliable in check box list.

string[] checkedItems = new string[M42CheckedListBox.CheckedItems.Count];

foreach (object objchecked in M42CheckedListBox.CheckedItems)
{
checkedItems[M42CheckedListBox.CheckedItems.IndexOf(objchecked)] = objchecked.ToString();
}
//This join method string.Join(_seperator, collectionOfCheckedItems) will give the selected items.
this.Description.Text= string.Join(_seperator, checkedItems);
}

# endregion

#region public
///
/// This check box option is firstly parse all the values and defaults then store iot in check
/// list boxes and text.
///


public void CheckBoxOption()
{
index = 0;
//This is to split through seperator
string[] parseString = _value.Split(_seperator.ToCharArray());
//thisd is to split the defailt value through seperator
string[] defaultString = _default.Split(_seperator.ToCharArray());
//this default description string array is just to store all the default values.
string[] defaultDescription = new string[defaultString.Length];

//This for loop is just to find the index of default value and create the check boxes.
if (_value != string.Empty)
{
foreach (string value in parseString)
{
if (M42CheckedListBox.Items.Contains(value))
{
}
else
{
M42CheckedListBox.Items.Add(value);
}
}
foreach (string defaultValue in defaultString)
{
if (M42CheckedListBox.Items.Contains(defaultValue))
{
M42CheckedListBox.SetItemCheckState(M42CheckedListBox.Items.IndexOf(defaultValue), CheckState.Checked);
defaultDescription[index++] = (defaultValue);
}
this.Description.Text = string.Join(_seperator, defaultDescription);
}
}
}

# endregion

}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to Send data from a User Control to another user control on a single form using Events and Delegates:--

 Unknown     2:40 AM     No comments   

This is an example how to create Dynamic Check Boxes and how to communicate betwwen two user controls on a sigle form using Events and Delegates.
In this application I have to send some data from control2 to control1 on a single button click.So for this i have used event and Delegates.

Have A look.
//Control2:----
namespace ParserF
{
public partial class Control2 : UserControl
{
public ArrayList CheckBoxName = new ArrayList();
public char[] seperator = new char[5];
static int count = 0, indexing=0;
public delegate void PassSelectedValues(ArrayList CheckBoxName, int countDefault);
public event PassSelectedValues DataSelected;
public int Flag = 0;

public Control2()
{
InitializeComponent();
}

# region Properties
///
/// These are the properties value contains the text string seperated by the seperator
///

private string _Value;
public string Value
{
get
{
return _Value;
}
set
{
_Value = value;
}
}
///
/// Seperator is also a string by which we will parse the text string.
///

private string _Seperator;
public string Seperator
{
get
{
return _Seperator;
}
set
{
_Seperator = value;
}

}
///
/// This is default value means which checkbox will be checked by default.
///

private string _Default;
public string Default
{
get
{
return _Default;
}
set
{
_Default = value;
}
}

# endregion

# region private

///
/// This function is just when we will click on Ok button then all the data will be sent to control1
/// by delegate public delegate void PassSelectedValues(ArrayList CheckBoxName, int ind);
/// and event public event PassSelectedValues DataSelected; In this function i m taking a string Builder
/// Temporary String in that we will store the string after parsing through seperator and then store it in a arraylist.
///
///

///
///
private void OkButton_Click(object sender, EventArgs e)
{
StringBuilder TemporaryString = new StringBuilder();

InitializaValues();
//This if codition will check that value (Text String) contains default or not .If yes the continue otherwise will make a messagebox.
if (Value.Contains(Default))
{
for (int index = 0; index < Seperator.Length; index++)
{
seperator[index] = Seperator[index];
}
//This for loop is just to extract strings upto the length of the value
for (; (indexing < Value.Length); indexing++)
{
if (Value[indexing] != seperator[0])
{
TemporaryString.Append(Value[indexing]);
}
else
{
if (Flag == 0)
{
count++;
}
String str = TemporaryString.ToString();
//This if condition is just to comapare default one and store the index.
if (!System.Convert.ToBoolean((str.CompareTo(Default))))
{
Flag = count;
count = 0;
}

//This will add the string to the array list
CheckBoxName.Add(str);
//This will replace the string Builder Temporary String to Empty One.
TemporaryString.Replace(str, String.Empty);
}
}
if ((indexing == Value.Length)&&(Flag==0))
{
Flag = (count+1);
}
String str1 = TemporaryString.ToString();
CheckBoxName.Add(str1);
//DataSelected is the event which will fire by this we are sending the arraylist and the index for defaultCheck
DataSelected(CheckBoxName, Flag-1);
}
else
{
MessageBox.Show("No focus set due to No string matches from TextString");
}
}
///
/// This is just to Inotialize values to the text boxes.
///

private void InitializaValues()
{
Value = ValueTextBox.Text;
Seperator = SeperatorTextBox.Text;
Default = DefaultTextBox.Text;
}

# endregion
}
}

//Control1:---

namespace ParserF
{
public partial class Control1 : UserControl
{

public Control1()
{
InitializeComponent();
}
public int flag1;
ArrayList Array1 = new ArrayList();
static int index2 = 0;

public ArrayList SelectedCheckBox
{

set
{
Array1 = value;
}

}
public int indexing
{

set
{
flag1 = value;
}

}

public void AddCheckBox()
{
for (int index = 0; index < Array1.Count; index++)
{
CheckBox checkBox = new CheckBox();
checkBox.AutoSize = true;
checkBox.Location = new Point((28), (27 + index2));

checkBox.Size = new System.Drawing.Size(80, 17);
checkBox.Text = Array1[index].ToString();
if (index == flag1)
{
checkBox.Checked = true;
}
if (checkBox.Checked)
{
textBox1.Text = checkBox.Text;
}
checkBox.UseVisualStyleBackColor = true;
index2 += 20;
Controls.Add(checkBox);
checkBox.CheckedChanged += new EventHandler(checkBox_CheckedChanged);

}
}
///
/// This is an event which will fire when a user will check the check Box
///

///
///
private void checkBox_CheckedChanged(object sender, System.EventArgs e)
{
if (((CheckBox)sender).Checked == true)
{
if (textBox1.Text == string.Empty)
{
textBox1.Text = ((CheckBox)sender).Text;
}
else
{
textBox1.AppendText(",");
textBox1.AppendText(((CheckBox)sender).Text);
}
}
else if (textBox1.Text == ((CheckBox)sender).Text)
{
textBox1.Text = string.Empty;
}
else
{
int FirstIndex=textBox1.Text.IndexOf(((CheckBox)sender).Text);
int length=((CheckBox)sender).Text.Length;
string str1=textBox1.Text.Remove(FirstIndex, length);
textBox1.Text = str1;
}
}

private void Control1_Load(object sender, EventArgs e)
{

}

private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{

}
}
}

//Form1.cs

namespace ParserF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
control21.DataSelected += new Control2.PassSelectedValues(passValuesHandlerMethod);
}
protected void passValuesHandlerMethod(ArrayList CheckBoxName, int flag2)
{
control11.SelectedCheckBox = CheckBoxName;
control11.flag1 = flag2;
control11.AddCheckBox();
}
private void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e)
{

}

private void control21_Load(object sender, EventArgs e)
{

}

private void control11_Load_1(object sender, EventArgs e)
{

}

}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Nagarro Placement Papers..

 Unknown     6:46 AM     37 comments   

Ques.1 :- Seat Reservation prog for the theatre. Write a function for seat allocation for the movie tickets. Total no of seats available are 200. 20 in each row. Each row is referred by the Character, "A" for the first row and 'J' for the last. And each seat in a row is represented by the no. 1-20. So seat in diffrent rows would be represented as A1,A2....;B1,B2.....;........J1,J2... Each cell in the table represent either 0 or 1. 0 rep would seat is available , 1 would represent seat is reserved. Booking should start from the last row (J) to the first row(A). At the max 20 seats can be booked at a time. if seats are available, then print all the seat nos like "B2" i.e (2 row, 3 col) otherwise Print "Seats are not available." and we must book consecutive seats only.

Ques.2 :- A string of charaters were given. Find the highest occurance of a character and display that character.
eg.: INPUT: AEGBCNAVNEETGUPTAEDAGPE
OUTPUT: E
Ques.3 :- Int Matrix of certain size was given, We had few values in it like this.
1 4 5 45
3 3 5 4
34 3 3 12
3 3 4 3
3 3
4 4 3
We were supposed to move back all the spaces in it at the end.
Note: If implemented this prog using recursion, would get higher preference.


Ques.4 :- write a function to give demostrate the functionality of 3D matrix in 1D matirx.
function prototype :-
void set (int value,int indexX,int indexY,int indexZ, int [] 1dArray);
void get (int value,int indexX,int indexY,int indexZ, int [] 1dArray);


Ques.5 :- A chessboard was given to us. Where in there was a Knight and King was placed on certain positions. Our aim is to reach the king from the knight in minimum no of counts.As we know, knight can either move 2 steps vertical/horizontal and 1 step horizontal/vertical. same goes here as well.
Proper image of the chess board was given in the question paper, and all the positions(max 8) were given that knight can take in the first step.

Sol : I've implemented using recursive func.I was appreciated by the interviewer.They will ask for the dry run becz there was 8 recursions.So Be prepare.

Ques.6 :-
Struct person
{
char * name;
person[] friends;
};
We were given the networklist of friends. Each has set of friends which was unidirectional i.e, if you are my frnd, then i may or may not be in ur frnds list. okie. Network was like this:
Amit - ->Rahul -> Aman -> kumar
Rahul- ->Vipin->Ankit->Reena->kumar
Kumar- ->Rahul->Reena->Tanmay

We need to identify whether 1st person being passed is a frnd of another person or not. Frnds can be frnd's friend also and so on. And we need to identify the distance.
For example :-
Input: Amit, Kumar
Output Distance 1
Input Amit, Tanmay
Output: Distance 2
Input: Rahul, Aman
Not frnds.

Ques.7 :- There was a 2D matrix given, we were supposed to sort the all diagnols elements. diagnols of Top left corner and Top right corner were to be sorted in the same matrix in an efficient way.

Ques.8 :- We need to write the function to check the password entered is correct or not based on the
following conditions..
a) It must have atleast one lower case character and one digit.
b)It must not have any Upper case characters and any special characters
c) length should be b/w 5-12.
d) It should not have any same immediate patterns like

abcanan1 : not acceptable coz of an an pattern
abc11se: not acceptable, coz of pattern 11
123sd123 : acceptable, as not immediate pattern
adfasdsdf : not acceptable, as no digits
Aasdfasd12: not acceptable, as have uppercase character

Ques.9 :- Wrie a function which returns the most frequent number in a list of integers. Handle the case of more than one number which meets this criterion.

public static int[] GetFrequency(int[] list)

Ques:10 :- Counting in Lojban, an artificial language developed over the last fourty years, is easier than in most
languages
The numbers from zero to nine are:
0 no
1 pa
2 re
3 ci
4 vo
5 mk
6 xa
7 ze
8 bi
9 so
Larger numbers are created by gluing the digit togather.
For Examle 123 is pareci

Write a program that reads in a lojban string(representing a no less than or equal to 1,000,000) and output it in numbers.

Ques.11 :- Where now stands that small knot of villages known as the Endians, a mighty forest once stood.Indeed, legand has it that you could have stoodon the edge of the wood and seen it stretch out for miles,were it not for the trees getting in the way.
In one section of the forest, the trees stood in a row and were of hight from 1 to n, each hight occurring once and once only.

Like:--
A tree was only visible if there were no higher trees before it in the row.
For example, if the heights were 324165, the only visible trees would have been those of height 3,4 &6.

Ques:12 :- Given an array containing k nos in the range 1..n and another scratch array of size n. Write an program to remove the duplicates from the array.

Written Test Pattern:--
The written exam consisted of 25 general maths questions on trigonometry, circles, area, perimeter,mensuration, time, work, distance etc ques.
and aptitude consisted of 10 ques with several parts. they wer twisty ques including the puzzle test ques
given in R.S.Aggarwal verbal-nonverbal book....
The second written exam included 4 coding ques which wer to be written in any programming languages .It was something like this:
Instructions:
1.The code should emphasize on min time and then min memory requirements.
2.The time limit was 1hr 30min.

Ques1: Given an array containing k nos in the range 1..n and another scratch array of size n. Write an program to remove the duplicates from the array.

Ques2: Given a table of the form:
Product Sold on
A 1/1/1980
B 1/1/1980
C 1/1/1980
A 1/1/1980
B 1/1/1980
C 2/1/1980
A 2/1/1980
There are 30 products and 10,000 records of such type. Also the month period during which sales happened is given to u.
Write the program to display the result as:
Product Month No. of copies
A January 12
A February 15
A March 27
B January 54
B February 15
B March 10
C January 37


Ques3: Definition of priority queue was given. We have to implement the priority queue using array of pointers with the priorities given in the range 1..n.
The array could be accessed using the variable top. The list corresponding to the array elements contains the items having the priority as the array index.
Adding an item would require changing the value of top if it has higher priority than top. Extracting an item would require deleting the first element from the corresponding queue.
The following class was given:
class PriorityQueue
{
int *Data[100];
int top;
public:
void put(int item, int priority); // inserts the item with the given priority.
int get(int priority); // extract the element with the given priority.
int count(); // returns the total elements in the priority queue.
int isEmpty(); // check whether the priority queue is empty or not.
};
We had to implement all these class functions.


Ques4: An array of size 5X5 is given to us. The elements from 1 to 25 are to be inserted in the array, such that starting from a particular position for an element i, the next element i+1can be inserted only at the mentioned positions (u,v), and if these all positions are occupied then it returns giving a count of how many positions have been occupied in the array:

(u,v) = (x+/-3 , y)
(u,v) = (x , y+/-3)
(u,v) = (x+/-2 , y+/-2).

Example: if the starting element is 1 with the given positions (1,2), then next element 2 can be placed at
any one of the positions marked with *.
_ _ _ _ _
1 _ _ _ *
_ _ _ _ _
_ _ * _ _
* _ _ _ _
Function to be implemented is fun(int start, int end) where start and end will give the start and end coordinate of first element i.e.


Ques.5 :- suppose u r given a 4*3 rectangle like (take these values from user)
Now u have to calculate the no. of squares in this rectangle like:
No. of squares of dimension 1 is 12
No. of squares of dimension 2 is 6
No. of squares of dimension 3 is 2
No. of squares of dimension 4 is 0
Total no. of squares are 20.

b) Suppose you are given a string. you have to find the occurance of the characters A-Z in that string.Each character must appear in the string and must appear only once. If It that occurs in string more than one time return 1 showing it is a perfect string otherwise return 0 showing it is not a perfect string.

c) Suppose you arr given 10000 marks. you have to pick up top 20 top marks from them and display it on the screen.(Use the optimal sorting algorithm)

d) Suppose you have a chess board. you have to insert 8 queens on the chessboard in the style that the queens don’t intersect in the diagonals, columns and rows. If they intersect return 1 else return 0.(that is no more than one queen should be present either in row or column or diagonals.)
If the queen is inserted at a position in the chessboard, its count is 1.

Then the next round was technical interview. The interviewer was very cool and friendly. He just asked some general questions and then u have to justify the code that u have written in the test line by line. If he is satisfied from ur code then HR interview is only a formality.

Ques.1 :- A Class Structure was given with function names only.
Using one dimensional array make the fuctionality of two dimensional array?
We have to write the function body and the main program which calls them.
the function attributes and return type was given.
some already defined variables were also there.

Ques.2 :- If employee B is the boss of A and C is the boss of B and D is the boss of C and E is the boss of D. Then write a program using the Database such that if an employee name is Asked to Display it also display his bosses with his name.
For eg. If C is displayed it should also display D and E with C?

Ques.3 :- Arrange Doubly linked list in the ascending order of its integral value and replace integer 5 with 7?

Ques.4 :- Three tables were given and we had to link them.


Ques.5 :- You have given a string containing a binary number and you have to calculate the decimal number from it.

Ques.6 :- It was the password validation question mentioned above.

Ques.7 :- You have given two list of names containing name first list is very large and second one is very small, Now you have to conclude whether names appers in the second list are in same order as in the frist or not.
Example :
First: Ram, Mohan, Babu, Shyam, Komal, Rani, Sita
Second: Mohan, Komal, Sita.
Ans : yes.

Questions Asked on 31 May 2008:
Ques.1 :- Subset sum problem.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

C Aptitude Questions...

 Unknown     6:31 AM     No comments   

C Questions Check Your Ability In C

Note : All the programs are tested under Turbo C/C++ compilers.
It is assumed that,
 Programs run under DOS environment,
 The underlying machine is an x86 system,
 Program is compiled using Turbo C/C++ compiler.
The program output may depend on the information based on this assumptions (for example sizeof(int) == 2 may be assumed).

Predict the output or error(s) for the following:

1. void main()
{
int const * p=5;
printf("%d",++(*p));
}
Answer:
Compiler error: Cannot modify a constant value.
Explanation:
p is a pointer to a "constant integer". But we tried to change the value of the "constant integer".

2. main()
{
char s[ ]="man";
int i;
for(i=0;s[ i ];i++)
printf("\n%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);
}
Answer:
mmmm
aaaa
nnnn
Explanation:
s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally array name is the base address for that array. Here s is the base address. i is the index number/displacement from the base address. So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i].

3. main()
{
float me = 1.1;
double you = 1.1;
if(me==you)
printf("I love U");
else
printf("I hate U");
}
Answer: I hate U
Explanation:
For floating point numbers (float, double, long double) the values cannot be predicted exactly. Depending on the number of bytes, the precession with of the value represented varies. Float takes 4 bytes and long double takes 10 bytes. So float stores 0.9 with less precision than long double.
Rule of Thumb:
Never compare or at-least be cautious when using floating point numbers with relational operators (== , >, <, <=, >=,!= ) .

4. main()
{
static int var = 5;
printf("%d ",var--);
if(var)
main();
}
Answer: 5 4 3 2 1

Explanation:
When static storage class is given, it is initialized once. The change in the value of a static variable is retained even between the function calls. Main is also treated like any other ordinary function, which can be called recursively.

5. main()
{
int c[ ]={2.8,3.4,4,6.7,5};
int j,*p=c,*q=c;
for(j=0;j<5;j++)
{
printf(" %d ",*c);
++q;
}
for(j=0;j<5;j++)
{
printf(" %d ",*p);
++p;
}
}

Answer: 2 2 2 2 2 2 3 4 6 5
Explanation:
Initially pointer c is assigned to both p and q. In the first loop, since only q is incremented and not c , the value 2 will be printed 5 times. In second loop p itself is incremented. So the values 2 3 4 6 5 will be printed.


6. main()
{
extern int i;
i=20;
printf("%d",i);
}

Answer: Linker Error : Undefined symbol '_i'
Explanation:
extern storage class in the following declaration,
extern int i; specifies to the compiler that the memory for i is allocated in some other program and that address will be given to the current program at the time of linking. But linker finds that no other variable of name i is available in any other program with memory space allocated for it. Hence a linker error has occurred .

7. main()
{
int i=-1,j=-1,k=0,l=2,m;
m=i++&&j++&&k++||l++;
printf("%d %d %d %d %d",i,j,k,l,m);
}
Answer: 0 0 1 3 1
Explanation :
Logical operations always give a result of 1 or 0 . And also the logical AND (&&) operator has higher priority over the logical OR (||) operator. So the expression ‘i++ && j++ && k++’ is executed first. The result of this expression is 0 (-1 && -1 && 0 = 0). Now the expression is 0 || 2 which evaluates to 1 (because OR operator always gives 1 except for ‘0 || 0’ combination- for which it gives 0). So the value of m is 1. The values of other variables are also incremented by 1.

8. main()
{
char *p;
printf("%d %d ",sizeof(*p),sizeof(p));
}

Answer: 1 2
Explanation:
The sizeof() operator gives the number of bytes taken by its operand. P is a character pointer, which needs one byte for storing its value (a character). Hence sizeof(*p) gives a value of 1. Since it needs two bytes to store the address of the character pointer sizeof(p) gives 2.

9. main()
{
int i=3;
switch(i)
{
default:printf("zero");
case 1: printf("one");
break;
case 2:printf("two");
break;
case 3: printf("three");
break;
}
}
Answer :three
Explanation :
The default case can be placed anywhere inside the loop. It is executed only when all other cases doesn't match.

10. main()
{
printf("%x",-1<<4);
}
Answer:
fff0
Explanation :
-1 is internally represented as all 1's. When left shifted four times the least significant 4 bits are filled with 0's.The %x format specifier specifies that the integer value be printed as a hexadecimal value.

11. main()
{
char string[]="Hello World";
display(string);
}
void display(char *string)
{
printf("%s",string);
}
Answer: Compiler Error : Type mismatch in redeclaration of function display

Explanation :

In third line, when the function display is encountered, the compiler doesn't know anything about the function display. It assumes the arguments and return types to be integers, (which is the default type). When it sees the actual function display, the arguments and type contradicts with what it has assumed previously. Hence a compile time error occurs.

12. main()
{
int c=- -2;
printf("c=%d",c);
}
Answer: c=2;
Explanation:
Here unary minus (or negation) operator is used twice. Same maths rules applies, ie. minus * minus= plus.
Note:
However you cannot give like --2. Because -- operator can only be applied to variables as a decrement operator (eg., i--). 2 is a constant and not a variable.

13. #define int char
main()
{
int i=65;
printf("sizeof(i)=%d",sizeof(i));
}
Answer: sizeof(i)=1
Explanation:
Since the #define replaces the string int by the macro char

14.
main()
{
int i=10;
i=!i>14;
Printf ("i=%d",i);
}
Answer: i=0
Explanation:
In the expression !i>14 , NOT (!) operator has more precedence than ‘ >’ symbol. ! is a unary logical operator. !i (!10) is 0 (not of true is false). 0>14 is false (zero).

15. #include
main()
{
char s[]={'a','b','c','\n','c','\0'};
char *p,*str,*str1;
p=&s[3];
str=p;
str1=s;
printf("%d",++*p + ++*str1-32);
}

Answer: 77
Explanation:
p is pointing to character '\n'. str1 is pointing to character 'a' ++*p. "p is pointing to '\n' and that is incremented by one." the ASCII value of '\n' is 10, which is then incremented to 11. The value of ++*p is 11. ++*str1, str1 is pointing to 'a' that is incremented by 1 and it becomes 'b'. ASCII value of 'b' is 98.
Now performing (11 + 98 – 32), we get 77("M");
So we get the output 77 :: "M" (Ascii is 77).

16.
#include
main()
{
int a[2][2][2] = { {10,2,3,4}, {5,6,7,8} };
int *p,*q;
p=&a[2][2][2];
*q=***a;
printf("%d----%d",*p,*q);
}
Answer: SomeGarbageValue---1
Explanation:
p=&a[2][2][2] you declare only two 2D arrays, but you are trying to access the third 2D(which you are not declared) it will print garbage values. *q=***a starting address of a is assigned integer pointer. Now q is pointing to starting address of a. If you print *q, it will print first element of 3D array.

17. #include
main()
{
struct xx
{
int x=3;
char name[]="hello";
};
struct xx *s;
printf("%d",s->x);
printf("%s",s->name);
}
Answer: Compiler Error
Explanation:
You should not initialize variables in declaration

18.
#include
main()
{
struct xx
{
int x;
struct yy
{
char s;
struct xx *p;
};
struct yy *q;
};
}
Answer: Compiler Error
Explanation:
The structure yy is nested within structure xx. Hence, the elements are of yy are to be accessed through the instance of structure xx, which needs an instance of yy to be known. If the instance is created after defining the structure the compiler will not know about the instance relative to xx. Hence for nested structure yy you have to declare member.

19.
main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}
Answer: hai
Explanation:
\n - newline
\b - backspace
\r - linefeed

20.
main()
{
int i=5;
printf("%d%d%d%d%d%d",i++,i--,++i,--i,i);
}

Answer:45545
Explanation:
The arguments in a function call are pushed into the stack from left to right. The evaluation is by popping out from the stack. and the evaluation is from right to left, hence the result.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

C code to Check the string has valid identifier or not in.

 Unknown     6:28 AM     30 comments   

#include
#include
#include

char keyword[][10]={"auto","break","case","char","const","continue","default","printf", "double","else","enum","extern","float","for","goto","if","int","do", "long","register","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while"};

#define SIZE 25

int main()
{
char str[SIZE];
int len,i,flag=0;
printf("Enter The C Identifier :> ");
gets(str);

for( i = 0 ; i <= 32 ; i++ )
{
if(strcmp(str,keyword[i])==0)
{
printf(" Given string is invalid identifier\n");
exit(0);
}
}
if( str[0]=='_' || isalpha(str[0]) )
{
flag=1;
len=strlen(str);
for(i = 1 ; i < len ; i++ )
{
if( str[i]=='_' || isalpha(str[i]) || isdigit(str[i]) )
continue;
else
{
flag=0;
//printf(" H!!!!!!!! ");
break;
}
}
}

if( flag == 1 )
printf("Given string is a valid C Identifier\n");
else
printf("Given string is invalid C identifier\n");
return 0;
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Code for matrix problem in C++

 Unknown     6:21 AM     1 comment   

#include
using namespace std;
#define row 10
#define col 10
int row1,row2,col1,col2;
class matrix
{
int a[row][col];
int b[row][col];
int c[row][col];
public :
void input();
void addtion();
void subtraction();
void multiply();
void show();
};
void matrix::input()
{
int i,j;
cout<<"enter the number of row of first matrix\n";
cin>>row1;
cout<<"enter the number of coloumn of first matrix\n";

cout<<"enter the elements of first matrix";
for loop from i=0 upto row1;
{
for loop from j=0 upto col1;
{
cin>>a[i][j];
}
}
cout<<"enter the number of row & coloumn of second matrix";
cin>>row2>>col2;
cout<<"enter the elements of second matrix";
for loop from i=0 upto row2;
{
for loop from j=0 upto col2;
{
cin>>b[i][j];
}
}
}
void matrix::addtion()
{
int i,j;
for loop from i=0 upto row1;
{
for loop from j=0 upto col2;
{
c[i][j]=a[i][j]+b[i][j];
}
}
}
void matrix::subtraction()
{
int i,j;
for loop from i=0 upto row1;
{
for loop from j=0 upto col1;
{
c[i][j]=a[i][j]-b[i][j];
}
}
}
void matrix::multiply()
{
int i,j,k,sum=0;
for loop from k=0 upto col2;
{
for loop from i=0 upto row1;
{
sum=0;
for loop from j=0 upto col1;
{
sum=sum+a[i][j]*b[j][k];
}
c[i][k]=sum;
}
}
}
void matrix::show()
{
int i,j;
for loop from i=0 upto row1;
{
for loop from j=0 upto col1;
{
print two dimension array c according to i and j<<' ';
}
cout<<"\n";
}
}
int main()
{
matrix m;
int ch;
m.input();
while(1)
{
cout<<"options:-\npress 1 for addition\npress 2 for subtraction\npress 3 for multiplication\npress any other key for exit\n";
cin>>ch;
switch(ch)
{
case 1:
if(row1!=row2 ||col1!=col2)
cout<<"addition is not possible\n";
else
{
m.addtion();
m.show();
}
break;
case 2:
if(row1!=row2 ||col1!=col2)
cout<<"subtraction is not possible\n";
else
{
m.subtraction();
m.show();
}
break;
case 3:
if(col1!=row2)
cout<<"multiplicaton is not possible\n";
else
{
m.multiply();
m.show();
}
break;
default:
exit(1);
}
}

}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Implementation of a queue in C++

 Unknown     6:14 AM     No comments   

#include
using namespace std;
class queue
{
int front,rear;
int item[3];
public:
void insert(int);
int remove();
void display();
void setvalues()
{
front=-1;
rear=0;
}
};
void queue::insert(int m)
{

item[rear++]=m;
}
int queue::remove()
{
int x;

if(front==-1)
cout<<"empty";
x=item[++front];
return(x);
}
void queue::display()
{
int i=front+1;
for loop upto rear then print the items according to item[i]

}
int main()
{
queue s;
int item,ch;
s.setvalues();
while(1)
{
cout<<"optoins:-\npress 1 for inserting the elements\npress 2 for removing the element\npress 3 for display the result\npress any key for exit\n";
cin>>ch;
switch(ch)
{
case 1:
cout<<"enter your item";
cin>>item;
s.insert(item);
break;
case 2:
item=s.remove();
print the item.
break;
case 3:
s.display();
break;
default:
exit(1);
}
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

A linked list program in C++

 Unknown     6:13 AM     1 comment   

#include
using namespace std;
struct node
{
int info;
struct node *next;

struct node *getnode();
struct node *insert_last(struct node *);
struct node *insert_begin(struct node *);
struct node *insert_after(struct node *);
struct node *delete_after(struct node *);
void display(struct node *);

};
struct node* node:: getnode()
{
int x;
struct node *p;
p=new node;
cout<<"enter the information ";
cin>>x;
p->info=x;
p->next=NULL;
return(p);
}
struct node* node::insert_last(struct node *ptr)
{
struct node *temp;
temp=ptr;
while(temp->next!=NULL)
temp=temp->next;
temp->next=getnode();
return(ptr);
}
struct node* node::insert_begin(struct node *ptr)
{
struct node *temp;
temp=ptr;
temp=getnode();
temp->next=ptr;
ptr=temp;
return(ptr);
}
struct node* node::insert_after(struct node *ptr)
{
struct node *temp1,*temp2;
int x,i;
temp2=temp1=ptr;
cout<<"enter the position";
cin>>x;
for(i=1;i<(x-1);i++)
{
temp1=temp1->next;
temp2=temp2->next;
}
temp2=temp2->next;
temp1->next=getnode();
temp1=temp1->next;
temp1->next=temp2;
return(ptr);
}
struct node* node::delete_after(struct node *ptr)
{
int x,i;
struct node *temp1,*temp2;
temp1=temp2=ptr;
cout<<"enter your position";
cin>>x;
for(i=1;i<(x-1);i++)
{
temp1=temp1->next;
temp2=temp2->next;
}
temp2=temp2->next;
temp1->next=temp2->next;
return(ptr);
}
void node:: display(struct node *ptr)
{
struct node *temp;
temp=ptr;
while(ptr!=NULL)
{
cout<info<<" ";
ptr=ptr->next;
}
}
int main()
{
struct node *head,a;
int ch;
head=a.getnode();
while(1)
{
cout<< "options:-\npress 1 for insert at last\npress 2 for insert at begin\n press 3 for insert in between\n press 4 for delete\n press 5 for display\n press any key for exit"<<"\n\n";
scanf("%d",&ch);
switch(ch)
{
case 1://head=n.getnode();
head=a.insert_last(head);
break;
case 2:
head=a.insert_begin(head);
break;
case 3:
head=a.insert_after(head);
break;
case 4:
head=a.delete_after(head);
break;
case 5:
a.display(head);
break;
default:
exit(1);
}
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

OOPS Concepts..

 Unknown     5:52 AM     No comments   

Q:-What is Function Overloading ?

A:-Function overloading:
C++ enables several functions of the same name to be defined, as long as
these functions have different sets of parameters (at least as far as their types are concerned). This
capability is called function overloading. When an overloaded function is called, the C++ compiler
selects the proper function by examining the number, types and order of the arguments in the call.
Function overloading is commonly used to create several functions of the same name that perform
similar tasks but on different data types.

Q:-What do you mean by Operator Overloading?

A:-Operator Overloading:
Operator overloading allows existing C++ operators to be redefined so that they work on objects
of user-defined classes. Overloaded operators are syntactic sugar for
equivalent function calls. They form a pleasant facade that doesn't add anything fundamental to the
language (but they can improve understandability and reduce
maintenance costs).


Q:-Difference between realloc() and free()?

A:-The free subroutine frees a block of memory previously allocated by the malloc subroutine.
Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a
null value, no action will occur. The realloc subroutine changes the size of the block of memory
pointed to by the Pointer parameter to the number of bytes specified by the Size parameter and
returns a new pointer to the block. The pointer specified by the Pointer parameter must have been
created with the malloc, calloc, or realloc subroutines and not been deallocated with the free or
realloc subroutines. Undefined results occur if the Pointer parameter is not a valid pointer


Q:- What do you mean by binding of data and functions?

A:-Encapsulation.

Q:- What is abstraction?

A:-Abstraction is of the process of hiding unwanted details from the user.

Q:- What is encapsulation?

A:-Packaging an object’s variables within its methods is called encapsulation.

Q:- What is the difference between an object and a class?


A:- Classes and objects are separate but related concepts. Every object belongs to a class and every class contains one or more related objects.
1: A Class is static. All of the attributes of a class are fixed before, during, and after the execution of a program. The attributes of a class don't change.
2: The class to which an object belongs is also (usually) static. If a particular object belongs to a
certain class at the time that it is created then it almost certainly will still belong to that class right up until the time that it is destroyed.
3: An Object on the other hand has a limited lifespan. Objects are created and eventually destroyed. Also during that lifetime, the attributes of the object may undergo significant change.

Q:- What is polymorphism? Explain with an example?

A:-"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an object (or
reference) to assume (be replaced by) or become many different forms of
object.
Example: function overloading, function overriding, virtual functions. Another example can be a plus ‘+’ sign, used for adding two integers or for using it to concatenate two strings.

Q:- What do you mean by inheritance?

A:-Inheritance is the process of creating new classes, called derived classes, from existing classes or base classes. The derived class inherits all the capabilities of the base class, but can add embellishments and refinements of its own.

Q:- What is a scope resolution operator?

A:-A scope resolution operator (::), can be used to define the member functions of a class outside the class.

Q:- What are virtual functions?

A:-A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever
the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.

Q:- What is friend function?

A:-As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be listed in the class definition.

Q:- What is the difference between class and structure?

A:- Structure:
Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public.
Class:
Class is a successor of Structure. By default all the members inside the class are private

Q:- What is public, protected, private?

A:-
1:- Public, protected and private are three access specifiers in C++.
2:-Public data members and member functions are accessible outside the class.
3:-Protected data members and member functions are only available to derived classes.
4:-Private data members and member functions can’t be accessed outside the class.
However there is an exception can be using friend classes.

Q:- What is an object?

A:- Object is a software bundle of variables and related methods. Objects have state and behavior.

Q:- What is a class?

A:-Class is a user-defined data type in C++. It can be created to solve a particular kind of problem.
After creation the user need not know the specifics of the working of a class.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

OOPS Concepts...

 Unknown     5:47 AM     No comments   

Q:-What is namespace?

A:-Namespaces allow us to group a set of global classes, objects and/or functions under a name. To say
it somehow, they serve to split the global scope in sub-scopes known
as namespaces.
The form to use namespaces is:
namespace identifier { namespace-body }
Where identifier is any valid identifier and namespace-body is the set of classes, objects and
functions that are included within the namespace.

For example:

namespace general { int a, b; } In this case, a and b are normal variables integrated within the
general namespace. In order to access to these variables from outside the namespace we have to
use the scope operator ::. For example, to access the previous variables we would have to put:
general::a general::b
The functionality of namespaces is specially useful in case that there is a possibility that a global
object or function can have the same name than another one, causing a
redefinition error.

Q:- What is RTTI?

A:- Runtime type identification (RTTI) lets you find the dynamic type of an object when you have only a
pointer or a reference to the base type. RTTI is the official way in
standard C++ to discover the type of an object and to convert the type of a pointer or reference
(that is, dynamic typing). The need came from practical experience with
C++. RTTI replaces many homegrown versions with a solid, consistent approach.


Q:- What is a template?

A:-Templates allow to create generic functions that admit any data type as parameters and return value
without having to overload the function with all the possible data types. Until certain point they fulfill
the functionality of a macro. Its prototype is any of the two following ones:
template function_declaration; template
function_declaration;
The only difference between both prototypes is the use of keyword class or typename, its use is
indistinct since both expressions have exactly the same meaning and behave exactly the same way.

Q:- What do you mean by inline function?

A:-The idea behind inline functions is to insert the code of a called function at the point where the
function is called. If done carefully, this can improve the application's
performance in exchange for increased compile time and possibly (but not always) an increase in the
size of the generated binary executables.

Q:-What is virtual class and friend class?

A:-Friend classes are used when two or more classes are designed to work together and need access
to each other's implementation in ways that the rest of the world
shouldn't be allowed to have. In other words, they help keep private things private. For instance, it may be desirable for class DatabaseCursor to have more privilege to the internals of class Database than main() has.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

 Unknown     5:44 AM     No comments   

1. What is virtual constructors/destructors?

Virtual destructors:

If an object (with a non-virtual destructor) is destroyed explicitly by applying
the delete operator to a base-class pointer to the object, the base-class destructor function
(matching the pointer type) is called on the object.
There is a simple solution to this problem – declare a virtual base-class destructor. This makes all
derived-class destructors virtual even though they don’t have the same name as the base-class
destructor. Now, if the object in the hierarchy is destroyed explicitly by applying the delete operator
to a base-class pointer to a derived-class object, the destructor for the appropriate class is called.

Virtual constructor:

Constructors cannot be virtual. Declaring a constructor as a virtual function is
a syntax error. Does c++ support multilevel and multiple inheritance?
Yes.
What are the advantages of inheritance?
• It permits code reusability.
• Reusability saves time in program development.
• It encourages the reuse of proven and debugged high-quality software, thus reducing problem
after a system becomes functional.
What is the difference between declaration and definition?
The declaration tells the compiler that at some later point we plan to present the definition of this
declaration.
E.g.: void stars () //function declaration
The definition contains the actual implementation.
E.g.: void stars () // declarator
{
for(int j=10; j>=0; j--) //function body
cout<<”*”;
Print New Line
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to: Read Image Metadata

 Unknown     3:30 AM     No comments   

Some image files contain metadata that you can read to determine features of the image. Like, a digital photograph might contain metadata that you can read to determine the Author,Title and Keywords of the image.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageMetaData.aspx.cs" Inherits="ImageMetaData" %>



Untitled Page














using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DSOFile;
public partial class ImageMetaData : System.Web.UI.Page
{
OleDocumentPropertiesClass oDocument;
string strImgName = string.Empty;
string strImgPath = string.Empty;
string strImgTitle = string.Empty;
string strImgAuthor = string.Empty;
string strImgSubject = string.Empty;
string strImgCompany = string.Empty;
string strImgComments = string.Empty;
string strImgApplication = string.Empty;
string strImgVersion = string.Empty;
string strImgCategory = string.Empty;
string strImgKeywords = string.Empty;
string strImgManager = string.Empty;
string strImgLastSavedBy = string.Empty;
string strImgByteCount = string.Empty;
string strImgDateCreated = string.Empty;
string strImgRevisionnum = string.Empty;
string strImgHeight = string.Empty;
string strImgWidth = string.Empty;
string strImgHResolution = string.Empty;
string strImgVResolution = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
OpenDocumentProperties(FileUpload1.PostedFile.FileName.ToString());
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("");
sb.Append("
AuthorSubjectTitle
");
sb.Append(strImgAuthor);
sb.Append("
");
sb.Append(strImgSubject);
sb.Append("
");
sb.Append(strImgTitle);
sb.Append("
");
Label1.Text = sb.ToString();
}
protected void OpenDocumentProperties(string strFile)
{
try
{
DSOFile.SummaryProperties oSummProps;
string strTmp = string.Empty;
oDocument = new DSOFile.OleDocumentPropertiesClass();
oDocument.Open(strFile, false, DSOFile.dsoFileOpenOptions.dsoOptionOpenReadOnlyIfNoWriteAccess);
oSummProps = oDocument.SummaryProperties;
strImgName = oDocument.Name;
strImgPath = oDocument.Path;
if (oSummProps.Author == "" || oSummProps.Comments == "" || oSummProps.Title == "" || oSummProps.Keywords == "")
{
strImgTitle = "All";
}
else
{
strImgTitle = oSummProps.Title;
}
if (oSummProps.Author == "")
{
strImgAuthor = "Unknown";
}
else
{
strImgAuthor = oSummProps.Author;
}
strImgSubject = oSummProps.Subject;
strImgCompany = oSummProps.Company;
strImgComments = oSummProps.Comments;
strImgApplication = oSummProps.ApplicationName;
strImgVersion = oSummProps.Version;
strImgCategory = oSummProps.Category;
strImgKeywords = "," + oSummProps.Keywords.ToString() + ",";
strImgManager = oSummProps.Manager;
strImgLastSavedBy = oSummProps.LastSavedBy;
strImgByteCount = oSummProps.ByteCount.ToString();
if (oSummProps.DateCreated != null)
{
strImgDateCreated = oSummProps.DateCreated.ToString();
}
else
{
strImgDateCreated = "";
}
strImgRevisionnum = oSummProps.RevisionNumber;
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
}
}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

How to store a record in xml file from a windows form and extract through Reflection..(A perfect example of reflection)

 Unknown     3:15 AM     No comments   

Reflection.cs Browse folder to store record in xml file and again browse to extract from the xml file all the properties are setting in settings.cs and all constants are defined in Constants.cs and Reflection.Designer contains the designer view..

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Text.RegularExpressions;

namespace ReflectionExample
{
public partial class Reflection : Form
{
private bool boolEmailValidation = false;
private bool boolPercentValidation;
public Reflection()
{
InitializeComponent();
}

Settings settings = new Settings();

private void Form1_Load(object sender, EventArgs e)
{

}
private void RetrieveButton_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
settings.Load(openFileDialog1.FileName);
UpdateSettings();
}
}

private void UpdateSettings()
{
textStudentName.Text = settings.StudentName;
textFathersName.Text = settings.FatherName;
textInstituteName.Text = settings.Institute;
textLastDegree.Text = settings.LastDegree;
textPercentage.Text = settings.Percentage;
textEmailId.Text = settings.EmailId;
SaveButton.Visible = false;
}

private void SaveButton_Click(object sender, EventArgs e)
{
if (boolPercentValidation)
{
if (boolEmailValidation)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
settings.Save(saveFileDialog1.FileName);
FunctionEmpty();
}
}
else
{
MessageBox.Show(Constants.EmailError, Constants.Error1, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show(Constants.PercentageError, Constants.Error1, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

private void FunctionEmpty()
{
textStudentName.Text = string.Empty;
textFathersName.Text = string.Empty;
textInstituteName.Text = string.Empty;
textLastDegree.Text = string.Empty;
textPercentage.Text = string.Empty;
textEmailId.Text = string.Empty;
}
private void textStudentName_TextChanged(object sender, EventArgs e)
{
settings.StudentName = textStudentName.Text;
}

private void textFathersName_TextChanged(object sender, EventArgs e)
{
settings.FatherName = textFathersName.Text;
}

private void textInstituteName_TextChanged(object sender, EventArgs e)
{
settings.Institute = textInstituteName.Text;
}

private void textLastDegree_TextChanged (object sender, EventArgs e)
{
settings.LastDegree = textLastDegree.Text;
}

private void textPercentage_TextChanged (object sender, EventArgs e)
{
boolPercentValidation = true;
Regex objNotNaturalPattern = new Regex(Constants.PercentageRegularExpression);
if (!objNotNaturalPattern.IsMatch(textPercentage.Text))
{
if (textPercentage.Text != string.Empty)
{
int Marks = Convert.ToInt32(textPercentage.Text);
if (Marks > 100)
{
boolPercentValidation = false;
}
settings.Percentage = textPercentage.Text;
}
}
else
{
boolPercentValidation = false;
}


}

private void textEmailId_TextChanged (object sender, EventArgs e)
{
boolEmailValidation = true;
Regex objNotNaturalPattern = new Regex(Constants.EmailIdRegularExpression);
if (objNotNaturalPattern.IsMatch(textEmailId.Text))
{
boolEmailValidation = true;
settings.EmailId = textEmailId.Text;
}
else
{
boolEmailValidation = false;
}

}

private void CancelButton_Click(object sender, EventArgs e)
{
this.Dispose();
}
}
}

/*Reflection.Designer View*/

namespace ReflectionExample
{
partial class Reflection
{
///
/// Required designer variable.
///

private System.ComponentModel.IContainer components = null;

///
/// Clean up any resources being used.
///

/// true if managed resources should be disposed; otherwise, false.
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code

///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.Namelabel = new System.Windows.Forms.Label();
this.textStudentName = new System.Windows.Forms.TextBox();
this.FNamelabel = new System.Windows.Forms.Label();
this.textFathersName = new System.Windows.Forms.TextBox();
this.Instituelabel = new System.Windows.Forms.Label();
this.textInstituteName = new System.Windows.Forms.TextBox();
this.Institutelabel = new System.Windows.Forms.Label();
this.textLastDegree = new System.Windows.Forms.TextBox();
this.Percentagelabel = new System.Windows.Forms.Label();
this.textPercentage = new System.Windows.Forms.TextBox();
this.Emaillabel = new System.Windows.Forms.Label();
this.textEmailId = new System.Windows.Forms.TextBox();
this.SaveButton = new System.Windows.Forms.Button();
this.RetrieveButton = new System.Windows.Forms.Button();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.CancelButton = new System.Windows.Forms.Button();
this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
this.errorProvider1 = new System.Windows.Forms.ErrorProvider(this.components);
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).BeginInit();
this.SuspendLayout();
//
// Namelabel
//
this.Namelabel.AutoSize = true;
this.Namelabel.Location = new System.Drawing.Point(68, 36);
this.Namelabel.Name = "Namelabel";
this.Namelabel.Size = new System.Drawing.Size(35, 13);
this.Namelabel.TabIndex = 0;
this.Namelabel.Text = "Name";
//
// textStudentName
//
this.textStudentName.Location = new System.Drawing.Point(185, 33);
this.textStudentName.MaxLength = 15;
this.textStudentName.Name = "textStudentName";
this.textStudentName.Size = new System.Drawing.Size(149, 20);
this.textStudentName.TabIndex = 1;
this.textStudentName.TextChanged += new System.EventHandler(this.textStudentName_TextChanged);
//
// FNamelabel
//
this.FNamelabel.AutoSize = true;
this.FNamelabel.Location = new System.Drawing.Point(28, 76);
this.FNamelabel.Name = "FNamelabel";
this.FNamelabel.Size = new System.Drawing.Size(75, 13);
this.FNamelabel.TabIndex = 2;
this.FNamelabel.Text = "Father\'s Name";
//
// textFathersName
//
this.textFathersName.Location = new System.Drawing.Point(185, 73);
this.textFathersName.MaxLength = 15;
this.textFathersName.Name = "textFathersName";
this.textFathersName.Size = new System.Drawing.Size(149, 20);
this.textFathersName.TabIndex = 3;
this.textFathersName.TextChanged += new System.EventHandler(this.textFathersName_TextChanged);
//
// Instituelabel
//
this.Instituelabel.AutoSize = true;
this.Instituelabel.Location = new System.Drawing.Point(59, 125);
this.Instituelabel.Name = "Instituelabel";
this.Instituelabel.Size = new System.Drawing.Size(44, 13);
this.Instituelabel.TabIndex = 4;
this.Instituelabel.Text = "Institute";
//
// textInstituteName
//
this.textInstituteName.Location = new System.Drawing.Point(185, 122);
this.textInstituteName.MaxLength = 25;
this.textInstituteName.Name = "textInstituteName";
this.textInstituteName.Size = new System.Drawing.Size(149, 20);
this.textInstituteName.TabIndex = 5;
this.textInstituteName.TextChanged += new System.EventHandler(this.textInstituteName_TextChanged);
//
// Institutelabel
//
this.Institutelabel.AutoSize = true;
this.Institutelabel.Location = new System.Drawing.Point(38, 174);
this.Institutelabel.Name = "Institutelabel";
this.Institutelabel.Size = new System.Drawing.Size(65, 13);
this.Institutelabel.TabIndex = 6;
this.Institutelabel.Text = "Last Degree";
//
// textLastDegree
//
this.textLastDegree.Location = new System.Drawing.Point(185, 171);
this.textLastDegree.MaxLength = 30;
this.textLastDegree.Name = "textLastDegree";
this.textLastDegree.Size = new System.Drawing.Size(149, 20);
this.textLastDegree.TabIndex = 7;
this.textLastDegree.TextChanged += new System.EventHandler(this.textLastDegree_TextChanged);
//
// Percentagelabel
//
this.Percentagelabel.AutoSize = true;
this.Percentagelabel.Location = new System.Drawing.Point(38, 220);
this.Percentagelabel.Name = "Percentagelabel";
this.Percentagelabel.Size = new System.Drawing.Size(62, 13);
this.Percentagelabel.TabIndex = 8;
this.Percentagelabel.Text = "Percentage";
//
// textPercentage
//
this.textPercentage.Location = new System.Drawing.Point(185, 217);
this.textPercentage.MaxLength = 3;
this.textPercentage.Name = "textPercentage";
this.textPercentage.Size = new System.Drawing.Size(149, 20);
this.textPercentage.TabIndex = 9;
this.textPercentage.TextChanged += new System.EventHandler(this.textPercentage_TextChanged);
//
// Emaillabel
//
this.Emaillabel.AutoSize = true;
this.Emaillabel.Location = new System.Drawing.Point(56, 274);
this.Emaillabel.Name = "Emaillabel";
this.Emaillabel.Size = new System.Drawing.Size(44, 13);
this.Emaillabel.TabIndex = 10;
this.Emaillabel.Text = "Email Id";
//
// textEmailId
//
this.textEmailId.Location = new System.Drawing.Point(185, 271);
this.textEmailId.MaxLength = 30;
this.textEmailId.Name = "textEmailId";
this.textEmailId.Size = new System.Drawing.Size(149, 20);
this.textEmailId.TabIndex = 11;
this.textEmailId.TextChanged += new System.EventHandler(this.textEmailId_TextChanged);
//
// SaveButton
//
this.SaveButton.Location = new System.Drawing.Point(185, 361);
this.SaveButton.Name = "SaveButton";
this.SaveButton.Size = new System.Drawing.Size(75, 23);
this.SaveButton.TabIndex = 12;
this.SaveButton.Text = "Save";
this.SaveButton.UseVisualStyleBackColor = true;
this.SaveButton.Click += new System.EventHandler(this.SaveButton_Click);
//
// RetrieveButton
//
this.RetrieveButton.Location = new System.Drawing.Point(281, 361);
this.RetrieveButton.Name = "RetrieveButton";
this.RetrieveButton.Size = new System.Drawing.Size(75, 23);
this.RetrieveButton.TabIndex = 13;
this.RetrieveButton.Text = "Retrieve";
this.RetrieveButton.UseVisualStyleBackColor = true;
this.RetrieveButton.Click += new System.EventHandler(this.RetrieveButton_Click);
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
this.openFileDialog1.Filter = "XML Files|*.xml|All Files|*.*";
//
// saveFileDialog1
//
this.saveFileDialog1.DefaultExt = "xml";
this.saveFileDialog1.Filter = "XML Files|*.xml|All Files|*.*";
//
// CancelButton
//
this.CancelButton.Location = new System.Drawing.Point(89, 361);
this.CancelButton.Name = "CancelButton";
this.CancelButton.Size = new System.Drawing.Size(75, 23);
this.CancelButton.TabIndex = 14;
this.CancelButton.Text = "Cancel";
this.CancelButton.UseVisualStyleBackColor = true;
this.CancelButton.Click += new System.EventHandler(this.CancelButton_Click);
//
// numericUpDown1
//
this.numericUpDown1.Location = new System.Drawing.Point(185, 245);
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(120, 20);
this.numericUpDown1.TabIndex = 15;
//
// errorProvider1
//
this.errorProvider1.ContainerControl = this;
//
// Reflection
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(416, 406);
this.Controls.Add(this.numericUpDown1);
this.Controls.Add(this.CancelButton);
this.Controls.Add(this.RetrieveButton);
this.Controls.Add(this.SaveButton);
this.Controls.Add(this.textEmailId);
this.Controls.Add(this.Emaillabel);
this.Controls.Add(this.textPercentage);
this.Controls.Add(this.Percentagelabel);
this.Controls.Add(this.textLastDegree);
this.Controls.Add(this.Institutelabel);
this.Controls.Add(this.textInstituteName);
this.Controls.Add(this.Instituelabel);
this.Controls.Add(this.textFathersName);
this.Controls.Add(this.FNamelabel);
this.Controls.Add(this.textStudentName);
this.Controls.Add(this.Namelabel);
this.Name = "Reflection";
this.Text = "Student-Information";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();

}

#endregion

private System.Windows.Forms.Label Namelabel;
private System.Windows.Forms.TextBox textStudentName;
private System.Windows.Forms.Label FNamelabel;
private System.Windows.Forms.TextBox textFathersName;
private System.Windows.Forms.Label Instituelabel;
private System.Windows.Forms.TextBox textInstituteName;
private System.Windows.Forms.Label Institutelabel;
private System.Windows.Forms.TextBox textLastDegree;
private System.Windows.Forms.Label Percentagelabel;
private System.Windows.Forms.TextBox textPercentage;
private System.Windows.Forms.Label Emaillabel;
private System.Windows.Forms.TextBox textEmailId;
private System.Windows.Forms.Button SaveButton;
private System.Windows.Forms.Button RetrieveButton;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.Button CancelButton;
private System.Windows.Forms.NumericUpDown numericUpDown1;
private System.Windows.Forms.ErrorProvider errorProvider1;
}
}

/*settings.cs*/
/*This class contains how to create a xml file how data can store in xml file and how can we extract*/

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Drawing;
using System.Reflection;
using System.Xml.Serialization;


namespace ReflectionExample
{
#region - public abstract class:XmlSerializable -

public class XmlSerializable
{
#region - public virtual void:Save(string path) -

public virtual void Save(string path)
{
StreamWriter objStreamWriter = new StreamWriter(path);
XmlSerializer objXmlSerializer = new XmlSerializer(this.GetType());
objXmlSerializer.Serialize(objStreamWriter, this);
objStreamWriter.Close();
}

#endregion

#region - public virtual void: Load(string path) -

public virtual void Load(string path)
{
if (File.Exists(path))
{
StreamReader objStreamReader = new StreamReader(path);
XmlTextReader objXmlTextReader = new XmlTextReader(objStreamReader);
XmlSerializer objXmlSerializer = new XmlSerializer(this.GetType());
object obj;
if (objXmlSerializer.CanDeserialize(objXmlTextReader))
{
obj = objXmlSerializer.Deserialize(objXmlTextReader);
Type objType = this.GetType();
PropertyInfo[] properties = objType.GetProperties();
foreach (PropertyInfo objProperty in properties)
{
objProperty.SetValue(this, objProperty.GetValue(obj, null), null);
}
}
objXmlTextReader.Close();
objStreamReader.Close();
}
}

#endregion
}
#endregion

public class Settings : XmlSerializable
{

[XmlIgnore()]
public string StudentName
{
get { return _StudentName; }
set { _StudentName = value; }
}
private string _StudentName = string.Empty;

[XmlElement("StudentName")]
public string XmlStudentName
{
get { return _StudentName; }
set { _StudentName = value; }
}

[XmlIgnore()]
public string FatherName
{
get { return _FatherName; }
set { _FatherName = value; }
}
private string _FatherName = string.Empty;

[XmlElement("FatherName")]
public string XmlFatherName
{
get { return _FatherName; }
set { _FatherName = value; }
}
[XmlIgnore()]
public string Institute
{
get { return _Institute; }
set { _Institute = value; }
}
private string _Institute =string.Empty;
[XmlElement("Institute")]
public string XmlInstitute
{
get { return _Institute; }
set { _Institute = value; }
}
[XmlIgnore()]
public string LastDegree
{
get { return _LastDegree; }
set { _LastDegree = value; }
}
private string _LastDegree = string.Empty;
[XmlElement("LastDegree")]
public string XmlLastDegree
{
get { return _LastDegree; }
set { _LastDegree = value; }
}
[XmlIgnore()]
public string Percentage
{
get { return _Percentage; }
set { _Percentage = value; }
}
private string _Percentage = string.Empty;
[XmlElement("Percentage")]
public string XmlPercentage
{
get { return _Percentage; }
set { _Percentage = value; }
}
[XmlIgnore()]
public string EmailId
{
get { return _EmailId; }
set { _EmailId = value; }
}
private string _EmailId = string.Empty;
[XmlElement("EmailId")]
public string XmlEmailId
{
get { return _EmailId; }
set { _EmailId = value; }
}
}

}

/*Constants.cs*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ReflectionExample
{
class Constants
{
internal const string EmailError = "Email Id is not valid!!";
internal const string Error1 = "Error";
internal const string PercentageError = "Percentage must be less than 100!!";
internal const string PercentageRegularExpression=@"[^0-9]";
internal const string EmailIdRegularExpression = @"^[a-zA-Z0-9_\-\.]+@([\w-]+\.)+[\w-]+$";

}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg

Sudoku-Checker in ASP.Net using C#

 Unknown     2:49 AM     No comments   

# region directives

using System;
using System.Collections;

#endregion


namespace sudokuChecker
{

class SudokuMainExample
{
static void Main()
{
SudokuCheck objectSudokuCheck = new SudokuCheck();
int[,] Board=new int[9,9];
int countnumberofInput=0;
string menuStatus="y";
string readInput="n";

try
{
Console.WriteLine("You Are Entering In Sudoku Checker:----");
for (int indexRow = 0; indexRow < 9; indexRow++)
{
for (int indexColumn = 0; indexColumn < 9; indexColumn++)
{
Board[indexRow, indexColumn] = 0;
}

}

do
{
/*try
{
Console.WriteLine("PLease Enter The Size of Row To Start The Game:--");
int row = Int32.Parse(Console.ReadLine());
Console.WriteLine("Lease Enter The Size of Row To Start The Game:--");
int column = Int32.Parse(Console.ReadLine());
if ((row != 9) && (column != 9))
throw new Exception("error");
else
Board = new int[row, column];
for (int indexRow = 0; indexRow < row; indexRow++)
{
for (int indexColumn = 0; indexColumn < column; indexColumn++)
{
Board[indexRow, indexColumn] = 0;
}

}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine("Your Input Is Not Valid Please Input A Right One ");
Console.WriteLine("If You Want To Input It Again then press :-Y otherwise Press N .");
readInput = (Console.ReadLine());
}*/
while ((menuStatus == "Y") || (menuStatus == "y"))
{
Console.WriteLine("You Have Some Choices:--");
Console.WriteLine("Press:-1 To Give Input In Sudoku Game:-");
Console.WriteLine("Press:-2 To Check Status");
Console.WriteLine("Press:-3 To Put Default Right Values:-");
Console.WriteLine("Press:-4 To Put Default Wrong Values:-");
Console.WriteLine("Press:-5 To Exit From The Menu Status:-");
int readChoice = Int32.Parse(Console.ReadLine());
switch (readChoice)
{
case 1:
int choiceCheck = 0;
while (choiceCheck != 1)
{
Console.WriteLine("Please Input A Row Number Where You Want To Put The Input");
int inputRow = Int32.Parse(Console.ReadLine());
Console.WriteLine("Please Input A Column Number Where You Want to Put The Input");
int inputColumn = Int32.Parse(Console.ReadLine());
Console.WriteLine("Please Input The Value You Want To Fill In This Particular Space");
int inputValue = Int32.Parse(Console.ReadLine());
if ((inputValue > 9) || (inputValue < 1))
{
Console.WriteLine("You Input Value Is Not Valid Please Input A Valid Value");
choiceCheck = 0;
}
else
{
choiceCheck = 1;
if (countnumberofInput != 81)
{
countnumberofInput++;
objectSudokuCheck.UserInputSudoku(inputRow, inputColumn, inputValue,Board);
}
else
{
Console.WriteLine("Board Has Already Filled");
Console.WriteLine("Now Check The status of Sudoku Game.");
}
}
}
Console.WriteLine("If You Again Want To Go To The Main menu Then Press Y To Continue Otherwise Press Any Button");
menuStatus = Console.ReadLine();
break;
case 2:
Console.WriteLine("We Are Going To Check the Status Of Sudoku Game");
SudokuCheck.Status obj= objectSudokuCheck.CheckSudokuStatus(Board);
Console.WriteLine(obj);
Console.WriteLine("If You Again Want To Go To The Main menu Then Press Y To Continue Otherwise Press Any Button");
menuStatus = Console.ReadLine();
break;
case 3:
Console.WriteLine("We Are Going To Put Default Right Values");
objectSudokuCheck.InputDefaultRightValues(Board);
Console.WriteLine("If You Again Want To Go To The Main menu Then Press Y To Continue Otherwise Press Any Button");
menuStatus = Console.ReadLine();
break;
case 4:
Console.WriteLine("We Are Going To Put Default Wrong Values");
objectSudokuCheck.InputDefaultWrongValues(Board);
Console.WriteLine("If You Again Want To Go To The Main menu Then Press Y To Continue Otherwise Press Any Button");
menuStatus = Console.ReadLine();
break;
case 5:
Console.WriteLine("We Are Exiting From The Program");
menuStatus = "N";
Console.WriteLine("If You Want To Input It Again then press :-Y otherwise Press N .");
readInput = (Console.ReadLine());
break;
default:
Console.WriteLine("Invalid Choice");
break;
}
}


} while (readInput == "y");
}
catch (Exception e)
{
Console.WriteLine("Your Input Is Not Valid:--");
Console.WriteLine("Do You Wanna Input It Again:--");
Console.ReadKey();
}
}
}
}



using System;
using System.Collections;

namespace sudokuChecker
{
class SudokuCheck
{
public enum Status
{
Success = 0,
Failure = 1,
Continue = 2
}
public void UserInputSudoku(int inputRow, int inputColumn, int inputValue,int [,]Board)
{
Board[inputRow,inputColumn] = inputValue;
}
public void InputDefaultWrongValues(int[,] Board)
{
Board[0, 0] = 9; Board[0, 1] = 6; Board[0, 2] = 1; Board[0, 3] = 1;
Board[0, 4] = 4; Board[0, 5] = 8; Board[0, 6] = 2; Board[0, 7] = 7;
Board[0, 8] = 3; Board[1, 0] = 8; Board[1, 1] = 7; Board[1, 2] = 2;
Board[1, 3] = 9; Board[1, 4] = 3; Board[1, 5] = 1; Board[1, 6] = 6;
Board[1, 7] = 4; Board[1, 8] = 5; Board[2, 0] = 6; Board[2, 1] = 5;
Board[2, 2] = 3; Board[2, 3] = 3; Board[2, 4] = 2; Board[2, 5] = 7;
Board[2, 6] = 8; Board[2, 7] = 9; Board[2, 8] = 1; Board[3, 0] = 5;
Board[3, 1] = 8; Board[3, 2] = 9; Board[3, 3] = 3; Board[3, 4] = 2;
Board[3, 5] = 2; Board[3, 6] = 1; Board[3, 7] = 6; Board[3, 8] = 7;
Board[4, 0] = 2; Board[4, 1] = 8; Board[4, 2] = 6; Board[4, 3] = 7;
Board[4, 4] = 1; Board[4, 5] = 5; Board[4, 6] = 4; Board[4, 7] = 3;
Board[4, 8] = 9; Board[5, 0] = 1; Board[5, 1] = 3; Board[5, 2] = 7;
Board[5, 3] = 4; Board[5, 4] = 9; Board[5, 5] = 6; Board[5, 6] = 5;
Board[5, 7] = 8; Board[5, 8] = 2; Board[6, 0] = 6; Board[6, 1] = 9;
Board[6, 2] = 4; Board[6, 3] = 1; Board[6, 4] = 5; Board[6, 5] = 3;
Board[6, 6] = 7; Board[6, 7] = 2; Board[6, 8] = 8; Board[7, 0] = 3;
Board[7, 1] = 2; Board[7, 2] = 5; Board[7, 3] = 8; Board[7, 4] = 7;
Board[7, 5] = 4; Board[7, 6] = 9; Board[7, 7] = 1; Board[7, 8] = 6;
Board[8, 0] = 7; Board[8, 1] = 1; Board[8, 2] = 8; Board[8, 3] = 2;
Board[8, 4] = 6; Board[8, 5] = 5; Board[8, 6] = 7; Board[8, 7] = 5;
Board[8, 8] = 4;
}
public void InputDefaultRightValues(int[,] Board)
{

Board[0,0]=9;Board[0,1]=6;Board[0,2]=1;Board[0,3]=5;
Board[0,4]=4;Board[0,5]=8;Board[0,6]=2;Board[0,7]=7;
Board[0,8]=3;Board[1,0]=8;Board[1,1]=7;Board[1,2]=2;
Board[1,3]=9;Board[1,4]=3;Board[1,5]=1;Board[1,6]=6;
Board[1,7]=4;Board[1,8]=5;Board[2,0]=4;Board[2,1]=5;
Board[2,2]=3;Board[2,3]=6;Board[2,4]=2;Board[2,5]=7;
Board[2,6]=8;Board[2,7]=9;Board[2,8]=1;Board[3,0]=5;
Board[3,1]=4;Board[3,2]=9;Board[3,3]=3;Board[3,4]=8;
Board[3,5]=2;Board[3,6]=1;Board[3,7]=6;Board[3,8]=7;
Board[4,0]=2;Board[4,1]=8;Board[4,2]=6;Board[4,3]=7;
Board[4,4]=1;Board[4,5]=5;Board[4,6]=4;Board[4,7]=3;
Board[4,8]=9;Board[5,0]=1;Board[5,1]=3;Board[5,2]=7;
Board[5,3]=4;Board[5,4]=9;Board[5,5]=6;Board[5,6]=5;
Board[5,7]=8;Board[5,8]=2;Board[6,0]=6;Board[6,1]=9;
Board[6,2]=4;Board[6,3]=1;Board[6,4]=5;Board[6,5]=3;
Board[6,6]=7;Board[6,7]=2;Board[6,8]=8;Board[7,0]=3;
Board[7,1]=2;Board[7,2]=5;Board[7,3]=8;Board[7,4]=7;
Board[7,5]=4;Board[7,6]=9;Board[7,7]=1;Board[7,8]=6;
Board[8,0]=7;Board[8,1]=1;Board[8,2]=8;Board[8,3]=2;
Board[8,4]=6;Board[8,5]=9;Board[8,6]=3;Board[8,7]=5;
Board[8,8]=4;

}

public Status CheckSudokuStatus(int[,] Board)
{
int flag = 0;
for (int rowCheck = 0; rowCheck < 9; rowCheck++)
{
flag = 0;
for (int columnCheck = 0; columnCheck < 9; columnCheck++)
{
if (Board[rowCheck, columnCheck] == 0)
continue;

if ((flag & (1 << Board[rowCheck, columnCheck])) != 0)
return Status.Failure;
flag |= (1 << Board[rowCheck, columnCheck]);
}
}
for (int columnCheck = 0; columnCheck < 9; columnCheck++)
{
flag = 0;
for (int rowCheck = 0; rowCheck < 9; rowCheck++)
{
if (Board[rowCheck, columnCheck] == 0)
continue;
if (((flag & (1 << Board[rowCheck, columnCheck])) != 0))
return Status.Failure;
flag |= (1 << Board[rowCheck, columnCheck]);
}
}
for (int rowCheck = 0; rowCheck < 3; rowCheck++)
{
for (int columnCheck = 0; columnCheck < 3; columnCheck++)
{
BoxCheck(Board, rowCheck* 3, columnCheck * 3);

}
}

return Status.Success;

}
private Status BoxCheck(int[,] Board, int Row, int Coloumn)
{
ArrayList ArrElementsCompare = new ArrayList();
ArrElementsCompare.Clear();
for (int rowIndex = Row; rowIndex < Row + 3; rowIndex++)
{
for (int columnIndex = Coloumn; columnIndex < Coloumn + 3; columnIndex++)
{
if (Board[rowIndex, columnIndex] == 0)
continue;
if (ArrElementsCompare.Contains(Board[rowIndex, columnIndex]))
return Status.Failure;
ArrElementsCompare.Add(Board[rowIndex, columnIndex]);
}
}
return Status.Success;
}

}
}
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Posts Home

About The Author

Unknown
View my complete profile

Total Pageviews

Popular Posts

  • Predicate delegate in C#
    Hello Everyone, In the article we will talk about Predicate delegate. Predicate is also a delegate which encapsulate a method that takes...
  • Clr - Common Language Runtime
    .Net framework provides a run time environment - CLR. Common language runtime takes the IL code from the compiler( language specific) and p...
  • Auto logout chrome extension for Gmail
    Hello Friends, In the last article we learned to create a sample chrome extension. Here we are going to create auto logout Gmail script as...
  • Nagarro Placement Papers..
    Ques.1 :- Seat Reservation prog for the theatre. Write a function for seat allocation for the movie tickets. Total no of seats available are...
  • What does it mean by disconnected data access architecture of ADO.Net?
    ADO.Net introduces the concept of disconnected data architecture. In traditional data access components, you make a connection to the databa...
  • .Net Framework overview
    Hello friends : Here i am writing my first article on .Net framework anyways....So the question is What is .Net Framework ? The .Net fram...
  • Calling the Delegates using Invoke(), BeginInvoke() and DynamicInvoke() ?
    Hello Guys, So in the last article we talked about What is delegate and how can we create a delegate. In this article we will discuss w...
  • C code to Check the string has valid identifier or not in.
    #include #include #include char keyword[][10]={"auto","break","case","char","const","...
  • Garbage Collection - Automatic memory management
    While thinking of this question few things are coming in my mind ~ How .Net reclaims objects and memory used by an application ? So the ans...
  • How to convert 3d array to 1d array ?
    Suppose you have to insert a value at (2,1,0) and the value is :-5 means firstly you have to find the index through (2,1,0) then you have to...

Blog Archive

  • ►  2016 (4)
    • ►  September (2)
      • ►  Sep 03 (2)
    • ►  August (1)
      • ►  Aug 28 (1)
    • ►  April (1)
      • ►  Apr 24 (1)
  • ►  2015 (12)
    • ►  September (10)
      • ►  Sep 30 (1)
      • ►  Sep 29 (1)
      • ►  Sep 28 (1)
      • ►  Sep 27 (2)
      • ►  Sep 26 (3)
      • ►  Sep 20 (1)
      • ►  Sep 19 (1)
    • ►  August (1)
      • ►  Aug 16 (1)
    • ►  March (1)
      • ►  Mar 31 (1)
  • ►  2013 (10)
    • ►  June (1)
      • ►  Jun 16 (1)
    • ►  April (1)
      • ►  Apr 21 (1)
    • ►  February (8)
      • ►  Feb 18 (3)
      • ►  Feb 17 (2)
      • ►  Feb 16 (2)
      • ►  Feb 15 (1)
  • ►  2012 (1)
    • ►  May (1)
      • ►  May 27 (1)
  • ►  2010 (22)
    • ►  October (14)
      • ►  Oct 21 (1)
      • ►  Oct 06 (12)
      • ►  Oct 04 (1)
    • ►  April (2)
      • ►  Apr 22 (1)
      • ►  Apr 16 (1)
    • ►  March (1)
      • ►  Mar 30 (1)
    • ►  January (5)
      • ►  Jan 08 (3)
      • ►  Jan 01 (2)
  • ▼  2009 (110)
    • ►  December (8)
      • ►  Dec 18 (2)
      • ►  Dec 05 (1)
      • ►  Dec 04 (5)
    • ►  November (1)
      • ►  Nov 27 (1)
    • ►  October (14)
      • ►  Oct 09 (4)
      • ►  Oct 07 (1)
      • ►  Oct 06 (3)
      • ►  Oct 05 (3)
      • ►  Oct 01 (3)
    • ►  September (17)
      • ►  Sep 30 (1)
      • ►  Sep 29 (1)
      • ►  Sep 28 (1)
      • ►  Sep 25 (1)
      • ►  Sep 24 (1)
      • ►  Sep 17 (2)
      • ►  Sep 15 (3)
      • ►  Sep 11 (2)
      • ►  Sep 09 (3)
      • ►  Sep 08 (2)
    • ►  August (31)
      • ►  Aug 31 (1)
      • ►  Aug 27 (3)
      • ►  Aug 26 (1)
      • ►  Aug 25 (2)
      • ►  Aug 24 (1)
      • ►  Aug 22 (2)
      • ►  Aug 21 (3)
      • ►  Aug 20 (2)
      • ►  Aug 19 (3)
      • ►  Aug 18 (1)
      • ►  Aug 16 (1)
      • ►  Aug 12 (2)
      • ►  Aug 11 (1)
      • ►  Aug 10 (3)
      • ►  Aug 07 (4)
      • ►  Aug 06 (1)
    • ►  July (24)
      • ►  Jul 25 (4)
      • ►  Jul 24 (20)
    • ▼  April (15)
      • ▼  Apr 10 (3)
        • Window Controls in ASP.Net
        • An Example to create an UserControl to create a ch...
        • How to Send data from a User Control to another us...
      • ►  Apr 07 (9)
        • Nagarro Placement Papers..
        • C Aptitude Questions...
        • C code to Check the string has valid identifier or...
        • Code for matrix problem in C++
        • Implementation of a queue in C++
        • A linked list program in C++
        • OOPS Concepts..
        • OOPS Concepts...
        • 1. What is virtual constructors/destructors?Virtua...
      • ►  Apr 06 (3)
        • How to: Read Image Metadata
        • How to store a record in xml file from a windows f...
        • Sudoku-Checker in ASP.Net using C#

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments
copyright @ TechGiant 2015. Powered by Blogger.

Disclaimer

This is my personal blog and i write articles on .Net, WPF, C#, OOPS, Threading and other .Net technologies. This is not related to any of my employer and organizations. This is the result of my personal interest.

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Followers

Copyright © A Developer Journey who codes for fun | Powered by Blogger
Design by Hardeep Asrani | Blogger Theme by NewBloggerThemes.com