Category Archives: ASP.NET - Page 3

Free Microsoft Press e-books!

Once again Microsoft brings some knowledge to the masses icon smile Free Microsoft Press e books! This time its free e-books. All the headings speak for them selfs and with few words these books are MUST HAVE for every developer. Only few chapters are included in pdf’s as you are encouraged to buy them! Here is the content:

ms linq cvr Free Microsoft Press e books!Introducing Microsoft LINQ
by Paolo Pialorsi and Marco Russo

ISBN: 9780735623910

* Chapter 1: LINQ Introduction
* Chapter 2: C# Language Features
* Chapter 3: Visual Basic 9.0 Language Features
* Chapter 4: LINQ Syntax Fundamentals
* Chapter 5: LINQ to ADO.NET
* Chapter 6: LINQ to XML

ms ajax cvr Free Microsoft Press e books!Introducing Microsoft ASP.NET AJAX
by Dino Esposito

ISBN: 9780735624139

* Chapter 1: The AJAX Revolution
* Chapter 5: The AJAX Control Toolkit

ms silverlight cvr Free Microsoft Press e books!Introducing Microsoft Silverlight 1.0
by Laurence Moroney

ISBN: 9780735625396

* Chapter 1: Silverlight and User Experience
* Chapter 5: Programming Silverlight with JavaScript

Log into Microsoft Press home page for more info here

ASP.NET Personal Web Site Starter Kit – Ajax Enabled with .NET Framework 3.5 and VS2008

Brad Abrams just converted the existing Web Site Starter Kit from the VS 2005 web site to use the new dot Net 3.5 framework, LINQ and Ajax extenders. Here is the full source code for that.

Here are some of the key points from his post:

– VS2008 Can Target .NET Framework 2.0
– Upgrade to ASP.NET 3.5 and Take Advantage of Linq
– Ajax Enabling the Site
– Tricking out the site with the Ajax Control Toolkit

read the whole post here

Drag and Drop with ASP.NET AJAX

I love reading great articles! The one I am posting today is simply deep and marvelous! Its written by the well known Jeff Prosise and is included in the last issue of MSDN Magazine.
In this article Jeff explains how to use drag and drop using ASP.NET Ajax Extensions with new Visual Studio. Here is a small part of it, at the end there is a link to the whole article:

fig01 Drag and Drop with ASP.NET AJAXAJAX has revolutionized Web user interfaces, and ASP.NET AJAX has made AJAX available to the Visual Studio® users. It comes in three separate downloads: ASP.NET AJAX Extensions (asp.net/ajax/downloads), which provides the core, fully tested set of AJAX functionality; ASP.NET AJAX Futures (asp.net/downloads/futures), which contains experimental features on which the product group wants feedback; and the ASP.NET AJAX Control Toolkit (asp.net/ajax/ajaxcontroltoolkit/samples), which provides a grab bag of AJAX controls as well as an SDK for building controls of your own.

Of the three, the Futures release has garnered the least attention from the developer community. That’s unfortunate because, more than providing a glimpse into what future versions of ASP.NET AJAX might look like, the Futures Community Technology Preview (CTP) is chock full of features that can be used to build cutting-edge Web apps today. A case in point is drag-and-drop.

Hidden away inside the Futures PreviewDragDrop.js file lies support for rich, browser-based drag-and-drop user interfaces. The model it uses is patterned after the old OLE drag-drop model, in which drag sources implement the IDragSource interface, drop targets implement the IDropTarget interface, and the system provides a drag-drop manager to connect drag sources to drop targets. The Futures drag-drop manager is an instance of a JavaScript class named Sys.Preview.UI._DragDropManager, which is automatically instantiated and made available through a global variable named Sys.Preview.UI.DragDropManager.

For months now, I’ve been meaning to write a sample showing how to use PreviewDragDrop.js to implement real drag-drop, featuring custom drag sourcing and custom drop targeting. I finally got around to it, and the results are pretty cool. I learned quite a lot about DragDropManager in the process, including how to enhance it by adding support for custom drag visuals. Once you’re familiar with the model (and comfortable with the concept of deriving classes and implementing interfaces in JavaScript), DragDropManager opens up a whole new world of possibilities for Web UIs.
read original

The Future of .NET: Visual Basic, the CLR and Managed JScript

This one I found today, it was published on 18th of Dec by Tony Davis on http://www.simple-talk.com. Its quite interesting post I loved reading it.
Here is a short brief:
Visual Basic v9 appeared on November 19. In the past, the new release of Microsoft’s longest-running language might have caused a stir, but it was part of Microsoft .NET Framework 3.5 and there were plenty of other distractions. The changes to VB itself were pretty minor: The ‘Inline IF’ was finally retired in favour of a true ternary IF. We got support for LINQ, Lambda expressions like those of Python, support for XML Literals, and Type Inference. Hopefully, the real changes to the language will come with Visual Basic v10, which will use the Dynamic Language Runtime, and benefit from experience gained in the development of IronPython. It is set to be released with Silverlight 2 as ‘Dynamic Visual Basic’. In the meantime C# continues to increase its dominance in the .NET world. Poor JScript.NET seems to be in terminal decline despite its high quality, though it is, like VB, promised a DLR makeover for SilverLight, and is likely to be renamed ‘Managed JScript’.

For .NET scripting, things already look a lot livelier, thanks in part to the Dynamic Language Runtime (DLR). IronPython and PowerShell have, in the past year, found good solid niches, thanks to their effortless access to the CLR and, in the case of IronPython, excellent tutorials and good compatibility with existing Python code. We all hoped for more with IronRuby, which now seems to be stuck in a pre-alpha limbo due more to legal than technical problems. This is disappointing for those of us who liked some of the ideas in Ruby on Rails. While we wait for Ruby, there is Boo and Nemerle to play with.
read the whole

Converting SQL to LINQ, Part 4: Functions

Part 4 from Bill Horst’s series, now its functions turn.

Functions

SQL SELECT clauses often involve functions, which can be scalar or aggregate. An aggregate function is applied to a field over all the selected records, while a scalar function is called with individual values, one record at a time. It is possible to re-create both kinds of functions with VB LINQ expressions, but in very different ways.

Scalar Functions

Scalar functions are called on each record with whatever parameters are specified. They can appear various places in a SQL query, such as in the SELECT clause. The Scalar Functions available differ from system to system, but usually, there will be an analogous VB method that can be used. If using a Scalar Function in a LINQ Select clause, you will probably need to specify an alias as well (FirstThreeLetters, CurrentTime).

SQL

SELECT LEFT(ItemName, 3) FirstThreeLetters, NOW() CurrentTime
FROM OrderTable

VB

From Shipment In OrderTable _
Select FirstThreeLetters = Left(Shipment.ItemName, 3), CurrentTime = Now

In the above case, Left and Now are methods already built into VB, defined in Microsoft.VisualBasic.dll. This will likely be the case for most common scalar functions you will find in SQL statements. Even if the function you wish to call does not exist in VB already, you can define your own methods, too. However, user-defined methods cannot be used in a Database query, as they will throw an exception at runtime. In the below example, MyFunction is a user-defined function called from the Select clause.

VB

From Shipment In OrderTable _
Select MyFunction(Shipment.Cost, Shipment.ShippingZip)

Aggregate Functions

Aggregate functions are called on certain fields over an entire set of records, and return one value. In a SQL statement, they can appear in the SELECT clause. With VB LINQ, this concept appears a bit differently.

A VB LINQ expression usually begins with a From clause. However, they can also begin with an Aggregate clause. The Aggregate clause has the same syntax as a From clause, except that it starts with a different keyword. If a query starts with an Aggregate clause, it must end with an Into clause. An Into clause is a comma-delimited list of Aggregate function calls, with aliases that can accompany them. The below example shows a SQL SELECT statement that uses Aggregate functions, and an equivalent VB LINQ expression.

SQL

SELECT SUM(Cost) TotalCost, COUNT(*)
FROM OrderTable
WHERE OrderDate > “Sept-29-2007

VB

Aggregate Shipment In OrderTable _
Where Shipment.OrderDate > #9/29/2007# _
Into TotalCost = Sum(Shipment.Cost), Count()

read source

Converting SQL to LINQ – DISTINCT, WHERE, ORDER BY and Operators

Bill Horst continues with those simple examples. After this one here comes the other set. They are perfect to show basic syntax. Here are few more:

DISTINCT
SQL SELECT statements can include the DISTINCT specifier, which causes all duplicate records in the query result to be removed. In a LINQ expression, Distinct is its own individual clause, rather than a specifier on the Select clause. This means that Distinct can appear between any two other clauses. The Distinct clause takes whatever result is returned by the preceding clause (Select, in the case below) and returns a filtered result with duplicates removed. To two code examples below accomplish the same results:

SQL

SELECT DISTINCT Name, Address
FROM CustomerTable

VB

From Contact In CustomerTable _
Select Contact.Name, Contact.Address _
Distinct

ORDER BY
The SQL ORDER BY clause can also be represented in a LINQ expression. A LINQ Order By clause allows for a comma-delimited list of expressions to specify how results should be sorted. Any valid VB expression can be used, so these expressions don’t necessarily have to be the names of field that were selected.

SQL

SELECT * FROM CustomerTable
ORDER BY Phone

VB

From Contact In CustomerTable _
Order By Contact.Phone

ASC/DESC
A SQL ORDER BY clause can also include ASC and DESC keywords, to specify that the sort should be in ascending or descending order, respectively. VB uses Ascending and Descending keywords for the same purpose, with the same syntax. If neither specifier is present, ascending order is the default.

SQL

SELECT * FROM CustomerTable
ORDER BY Phone ASC, Name DESC

VB

From Contact In CustomerTable _
Order By Contact.Phone Ascending, Contact.Name Descending

Here is the original post by Bill Horst

Two interesting posts!

I have severe lack of time so thats the reason to blog about the following posts in one short notice. Few weeks ago I came across Matt Berseth’s blog and made me quite good impression. He blogs frequently and providing quality posts. His last two I liked a lot.

The first one was about how to create image reflections. He describes three practices:

image%7B0%7D%5B4%5D Two interesting posts!

– Browser Specific Client Side Solution
– Cross Browser Client Side Solution
– Cross Browser Server Side Solution

Which one we choose is a matter of what we really want – rendering time or support for all browsers.

Then he wrote about my favourtite IDE – Visual Studio 2008. Matt described how we can use the new ListVew control plus adding DataPager control and extend it with SliderExtender Control from AjaxControlToolkit.

image%7B0%7D Two interesting posts!

This post is provided with demo and source code for download. Thanks Matt!

Silverlight в ASP.NET уеб сайт

Въведение

Silverlight е нова технология от Майкрософт предназначена за разработването на RIA. Тя се вгражда във всеки браузър като плъг-ин и е платформено независима. В тази статия ще покажа как се вграждат Silverlight проект в ASP.NET сайт.

Какво е необходимо

Като за начало изтеглете и инсталирайте новата версия на VS 2008 бета 2 от тук. Повече за новостите във Visual Studio 2008 бета 2. За да разработвате Silverlight приложения, също така ви е необходимо и Silverlight Tools Alpha. След като ги инсталирате, опцията за Silverlight проект ще стане активна в VS.
За да виждаме резултата в браузър ни е необходимо Silverlight runtime/plugin 1.1 Alpha

Идеята

Silverlight е базиран на Xaml, което е XML базиран език за UI елементи. С помоща на Xaml е възможно разграничаването на визуалните елементи от програмната част. Това се реализира чрез ‘code-behind’ концепция позната ни от ASP.NET. На всеки Xaml файл съществува C# файл, който съдържа програмната логика за управлението на графичните елементи.
Когато създаваме Silverlight проект използвайки темплейт от VS 2008, някои файлове се генерират автоматично с образователна цел. Xaml файлът е интегриран в примерена HTML страница. В тази статия ще ви покажа как да извадите Xaml от HTML страницата и да го интегрирате в ASP.NET страница.

Проектите

1. Silverlight проекта
Ако сте инсталирали всичко правилно трябва да видите следният екран когато изберете от менюто File -> New Project:

1 Silverlight в ASP.NET уеб сайт

Проекта ще бъде създаден след като натиснете OK. Следните страници са създадени по подразбиране:
- Page.xaml: това е страницата в която описвате UI елементите
- Page.xaml.cs: тук пишете програмната логика. Обикновен C# код
- Silverlight.js: това е javascript файл с който създавате Silverlight контрола в HTML/ASPX страницата за да показвате Xaml съдържанието.
- TestPage.html: HTML страницата която съдържа Silverlight контрола

2. ASP.NET сайтът
Трябва да добавим и асп проектът към общия solution. Add -> New Web Site.

3. Добавяме Silverlight към уеб сайта
Натискаме с десния бутон на прокта на уеб сайта и от падащото меню избираме Add Silverlight Link.

2 Silverlight в ASP.NET уеб сайт

Това беше първата стъпка. Следващата е да разгледаме HTML страницата за да разберем кой код е отговорен за генерирането на Silverlight контрола в testpage.html:

<head>
    <title>Silverlight Project Test Page </title>
 
    <script type="text/javascript" src="Silverlight.js"></script>
    <script type="text/javascript" src="TestPage.html.js"></script>
 
</head>
 
<body>
    <div id="SilverlightControlHost">
        <script type="text/javascript">
            createSilverlight();
        </script>
    </div>
</body>
</html>

Както се вижда, контрола е създаден с javascript функция, която се съдържа в Silverlight.js. Това което трябва да направим е да добавим този файл към асп сайта. После създаваме нов javascript файл, който ще съдържа в себе си кода от testpage.html.js

// JScript source code
 
//contains calls to silverlight.js, example below loads Page.xaml
function createSilverlight( xamlPage )
{
    Silverlight.createObjectEx({
        source: xamlPage,
        parentElement: document.getElementById("SilverlightControlHost"),
        id: "SilverlightControl",
        properties: {
            width: "100%",
            height: "100%",
            version: "1.1",
            enableHtmlAccess: "true"
        },
        events: {}
    });
 
    // Give the keyboard focus to the Silverlight control by default
    document.body.onload = function() {
      var silverlightControl = document.getElementById('SilverlightControl');
      if (silverlightControl)
      silverlightControl.focus();
    }
 
}

С малка промяна(добавен параметър) кодът изглежда по следния начин:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Integrating Silverlight in aspx</title>
 
    <script type="text/javascript" src="Silverlight.js"></script>
    <script type="text/javascript" src="XamlPageCreation.js"></script>
 
</head>
<body>
    <form id="frmMain" runat="server">
    <div id="SilverlightControlHost" >
        <script type="text/javascript">
            createSilverlight( 'Page.xaml' );
        </script>
    </div>
    </form>
</body>
</html>

Какво ще показваме?

Засега имаме работещ ASP.NET/Silverlight пример който не показва нищо. Нека направим TextBlock със съобщение потребителя да избира файлове. При кликване на TextBlock-а се отваря FileBrowse диалог и след селекция на няколко файла, техните имена се показват в TextBlock контрола.

<Canvas x:Name="parentCanvas"
        xmlns="http://schemas.microsoft.com/client/2007" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Loaded="Page_Loaded" 
        x:Class="SilverlightSamplePrj.Page;assembly=ClientBin/SilverlightSamplePrj.dll"
        Width="400"
        Height="400"
        Background="#EEEEEE"
        >
 
  <TextBlock x:Name="txtFileName"
             Canvas.Top="5" Canvas.Left="5" 
             Foreground="Black"
             Text="Click for OpenFileDialog"
             MouseLeftButtonDown="OnClick"/>
 
</Canvas>

Ето и кода в C# файла:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
 
namespace SilverlightSamplePrj
{
    public partial class Page : Canvas
    {
        public void Page_Loaded(object o, EventArgs e)
        {
            // Required to initialize variables
            InitializeComponent();
        }
 
        public void OnClick(object o, MouseEventArgs e)
        {
            txtFileName.Text = "";
            string NL = Environment.NewLine;
            OpenFileDialog ofDlg = new OpenFileDialog();
            ofDlg.EnableMultipleSelection = true;
            if (ofDlg.ShowDialog() == DialogResult.OK)
            {
                foreach (FileDialogFileInfo fdFileInfo in ofDlg.SelectedFiles)
                {
                    txtFileName.Text += fdFileInfo.Name + NL;
                }
            }
        }
    }
}

Заключение

Това е достатъчно за начало, очакваме следващите версии на Silverlight където се надяваме да има предефинирани контроли плюс куп други възможности който да утвърдят Silverlight като Технологията за RIA.