-

Tuesday, May 12, 2020

Find Pair for the sum C#

This problem is about finding two elements from array/list which equal to the given sum value.

Ex:
CASE# 1: source = [1, 2, 3, 9], sum = 8, in this scenario we need to find two elements from the given list/array whose sum is 8, based on permutations you find none of the element's total is 8 so this problem will fail to find the value of sum.

CASE# 2: source = [1, 2, 4, 4], sum = 8, in this scenario we need to find two elements from the given list/array whose sum is 8, based on permutations you find at least a pair whose sum is 8 so this problem will success to find the value of sum.

Here I am going to an efficient solution, which means it'll provide you a solution in minimal iteration/efforts.


  • This is list base operation
        private static bool PairForSumExists(List<int> sourceList, int sum)
        {
            List<int> resultList = new List<int>();
            foreach (int item in sourceList)
            {
                if (resultList.Contains(sum - item))
                    return true;

                resultList.Add(sum - item);
            }
            return false;
        }

  • This is an array base operation
         private static bool PairForSumExists(int[] sourceArray, int sum)
        {
            int[] resultArr = new int[(sourceArray.Length)];
            for (int counter = 0; counter < sourceArray.Length; counter++)
            {
                int item = sourceArray[counter];
                if (resultArr.Contains(sum - item))
                    return true;

                resultArr[counter] = (sum - item);
            }
            return false;
        }


In this way, you can find the solution for the given problem, if you have batter solution then it's my pleasure if you share with me your knowledge.

Of course, I can provide here the explanation for this code written here, I suggest here to debug this code on your own by creating a console application that will provide you batter understanding of this. 
Still, if you have any query/confusion to digest it plz. put your questions/suggestions in the comment box

If you want this code sample then mention in comment section with your email, I'll share on same

Put in the comment section which algorithm you want to appear in my next blog.

Happy coding.

Sunday, May 10, 2020

Sudoku Solving Algorithm

Introduction
Sudoku puzzles are solved by logic and no math is required. As seen on the right, it consists of a grid that is usually made up of nine rows, nine columns, and nine boxes that are separated by thicker, darker lines. Some of these boxes will contain numerals from 1 to 9. To solve the puzzle, a person must fill in all the empty squares without using the same numeral twice in each column, row, or box, and without changing the numerals that are already in the grid.
These puzzles were created to be done using pencil and paper, and there are many books that contain collections of these puzzles with tips and strategies for completing them. They also appear in newspapers and magazines: typically, a different puzzle appears every day, and the solution is printed somewhere else or in the next issue. Later, small handheld machines were created that generate Sudoku puzzles for the user to solve. More recently, though, the game can be played on the Internet or on mobile apps.
You can find more details here

This solution is successfully run and tested on C#
Required assemblies are as follows:
using System;
using System.Linq;

Request sample you can change values as per your case:
char[,] sudokuBoard = new char[,]{{'.', '8', '9', '.', '4', '.', '6', '.', '5'}
                                        ,{'.','7','.','.','.','8','.','4','1'}
                                        ,{'5','6','.','9','.','.','.','.','8'}
                                        ,{'.','.','.','7','.','5','.','9','.'}
                                        ,{'.','9','.','4','.','1','.','5','.'}
                                        ,{'.','3','.','9','.','6','.','1','.'}
                                        ,{'8','.','.','.','.','.','.','.','7'}
                                        ,{'.','2','.','8','.','.','.','6','.'}
                                        ,{'.','.','6','.','7','.','.','8','.'}};

/*Member declaration*/
static int BOARD_START_INDEX = 0, BOARD_SIZE = 9, MIN_VALUE = 1, MAX_VALUE = 9, SUBSECTION_SIZE = 3;

static char NO_VALUE = '.';

public static bool SudokuSolve(char[,] board)
{
     // your code goes here
     for (int row = BOARD_START_INDEX; row < BOARD_SIZE; row++)
     {
           for (int column = BOARD_START_INDEX; column < BOARD_SIZE; column++)
           {
                 if (board[row, column] == NO_VALUE)
                 {
                       for (int assign = MIN_VALUE; assign <= MAX_VALUE; assign++)
                       {
                             board[row, column] = assign.ToString().ToCharArray()[0];
                             if (isValid(board, row, column) && SudokuSolve(board))
                                     return true;
                             board[row, column] = NO_VALUE;
                        }
                        return false;
                 }
           }
     }
     return true;
}

public static bool isValid(char[,] board, int row, int column)
{
     return (rowConstraint(board, row) && columnConstraint(board, column) && subBoardConstraint(board, row, column));
}
public static bool rowConstraint(char[,] board, int row)
{
     bool[] constraint = new bool[BOARD_SIZE];
     return Enumerable.Range(BOARD_START_INDEX, BOARD_SIZE).All(column => checkConstraint(board, row, constraint, column));
}
public static bool columnConstraint(char[,] board, int column)
{
     bool[] constraint = new bool[BOARD_SIZE];
     return Enumerable.Range(BOARD_START_INDEX, BOARD_SIZE).All(row => checkConstraint(board, row, constraint, column));
}
public static bool subBoardConstraint(char[,] board, int row, int column)
{
     bool[] constraint = new bool[BOARD_SIZE];
     int subsectionRowStart = (row / SUBSECTION_SIZE) * SUBSECTION_SIZE;
     int subsectionRowEnd = subsectionRowStart + SUBSECTION_SIZE;

     int subsectionColumnStart = (column / SUBSECTION_SIZE) * SUBSECTION_SIZE;
     int subsectionColumnEnd = subsectionColumnStart + SUBSECTION_SIZE;

     for (int r = subsectionRowStart; r < subsectionRowEnd; r++)
     {
          for (int c = subsectionColumnStart; c < subsectionColumnEnd; c++)
          {
               if (!checkConstraint(board, r, constraint, c)) return false;
           }
      }
      return true;
}
public static bool checkConstraint(char[,] board, int row, bool[] constraint, int column)
{
     if (board[row, column] != NO_VALUE)
     {
          int.TryParse(Convert.ToString(board[row, column]), out int number);
          if (!constraint[number - 1])
          {
               constraint[number - 1] = true;
           }
           else
           {
                return false;
            }
     }
     return true;
}


Of course, I can provide here the explanation for this code written here, I suggest here to debug this code on your own by create a console application that will provide you batter understanding of this. 
Still, if you have any query/confusion to digest it plz. put your questions/suggestions in comment box

If you want this code sample then mention in comment section with you email, I'll share on same

Put in the comment section which algorithm you want to appear in my next blog.

Happy coding.

Wednesday, October 12, 2016

LINQ Single vs SingleOrDefault vs First vs FirstOrDefault

Many people get confused about the difference between Single, SingleOrDefault, First, and FirstOrDefault methods in Linq. Below is a chart explaining the difference between them and examples of each scenario.

Single() SingleOrDefault() First() FirstOrDefault()
Description Returns a single, specific element of a sequence Returns a single, specific element of a sequence, or a default value if that element is not found Returns the first element of a sequence Returns the first element of a sequence, or a default value if no element is found
Exception thrown when There are 0 or more than 1 elements in the result There is more than one element in the result There are no elements in the result Only if the source is null (they all do this)
When to use If exactly 1 element is expected; not 0 or more than 1 When 0 or 1 elements are expected When more than 1 element is expected and you want only the first When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty

Examples

First we create an Employee table for querying. We will test with three difference scenarios:
  • Employeeid = 1: Only one employee with this ID
  • Firstname = Robert: More than one employee with this name
  • Employeeid = 10: No employee with this ID
Employeeid Lastname Firstname Birthdate
1 Davolio Nancy 12/8/1948 12:00:00 AM
2 Fuller Andrew 2/19/1952 12:00:00 AM
3 Leverling Janet 8/30/1963 12:00:00 AM
4 Peacock Margaret 9/19/1937 12:00:00 AM
5 Buchanan Robert 3/4/1955 12:00:00 AM
6 Suyama Michael 7/2/1963 12:00:00 AM
7 King Robert 5/29/1960 12:00:00 AM
8 Callahan Laura 1/9/1958 12:00:00 AM
9 Dodsworth Anne 1/27/1966 12:00:00 AM

Single()


Statement
Employee.Single(e => e.Employeeid == 1)
Expected Result There is only one record where Employeeid == 1. Should return this record.
Actual Result
Employeeid 1
Lastname Davolio
Firstname Nancy
Birthdate 12/8/1948 12:00:00 AM
Statement
Employee.Single(e => e.Firstname == "Robert")
Expected Result There are multiple records where Firstname == Robert. Should fail.
Actual Result InvalidOperationException: Sequence contains more than one element
Statement
Employee.Single(e => e.Employeeid == 10)
Expected Result There is no record with Employeeid == 10. Should fail.
Actual Result InvalidOperationException: Sequence contains no elements

SingleOrDefault()


Statement
Employee.SingleOrDefault(e => e.Employeeid == 1)
Expected Result There is only one record where Employeeid == 1. Should return this record.
Actual Result
Employeeid 1
Lastname Davolio
Firstname Nancy
Birthdate 12/8/1948 12:00:00 AM
Statement
Employee.SingleOrDefault(e => e.Firstname == "Robert")
Expected Result There are multiple records where Firstname == Robert. Should fail.
Actual Result InvalidOperationException: Sequence contains more than one element
Statement
Employee.SingleOrDefault(e => e.Employeeid == 10)
Expected Result There is no record with Employeeid = 10. Should return default value.
Actual Result null

First()


Statement
Employee.OrderBy(e => e. Birthdate)
.First(e => e.Firstname == "Robert")
Expected Result There are multiple records where Firstname == Robert. Should return the oldest one.
Actual Result
Employeeid 5
Lastname Buchanan
Firstname Robert
Birthdate 3/4/1955 12:00:00 AM
Statement
Employee.OrderBy(e => e. Birthdate)
.First(e => e.Employeeid == 10)
Expected Result There is no record with Employeeid = 10. Should fail.
Actual Result InvalidOperationException: Sequence contains no elements

FirstOrDefault()


Statement
Employee.OrderBy(e => e. Birthdate)
.FirstOrDefault(e => e.Firstname == "Robert")
Expected Result There are multiple records where Firstname == Robert. Should return the oldest one.
Actual Result
Employeeid 5
Lastname Buchanan
Firstname Robert
Birthdate 3/4/1955 12:00:00 AM
Statement
Employee.OrderBy(e => e. Birthdate)
.FirstOrDefault(e => e.Employeeid == 10)
Expected Result There is no record with Employeeid = 10. Should return default value.
Actual Result null
This article referred from Technical Overload Posted by Nanthan, Thanks for posting

Tuesday, August 23, 2016

Implementing the Singleton Pattern in C#

Introduction

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.
There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version.
All these implementations share four common characteristics, however:
  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.
Note that all of these implementations also use a public static property Instance as the means of accessing the instance. In all cases, the property could easily be converted to a method, with no impact on thread-safety or performance.

First version - not thread-safe

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance=null;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}
As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}
This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.
Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Third version - attempted thread-safety using double-check locking

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}
This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:
  • It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).
  • Without any memory barriers, it's broken in the ECMA CLI specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it's safe, but I'd rather not rely on those stronger semantics, especially if there's any doubt as to the safety. Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong!
  • It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
  • It still doesn't perform as well as the later implementations.

Fourth version - not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}
As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:
  • It's not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
  • There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
  • The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit. I now have an article with more details about this issue. Also note that it affects performance, as discussed near the bottom of the page.
One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)

Fifth version - fully lazy instantiation

public sealed class Singleton
{
    private Singleton()
    {
    }

    public static Singleton Instance { get { return Nested.instance; } }
      
    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}
Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Sixth version - using .NET 4's Lazy<T> type

If you're using .NET 4 (or higher), you can use the System.Lazy<T> type to make the laziness really simple. All you need to do is pass a delegate to the constructor which calls the Singleton constructor - which is done most easily with a lambda expression.
public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());
  
    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}
It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.

Performance vs laziness

In many cases, you won't actually require full laziness - unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a (relatively) significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class.
A lot of the reason for this page's existence is people trying to be clever, and thus coming up with the double-checked locking algorithm. There is an attitude of locking being expensive which is common and misguided. I've written a very quick benchmark which just acquires singleton instances in a loop a billion ways, trying different variants. It's not terribly scientific, because in real life you may want to know how fast it is if each iteration actually involved a call into a method fetching the singleton, etc. However, it does show an important point. On my laptop, the slowest solution (by a factor of about 5) is the locking one (solution 2). Is that important? Probably not, when you bear in mind that it still managed to acquire the singleton a billion times in under 40 seconds. (Note: this article was originally written quite a while ago now - I'd expect better performance now.) That means that if you're "only" acquiring the singleton four hundred thousand times per second, the cost of the acquisition is going to be 1% of the performance - so improving it isn't going to do a lot. Now, if you are acquiring the singleton that often - isn't it likely you're using it within a loop? If you care that much about improving the performance a little bit, why not declare a local variable outside the loop, acquire the singleton once and then loop. Bingo, even the slowest implementation becomes easily adequate.
I would be very interested to see a real world application where the difference between using simple locking and using one of the faster solutions actually made a significant performance difference.

Exceptions

Sometimes, you need to do work in a singleton constructor which may throw an exception, but might not be fatal to the whole application. Potentially, your application may be able to fix the problem and want to try again. Using type initializers to construct the singleton becomes problematic at this stage. Different runtimes handle this case differently, but I don't know of any which do the desired thing (running the type initializer again), and even if one did, your code would be broken on other runtimes. To avoid these problems, I'd suggest using the second pattern listed on the page - just use a simple lock, and go through the check each time, building the instance in the method/property if it hasn't already been successfully built.
Thanks to Andriy Tereshchenko for raising this issue.

Conclusion (modified slightly on January 7th 2006; updated Feb 12th 2011)

There are various different ways of implementing the singleton pattern in C#. A reader has written to me detailing a way he has encapsulated the synchronization aspect, which while I acknowledge may be useful in a few very particular situations (specifically where you want very high performance, and the ability to determine whether or not the singleton has been created, and full laziness regardless of other static members being called). I don't personally see that situation coming up often enough to merit going further with on this page, but please mail me if you're in that situation.
My personal preference is for solution 4: the only time I would normally go away from it is if I needed to be able to call other static methods without triggering initialization, or if I needed to know whether or not the singleton has already been instantiated. I don't remember the last time I was in that situation, assuming I even have. In that case, I'd probably go for solution 2, which is still nice and easy to get right.
Solution 5 is elegant, but trickier than 2 or 4, and as I said above, the benefits it provides seem to only be rarely useful. Solution 6 is a simpler way to achieve laziness, if you're using .NET 4. It also has the advantage that it's obviously lazy. I currently tend to still use solution 4, simply through habit - but if I were working with inexperienced developers I'd quite possibly go for solution 6 to start with as an easy and universally applicable pattern.
(I wouldn't use solution 1 because it's broken, and I wouldn't use solution 3 because it has no benefits over 5.)

 This article taken from "http://csharpindepth.com/"

Tuesday, September 25, 2012

Create CSV file integration with ASP.NET


Instructions Create a New CSV File

1 Open Windows Notepad to create a new file.

2 Type the following:

1,John Smith,blue

2,Fred Jones,purple

3,Rita Chavez,yellow

4,Belinda Simms,pink

3 Save the file to the root of your C drive as "favcolors.csv" in the "File name" text box.

Create a New Web Project

4 Open Microsoft Visual Studio 2010 and from the "File" menu choose "New Project."

5 Select Visual C# from the "Installed Templates" column and choose "ASP.NET Empty Web Application."

6 Enter a name of your choice in the "Name" text box.

7 Specify a location of your choice in the "Location" text box.

8 Click "OK."

Create the ASP.NET Page

9 Right-click the project name in "Solution Explorer," then click "Add" and "New Item."

10 Select "Web Form" from Visual C# Installed Templates and click "OK"

11 Click the "Design" button to switch to the designer view.

12 Double-click the "ListBox" control under the Standard tab of the Toolbox to add it to the page.

13 Double-click the "Button" control under the Standard tab of the Toolbox to add it to the page.

14 Right-click the button and choose "Properties," and change the Text Property to "Upload."

Write the Code

15 Double-click the button added to the designer page to display the code-behind page.

16 Type the following at the top of the file with other "using" statements:

using System.IO;

17 Type the following code between the opening "{" and closing "}" brackets of the Button1_Click event:

string fileName = @"C:\\favcolors.csv";

using (StreamReader strdr = File.OpenText(fileName))

{

String content;

while ((content = strdr.ReadLine()) != null)

{

ListBox1.Items.Add(content);

}

}

18 Click the "Save All" icon to save your changes.

Test the Program

19 Press "F5" on the keyboard to run the program in Debugging mode.

20 Click the "Upload" button.

21 Check that the names listed in the CSV file display as separate lines in the ListBox control.

for more reference please visit http://www.ehow.com/how_7416148_import-csv-file-asp_net.html

Friday, January 27, 2012

Error: "Parser Error Message: Could not load type 'WebApplication1.Global'." when browsing an asp.net

Introduction
You may receive the following error when browsing an asp.net application "Parser Error Message: Could not load type 'WebApplication1.Global'." Source Error: Line 1: <%@ Application Codebehind="Global.asax.cs" Inherits="'WebApplication1.Global'" %>
Why this error occurs?
This error occurs when you create a new web application in asp.net using visual studio.net and without compiling the application, you try to browse a page in the application. This occurs because of the Application DLL not having been formed. Asp.net will look in the Global Assembly Cache, and then in the application's local bin directory. If it can't find the class with the name you specified then it won't load. When you do a codebehind file in Visual studio, you are writing a base class for your aspx file to inherit from - the HTML template you write in the aspx is inlined into the dynamically generated subclass's Render method. Even if you don't put any code in your page, you still need to compile it as long as you put the Inherts Webappname.Global in your Page directive.
Resolution
To resolve this, Built the application using Ctrl + Shift + B or use F5 to build the application and then try to browse the application. The error will be resolved.
Applies To
This is applicable to .NET 1.0, 1.1 versions - Visual Studio.NET
Thank You

Monday, January 23, 2012

Sql Helper Class in asp.net

Labels: Asp.net, Methods in .net
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.UI;


///
/// Summary description for Dal
///
public class Dal
{

string ConnectionString=string.Empty;
static SqlConnection con;

public Dal()
{
ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
con = new SqlConnection(ConnectionString);
}

public void SetConnection()
{
if (ConnectionString == string.Empty)
{
ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
con = new SqlConnection(ConnectionString);
}

public DataSet ExecuteProcudere(string procName, Hashtable parms)
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
cmd.CommandText = procName;
cmd.CommandType = CommandType.StoredProcedure;
if (con == null)
{
SetConnection();
}
cmd.Connection = con;

if (parms.Count > 0)
{
foreach (DictionaryEntry de in parms)
{
cmd.Parameters.AddWithValue(de.Key.ToString(), de.Value);
}

}
da.SelectCommand = cmd;

da.Fill(ds);
return ds;
}

public int ExecuteQuery(string procName, Hashtable parms)
{
SqlCommand cmd = new SqlCommand();

cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = procName;
if (parms.Count > 0)
{
foreach (DictionaryEntry de in parms)
{
cmd.Parameters.AddWithValue(de.Key.ToString(), de.Value);
}

}
if (con == null)
{
SetConnection();
}
cmd.Connection = con;
if (con.State == ConnectionState.Closed)
con.Open();

int result=cmd.ExecuteNonQuery();

return result;

}


public int ExecuteQuerywithOutputparams(SqlCommand cmd)
{
if (con == null)
{
SetConnection();
}
cmd.Connection = con;
if (con.State == ConnectionState.Closed)
con.Open();

int result = cmd.ExecuteNonQuery();

return result;

}

public int ExecuteQueryWithOutParam(string procName, Hashtable parms)
{
SqlCommand cmd = new SqlCommand();
SqlParameter sqlparam = new SqlParameter();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = procName;
if (parms.Count > 0)
{
foreach (DictionaryEntry de in parms)
{
if (de.Key.ToString().Contains("_out"))
{
sqlparam = new SqlParameter(de.Key.ToString(),de.Value);
sqlparam.DbType = DbType.Int32;
sqlparam.Direction = ParameterDirection.Output;
cmd.Parameters.Add(sqlparam);
}
else
{
cmd.Parameters.AddWithValue(de.Key.ToString(), de.Value);
}
}

}
if (con == null)
{
SetConnection();
}
cmd.Connection = con;
if (con.State == ConnectionState.Closed)
con.Open();

int result = cmd.ExecuteNonQuery();

if (sqlparam != null)
result = Convert.ToInt32(sqlparam.SqlValue.ToString());
return result;
}
}

Saturday, January 21, 2012

.NET Generics

By Akash Maru
When we look at the term "generic", unrelated to the programming world, it simply means something that is not tied to any sort of brand name. For example, if we purchase some generic dish soap, soap that has no brand name on it, we know that we are buying dish soap and expect it to help us clean our dishes, but we really don't know what exact brand (if any) will be inside the bottle itself. We can treat it as dish soap even though we don't really have any idea of its exact contents.
Think of Generics in this manner. We can refer to a class, where we don't force it to be related to any specific Type, but we can still perform work with it in a Type-Safe manner. A perfect example of where we would need Generics is in dealing with collections of items (integers, strings, Orders etc.). We can create a generic collection than can handle any Type in a generic and Type-Safe manner. For example, we can have a single array class that we can use to store a list of Users or even a list of Products, and when we actually use it, we will be able to access the items in the collection directly as a list of Users or Products, and not as objects (with boxing/unboxing, casting).
"Generic" Collections as we see them today
Currently, if we want to handle our Types in a generic manner, we always need to cast them to a System.Object, and we lose any benefit of a rich-typed development experience. For example, I'm sure most of us are familiar with the System.Collection.ArrayList class in Framework v1 and v1.1. If you have used it at all, you will notice a few things about it:
1. It requires that you store everything in it as an object

public virtual int Add(object value);
public virtual object this[int index] {get; set;}


2. You need to cast up in order to get your object back to its actual Type 3. Performance is really lacking, especially when iterating with foreach()
4. It performs no type safety for you (no exceptions are thrown even if you add objects of different types to a single list)

System.Collections.ArrayList list = new System.Collections.ArrayList();

list.Add("a string");
list.Add(45); //no exception thrown
list.Add(new System.Collections.ArrayList()); //no exception

foreach(string s in list) { //exception will be thrown!
  System.Console.WriteLine(s);
}

For some situations we may feel the need to implement IEnumerable and IEnumerator in order to create a custom collection of our given Type, that is, a Type-safe collection for our needs. If you had a User object, you could create another class (which implements IEnumerable and IEnumerator, or just IList) that allows you to only add and access User objects, even though most implementations will still store them as objects. It is a lot of work implementing these two interfaces, and you can imagine the work needed to create this additional collection class every time you wanted a Type-safe collection. The third and final way of creating a collection of items is by simply creating an array of that type, for example:


string[] mystrings = new string[]{"a", "b", "c"};

This will guarantee Type safety, but is not very reusable nor very friendly to work with. Adding a new item to this collection would mean needing to create a temporary array and copy the elements into this new temporary array, resizing the old array, copying the data back into it, and then adding the new item to the end of that collection. In my humble opinion, this is too much work that tends to be very error prone. What we need is a way to create a Type-safe collection of items that we can use for any type imaginable. This template, or generic class, should be able to perform all of the existing duties that we need for our collections: adding, removing, inserting, etc. The ideal situation is for us to be able to create this generic collection functionality once and never have to do it again. You must also consider other types of collections that we commonly work with and their functionality, such as a Stack (First in, Last out) or a Queue (First In, First out), etc. It would be nice to be able to create different types of generic collections that behave in standard ways.
In the next I will show you how to create your first Generic Type.
Creating Our First Generic Type
In this section we will create a very simple generic class and demonstrate how it can be used as a container for a variety of other Types. Below is a simple example of what a generic class could look like:

public class Col<T> 
{
  T t;
  public T Val{get{return t;}set{t=value;}}
}

There are a few things to notice. The class name "Col<T>" is our first indication that this Type is generic, specifically the brackets containing the Type placeholder. This Type placeholder "T" is used to show that if we need to refer to the actual Type that is going to be used when we write this class, we will represent it as "T". Notice on the next line the variable declaration "T t;" creates a member variable with the type of T, or the generic Type which we will specify later during construction of the class (it will actually get inserted by the Common Language Runtime (CLR) automatically for us). The final item in the class is the public property. Again, notice that we are using the Type placeholder "T" to represent that generic type for the type of that property. Also notice that we can freely use the private variable "t" within the class. In order to use this class to hold any Type, we simply need to create a new instance of our new Type, providing the name of the Type within the "<>" brackets and then use that class in a Type-safe manner. For example:

public class ColMain 
{
  public static void Main() 
    {
 //create a string version of our generic class
    Col<string> mystring = new Col<string>();
 //set the value
    mystring.Val = "hello";
    
 //output that value
    System.Console.WriteLine(mystring.Val);
 //output the value's type
    System.Console.WriteLine(mystring.Val.GetType());
    
 //create another instance of our generic class, using a different type
    Col<int> myint  = new Col<int>();
 //load the value
    myint.Val = 5;
 //output the value
    System.Console.WriteLine(myint.Val);
 //output the value's type
    System.Console.WriteLine(myint.Val.GetType());
    
  }
}


When we compile the two classes above and then run them, we will see the following output:

hello
System.String
5
System.Int32

Even though we used the same class to actually hold our string and int, it keeps their original type intact. That is, we are not going to and from a System.Object type just to hold them. Generic Collections
The .NET team has provided us with a number of generic collections to work with in the the latest version of the .NET Framework. List, Stack, and Queue are all going to be implemented for us. Let's see an example on how to use the provided Generic List class.
For this example we want to be able to hold a collection of a Type that we create, which we used to represent a User in our system. Here is the definition for that class:

namespace Rob {
  public class User {
    protected string name;
    protected int age;
    public string Name{get{return name;}set{name=value;}}
    public int Age{get{return age;}set{age=value;}}
  }
}

Now that we have our User defined, let's create an instance of the .NET Framework Generic version of a simple List:

System.Collections.Generic.List<Rob.User> users 
= new System.Collections.Generic.List<Rob.User>();

Notice the new "Generic" namespace within the System.Collections namespace. This is where we will find all the new classes for our use. The "List" class within that namespace is synonymous with the typical System.Collections.ArrayList class, which I'm sure most of us are very familiar with by now. Please note that although they are similar there are several important differences. So now that we have a Type-safe list of our User class, let's see how we can use this class. What we will do is simply loop 5 times and create a new User and add that User to our users collection above:

    for(int x=0;x<5;x++) {
      Rob.User user = new Rob.User();
      user.Name="Rob" + x;
      user.Age=x;
      users.Add(user);
    } 

This should seem straight forward to you by now. In the next step we will iterate over that same collection and output each item to the console:

foreach(Rob.User user in users) {
     System.Console.WriteLine(
System.String.Format("{0}:{1}", user.Name, user.Age)
);
}

This is slightly different that what we are used to. What you should notice right off the bat is that we do not have to worry about the Type being "Rob.User". This is because our generic collection is working in a Type-safe manner; it will always be what we expect. Another way to output the same list would be to use a simple for() loop instead, and in this case we do not have to cast the object out of the collection in order to use it properly:

for(int x=0;x<users.Count;x++) {
System.Console.WriteLine(
System.String.Format("{0}:{1}", users[x].Name, users[x].Age)
);
}

No more silly casting or boxing involved. Here is the complete listing of the source plus the output of the result of executing the console application: User.cs

namespace Rob {
  public class User {
    protected string name;
    protected int age;
    public string Name{get{return name;}set{name=value;}}
    public int Age{get{return age;}set{age=value;}}
  }
}

Main.cs

public class M {
  public static void Main(string[] args) {
    System.Collections.Generic.List<Rob.User> users = new System.Collections.Generic.List<Rob.User>();
    for(int x=0;x<5;x++) {
      Rob.User user = new Rob.User();
      user.Name="Rob" + x;
      user.Age=x;
      users.Add(user);
    }

    foreach(Rob.User user in users) {
      System.Console.WriteLine(System.String.Format("{0}:{1}", user.Name, user.Age));
    }
    System.Console.WriteLine("press enter");
    System.Console.ReadLine();

    for(int x=0;x<users.Count;x++) {
      System.Console.WriteLine(System.String.Format("{0}:{1}", users[x].Name, users[x].Age));
    }
    
  }
}


Output


Rob0:0
Rob1:1
Rob2:2
Rob3:3
Rob4:4
press enter

Rob0:0
Rob1:1
Rob2:2
Rob3:3
Rob4:4


More on Generics


more Generics features in the latest release of the .NET Framework
include Generic Methods and Constraints.  A generic method is very 
straight forward. Consider this example:



public static T[] CreateArray<T>(int size) {
 return new T[size];
}



This static method simply creates a method of the given Type "T" and of 
the given "size" and returns it to the caller.  An example of calling 
this method would be:

string[] myString = CreateArray<string>(5);


This will new up an instance of our string array, with an initial size 
of 5.  You should take time to investigate the new version of the 
framework.  You will be surprised at all the little helpful features 
like this.  

Lastly, we should take a quick look at constraints.  A constraint is 
setup to limit the Types which the Generic can accept.  Let's say for 
example we had a generic type:



public class Dictionary<K, V> where K : IComparable {}



Notice the "where" clause on this class definition.  It is forcing the K
 Type to be of Type IComparable.  If K does NOT implement IComparable, 
you will get a Compiler error.  Another type of constraint is a 
constructor constraint:

public class Something<V> where V: new() {}


In this example V must have at least the default constructor available, if not the Compiler will throw an error.

Monday, November 7, 2011

C Language Quiz

1) The correct order of compilation of a C program is

i) Compile source code to object code
ii) Link object code and libraries
iii) Create binary or executable file
iv) Process Preprocessor directives

A) i → ii → iii → iv
B) iv → i → ii → iii
C) i → iv → ii → iii

Answer: Preprocessor directives are processed first, followed by compilation, linking and binary file
creation.

2) Which of the following data type can be used for storing a floating point constant?

A) long int
B) double
C) unsigned char

Answer: float & double data types can be used for storing floating point constants in C

3) What is the result of running the following code snippet?

float result;
result = 5/2;
printf("%.1f",result);
A) 2.0
B) 2.5
C) 0

Answer: Division of two integer constants results in an integer in C. So 5/2 becomes 2. As the output is
printed in %.1f format, it is printed as 2.

4) What is the result of running the following code snippet

if(0)
printf("The Sun rises in the East");
else
printf("The Sun rises in the West");
A) The Sun rises in the East
B) The Sun rises in the West
C) Compilation Error

Answer: Non-zero is considered true and zero is false in C. So the statement in else is printed

5) What is the value of variable ‘i’ after running the following statements?

int i = 10;
i = i / 2;
i = i % 2;
A) 0
B) 1
C) 2

Answer: 10/2 is 5. 5%2 is 1. % is modular division operator

6) The purpose of the function int toupper (int c) as defined in ctype.h is to

A) Convert the input string stored in variable c to upper case
B) Convert the input character stored in variable c to upper case
C) None of the above

Answer: toupper converts input character to upper case. Even none of the above is awarded marks as
there is ambiguity in answers A, B. The answers were meant to mean “Convert the input character
stored in variable c to upper case.” The answers give a wrong meaning like “Convert the input character
‘c’ to upper case. Like ‘c’ to ‘C’ ”.

7) The difference between the user defined constants ‘Z’ and “Z” is

A) ‘Z’ is a string constant whereas “Z” is a character constant
B) ‘Z’ is a character constant whereas “Z” is a string constant
C) There is no difference

Answer: Character constants are enclosed within single inverted comma or apostrophe ‘. Whereas,
strings in C are enclosed within double inverted commas “.

8) Output of running the following code snippet is

int i;
for ( i = 0; i < 3; i++ )
{
if(i == 2)
{
printf("%d\t",i);
}
}
A) 0 1 2 3
B) 0 1 2
C) 2

9) The conversion character for printing an integer in hexadecimal number using printf is

A) %x
B) %d
C) %o

10) Output of following code snippet

float marks[10] = {53,66,36,36,53,23,64,12,53,88};
float *marksPtr = marks;
marksPtr = marksPtr + 4;
printf("%.0f", *marksPtr);
A) 0
B) 53
C) 36
D) Garbage value

Answer: marksPtr + 4 points to the 5th element in array. Therefore 53

11) Which of the following is the correct way to allocate space for an array of 15 float variables?

A) float *floatArray = (float *) malloc ( 15 );
B) float floatArray = (float *) malloc ( 15 );
C) float *floatArray = (float *) malloc ( 15 * sizeof(float) );
D) float *floatArray = 15 * malloc (sizeof(float) );


Answer: This is syntax of malloc

12) The following C statement causes an infinite loop (true/false):

while (1);
A) true
B) false

Answer: 1 is true. So while gets stuck in an infinite loop

13) Output of the following code snippet is:

int array[] = {1,2,3,4,5};
printf("%d", array[5]);
A) 0
B) 4
C) 5
D) Garbage value

Answer: array[5] refer to 6th element in the array. Hence garbage value

14) Output of following statement is:

#define NUM 5
int main()
{
NUM++;
printf("%d", NUM);
return 0;
}
A) 5
B) 6
C) Compilation error

Answer: NUM is a symbolic constant. A constant’s value can’t be modified

15) Output of the following statement is

int i = 5;
if(i = 5)
{
puts("Structured programming language");
}
else
{
puts("Object oriented programming language");
}
A) Structured programming language
B) Object oriented programming language
C) Compilation error

Answer: i=5 is an assignment, not a comparison. Hence the statement becomes if(5) and hence prints
statement in if block

16) Which of the following is a true statement?

A) Strings in C are char arrays terminated by ‘\0’
B) Strings in C are char arrays terminated by NULL
C) Strings in C are char arrays terminated by EOF

17) Which of the following is a NOT a true statement?

A) The base address of an array is same as the name of the array
B) The base address of an array is address of the first element in the array
C) The base address of a static array can be modified

18) Which of the following is true about break statement in C?

A) break statement exits out of the innermost loop nested around it
B) break statement exits out of all the outer loops nested around it
C) break statement skips one iteration and continues looping

Answer:
Consider a loop
for(i=0; i<5;i ++)
for(j=0;j<6;j++)
break;
break statement exits out of the inner most loop nested around it.

19) Output of the following program is:

int main()
{
int i =0;
modify(i);
printf("%d", i );
return 0;
}

int modify(int z)
{
return (++z);
}
A) 0
B) 1

Answer: A copy of i is sent to the function modify, hence changes to that copy are not reflected in i. Call
by value concept

20) Point out at least two errors in the following code snippet

float a;
scanf("Enter number: %f", a );


Answer:
1. String “Enter number” can’t be entered in scanf format string
2. & is missing for a. it should have been scanf("%f", & a );
3. Semicolon missing at the end of the statemen

For more references about fundamentals prectical concepts kindly visit: http://www.interviewmantra.net
This site give you solutions about JAVA, C,C++__Thank you

Tuesday, October 12, 2010

What is Junagadh...?

An impressive fort, Uperkot, located on a plateau in the middle of town, was originally built during the
Mauryan dynasty by Chandragupta
in 319 BCE The fort remained in use until the 6th century, when it was covered over for 300 years, then rediscovered in 976 CE The fort was besieged 16 times over an 800-year period. One unsuccessful siege lasted twelve years.[1]

An inscription with fourteen Edicts of Ashoka is found on a large boulder within 2 km of Uperkot Fort[2]. The inscriptions carry Brahmi script in Pali language and date back to 250 BCE On the same rock are inscriptions in Sanskrit added around 150 CE by Mahakshatrap Rudradaman I, the Saka (Scythian) ruler of Malwa, a member of the Western Kshatrapas dynasty[3]. Another inscription dates from about 450 CE and refers to Skandagupta, the last Gupta emperor. Old rock-cut Buddhist "caves" in this area, dating from well before 500 CE, have stone carvings and floral work. There are also the Khapra Kodia Caves north of the fort, and the Babupyana Caves south of the fort.

The Maitraka dynasty ruled Gujarat in western India from 475 to 767 CE The founder of the dynasty, general Bhatarka, a military governor of Saurashtra peninsula under the Gupta empire, established himself as the independent ruler of Gujarat approximately in the last quarter of the 5th century[4]. However, James Tod states Maitraka rule ended as early as 524 CE[5].

Wednesday, September 22, 2010

'Mother' who is dosen't wrong...


One upon a time in history...
            A Mother who gives life to another and helps him/her to growth..
            A great king and of course Gladiator named ‘SIKANDAR’ was won him battle and comeback to home at the time his mother says – “you come back my son from war and by the blessing of god you won...”
            At that moment a great warrior repaid to his mother...
”mother , I am the great King “SIKANDAR” and ruler of the world who won the whole world and no one can got won over myself and you told  me son? You are insulting me with saying this kind of sentence”
            Mother replies to great Gladiator that ok my son I will call you only “SIKANDAR” , now days...
            After some days....
            In a great war The SIKANDAR got died...
            Mother of The Sikandar visit graveyard and went to ‘Sikandar’s’ grave and says ‘The Great Gladiator SIKANDAR  I miss you....

            At the time sound came out from Grave and says....
            Mother don’t  call me ‘SIKANDAR’ because after death I realise that ‘THE GREAT WARRIOR THEN ME ARE HERE but at last they are someone’s son
            So You call me only “MY SON”  not “SIKANDAR” that is the reality of the life...
            The definition of RELATION never be change...
May status will be vary...
                                                                                                            Thanking you,
                                                                                                            Akash J Maru