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