‘C#’ Archive

C# asp.net verify Twitter credential via Twitter API

If you want to check (verify) a Twitter account login information or check (verify) a Twitter account credential for some reason, let’s try asp.net (C#) code below.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;
using System.Text;
using System.Xml;

public partial class verify_twitter_credential : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string twitter_username = "your_username";
        string twitter_password = "your_password";
        string twitter_verify_credential_url = "https://twitter.com/account/verify_credentials.xml";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(twitter_verify_credential_url);

        request.Method = "GET";
        request.MaximumAutomaticRedirections = 4;
        request.MaximumResponseHeadersLength = 4;
        request.ContentLength = 0;

        request.Credentials = new NetworkCredential(twitter_username, twitter_password);

        StreamReader readStream;

        HttpWebResponse response = null;

        try
        {
            response = (HttpWebResponse)request.GetResponse();

            if (response.StatusCode.ToString() == "OK")
            {
                Response.Write("Okay, your twitter account is authorized successful!");
            }
        }
        catch (WebException wex)
        {
            HttpWebResponse ErrorResponse = (HttpWebResponse)wex.Response;

            if (ErrorResponse.StatusCode == HttpStatusCode.Unauthorized)
            {
                Response.Write("Authorization Failed");
            }
            else if (ErrorResponse.StatusCode == HttpStatusCode.InternalServerError)
            {
                Response.Write("Twitter is currently unavailable.");
            }
            else if (ErrorResponse.StatusCode == HttpStatusCode.ServiceUnavailable)
            {
                Response.Write("Twitter is overloaded or you are being rate limited.");
            }
            else
            {
                Response.Write("StatusCode: " + ErrorResponse.StatusCode + "<br>");
                Response.Write("Message: " + wex.Message);
            }
        }
    }
}

C# Auto-Implemented Properties Example

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field can only be accessed through the property’s get and set accessors.

Example

public class User
{
	public int ID { get; set; }
	public string UserName { get; set; }
	public string ScreenName { get; set; }
	public string Location { get; set; }

	public override string ToString()
	{
		return (string.IsNullOrEmpty(this.UserName) ? this.ScreenName : this.UserName);
	}
}

asp.net c# read csv and bulk insert to MSSQL

What we are learning from this post:

  • 1. Parsing CSV file to a LIST (namespace: using System.Collections.Generic;)
  • 2. Creating a DataTable with CSV columns then store all CSV rows
  • 3. Using SqlBulkCopy to batch insert all CSV rows to Microsoft Sql Server with one database connection

Here we go

1. Assume we have a mssql table SongVoteRpt with 5 columns as sql script below:

CREATE TABLE [dbo].[SongVoteRpt](
	[SongVoteId] [int] NULL,
	[SongId] [int] NULL,
	[IPAddress] [varchar](20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
	[CurrentVote] [int] NULL,
	[VotedDate] [datetime] NULL CONSTRAINT [DF_SongVoteRpt_VotedDate]  DEFAULT (getdate())
) ON [PRIMARY]

2. We have a CSV file with 5 columns respectively need to be imported to mssql server database:

SongVoteId,SongId,IPAddress,CurrentVote,VotedDate,
1,30,210.245.33.233,1,4/20/2007 8:43:46 PM,
2,3,125.214.44.80,1,4/22/2007 10:01:06 PM,
3,30,125.214.44.80,1,4/22/2007 10:01:32 PM,
4,36,125.214.44.80,1,4/22/2007 10:01:34 PM,
5,42,125.214.44.80,1,4/22/2007 10:01:49 PM,
6,30,125.214.44.80,1,4/22/2007 10:02:16 PM,

3. Create a super simple .aspx page with one textbox to get csv file which is entered by user and one button to make action

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="aa_read_csv.aspx.cs" Inherits="aa_read_csv" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        CSV filename: <asp:TextBox ID="txt_csv_filename" runat="server"></asp:TextBox> <asp:Button runat="server" ID="btn_Go" OnClick="btn_Go_Click" Text="Go" />
    </div>
    </form>
</body>
</html>

4. Declare database connection information and do the rest

using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class aa_read_csv : System.Web.UI.Page
{
    string db_server = "";
    string db_name = "";
    string db_user = "";
    string db_password = "";

    string csv_filename = "";
    string table_name = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        db_server = "192.168.1.8";
        db_name = "song";
        db_user = "sa";
        db_password = "123456";

        csv_filename = txt_csv_filename.Text.Trim();
        table_name = "SongVoteRpt";
    }

    public List<string[]> parseCSV(string path)
    {
        List<string[]> parsedData = new List<string[]>();

        using (StreamReader readFile = new StreamReader(path))
        {
            string line;
            string[] row;

            char[] separator = new char[] { ',' };

            while ((line = readFile.ReadLine()) != null)
            {
                if (line != "")
                {
                    string[] row_tmp = new string[5];

                    row = line.Split(separator);

                    for (int i = 0; i < row.Length - 1; i++)
                    {
                        row_tmp[i] = row[i];
                    }

                    parsedData.Add(row_tmp);
                }
            }
        }

        return parsedData;
    }

    protected void btn_Go_Click(object sender, EventArgs e)
    {
        List<string[]> testParse = parseCSV(Server.MapPath(csv_filename));

        DataTable newTable = new DataTable();

        int first_line = -1;

        foreach (string[] row in testParse)
        {
            first_line++;

            //Parse the CSV first line to create DataTable Column
            if (first_line == 0)
            {
                foreach (string column in testParse[0])
                {
                    newTable.Columns.Add();
                }
            }
            else // Insert CSV rows to DataTable
            {
                newTable.Rows.Add(row);
            }
        }

        string dbConnString = "Data Source=" + db_server + ";Initial Catalog=" + db_name + ";Persist Security Info=True;User ID=" + db_user + "; Password=" + db_password + ";";

        SqlBulkCopy bulkCopy = new SqlBulkCopy(dbConnString, SqlBulkCopyOptions.TableLock);
        bulkCopy.DestinationTableName = table_name;
        bulkCopy.BulkCopyTimeout = 0;
        bulkCopy.WriteToServer(newTable);

        Response.Write("Row inserted: " + first_line.ToString());
    }
}

StreamReader Namespace

Here we go:

C#

using System.IO;

VB.net

Imports System.IO

asp.net c# convert text to URL or email automatically

By using using System.Text.RegularExpressions;, you can detect if a string contains url[s] or email address[es] then wrap them into hyperlink or mailto email address, respectively.

Below is an example on how to wrap text to hyperlink or email

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

public partial class automatically_hyperlink : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string content = "Lets visit http://www.rapid-dev.net" + " to accumulate and share your experience.<br>";
        content += "Any feedback, please send an email to info@rapid-dev.net";

        Regex url_regex = new Regex(@"(http:\/\/([\w.]+\/?)\S*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);

        Regex email_regex = new Regex(@"([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);

        content = url_regex.Replace(content, "<a href=\"$1\" target=\"_blank\">$1</a>");
        content = email_regex.Replace(content, "<a href=mailto:$1>$1</a>");

        Response.Write(content);
    }
}

Output:

Lets visit http://www.rapid-dev.net to accumulate and share your experience.
Any feedback, please send an email to info@rapid-dev.net

Lets visit <a href="http://www.rapid-dev.net" target="_blank">http://www.rapid-dev.net</a> to accumulate and share your experience.<br>
Any feedback, please send an email to <a href=mailto:info@rapid-dev.net>info@rapid-dev.net</a>