08 May 2017

How Do We Get The Parameter Value from a URL?

Here's a quick and easy way to read and display the paramater value from a URL.

Ex:
var sampleUri = new Uri("http://www.mysite.com/default.aspx?ID=21");
string getParam = HttpUtility.ParseQueryString(sampleUri.Query).Get("ID");

20 April 2017

System.InvalidCastException: Specified cast is not valid.

When you try to map bigint in SQL to int in C#, you will get an error equivalent to "System.InvalidCastException: Specified cast is not valid."

You need to map the bigint to long, which is equal to 64-bit integer in C# or Int64, because Int32 cannot store the maximum value of bigint.

19 April 2017

How To Find Duplicate Record in SQL

Whenever I need to delete duplicate records in database, I try to find them first and identify the number of times the same row occurs.

Here's a simple way to find them:

SELECT Name, Age, COUNT(*) AS NoOfDuplicateRecords
FROM Table_Name
GROUP BY Name, Age
HAVING COUNT(*) > 1

11 April 2017

How lock(obj) Method Works

I once had a requirement to generate a random integer number from let's say 0 to 10 million. Here's what I did:

public static int GetRandomNumber(int min, int max)
{
    lock (obj)
    {
        //some codes for calling Random method is omitted for brevity      
    }
}

I used lock statement to ensure that the object was locked by the first thread and released the object first before another thread to lock the same object.

I think lock is more concise that using a monitor class in blocking the thread.


10 April 2017

Uploading An Image File with Unique Filename and Save It In A Folder


I just have a requirement to upload an image file in a folder named "UploadedFiles" and replace its file extension from ".whateverFileExtension" to ".jpg".
And to ensure that each picture will have a unique (or at least have a higher probability of a unique filename), I will use SyncLock method and Random class to generate random number (ex. from 1 to 10,000,000) and assign the auto-generated number to every uploaded picture.

Below is my sample code:

<HTML>

<input type="file" id="fileUpload" runat="server" />
<input type="submit" id="btnUploadFile" runat="server" value="Upload" onserverclick="btnUploadFile_OnServerClick" />


<CODE BEHIND>

private string _myRandomNumber;
private static readonly Random Random = new Random();
private static readonly object SyncLock = new object();

public static int RandomNumber(int min, int max)
{
    lock (SyncLock)
    {
        return Random.Next(min, max);
    }
}

protected void btnUploadFile_OnServerClick(object sender, EventArgs e)
{
    _myRandomNumber = RandomNumber(0, 10000000).ToString("D");
    int newPictureId = Int32.Parse(_myRandomNumber);
    string baseDirectory = Server.MapPath("~/UploadedFiles/");
    fileUpload.PostedFile.SaveAs((baseDirectory + (newPictureId + ".jpg")));
}

07 April 2017

How Do You Validate Input Date Programmatically?

When validating a date, I recommend that you use both the client-side and the server side techniques. For client-side, you can use native JS or any JS framework available. For the server-side, you can do it programmatically such as the below sample:

<ASPX page>

Enter a date: <input type="date" id="txtExpirationDate" runat="server" required="" />
<p></p>
<label id="lblMessage" runat="server"></label>


<CODE BEHIND>

DateTime validDate;
if (DateTime.TryParse(txtExpirationDate.Value, out validDate))
{
    //some code goes here
}
else
{
    lblMessage.InnerText = "You entered an invalid date.";
}

05 April 2017

How To Use HTML's Map Area with Pure JavaScript

If you're looking for an easier way to create a clickable area/s in the image (or image map), you might consider using the HTML's <map> tag and JavaScript.

Example:


<!DOCTYPE html>
<html>
<head>
    <title>
        Sample Use of Map Area with JavaScript
    </title>
    <script>
        function writeText(txt) {
            document.getElementById("AboutTheLocation").innerHTML = txt;
        }
    </script>
</head>

<body>

<map name="targetLocation">
    <area shape="poly" coords="74,261,49,250,80,103,117,113" onmouseover="writeText('My home is located somewhere here.')" onmouseout="writeText('')" />
<map name="targetLocation">
    <area shape="circle" coords="124,58,8" onmouseover="writeText('My office is located somewhere here.')" onmouseout="writeText('')" />

<img src ="vs.png" alt="Visual Studio" usemap="#targetLocation" width="145" height="126" />
<p></p>
<p id="AboutTheLocation"></p>

</body>
</html>

In Response.Redirect("URL"), Should We Use True or False?

Response.Redirect("URL", true);
                     or
Response.Redirect("URL", false);


Did you know that using true or false is just a matter of how you control the logic flow of your code? We use true to abort the thread so that nothing will execute once you redirect the page. Then, we use false when you don't want to abort the thread after the Response.Redirect executes.

For some developers, using true is considered a bad practice because it's a sign that you have no control on your code's logic and you're simply aborting the thread and the application will not continue when an error arises.

But the funny thing is that I've seen a lot of developers not putting either true or false whenever they use Response.Redirect and keep saying that using true is not a good practice. But the truth is that when you don't declare a false value, "true" is the default when you use Response.Redirect.

04 April 2017

Should I go to Parameters.Add or to a simplified Parameters.AddWithValue?

For some developers, choosing between the two is just a matter of preferences because in fact there is no difference in terms of functionality between these two.

I disagree.

Providing only the type Parameters.AddWithValue, the compiler will just try to implicitly convert the input parameter to what is expected and it may cause you a performance issue.

How To Add Google Map with Marker in Pure JavaScript

Okay, I said 'pure' JavaScript. Forgive me if I use a few CSS lines.

Here's my sample webpage displaying a Google map and our sample offices in Norway and in Makati City (Philippines):

<!DOCTYPE html>
<html>

<head>
    <title>Sample Google Map with Marker</title>
    <style type="text/css">
        #place_map_here {
            height: 500px;
            width: 1000px;
        }
    </style>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script>
        function initialize() {
            var pointDestinations = [
                {
                    lat: 61.792135,
                    lon: 8.381478,
                    title: "Grosvik Norway",
                    description: "Norway office"
                },
                {
                    lat: 14.557985,
                    lon: 121.023870,
                    title: "Grosvik Phils.",
                    description: "Makati office"
                }
            ];
            var initialLocation = {
                zoom: 2,
                center: new google.maps.LatLng(61.792135, 8.381478),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById("place_map_here"), initialLocation);

            var infoAboutThePlace = new google.maps.InfoWindow({
                content: ''
            });
            var y;
            for (y = 0; y < pointDestinations.length; y++) {

                var marker = new google.maps.Marker({
                    title: pointDestinations[y].title,
                    position: new google.maps.LatLng(pointDestinations[y].lat, pointDestinations[y].lon),
                    map: map
                });
                markerAndInformationBinder(marker, map, infoAboutThePlace, "<p>" + pointDestinations[y].description + "</p>");
            }
        }
        function markerAndInformationBinder(marker, map, infoAboutThePlace, html) {
            google.maps.event.addListener(marker, 'click', function () {
                infoAboutThePlace.setContent(html);
                infoAboutThePlace.open(map, marker);
            });
        }
        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>

<body>
    <div id="place_map_here"></div>
</body>

</html>

03 April 2017

How To Enable Paging in ListView

I know it's a bit old, but there are newbies who still had difficulty in adding a pager in their ListView control. So I think that justifies why I should post this blog.

If for example you add a DataPager in you ListView's LayoutTemplate

<asp:DataPager ID="DataPager1" runat="server" PagedControlID="ListView1" PageSize="5">
    <Fields>
        <asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="false" ShowPreviousPageButton="true" ShowNextPageButton="false" />                                       <asp:NumericPagerField ButtonType="Link" />
        <asp:NextPreviousPagerField ButtonType="Link" ShowNextPageButton="true" ShowLastPageButton="false" ShowPreviousPageButton="false" />
    </Fields>
</asp:DataPager>


First, you need to set the OnPagePropertiesChanging="OnPagePropertiesChanging" on your ListView properties like:

<asp:ListView ID="ListView1" runat="server" OnPagePropertiesChanging="OnPagePropertiesChanging">


Then, from code behind you can do the following:

protected void OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        (ListView1.FindControl("DataPager1") as DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, false);

        //call your method in displaying the list
    }

31 March 2017

How To Validate User Input Using Native JavaScript

In the presence of numerous JS frameworks and 'drag n drop' features, I just found that some graduating students of computer science can't write a simple user input validation using a pure JavaScript. What even bothered me was that some web developers can't even write a simple JS script without searching from Google or without using the so-called 'copy-paste programming'!

Okay, I'll just share with you a very simple and neat way to validate a required text entry using our native JavaScript:

Name: <input type="text" id="txtName"  /><br/>
<input type="button" id="btnSubmit"  onclick ="javascript:validate()"  value="Submit" />    


<script type="text/javascript">
        function validate()
        {
           if (document.getElementById("txtName").value=="")
           {
                 alert("Name is required.");
                 document.getElementById("txtName").focus();
                 return false;
           }          
           return true;
        }
</script>

28 March 2017

How To Pass Querystring From One Page to Another Using JavaScript

I used to pass QueryString from one ASP.NET page to another using Hyperlink control. But since I had a requirement to pass the Querystring using pure JavaScript, I used the following code:

<script type="text/javascript">
        $(function () {
            $("#btnSend").bind("click", function () {
                var url = "SecondPage.aspx?name=" + encodeURIComponent($("#txtInput").val());
                window.location.href = url;
            });
        });
</script>


Enter string message: <input type="text" id="txtInput"/>
<input type="button" id="btnSend" value="Submit" />



27 March 2017

How To Disable Bootstrap Modal Window from Closing

In any ordinary day when I need to disable the bootstrap modal window from closing due to my client requirement, I simply make the backdrop to 'static' and set the keyboard property to 'false' like the below sample:

<script type="text/javascript">
    $('#sampleModal').modal({
    backdrop: 'static',
    keyboard: false
    });
</script>


<div class="modal fade" id="sampleModal" tabindex="-1" role="dialog" aria-labelledby="sampleModalLabel" aria-hidden="true">

//some text are omitted here for brevity....

</div>



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();
        }

05 March 2017

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);
}

19 February 2017

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

17 February 2017

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
)

16 February 2017

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();

15 February 2017

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>

06 February 2017

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

07 December 2016

ASP.NET Essential Training for Developers

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


27 November 2016

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.




18 November 2016

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!




16 November 2016

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.

13 November 2016

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


22 October 2016

ASP.NET in Practice goes to DFCAITTI (Philippines)

Teaching our today's generation about the power of ASP.NET is fun!






20 October 2016

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();



25 February 2015

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.

24 February 2015

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

23 February 2015

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')

13 January 2015

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

10 December 2014

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;
    }

11 November 2014

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;
    }

11 August 2014

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);
        }
    }

09 August 2014

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());
                }
            }
        }
    }

15 May 2014

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)
        {

        }

    }

10 February 2014

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;               
            }                   
        }       
    }
}

08 February 2014

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 (*_*)

12 December 2013

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.

24 September 2013

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>