Search (Article Or Program)

07 October 2014

Read & Insert Data Using Stored Procedures in C#

This article will show you in a simple manner how to read data from SQL data base by using stored procedures and how to insert data through a stored procedure.

Background

There is a description to explain how to write stored procedures as well. Since it is a complex area for beginners I have explained it in very simple manner.

Using the code

Step 1 : Create the table(user_tab) to insert data
CREATE TABLE [dbo].[user_tab](
    [U_name] [varchar](50) NULL,
    [U_pwd] [varchar](50) NULL,
    [U_type] [varchar](10) NULL
)

Step 2 : Create the stored procedure to insert data to user table
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE AddUser
    @name varchar(50),
    @pwd varchar(50),
    @type varchar(10)
AS
BEGIN

    SET NOCOUNT ON;

    insert into user_tab (U_name,U_pwd,U_type)
    values(@name,@pwd,@type)

END
GO

Step 3 :Add windows form
Create a windows form to enter the details which we are going to save in database.
textbox1=> to enter name
textbox2=> to enter password
combobox => to select user type
button(btnSave)=> to save data to database through stored procedure


Step 3 : Add a class called DBConnect
class DBConnect
    {
        public static SqlConnection myCon = null;

        public void CreateConnection()
        {
            myCon = new SqlConnection("Data Source=GAYANI-PC;Initial Catalog=soft1;Integrated Security=True");
            myCon.Open();

        }
    }

Step 4 : Button click event
Click on button. Then add this code inside that event.
private void btnAdd_Click(object sender, EventArgs e)
        {
            SqlConnection con = DBConnect.myCon;
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = "Execute AddUser @name,@pwd,@type";

            cmd.Parameters.Add("@name", SqlDbType.VarChar, 50).Value = textBox1.Text.ToString();
            cmd.Parameters.Add("@pwd", SqlDbType.VarChar, 50).Value = textBox2.Text.ToString();
            cmd.Parameters.Add("@type", SqlDbType.VarChar, 10).Value = comboBox1.Text.ToString();
            
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            
        }
You can insert data to the database now ! Check it.

Step 5 : Stored procedure to Read data
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE ReadUser
    
AS
BEGIN
    
    SET NOCOUNT ON;

    select U_name,U_type from user_tab
END
GO

Step 6 : Read data through Stored procedure(ReadUser) and display on a grid view
public void LoadGrid()
        {
            SqlConnection con = DBConnect.myCon;
            SqlDataReader rd;

            using(con)
            {
                SqlCommand cmd = new SqlCommand("ReadUser",con); // Read user-> stored procedure name
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    dataGridView1.Rows.Add(rd[0].ToString(), rd[1].ToString()); //gridview has 2 columns only(name, type)
                }
                rd.Close();
            }
            con.Close();
        }

Step 7 : Call above method to form load event or any button click event.
private void Form1_Load(object sender, EventArgs e)
        {
            this.LoadGrid();           
        }
 Now you can read and insert data through a stored procedure.


, 6 Oct 2014  on codeproject

30 January 2014

15 hot programming trends -- and 15 going cold


Programming trends that might surprise the boss, but shouldn't surprise you in the year ahead

Programmers love to sneer at the world of fashion where trends blow through like breezes. Skirt lengths rise and fall, pigments come and go, ties get fatter, then thinner. But in the world of technology, rigor, science, math, and precision rule over fad.
That's not to say programming is a profession devoid of trends. The difference is that programming trends are driven by greater efficiency, increased customization, and ease-of-use. The new technologies that deliver one or more of these eclipse the previous generation. It's a meritocracy, not a whimsy-ocracy.
What follows is a list of what's hot -- and what's not -- among today's programmers. Not everyone will agree with what's A-listed, what's D-listed, and what's been left out. But that's what makes programming an endlessly fascinating profession: rapid change, passionate debate, sudden comebacks.
Hot: Preprocessors
Not: Full language stacks

24 January 2014

How to write a scientific calculator with an implementation in c++


Table of contents 

1. Abstract 
2. Introduction
3. Coding Mathematics' problems 
3.1. Inputs' wide possibilities 
3.2. Agreement of input formulas with standard rules of math.
3.3. Length of input formula  
 4. Overview on the Implementation
4.1. Data class
4.2.   MyChecker class 
4.3.   MyFixer class 
4.4.   Calculator class  
5. How to use the implementation  
6. Appendix  
6.1. Linked lists  
6.2. Bisection method    
7. conclusion   

 

1. Abstract  

Have you tried before to put the upper formula in one of your program, but you found its hard to calculate it? Have you stopped codding one of your programs because you need to treat with complex formulas and their isn't a route to calculate it in your programming language? have you gone to use programming language such as fortran or mathlab, because you need to use some of its mathematical power, as the same time if you have this power in your main language you may produce a better program? If you are one these slides I have told about, this article will be good for you inshallah as its give you two solutions to your problems; the first is how to program mathematical programs and the second a header file in c++ that you can use in order to calculate formula such as which in Fig.1, in order to facility your creative c++ program.   

2. Introduction  

Mathematical programming is the backbone of any programming language and the one of the most important reasons to invite computers and with subordination programming language, that is because all science in the world are depending on mathematics, so needing of easier routes to do it is continue one of the most required things in these days and will still obtainable until the end of the world, so from this point we are starting in order to implement a scientific calculator coded by myself me and will be coded by your self in the coming days inshallah, except you don't wanna.
In c++ there is some libraries work on mathematics such as math.h and c math, but these libraries don't give you all operations you may need, but at the same time they are the soul which we plant our implementation on.   

19 December 2013

Shoot'em Up .NET


Before Introduction

If you only want to download the code and see what's happening, then the important things are:
  • There's a solution for Silverlight 5 and one for WPF, but most units are simply used by both;
  • The game uses the directional keys to move, Space to shot and either EscP or Enter to pause;
  • The game has three levels. Between the levels you may acquire upgrades to your ships, so if you think the initial ships are too weak, well, that's on purpose.
You can play the Silverlight game by opening this link:http://paulozemek.azurewebsites.net/ShootEmUpTestPage.2013_10_10.html
Or you can download the WPF version by clicking on the next image:

Introduction

I know that many programmers would love to write games. I myself started to program computers because I wanted to create games and, even if I already wrote some games, I've spent most of my time dealing with systems and solving problems related to database connectivity and better caching mechanisms.
One of the problems I see to write games is the lack of material. In my particular case, I usually look for graphics and sounds, as those are the things that I am not able to do. Yet, I think there's missing material for games in general. It is hard to find game tutorials and, when I find something, I only see material to write games using XNA or Unity. There is almost no material on how to write games using WPF or Silverlight or other similar technologies.
And, considering that I usually write games using those technologies, I though it will be a good idea to present a solution on how to write games using non-game specific technologies.

Why not use XNA or Unity?

My idea on writing games without using XNA or Unity is to show that you can use normal UI technologies to write games, which in many cases simplify the job as you don't need to care about how to render things to the screen or to recreate layout controls. Also, by doing this you will be able to create games without having to install such libraries/engines and you will be able to write games even for Windows 8, as using C# + XAML(which is what I am going to use in this article) is a trait of SilverlightWPF and of Windows 8 applications.

16 September 2013

Create Tic Tac Toe Game


Hello Guys, I am going to show you How to Create Tic Tac Toe for 2-Players.
Before Going to start, a short description on What is Tic Tac Toe?
Tic-tac-toe (or Noughts and crossesXs and Os) is a paper and pencil for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three respective marks in a horizontal, vertical, or diagonal row wins the game.

Let's Start:

Create a New project and select windows application.Give it name and then press enter.(All of us know this step).
After that you see a blank form like that:
image1
Now add 9 buttons on your form using tools.
image2

Select button then delete the text from properties(i.e. button1,button2).Actually we want no text on buttons.
Now, Put a label on your form set backcolor according to your wish(here i choose skyblue color from properties), set textalign to middlecenter and set text to "Turn".Actually We are creating a box for showing the player's Turn.

11 September 2013

Short Intro of OOP and Its Basic Principle

What is OOP?
OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects". Hence, you gain re-usability by means of four main object-oriented programming concepts.
In order to clearly understand the object orientation, let’s take your “hand” as an example. The “hand” is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it.

Basic Principle of oops:- There are main three core principles of  any object oriented languages.
  • ENCAPSULATION:- Encapsulation provides the ability to hide the internal details of an object from its users.The concept of encapsulation is also known as data hiding or information hiding. In c# , Encapsulation is implemented using the access modifier keywords.
  1. Public
  2. Private
  3. protected
  4. Internal
  5. Protected Internal
    • POLYMORPHISM:- It is also concept of oops. It is ability to take more than one form. An operation may exhibit different behaviour in different situations.                       Ex:-  An addition operation involving two numeric values will produce sum and the same addition operation will produce a string.If we pass parameter numeric value then method return sum(numeric value) and if we pass parameter  String then same method is return string value .this called Polymorphism.
    • INHERITANCE:-  One class can include the feature of another class by using the concept of inheritance.In c# a class can be inherit only from one class at a time.Whenever we create class that  automatic inherit from System.Object class,till the time the class is not inherited from any other class.

    Easy Guide to Method Overriding in C#


    Method Overriding in C#

    When one class inherit from another class ,all the member of parent class become the member of child class .If there is a method of parent class that we want to predefined in child class. we can implement the concept of method overriding ,it means a method overriding of parents class and child class can have same method name with same parameter but parent class method will have "VIRTUAL"Keyword and child class method have "OVERRIDE"Keyword.


    EXAMPLE:-
    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    using System;
    namespace methodoverriding
    {
        class Program
        {
            static void Main(string[] args)
            {
                employee obj = new employee();
                obj.display();
                Console.ReadLine();
            }
        }
    public class cls
    {
        public virtual void display()
        {
            Console.WriteLine("hello");
        }
    }
    public class employee : cls
    {
        public override void display()
        {
            Console.WriteLine("welcome");
        }
    }
    }

    Description:- Here ,I have maked the object of employee class. The display method of only employee class will get in memory,because the "display method" of cls  class has been over-hidden by the employee class.

    Follow these steps to run this program:-

    Step1:- Open your visual studio and go File->New Project->Click Console Application.
    See it:-



    Step2:- copy the whole program code in program.cs file.
    See it:-

    Step3:-  Now Run the Application(Press F5).
    OUTPUT:-


    I hope this is helpful for you

    ref: http://www.msdotnet.co.in/2012/06/method-overriding-in-c.html

    How to Create Setup file of Windows Forms Application in VS 2010


    How to Create Setup file(.Exe File) from Windows Forms Application

    This is the most important tutorial for creating the Setup File(.exe file) from windows forms application.You can easily install it any windows computers.You can use it only windows platform.

    Now i am going to convert these windows forms application to the Setup File. Friends who have not read my previous tutorials please read  first this tutorial and download it, otherwise you will not understand correctly.For read the previous tutorial .
    There are some steps to create Setup File From windows forms applications. please follow these steps carefully. 

    Step1:-  First open your windows form application in your visual studio.Here i am using visual studio 2010 and my windows forms application Name is "test",which had made in previous tutorial.you can download it Clickdownload. 
    Now i am going to open "test" application in visual studio 2010,my "test" application is on desktop. See it carefully and open your application together.



    How can Take Print Receipt and Save the Data in Database in Windows Forms Application


    Hi friends, here i am going to make an Application "how can take Print Receipt and save data in database in windows Forms application".This project is very helpful for your Real Time Project Development and you can achieve more knowledge from this projects. You can download whole Application from the bottom of this page.
    There are some steps ,Please follow it 
    Step1:- Open your visual studio-> File->Click New Project->Select Windows Forms Application  -> Select c#language from left window->write your application name->click OK.

    24 July 2013

    162 questions for C# Developer jobs



    Learn C# (Sharp) Programming Language by Interview Questions and Answers
    What's C#?
    Is it possible to inline assembly or IL in C# code? 
    Is it possible to have different access modifiers on the get/set methods of a property in C#?
    Is it possible to have a static indexer in C#?
    If I return out of a try/finally in C#, does the code in the finally-clause run? 
    I was trying to use an out int parameter in one of my functions. How should I declare the variable that I am passing to it? 
    How does one compare strings in C#? 
    How do you specify a custom attribute for the entire assembly (rather than for a class)? 
    How do you mark a method obsolete? 
    10 How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#? 
    11 How do you directly call a native function exported from a DLL? 
    12 How do I simulate optional parameters to COM calls?
    13 The C# keyword .int. maps to which .NET type? 
    14 Which of these string definitions will prevent escaping on backslashes in C#? 
    15 Which of these statements correctly declares a two-dimensional array in C#? 
    16 If a method is marked as protected internal who can access it? 
    17 What is boxing in C#? 
    18 What compiler switch creates an xml file from the xml comments in the files in an assembly? 
    19 What is a satellite assembly in C#? 
    20 What is a delegate in C#? 
    21 How does assembly versioning in .NET prevent DLL Hell? 
    22 Which .Gang of Four. design pattern is shown below? 
    23 In the NUnit test framework, which attribute must adorn a test class in order for it to be picked up by the NUnit GUI? 
    24 Which of the following operations can you NOT perform on an ADO.NET DataSet? 
    25 In Object Oriented Programming, how would you describe encapsulation in C#? 
    26 What do you know about .NET assemblies?
    27 What is the difference between private and shared assembly?
    28 What is a strong name in C#?
    29 How can you tell the application to look for assemblies at the locations other than its own install?
    30 How can you debug failed assembly binds?
    31 Where are shared assemblies stored?
    32 How can you create a strong name for a .NET assembly?
    33 Where is global assembly cache located on the system?
    34 Can you have two files with the same file name in GAC?
    35 So lets say I have an application that uses MyApp.dll assembly ...
    36 What is delay signing?
    37 Is there an equivalent of exit() for quitting a C# .NET application?
    38 Can you prevent your class from being inherited and becoming a base class for some other classes?
    39 If a base class has a bunch of overloaded constructors ...
    40 I was trying to use an "out int" parameter in one of my functions. How should I declare the variable that I am passing to it?
    41 How do I make a DLL in C#?
    42 Will finally block get executed if the exception had not occurred?
    43 What is the C# equivalent of C++ catch (), which was a catch-all statement for any possible exception? Does C# support try-catch-finally blocks?
    44 Is there regular expression (regex) support available to C# developers?
    45 Is there a way to force garbage collection?
    46 Does C# support properties of array types?
    47 What connections does Microsoft SQL Server support?
    48 What is a satellite assembly?
    49 How is method overriding different from overloading?
    50 When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?
    51 Why would you use untrusted verification?
    52 What is the implicit name of the parameter that gets passed into the class set method?
    53 How do I register my code for use by classic COM clients?
    54 How do I do implement a trace and assert?
    55 How do I create a multilanguage, multifile assembly?
    56 C# provides a default constructor for me. I write a constructor that takes a string as a parameter ...
    57 What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development?
    58 Explain ACID rule of thumb for transactions.
    59 Where is the output of TextWriterTraceListener redirected?
    60 How do I create a multilanguage, single-file assembly?
    61 Why cannot you specify the accessibility modifier for methods inside the interface?
    62 Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace?
    63 Why do I get a syntax error when trying to declare a variable called checked?
    64 Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
    65 What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)?
    66 Why do I get a "CS5001: does not have an entry point defined" error when compiling?
    67 What does the keyword virtual mean in the method definition?
    68 What optimizations does the C# compiler perform when you use the /optimize+ compiler option?
    69 How can I create a process that is running a supplied native executable (e.g., cmd.exe)?
    70 What is the difference between the System.Array.CopyTo() and System.Array.Clone()?
    71 How do I declare inout arguments in C#?
    72 Is there a way of specifying which block or loop to break out of when working with nested loops?
    73 What is the difference between const and static read-only?
    74 What does the parameter Initial Catalog define inside Connection String?
    75 What is the difference between System.String and System.StringBuilder classes?
    76 What is the top .NET class that everything is derived from?
    77 Can you allow class to be inherited, but prevent the method from being over-ridden?
    78 Can you change the value of a variable while debugging a C# application?
    79 Are private class-level variables inherited?
    80 Can you inherit multiple interfaces?
    81 From a versioning perspective, what are the drawbacks of extending an interface as opposed to extending a class?
    82 Which one is trusted and which one is untrusted?
    83 What namespaces are necessary to create a localized application?
    84 Does Console.WriteLine() stop printing when it reaches a NULL character within a string?
    85 What is the advantage of using System.Text.StringBuilder over System.String?
    86 What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
    87 Why do I get a security exception when I try to run my C# app?
    88 Is there any sample C# code for simple threading?
    89 What is the difference between // comments, /* */ comments and /// comments?
    90 What is the difference between and XML documentation tag?
    91 Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
    92 How do you inherit from a class in C#?
    93 How do I port "synchronized" functions from Visual J++ to C#?
    94 Can I define a type that is an alias of another type (like typedef in C++)?
    95 Is it possible to have different access modifiers on the get/set methods of a property?
    96 Does C# support #define for defining global constants?
    97 Does C# support templates?
    98 Does C# support parameterized properties?
    99 Does C# support C type macros?
    100 Can you store multiple data types in System.Array?
    101 Can you declare the override method static while the original method is non-static?
    102 Does C# support multiple inheritance?
    103 Can multiple catch blocks be executed?
    104 Can you override private virtual methods?
    105 What is a pre-requisite for connection pooling?
    106 What is the data provider name to connect to Access database?
    107 Why does my Windows application pop up a console window every time I run it?
    108 What is the wildcard character in SQL?
    109 What is the role of the DataReader class in ADO.NET connections?
    110 What does the This window show in the debugger?
    111 Describe the accessibility modifier protected internal?
    112 What is an interface class in C#?
    113 What is a multicast delegate in C#?
    114 What does assert() do in C#?
    115 How do I get deterministic finalization in C#?
    116 How can I get around scope problems in a try/catch?
    117 Why do I get an error (CS1006) when trying to declare a method without specifying a return type?
    118 How do I convert a string to an int in C#?
    119 How do you directly call a native function exported from a DLL?
    120 What is the .NET datatype that allows the retrieval of data by a unique key?
    121 How do you specify a custom attribute for the entire assembly (rather than for a class)?
    122 What is the difference between a Struct and a Class?
    123 What is the implicit name of the parameter that gets passed into the set method/property of a class?
    124 What does the keyword virtual declare for a method or property?
    125 How is method overriding different from method overloading?
    126 Can you declare an override method to be static if the original method is not static?
    127 What are the different ways a method can be overloaded?
    128 If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
    129 What is a C# delegate?
    130 What is a multicast C# delegate?
    131 How do you generate documentation from the C# file commented properly with a command-line compiler?
    132 What debugging tools come with the .NET SDK?
    133 What does assert() method do?
    134 What is the difference between the Debug class and Trace class?
    135 How do you debug an ASP.NET Web application?
    136 What are three test cases you should go through in unit testing?
    137 Explain ACID rule of thumb for transactions in C#.
    138 Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
    139 What does the Initial Catalog parameter define in the connection string?
    140 What does the Dispose method do with the connection object?
    141 How is the DLL Hell problem solved in NET
    142 What are the ways to deploy an assembly?
    143 What is the smallest unit of execution in .NET?
    144 When should you call the garbage collector in .NET?
    145 How do you convert a value-type to a reference-type?
    146 Difference between directcast and ctype.
    147 An example of a ctype and directcast.
    148 ctype(123.34,integer) - should it throw an error? Why or why not?
    149 directcast(123.34,integer) - should it throw an error? Why or why not?
    150 Difference between a sub and a function in C#.
    151 Explain manifest & metadata in C#.
    152 Difference between imperative and interrogative code.
    153 Difference between value and reference type.
    154 What are the two kinds of properties.
    155 Constructor in C#.
    156 Describe ways of cleaning up objects in C#.
    157 How can you clean up objects holding resources from within the code?
    158 Which controls do not have events?
    159 What is the maximum size of the textbox?
    160 Which property of the textbox cannot be changed at runtime?
    161 Which control cannot be placed in MDI?
    162 What is the difference between proc. sent BY VAL and BY SUB?