Thursday, 24 May 2018

Upload file on FTP using C#


1. Open Visual Studio and create a new website

2. Add namespaces like using System.IO; and using System.Net;
3. On Button Click event write below code

string filename = Path.GetFileName(localFile);

                string ftpPath = ftpUrl;
                FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpPath);
                ftp.Credentials = new NetworkCredential(Username, Password);

ftp.UsePassive = true;

                ftp.KeepAlive = true;
                ftp.UseBinary = true;
                ftp.Method = WebRequestMethods.Ftp.UploadFile;
             
                FileStream fs = File.OpenRead(localFile);
                byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);
                fs.Close();

                Stream ftpstream = ftp.GetRequestStream();

                ftpstream.Write(buffer, 0, buffer.Length);
                ftpstream.Close();

4.Run project and upload file.

Friday, 18 May 2018

How to Deploy ASP. Net Websites on IIS



Step 1: From Visual Studio, publish your Web application.
Step 2: From RUN -> inetmgr -> OK
Step 3: Add Application Pool for your Website Select Version V4 for Application Pool. And Select Pipeline Mode to Integrated
Step 4: From Sites ->Right click -> Add Website 

Step 5: Configure the Website
Give your Site name
Select Application Pool you created
Set Physical Path of your website
Set Bindings and Port of Website
Set Host Name and then Click OK



Thursday, 17 May 2018

Download File from SFTP using C#

1. Open Visual studio and create a new website
2. Right Click to your solution and go to Manage Nuget Packages
3. Search for SSH.NET and install it
4. Include namespaces like using Renci.SshNet; and using System.IO;
5. On your Button Click Event write below code

          string port = SFTP Port;

          string host = SFTP Host;
          string username = SFTP Username;
          string password = SFTP Password;
          string remoteDirectory = SFTP Folder from where the file will be downloaded;

          string localDirectory = Local Directory Path;

                if (!File.Exists(Path.GetDirectoryName(localDirectory)))
                    Directory.CreateDirectory(Path.GetDirectoryName(localDirectory));

                using (SftpClient sftp = new SftpClient(host, Convert.ToInt32(port), username, password))

                {
                    sftp.Connect();
                    var files = sftp.ListDirectory(remoteDirectory);
                    foreach (var file in files)
                    {
                        string remoteFileName = file.Name;
                        if (file.Name.Contains("."))
                        {
                            using (Stream file1 = File.OpenWrite(localDirectory + "\\" + remoteFileName))
                            {
                                sftp.DownloadFile(remoteDirectory + "\\" + remoteFileName, file1);
                            }
                        }
                    }
                }
6. Run Your Project

Upload file on SFTP using C#

1. Open Visual studio and create a new website
2. Right Click to your solution and go to Manage Nuget Packages
3. Search for SSH.NET and install it
4. Include namespaces like using Renci.SshNet; and using System.IO;
5. On your Button Click Event write below code

          string port = SFTP Port;

          string host = SFTP Host;
          string username = SFTP Username;
          string password = SFTP Password;
          string destinationFolder = SFTP Folder where the file will be uploaded;

          using (SftpClient client = new SftpClient(host, Convert.ToInt32(port), username, password))

                   {
                        client.Connect();
                        client.ChangeDirectory(destinationFolder);
                        using (FileStream fs = new FileStream(path, FileMode.Open))
                            {
                                    client.BufferSize = 4 * 1024;
                                    client.UploadFile(fs, Path.GetFileName(path));
                            }
                    }
6. Run Your Project

How to Create Proxy Class from wsdl.exe

1.  Download wsdl.exe
2.  Place it on your local computer
3.  Open Command Prompt
4.  Run command
     C:\Project>wsdl.exe [Path to your WSDL file]
5.  You will see the .cs file in the C:\Project Folder

Thursday, 2 February 2017

Highcharts in Asp.net

1. Open visual studio and create MVC project
2. Create a SQL Server Database table named "VehicleSummary".

3. Enter some data in the table.


4. Add Controller named HighchartsController.cs.
5. Write code in controller to get VehiclaSummary.


public static DataSet GetVehicleSummary()
        {
            SqlConnection con = new SqlConnection(str);
            string query = "Select * from VehicleSummary";
            SqlCommand cmd = new SqlCommand(query,con);
            cmd.CommandType = CommandType.Text;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
        
            return ds;
        }


6. Now we will create a model to hold this data and it to the controller:

public class Summary
        {
            public int Item { get; set; }
            public string Value { get; set; }
        }

7. Now return JSON  to get table values.

 [HttpGet]
        public JsonResult VehicleSummary()
        {
            List<Summary> lstSummary = new List<Summary>();

            foreach (DataRow dr in GetVehicleSummary().Tables[0].Rows)
            {
                Summary summary = new Summary();
                summary.Value = dr[1].ToString().Trim();
                summary.Item = Convert.ToInt32(dr[2]);
                lstSummary.Add(summary);

            }
            return Json(lstSummary.ToList(), JsonRequestBehavior.AllowGet);
        }
8. Now add view.
9. Add .js files 

10. Add Code to view


    

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
    <script src="http://code.highcharts.com/modules/exporting.js"></script> 
    
    
       
</head>
<body>
    
    <script type="text/javascript">

        $(function () {
            $.ajax({
                url: '/HighCharts/VehicleSummary',
                dataType: "json",
                type: "GET",
                contentType: 'application/json; charset=utf-8',
                async: false,
                processData: false,
                cache: false,
                delay: 15,
                success: function (data) {
                    // alert(data);
                    var series = new Array();
                    for (var i in data) {
                        var serie = new Array(data[i].Value, data[i].Item);
                        series.push(serie);
                    }
                    DrawPieChart(series);
                },
                error: function (xhr) {
                    alert('error');
                }
            });
        });
        function DrawPieChart(series) {
            $('#container').highcharts({

                chart: {
                    plotBackgroundColor: null,
                    plotBorderWidth: 1, //null,
                    plotShadow: false
                },
                title: {
                    text: ' Vehicle Summary'
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: false
                        },
                        showInLegend: true
                    }
                },
                series: [{
                    type: 'pie',
                    name: 'Task Status',
                    data: series
                }]
            });
        }
    </script>
    <div id="container" style="min-width: 350px; height: 350px; max-width: 600px; margin: 0 auto"></div>
</body>
</html>


12. Now run the project.


Elmah (Error Logging)

1. Open visual studio
2. Create a new project.
3. Right Click solution and select Manage Nuget Packages
4. Search Elmah and add the elmah package.




                                                                                                                                                            

6. Click Install to install Elmah.                                                                                                               7. Now run application and check for the 404 Error.                                                                                                    



  8. You can see error log by entering URL http://localhost:56571/Elmah.axd

SQL server tricky questions