Tuesday, December 8, 2015

C# when to use ExecuteNonQuery()

ExecuteNonQuery- ExecuteNonQuery does not return any data at all. it is used basically to insert update operationas on table.

C# does Datatable.acceptchanges() save changes to the actual database ?

NO!


http://msdn.microsoft.com/en-us/library/system.data.datatable.acceptchanges.aspx


When AcceptChanges is called, any DataRow object still in edit mode successfully ends its edits. The DataRowState also changes: all Added and Modified rows become Unchanged, and Deleted rows are removed.
The AcceptChanges method is generally called on a DataTable after you attempt to update the DataSet using the DbDataAdapter.Update method.



So your actual database is unaffected.
 

Sunday, November 1, 2015

C# What are try, catch and finally

Its pretty simple again as the name suggests, 



Remember you shouldn't use a try catch block if you don't expect any errors in the first place

An example of try catch finally would be this;



     try
        {
            int a = 10;
            int b = 20;
            int z = a + b;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            Console.WriteLine("Executed");
        }

C# What are access modifiers

People I know C# can be intimidating at once but Access Modifiers is  a self-explanatory term innit ? I' mean access = permission to enter, modifiers = 1/0 (if one = access granted, 
0 = access denied). Lets view some graphic,




Many programmers prefer to use public methods so that its like always an open gate, kinda flexible and anyonem anything can access it, without any hassle.

Now, when i was first learning C# I used to search for ebooks, videos on youtube and even forums like stackoverflow they used to mention about like yea try changing your access modifier and I was like before going further I wanna find out what access modifiers are in the first place.

Here's an example; (view fullscreen click here)

C# what does static mean

C# can be intimidating and consists of several terms which addup to the pile of shit and one such term is static you've mostly seen it in "public static void main";

Best way to remember what it means is to remember it as a magic word which will allow you to access any method in any class without creating an instance of class.


To explain this I'll be creating a fun and simple program which will shout out your name back to you, its more fun cuz it'll shout back whatever you enter =D

In visual studio after you've created a new console application create a new class called shoutout.cs 



Now here I'll be showing you two examples one with static and one without static, so that you finally get to know the difference, (view in Fullscreen Click Here)






C# what is main



Saturday, October 31, 2015

C# what is a class

C# has got too much going on and you do forget whats a class, or object, or method or function...so what were we learning, yes the "class".

Let me put it as simply as possible.


Even after that mall example you didn't get it, you a thick head, follow the example below:

Lets take a look at our SimpleCalculator Example;

The class code;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class SimpleCalculator
    {

        public int add(int x, int y)
        {
            Console.Write("\nThe addition is ");
            return x + y;

        }


        public int mul(int x, int y)
        {
            Console.Write("\nThe multiplication is ");
            return x * y;

        }
    }
}
Have a look at the image below in fullscreen to know what is what.


C# how to create a simple calculator based on user input

We've seen all those tutorials about calculators n all which show how to add and stuff, example;
int x = 4;
int y = 5;
int result = x + y;
Console.WriteLine("Total Sum is : {0}", result);  
Now above code is like really basic and to be honest kinda stupid cuz common who really embeds their sum in a program, what you want is that the user enters what two numbers he/she wanna add/multiply and then the result is displayed on the console. Thats cool innit ?

So fireup your visual studio create a new console application, if you dunno how to read,
How to create new console app. in C#.

1. Ask for user input whether he/she wants to add or multiply, and store input in "choice
Console.Write("Enter 1 for addition, 2 for multiplication: ");
int choice = int.Parse(Console.ReadLine()); 
2. Now make a new class called SimpleCalculator which will hold our add and multiply methods.

class SimpleCalculator{

}
3. Now lets make two methods for add and multiply

 public int add(int x, int y)
        {
            Console.Write("\nThe addition is ");
            return x + y;

        }
  public int mul(int x, int y)
        {
            Console.Write("\nThe multiplication is ");
            return x * y;

        }

4. Full code for main method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {



            Console.Write("Enter 1 for addition, 2 for multiplication: ");
            int choice = int.Parse(Console.ReadLine());


            if (choice == 1)
            {
                //addition
                Console.WriteLine("Welcome to Addition...");
                Console.WriteLine("\nEnter first number: ");
                int num1 = int.Parse(Console.ReadLine());
                Console.WriteLine("\nEnter second number: ");
                int num2 = int.Parse(Console.ReadLine());
                SimpleCalculator AddCalc = new SimpleCalculator();
                Console.WriteLine(AddCalc.add(num1, num2));

            }
            else if (choice == 2)
            {
                Console.WriteLine("Welcome to Multiplication...");
                Console.WriteLine("\nEnter first number: ");
                int num1 = int.Parse(Console.ReadLine());
                Console.WriteLine("\nEnter second number: ");
                int num2 = int.Parse(Console.ReadLine());
                SimpleCalculator Mul = new SimpleCalculator();
                Console.WriteLine(Mul.mul(num1, num2));
            }





            Console.ReadLine();

        }
    }
}
5. Full code for SimpleCalculator class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class SimpleCalculator
    {

        public int add(int x, int y)
        {
            Console.Write("\nThe addition is ");
            return x + y;

        }


        public int mul(int x, int y)
        {
            Console.Write("\nThe multiplication is ");
            return x * y;

        }
    }
}

C# how to create a new console application in Visual Studio

I know ya'll wanted to learn C# to build all those boss looking windows forms applications (the ones with a gui) btw gui stands for guided user interface. But for the learning of basics a console application is whats needed. Don't ask for  a reason thats how its been since ages.




They first invented the wheel didn't they...


So how would you make a console application, its simple follow me homie;

 Open up visual studio and press ctrl+shift+n to bring the new project dialog box



Thats it a new console application just got created...

Sunday, October 25, 2015

Data-types & Variables

In this chapter we'll be looking at data-types in C# as well variables and how to declare them.

Now let's take a look at the different datatypes and a first look at variables. We'll look more into this later.

Data-type chart:
[Image: unified-type-system-chart-c-sharp.jpg]

Source: http://www.dotnet-guide.com/images/unifi...-sharp.jpg

You may notice that string is not on the list, but maybe I know why that is. A string is not an actual data type (It is one, but not a simple datatype), but an array or sequence of unicode characters. Which the char data-type is equal to.

A char is actually equal to a byte as well, but more about that later when we get to some of the advanced things.

If you look at the example that's how you declare the different variables.

So let's try to declare a string.

Code:
string myString = "Hello Hack Forums!";

Let's break this line into pieces.
The first thing we see is:
Code:
string

That is the datatype of our variable.

Then we have:
Code:
myString

That is the name of our variable.

Then we have:
Code:
=

That is an operator used to make it equal to the value we're giving it. It can also be used to assign the left handed variable with a (data)type or pointer.

Then we have:
Code:
"Hello Hack Forums!"

That is the value of our string. A string has to be declared in apostrophes ("), but an integer ex. int or byte does not need them, but they're also only numerics as they're integers.

At last we have:
Code:
;

If you cannot remember what it does then read back in the previous tutorial.

Or mark below:
<from>A semi-colon (;) is used as an end statement in C#. For a clear explanation look back in the previous tutorial.<to>

What I will suggest now is to try to declare different types of variables, look at the chart for examples.

Now try to see if you can write them out to the console as well.

Example:
Code:
static void Main(string[] args)
  {
    string myString = "Hello Hack Forums!";
    int myInt = 105000;
    short myShort = 5252;
    byte myByte = 200;
    Console.WriteLine(myString);
    Console.WriteLine(myInt);
    Console.WriteLine(myShort);
    Console.WriteLine(myByte);
    Console.ReadLine();
  }

Now let's look into some mathematical operations.
You can add/remove values etc. to a variable, some variables support other operators than others, but let's just take a look at int as of now. More about type-conversion later.)

Here are some examples of mathematical operations:
Code:
int X = 10;
    int Y = 15;
    int Res = X + Y;
Code:
int X = 10;
    int Y = 15;
    int Res = X - Y;
Code:
int X = 10;
    int Y = 15;
    int Res = X * Y;
Code:
int X = 10;
    int Y = 15;
    int Res = X / Y;
Code:
int X = 10;
    int Y = 15;
    int Res = X ^ Y;

You can also do this if you wish to make X equal to the result then instead doing:
Code:
X = Res;

You could just do this from the start.
Code:
int X = 10;
    int Y = 15;
    X += Y;
Code:
int X = 10;
    int Y = 15;
    X -= Y;
Code:
int X = 10;
    int Y = 15;
    X *= Y;
Code:
int X = 10;
    int Y = 15;
    X /= Y;
Code:
int X = 10;
    int Y = 15;
    X ^= Y;

These are just examples and there is a lot more operators etc. and things you can do.

Now let's get more specific what a variable is. A variable is a place in your computers memory that you can use to hold some data. See your memory as a city. A city has a lot of different house. The different house has differerent peoples living/objects stored in them.

If the memory is the city, the variable is the house and the data is the people and objects in the house.

Example of memory.
[Image: Gz5rC.png]

That was a bit about data-types and variables.

Downloads/Links:
MSDN (Data-types)
MSDN (Operators)
Datatypes & Variables Download (Source)

Original

Your First Project & Application

Your First Project & Application

Introduction:

In this chapter you'll be creating your first project in C# as well your first application. The very basics of a C# programming interface is covered here as well.

First of all start by starting Visual Studio up and then go to File -> New -> Project.

I will only cover Console Applications in these tutorials, because that's the best way to actually learn the language, instead of jumping into Windows Forms and event handling then you won't have to struggle with it later, so as of now start out with a Console Application.

I will be calling my application "My First C-Sharp Application". You can call yours whatever you want, the name doesn't really matter.

At the right side you'll see your solution. A solution can be consiting of more than one project, but that's not important now as we'll only work with one project at a time. When you start to use more projects then when you start to create real applications.

Solution Explorer:
[Image: o94Jq.png]

You can view all the files and folders in your project. The .cs files is the C-sharp Codefiles which is the files you want to code in. If you want to add new files you can right click your project and choose "Add".

We won't look into this now, so don't sweat it.

At your left you should see something like this:
[Image: sFYxj.png]

That is the place you want to produce your code. You might not understand what these things are now, so let's break it down.

We'll start with the first few lines showed which are the following:

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

The using keyword basically tells that we want to use a namespace. The "words" you see afterwards ex. System; is the namespace we want to use.
You may want to use one or more namespaces and that's why you can use multiple namespaces.

The ; (semicolon) is used to finish a statement. If you come from VB then it'll be hard to be used to use that all the time, because in VB you won't have to use it at all, but the beauty of using it is that you do not have to have seperate lines of all your code.
This:
Code:
using System;using System.Collections.Generic;using System.Linq;
using System.Text;

Is actually equal to:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

Now I'm not saying you should do that, because you should still keep in mind that your code should be readable by yourself and others who's maybe going to use your code or is your team-partner.

The next thing we see is the keyword namespace.
Basically it will give a sequence of classes, structs and other things a name which you can use to access them. Basically namespaces are useful to group your classes, so it's easier to navigate through your classes.

In our case the default namespace is My_First_C_Sharp_Application for me, but for you it will be whatever your project was called. If you make a new folder then to create a new namespace (Will use the folder name) then a good idea is to right click the folder and then add your classes through there, because they'll be given the default namespace + the folder name as a namespace.

We could use this as a reference:
Code:
System.Linq

System would be our default namespace and Linq would be a folder under the System project.

Now this is not exactly how it works and it was just an example.

Now we'll see this:
Code:
class Program

I won't really explain a lot about that, because you'll learn about classes later on, but basically a class is a sequence of variables and methods which you have to access through that class.

Example on MyMethod:
Code:
class Myclass
{
    public static void MyMethod()
    {
    }
}

Cannot just be accesed like:
Code:
MyMethod();

We would have to do it like:
Code:
Myclass.MyMethod();

And if it was in another namespace we would have to type the namespace as well or do as the first thing I explain use the using keyword to define the namespace. Then we wouldn't need to type the namespace, but could just do as above.
Code:
Mynamespace.Myclass.MyMethod();

The next thing we'll see is this:
Code:
static void Main(string[] args)

That is a method. I won't really explain this what it does, but what I'll explain here is that the Main method is first default entry point, but it's possible to actually execute some code before it gets to that using constructors, but I won't be teaching any of that now as it's not relevant and I do not expect you do understand it, if you do not have any experience at all, so just remember the Main method as being the entry point of the application. That's where we want to do out code for the next tutorials, so do not focus on any of the codes shown here as of now.

At last there is brackets { & } which you may question yourself what does.
Brackets in C# is used to declare a scope. Basically every scope in C# has some sort of code. The places where you usually are using scopes would be namespaces, classes, methods, properties & loops.

And explanation of the scopes for the different types.
Namespace scope:
A scope for a namespace can hold different classes, structs, interfaces, delegates, enums and such things, but not variables, methods etc.

Class scope:
A class scope can hold variables, properties, delegates, methods, other classes, interfaces, structs, enums and such things.

Method scope:
A method scope can hold variables, operations (ex. i += 10), loops and codes for execution. A method cannot hold any other types can variables thought.

Property scope:
A property scope will consist of one or two scopes. A scope for get and a scope for set. The get has to return a value which is the same type as the property and the set will basically set the value of the property (Usually linked to another variable.). The two scopes is actually the same as a method scope. You'll learn more about this when we get to properties.

Loop scopes:
A loop scope has to be declared within a method scope as it's just looping through a sequence of codes that are getting executed. That means the loop scope can hold the same things as a method scope.

Now let's get started with some writing to the console. We have to use the Console class which is a part of the System namespace, but since we have already declared the System namespace (As I explained earlier) then we can just call Console. and we want to call the WriteLine() method, however there is Write() as well. WriteLine() will write to the console and create a new line afterwards, which Write() won't. You can try type a string in the parameters. You start a string by using " and ending it by using " as well.
Ex:
Code:
"Hello Hack Forums!"

You have to do that as the parameter. A parameter is the variables or what you can say that is passed into a method when called.

Ex.
Code:
static void MyMethod(string parameter1, string parameter2)
{
}

You'd call it like:
Code:
MyMethod("parameter1", "parameter2");

This is how we'd use WriteLine().
Code:
Console.WriteLine("Hello Hack Forums!");

Now I don't really explain where to put this now and it may confuse you, but remember what I explained about scopes?

Where do you think a code for executions should be placed? ;)

That's correct in the Main Method.


Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace My_First_C_Sharp_Application
{
    class Program
    {
  static void Main(string[] args)
  {
    Console.WriteLine("Hello Hack Forums!);
  }
    }
}

To build you press F6, you can find your application in your project folder in either bin\debug or bin\release. However if you wish to build and run you simply debug by pressing F5. Debugging is a good tool, because if there is any exceptions thrown (errors) then it will jump into your code and tell you where the problem is and tell you exactly what the problem is, but you can also set breakpoints. Breakpoints can be used to check how your program actually works and you can use it to check when variables change and what their values are. It's a good thing to check for errors and mistakes.

To set a break point you just click at the left side of your code editor and it will create a red dot, which marks the breakpoint. You can click on that to remove it again as well.

Your program will pause/stop when it reaches that break point and then you can follow your code line by line. You can have more than one break point.

To follow your program you'll have to press F10 for each line. If you have finished checking a breakpoint you can press F5 and it will either run the program regular (If there is no more breakpoints) or jump to the next break point.

Now try to debug.

What happened? The program closed.

That's weird, isn't it?
Not really, because the program has no more code to execute. We can stop it from doing that by creating an infinite loop or just call the read methods from the console class and wait for an input.

ReadKey() will wait for a key input, where ReadLine() will wait for enter to be pressed. ReadLine() can also be used to give a string a value, because it returns a string.

Code:
Console.ReadLine();

Final code:

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace My_First_C_Sharp_Application
{
    class Program
    {
  static void Main(string[] args)
  {
    Console.WriteLine("Hello Hack Forums!");
    Console.ReadLine();
  }
    }
}

Congratulations you have made your first C# application.

Downloads/Links:
My First C-Sharp Application Download (Source)

Original 

IDE & Compiler

IDE & Compiler

Introduction:

Before you start you'll need an IDE and a compiler. Luckily Microsoft have already created that for us when they decided they'd create their language they already had in mind that the users of their language would need to have some kind of environment to create their codes on and that's what's called Visual Studio.

There is a difference on an IDE and a compiler thought and it's important you understand the difference.

An IDE (Intergrated Development Environment) is an application which you can use to produce your codes in. Technically you could do them in ex. notepad (Some actually preferre to use Notepad++) however that will only slow down your work, because an IDE usually include things such as project creation, project explore, easy binding to a compiler, syntax high light, auto-indent etc. Visual Studio already include all that and more. If you're developing C# then Visual Studio would be the best IDE, but if you have problems with it using too much CPU or being slow then an alternative IDE could be the SharpDevelop or Mono (Which is available for Linux, Mac and other OS's as well.) Though Mono requires the Mono C# compiler and I'll not be teaching anything related to Mono, so I'd suggest not to look into Mono unless you want to be on your own.

Visual Studio Image:
[Image: code.png]

Source: http://www.otakusoft.com/wp-content/uplo...0/code.png

A compiler is the program that we use to convert (compile) your code into machine code. In our case we do not compile to native code (machine code or assmebly if you preferre to say that.), but to the CIL or MSIL. The CIL will then compile the IL code into machine code at run time. I could be wrong at this as I've never looked it up that much and it's just from the tip of my tongue I say this as I felt too lazy to search.

To get started you'll need the IDE and compiler for C#, if you do not have Visual Studio and do not wish to buy it then you can get the C# Express version which is free. After 30 days or something you'll have to activate it and you can do that by signing up and then you'll be send a free key which will activate your product permanent.

Downloads/Links:
CIL
C# Express Download (C# Express 2012)
Sharp Develop Download
MonoDevelop Download

Original 

.NET Framework

Introduction:
In this chapter I will be explaining a bit about the .NET Framework and what it is.

The .NET Framework is a huge framework of libraries and other stuff developed by Microsoft. I will not go in depth about the actual .NET Framework, because it's a huge area and if you'd like to know more about it then you should check out Google, but basically as I already mentioned it's a huge library developed by Microsoft.

Basically most things developed for Windows are in some sort using .NET Framework this goes from Windows Applications to X-Box Games. .NET is not necessary to make something work on Windows or any of Mirosofts devices, but it's a huge help when developing something, because it speeds up your development, that's why C# has become one of the leading Rapid Development Languages out there today.

If you compare C# with C++ then C++ might beat C# by performance, but the time it takes to create something elegant in C++ will take far more time, but its dependencies is also lower, but even with the dependencies C# is still a great language and if you wish to continue to learn C++ and more powerful languages later then C# is perfect, because it teaches you programming in a good and "fast" way, but also an elegant way of produce your code which you can use later on.

Enough of that now, but basically when developing something for the .NET framework the users must have the .NET Framework installed. As of now it's installed already on Microsofts devices, usually .NET 3.5, but also .NET 2.0.
As of now with VS 2012 they have released 4.5, but a lot of people still prefere to use 4.0 which I do as well. You can always change your properties of your application to use a lower .NET Framework, but remember that the lower .NET you choose, the less features will be available and you might have to code some things yourself, instead of relying on classes and methods they have already created. Try to target your project at .NET 3.5 because it's the most common, but if you must then you can use .NET 4.0. I wouldn't recommend to use 2.0 at anytime unless you want as less dependencies as possible and you don't mind doing quite some code yourself.

Downloads/Links:
.NET Framework (Wikipedia)

Original

About C# and Chapters

Introduction:
In this category you will be learning about the basics of C# such as variables, classes, methods, loops etc. This category will only cover Console Applications.

Chapters:

  • C# Introduction
  • .NET Framework
  • IDE & Compiler
  • Your First Project & Application
  • Data-types & Variables
  • Strings
  • Booleans
  • Conditional Statements
  • Switch
  • Type-Conversion
  • Loops #1 (For & While)
  • Arrays & Collections
  • Loops #2 (Foreach)
  • Classes
  • Access Modifiers
  • Properties
  • Methods & Functions
  • Parameters, Ref & Out
  • Enums
  • Generics
  • Exceptions


C# Introduction

Introduction:

In this chapter I will explain a bit about C# and what it is, but also why it's a great language to learn.

C# is a wonderful language to use. It's very easy to use and you can continue to other languages after like Java & C++. They won't be that hard to grab if you've learned C#. I don't see a point in jumping from C# to Java though as they're both "High Level" languages, but from C# to C/C++ would be a great idea, because they're both build on the C-syntax. A lot of people who are new to C# mistakes C# for being in the C-family, but it's not. It has nothing common with the C-family (C, C++, Objective-C etc.) and the only thing in common is basically some of the syntax. C# is not unmanaged either which means it does not compile to assembly, but to the CIL. You can still use C# on other platforms with the use of things such as Mono etc. I won't be covering other operating systems than Windows though as I do not have experience with anything else.

So why is C# a good language to learn?
Well it's very easy to pickup and there isn't that much of advanced words to use. It's basically English everything which is what's a + about the .NET Framework and its libraries. Even if you come from other languages based on .NET such as VB.NET then you can still pickup C# easy as you'd basically only need to learn the syntax. I've heard from people who started out with VB.NET and then went to C# that they're very happy to do that because they can do the same and a bit more as well continue much easier to other languages. Though I've heard a few saying that they had it hardest with coming from VB.NET to C#, because they had to end everything with a semicolon and the way that variables are declared is a bit different. If you get a good grab around that then you should have no problems coming from VB.NET to C#.

So what if you have no programming experience at all, is C# easy to pick up?
Yes. It was the first programming language that I learned and you might struggle a bit in the start to understand the concept behind programming and remembering keywords etc. but just give it time and for god's sake don't cheat yourself to say you know more than you actually do, because you'll only cheat yourself by doing that! Some might learn it faster than others, but take the time you need and do not compare your learning time with others. We also learn different, some might learn better from practice while other learn better from e-books, tutorials or maybe even videos. I do not recommend videos for programming though and the reason is simple. When you watch a video you can't really follow what is done that much and you might have to rewatch it over and over to actually understand or see what's going on. That's why an e-book or tutorials might be better as you'll get to write code yourself rather than looking someone who codes. You'll remember what you did much better that way!

Downloads/Links:
N/A

Original

Saturday, October 24, 2015

Introduction

Welcome to another C# tutorial by me. This tutorial is 100% written by me on behalf of 143. I will be covering the same things as I did in my previous tutorials though I have rewrote a bit, but then I have covered a few new categories, which you can see. I've chosen to cover the Windows Forms in this as well! I hope you'll enjoy this thread and that you will learn something from it!

Regards,
BaussHacker.

Note: As Visual Studio doesn't work for me then I've been using SharpDevelop for the projects.
It shouldn't do a difference code-wise though, but it might be a bit different when coming to Windows Forms!


Original