Tuesday, February 14, 2017

Difference between int,int16,int32,int64 C#

A number of developers think that int represents a 32-bit integer when the application is running on a 32-bit OS and it represents a 64-bit integer when the application is running on a 64-bit OS. This is absolutely wrong.
    In C# int is a primitive data type and it always mapped to System.Int32 whether the OS is 32-bit or 64-bit.
int

    It is a primitive data type defined in C#.
    It is mapped to Int32 of FCL type.
    It is a value type and represent System.Int32 struct.
    It is signed and takes 32 bits.
    It has minimum -2147483648 and maximum +2147483647 capacity.

Int16

    It is a FCL type.
    In C#, short is mapped to Int16.
    It is a value type and represent System.Int16 struct.
    It is signed and takes 16 bits.
    It has minimum -32768 and maximum +32767 capacity.

Int32

    It is a FCL type.
    In C#, int is mapped to Int32.
    It is a value type and represent System.Int32 struct.
    It is signed and takes 32 bits.
    It has minimum -2147483648 and maximum +2147483647 capacity.

Int64

    It is a FCL type.
    In C#, long is mapped to Int64.
    It is a value type and represent System.Int64 struct.
    It is signed and takes 64 bits.
    It has minimum –9,223,372,036,854,775,808 and maximum 9,223,372,036,854,775,807 capacity

Generate Model property from database

use c08824

--from SO: http://stackoverflow.com/questions/5873170/generate-class-from-database-table

declare @TableName sysname = '[CMCT].[Checks]' -- table name
declare @Result varchar(max) = 'public class ' + @TableName + '
{'

select @Result = @Result + '
    public ' + ColumnType + NullableSign + ' ' + ColumnName + ' { get; set; }
'
from
(
    select
        replace(col.name, ' ', '_') ColumnName,
        column_id ColumnId,
        case typ.name
            when 'bigint' then 'long'
            when 'binary' then 'byte[]'
            when 'bit' then 'bool'
            when 'char' then 'string'
            when 'date' then 'DateTime'
            when 'datetime' then 'DateTime'
            when 'datetime2' then 'DateTime'
            when 'datetimeoffset' then 'DateTimeOffset'
            when 'decimal' then 'decimal'
            when 'float' then 'float'
            when 'image' then 'byte[]'
            when 'int' then 'int'
            when 'money' then 'decimal'
            when 'nchar' then 'char'
            when 'ntext' then 'string'
            when 'numeric' then 'decimal'
            when 'nvarchar' then 'string'
            when 'real' then 'double'
            when 'smalldatetime' then 'DateTime'
            when 'smallint' then 'short'
            when 'smallmoney' then 'decimal'
            when 'text' then 'string'
            when 'time' then 'TimeSpan'
            when 'timestamp' then 'DateTime'
            when 'tinyint' then 'byte'
            when 'uniqueidentifier' then 'Guid'
            when 'varbinary' then 'byte[]'
            when 'varchar' then 'string'
            else 'UNKNOWN_' + typ.name
        end ColumnType,
        case
            when col.is_nullable = 1 and typ.name in ('bigint', 'bit', 'date', 'datetime', 'datetime2', 'datetimeoffset', 'decimal', 'float', 'int', 'money', 'numeric', 'real', 'smalldatetime', 'smallint', 'smallmoney', 'time', 'tinyint', 'uniqueidentifier')
            then '?'
            else ''
        end NullableSign
    from sys.columns col
        join sys.types typ on
            col.system_type_id = typ.system_type_id AND col.user_type_id = typ.user_type_id
    where object_id = object_id(@TableName)
) t
order by ColumnId

set @Result = @Result  + '
}'

print @Result

Finding Empty lines in visual studio

Press Ctrl+F (Find) Use regular Expression  ^\s+$

Friday, February 3, 2017

what is the use of partial class in C#

A partial class splits the definition of a class over two or more source files. You can create a class definition in multiple files but it will be compiled as one class.

More than one developer can simultaneously write the code for the class.
Suppose you have a "Emp" class. That definition is divided into the two source files "Emp1.cs" and "Emp2.cs". Then these two files have a class that is a partial class. You compile the source code, then create a single class.
Or Suppose you have a class that has multiple interfaces so you can create multiple source files depending on interface implements. It is easy to understand and maintain an interface implemented on which the source file has a partial class.

Saturday, January 7, 2017

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

A static variable shares the value of it among all instances of the class.

Example without declaring it static

public  class Variable
{
    public int i = 5;
    public void test()
    {
        i=i+5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}
Explanation:If you look at the above example i just declare int variable.when i run this code the output will be 10 and 10.Its simple

Now Lets Look at the static variable Here,I am declaring the variable as a static.

Example with static variable

public  class Variable
{
    public static int i = 5;
    public void test()
    {
        i=i+5;
        Console.WriteLine(i);
    }
}


public class Exercise
{
    static void Main()
    {
        Variable var = new Variable();
        var.test();
        Variable var1 = new Variable();
        var1.test();
        Console.ReadKey();
    }
}
Now when I run above code then the output will be 10 and 15. So static variable value is shared among all instances of that class.

Friday, December 16, 2016

Access denied fix for whatismyipaddress.com

//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Create a request for the URL.
            WebRequest request = WebRequest.Create (
              //@"http://whatismyipaddress.com/ip/31.207.0.99"
                "http://ipv4bot.whatismyipaddress.com"
            );
            // If required by the server, set the credentials.
            // Get the response.
            WebResponse response = request.GetResponse ();
            // Display the status.
            Console.WriteLine (((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream ();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader (dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd ();
            // Display the content.
            Console.WriteLine (responseFromServer);
            // Clean up the streams and the response.
            reader.Close ();
            response.Close ();
        }
    }
}

Find Highest,Lowest and average using two dimensional arrays

//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5

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

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int[] marks = new int[5]{90,29,100,48,60};
            string[] names = new string[5]{"Bongani","Zesipho","Edward","Thato","Thobela"};
         
            string Hname = null;
            string Lname = null;
            int highest = marks[0];
            int lowest = marks[0];
            int sum =0;
            double average;
            int aboveAvg =0;
            int lessthanAvg= 0;
         
            for(int x = 0;x<marks.Length;x++)
            {
             
                //find highest
                if(marks[x]>highest)
                {
                    highest = marks[x];
                    Hname = names[x];
                }
             
                //Find Lowest
                if(marks[x]<lowest)
                {
                    lowest = marks[x];
                    Lname = names[x];
                }
             
                //Find Average
                sum +=marks[x];
             
             
             
            }
         
            average = sum / marks.Length;
         
            for(int x = 0;x<marks.Length;x++)
            {
                if(marks[x]>average)
                {
                    aboveAvg++;
                }
                else
                {
                    lessthanAvg++;
                }
            }
             
            //PRINTING NECESSARY RESULTS
         
            Console.WriteLine("{0} is the highest with {1}% ",Hname,highest);
            Console.WriteLine("{0} is the lowest with {1}% ",Lname,lowest);
            Console.WriteLine("The Average Mark is {0}%",average);
            Console.WriteLine("Number of Students less than Average is {0}%",aboveAvg);
            Console.WriteLine("Number of Students Above Average is {0}%",lessthanAvg);
         
        }
    }
}
=================
Edward is the highest with 100% 
Zesipho is the lowest with 29% 
The Average Mark is 65%
Number of Students less than Average is 2%
Number of Students Above Average is 3%

Example Deserialize a Json Array using Newtonsoft.Json

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Newtonsoft.Json;

namespace Rextester
{

public class MyClass
{
    public List<Item> data;
}
    public class Item
    {
        public string Comment;
        public string Name;
        public string CreationDate;
        public string Url;
        public string Uuid;
    }
    
    public class Program
    {
        static string json =@"
{
    'data': [
        {
            'comment': '<No comment>',
            'creationDate': '14.07.2016 22:14',
            'name': 'Name version 1',
            'url': 'http:\\\\www.google.com',
            'uuid': '12345'
        },
        {
            'comment': 'Hotfix. ',
            'creationDate': '14.07.2016 22:13',
            'name': 'Name version 2',
            'url': 'http:\\\\www.google.com',
            'uuid': '8888888'
        },
        {
            'comment': 'for test purposes',
            'creationDate': '14.07.2016 13:34',
            'name': 'Name version 3',
            'url': 'http:\\\\www.google.com',
            'uuid': 'hiuhihiuphpuihiuh'
        }
    ]
}
";
        
        public static void Main(string[] args)
        {
            //Your code goes here
            
            MyClass ss = JsonConvert.DeserializeObject<MyClass>(json);
            Console.WriteLine(ss.data[0].Comment);
            
        }
    }
}

StringCompare

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

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
       

           string str1="ri", str2 = "si";
         
            var common = str1.Intersect(str2);
         
         
            foreach(var c in common)
            {
                Console.Write(c);
         
            }
         
         

        }

    }

}
=========
i
      

Difference between Code first, Model first & Database first

n this article we are going to discuss difference between Code First, Model First & Data Base First. These are the basic approaches used in Entity Framework.  

Code first

  • popular in hardcore programmers.
  • The database is used for data only.
  • Manual changes to database will be lost because your code defines the database.
  • Full control by code.
Database first

  • Mostly used when Database is already created.
  • If you want additional features in POCO entities you must either T4 modify template or use partial classes.
  • Code is auto generated..
  • The developer can update the database manually.
Model first

  • We can create the database model.
  • Extensible through partial classes
  • Manual changes to database will be most probably lost because your model defines the database.