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 4.0 Hosting :: Using connection strings from web.config in ASP.NET v2.0

clock June 30, 2011 06:42 by author Scott

A typical web.config file in v2.0 could have the following section which is placed directly under the root <configuration> section.

<connectionStrings>
    <
remove name
="LocalSqlServer" />
    <
add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName
="System.Data.SqlClient"/>
    <
add name="MainConnStr" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName
="System.Data.SqlClient"/>
</
connectionStrings>


connectionStrings>
    <
remove name=
"LocalSqlServer" />
    <
add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"
/>
    <
add name="MainConnStr" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|main.mdf;User Instance=true" providerName
="System.Data.SqlClient"/>
</
connectionStrings>


You can reference this directly from code using:

[C#]
string connStr = ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;


[VB]
Dim connStr As String = ConfigurationManager.ConnectionStrings("MainConnStr").ConnectionString


Note that the namespace for this is System.Configuration so for a console application the full namespace is required.

Or you can reference this declaratively within the ConnectionString property of a SqlDataSource:

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
 
ConnectionString
="<%$ ConnectionStrings:MainConnStr %>"
 
SelectCommand="SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors]" />



European ASP.NET 4.0 Hosting :: How to Send Email Using Gmail in ASP.NET

clock June 16, 2011 06:55 by author Scott

If you want to send email using your Gmail account or using Gmail's smtp server in ASP.NET application or if you don't have a working smtp server to send mails using your ASP.NET application or aspx page than sending e-mail using Gmail is best option.

You need to write code like this

First of all add below mentioned namespace in code behind of aspx page from which you want to send the mail.

using System.Net.Mail;

Now write this code in click event of button

C# code

protected void Button1_Click(object sender, EventArgs e)

{
  MailMessage mail = new MailMessage();
  mail.To.Add("[email protected]");
  mail.To.Add("[email protected]");
  mail.From = new MailAddress("[email protected]");
  mail.Subject = "Email using Gmail";

  string Body = "Hi, this mail is to test sending mail"+
                "using Gmail in ASP.NET";
  mail.Body = Body;

  mail.IsBodyHtml = true;
  SmtpClient smtp = new SmtpClient();
  smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
  smtp.Credentials = new System.Net.NetworkCredential
       ("[email protected]","YourGmailPassword");
//Or your Smtp Email ID and Password
  smtp.EnableSsl = true;
  smtp.Send(mail);
}

VB.NET code

Imports System.Net.Mail

Protected  Sub Button1_Click
(ByVal sender As Object, ByVal e As EventArgs)
  Dim mail As MailMessage =  New MailMessage()
  mail.To.Add("[email protected]")
  mail.To.Add("[email protected]")
  mail.From = New MailAddress("[email protected]")
  mail.Subject = "Email using Gmail"

  String Body = "Hi, this mail is to test sending mail"+
                "using Gmail in ASP.NET"
  mail.Body = Body

  mail.IsBodyHtml = True
  Dim smtp As SmtpClient =  New SmtpClient()
  smtp.Host = "smtp.gmail.com" //Or Your SMTP Server Address
  smtp.Credentials = New System.Net.NetworkCredential
       ("[email protected]","YourGmailPassword")
  smtp.EnableSsl = True
  smtp.Send(mail)
End Sub

You also need to enable POP by going to settings > Forwarding and POP in your gmail account


Change [email protected] to your gmail ID and YourGmailPassword to Your password for Gmail account and test the code.

If your are getting error mentioned below
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

than you need to check your Gmail username and password.

If you are behind proxy Server then you need to write below mentioned code in your web.config file

<system.net>

<defaultProxy>
<proxy proxyaddress="YourProxyIpAddress"/>
</defaultProxy>
</system.net>

If you are still having problems them try changing port number to 587

smtp.Host = "smtp.gmail.com,587";


If you still having problems then try changing code as mentioned below

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = False;
smtp.Credentials = new System.Net.NetworkCredential
("[email protected]","YourGmailPassword");
smtp.EnableSsl = true;
smtp.Send(mail);

Hope this help!!



European ASP.NET 4 Hosting :: ASP.NET AJAX 4.0 Template Programming - Part II

clock June 4, 2011 06:23 by author Scott

This article is continuation of ASP.NET AJAX 4.0 Template Programming Part 1. In this part, I explain the different data binding options in ASP.NET AJAX 4.0 templates. Just a recap that I've consumed an ADO.NET data services to fetch AdventureWorks's Product table records. In this article, I explain how to update/add new record from client side.

Bindings

Template supports the following bindings:

- One-time - The expression is evaluated only once when the template rendering happen
- One-way Live Binding - The expression is evaluated and update the value, if items in the data source changed
- Two-way Live Binding - If the data source value changed, the value in the expression updated. And if the value in the expression is updated, it will update data source also.

The below diagram depicts the binding.



In the above diagram, the red dashed arrow shows one-time data binding. Once the data from data source has been fetched by DataView using AdoNetDataContext. The one-way live binding has been shown as purple shadowed arrow. The purpose shadow here is whenever a data updated at data source, it is being updated to data view through AdoNetDataContext. The two-way live binding has been shown as green shadowed two-head arrow. In this case, data context should have the knowledge about update operation on data source and provide an interface to data view to send the modified values.

The these three bindings, ASP.NET AJAX provides the following expression convention:

- {{ }} - One-time (can be used on any HTML controls for example <p>{{ Name }}</p>)
- { binding } - One-way if other than user input HTML controls for example <td>{ binding Name } </td>
- {binding } - Two-way if INPUT HTML controls for example <input type="text" sys:value="{{ binding Name }}" />

Here, the input controls binds the values using sys:value attribute for two-way binding. Before going into the updatable data source, let us see how can we design master-detail layout to display Product name and Product details.

Master-Detail Layout

<body xmlns:sys="javascript:Sys"
xmlns:dataview="javascript:Sys.UI.DataView"
sys:activate="*">
  <form id="form1" runat="server">
  <div>
      <!--Master View-->
      <ul sys:attach="dataview" class=" sys-template"
          dataview:autofetch="true"
          dataview:dataprovider="{{ dataContext }}"
          dataview:fetchoperation="Products"
          dataview:selecteditemclass="myselected"            
          dataview:fetchparameters="{{ {$top:'5'} }}"
          dataview:sys-key="master"            
      >
          <li sys:command="Select">{binding Name }</li>
      </ul>

      <!--Detail View-->
      <div class="sys-template"
          sys:attach="dataview"
          dataview:autofetch="true"
          dataview:data="{binding selectedData, source={{master}} }">
          <fieldset>
            <legend>{binding Name}</legend>
            <label for="detailsListPrice">List Price:</label>
            <input type="text" id="detailsListPrice"
                sys:value="{binding ListPrice}" />
            <br />
            <label for="detailsWeight">Weight:</label>
            <input type="text" id="detailsWeight" sys:value="{binding Weight}" />
            <br />              
          </fieldset>
          <button onclick="dataContext.saveChanges()">Save Changes</button>
      </div>
  </div>
  </form>
</body>

Selectable And Editable

An unordered list shows the master details, here the product name (line 15). This line also indicates that the list item is selectable using
sys:command="Select". For maintaining master-detail or selectable item, primary key needs to be specified. The sys-key property of data view refers that primary key. In this example, I call the primary key as "master" (line 13). Also, you can see that I've passed a filter option using fetchparameter
property of data view (line 12). In this example, I request the ADO.NET data service to give only top five records using its filter syntax.

Whenever an item in the master list is selected, the details view needs to be notified. The widget for the details view and binding details should be identified using regular
sys:attach="dataview" and dataview's data property. In this example, dataview:data="{binding selectedData, source={{master}} }" specifies that binding with data view with sys-key name "master"
. The fieldset is used to show set of values for a product. Here, the list price and weight can be editable.

Once an item has been edited, this needs to be notified to the data source through data context. The button with caption "Save Changes" specifies that whenver this button is clicked, save the items in the details view into data source through data context's
saveChanges() method. The corresponding data source's update option should be set on data context's set_saveOperation()
. The following JavaScript code explains this.

var dataContext = new Sys.Data.AdoNetDataContext();
dataContext.set_serviceUri("AWProductDataService.svc");
dataContext.set_saveOperation("Products(master)");
dataContext.initialize();

The ADO.NET Product data service's Products(id) method is used on set_saveOperation. An item can be updated, when Product service of ADO.NET data service is being invoked with product primary key as argument. Here, again I'm referring master layout's "master" sys-key as primary key of Product.

The output of the above code is



The top one is master view where Sport-100 Helmet, Red is selected and the details has been shown in the bottom page. You can edit and update the data source.

The selecteditemclass property of data view is used to show the selected item in different style.

.myselected  {
        color: white;
        font-weight: bold;
        background-color: Silver;
      }



European ASP.NET 4.0 Hosting :: ASP.NET AJAX 4.0 Template Programming - Part I

clock June 2, 2011 05:27 by author Scott

Introduction

When Microsoft released its flavour of AJAX framework named "ASP.NET AJAX" as part of ASP.NET 3.0 preview, it did not have much competency when compared to other AJAX frameworks. But when I evaluated ASP.NET AJAX 4.0, I was really inspired with the new features that are completely focused on your browser technologies such as XHTML and JavaScript. I really admired the effort made by the ASP.NET AJAX team. There could not be any second opinion when you see the following features:

- Template based client side programming
- DataView and DataContext
- Live Data Binding

Template Programming

Template provides pattern to design a web UI form and enables to put placeholders for runtime data. For example, I've designed a web page to display AdventureWorks database Product data through ADO.NET data service. The entity model (edmx) is:



The service code is:

public class AWProductDataService : DataService
{  
    public static void InitializeService(IDataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("*", EntitySetRights.All);
    }
}

By ASP.NET templates, the page looks like:

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

  CodeBehind
="ClientTemplateAndDataViewDemo.aspx.cs"

  Inherits
="CoreEnhancements.AJAX.ClientTemplateAndDataViewDemo"
%>
<!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>Microsoft Tech.Ed - Client-side Templating Demo</title>
    <style type="text/css">
        .sys-template {display:none}
    </style>    
    <script type="text/javascript" src="../scripts/MicrosoftAjax.debug.js"></script>
    <script type="text/javascript" src="../scripts/MicrosoftAjaxTemplates.debug.js">
    </script>
    <script type="text/javascript" src="../scripts/MicrosoftAjaxAdoNet.debug.js">
    </script>
    <script type="text/javascript">
        var dataContext = new Sys.Data.AdoNetDataContext();
        dataContext.set_serviceUri("AWProductDataService.svc");
        dataContext.initialize();
    </script>
</head
>
<
body xmlns:sys="javascript:Sys" xmlns:dataview="javascript:Sys.UI.DataView"
  sys:activate="*">
    <form id="form1" runat="server">   
    <div> 
    <table border="1">
        <thead>
            <tr>
                <td>Name</td>
                <td>List Price</td>
                <td>Size</td>
                <td>Weight</td>
            </tr>
        </thead>   
    <tbody class="sys-template" sys:attach="dataview" dataview:autofetch="true"
    dataview:dataprovider="{{ dataContext }}"
    dataview:fetchoperation="Products">                
        <tr>
          <td>{binding Name }</td>
          <td>{binding ListPrice}</td>
          <td>{binding Size}</td>
          <td>{binding Weight}</td>
        </tr>
    </tbody>
    </table>
    </div> 
    </form>
</body>

I have used a typical HTML table for displaying the data. You can see some new attributes in <TBODY> and data place holders in <TD>. ASP.NET AJAX 4.0 has a dedicated template engine to parse these new attributes and data place holders. ASP.NET AJAX has defined a rich set of attributes and data placeholder patterns collectively called as expression language which are none other than X(HT)ML and JavaScript. Remarkable point here is its XHTML compliance, so these are not custom attributes in the regular HTML elements. The class attribute of the <TBODY> is set to sys-template, which is a convention used to hide the initial template from the user. .sys-template {display:none} The fields or properties of a data item which are needed to be rendered on data place holders can be expressed by {{ }} or { }.

DataContext

Template requires data for its place holders as contexts. The data context enables to bind any JavaScript array or objects to template. The real power of data context is to interact with JSON/ATOM based web services. ASP.NET AJAX provides two data contexts in MicrosoftAjaxAdoNet.js:

-
Sys.Data.DataContext

-
Sys.Data.AdoNetDataContext

The data context tracks all changes to the data automatically using new Sys.Observer object. AdoNetDataContext
supports additional features for ADO.NET data services such as identity management, links and association between entity sets. The below code sample describes how to interact with AdventureWorks Product's ADO.NET data service:

var dataContext = new Sys.Data.AdoNetDataContext();
dataContext.set_serviceUri("AWProductDataService.svc");
dataContext.initialize();

The set_serviceUri() method is used to interact with WCF AJAX or ADO.NET data service. The initialize()
method does initialization or invocation.

Data View

This is the fundamental component for templates to display data defined in
System.UI.DataView
. This is similar to server side data source component supports to bind any JavaScript object or array or to any ASP.NET AJAX component. It has two properties to bind a data set:

-
data
- To bind a JavaScript array or object
-
dataprovider - To bind to a WCF service

The fetchoperation property is used to set which method needs to be invoked for fetching data. In the code snippet 1, I've set the dataContext declared in code snippet 2 as data source. To run this application, refer to the following ASP.NET AJAX client side libraries:

- MicrosoftAjax.js
-
MicrosoftAjaxTemplates

-
MicrosoftAjaxAdoNet

The xmlns:sys declares the namespace Sys for the entire page (Code 1. Line 2). The xmlns:dataview declares DataView control. A data view instance has been associated with <TBODY> using sys:attach.

The following figure shows the conceptual model of the template programming:



The output code is:


 



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