Tuesday, May 17, 2022

GET and PUSH operation in ASP.NET C# with API and return JSON or XML

 using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using Luminious.Connection;

using Luminious.DataAcessLayer;

using System.Data.SqlClient;

using System.IO;

using System.Web.Script.Serialization;

using System.Collections;

using System.Text.RegularExpressions;

using System.Net;

using System.Text;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Security.Cryptography;


public partial class Skilldevelopment_Details : System.Web.UI.Page

{

    //CSComClass cc = new CSComClass();

    //CSUtility fcs = new CSUtility();


    DataSet ds;

    Hashtable param;

    

    string mcode = "37"; //As provided by DARPAN Dashboard.

    string State_Code = "0"; //Fixed.

    string Sector_Code = "23"; //As provided by DARPAN Dashboard.

    string Department_Code = "188"; //As provided by DARPAN Dashboard.

    string Project_Code = "10001"; //As provided by DARPAN Dashboard.


    // Step 1 API URL

    string PushDataAPIUrl = "http://api.dashboard.nic.in/MDREST/api/dashboard";

    // Step 2 API URL

    string GetDateRangeAPIUrl = "http://api.dashboard.nic.in/MDREST/api/DateRange";


    // Set the values of Stored Procedure which is used to perform actions on the SQL DataBase.

    string SQLDBStoredProc = "Save_Key_Demo";


 protected string ApiConnect(List<string> records, InputParam api)

    {

        try

        {

            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Accept.Clear();

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            httpClient.Timeout = TimeSpan.FromMinutes(60.0);


            var f = new Param();

            f.IP = api;

            f.Records = records;


            var inputContent = (new JavaScriptSerializer() { MaxJsonLength = 2147483644 }).Serialize(f);

            var buffer = Encoding.UTF8.GetBytes(inputContent);

            var byteContent = new ByteArrayContent(buffer);

            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpResponseMessage response = httpClient.PostAsync(PushDataAPIUrl, byteContent).Result;

            string xml = null;


            if (response.IsSuccessStatusCode)

            {

                xml = response.Content.ReadAsStringAsync().Result;


                if (xml.Equals("null"))

                    xml = null;

            }

            else

            {

                xml = response.Content.ReadAsStringAsync().Result;

            }


            return xml;

        }

        catch (Exception ex)

        {

            object response = null;

            var r = new { Status = "0", Message = ex.Message };

            response = r;

            return response.ToString();

        }

    }

protected string ApiConnectWithDaterange(InputParam api)

    {

try

        {

            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Accept.Clear();

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            httpClient.Timeout = TimeSpan.FromMinutes(60.0);


            //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetDateRangeAPIUrl);//PushDataAPIUrl     GetDateRangeAPIUrl

            //request.Method = "POST";

            //request.ContentType = "application/json";


            var f = new InputParam();

            f = api;


            var inputContent  = (new JavaScriptSerializer() { MaxJsonLength = 2147483644}).Serialize(f);

            var buffer = Encoding.UTF8.GetBytes(inputContent);

            var byteContent = new ByteArrayContent(buffer);

            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpResponseMessage response = httpClient.PostAsync(GetDateRangeAPIUrl, byteContent).Result;

            string xml = null;


            if (response.IsSuccessStatusCode)

            {

                xml = response.Content.ReadAsStringAsync().Result;


                if (xml.Equals("null"))

                    xml = null;

            }

            else

            {

                xml = response.Content.ReadAsStringAsync().Result;

            }


            return xml;

}

        catch (Exception ex)

        {

            object response = null;

            var r = new { Status = "0", Message = ex.Message };

            response = r;

            return response.ToString();

        }

    }


//Clicking on button

protected void btn_Api_Click(object sender, EventArgs e)

    {

        // new code 

        var g = new InputParam();

        g.mcode = Convert.ToInt32(mcode);

        g.state_code = Convert.ToInt32(State_Code);

        g.sec_code = Convert.ToInt32(Sector_Code);

        g.dept_code = Convert.ToInt32(Department_Code);

        g.project_code = Convert.ToInt32(Project_Code);


        string datefrom = "01/01/1900";

        string dateto = "01/01/1900";


        //Transaction_Log();


        

        try

        {

            DataSet ds2 = new DataSet();

            int cnt = 0;


            ds2 = ConvertJsonToDatatable(ApiConnectWithDaterange(g));


            cnt = ds2.Tables[0].Rows.Count;

            if (cnt > 0)

            {

                string op = "";

                op = ds2.Tables[0].Rows[0].ItemArray[0].ToString();


                if (op == "0" | op == "99" | op.Length > 10)

                {

                    lbl_API.Text = "No Date Found for Date Range";

                    return;

                }

                else if (cnt == 1)

                {

                    datefrom = ds2.Tables[0].Rows[0].ItemArray[1].ToString();

                    dateto = ds2.Tables[0].Rows[0].ItemArray[1].ToString();

                }

                else

                {

                    datefrom = ds2.Tables[0].Rows[0].ItemArray[1].ToString();

                    dateto = ds2.Tables[0].Rows[cnt - 1].ItemArray[1].ToString();

                }

            }


            //string ResultMessage = "";

            //ds = new DataSet();

            //param = new Hashtable();

            //param.Clear();

            //param.Add("@Flag", Flag2);

            //param.Add("@mCode", mcode);

            //param.Add("@state_code", State_Code);

            //param.Add("@sec_code", Sector_Code);

            //param.Add("@dept_code", Department_Code);

            //param.Add("@project_code", Project_Code);

            //param.Add("@datef", datefrom);

            //param.Add("@datet", dateto);

            //ds = getDatasetParametersp(SQLDBStoredProc, "", param);


            string Query = @"select 

                            37 as mcode,

                            0 as state_code,

                            0 as district_code,

                            0 as teh_code,

                            0 as blk_code,

                            23 as sector_code,

                            0 as gp_code,

                            0 as vill_code,

                            188 as dept_code,

                            10001 as project_code,

                            ISNULL(SD_Total_Target,0) as cnt1,

                            ISNULL(SD_ESDM,0) + ISNULL(SD_NIELIT,0) + ISNULL(SD_CDAC,0) as cnt2,

                            0 as cnt3,

                            0 as cnt4,

                            0 as cnt5,

                            5 as dataportmode,-- for yearly

                            case when convert(varchar,SD_Date,101) between '01/01/2019' AND '03/31/2019' THEN '1'

                            when convert(varchar,SD_Date,101) between '01/04/2019' AND '06/30/2019' THEN '2'

                            when convert(varchar,SD_Date,101) between '07/01/2019' AND '09/30/2019' THEN '3'

                            when convert(varchar,SD_Date,101) between '10/01/2019' AND '12/31/2019' THEN '4'

                            else '0' end as modedesc, --1 quarter1(jan feb mar)  2-- quarter2 (apr may june)

                            1 as data_lvl_code, --1 for centrally

                            year(SD_Date) as yr,

                            month(SD_Date) as mnth,

                            convert(varchar,CURRENT_TIMESTAMP,1) as Datadt

                            from [T004_SkillDevelopment]";


            ds = Luminious.DataAcessLayer.SqlHelper.ExecuteDataset(Luminious.Connection.Configuration.ConnectionString, System.Data.CommandType.Text, Query);

           

            string ResultMessage = "";


            if (ds.Tables.Count > 0)

            {

                if (ds.Tables[0].Rows.Count > 0)

                    ResultMessage = ApiConnect(ConvertTableToList(ds.Tables[0]), g);

                else

                    ResultMessage = "No Record found for the given date range.";

            }

            else

                ResultMessage = "No Data or KEY found.";


            // If Step 2 executed successfully, you got the message from API in "ResultMessage" Variable.


            DataSet ds1 = new DataSet();

            ds1 = ConvertJsonToDatatable(ResultMessage.Replace("=", ":"));


            // Update the existing record with the values, return from Web Api as a response.

            //LogEntry(datefrom, dateto, ds1.Tables[0].Rows[0].ItemArray[1].ToString());

            //Transaction_Log();


            lbl_API.Text = ds1.Tables[0].Rows[0].ItemArray[1].ToString();

            //string Query = "select 'Miety Skill Development Achievement' as 'Name',SD_ESDM + SD_NIELIT + SD_CDAC as 'Total' from [T004_SkillDevelopment]";


//            string GetDate_Query = @"select 

//                            38 as mcode,

//                            999 as state_code,

//                            188 as dept_code,

//                            40 as project_code,

//                            23 as sector_code";


//            string Query = @"select 

//                            0 as mcode,

//                            0 as state_code,

//                            0 as district_code,

//                            0 as teh_code,

//                            0 as blk_code,

//                            0 as sector_code,

//                            0 as gp_code,

//                            0 as vill_code,

//                            0 as dept_code,

//                            0 as project_code,

//                            ISNULL(SD_Total_Target,0) as cnt1,

//                            ISNULL(SD_ESDM,0) + ISNULL(SD_NIELIT,0) + ISNULL(SD_CDAC,0) as cnt2,

//                            0 as cnt3,

//                            0 as cnt4,

//                            0 as cnt5,

//                            7 as dataportmode,-- for quarterly

//                            case when convert(varchar,SD_Date,101) between '01/01/2019' AND '03/31/2019' THEN '1'

//                            when convert(varchar,SD_Date,101) between '01/04/2019' AND '06/30/2019' THEN '2'

//                            when convert(varchar,SD_Date,101) between '07/01/2019' AND '09/30/2019' THEN '3'

//                            when convert(varchar,SD_Date,101) between '10/01/2019' AND '12/31/2019' THEN '4'

//                            else '0' end as modedesc, --1 quarter1(jan feb mar)  2-- quarter2 (apr may june)

//                            1 as data_lvl_code, --1 for centrally

//                            year(SD_Date) as yr,

//                            month(SD_Date) as mnth,

//                            convert(varchar,CURRENT_TIMESTAMP,101) as Datadt

//                            from [T004_SkillDevelopment]";


//            ds = Luminious.DataAcessLayer.SqlHelper.ExecuteDataset(Luminious.Connection.Configuration.ConnectionString, System.Data.CommandType.Text, Query);

            

//            //ds = Luminious.DataAcessLayer.SqlHelper.ExecuteDataset(Luminious.Connection.Configuration.ConnectionString, System.Data.CommandType.Text, GetDate_Query);


//            try

//            {

//                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer() { MaxJsonLength = 86753090 };

//                ArrayList root = new ArrayList();

//                List<Dictionary<string, object>> table;

//                Dictionary<string, object> data;


//                foreach (DataTable dt in ds.Tables)

//                {

//                    table = new List<Dictionary<string, object>>();

//                    foreach (DataRow dr in dt.Rows)

//                    {

//                        data = new Dictionary<string, object>();

//                        foreach (DataColumn col in dt.Columns)

//                        {

//                            data.Add(col.ColumnName, dr[col]);

//                        }

//                        table.Add(data);

//                    }

//                    root.Add(table);

//                }



//                JavaScriptSerializer js = new JavaScriptSerializer();

//                Context.Response.Write(js.Serialize(root));


//                lbl_API.Text = js.Serialize(root);


                


//                try

//                {

//                    // Step 1: Call Method to Get Date Range "ApiConnectWithDaterange"


//                    //DataSet ds2 = new DataSet();

//                    int cnt = 0;


//                    string S1 = ApiConnectWithDaterange(g);


//                    //cnt = S1;//ds2.Tables[0].Rows.Count;

//                }

//                catch { }

//            }

//            catch { }

//        }

//        catch (Exception ex1)

//        {

//        }


//        Transaction_Log();

        }

        catch (Exception ex)

        {

            object response = null;

            var r = new { Status = "0", Message = ex.Message };

            response = r;


            // Inset/Update the existing record with the exception message.

            //LogEntry(datefrom, dateto, ex.Message);

        }

    }

}


reference:- https://www.alphavantage.co/documentation/

No comments:

Post a Comment