Wednesday, 28 September 2016

Convert Datatable to String or Datatable to Json string


Some times we came to situation where we need to convert data to string , it may be data table to string or data set to string .To do this I have created two function

To convert into string
public String DataTable2String(DataTable dt)
    {
        StringBuilder rst = new StringBuilder();
        foreach (DataRow row in dt.Rows)
        {
            foreach (DataColumn col in dt.Columns)
            {
                rst.Append(row[col] + "/**/");
            }
            rst.Append("/***/");
        }
        rst.Append("/****/");
        return rst.ToString();

        //column Deliminatoe-/**/
        //Row Deliminator Deliminatoe-/***/
        //table deliminator -/****/
    }

To convert into JSON
    public string DataTableToJson(DataTable table)
    {
        var lst = new List<Dictionary<string, object>>();
        foreach (DataRow row in table.Rows)
        {
            var dict = new Dictionary<string, object>();
            foreach (DataColumn col in table.Columns)
            {
                dict[col.ColumnName] = row[col];
            }
            lst.Add(dict);
        }
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return serializer.Serialize(lst);
    }

To run the program , we have to add the namespace
//add this Namespace
using System.Text;
using System.Data;

Now I am creating a data table
//define a data table
        DataTable dt = new DataTable();
        dt.Columns.Add("col1", typeof(String));
        dt.Columns.Add("col2", typeof(String));
        dt.Columns.Add("col3", typeof(Double));

I am adding some data to it
DataRow dr = dt.NewRow();
        dr["col1"] = "abc1";
        dr["col2"] = "efg1";
        dr["col3"] = "100";
        dt.Rows.Add(dr);


        //adding row to data table
        DataRow dr1 = dt.NewRow();
        dr1["col1"] = "abc2";
        dr1["col2"] = "efg2";
        dr1["col3"] = "200";
        dt.Rows.Add(dr1);

Now I am calling function to convert data table to string
string strdata = DataTable2String(dt);
output :abc1/**/efg1/**/100/**//***/abc2/**/efg2/**/200/**//***//****/

Now I am calling function to convert data table to Json
string strdata = DataTableToJson(dt);
//output : [{"col1":"abc1","col2":"efg1","col3":100},{"col1":"abc2","col2":"efg2","col3":200}]

SQL Server Split



 Some times we meet situation were we pass multiple value ,separeted with deliminator.We need to get the data and get the result in column wise.

 For example i am passing a parameter to a stored procedure which contain 5 student id,I need to get all id in a column for processing

 create procedure pr_school
 (
 @in_student VARCHAR(MAX)
 )

 EXEC pr_school '1,2,3,4,5'

In this situation we need to split the student record , we need a function
----------------------------------------------------------------
CREATE FUNCTION [dbo].[fn_GetSplit]
( 
    @sInputList VARCHAR(8000) -- List of delimited items 
  , @sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items 
) RETURNS @List TABLE (item VARCHAR(8000)) 
 
BEGIN 
DECLARE @sItem VARCHAR(8000) 
WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0 
 BEGIN 
 SELECT 
  @sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))), 
  @sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList)))) 
  
 IF LEN(@sItem) > 0 
  INSERT INTO @List SELECT @sItem 
 END 
 
IF LEN(@sInputList) > 0 
 INSERT INTO @List SELECT @sInputList -- Put the last item in 
RETURN 
END
 ---------------------------------------------------------------
Example 1:
 SELECT item  FROM dbo.fn_GetSplit('India,Russia,japan',',')

 Result :
 item
 India
 Russia
 japan
 here , deliminator is comma(,)

 Example 2:
 SELECT item  FROM dbo.fn_GetSplit('India/==/Russia/==/japan','/==/')

 Result :
 item
 India
Russia
japan

here , deliminator is some character ('/==/')

C# Tutorial Part 1 Introduction





                    .Net is a manage type safe environment for development and execution of software..Net framework allow us to memory allocation , storage and grant permission on software ..Net component can interact with each other , it does not matter , it is written in C# ,Vb.Net or else .This feature is possible for MSIL or Microsoft Intermediate Library .When a source code is compiled , complier convert the source code to Il or Inter mediate language , MSIL include loading ,storing ,initialization and calling method. We can view IL generated code by ILSAM.exe , Intermediate Language disassembly , which is present in .Net sdk folder.


    Another component of .Net is JIT , which convert MSIL code to machine code or CPU instruction during runtime.

            The CTS ensure the type compatibility between .Net component . CTS defines the predefined data type that are available in IL , so that all language target the .NET framework will produce the compiled code that is ultimately based on these types..Net source code can be written in C#,Vb.Net etc , but after MSIL compilation both will be same type as guaranteed by CTS . For Example Visual Basic Interger and C# will both represent as Syste.Int32.

          But when we are going to understand .Net architecture , we need to know assemble .Assembly also a compiled code for deployment , it is self describing and has collection of metadata .An assembly contain
  1. IL- Intermediate Language
  2. Metadata-data about data
  3. Manifest-Information about version.

Now what actually happen when a .Net program executed , When a Program executed , the assembly is the first loaded into memory .Now CLR examine the requirement to run the program .Then CRL create a process for the application .The JIT just convert the MSIL code to CPU instruction and loaded into memory as native code.


The .NET framework has its own Base class libraries which provide functions and features , implementation ,execution and  which can be  used with any programming language which implements .NET, such as Visual Basic, C# (or course), Visual C++, etc.

System : Responsible for  fundamentals of programming such as the data types, console, match and   arrays, loop ,event hadling

System.Data : Responsible for ADO.NET feature , dataaset , datatable,datareader ect.

System.Drawing : Responsible for  the GDI+ functionality for graphics support

System.IO: Responsible for file system and the reading and writing to data streams such as files.

System.Net: Responsible for network protocols such as SSL, HTTP, SMTP and FTP

System.Text: Responsible  for  StringBuilder class, plus regular expression capabilities.

System.Web: Namespace for ASP.NET capabilities such as Web Services and browser communication.

System.Windows.Forms: Namespace containing the interface into the Windows API for the creation of Windows Forms programs.



Value Type & Reference Type

Application memory is mainly divided into two memory component . Heap and Stack .
Heap is a separate area of memory for holding reusable objects .Actual object is allocated in Heap .A variable containing pointer to an object is allocated on stack , when call by stack actually return the memory address of the objects.

Value Type : Int/Bool/Struct /Enum
Reference Type :Class/array/interface/delegate

Value Type
  • Value Type  are stored on stack
  • Value Type  contains actual value
  • Value Type  cannot contain null values.
  • Value type is popped on its own from stack when they go out of scope.
  • For Value Type  Memory is allocated at compile time

Reference Type
  • Reference Type  are stored on heap
  • Reference Type contains reference to a value
  • Reference Type  can contain null values.
  • Reference Type required garbage collector to free memory.
  • Reference Type memory is allocated at run time
Stack
  • very fast access
  • local variables only
  • variables cannot be resized
  • It is a Last-in, First-out (LIFO) data structure
  • Static memory allocation

Heap

  • No limit on memory size
  • Variables can be resized
  • Fist in First Out
  • Dynamic memory allocation

Example of Stack
 
 int a=100;
 string ="C# program”;
  int a=5+6;

Exaple of Heap 

class MyClass
{
    int myInt = 0;
    string myString = "Something";
}

class Program
{
    static void Main(string[] args)
    {
       MyClass m = new MyClass();
    }
}

Namespaces
Namespaces are a logical grouping , it is not connected with physical file or code ect. Namespaces are generally  structured as hierarchies to use & reuse of names in different contexts . In Microsoft .Net ,a namespace is an abstract container providing context for the items . When we write  program , it is created  with a default namespace. This default namespace is called as global namespace. But the program has capability of declare any number of namespaces in it also , but it should be  a unique name. The result  is that every namespace can contain any number of classes, functions, variables and also namespaces etc., whose names are unique only inside the namespace. 

In C# , we can define

namespace namespace_name
{
    // code
}

For example I am writing names space student , and declaring object in it

namespace student
{
   class student_info
   {
     name string;  
     roll int;    
   }
}

Now I , can create instance of class “student_info” ,like  


student.student_info sc = new student. student_info();

We can use “using” keyword also to access the namespace. This statement tells the compiler that the subsequent code is making use of names in the that namespace.For example I am creating a namespace “class” and a class of name “class_info”


namespace class
{
   class class_info
   {
     class_name string;  
     no_of_student  int;
     class_teacher_name string;  
   }
}
 Now at the top , we should write 

using System;
using classes;
Now class under namespace “classes” , will be easily available .We ca use


class_info c1=new class_info();

 Namespace hierarchy
Namespaces allow you to create a systematic organized code via hierarchical system.
A good code should put the general name at the top of the hierarchy and more specific
As get down.
For example “System” is the highest level of  namespace hierarchy, “using System” will allow you some general coding , standard library etc.
System.Data, System.Net comes under “System” names space .” System.Data” will allow you to access data adopter, dataset,data reader ect. ” System.Net” for some netword component.Please see the below example


namespace Level1Hierchy
{
    class MyClass1
    {
        //defination of the class
    }
    namespace Level2Hierchy
    {
        // Program start class
        class MyClass2
        {
             //defination of the class
        }
    }
}

“Level1Hierchy” is the top level namespace , “Level2Hierchy” is under Level1Hierchy.
“MyClass2” is defined under “Level2Hierchy” , we need to write code to access
Level1Hierchy.Level2Hierchy.MyClass2 obj1 = new Level1Hierchy.Level2Hierchy.MyClass2();

But “MyClass1” is defined under “Level1Hierchy” , we can access by
Level1Hierchy.MyClass1 obj2 = new Level1Hierchy.MyClass1();

Tuesday, 27 September 2016

Table-value function sql server


There are three type of function in sql server
     1)Syetem function : which is defined by system
     2)Sclar-value function : function return single value
     3)Table-value function :function return an table
    
     Table-value function
     a)Return table
     b)only return a result set directly to a user
   
       

--we aree creating a table named STUDENT
CREATE TABLE STUDENT
(
id   INT IDENTITY,
NAME VARCHAR(500),
AGE  INT
)
--we are inserting values to the STUDENT table
INSERT INTO STUDENT(NAME,AGE)
VALUES ('NAME1',17)

INSERT INTO STUDENT(NAME,AGE)
VALUES ('NAME2',20)

INSERT INTO STUDENT(NAME,AGE)
VALUES ('NAME3',25)
--we aree creating a table named STUDENT_PARENTS
CREATE TABLE STUDENT_PARENTS
(
ID INT,
PARENT_NAME VARCHAR(500)
)
--we are inserting values to the STUDENT_PARENTS table
INSERT INTO STUDENT_PARENTS(ID,PARENT_NAME)
VALUES (1,'PARENT1')

INSERT INTO STUDENT_PARENTS(ID,PARENT_NAME)
VALUES (2,'PARENT2')
--we aree creating a table named MARKS
CREATE TABLE MARKS
(
id INT IDENTITY,
STUDENT_ID INT,
SUBJECT_ID INT,
MARKS      DECIMAL(18,2)
)
--we are inserting values to the MARKS table
INSERT INTO MARKS(STUDENT_ID,SUBJECT_ID,MARKS)
VALUES (1,1,95.23)

INSERT INTO MARKS(STUDENT_ID,SUBJECT_ID,MARKS)
VALUES (1,2,90.23)

INSERT INTO MARKS(STUDENT_ID,SUBJECT_ID,MARKS)
VALUES (2,1,80.00)

INSERT INTO MARKS(STUDENT_ID,SUBJECT_ID,MARKS)
VALUES (2,2,85.21)

----------------------------------------
/*
Now, i am creating a table value function , the function insert the data to a table variable depending
on parameter which has received
*/
CREATE FUNCTION fn_GetStudentDetais
(
@student_id INT
)
RETURNS @studentData TABLE
(
   NAME                   VARCHAR(500),
   AGE                    INT ,
   PARENT_NAME    VARCHAR(500)
)
AS
BEGIN
   INSERT INTO @studentData (NAME, AGE, PARENT_NAME)
   SELECT X.NAME,X.AGE,Y.PARENT_NAME FROM STUDENT X
   INNER JOIN STUDENT_PARENTS Y ON X.ID=Y.ID
   WHERE X.ID=@student_id
   RETURN;
END;
------------------------------------------
--like sclar function we can not run directly
SELECT dbo.fn_GetStudentDetais(5)
--Cannot find either column "dbo" or the user-defined function or aggregate "dbo.fn_GetStudentDetais", or the name is ambiguous.

--like sclar function we can not run directly with query
SELECT dbo.fn_GetStudentDetais(X.id) FROM STUDENT X
--Cannot find either column "dbo" or the user-defined function or aggregate "dbo.fn_GetStudentDetais", or the name is ambiguous.
-----------------------------------------------------------
--we have to write either cross apply , outer apply join to fetch the data from table-value function
SELECT ML.NAME,ML.AGE,ML.PARENT_NAME,V.MARKS
FROM MARKS V
OUTER APPLY dbo.fn_GetStudentDetais(V.STUDENT_ID) ML


011 Weekend Tour Jamsedpur


Jamsedpur is a city in the state of Jharkhand ,India . This city known as Tata Nagar and named after the famous industrialist Jamshedji tata .This city is well known for Tata industry in the world ,Tata steel , Tata motor ect ,the city is also known as “The steel city of india”. The city’s most infrastructure is build and maintained by Tata industry .The city is very well constructed clean and smooth.

What to see : Dalma lake ,Jubeille park, Tata steel Zoological Park, Russi Modi Center of Excellence ,Jayanti sarovar.





Dalma is located in kharai & Subarnarekha river . This Green forest is welknown for elephant inhabitant .One can go to visit elephant in the month of November to January .That time elephant comes down hill during the monsoon and winter and enter nearby locality.It is just 10 km away from Jamshedpur main city .Other than elephant , there are barking dear , sloth bear .This occasion leads to conflict between man and elephant.

Jubeilee park is an amusement park for all ages . There are several item for all ages .There are several item to make a child or youth thrill, most of are for child .The park was inaugurated by Pandit Jawaharlal Nehru.The most attractive feature of Jubeilee park is colorful fountain which is situated upvan of jubilee park .The spot is ideal for picnic also.




Tata steel Zoological park is a small , not very widely spread Zoo .But it is also well maintained by JUSCO .The animal have an good health , you will get almost all kind of animal in a short glimpse .There is a safari in between the park .Ticket is only Rs.10/- , while going through the safari, you will see several kind of dear moving around you .You can get an amazing boating experience here .The park is also Natural education center.

Dimna lake , it is man made lake with excellent scenic beauty .Blue color water surrounded by Green Dalma hill create a marvelous beauty here .You can spent some time here .This place is also attractive for water scooting , Jetking and other water sport.A lot of picnic party comes here every year and spent their day with Dalma.

Where to Stay : There are a lot of hotels in Jamshedpur.There hotels category are divided into two, Near railway station , the hotels are cheap , around sakchi the hotel are expensive . Sakchi is the elite are of Jamshedpur.

How to Reach : Howrah-Jamshedpur
Lalmati express, Howrah junction koraput Express ,howrak Rachi intercity Express ,Gitanjali Express

How declare table variable in sql


Declare a table variable
DECLARE @t table
( 
    id        INT Identity, 
    column1   VARCHAR(200)
)

insert value to the table 
insert into @t(a)
     select 'aa'
     union
     select 'bb'
     union
     select 'cc'
     union
     select 'dd'

Run select query
select * from @t
 
 
1       aa
2       bb
3       cc
4       dd 

Monday, 26 September 2016

009 Weekend Tour Bakkali

Bakkali is famous weekend destination among Bengali. It comes under Namkhana-Kakdip sub division of 24 pgs(s) ,West Bengal , India . Bakkali is ideal for them who wants to spend some time in river side , calm atmosphere with pure and fresh water . Bakkali beach is around 8 km long ,it is wide from Bakkali to Frasergung .You can walk through the beach , with rolling waves of sea touching your feet. 





How to Reach : By train , take Sealdha to Namkhana local , it will take around 2.30 hour , from there , take a van , go to ferry ghat of Hatania-Doania river , crossing river , you will get local bus/private car for Bakkahli .It will take around 45 minutes.

By car , you can also come here , Diamond Harbour-Namkhana-Kakdip .You have to take ferry to cross your vehicle Hatania-Doania river.This special Ferry are available always.






Where to stay: There are a plenty of hotels in Bakkhali , you can stay Bakkahli  or Frasergung , it is you own choice. There are accommodation of West Bengal Tourism , I recommended to stay there . Other hotels are  Hotels Dolphin , Hotel Amrabati, , Balaka Lodge.

What to see : Bakkali beach is the main attraction of Bakkahli , other are Frasergung , Watch tower , Jambu Dwip , Henry’s island .




                         Bakkali beach is wide beach , you can spent a lot of time of your tour in this beach .You can take a long walk here. Sunset and sun shine is a huge attraction for the tourist.There is a temple called Bishlashimi at the end of beach , you can worship here .Here you will find plenty of red crab along the beach .The sea wave are gentle and smooth , some visitor and local people take bath in the sea also .During the low tide , some goes among the sea , as the sea are not so deep.


                    Next you can go Frasergung .There ,you will see wind mill , just beside the sea beach . From there you can go to Frasergung harbor. Here you will see a lot of fisher man , all are busy with there own work, some are repairing fishing net, some are cooking. A lot of fishing trawler are there , some are preparing to set their journey to the sea ,some have just come .You will see people are carrying fish from trawler .
 

      From this Harbour , you can hire a "bhut-bhuti" and set you journey to Jambu dwip. The is not quite smooth , only lion hearted fellow are advise to take the ride. A small island with dense forest is the attraction of the island.


         Henry’s island is the next attraction of Bakkali .You have to hire  a car/ van to go there .While going there , you will watch Mangrove forest around you , tree of sundari , goran, hetal all arounf you , in between there are several pond , this are cultivation of porn locally know “Bagda Chinri” .There is watch tower , you can go to the top and take a view of the total island.

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...