Autocomplete with Ajax and JSON

Autocomplete with Ajax and JSON is as simple as this:

In your ASPX page:

<script type="text/javascript">
    $(function () {
        $("[id$=txtLastNameSearch]").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("Home.aspx/GetLastName") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function(item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }));
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("[id$=LastName]").val(i.item.val);
            },
            minLength: 3
        });
    });  
</script>

Enter Last Name: <asp:TextBox ID="txtLastNameSearch" runat="server" />
<asp:HiddenField ID="LastName" runat="server" />


And in your code behind:

        [WebMethod]
        public static string[] GetLastName(string prefix)
        {
            var lastName = new List<string>();
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "SELECT LastName FROM tbl_Profile WHERE LastName LIKE @SearchText + '%'";
                    cmd.Parameters.AddWithValue("@SearchText", prefix);
                    cmd.Connection = conn;
                    conn.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            lastName.Add(sdr["LastName"].ToString());
                        }
                    }
                    conn.Close();
                }
            }
            return lastName.ToArray();
        }

Unit Testing the ASP.NET WebForm (Part 2)

In Unit Testing the ASP.NET WebForm (Part 1), I showed you how to unit test the Create method in our data model or class. This time, I'll show you a simple way to unit test the Generic List<T> method in displaying records from the database and bind the result to GridView.


** Test Class **

[TestClass]
class ProfileTests
{
    [TestMethod]
    public void Get_All_Profile()
    {
        //Arrange
        var profile = new List<Profile>();
    
        //Act
        var results = ProfileData.Get_All_Profile();
    
        //Assert
        Assert.IsTrue(profile.SequenceEqual(results));
        Assert.IsNotNull(results);
    }
}


** Data Model **

public static List<Profile> Get_All_Profile()
{
    var profile = new List<Profile>();
    using (var con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ProfileConnectionString"].ConnectionString))
    {
        string strSelect = "SELECT Name, Age FROM Profile";
        var cmd = new SqlCommand(strSelect, con);
        con.Open();
        var reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            var result = new Profile
            {
                Name = reader.GetString(0),
                Age = reader.GetDecimal(1)
            };
            profile.Add(result);
        }
        reader.Close();
    }
    return profile;



** Business Model **

public class Profile
{
    public int ProfileId { get; set; }
    public string Name { get; set; }
    public decimal Age { get; set; }



** Code Behind **

void Display_Profile()
{
    Profiles = ProfileData.Get_All_Profile();
    GridView1.DataSource = Profiles.ToList();
    GridView1.DataBind();
}

Unit Testing the ASP.NET WebForm (Part 1)

Unit testing an ASP.NET Webform gives us more challenging job than a loosely coupled MVC. In practice, we just unit test custom controls and the methods that perform actual logic. In doing so, we try to minimize the code behind and put all those logic in separate libraries or classes.

In my example below, I try to write a unit test (using MSTest) on a method that inserts a new record to the database:


** Test Class **

[TestClass]
class ProfileTests
{
    [TestMethod]
    public void Create_New_Profile_Should_Save_New_Record()
    {
        //Arrange
        var content = new Profile { ProfileId = 1, Name = "Bob", Age = 21m};

        //Act
        var results = ProfileData.Create_New_Profile(content);

        //Assert
        Assert.IsNotNull(results);
    }
}


** Data Model **

public class ProfileData
{
    public static Profile Create_New_Profile(Profile profiles)
    {
        using (var con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ProfileConnectionString"].ConnectionString))
        {
            string strInsert = "INSERT INTO Profile (Name, Age) VALUES(@Name, @Age)";
            var cmd = new SqlCommand(strInsert, con);
            cmd.Parameters.AddWithValue("@Name", profiles.Name);
            cmd.Parameters.AddWithValue("Age", profiles.Age);
            con.Open();
            var profile = new Profile
                {
                    Name = profiles.Name,
                    Age = profiles.Age
                };
            cmd.ExecuteNonQuery();
            con.Close();
            return profile;
        }
    }
}


** Business Model **

public class Profile
{
    public int ProfileId { get; set; }
    public string Name { get; set; }
    public decimal Age { get; set; }



** Code Behind **

protected void btnSave_Click(object sender, EventArgs e)
{
    var profile = new Profile
    {
        Name = txtName.Text,
        Age = Decimal.Parse(txtAge.Text)
    };
    Profiles = ProfileData.Create_New_Profile(profile);
}

"Resources was specified more than once” or "Resource name xxx cannot be used more than once"

Have you experienced getting an error that says, "Resources was specified more than once” or "Resource name xxx cannot be used more than once"?

Usually it happened when you just copy/paste a form from your old project to the new one. Or sometimes if you "accidentally" include the obj folder to your existing project.

In any case, the simplest solution to this is by simply removing the obj folder to your project or solution.

Hope it helps you.

Creating a Table With a Column Value to be Generated Automatically as GUID

Let's say you want to create a table tbl_Users with columns Id, UserId, and Name.

To generate a GUID (uniqueidentifier) automatically for column UserId, you simply need to add DEFAULT NEWSEQUENTIALID() to the UserId column when you create a table like the sample below:

CREATE TABLE [dbo].[tbl_Users]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY,
    [UserId] UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID(),
    [Name] VARCHAR(50) NULL
)

Calling Stored Procedure from Entity Framework

Let's say we have a simple stored procedure that displays all the records from tbl_Sales table:

CREATE PROCEDURE [dbo].[sp_DisplayRecord]
AS
BEGIN
    SELECT * FROM tbl_Sales
END


Assuming that ctx is our DbContext, we can call the stored procedure from EF using the following command:

var query = ctx.Database.SqlQuery<tbl_Sales>("sp_DisplayRecord").AsEnumerable();

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive).

Have you experienced this problem when you browsed your website or web application using Visual Studio 2013 or 2015?

A simple solution to this issue is to add something like the one below on your web.config file:

<appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>

Filtering The Result Based On Specific User

In one of my seminars, one student asked me how to filter the result of database query to specific user and display it in GridView.

Okay, here's what we did:


Assuming that  we have a table named tbl_Profile with columns Name (varchar), Age (int), Address (varchar), Birthdate (date), and UserId (uniqueidentifier)

Now, if we want to display the records that belong to the specific user, we simply add a Label on the page and set its visibility to false.

ex. Label1.visible = false;

Then in our query, we filter the result using WHERE clause like this:


SELECT Name, Age, Address, Birthdate FROM tbl_Profile WHERE UserId=@UserId

ASP.NET Essential Training for Developers

Conducted a successful training on ASP.NET Essential Training for software developers of Manly Plastics, Inc.


Seminar on Cloud Computing with Microsoft Azure

Had a great experience sharing the basics of cloud computing with Microsoft Azure to hundreds of students and faculty members of Colegio de Porta Vaga in Imus City, Cavite, Philippines.




ASP.NET in Practice goes to AMA Computer College - ParaƱaque City (Philippines)

Sharing my real-life experiences as .NET developer, as well as my in-depth knowledge in ASP.NET, to our young developers is fun and fulfilled!




Inserting Null Value from Code Behind

Just so happened to check some old codes and found out how we assigned null values from code behind. The code looks like this:

System.Data.SqlTypes.SqlDateTime getDate;
getDate = SqlDateTime.Null;
    if (DateDelivered.Text == "")
    {
        cmd.Parameters.Add(new SqlParameter("@DateDelivered ", SqlDbType.DateTime)).Value = getDate;
    }
    else
    {
        cmd.Parameters.Add(new SqlParameter("@DateDelivered ", SqlDbType.DateTime)).Value = DateTime.Parse(DateDelivered.Text);
    }


I know it works fine. But I'm looking for ways for a better (or maybe shorter) approach.

Unable to cast object of type 'System.Int32' to type 'System.String'.

I attended a student brainstorming session this morning. One of the students asked a question to the group about the possible reason why this error appeared on the screen:

Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.

Many newbies assumed that it's a casting error. They even offered him numerous solutions without first inspecting the program.

10 minutes later, they still couldn't figure out the solution to the error.

When I checked it, my first instinct was to read his codes and inspect his SQL query. Then I found that the error appeared simply because he forgot the comma (,) between the two columns in his SQL query!

My advice: Read codes when debugging (and minimize the talking).


Adding Decimal Numbers in String Format

In one of my seminars, a high school student asked me what's a simple way to add two decimal numbers from the two textbox and display the result on the third textbox.

I know it's so simple and we have 'shortcuts' in doing this task. But since I found that it's a common question by some public high school studs who attended my seminars, I decided to post here a simple solution that can be easily understood by students:


decimal num1 = 0;
decimal num2 = 0;

if (txtValue1.Text != "")
    {
        decimal value1 = Decimal.Parse(txtValue1.Text);
        num1 = value1;
    }

if (txtValue2.Text != "")
    {
        decimal value2 = Decimal.Parse(txtValue2.Text);
        num2 = value2;
    }

var total = num1 + num2;

txtTotal.Text = total.ToString();



Converting String To Integer Properly

If I have a string myNumber = '21' and I want it to convert to an integer, the proper way to do this is to use TryParse like this:

int x = 0;

Int32.TryParse(myNumber, out x);

By using TryParse, it won't throw exceptions if in case your string (text) is non-numeric.

Accessing The Label Inside The DetailsView DataBound

 If I have a Label (lblAmount) in my DetailsView's TemplateField, one of the simplest way to access it and modify its format is shown below:

       Label myLabel = dvIncomeSummary.FindControl("lblAmount") as Label;
       string newLabelFormat = myLabel.Text;
       const string fmt1 = "#,##0.00;(#,##0.00)";
       double newAmountFormat = Double.Parse(newLabelFormat);
       string myAmountFormat = newAmountFormat.ToString(fmt1);
       newLabelFormat = myAmountFormat;
       myLabel.Text = newLabelFormat;

       

Accessing The Label Inside The GridView RowDataBound

 If I have a Label (lblAmount) in my GridView's TemplateField, one of the simplest way to access it and modify its format is shown below:

if (e.Row.RowType == DataControlRowType.DataRow)
    {
            Label myLabel = (Label)e.Row.FindControl("lblAmount");
            string newLabelFormat = myLabel.Text;
            const string fmt1 = "#,##0.00;(#,##0.00)";
            double newAmountFormat = Double.Parse(newLabelFormat);
            string myAmountFormat=
newAmountFormat .ToString(fmt1);
            newLabelFormat =
myAmountFormat;
            myLabel.Text = newLabelFormat;
      }

Combining Multiple Rows Into A Single Row With A Common Column Value

Sample:

Harold    ASP.NET
Harold    C#
Harold    LINQ


SELECT X.myName,
   (SELECT ' ,  ' + Y.ProgrammingLanguage
    FROM myTable Y
    WHERE Y.myName = X.myName
    FOR XML PATH('')) [SECTORS/USERS]
FROM myTable X
GROUP BY X.myName
ORDER BY 1



Result:

Harold    ASP.NET, C#, LINQ

How To Fix The FieldHeader Size Of DetailsView

Just add the following code to DetailsView to fix its size to 400px:

FieldHeaderStyle-Width="400px"


How To Update Only The First Row Of The Table With Duplicate Column Value

For instance, you have a multiple rows with 3 columns (myName, myAge, myExpertise) like

Harold    34    C#
Harold    12    ASP.NET
Harold    21    LINQ

Now if you just want to update the 2nd column (myAge) of the first row, one solution that should work is the following:

UPDATE myTableName SET myAge=35 WHERE myPrimaryId=(SELECT MIN(myPrimaryId) FROM  myTableName WHERE myName='Harold')

How To Reset the 'Primary Key' To 1 After Deleting All The Rows On The Table

I've been testing a couple of samples for our project before we deploy it to production.

One of my developers asked me how could we reset the Primary Key to 1 after we deleted all the samples (rows) on the table?

A very short script helped us in doing so:

TRUNCATE TABLE tbl_SampleTable

Invalid attempt to read when no data is present.

Have you experienced this error?

If you're using SqlDatareader, a simple solution is to use something like this:

while (reader.Read())
    {

    }

Inserting NULL values for Both SQL and LINQ

SQL


SqlDateTime myNullDate;

myNullDate = SqlDateTime.Null;


if (txtOrderCreated.Text == "")
    {
        cmd.Parameters.Add(new SqlParameter("@OrderCreated ", SqlDbType.DateTime)).Value = myNullDate;
    }
else
    {
        cmd.Parameters.Add(new SqlParameter("@OrderCreated ", SqlDbType.DateTime)).Value = DateTime.Parse(txtOrderCreated.Text);
    }



LINQ



var x = new tbl_Order();

if (txtOrderCreated.Text != "")
    {
        x.OrderCreated = DateTime.Parse(txtOrderCreated.Text);
    }
else
    {
        x.OrderCreated = null;
    }

How To Convert Integer To Words

I'll show you a simple solution to convert an integer to words. It's useful when dealing with money or printing a receipt or check.

public static string ValueToWords(int number)
    {
        if (number == 0)
            return "zero";

        if (number < 0)
            return "minus " + ValueToWords(Math.Abs(number));

        string words = "";

        if ((number / 1000000) > 0)
        {
            words += ValueToWords(number / 1000000) + " Million ";
            number %= 1000000;
        }

        if ((number / 1000) > 0)
        {
            words += ValueToWords(number / 1000) + " Thousand ";
            number %= 1000;
        }

        if ((number / 100) > 0)
        {
            words += ValueToWords(number / 100) + " Hundred ";
            number %= 100;
        }

        if (number > 0)
        {
            if (words != "")
                words += "and ";

            var ones = new[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
            var tens = new[] { "Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };

            if (number < 20)
                words += ones[number];
            else
            {
                words += tens[number / 10];
                if ((number % 10) > 0)
                    words += " " + ones[number % 10];
            }
        }
        return words;
    }

Simplest Way To Copy Any File From Your Computer Going To FTP Server in C#

protected void btnUpload_Click(object sender, EventArgs e)
    {
        FtpUpload("ftp://100.89.90.23", "myUserName", "myPassword", @"C:\ForUpload\myFile.txt");
    }

    private static void FtpUpload(string ftpServer, string userName, string passWord, string fileName)
    {
        using (var client = new WebClient())
        {
            client.Credentials = new NetworkCredential(userName, passWord);
            client.UploadFile(ftpServer + "/" + new FileInfo(fileName).Name, "STOR", fileName);
        }
    }

Exporting Data from Database To Text File in C#

public override void VerifyRenderingInServerForm(Control control)
    {
    }
    protected void btnExport_Click(object sender, System.EventArgs e)
    {
        string connectionString = WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            try
            {
                connection.Open();
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                // handle
                return;
            }
            string selectCommandText = "SELECT * FROM Students";
            using (SqlDataAdapter adapter = new SqlDataAdapter(selectCommandText, connection))
            {
                using (DataTable table = new DataTable("Students"))
                {
                    adapter.Fill(table);
                    StringBuilder commaDelimitedText = new StringBuilder();
                    //commaDelimitedText.AppendLine("col1,col2,col3"); // optional if you want column names in first row
                    foreach (DataRow row in table.Rows)
                    {
                        string value = string.Format("{0} {1} {2}  {3}  {4}  {5}", row[0], row[1], row[2], row[3], row[4], row[5]); // how you format is up to you (spaces, tabs, delimiter, etc)
                        commaDelimitedText.AppendLine(value);
                    }
                    string str = "CustomName1";
                    string btr = "CustomName2";
                    File.WriteAllText(@"C:\\temp\" + str + btr + ".txt", commaDelimitedText.ToString());
                }
            }
        }
    }

Inserting Column from One Table To Another in SQL

A former student asked me that simple question.

What's your easiest way to do it?

Mine?

Simple.

Example:

INSERT INTO EmployeeDetalye (Name)

SELECT Name FROM EmployeeDetails


What do you think?

Uploading Excel File to SQL Server Database

protected void btnSave_Click(object sender, EventArgs e)
    {
        ImportlToDb();
     }

void ImportToDb()
    {

        try
        {

            if (FileUpload1.HasFile)
            {
                string saveFolder = @"C:\MyFolder";

                string filePath = Path.Combine(saveFolder, FileUpload1.FileName);

                FlUploadcsv.SaveAs(filePath);
                String strConnection = "Data Source=hack3r;Initial Catalog=eLogisticsDb;Integrated Security=True";

                String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
                //Create Connection to Excel work book
                using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
                {
                    //Create OleDbCommand to fetch data from Excel
                    using (OleDbCommand cmd = new OleDbCommand("Select [Id],[Name] from [Sheet1$]", excelConnection))
                    {
                        excelConnection.Open();
                        using (OleDbDataReader dReader = cmd.ExecuteReader())
                        {
                            using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
                            {
                                //Give your Destination table name
                                sqlBulk.DestinationTableName = "Employees";
                                sqlBulk.WriteToServer(dReader);
                            }
                        }
                        excelConnection.Close();
                    }
                }

            }

        }

        catch (Exception ex)
        {

        }

    }

Retrieving JSON objects using AJAX

I have a simple code here that I use to read JSON data.

function loadJSON() {
   
    "use strict";

    var xhr = false;
   
    if (window.XMLHttpRequest) {
       
        xhr = new XMLHttpRequest();
       
    } else {
       
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
       
    }   
   
    if (xhr) {
   
    xhr.open("GET", "data.json", true);
    xhr.send(null);   
    xhr.onreadystatechange = getContents;
   
    } else {   
   
    document.getElementById("myDiv").innerHTML = "Sorry. Unable to process your request. Try again later.";
   
    }
   
    function getContents() {
   
        if (xhr.readyState == 4){
       
            if (xhr.status == 200 || window.location.href.indexOf("http") == -1) {
           
                //To retrieve as a JavaScript object
               
                var jsonData = eval("("+xhr.responseText+")");                
                var getData = jsonData.items;       
               
                var output = '';
                for (var i = 0; i < getData.length; i++) {
                    output +=    '<ul>';
                    output +=    '<li>';
                    output +=    '<a href="' + getData[i].website + '">';
                    output +=    getData[i].name + '</a>';
                    output += '</li>';
                    output += '</ul>';
                }
               
                output += '</ul>';               
                document.getElementById("myDiv").innerHTML = output;               
            }                   
        }       
    }
}

Retrieving XML data using AJAX

Since I shared an example on getting data using the native javascript in my last post, I will share another good example on retrieving an XML data using AJAX in native javascript format.


function loadXML()
    {
        "use strict;"
        var xhr = new XMLHttpRequest();          
        xhr.open("GET", "sample.xml", true);
        xhr.send(null);
        xhr.onreadystatechange = function() {      
            if (xhr.readyState == 4) {

                if (xhr.status == 200 || window.location.href.indexOf("http") == -1) {

                    //To retrieve data as an XML object
                    var xmlData = xhr.responseXML;
                    var getData = xmlData.getElementsByTagName("companies");
              
                    var result = '';

                    for (var i = 0; i < getData.length; i++) {

                        result += '<table>';
                        result += '<tr><td>';
                        result += ' <a href="';
                        result += getData[i].getElementsByTagName('name')[0].firstChild.nodeValue;
                        result += '">';
                        result +=  getData[i].getElementsByTagName('website')[0].firstChild.nodeValue;
                        result += '</a>';
                        result += '<p>';
                        result += getData[i].getElementsByTagName('about_us')[0].firstChild.nodeValue;
                        result += '</p>';
                        result += '</td></tr>';
                        result += '</table>';                          
                    }              
                        document.getElementById("xmlDisplay").innerHTML = result;
                }
            }              
        };                  
    }   

A Very Simple GET Application (AJAX)

My former student sent me a pm this am regarding a sample code in getting external files using AJAX in native JavaScript code.

Working with AJAX with or without using 'other' framework is fine. But let me show you the difference between getting a text file using a native JavaScript against jQuery framework.

Native:

function testGET()
    {  
        "use strict;"      
        var xhr = false;
        if (window.XMLHttpRequest) {
      
            xhr = new XMLHttpRequest();
      
        } else {
      
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
      
        xhr.open("GET", "SampleText.txt", true);
        xhr.send(null);
        xhr.onreadystatechange = function() {      
      
            if (xhr.readyState == 4) {

                if (xhr.status == 200 || window.location.href.indexOf("http") == -1) {
              
                    var obj = document.getElementById("myDiv");      
                    obj.innerHTML = xhr.responseText;          
                  
                }
            }              
        };      
    }



With jQuery:

$(document).ready(function(){
  $("button").click(function(){
    $("#myDiv").load("SampleText.txt");
  });
});



Which one is better? They're both fine with me.

Hope you could learn something from this. Suggestions and reactions are welcome (*_*)

Create A Simple DropDownList in MVC

You can create a DropDownList in Controller using the following script. The purpose of this is to simply give you an idea how to easily create a DropDownList in MVC.

First, create a class like this:

public class DropDownList
{
  public int Id { get; set; }
  public string Name { get; set; }
  public IEnumerable <SelectListItem> Names { get; set; }
  public IEnumerable <SelectListItem> Ids { get; set; }
}

Next, create an ActionResult like this:

public ActionResult MyDropDownList (DropDownList ddl)
{
  ddl.Names = new SelectList(ctx.Names.ToArray(), .......



Yeah. I know it's not complete. I intended to leave it that way to make you think how you could make it even better. Again, the purpose is to show you how simple to create a DDL in your controller.

Cannot open user default database. Login failed. Login failed for user 'THISCOMPUTER\COMPUTERNAME'.

Many newbies experience this type of error when they develop an ASP.NET website in their computer (laptop or desktop) and when they try to publish it on the web server (IIS Server) on a different machine or computer.

Actually, it happens because the default database is unavailable at the time of connection. Most reasons are maybe because the database has been detached or maybe because the only available connection is already being used by someone else or maybe because the database has been set to the RESTRICTED_USER state and the user has been denied access.

In many cases, one solution that works (sometimes) is when you run the aspnet_regsql.exe from the command line. But most of the time, I add applicationName attribute to the web.config and it works really great!

When you copy the application to the IIS server, the membership provider has been added in the web.config file but without an applicationName attribute. I suggest you add an “applicationName” attribute to your provider declaration like this:

<membership>
<providers>
<add name ....
.
.
.
.
applicationName="/yourWebApp" />

</providers>
</membership>
 
Just look in the aspnet_Application table to find out the application name that was used when creating the users/data during development.

Calling & Using User Control

// To call it on the page
<%@ Register Src="WebUserControl.ascx" TagName="MyUserControl" TagPrefix="uc1"%>

// To use it
<uc1:MyUserControl id="myControl" Runat="server" />


Sample Chart Applications

Sample Use of Pie Chart:

<asp:Chart ID="Chart2" runat="server" DataSourceID="accountRevenueSource" Style="margin-left: 50px"
                Width="310px" BackColor="229, 229, 229" Height="190px">
                <Series>
                    <asp:Series ChartType="Pie" Name="Account" XValueMember="AccountName" YValueMembers="TotalGrossRevenue"
                        CustomProperties="PieLabelStyle=Disabled" MapAreaAttributes="#VAL" ToolTip="#PERCENT{P}">
                        <EmptyPointStyle IsVisibleInLegend="False" IsValueShownAsLabel="false" />
                    </asp:Series>
                </Series>
              
                <ChartAreas>
                    <asp:ChartArea Name="ChartArea1" AlignmentOrientation="Horizontal" BackColor="#E5E5E5"
                        BorderColor="#E5E5E5" ShadowColor="White">
                        <Area3DStyle Rotation="10" Perspective="20" Enable3D="true" Inclination="40" IsRightAngleAxes="false"
                            WallWidth="0" IsClustered="false" />
                        <AxisY IsLogarithmic="true" />
                    </asp:ChartArea>
                </ChartAreas>
                <Legends>
                    <asp:Legend Name="Legend1" Title="Best Performing Accounts" IsDockedInsideChartArea="False"
                        IsTextAutoFit="true">
                    </asp:Legend>
                </Legends>
            </asp:Chart>



Sample Use of Bar Chart:

<asp:Chart ID="Chart1" runat="server" DataSourceID="viewOpportunitySource"
                Height="350px" style="margin-left: 0px" Width="400px" Palette="Fire"
                PaletteCustomColors="Gold" ImageType="Jpeg" BackColor="#E5E5E5"
                AlternateText="Please create an opportunity.">
                <Titles>
      <asp:Title Name="Title1"
         Alignment="TopCenter" Font="Tahoma, 10pt" ForeColor="102, 0, 102"
                        BackColor="229, 229, 229">
      </asp:Title>
   </Titles>
                <series>
                    <asp:Series Name="My Golden Opportunities" XValueMember="AccountName"
                        YValueMembers="ExpectedRevenue" ChartType="StackedColumn"
                        YValuesPerPoint="2" ToolTip="#VAL{D}" IsValueShownAsLabel="false"
                        LabelBackColor="White" LabelForeColor="RoyalBlue" ShadowOffset="2"
                        IsVisibleInLegend="False"  >
                    </asp:Series>
                </series>
               <chartareas>
            <asp:ChartArea Name="ChartArea1" AlignmentOrientation="Horizontal"
        BackColor="#E5E5E5" BackGradientStyle="HorizontalCenter" BorderColor="MediumOrchid"
                       BackImageTransparentColor="MediumPurple" ShadowColor="MediumPurple">
            <Area3DStyle
            rotation = "10"
            Perspective = "10"
            Enable3D = "true"
            Inclination = "15"
            IsRightAngleAxes = "false"
            WallWidth = "0"
            IsClustered = "false" />
            <AxisY IsLogarithmic = "false" />

            </asp:ChartArea>
        </chartareas>
        <Legends>
        <asp:Legend Name="Legend1" ShadowColor="Fuchsia" Enabled="False"></asp:Legend>
        </Legends>
                 <BorderSkin BackColor="MediumOrchid" />
    </asp:Chart>

Account Logout Management

Just to share a simple solution in creating an account logout management for a web application:

 <h1>
        User Lockout Management</h1>
        <table width="400" bgcolor="#A8CBFF">
        <tr>
            <td class="style4">
                Login Name:</td>
            <td bgcolor="#E4E4E4"><asp:Label runat="server" ID="UserNameLabel" Font-Bold="True"
                    Font-Names="Verdana" ForeColor="Blue" Font-Size="9pt"
                    style="color: #808080; font-size: medium;"></asp:Label></td>
        </tr>
        <tr>
            <td class="style4">
                Approved:</td>
            <td bgcolor="#E4E4E4">
                <asp:CheckBox ID="IsApproved" runat="server" AutoPostBack="true"
                    ForeColor="Blue" Font-Names="Verdana" Font-Size="9pt"
                    style="color: #333333; font-size: medium;"
                    oncheckedchanged="IsApproved_CheckedChanged" />
            &nbsp;<asp:Label ID="StatusMessage" runat="server"></asp:Label>
            </td>
        </tr>
        <tr>
            <td class="style4">
                Locked Out:</td>
            <td bgcolor="#E4E4E4">
                <br />
                <asp:Label runat="server" ID="LastLockoutDateLabel" ForeColor="Red" Font-Names="Verdana" Font-Size="9pt"></asp:Label>
                <br />
                <br />
                <asp:Button runat="server" ID="UnlockUserButton" Text="Unlock User"
                    Font-Names="Verdana" Font-Size="9pt"
                    style="font-size: small; font-family: Tahoma"
                    onclick="UnlockUserButton_Click" BackColor="#666666" BorderColor="#666666"
                    BorderStyle="Solid" ForeColor="White" />
            </td>
        </tr>
    </table>


Code-Behind

using System;
using System.Web.Security;

public partial class webAdmin_userLockoutManagement : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {   
       
        if (!Page.IsPostBack)
        {
            // If querystring value is missing, send the user to ManageUsers.aspx
            string userName = Request.QueryString["user"];
            if (string.IsNullOrEmpty(userName))
            {
                Response.Redirect("loginAccountList.aspx");
            }

            // Get information about this user
            MembershipUser usr = Membership.GetUser(userName);
            if (usr == null)
            {
                Response.Redirect("loginAccountList.aspx");
            }

            UserNameLabel.Text = usr.UserName;
            IsApproved.Checked = usr.IsApproved;

            if (usr.LastLockoutDate.Year < 2000)
            {
                LastLockoutDateLabel.Text = string.Empty;
            }
            else
            {
                LastLockoutDateLabel.Text = usr.LastLockoutDate.ToShortDateString();

                UnlockUserButton.Enabled = usr.IsLockedOut;
            }
        }
    }
    protected void IsApproved_CheckedChanged(object sender, EventArgs e)
    {
        //Toggle the user's approved status
        string userName = Request.QueryString["user"];
        MembershipUser usr = Membership.GetUser(userName);
        usr.IsApproved = IsApproved.Checked;
        Membership.UpdateUser(usr);

        StatusMessage.Text = "The user's approved status has been updated.";
    }
    protected void UnlockUserButton_Click(object sender, EventArgs e)
    {
        //Unlock the user account
        string userName = Request.QueryString["user"];
        MembershipUser usr = Membership.GetUser(userName);
        usr.UnlockUser();

        UnlockUserButton.Enabled = false;
        StatusMessage.Text = "The user account has been unlocked.";
    }
}

Uploading Any File To A Folder Then VIew It Using GridView

Got a simple codes here for those who want to upload files (any files) in a specific folder, then view it in GridView.

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

<!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>File Uploading</title>
</head>
<body>
    <form id="form1" runat="server">
    <h1>
        File Uploading....</h1>
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnUploadFile" runat="server" Text="Upload" OnClick="DataUploading" />
    <hr />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="Text" HeaderText="Files:" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID="btnDownloading" Text="Download" CommandArgument='<%# Eval("Value") %>'
                        runat="server" OnClick="DataDownloading"></asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:LinkButton ID="btnDeleting" Text="Delete" CommandArgument='<%# Eval("Value") %>'
                        runat="server" OnClick="DataDeleting" OnClientClick="return confirm ('Are you sure you want to delete this file?')" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>


Code Behind

using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.IO;

public partial class FileUploading : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string[] myfilePath = Directory.GetFiles(Server.MapPath("~/UploadedFiles/"));
            List<ListItem> myFiles = new List<ListItem>();
            foreach (string filePath in myfilePath)
            {
                myFiles.Add(new ListItem(Path.GetFileName(filePath), filePath));
            }
            GridView1.DataSource = myFiles;
            GridView1.DataBind();
        }
    }
    protected void DataUploading(object sender, EventArgs e)
    {
        string myFileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/UploadedFiles/") + myFileName);
        Response.Redirect(Request.Url.AbsoluteUri);
    }
    protected void DataDownloading(object sender, EventArgs e)
    {
        string myPath = (sender as LinkButton).CommandArgument;
        Response.ContentType = ContentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(myPath));
        Response.WriteFile(myPath);
        Response.End();
    }
    protected void DataDeleting(object sender, EventArgs e)
    {
        string myOtherPath = (sender as LinkButton).CommandArgument;
        File.Delete(myOtherPath);
        Response.Redirect(Request.Url.AbsoluteUri);
    }
}

Password Recovery (A Simple Solution in C#)



My simple solution in recovering passwords without sending it via SMTP. I prefer this approach for some security reasons....

 
 

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

<!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>Password Recovery</title>
</head>
<body>
    <form id="form1" runat="server">
    <h1>
        Password Recovery</h1>
    <br />
    <asp:PasswordRecovery ID="recoverPassword" runat="server" Style="font-size: small;
        font-family: Tahoma; color: #666666;" OnSendingMail="recoverPassword_SendingMail">
        <MailDefinition From="admin@admin.com" Priority="High" BodyFileName="~/ForgotPassword.txt">
        </MailDefinition>
        <UserNameTemplate>
            <table cellpadding="1" cellspacing="0" style="border-collapse: collapse;">
                <tr>
                    <td>
                        <table cellpadding="0">
                            <tr>
                                <td align="center" colspan="2">
                                    Enter User Name to create a new password.<br />
                                    <br />
                                </td>
                            </tr>
                            <tr>
                                <td align="right">
                                    <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
                                </td>
                                <td>
                                    <asp:TextBox ID="UserName" runat="server" Style="font-size: medium; font-family: Tahoma"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName"
                                        ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="recoverPassword">*</asp:RequiredFieldValidator>
                                    <br />
                                </td>
                            </tr>
                            <tr>
                                <td align="center" colspan="2" style="color: Red;">
                                    <asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
                                </td>
                            </tr>
                            <tr>
                                <td align="center" colspan="2">
                                    <br />
                                    <asp:Button ID="SubmitButton" runat="server" CommandName="Submit" Text="Generate New Password"
                                        ValidationGroup="recoverPassword" Style="font-size: small; font-family: Tahoma"
                                        BackColor="#666666" BorderColor="#666666" BorderStyle="Solid" ForeColor="White" />
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </UserNameTemplate>
    </asp:PasswordRecovery>
    </form>
</body>
</html>

- Code-Behind -

using System;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void recoverPassword_SendingMail(object sender, MailMessageEventArgs e)
    {
        e.Cancel = true;
        recoverPassword.SuccessText = e.Message.Body;
    }
}