Tuesday, April 30, 2013

Convert jsonstring to c# list of objects

 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            WebRequest request = WebRequest.Create("Your Service Path");
            // If required by the server, set the credentials.

            // Get the response.
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            // 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.

            var responseFromServer = reader.ReadToEnd();
            
            string jsonString = responseFromServer;
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            DataResult collection = serializer.Deserialize<DataResult>(jsonString);

        }
    }
    

public class DataResult
{    
    [DataMember]
    public List<DataList> Data { get; set; }

}
[Serializable, DataContract]
public class DataList
{
    [DataMember]
    public string ID { get; set; }
    [DataMember]
    public string areaCode { get; set; }
    [DataMember]
    public string name { get; set; }

}

Note : Give the same name of class property which is match in json string like ID, areaCode, name and the Data which is in DataResult class.    

JsonString Exapmle :
 {"Data":[{"ID":"AF","areaCode":"93","name":"Afghanistan"}, {"ID":"AI","areaCode":"1","name":"Anguilla"}, {"ID":"AG","areaCode":"1","name":"Antigua and Barbuda"}, {"ID":"ZM","areaCode":"260","name":"Zambia"}, {"ID":"ZW","areaCode":"263","name":"Zimbabwe"}]}

Tuesday, April 2, 2013

Create SQL Table and Procedure in c#

  

 public string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

   public void ExcecuteSongBookScript()
    {
        DirectoryInfo rootFolder = new DirectoryInfo(Server.MapPath("../../TCPA"));
        string DirectoryPath = rootFolder + "\\" + "SongBookScript";
        SqlConnection con = new SqlConnection(str);
        con.Open();
        int countTbl;
        int countProc;

        
        SqlCommand cmdTbl = new SqlCommand("select count(*) from sys.objects where type='u' and name='SongBook'",con);
        countTbl = Convert.ToInt32(cmdTbl.ExecuteScalar());

        if (countTbl == 0)
        {
            if (!Directory.Exists(DirectoryPath))
            {
                Directory.CreateDirectory(DirectoryPath);
            }

            string filePathTable = DirectoryPath + "\\" + "SongBook.sql";

            if (!File.Exists(filePathTable))
            {
                System.IO.File.AppendAllText(filePathTable,


    "CREATE TABLE [dbo].[SongBook]([SongBookID] [int] IDENTITY(1,1) NOT NULL, [FormInserted] [datetime] NULL, [FormUpdated] [datetime] NULL,[Name] [nvarchar](300) NOT NULL,[StreetAddress] [nvarchar](max) NOT NULL,[City] [nvarchar](200) NULL,[State] [nvarchar](200) NULL,[Email] [nvarchar](300) NOT NULL,[Birthday] [datetime] NOT NULL,[YearinSchool] [nvarchar](10) NULL,[Highschool] [nvarchar](300) NULL,[Director] [nvarchar](300) NULL,[ParentName] [nvarchar](300) NULL,[ParentEmail] [nvarchar](300) NULL,[Status] [int] NULL,[Song1] [varchar](max) NULL,[Song2] [varchar](max) NULL,[DayPhone] [nvarchar](20) NULL,[EveningPhone] [nvarchar](20) NULL,[Photo] [varchar](max) NULL,CONSTRAINT [PK__SongBook__444243E5446B1014] PRIMARY KEY CLUSTERED ([SongBookID] ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]) ON [PRIMARY] " + Convert.ToChar(13).ToString() +

    "ALTER TABLE [dbo].[SongBook] ADD  CONSTRAINT [DEFAULT_SongBook_FormInserted]  DEFAULT ('11/9/2011 3:06:05 PM') FOR [FormInserted]" + Convert.ToChar(13).ToString() +

    "ALTER TABLE [dbo].[SongBook] ADD  CONSTRAINT [DEFAULT_SongBook_FormUpdated]  DEFAULT ('11/9/2011 3:06:05 PM') FOR [FormUpdated]" + Convert.ToChar(13).ToString() +

    "ALTER TABLE [dbo].[SongBook] ADD  CONSTRAINT [DEFAULT_SongBook_Name]  DEFAULT ('') FOR [Name]" + Convert.ToChar(13).ToString() +

    "ALTER TABLE [dbo].[SongBook] ADD  CONSTRAINT [DEFAULT_SongBook_Address]  DEFAULT ('') FOR [StreetAddress]" + Convert.ToChar(13).ToString() +

    "ALTER TABLE [dbo].[SongBook] ADD  CONSTRAINT [DEFAULT_SongBook_Email]  DEFAULT ('') FOR [Email]" + Convert.ToChar(13).ToString() +

    "ALTER TABLE [dbo].[SongBook] ADD  CONSTRAINT [DEFAULT_SongBook_Birthday]  DEFAULT ('11/9/2011 3:10:05 PM') FOR [Birthday]" + Convert.ToChar(13).ToString() +

    "ALTER TABLE [dbo].[SongBook] ADD  CONSTRAINT [DEFAULT_SongBook_Status]  DEFAULT ((0)) FOR [Status]");

                FileInfo file = new FileInfo(filePathTable);
                string script = file.OpenText().ReadToEnd();
                string[] splitter = { Convert.ToChar(13).ToString() };
                string[] sqlArray = script.Split(splitter, StringSplitOptions.None).ToArray();

                foreach (var item in sqlArray)
                {
                    SqlCommand cmd = new SqlCommand(item, con);
                    cmd.CommandType = CommandType.Text;
                    cmd.ExecuteNonQuery();
                }

            }

        }

        SqlCommand cmdProc = new SqlCommand("select COUNT(*) from sys.objects where type='p'and name='Proc_InsertSongBook'", con);
        countProc = Convert.ToInt32(cmdProc.ExecuteScalar());
        
        if (countProc == 0)
        {
            string filePathProc = DirectoryPath + "\\" + "Proc_InsertSongBook.sql";

            if (!File.Exists(filePathProc))
            {
                System.IO.File.AppendAllText(filePathProc, "CREATE procedure [dbo].[Proc_InsertSongBook](@FormInserted datetime,@FormUpdated datetime,@Name nvarchar(300),@StreetAddress nvarchar(max),@City nvarchar(200),@State nvarchar(200),@Email nvarchar(300),@Birthday datetime,@YearinSchool nvarchar(10),@Highschool nvarchar(300),@Director nvarchar(300),@ParentName nvarchar(300),@ParentEmail nvarchar(300),@Status int,@Song1 varchar(MAX),@Song2 varchar(MAX),@DayPhone nvarchar(20),@EveningPhone nvarchar(20),@Photo varchar(MAX)) as insert into SongBook values(@FormInserted,@FormUpdated,@Name,@StreetAddress,@City,@State,@Email,@Birthday,@YearinSchool,@Highschool,@Director,@ParentName,@ParentEmail,@Status,@Song1,@Song2,@DayPhone,@EveningPhone,@Photo)");
                FileInfo file = new FileInfo(filePathProc);
                string script = file.OpenText().ReadToEnd();
                SqlCommand cmd = new SqlCommand(script, con);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
            }
        }
    }