European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET 5 Hosting - HostForLIFE.eu :: How to Make Ext.NET in ASP.NET?

clock April 11, 2016 23:29 by author Anthony

In this article, I want to share about Ext.Net. Before we begin to learn Ext.net, we need to know what it Ext.net, according to the official web ext.net of are.

Ext.Net is ported to .Net Programming Ext JS, Ext JS is actually also be used in .Net programming, but this Ext.Net easier for developers because it has been created controls can be drag directly to the webform.

Things need to be prepared are:

  • IDE for .Net Programming, here I am using Visual Studio 2010
  • Ext.Net, which can be downloaded on the official website download ext.net, in sharing this time I used ext.net 2.0.0.rc2 community edition version.
  • Extract the downloaded ext.net, in which there Ext.net.dll.
  • ASP.Net with C # code behind.

When you get all the things that needed to be prepared:

  • Create a project, select Visual C # => Web, and then select ASP.Net Web Application
  • Give the name of this project ext.net
  • In the ToolBox window, usually on the left side of the screen, or if no can press Ctrl + Alt + X, right-click the toolbox and select Add Tab, named Ext.Net
  • Right-click the Toolbox Ext.Net, select Choose Items.
  • On the .Net Framework Components, click Browse, find Ext.net.dll then click OK
  • Now the ToolBox Ext.Net already charged components Ext.net.
  • The next step is to create a webform, named WebForm1.aspx
  • Add a ResourceManager to WebForm1.aspx (ResourceManager can be found in the ToolBox Ext.net). ResourceManager is needed by each component Ext.net.
  • Add Ext: Button, set property looks like this:
    <ext:Button ID="Button1" runat="server" Text="Direct Event">
          <DirectEvents>
              <Click OnEvent="Button1_Click" />
          </DirectEvents>
    </ext:Button>

    Button1 DirectEvents method to perform the action.
  • Then, we move on Code Behind of Webform1.aspx, open webform1.aspx.cs or by pressing the F7 key or you can also select the menu View => Code.
  • On Windows Code Behind, on the declaration using (top) add using Ext.Net;
  • Then, add the following method Button1_Click
    protected void Button1_Click(Object sender, DirectEventArgs e)
    {
       X.Msg.Notify("DirectEvent", DateTime.Now.ToLongTimeString()).Show();
    }
  • Back again to WebForm1.aspx by pressing the Shift + F7 keys or select menu View => Designer.
    Add an Ext: Button again into Webform1.aspx, set its properties as follows.
    <ext:Button ID="Button2" runat="server" Text="Direct Method">
          <Listeners>
              <Click Handler="Ext.net.DirectMethods.DoSomething();" />
          </Listeners>
    </ext:Button>
  • Then, add Method Do Something in Code Behind (press F7 to switch to Code Behind window.
    [DirectMethod]
    public void DoSomething()
    {
       X.Msg.Notify("DirectMethod", "Akhirnya bisa Ext.Net").Show();
    }
  • When finished, open the Web.Config the solution Explorer, add the following script.
    <httpModules>
       <add name="DirectRequestModule" type="Ext.Net.DirectRequestModule, Ext.Net" />
    </httpModules>
  • Run the Project by Press F5 or select Debug menu => Start Debugging

 

HostForLIFE.eu ASP.NET 5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET 5 Hosting - HostForLIFE.eu :: Root Of ASP.NET 5

clock April 8, 2016 19:00 by author Anthony

Today we will discuss about the root of ASP.NET 5, which is WWWroot. When you take a closer look at the ASP.NET 5 project, you will see that there are many things which are carry forwarded like Model, View, Controller, clean separation of concerns and may more.

But, there are also some significant changes around ASP.NET 5. Now, the root of the website is no longer the root of the project. By default, root will be WWWroot folder. The idea behind this to maintain the clean separation between the files at the web-server retrieved and sent to the client and the files which contains the logic and configuration. Static files like JS, CSS, HTMLs can live in WWWroot folder.

15th

Now, lets suppose when i run the app and tried to see the image which i have placed in My Imgaes folder, then it will give me 404 error. On the other hand, if i go ahead and add the same folder in WWWroot folder and try to navigate the same then it will produce me the result.

18th

so, the point is all static files are served by root folder and logical stuffs served by project space as we initially saw, when i added controller in the controller’s folder and it took effect. One more thing you might have observed that there is no web.config file now in the solution. Also now there is no Global.asax file; however the same is replaced by startup.cs file. But, we’ll see this later. 1st let’s see project.json file. This file now manages many aspects of website.

19th

First thing which you will notice here that root folder is set to WWWroot here. So, this is the place which is telling website that this is the root folder. So begin the show from here. This you can change as well or rename if you like to. Now, this configuration file is in JSON format. This is also telling the ASP.NET runtime what dependencies project is going to need. In this new ASP.NET 5 system there is a new way to manage dependencies. No need to reference assemblies and store the lists of referenced assemblies in the project file. Instead we refer to nuget packages as dependencies and these dependencies are listed in our project.json file. Now, there are couple of reasons for this change. One reason is to simplify the dependency management. Another good reason for this is that ASP.NET is moving away from VS dependency. So, in future i can use any text editor to build the ASP.NET App.

Now, these dependencies can be both the ways. One way which we used already shown below in the screen shot.

20th

21th

Now, the UI of this also changed. Initially we used to have Modal window. Now, this is more like complete screen giving wider visibility. I can also see the installed templates like

22nd

Also, i still have the flexibility of different nuget source. 2nd Option is via project.json file. Let’s suppose i am planning to install some custom package. Then i can do like shown below as well

24th

However, whatever package you install; you can find its references under “References“. Below, in the screen shot you can see that there are two versions of runtime here. 1st one is the core version and 2nd one is the cloud optimized version.

25th

Let’s collapse the same and drill into it. Now, here dependency management system will keep your assemblies in nice tree structure. So, it nicely tells which package are dependent on which package.

27th

Now, as far as Framework and runtime is concerned as you can see below in the screen shot; i have both frameworks listed here.

28th

So, whenever i am building the solution i am building against both of these frameworks. By building against both i am actually ensuring that it will work well against both the frameworks. This also means whenever i am switching platform my code won’t break there.

But, let’s go ahead and break something here. You remember in the last segment i created one new controller with a notepad. Now, let’s modify the same and refresh the app.

29th

As you can see that it says that GetCallingAssembly() which is part of System.Reflection is not supported in the cloud optimized version. But, let’s suppose i overlooked this error and refresh the app.So, it actually produced me desired result.

31th

But, when i explicitly build the project and checked the output window, then it gave me below error message.

32nd

So, building with error but application is working fine with full blown CLR. Now, if you have decided that you don’t want CORE CLR version. so, you can just comment the Core CLR section in the project.json file as shown below in the screen shot.

33th

As soon as i commented the above section, below references got refreshed automatically.

34th

Now, when i build the app then it will build fine. But, suppose you want the other way means you would like to keep the cloud optimized version also and build should also succeed. For this scenario i need to refer the conditional build as shown below.

36th

 

HostForLIFE.eu ASP.NET 5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET 4.5 Hosting - HostForLIFE.eu :: How To Prevent XSS Attacks in ASP.NET?

clock April 6, 2016 19:17 by author Anthony

In this article, I will explain about how to prevent XSS Attacks. XSS (Cross-Site Scripting) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted web sites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. For sites that allow user input to be displayed in the browser, cross site scripting (XSS) attacks are a possibility that must be protected against.  These attacks are carried out by placing <script> tags pointing to malicious code in the public facing elements, which can be persisted elements such as comments or reviews, or more ephimeral examples such as query variables in the url.  The aim of these attacks varies, but some examples are stealing sensitive information (login credentials, personal data), forcing redirects, or just about anything else that can be accomplished with JavaScript.  These attackes can be prevented by encoding input. So instead of the literal string <script>bad script code</script>, it becomes &lt;script&gt;bad script code&lt;/script&gt;, and instead of running the code, it will simply display the text content of the script.

According to Microsoft, the primary purpose of the HttpUtility.HtmlEncode method is to ensure that ASP.NET output does not break HTML; it's purpose is not necessarily security.  However, the AntiXssEncoder class is primarily designed for security.  To this end, it uses a white-list approach rather than a black-list, only allowing known safe characters to remain unencoded.  The AntiXss method is slightly less performant, and will work in multiple languages.

It is possible to set the AntiXssEncoder as the default for your application, and this has gotten steadily easier.  Phil Haack wrote in 2010 about doing this using a the HttpEncoder abstract base class, and Jon Galloway wrote in 2011 about doing it with version 4.1 which already included an encoder, so it required little more than adding the assembly to the project and changing the web.config file.  Since AntiXss can now be had in NuGet, it's as simple as installing it and setting the httpRuntime encoderType property:

 <system.web>
    <httpRuntime targetFramework="4.5"
             encoderType="Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary"/>
  </system.web>


HostForLIFE.eu ASP.NET 4.5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET 5 Hosting - HostForLIFE.eu :: How to Use Entity Framework 7 To Persist Movie Data To a Database?

clock April 4, 2016 19:50 by author Anthony

Today I will explain about how to use entity framework 7 to presist movie data to a database. But before you start, you must add Entity Framework 7 NuGet packages to your project. Also make sure that your project.json file includes the following two dependencies (you’ll get Intellisense while entering the names of the packages and their versions).

"EntityFramework.SqlServer": "7.0.0-beta2",
"EntityFramework.Commands": "7.0.0-beta2",

 

After you complete this step, the Entity Framework packages should appear under References.

Creating the Model and DbContext

Next, we need to create our Movie model class. This class represents the entity that we want to store in the database. Add the following Movie.cs class to your Models folder:

namespace MovieAngularJSApp.Models
{
    public class Movie
    {
        public int Id { get; set; }
 
        public string Title { get; set; }
 
        public string Director { get; set; }
    }
}

We also need to create an Entity Framework DbContext class. We create this class when using Entity Framework 7 in exactly the same way as we created this class for previous versions of the Entity Framework.

using Microsoft.Data.Entity;
namespace MovieAngularJSApp.Models
{
    public class MoviesAppContext:DbContext
    {
 
        public DbSet<Movie> Movies { get; set; }
 
    }
}

Registering the Entity Framework Services
Now that we have our DbContext class, we need to register the DbContext with our application services. Modify your Startup.cs file so it contains the code for registering the Entity Framework in the code below:

using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Data.Entity;
using MovieAngularJSApp.Models;
using Microsoft.AspNet.Hosting;
using Microsoft.Framework.ConfigurationModel;
namespace MovieAngularJSApp
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            // Setup configuration sources.
            Configuration = new Configuration()
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();
        }
         public IConfiguration Configuration { get; set; }
         public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
 
            // Register Entity Framework
            services.AddEntityFramework(Configuration)
                .AddSqlServer()
                .AddDbContext<MoviesAppContext>();
        }
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
 
    }
}

The database connection string is loaded up from the Config.json file (notice the constructor in the Startup.cs file). Here is what the Config.json file looks like:

{
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=MoviesDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
        }
    },
    "EntityFramework": {
        "MoviesAppContext": {
            "ConnectionStringKey": "Data:DefaultConnection:ConnectionString"
        }
    }
}

Updating the MoviesController

Because we registered our MoviesAppContext class as a service, we can take advantage of the built-in ASP.NET 5 Dependency Injection framework to use the MoviesAppContext in our MoviesController. Notice that the MoviesAppContext class is added to the MoviesController using constructor dependency injection in the code below:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc;
using MovieAngularJSApp.Models;
namespace MovieAngularJSApp.API.Controllers
{
    [Route("api/[controller]")]
    public class MoviesController : Controller
    {
        private readonly MoviesAppContext _dbContext;
 
        public MoviesController(MoviesAppContext dbContext)
        {
            _dbContext = dbContext;
        }
 
        [HttpGet]
        public IEnumerable<Movie> Get()
        {
            return _dbContext.Movies;
        }
        [HttpGet("{id:int}")]
        public IActionResult Get(int id)
        {
            var movie = _dbContext.Movies.FirstOrDefault(m => m.Id == id);
            if (movie == null) {
                return new HttpNotFoundResult();
            } else {
                return new ObjectResult(movie);
            }
        }
        [HttpPost]
        public IActionResult Post([FromBody]Movie movie)
        {
            if (movie.Id == 0)
            {
                _dbContext.Movies.Add(movie);
                _dbContext.SaveChanges();
                return new ObjectResult(movie);
            }
            else
            {
                var original = _dbContext.Movies.FirstOrDefault(m => m.Id == movie.Id);
                original.Title = movie.Title;
                original.Director = movie.Director;
                _dbContext.SaveChanges();
                return new ObjectResult(original);
            }
        }
        [HttpDelete("{id:int}")]
        public IActionResult Delete(int id)
        {
            var movie = _dbContext.Movies.FirstOrDefault(m => m.Id == id);
            _dbContext.Movies.Remove(movie);
            _dbContext.SaveChanges();
            return new HttpStatusCodeResult(200);
        }
 
 
    }
}

Performing Database Migrations

After we complete all of the steps above, our application still won’t work. If we run the Movies app then we will get an error message about not being able to open the MoviesDatabase.

The Entity Framework 7 does not support database initializers. Instead, you are encouraged to use Database Migrations.There are two ways to use Migrations with ASP.NET 5: from a Command Prompt or from the NuGet Package Manager Console. I used the Command Prompt approach and I executed the following two commands from the same directory that contains my project.json file:

k ef migration add initial
k ef migration apply

KPrompt

After you execute the two ef commands above, a new database named MoviesDatabase will be created. You can see the new database by opening up the Visual Studio SQL Server Object Explorer:

SQLExplorer

Executing the ef commands above will also add a new Migrations folder to your project.

Migrations

You now should be able to run the Movies app successfully.

HostForLIFE.eu ASP.NET 5 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Get Youtube Video Thumbnail image in ASP.NET?

clock March 31, 2016 23:15 by author Peter

This tutorial will show you how to get youtube video thumbnail image in ASP.NET. Write the following code that returns image thumbnail url of given youtube video url by passing video url as a parameter in getYouTubeThumbnail method.

public string getYouTubeThumbnail(string YoutubeUrl)   
{   
    string youTubeThumb=string.Empty;   
    if (YoutubeUrl == "")   
        return "";   
 
    if (YoutubeUrl.IndexOf("=") > 0)   
    {   
        youTubeThumb = YoutubeUrl.Split('=')[1];   
    }   
    else if (YoutubeUrl.IndexOf("/v/") > 0)   
    {   
        string strVideoCode = YoutubeUrl.Substring(YoutubeUrl.IndexOf("/v/") + 3);   
        int ind = strVideoCode.IndexOf("?");   
        youTubeThumb = strVideoCode.Substring(0, ind == -1 ? strVideoCode.Length : ind);   
    }   
    else if (YoutubeUrl.IndexOf('/') < 6)   
    {   
        youTubeThumb = YoutubeUrl.Split('/')[3];   
    }   
    else if (YoutubeUrl.IndexOf('/') > 6)   
    {   
        youTubeThumb = YoutubeUrl.Split('/')[1];   
    }   
 
    return "http://img.youtube.com/vi/" + youTubeThumb + "/mqdefault.jpg";   
}   

You may call the above function with various youtube url format like,
getYouTubeThumbnail("http://youtu.be/4e3qaPg_keg");   
getYouTubeThumbnail("http://www.youtube.com/watch?v=bvLaTupw-hk");

HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET 4.5 Hosting - HostForLIFE.eu :: How to Create a Database With Data Source Control in ASP.NET

clock March 29, 2016 21:10 by author Anthony

In this post we are going to talk about techniques for displaying data contained in the SQL Server database with ASP.NET. There are at least three ways commonly used to perform the data binding to server conrol in ASP.NET 4.5

Here are three ways:

  • Data Source Control (Declarative)
  • Code by Hand
  • Model Binding

but in this time I will explain how to create a database with the Data Source Control in ASP.NET 4.5


Web Config

Before going into the main discussion helps me informed beforehand that the connection string that is used to communicate with the database in ASP.NET contained in the configuration file "web.config". Here are the contents

file: Web.config


<?xml version="1.0"?>
<configuration>

<connectionStrings>
<add name="learn_webConnectionString" connectionString="Data Source=SOFT-ENGINEER;Initial Catalog=learning_web;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>


Database Design

The database used in this post only use one of the table is very simple with the name "Category"

Data Source Control

Data Source Control in ASP.NET 4.5 used as a link between the database with controls for displaying data. Using this approach means that we do is get the data in a declarative rather than programmatic. To be more explicit, the following is a sample code

file: default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TryingWebForm.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Data Source Control</title>

</head>
<body>

<form id="form1" runat="server">

<div>

<p>The Declarative Way</p>

<asp:SqlDataSource ID="sdsCategory" runat="server" ConnectionString="<%$ ConnectionStrings:trying_webConnectionString %>"

SelectCommand="SELECT [id], [name_category] FROM [Category]"/>

<asp:GridView ID="gvCategoryDeclarative" runat="server" DataSourceID="sdsCategory" />

</div>

</form>

</body>

</html>

As seen in the above code, control "SqlDataSource" requires a connection string and a query command to be executed. In magic this control will connect to the database and execute commands query and the result was thrown into "GridView" by filling property "DataSourceID" with the Id of control SqlDataSource concerned. The image below is the result

 

HostForLIFE.eu ASP.NET 4.5 Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Upload File to SFTP Server using free Utility WINSCP?

clock March 2, 2016 21:45 by author Peter

In this tutorial, I will describe a technique for uploading a file to sftp server using third party tools WinSCP. WinSCP is an open source free SFTP client, FTP client, WebDAV client and SCP client for Windows. Its main function is file transfer between a local and a remote computer. Beyond this, WinSCP offers scripting and basic file manager functionality.

Features

  • Graphical user interface
  • Translated into many languages
  • Integration with Windows (drag&drop, URL, shortcut icons, jump list)
  • All common operations with files
  • Support for SFTP and SCP protocols over SSH and FTP and WebDAV protocols
  • Batch file scripting and command-line interface and .NET assembly for advanced programming tasks
  • Directory synchronization in several semi or fully automatic ways
  • Integrated text editor
  • Shares site settings with PuTTY
  • Support for password, keyboard-interactive, public key and Kerberos (GSS) authentication
  • Integrates with Pageant (PuTTY authentication agent) for full support of public key authentication with SSH
  • Explorer and Commander interfaces
  • Optionally protects stored site information with master password
  • Optionally supports portable operation using a configuration file in place of registry entries, suitable for operation from removable media

Now, write the following code:
private static void UploadToSFTP(string stringJasontext) 

try 

    //get static value from App.config file. 
    string ftpServerIP = ConfigurationSettings.AppSettings["sftpServerIP"].ToString(); 
    string stringsFtpUserID = ConfigurationSettings.AppSettings["sftpUserID"].ToString(); 
    string stringsFtpPassword = ConfigurationSettings.AppSettings["sftpPassword"].ToString(); 
    string stringStrDate = System.DateTime.Now.ToString("dd_MM_yyyy-hh_mm_ss"); 
    string stringFileName = "LeaseJson_" + stringStrDate + ".json"; 
    string stringFromPath = ConfigurationSettings.AppSettings["sFromPath"].ToString(); 
    string stringToPath = ConfigurationSettings.AppSettings["sToPath"].ToString(); 
    string stringHostKey = ConfigurationSettings.AppSettings["sHostKey"].ToString(); 
    string stringsBackUpFolder = "Processed"; 
    //create folder for back up data 
    if (!Directory.Exists(stringFromPath + stringsBackUpFolder)) 
    { 
          Directory.CreateDirectory(stringFromPath + stringsBackUpFolder); 
    } 
    //check whether file exist or not in local machine. 
    if (!System.IO.File.Exists(stringFromPath + stringFileName)) 
    { 
          using (FileStream fileStreamLocalFile = File.Create(stringFromPath + stringFileName)) 
          { 
                byte[] byteLocalFile = new UTF8Encoding(true).GetBytes(stringJasontext); 
                fileStreamLocalFile.Write(byteLocalFile, 0, byteLocalFile.Length); 
          } 
    } 
    SessionOptions sessionOptionsSFTP = new SessionOptions 
    { 
          Protocol = Protocol.Sftp, 
          HostName = ftpServerIP, 
          UserName = stringsFtpUserID, 
          Password = stringsFtpPassword, 
          PortNumber = 22, 
          SshHostKeyFingerprint = stringHostKey 
    }; 
    WinSCP.Session sessionSFTP = new WinSCP.Session(); 
    sessionSFTP.Open(sessionOptionsSFTP); 
    TransferOptions transferOptionsSFTP = new TransferOptions(); 
    transferOptionsSFTP.TransferMode = TransferMode.Binary; 
    transferOptionsSFTP.FilePermissions = null; 
    transferOptionsSFTP.PreserveTimestamp = false; 
    transferOptionsSFTP.ResumeSupport.State = TransferResumeSupportState.Off; 
    TransferOperationResult transferOperationResultSFTP; 
    transferOperationResultSFTP = sessionSFTP.PutFiles(stringFromPath + stringFileName, stringToPath, false, transferOptionsSFTP); 
    if (System.IO.File.Exists(stringFromPath + stringFileName)) 
    { 
          File.Move(stringFromPath + stringFileName, stringFromPath + "\\" + stringsBackUpFolder + "\\" + stringFileName); 
    } 
    transferOperationResultSFTP.Check();

    if (transferOperationResultSFTP.IsSuccess == true) 
    { 
          Console.Write("File upload successfully"); 
    } 
    else 
    { 
          Console.Write("File upload failed"); 
    } 


catch (Exception exError) 

    Console.Write(exError.Message); 


#endregion 
#region Upload File to FTP server as Json File 
//private static void UploadToFTP(string stringJasontext) 
//{ 
// try 
// { 
// string stringFtpUserID = ConfigurationSettings.AppSettings["ftpUserID"].ToString(); 
// string stringFtpPassword = ConfigurationSettings.AppSettings["ftpPassword"].ToString(); 
// string stringStrDate = System.DateTime.Now.ToString("dd_MM_yyyy-hh_mm"); 
// string stringToPath = ConfigurationSettings.AppSettings["ToPath"].ToString() + "LeaseJson_" + stringStrDate + ".json"; 
// FtpWebRequest ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(stringToPath); 
// ftpWebRequest.Credentials = new NetworkCredential(stringFtpUserID, stringFtpPassword); 
// ftpWebRequest.KeepAlive = false; 
// ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile; 
// ftpWebRequest.UseBinary = true; 
// ftpWebRequest.ContentLength = stringJasontext.Length; 
// ftpWebRequest.Proxy = null; 
// using (Stream TempStream = ftpWebRequest.GetRequestStream()) 
// { 
// System.Text.ASCIIEncoding TempEncoding = new System.Text.ASCIIEncoding(); 
// byte[] byteTempBytes = TempEncoding.GetBytes(stringJasontext); 
// TempStream.Write(byteTempBytes, 0, byteTempBytes.Length); 
// } 
// ftpWebRequest.GetResponse(); 
// } 
// catch (Exception exError) 
// { 
// Console.Write(exError.Message); 
// } 
//} 
#endregion 

 

HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET Core 1.0 Hosting - HostForLIFE.eu :: How to Make all Child Check Boxes checked on Master Check Box Checked Event ?

clock February 24, 2016 19:43 by author Peter

This code for how to Make all Child Check Boxes checked on Master Check Box Checked Event. Checkboxes allow the user to select one or more options from a set. Typically, you should present each checkbox option in a vertical list. Now write the following code:

<!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></title> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div style="height:70%;width:70%"> 
<asp:GridView ID="gridview1" runat="server" AutoGenerateColumns="False"  
DataKeyNames="ID" DataSourceID="SqlDataSource1" BackColor="White"  
BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3"  
GridLines="Horizontal" Width="100%"> 
<AlternatingRowStyle BackColor="#F7F7F7" /> 
<Columns> 
<asp:TemplateField> 
<HeaderTemplate> 
    <asp:CheckBox ID="CheckBox2" onclick="headercheckbox(this);" runat="server" /> 
</HeaderTemplate> 
<ItemTemplate> 
    <asp:CheckBox ID="CheckBox1" onclick="childcheckboxes(this);" runat="server" /> 
</ItemTemplate> 
</asp:TemplateField> 
<asp:TemplateField> 
<HeaderTemplate> 
    <asp:LinkButton ID="LinkButton1" runat="server">Delete</asp:LinkButton> 
</HeaderTemplate> 
<ItemTemplate> 
    <asp:LinkButton ID="LinkButton2" runat="server">Delete</asp:LinkButton> 
</ItemTemplate> 
</asp:TemplateField> 
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"  
ReadOnly="True" SortExpression="ID" /> 
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> 
<asp:BoundField DataField="Class" HeaderText="Class" SortExpression="Class" /> 
<asp:BoundField DataField="Lastname" HeaderText="Lastname"  
SortExpression="Lastname" /> 
</Columns> 


<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" /> 
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" /> 
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" /> 
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" /> 
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" /> 
<SortedAscendingCellStyle BackColor="#F4F4FD" /> 
<SortedAscendingHeaderStyle BackColor="#5A4C9D" /> 
<SortedDescendingCellStyle BackColor="#D8D8F0" /> 
<SortedDescendingHeaderStyle BackColor="#3E3277" /> 


</asp:GridView> 
<asp:SqlDataSource ID="SqlDataSource1" runat="server"  
ConnectionString="<%$ ConnectionStrings:akConnectionString %>"  
SelectCommand="SELECT [ID], [Name], [Class], [Lastname] FROM [nametb]"> 
</asp:SqlDataSource> 

<script type="text/javascript" language="javascript"> 
var gridview = document.getElementById("gridview1"); 
function headercheckbox(checkbox) { 
for (var i = 1; i < gridview.rows.length; i++)  

  gridview.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = checkbox.checked; 


function childcheckboxes(checkbox) { 
  var atleastekcheck = false; 
  for (var i = 1; i < gridview.rows.length; i++)  
  { 
      if (gridview.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked == false)  
      { 
          atleastekcheck = true; 
          break; 
      } 
      
  } 
   gridview.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = !atleastekcheck  ; 


</script> 

HostForLIFE.eu ASP.NET Core 1.0 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET 5 Hosting - HostForLIFE.eu :: Recursive FindControl & Extension Methods

clock February 17, 2016 21:20 by author Peter

Here's a really short and easy little bit of code that has the potential to be slightly of a time-saver. The FindControl method of the control class is used to find a specific child control of a given parent, searching by ID. This method, however, does not search the control hierarchy recursively: it searches the direct children of the specified parent control only. While writing a recursive version of this method is trivial, a rather nice way to make the technique reusable is to implement it as an extension method. Here's how it can be done:

//search the children
foreach (Control child in control.Controls)
{
    ctrl = FindControlRecursive(child, id);
    if (ctrl != null) break;
}
}

return ctrl;
}

}
}


And to call it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using Boo.Web.UI.Extensions;

namespace MyWebApp
{
public partial class WebForm1 : System.Web.UI.Page

{
    public void Page_Load(object sender, EventArgs e)
    {
       //call the recursive FindControl method
        Control ctrl = this.FindControlRecursive("my_control_id");
    }
}
}


Now, don't forget to import the namespace within which the extensions method class is declared- or a compilation error will not long follow. Now, all you need to do is import this same namespace for any pages/user controls/custom controls which need to use the recursive control search and you're good to go.

Doing it this way is of course logically no different to creating a static method in a util class, and passing both the parent control and the ID of the child control you want to find to it, but considering how commonly this functionality is required, it's nice to be able to tack it onto the control class itself, and extension methods provide an elegant way to accomplish this.

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



ASP.NET 4.6 Hosting - HostForLIFE.eu :: How to Use FileUpload in ASP.NET, How to Save Image , Picture in Website Folder?

clock February 3, 2016 19:24 by author Peter

First we  craete  a  table UserImage using database test:
use test
create  table UserImage(SrNo int  primary key,Name nvarchar(50),UserImg nvarchar(max))

After than we  create  a Web from  like  this and  take  a Folder Image  in our  WebSite  for  saving  image  which are  upload  by  user.

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

<!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></title>
<style type="text/css">
.style1 {
    width: 100%;
}
.style2
{
    width: 351px;
}
</style>
</head>
<body>

<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
    <td colspan="3"><center><asp:Label ID="Label1" runat="server" Text="Save Image in Image folder and Database" Font-Bold="true"></asp:Label></center>
      
    </td>
</tr>
<tr>
    <td>
        <asp:Label ID="SrNo" runat="server" Text="SrNo"></asp:Label>
    </td>
    <td class="style2">
        <asp:TextBox ID="txtsrno" runat="server"></asp:TextBox>
    </td>
    <td rowspan="5">
        <asp:Image ID="Image1" runat="server" Height="91px" Width="99px" />
    </td>
</tr>
<tr>
    <td>
        <asp:Label ID="Label4" runat="server" Text="Name"></asp:Label>
    </td>
    <td class="style2">
        <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
    </td>
</tr>
<tr>
    <td>
        <asp:Label ID="Label5" runat="server" Text="Image"></asp:Label>
    </td>
    <td class="style2">
        <asp:FileUpload ID="FileUpload1" runat="server" />
    </td>
</tr>
<tr>
    <td>
        &nbsp;</td>
    <td class="style2">

        <asp:Button ID="BSave" runat="server" onclick="BSave_Click" Text="Save" />
    <asp:Button ID="BSelect" runat="server" onclick="BSelect_Click" Text="Select" />
        <asp:Button ID="BDelete" runat="server" onclick="BDelete_Click" Text="Delete" />
&nbsp;<asp:Button ID="BUpdate" runat="server" onclick="BUpdate_Click" Text="Update" />
    </td>
</tr>
<tr>
    <td>
        &nbsp;</td>
    <td class="style2">
        <asp:Label ID="Message" runat="server" Text="Label" Visible="False"></asp:Label>
    </td>
</tr>
</table>
</div>
</form>
</body>
</html>


Now we create Connection global for Website in web.config
<configuration>
<connectionStrings>
<add name="kush" connectionString="Data Source=KUSH-PC; Initial Catalog=test;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
</configuration>


Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

//Using this namespace for DirectoryInfo and FileInfo
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["kush"].ConnectionString);
}
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
//Saving image in Database and Image Folder which are exist in Website
protected void BSave_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("insert into UserImage (SrNo,Name,UserImg) values (@SrNo,@Name,@UserImg)", con);
cmd.Parameters.AddWithValue("@SrNo", Convert.ToInt32(txtsrno.Text));
cmd.Parameters.AddWithValue("@Name", txtname.Text);
cmd.Parameters.AddWithValue("@UserImg", FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath("~/Image/") + FileUpload1.FileName);
cmd.ExecuteNonQuery();
 Message.Visible=true;
Message.Text = "Add Successfully ";
con.Close();
txtname.Text = "";
}
//retrive image  from Database  and  Image Folder which are exist  in Website
protected void BSelect_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("select * from UserImage where SrNo=@SrNo", con);
cmd.Parameters.AddWithValue("@SrNo", Convert.ToInt32(txtsrno.Text));
 dr=cmd.ExecuteReader();
 if (dr.Read())
 {
     txtname.Text = dr["Name"].ToString();
     Image1.ImageUrl = "~/Image/" + dr["UserImg"].ToString();
 }
con.Close();
}

//The following code is for  delete image  from  Database  and  Image Folder which are exist  in  Website
protected void BDelete_Click(object sender, EventArgs e)
{
DirectoryInfo dd = new DirectoryInfo(Server.MapPath("~/Image"));
foreach (FileInfo ff in dd.GetFiles())
{
    if (ff.Name == Path.GetFileName(Image1.ImageUrl))
        ff.Delete();
}

 con.Open();
 cmd = new SqlCommand("delete from UserImage where SrNo=@SrNo", con);
 cmd.Parameters.AddWithValue("@SrNo", Convert.ToInt32(txtsrno.Text));
 cmd.ExecuteNonQuery();
 con.Close();
 txtname.Text = "";
 Message.Visible=true;
 Message.Text="Delete Successfully Image "+"For SrNo"+"-"+txtsrno.Text+"";
}

//this  code  for  Update  image  in Database  and  Image Folder and  old  image  deleted  from Image Folder

protected void BUpdate_Click(object sender, EventArgs e)
{
try
{

    DirectoryInfo dd = new DirectoryInfo(Server.MapPath("~/Image"));
    foreach (FileInfo ff in dd.GetFiles())
    {
        if (ff.Name == Path.GetFileName(Image1.ImageUrl))
            ff.Delete();
    }

    con.Open();
    cmd = new SqlCommand("update  UserImage set Name=@Name, UserImg=@UserImg  where SrNo=@SrNo", con);
    cmd.Parameters.AddWithValue("@SrNo", Convert.ToInt32(txtsrno.Text));
    cmd.Parameters.AddWithValue("@Name", txtname.Text);
    if (FileUpload1.HasFile)
    {
        cmd.Parameters.AddWithValue("@UserImg", FileUpload1.FileName);
    }
    else
    {
        cmd.Parameters.AddWithValue("@UserImg", Image1.ImageUrl);
    }

    FileUpload1.SaveAs(Server.MapPath("~/Image/") + FileUpload1.FileName);
    cmd.ExecuteNonQuery();
    con.Close();
    txtname.Text = "";
    Message.Visible = true;
    Message.Text = "update Successfully Image " + "For SrNo" + "-" + txtsrno.Text + "";
}
catch (Exception ex)
{
    Message.Visible = true;
    Message.Text = ex.Message;
}

}
}

HostForLIFE.eu ASP.NET 4.6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments. 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in