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

European ASP.NET Hosting - Nederland :: How to Solve System.Net.Mail: The specified string is not in the form required for a subject

clock January 21, 2014 08:59 by author Scott

Sometimes you’ll see this error on your site and it is really annoying. I post this issue as I see many people on forums experiencing on this issue. This is an error message:

“ArgumentException: The specified string is not in the form required for a subject“.

So what is exactly “the form required for a subject”? Googling for this error message returns a lot of junk and misinformed forum posts. It turns out that setting the Subject on a System.Net.Mail.Message internally calls MailBnfHelper.HasCROrLF (thank you Reflector) which does exactly what it says on the tin. Therefore one forum poster’s solution of subject.Replace("\r\n", " ") isn’t going to work when you have either a carriage returnor line feed in there.

The solution is like this:

message.Subject = subject.Replace('\r', ' ').Replace('\n', ' ');

Personally, I think that the MailMessage should to this for you or at least Microsoft should document what actually constitutes a “form required for a subject” in MSDN or, even better, in the actual error message itself!

 



European ASP.NET 4.5 Hosting - Amsterdam :: Model Binding with Dropdown List in ASP.NET 4.5

clock December 20, 2013 05:32 by author Administrator

ASP.NET 4.5 Preview introduces new model binding for  ASP.NET web forms. The concept of model binding was first introduced with ASP.NET MVC and now it has incorporated with ASP.NET Web Forms. You can easily perform any CURD operation with any sort of data controls using any data access technology like Entity Framework,  ADO.NET, LINQ to SQL Etc.  In this post I am going talk about how you can bind the data with ASP.NET DropdownList using new Model Binding features.

Let’s say we have a speaker database and we wants to bind the name of the speakers with the DropDownList.  First placed an ASP.NET Dropdown control with the page  and set the “DataTextField” and “DataValueField” properties.

We can set the  ddlName.DataSource to specifying the data source from the code behind and bind the data with dropdpwnlist, but  in this case from the code behind to providing the data source.

Now, instead of specifying the DataSource, we will be setting the Dropdownlists SelectMethod property to point a method GetSpeakerNames() within the code-behind file.

Select method is expected to return us result of type IQueryable<TYPE>. Here is GetSpeakerName() method is defined as follows.

So, Instead of specifying the data source we are specifying the SelectMethod, which return the IQueryable type of Speaker object. Run the application, you will find the names binded with dropdown list. Hope this helps !



European ASP.NET Hosting Tips :: How to Consume Web API OData From .NET And JavaScript Client Applications

clock December 5, 2013 06:25 by author Scott

In this post, we will consume the service from a .NET client and a web page.

Consuming Web API OData using a .NET client:

A Web API OData service can be consumed using WCF Data Services client. If you gave already worked with WCF Data Services, you already know about consuming Web API OData Service as well.

Right click on a .NET project and choose the option Add Service Reference. In the dialog, enter the OData service URL and click the Go button.

The dialog parses the metadata received from the server and shows the available entities under container as shown in the screenshot. As we created just one entity in the service, we see the entity Employee alone. Name the namespace as you wish and hit OK. Visual Studio generates some classes for the client application based on the metadata.

The generated code contains the following:

  • A Container class, which is responsible for communicating with the service. It holds DataServiceQuery<TEntity> type properties for each EntitySet on the server
  • A class for every entity type. This class contains all properties mapped on the server, information about key of the entity

A Container is much like a DbContext in Entity Framework. It handles all the operations. Container is responsible for building OData URLs and sending requests to the service for any operation that client asks for. Let’s start by creating a Container. Constructor of the container accepts a URI, which is base address of the Web API OData service.

Container container = new Container(new Uri("http://localhost:1908/odata"));

To fetch details of all employees, we need to invoke the Corresponding DataServiceQuery property.

var employees = container.Employees;

Although the statement looks like an in-memory operation, it generates the corresponding URL internally and calls the server. Similarly, to get details of an employee with a given Id, we can write a LINQ query as shown:

var employee = container.Employees.Where(e => e.Id == 3).FirstOrDefault();

The above query makes a call to the Get method accepting key in the Web API Controller.

To create a new employee, we need to create an object of the Employee class, add it and ask Container to save it. Following snippet demonstrates this:

Employee emp = new Employee() { Id = 0, Name = "Hari", Salary = 10000 };
container.AddToEmployees(emp);
container.SaveChanges();

Performing update is also much similar. The difference is with calling the SaveChanges method.

emp = container.Employees.Where(e => e.Id == 3).FirstOrDefault();
emp.Name = "Stacy";
container.UpdateObject(emp);
container.SaveChanges(SaveChangesOptions.ReplaceOnUpdate);

If SaveChanges is called with SaveChangesOptions.ReplaceOnUpdate, it performs PUT operation on the resource. If SaveChangesOptions.PatchOnUpdate is passed, it performs PATCH operation on the resource.

To delete an entry, we need to pass an object to DeleteObject method and just like earlier cases; we need to call the SaveChanges method on the Container.

container.DeleteObject(container.Employees.Where(e => e.Id == 3).FirstOrDefault());
container.SaveChanges();

Consuming Web API OData using JavaScript client:

To consume the Web API OData service from a web page, the service has to be called using AJAX. The client can send an AJAX request to the URL of the OData service by specifying an HTTP verb to operate on the resource. To make our life easier, let’s use jQuery for AJAX calls.

To get details of all employees, we need to send a GET request to the OData URL. Values of entries in the collection are stored in a property named value in the object received as response. Fetching details of an employee with a given Id also follows similar approach. Following snippet demonstrates this:

$.getJSON(“/odata/Employees”, function(data){
    $.each(data.value, function(){
        //Modify UI accordingly
    });
}); 

$.getJSON(“/odata/Employees(3)”, function(data){
        //Modify UI accordingly
});

To add a new employee, we need to send the new object to $.post along with the URL.

var employee = {
    "Id": 0,
    "Name": “Ravi”,
    "Salary": 10000
}; 

$.post(“/odata/Employees”, employee).done(function(data){
    //Modify UI accordingly
});

Unfortunately, jQuery doesn’t have a shorthand method for PUT. But it is quite easy with $.ajax as well. To perform PUT on the resource, the request should be sent to the specific address with an ID and the modified object should be passed with the request.

var employee = {
    "Id": 3,
    "Name": “Ravi”,
    "Salary": 10000
}; 

$.ajax({
url: "/odata/Employees(" + employee.Id + ")",
       type: "PUT",
       data: employee
});

Building request for DELETE is similar to put, we just don’t need to pass the object.

$.ajax({
url: "/odata/Employees(" + id + ")",
type: "DELETE"
});



European ASP.NET Hosting - Amsterdam :: Tips to Populate Or Bind DropDownList With JQuery And XML In Asp.Net

clock July 8, 2013 11:32 by author Scott

In this example i'm explaining How To Populate Or Bind DropDownList With JQuery And XML In Asp.Net.

Add jquery library reference in head section and place one dropdown on the page.

Add one list item with select as it's value.

   1:  <asp:DropDownList ID="DropDownList1" runat="server">
   2:  <asp:ListItem>Select</asp:ListItem>
   3:  </asp:DropDownList>
   4:   
   5:  <asp:Label ID="Label1" runat="server" Text=""/>


Following is the Cities.xml file i'm using to bind dropdownlist using jquery.

01<!--?xml version="1.0" encoding="utf-8" ?-->
02<cities>
03  <city>
04    <name>New York</name>
05    <id>1</id>
06  </city>
07    <city>
08    <name>Washington</name>
09      <id>2</id>
10  </city>
11  <city>
12    <name>Chicago</name>
13    <id>3</id>
14  </city>
15  <city>
16    <name>Seattle</name>
17    <id>4</id>
18  </city>
19</cities>

Add this script in head section of page.

01<script src="jquery-1.7.2.min.js" type="text/javascript"></script>  
02<script type="text/javascript">
03$(document).ready(function()
04{
05  $.ajax(
06  {
07    type: "GET",
08    url: "Cities.xml",
09    dataType: "xml",
10    success: function(xml)
11    {
12      var dropDown = $('#<%=DropDownList1.ClientID %>');
13      $(xml).find('City').each(function()
14      {
15        var name = $(this).find('name').text();
16        var id = $(this).find('id').text();
17        dropDown.append($("<option></option>").val(id).html(name));
18      });
19      dropDown.children(":first").text("--Select--").attr("selected", true);
20    }
21  });
22  $('#<%=DropDownList1.ClientID %>').change(function()
23  {
24  var ddl = $('#<%=DropDownList1.ClientID %>');
25  var selectedText = $('#<%=DropDownList1.ClientID %> option:selected').text();
26  var selectedValue = $('#<%=DropDownList1.ClientID %>').val();
27  document.getElementById('Label1').innerHTML = "You selected " + selectedText + " With id " + selectedValue;
28  });
29});
30</script>

Build and run the code.

 



European ASP.NET Hosting - Amsterdam :: A potentially dangerous Request.Form value was detected from the client

clock June 5, 2013 06:39 by author Scott

This is the error message that sometimes you’ll see on the shared hosting:

Server Error in 'ASP.Net' Application.


A potentially dangerous Request.Form value was detected from the client (TextBox1"=<p>Hello</p>").

Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.

Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (TextBox1="<p>Hello</p>").

Cause

ASP.Net By default validates all input controls for potentially unsafe contents that can lead to Cross Site Scripting and SQL Injections. Thus it disallows such content by throwing the above Exception. By default it is recommended to allow this check to happen on each postback.

Solution

On many occasions you need to submit HTML Content to your page through Rich TextBoxes or Rich Text Editors. In that case you can avoid this exception by setting the ValidateRequest tag in the @Page Directive to false.

<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest = "false"

This will disable the validation of requests for the page you have set the ValidateRequest flag to false. If you want to disable this check throughout your Web Application you’ll need to set it  false in your web.config <system.web> section

<pages validateRequest ="false " />

That’s it. Hope this helps you in getting rid of the above issue.



European ASP.NET Hosting - Amsterdam :: How to Develop Mobile WebSite Using ASP.NET

clock May 8, 2013 06:58 by author Scott

In this article we will learn how to create web pages for mobile. Developing mobile web pages is not as developing our simple desktop pages. For developing mobile web pages we have to use “System.Web.Mobile” dll which will provide the classes for developing our mobile web pages. This dll contains all about mobile web pages. How to add this dll and how to use we will see here step-by-step.

1. Start new Website give some name. It will create a website with web.confige and one Default.aspx and Default.aspx.cs files.

2. Next Goto Website menu and add Reference to “System.Web.Mobile” namespace.

3. Now just open Default.aspx page in source code view and register our System.Web.Mobile assembly like this.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
<%@ Register TagPrefix="mobile" Namespace="System.Web.UI.MobileControls" Assembly="System.Web.Mobile" %>

4. Open the page in Design view and see how the page is looking now. Generally mobile pages are not editable. If we want to design this pages with controls we cannot use our toolbox controls. For creating controls we must have to write control code in source view.

5. Now move to source code view and create controls like bellow. Here we will Create Label,TextBox And Button controls. For creating mobile web controls we must have to create mobile form for that just replace our Desktop form like and create the controls for our mobile web page.

<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
    <mobile:Form id="Form1" runat="server">
<mobile:Label ID="label1" Runat="server">Label1</mobile:Label>
<mobile:TextBox ID="TextBox1" Runat="server"></mobile:TextBox>
<mobile:Command ID="Command1" Runat="server" OnClick="Command1_Click">Command1</mobile:Command>
    </mobile:Form>
</body>
</html>

6. Now go code view mean in aspx.cs file and import the namespace of mobile pages and controls as well inherit the Default page with MobilePage.

using System.Web.Mobile;
using System.Web.UI.MobileControls;
public partial class Default : System.Web.UI.MobileControls.MobilePage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Command1_Click(object sender, EventArgs e)
    {

    }
}

7. Now run the application and see in the browser pages will look like something bellow screen. To test this mobile web pages in mobile screens we have to test in mobile emulators. But here we will see our pages in generally desktop browser.

Adding Mobile Web Pages Template To Visual Studio 2008:

Here we will see how to add Deafult template to visual studio 2008. This template actually I got from some website. This template are specially mobile page templates which will add mobile page to our project. This is will make your work easy for adding the mobile web page. Means here you need not to write the code every time just follow the steps given bellow.

1. Here we will see how to add Deafult template to visual studio 2008. This template actually I got from some website. This template are specially mobile page templates which will add mobile page to our project. This is will make your work easy for adding the mobile web page. Means here you need not to write the code every time just follow the steps given bellow.

2. Now open this directory which contains 3 zip files and one text file just open that text file and copy that zip file to the given location  in text file. Fallol same procedure for both directory.

3. Now open Visual Studio and start new website again. Which will give same web.Confige Default.aspx and Default.aspx.cs files. Now delete this files and say Add new item which display visual studio template with our mobile web page templates as follows.

Done…. Now, you know how to develop mobile web pages.

 



European ASP.NET Hosting - Amsterdam :: Configuring ASP.NET Membership Using SQLMembershipProvider

clock May 1, 2013 08:57 by author Scott

This article describe article about how to configure ASP.NET Membership to store user information in an external SQL Server database. We will use SQLMembershipProvider for this task.

ASP.NET Membership

ASP.NET Membership enables us to validate and store user information. It creates all the necessary tables and stored procedures to store and manage user credentials. It provides an API that can be used to manage user's information programmatically.

ASP.NET Membership provides two types of Membership providers:

  1. SQLMembershipProvider : It is used to store user information in a SQL Server database
  2. ActiveDirectoryMembershipProvider : It is used to store user information in an Active Directory.


To configure SQLMembershipProvider, first you need to configure your database.

Open Visual Studio Command Prompt (All Programs -> Microsoft Visual Studio 2008 -> Visual Studio Tools -> Visual Studio 2008 Command Prompt)

Type command : aspnet_regsql and press Enter

This will launch ASP.NET SQL Server Setup Wizard

Click Next

Leave the default selection "Configure SQL Server for application services" and click Next again.

Enter the server name, Select SQL Server authentication and enter user id and password as in the following figure. Select the database you want to configure. Here, I am using Employee database.

Click Next

Click Next and then Finish.

Now, you can see the new tables created in the Employee database for storing user credentials. These table names start with "aspnet_". Similarly, you can also see new Stored Procedures created in the database with "aspnet_" prefix.

Now, we have configured our Employee database. Our next task is to enable SQLMembershipProvider in a Web application. Follow these steps to do that:

  • Create a new ASP.NET Web Application
  • Add <authentication mode="Forms"/> in the Web.Config file. ASP.NET Membership works with only Forms Authentication
  • Add the following to enable SQLMembershipProvider:

          <membership defaultProvider="MyMembershipProvider" >
            <providers>
              <add name="MyMembershipProvider"

          type="System.Web.Security.SqlMembershipProvider"
          connectionStringName="ConString" />
              </providers>
          </membership>

  • Add a connection string with the name "ConString" to connect with the Employee database

        <connectionStrings>
          <add name="SqlConString" connectionString="Data Source=localhost\SQL2005EXPRESS; User ID=youruserid; Password=yourpassword;
                Initial Catalog=Employee;" />
        </connectionStrings>

Now, we are ready to use ASP.NET Membership to create a new user using CreateUserWizard control and authenticate users using Login control.



European ASP.NET Hosting - Amsterdam :: Tips Submit Form with ASP.NET

clock March 11, 2013 06:11 by author Scott

In this article I try to explain the default submit behavior of form and panel. Suppose, you want to press/click submit button on Enter key press or you are trying to post the form on Enter key press. In asp.net, to achieve this functionality we need to set "Defaultbutton" property either in Form or in panel.

Form DefaultButton Property

     <form id="form1" runat="server" defaultbutton="btnSubmit">
    <div>
    <asp:TextBox ID="txtUserID" runat="server"/> <asp:TextBox ID="txtUserpwd" runat="server"/> <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit _Click" Text="Submit"/>
    </div>
    </form>

Panel DefaultButton Property

     <asp:Panel ID="Panel1" runat="server" defaultbutton="btnSubmit">
    <div>
    <asp:TextBox ID="txtUserID" runat="server"/> <asp:TextBox ID="txtUserpwd" runat="server"/> <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit _Click" Text="Submit"/>
    </div>
    </asp:Panel >

Note

1. We specify the defaultbutton property at the Form level in the form tag when there is only one Submit Button for post back.

2. We specify the defaultbutton property at the Panel level in the Panel tag when there are multiple Submit Button for post back.



European ASP.NET Hosting - Amsterdam :: How to download a file from FTP Server using Csharp/VB.NET

clock February 19, 2013 08:26 by author Scott

This is brief tutorial how to download file from FTP using C#/VB.NET. Let’s start it:

C#

using System.Net;
using System.IO;

VB.NET

Imports System.Net
Imports System.IO

Following is the code of download file from the FTP Server.

C#

private void Download(string filePath, string fileName)
   {
       FTPSettings.IP = "DOMAIN NAME";
       FTPSettings.UserID = "USER ID";
       FTPSettings.Password = "PASSWORD";
       FtpWebRequest reqFTP = null;
       Stream ftpStream = null;
       try
       {
           FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
           reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FTPSettings.IP + "/" + fileName));
           reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
           reqFTP.UseBinary = true;
           reqFTP.Credentials = new NetworkCredential(FTPSettings.UserID, FTPSettings.Password);
           FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
           ftpStream = response.GetResponseStream();
           long cl = response.ContentLength;
           int bufferSize = 2048;
           int readCount;
           byte[] buffer = new byte[bufferSize];

           readCount = ftpStream.Read(buffer, 0, bufferSize);
           while (readCount > 0)
           {
               outputStream.Write(buffer, 0, readCount);
               readCount = ftpStream.Read(buffer, 0, bufferSize);
           }

           ftpStream.Close();
           outputStream.Close();
           response.Close();
       }
       catch (Exception ex)
       {
           if (ftpStream != null)
           {
               ftpStream.Close();
               ftpStream.Dispose();
           }
           throw new Exception(ex.Message.ToString());
       }
   }
   public static class FTPSettings
   {
       public static string IP { get; set; }
       public static string UserID { get; set; }
       public static string Password { get; set; }
   }

VB.NET

   Private Sub Download(ByVal filePath As String, ByVal fileName As String)
       FTPSettings.IP = "DOMAIN NAME"
       FTPSettings.UserID = "USER ID"
       FTPSettings.Password = "PASSWORD"
       Dim reqFTP As FtpWebRequest = Nothing
       Dim ftpStream As Stream = Nothing
       Try
           Dim outputStream As New FileStream(filePath + "\" + fileName, FileMode.Create)
           reqFTP = DirectCast(FtpWebRequest.Create(New Uri("ftp://" + FTPSettings.IP + "/" + fileName)), FtpWebRequest)
           reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
           reqFTP.UseBinary = True
           reqFTP.Credentials = New NetworkCredential(FTPSettings.UserID, FTPSettings.Password)
           Dim response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
           ftpStream = response.GetResponseStream()
           Dim cl As Long = response.ContentLength
           Dim bufferSize As Integer = 2048
           Dim readCount As Integer
           Dim buffer As Byte() = New Byte(bufferSize - 1) {}

           readCount = ftpStream.Read(buffer, 0, bufferSize)
           While readCount > 0
               outputStream.Write(buffer, 0, readCount)
               readCount = ftpStream.Read(buffer, 0, bufferSize)
           End While

           ftpStream.Close()
           outputStream.Close()
           response.Close()
       Catch ex As Exception
           If ftpStream IsNot Nothing Then
               ftpStream.Close()
               ftpStream.Dispose()
           End If
           Throw New Exception(ex.Message.ToString())
       End Try
   End Sub
   Public NotInheritable Class FTPSettings
       Private Sub New()
       End Sub
       Public Shared Property IP() As String
           Get
               Return m_IP
           End Get
           Set(ByVal value As String)
               m_IP = Value
           End Set
       End Property
       Private Shared m_IP As String
       Public Shared Property UserID() As String
           Get
               Return m_UserID
           End Get
           Set(ByVal value As String)
               m_UserID = Value
           End Set
       End Property
       Private Shared m_UserID As String
       Public Shared Property Password() As String
           Get
               Return m_Password
           End Get
           Set(ByVal value As String)
               m_Password = Value
           End Set
       End Property
       Private Shared m_Password As String
   End Class

Hope you enjoy this simple tutorial. :)

 



European ASP.NET Hosting - Amsterdam :: How to Publish ASP.NET Web Application

clock February 6, 2013 07:04 by author Scott

In this article I will show you how to publish ASP.NET web application. I have found many people ask this question on asp.net forum. You can simply publish your web application to the File System and copy paste all the files to your server. Then from IIS, you can add a new website. You can set this by right clicking on the web application in the solution explorer and choosing 'Package/Publish Settings'.

Right click on your project in the solution explorer and choose 'Publish'. From the dialog box, as the publish method, choose 'File System'. And choose some directory as the Target Location.

Add the website by right clicking on the 'Sites' in IIS.

Then give a name to your site and select the Physical path from where you copied the site folder.

 



About HostForLIFE.eu

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 offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in