Thursday 29 October 2015

How to find files in directory using c#?

0

Getting a file path :


// This will give the complete path to the folder name  ( ~ File)such as 
//C:\Users\Kumarg\Documents\Visual Studio 2010\Projects\Tag_Cloud\Tag_Cloud\File


string path = Server.MapPath(" ~/folderName");   

Getting all files path under a folder or directory : 


string [ ] fileList = new  string[20];
fileList = Directory.GetFiles(Server.MapPath("~/folderName"));

Getting only file name without the path under a folder or directory 



  var UploadedFile = Directory.GetFiles(Server.MapPath("~/folderName")).Select(f => Path.GetFileName(f));   



Read More »

Wednesday 28 October 2015

Uploading and Reading a file in asp.net

0



Design

<strong> Upload File</strong>
<asp:FileUpload ID="txtfileUpload" runat="server"/>
<asp:Button ID="btnViewFile" runat="server" Text="Add File"
onclick="btnViewFile_Click" />
<span><asp:TextBox ID="txtMain" runat="server" TextMode="MultiLine"></asp:TextBox>

</span>

Note : Make a new folder named File ( or any as per choice ) in the solution explorer for the project.

Now on .cs File do the following code on button click (btnViewFile)

   

.cs File


protected void btnViewFile_Click(object sender, EventArgs e)
{

if (txtfileUpload.HasFile)
{
string fileName = txtfileUpload.PostedFile.FileName;
string pathToSave = "~/File";
txtfileUpload.PostedFile.SaveAs(Server.MapPath(pathToSave) + fileName);
string Filepath = Server.MapPath(pathToSave + fileName);

StreamReader reader = new StreamReader(Filepath);
string text = reader.ReadToEnd();
txtMain.Text = text;

}

Code Explanation :

 The if condition is checking for the availability of file.
After that we are saving the file by taking the "Server.MapPath" method in bracket we have given the path with the name of the file.

StreamReader is used to read the file.



Read More »

Tuesday 27 October 2015

Abstraction basics in C#

0
Abstraction is general means dealing with ideas rather the events. Through the process of abstraction, a programmer hides all but the relevant data about an object in order to reduce complexity and increase efficiency. In the same way that abstraction sometimes works in art, the object that remains is a representation of the original, with unwanted detail omitted. 


An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation. Abstract classes allow specialization of inherited classes.


Code Example :


AbstractClass.cs

// We have made an abstract class with a abstract method add that will return int type data, taking two parameters, notice that only method definition is present without a body and the class as well as the method are marked abstract. Abstract method is always followed by a semicolon (;).  Also keep in mind that an abstract class can have non - abstract method but abstract method are supposed to present within the abstract class.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ClassInCsharp
{
    public abstract  class AbstractClass
    {
         public abstract int add(int a, int b);
    }
}


usingAbstract.cs

// Here we have inherited our abstract class and have declared the body of the add method by using a override keyword. Always remember that the child class has to override all the abstract method of parent class if any.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ClassInCsharp
{
    public class UsingAbstract:AbstractClass
    {
        public override int add(int a, int b)
        {
            int c = a + b;
            return c;
        }
    }
}


AbstractExample.aspx

// We have developed a GUI with three textbox with id txtNo1, txtNo2, txtResult and a button to perform the addition operation. Here we are using that abstract method by calling add method with the help of UsingAbstract class (child class). 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ClassInCsharp
{
    public partial class AbstractExample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            UsingAbstract abs = new UsingAbstract();
           int result =  abs.add(int.Parse(txtNo1.Text), int.Parse(txtNo2.Text));
           txtResult.Text = result.ToString();
        }
    }
}

Read More »

Heap and Stack

0
The Stack is more or less responsible for keeping track of what's executing in our code (or what's been "called").  The Heap is more or less responsible for keeping track of our objects (our data, well... most of it; we'll get to that later).



What goes on the Stack and Heap?


We have four main types of things we'll be putting in the Stack and Heap as our code is executing: Value Types, Reference Types, Pointers, and Instructions. 

Value Types:

In C#, all the "things" declared with the following list of type declarations are Value types (because they are from System.ValueType):

bool
byte
char
decimal
double
enum
float
int
long
sbyte
short
struct
uint
ulong
ushort

Reference Types:


All the "things" declared with the types in this list are Reference types (and inherit from System.Object, except, of course, for object which is the System.Object object):

class
interface
delegate
object
string

Pointers:


The third type of "thing" to be put in our memory management scheme is a Reference to a Type. A Reference is often referred to as a Pointer. We don't explicitly use Pointers, they are managed by the Common Language Runtime (CLR). A Pointer (or Reference) is different than a Reference Type in that when we say something is a Reference Type, it means we access it through a Pointer. A Pointer is a chunk of space in memory that points to another space in memory.  A Pointer takes up space just like any other thing that we're putting in the Stack and Heap and its value is either a memory address or null. 

How is it decided what goes where? 


A Reference Type always goes on the Heap;  
Value Types and Pointers always go where they were declared



Example: For stake

Take the following method:

           public int AddFive(int pValue)
          {
                int result;
                result = pValue + 5;
                return result;
          }
NOTE : the method does not live on the stack and is illustrated just for reference.



Next, control (the thread executing the method) is passed to the instructions to the AddFive() method which lives in our type's method table, a JIT compilation is performed if this is the first time we are hitting the method.


As the method executes, we need some memory for the "result" variable and it is allocated on the Stack.




The method finishes execution and our result is returned.



And all memory allocated on the Stack is cleaned up by moving a pointer to the available memory address where AddFive() started and we go down to the previous method on the stack (not seen here).




Example : for heap


If we have the following MyInt class (which is a Reference Type because it is a class):

          public class MyInt
          {        
             public int MyValue;
          }

and the following method is executing:

          public MyInt AddFive(int pValue)
          {
                MyInt result = new MyInt();
                result.MyValue = pValue + 5;
                return result;
          }


Then just as before, the thread starts executing the method and its parameters are placed on sthe thread's stack.

 


Because MyInt is a Reference Type, it is placed on the Heap and referenced by a Pointer on the Stack.



After AddFive() is finished executing (like in the first example), and we are cleaning up...





we're left with an orphaned MyInt in the Heap (there is no longer anyone in the Stack standing around pointing to MyInt)!



This is where the Garbage Collection (GC) comes into play.  Once our program reaches a certain memory threshold and we need more Heap space, our GC will kick off.  The GC will stop all running threads (a FULL STOP), find all objects in the Heap that are not being accessed by the main program and delete them.  The GC will then reorganize all the objects left in the Heap to make space and adjust all the Pointers to these objects in both the Stack and the Heap.



Note : This blog is taken from codeproject website, as it was well explained there. 




Read More »

Monday 26 October 2015

Boxing and Unboxing

0


Boxing and unboxing is a  essential concept in .NET’s type system. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object. Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object.

Converting a value type to reference type is called Boxing. Unboxing is the opposite operation and is an explicit operation


class Test
{
                  static void Main() {
int i = 1;
object o = i; // boxing
int j = (int) o; // unboxing
}
}


An int value can be converted to object and back again to int.

This example shows both boxing and unboxing. When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box.

Unboxing is just the opposite. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.



Read More »

How to make dll files using visual studio ?

0

Making DLL files

Using visual studio

Step 1

Take a class library project from visual studio.

Step 2

Open the class1 file, which is created by default or add any other as per the choice and requirement.

Step 3

write down the logic part which is need to be used in the related project.

Step 4

Build your project, check the bin > debug folder, you must have got a dll file with the project name.
Example : example.dll

Step 5

Open the project where the dll is needed

Step 6 

Add reference to the dll file by browsing where it was stored.

Step 7

Now add the dll file name with "using" directive.

Step8

Make the object of the class in the dll , which is required at this point.

Step 9

Now use the dll file, as normal class file in your project by sending and receiving arguments as per the project.


Code Example


Class Libray Project file named dllExample


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace dllExample
{
    public class Class1
    {
        public int sum(int a, int b)
        {
            return a + b;
        }
        public int multiply(int a, int b)
        {
            return a * b;
        }
        public int subtract(int a, int b)
        {
            return a - b;
        }
    }
}

Project file where dll is used after providing reference

Here, on GUI we have made two TextBox with id txtNo1 and txtNo2, a button and a lblResult to show the output.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using dllExample;
namespace usingDll
{
    public partial class calc : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Class1 calculate = new Class1();
            int result = calculate.sum(int.Parse(txtNo1.Text),int.Parse(txtNo2.Text));
            lblResult.Text = result.ToString();
        }
        protected void btnSubt_Click(object sender, EventArgs e)
        {
            Class1 calculate = new Class1();
           int result = calculate.subtract(int.Parse(txtNo1.Text), int.Parse(txtNo2.Text));
           lblResult.Text = result.ToString();
        }
        protected void btnMult_Click(object sender, EventArgs e)
        {
            Class1 calculate = new Class1();
         int result = calculate.multiply(int.Parse(txtNo1.Text), int.Parse(txtNo2.Text));
         lblResult.Text = result.ToString();
        }
    }
}


Read More »

Access Modifiers with example

0

Public:

 As the name species it it available to all, means the members marked public are available within and outside the class.

Example:

public class A {
  public int add(int a, int b)
  {
    return a + b;
  }
class B {
   A a = new A( );
   a.add(5,4);  // This method is available as it is public in nature
}


Private:

 It is available only within the class.


Example:

public class A {
  private int add(int a, int b)
  {
    return a + b;
  }
class B {
   A a = new A( );
   a.add(5,4);  // This will give error as the method is marked private so it is not available                           outside the class
}

Protected : 

Members marked protected are available within the class and by derived class instances.

Example:

public class A {
  protected int add(int a, int b)
  {
    return a + b;
  }
class B:A    // Inherit A class 
{
   A a = new A( );
   a.add(5,4);  // This will give error as the method is marked protected so it is not                                       available outside the class

           B b = new B( );
           b.add(5,4);  / / This will work fine as we can call protected method using derived class                                                  instance.
}

Internal : 

Internal types or members are accessible only within files in the same assembly.


Read More »

Encapsulation in C#

0

Encapsulation is one of the main concept of Object-Oriented Programming. You must have seen and had a capsule (medicine) in life as a gift from doctor when you get ill. Capsule mainly consist some powder substance in it  which is wrapped with a cover.

The same way when we cover up details of things ( data members and function ) into a single unit 
( such as class ) it is called encapsulation.




Definition : 

Encapsulation, refers to an ability to hide data and behavior that are not necessary to its user. Encapsulation enables a group of properties, methods and other members to be considered a single unit or object.

Using Encapsulation In C#


Encapsulation in c#  can be  achieved by following ways :

Using Access Modifiers :


Access modifiers basically defines the scope and visibility of a class member. It help to make the scope of some members limited to a particular point. For example if you dont want your mobile phone to be used by someone else you put a keypad lock on it so that no one else can you it. That make the phone as a private property to you.

C# supports the following access specifiers :

Public  : As the name specifies it it available to all, means the members marked public are available within and outside the class.

Private : It is available only within the class.

Protected : Members marked protected are available within the class and by derived class           instances. 

Internal :  internal keyword is an access modifier for types and type members. Internal types or members are accessible only within files in the same assembly

Protected Internal :  can be accessed from the current assembly or from types that are derived from the containing class.

By using properties


Properties in C# helps in protect a field in a class by reading and writing to it. We can use a property (which has a get and set part), or we can use a read only property (which has only a get part) or we can also use a write only property (which has only a set part). But in all cases we can achieve encapsulation

Example:

public class Account
{
   private string accountName = "current account";
   public string AccountName
 {
   get
     {return accountName;}
  set
  {
     accountName = value;
  }
 }
}





Read More »

Friday 23 October 2015

Array

0

Arrays 

  • It has element of any one type.
  • Elements are accessed with an index.
  • Index start at zero.

Consider you want to add all your friends name somewhere. Adding them like this


string frnd1 = "John";
string frnd2 = "Ram";
string frnd3 = "Rohit";

This format of adding information will be tedius and difficult to access and modified later.
Therefore, to achieve these types of goals where we need similar type of data to be put together the concept of Array came.

Array has the capability to store same type of data where you can access the required data by using index of array.

Initializing an Array : 


Let us create our friend list array ,
so our friend name will be definitely in string format.

The Syntax goes as :

 string [] friend = new string[20];
here,

first we define the datatype of our array : string
then the name of the array : friend
after that new operator to initialize a new array of type string with size of 20.

Note : These type of array are called 1-D arrays.

Assigning values to arrays : 


We can add our friend list to the array by many ways few of them are discussed :

1) At the time of initialization:

string[] friend = new string[] { "John","Ram", "Mohan"};
2) After initialization:

string[] friend = new string[5];friend[0] = "John";friend[1] = "Ram";friend[2] = "Mohan";


Example program that initialize and receives array parameter:



class Program {
static void Main()
{

//Three element array
int[] array = new array[]{-5,-6,7};

//Pass array to Method.
Console.WriteLine(Method(array));

}

//Recieves array parameter
static int Method(int[] array)
{
return array[0]*2;
}


Output 

-10

 Square brackets are used for all arrays.
Read More »

Basics of Dictionary

0

Dictionary


"Dictionary" in C# programming  make use of 'hash table' data-structure to build up the index/ value pair.

Like our normal dictionary it consist of an index and with reference to index it has one more values. (Apni oxford dictionary and c# k dictionary m koe anter nhi h).


Initialize A dictionary Object in C#


Think if you want to make your own dictionary then you must have a name to the dictionary and the type of data which is required to be filled in the dictionary.

Same way,
The syntax goes like

Dictionary <string, string> myDictionary = new Dictionary<string, string>();

Here,

myDictionary is the name of our dictionary,
<string, string> specifies that the index and value will be in string format respectively.

Add Pairs in Dictionary Object :


Now if you want to start to build your dictionary i.e you want to add fields in it.
Then simply we do,

myDictionary.Add("A","Apple");

//Here we have added a index of "A" which is the key and the value assigned to it is Apple.
So, if you refer to "A" then it will return Apple as the value . ( A for Apple).

Delete Pairs in Dictionary :


If you don't like a pair and want to delete it from your dictionary. (tumhri khud ke h kuch bhi kr skta ho).
Then,

myDictionary.Remove("A");

This will delete the index "A" and corresponding values.


Yeah, I think you know more words that start with "A" so, if you want to add more then just one entry per index then make use of List<string> .

The syntax goes as

Dictionary<string, List<string>> myDictionary = new Dictionary<string, List<string>>();
Read More »

Wednesday 21 October 2015

Classes in C#

0

CLASS

A class is a construct that enables you to create your own custom types by grouping together variables of other types, methods and events. A class is like a blueprint. It defines the data and behavior of a type. If the class is not declared as static, client code can use it by creating objects or instances which are assigned to a variable. The variable remains in memory until all references to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class is declared as static, then only one copy exists in memory and client code can only access it through the class itself, not an instance variable.

Defining Classes


The first line of code defines the code block as a class definition using the keyword Class followed by the name of the class. The body of the class definition is enclosed by an open and closing curly bracket. The code block is structured like this:

class Employee
 {
 }

Creating Class Properties


After defining the starting and ending point of the class code block, the next step is to define the instance variables (often referred to as fields) contained in the class. These variables hold the data that an instance of your class will manipulate. The Private keyword ensures that these instance variables can be manipulated only by the code inside the class. Here are the instance variable definitions:

private int _empID;
private string _loginName;
private string _password;
private string _department;
private string _name;

When a user of the class (client code) needs to query or set the value of these instance variables, public properties are exposed to them. Inside the property block of code are a Get block and a Set block. The Get block returns the value of the private instance variable to the user of the class. This code provides a readable property. The Set block provides a write-enabled property; it passes a value sent in by the client code to the corresponding private instance variable. Here is an example of a property block:

public string Name
{
    get { return _name; }
    set { _name = value; }
}

There may be times when you want to restrict access to a property so that client code can read the property value but not change it. By eliminating the Set block inside the Property block, you create a read-only property. The following code shows how to make the EmployeeID property read-only:

public int EmployeeID
{
    get { return _empID; }
}


The following are some of the benefits of encapsulating the data in this way:

  • Preventing unauthorized access to the data.
  • Ensuring data integrity through error checking.
  • Creating read-only or write-only properties.
  • Isolating users of the class from changes in the implementation code.

Abstract Class:


An Abstract Class means that, no object of this class can be instantiated, but can make derivation of this. It can serve the purpose of base class only as no object of this class can be created.
Abstract Class is denoted by the keyword abstract.

Example:


abstract class myClass
{
public myClass()
{
 // code to initialize the class…
}
abstract public void anyMethod_01();
abstract public void anyMethod_02(int anyVariable);
abstract public int anyMethod_03 (int anyvariable);
}

It is important here to note that abstract classes can have non-abstract method(s), even can have only non-abstract method(s).

Partial Class:


This special type of class called "Partial Class" is introduced with .Net Framework 2.0. Partial Class allows its members – method, properties, and events – to be divided into multiple source files (.cs). At compile time these files get combined into a single class.
Partial Class is denoted by the keyword partial.

Some do's and don'ts about partial class:-


  • All the parts of a partial class must be prefixed with the keyword partial.
  • Accessibility, signature etc. must be same in all parts of the partial class.
  • You cannot sealed one part of the partial class. In that case entire class in sealed.
  • If you define any part of the partial class abstract, entire class will become abstract. 
  • Inheritance cannot be applied to a part of partial class. If you do so, it applies to entire class. 

Example:


public partial class myPartialClass
{
public void firstMethod()
{
// code…
}
}
public partial class myPartialClass
{
public void secondMethod()
{
// code…
}
}

Sealed Class:


A sealed class is a class which cannot be inherited. A sealed class cannot be a base class. The modifier abstract cannot be applied to a sealed class. By default, struct (structure) is sealed. It is the last class in hierarchy. To access the members of a sealed class, you must create objects of that class. 
Sealed Class is denoted by the keyword sealed.

Example:


sealed class mySealedClass
{
int a;
int b;
}
Class mainClass
{
public static void Main()
{
mySealedClass obj = new mySealedClass();
obj.a = 5;
obj.b = 7;
Console.WriteLine("a = {0}, b = {1}", obj.a, obj.b);
}
}

Static Class:


A Static Class is one which cannot be instantiated. The keyword new cannot be used with static classes as members of such class can be called directly by using the class name itself.

Following are the main characteristics of a static class:-


  • A Static Class can only have static members.
  • A Static Class cannot be instantiated. 
  • A Static Class is sealed, so cannot be inherited.
  • A Static Class cannot have a constructor (except static constructor).

Static Class is denoted by the keyword static.


Example:


// static class definition…
public static class myclass
{
public static int addNumbers(int a, int b)
{
return (a + b);
}
}
// to use it, we call directly on the class…
Console.WriteLine("The addition of 5 and 7 is: " + myClass.addNumbers(5, 7));

Related Articles : 






Read More »

.Net Architecture and working

0

.NET Framework - Basics

  • Software framework developed by Microsoft.
  • includes a large class library - Framework Class Library (FCL).
  • it has application virtual machine know as Common Language Run-time (CLR).

Framework Class Library

  • collection of reusable classes, namespace and interfaces.
  • Base Class Library is the core 
  •  .NET framework implementation of the Standard Libraries as defined in the Common language infrastructure. 
  •   FCL provides user interface, data access, database connectivity, cryptography, web application development, numeric algorithms, and network communications.

Common Language Runtime


  • CLR is the platform on which applications are hosted and executed.
  • It is used to manage memory, thread execution, code execution, code safety, verification, compilation, and other system services.
  • The CLR also supports a set of services that the application can use to access various resources like array, collections, operating system folders etc:
  • The managed environment of the run-time eliminates many common software issues. For example the run-time automatically releases the object when they are no longer being used.
  • This automatic memory management resolves the memory leaks and invalid memory references.
  • It implements a strict type and code verification infrastructure called Common Type System (CTS).

Design Principles:

  1. Interoperability : 
  2. Language independence
  3. Portability
  4. Security
  5. Memory management
  6. Simplified deployment
  7. Performance

The Role of .NET Framework:


The .NET Framework has two main components: the common language runtime (CLR) and the .NET Framework class library. The common language runtime is the foundation of the .NET Framework. CLR act as an agent that manages code at execution time, providing core services such as memory management, thread management, and remoting, while also enforcing strict type safety and facilitates with code accuracy that ensure security and robustness. The concept of code management is a fundamental principle of the CLR. Code that targets the CLR is known as managed code, while code that does not target the CLR is known as unmanaged code.


The class library, is a integral component of the .NET Framework, consists of object-oriented collection of reusable classes (types) that we can use to develop applications ranging from traditional command-line or any graphical user interface (GUI) applications such as Windows Forms, ASP. NET Web Forms and Windows Services the newly invented XML Web services.

The European Computer Manufacturers Association (ECMA) standard has defines the Common Language Specification (CLS); this enforces that software development languages should be inter-operable between them. The code written in a CLS should be compliant with the code written in another CLS-compliant language. Because the code supported by CLS-compliant language should be compiled into an intermediate language (IL) code. The CLR engine executes the IL code. This ensures interoperability between CLS-compliant languages. Microsoft .NET Framework supports Languages like Microsoft Visual Basic .NET, Microsoft Visual C#, Microsoft Visual C++ .NET, and Microsoft Visual J# .NET.

The language compilers generate an Intermediate Language code, called Microsoft Intermediate Language (MSIL), which makes programs written in the .NET languages inter-operable across languages.

The ECMA standard, Common Language Infrastructure (CLI), defines the specifications for the infrastructure that the IL code needs for execution. The CLI provides a common type system (CTS) and services such as type safety, managed code execution and side by side execution.


Execution Process

Choosing a compiler : 


- You can choose one or more language compiler targeting the run time such as VB. C#, Visual C++.


Compiling your code to MSIL


- When you compile source code into MSIL, it generated metadata. MSIL is a CPU independent set of instruction that can be efficiently changed to native code.

- The instruction for loading, storing, initializing, arithmetic and logical operations, control flow, direct memory access, exception handling, calling methods on objects and so many other operations are included in MSIL.

- At the time of creating MSIL the compiler also generates the metadata that describes the types, Reference and value type, in your code along with each type definition, the signature of each type's members, members referenced by  your code, and other data that the runtime uses at execution time.

- Metadata are basically information about the compiled time.

- The MSIL and metadata are contained in a portable executable file, which is standard format for processor - specific execution.

- While executing your application JIT translate the MSIL into native code. When this compilation is performed, the code must be passed through a verification process that examines to check whether the code is type safe or not. It means that it is known to access the authorized memory location.

- JIT compilation allows the fact that some code might never get called during execution. Instead of using time and memory to convert all IL to native code, it converts the IL as needed during the exection and stores the resulting native code so that it is accessible for subsequent call.

- The runtime also supports another way of compilation known as install-time code generation. It converts all the MSIL into native code in single shot by taking larger unit of code at a time. The entire assembly is converted into native code at the installation time  only.

Executing the code: 


-  The method must be complied to processor specific code before running.

-Each method for which MSIL is there is JIT complied, when it called for first time and then run.

- Next time when the method is run, the existing JIT complied native code is run. 

Read More »