Send an HTML POST to api using basic authentication with C#

To secure your api, you need at least the basic authentication. Here is a way to post to the secure api

 

using (WebClient client = new WebClient())
{

// set the variables for the basic authentication needed
String userName = “myusername”;
String passWord = “mysecretpassword”;
// convert the auth vars into a credential string
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + “:” + passWord));

// add the auth string to the request header
client.Headers[HttpRequestHeader.Authorization] = “Basic ” + credentials;
byte[] response =
client.UploadValues(“http://mySweetAPI.aspx”, new NameValueCollection()
{
{ “Title”, “The title of my post” },
{ “Body”, “The body of my post.” }
});

string result = System.Text.Encoding.UTF8.GetString(response);
LabelResponse.Text = result;
}

Send a JSON payload in C# using newtonsoft JSON package

To send and recieve JSON using C# in visual studio, you must install the NuGET package : Newtonsoft Json. Then you can use it to send a payload:

 

// set the text that will be the  json payload as a variable.
var TestJsonMessage = new { id = "8", text = "This is a test of the Newtonsoft package", sentDate = System.DateTime.Now };

// use a web client object
using (WebClient client = new WebClient())
            {
                // convert the variable into JSON
                var dataString = JsonConvert.SerializeObject(TestJsonMessage);
                 // add the content type headers !! super important 
                client.Headers.Add(HttpRequestHeader.ContentType, "application/json");

             // set a string to recieve the response, and send the payload to an api
               string theresponse =
                client.UploadString("http://someapiaddress", "POST", dataString);

                // display the response on the page for debugging.
                LabelResponse.Text = theresponse;
            }

 

 

Receive a JSON payload C#

I have been tasked to receive a JSON payload to my API that was made to recieve http post variables. We are going to receive the request stream and convert it into a byte array, then DeSerialize the JSON using the Newtonsoft JSON .Net package. When we are finished, we will have a Dictionary object with the contents of the JSON payload. This technique will only work for a single JSON object, as the dictionary can only hold a unique key and value (id:1, text:This is the text)

We will need to get the total number of bytes in the stream to set the array length.

// set a variable to hold the incoming stream.
System.IO.Stream str;

// set two variables for the stream array
Int32 strLen, strRead;

// Create a Stream object.
str = Request.InputStream;
// Find number of bytes in stream.
strLen = Convert.ToInt32(str.Length);
// Create a byte array.
byte[] strArr = new byte[strLen];
// Read stream into byte array.
strRead = str.Read(strArr, 0, strLen);
// change they bytes into UTF8 text
string response = Encoding.UTF8.GetString(strArr);
// convert the JSON object into a .net dictionary
Dictionary<string, string> MyData = JsonConvert.DeserializeObject<Dictionary<string, string>>(response);
// display the JSON payload for debugging
LabelPostVars.Text = response;

Asp array from comma delimited list

This is a handy snipped to create an array from a list of items separated by a comma, like you would get submitted from a checkbox group. Its as easy as using the “Split” function as so:

MyString = "ItemOne, ItemTwo, ItemThree"
MyArray= Split(MyString , ",")

 

You could then access the elements using the standard array language MyArray(x)

For x = LBound(MyArray) to UBound(MyArray)
    Response.Write MyArray(x)
Next

Database connection and query using c#

First you need to add a connection string. For a Webforms app, I add them to the web.config file.

 

<configuration>

<connectionStrings>
<add name="devConn" connectionString="Data Source=1.2.3.4;network library=DBMSSOCN;Initial Catalog=Deveee;Persist Security Info=True;User ID=ADevUser;Password=*********" />
</connectionStrings>

....</configuration>

 

 

Then you can use the connection string to connect to a database…

 

public static bool SaveRecordToDB(string myData, out string Message, out int returnCode){

System.Data.SqlClient.SqlCommand objCmd;
System.Data.SqlClient.SqlConnection objConn = new        System.Data.SqlClient.SqlConnection();            objConn.ConnectionString = WebConfigurationManager.ConnectionStrings["devConn"].ConnectionString;

int rowsAffected = 0;
try
{
objConn.Open();

objCmd = new System.Data.SqlClient.SqlCommand();

objCmd.Connection = objConn;
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.CommandText = "usp_add_alert";
System.Data.SqlClient.SqlParameter objP1 = new System.Data.SqlClient.SqlParameter();
objP1.Direction = ParameterDirection.Input;
objP1.ParameterName = "@head";
objP1.SqlDbType = SqlDbType.NVarChar;
objP1.Size = 50;
objP1.Value = emer_head;
objCmd.Parameters.Add(objP1);
System.Data.SqlClient.SqlParameter objRC = new System.Data.SqlClient.SqlParameter();
objRC.Direction = ParameterDirection.ReturnValue;
objRC.SqlDbType = SqlDbType.Int;
objRC.ParameterName = "@ID";
objCmd.Parameters.Add(objRC);

rowsAffected = objCmd.ExecuteNonQuery();
returnCode =                     System.Convert.ToInt32(objCmd.Parameters["@ID"].Value.ToString());
}
catch (Exception e)
{
Message = e.Message;
returnCode = 0;
return false;
}
finally
{
objConn.Close();
}

if (rowsAffected > 0 && returnCode > 0)
{

return true;
}
else
{
Message = "Record Add not successfull";

return false;
}

}

 

 

Then you can call the method when you need to in your code…

 

I prefer this method of adding the stored procedure parameters…

//********* create a new page section record ***********
public static bool DBcreatePageSection(int UID, string title, string body, int sequence, string photo, string byline, string date, out string Message)
{
Message = "";
System.Data.SqlClient.SqlCommand objCmd;
System.Data.SqlClient.SqlConnection objConn = new System.Data.SqlClient.SqlConnection();
objConn.ConnectionString = WebConfigurationManager.ConnectionStrings["facSiteConn"].ConnectionString;
int rowsAffected = 0;
try
{
objConn.Open();
objCmd = new System.Data.SqlClient.SqlCommand();
objCmd.Connection = objConn;
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.CommandText = "usp_DBcreatePageSection";
objCmd.Parameters.Add("@UID", SqlDbType.Int).Value = UID;
objCmd.Parameters.Add("@Sequence", SqlDbType.Int).Value = sequence;
objCmd.Parameters.Add("@Heading", SqlDbType.VarChar, 500).Value = title;
objCmd.Parameters.Add("@Body", SqlDbType.Text).Value = body;
objCmd.Parameters.Add("@Photo", SqlDbType.VarChar, 500).Value = photo;
objCmd.Parameters.Add("@ByLine", SqlDbType.VarChar, 500).Value = byline;
objCmd.Parameters.Add("@Date", SqlDbType.VarChar, 500).Value = date;


rowsAffected = objCmd.ExecuteNonQuery();

}
catch (Exception e)
{
Message = e.Message;

return false;
}
finally
{
objConn.Close();
}

if (rowsAffected > 0)
{

return true;
}
else
{
Message = "Record ADD not successfull" + Message;

return false;
}

}
//---------------------------------------------------


Here’s how to call for records and put them in a dataset

 public static bool DBgetUserName(DataSet UserInfo, string SID, out string errInfo)
        {
            errInfo = "";
            System.Data.SqlClient.SqlCommand objCmd;
            System.Data.SqlClient.SqlConnection objConn = new System.Data.SqlClient.SqlConnection();
            objConn.ConnectionString = WebConfigurationManager.ConnectionStrings["ODSConnectionString_ctcLink"].ConnectionString;
            System.Data.SqlClient.SqlDataAdapter objDA;
            try
            {
                objConn.Open();

                objCmd = new System.Data.SqlClient.SqlCommand();

                objCmd.Connection = objConn;
                objCmd.CommandType = CommandType.StoredProcedure;
                objCmd.CommandText = "usp_GetEmpFromEmpInfo_ctcLink";

                System.Data.SqlClient.SqlParameter objP5 = new System.Data.SqlClient.SqlParameter();
                objP5.Direction = ParameterDirection.Input;
                objP5.ParameterName = "@sid";
                objP5.SqlDbType = SqlDbType.NVarChar;
                objP5.Size = 9;
                objP5.Value = SID;
                objCmd.Parameters.Add(objP5);

                objCmd.Parameters.AddWithValue("@LastName", "%");
                objCmd.Parameters.AddWithValue("@FirstName", "%");



                objDA = new System.Data.SqlClient.SqlDataAdapter();
                objDA.SelectCommand = objCmd;
                objDA.Fill(UserInfo, "UserInfo");

            }
            catch (Exception e)
            {
                errInfo = e.Message;
                UserInfo = null;
                return false;
            }
            finally
            {
                objConn.Close();
            }

            return true;
        }

heres how to call for a single record and put into variables.

   public static bool getFacultyInfo(string SID, out int lid, out int uid, out string title, out string URL, out string errMsg)
        {
            errMsg = "";
            string connStr = ConfigurationManager.ConnectionStrings["facSiteConn"].ConnectionString;
            using (SqlConnection connection = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = new SqlCommand("usp_getFacultyInfo", connection))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@SID", SqlDbType.Char, 9).Value = SID;
                    try
                    {
                        connection.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            if (sdr.HasRows)
                            {
                                sdr.Read();
                                lid = Convert.ToInt32(sdr["LoginID"]);
                                uid = Convert.ToInt32(sdr["UniverseID"]);
                                title = sdr["Title"].ToString();
                                URL = sdr["DirectURL"].ToString();

                                connection.Close(); return true;
                            }
                            else
                            {
                                lid = 0;
                                uid = 0;
                                title = "";
                                URL = "";
                                connection.Close(); return false;
                            }
                        }
                    }
                    catch (SqlException sqlex)
                    {
                        string error = sqlex.Message;
                        errMsg = error.ToString();
                        lid = 0;
                        uid = 0;
                        title = "";
                        URL = "";
                        return false;
                    }
                }
            }
        }
        //----------------------------------------------------------------------

Working with c# dataset

A Data Set resembles a database. Data Table resembles the database table. Data Row resembles a record in the table.

DataSet reqClasses = new DataSet();
DataTable reqClassesTable = new DataTable();

//.. from stored procedure … selecting ClassID from InstCrsReq …The dataset is defined as DataSet reqList in this line…
objDA.Fill(reqList, “ReqList”);

So I can access the data using this assignment…
reqClassesTable  = reqClasses.Tables[“reqList”];

Then I can loop through the data and do whatevs…
foreach (DataRow row in reqClassesTable.Rows)
{string ClassID = row[“ClassID”].ToString();}

Another way to use the data set is to call to a database and return one.

DataSet movieList = new DataSet();
myDatabaseCall(movieList);

movieList.Tables[“movieList”] now contains the results of the database call, maybe somthing like:

MovieIDMovieName
1The Matrix
2Justice League

You can loop through the rows as so…

foreach (DataRow row in movieList.Tables[“movieList”] )

{ Label1.Text += row[“MovieName”];}

The control named “Label1” would contain: The MatrixJustice League

because I didn’t use any logic to add commas or a space between the field results display.