블로그 이미지
Sunny's

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Notice

2010. 7. 6. 11:04 ASP.NET

ASP.NET 프로젝트에서는 Visual Studio에서 참조된 어셈블리 외에도 bin 폴더에 포함된 모든 어셈블리를 참조된 어셈블리로 인식합니다.
외부에서 컴파일 된 어셈블리 또한 런타임에 bin폴더로 추가하여도 정상적으로 동작하게 됩니다.

그렇다면, ASP.NET 프로젝트에서 참조된 모든 어셈블리의 목록을 어떻게 가져올 수 있을까요?
이는
System.Web.Extenstions 참조후
System.Web.Compliation.BuildManager 클래스의 GetReferencedAssemblies 정적 메서드를 이용하여 알 수 있습니다.

만일 참조된 어셈블리에 존재하는 WCF RIA Services의 DomainService의 하위 클래스의 목록을 가져오려 한다면 아래와 같은 코드를 이용할 수 있습니다.

Dictionary<string, Type> dictionary = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);

Type type = typeof(DomainService);

 

foreach (Assembly assembly in BuildManager.GetReferencedAssemblies().Cast<Assembly>())

{

    Type[] exportedTypes = null;

    try

    {

        exportedTypes = assembly.GetExportedTypes();

    }

    catch (ReflectionTypeLoadException exception)

    {

        exportedTypes = exception.Types;

    }

    catch (Exception)

    {

    }

 

    if (exportedTypes != null)

    {

        foreach (Type type2 in exportedTypes)

        {

            if ((!type2.IsAbstract && !type2.IsInterface) &&

                (!type2.IsValueType && type.IsAssignableFrom(type2)) &&

                (TypeDescriptor.GetAttributes(type2)[typeof(EnableClientAccessAttribute)] != null))

            {

                string canonicalFileName = GetCanonicalFileName(type2);

                dictionary[canonicalFileName] = type2;

            }

        }

    }

}


위 코드에서는 BuildManager.GetReferencedAssemblies 메서드를 통하여 참조로 등록된 어셈블리들을 가져오고,
Type.IsAssignableFrom(Type) 메서드를 이용하여 현재 타입이 DomainService를 상속받고 있는지를 확인합니다.
그리고, TypeDescriptor.GetAttributes 메서드를 이용하여 등록된 특성 중에 EnableClientAccess 가 있는지를 확인하게 됩니다.

위와 같은 방식으로 BuildManager 클래스와 리플렉션을 이용하여 런타임에 참조된 어셈블리를 불러와서 다양한 활용이 가능해집니다.

출처 : http://blog.ntils.com/entry/ASPNET-프로젝트에서-참조된-어셈블리-불러오기

posted by Sunny's
2010. 5. 26. 19:03 ASP.NET
 

Here is the latest in my link-listing series.  Also check out my VS 2010 and .NET 4 series and ASP.NET MVC 2 series for other on-going blog series I’m working on.

[In addition to blogging, I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu]

ASP.NET MVC

  • ASP.NET MVC with jTemplates Part 1 and Part 2: Steve Gentile has a nice two-part set of blog posts that demonstrate how to use the jTemplate and DataTable jQuery libraries to implement client-side data binding with ASP.NET MVC.

  • How to Configure VS 2010 Code Coverage for ASP.NET MVC Unit Tests: Visual Studio enables you to calculate the “code coverage” of your unit tests.  This measures the percentage of code within your application that is exercised by your tests – and can give you a sense of how much test coverage you have.  Gunnar Peipman demonstrates how to configure this for ASP.NET MVC projects.

  • Shrinkr URL Shortening Service Sample: A nice open source application and code sample built by Kazi Manzur that demonstrates how to implement a URL Shortening Services (like bit.ly) using ASP.NET MVC 2 and EF4.  More details here.

  • Creating RSS Feeds in ASP.NET MVC: Damien Guard has a nice post that describes a cool new “FeedResult” class he created that makes it easy to publish and expose RSS feeds from within ASP.NET MVC sites.

ASP.NET

.NET 4

  • Entity Framework 4 Video Series: Julie Lerman has a nice, free, 7-part video series on MSDN that walks through how to use the new EF4 capabilities with VS 2010 and .NET 4.  I’ll be covering EF4 in a blog series that I’m going to start shortly as well.

  • Getting Lazy with System.Lazy: System.Lazy and System.Lazy<T> are new features in .NET 4 that provide a way to create objects that may need to perform time consuming operations and defer the execution of the operation until it is needed.  Derik Whittaker has a nice write-up that describes how to use it.

  • LINQ to Twitter: Nifty open source library on Codeplex that enables you to use LINQ syntax to query Twitter.

Visual Studio 2010

  • Using Intellitrace in VS 2010: Chris Koenig has a nice 10 minute video that demonstrates how to use the new Intellitrace features of VS 2010 to enable DVR playback of your debug sessions.

  • How to maintain control of your code using Layer Diagrams: Another great blog post by Jennifer Marsman that demonstrates how to setup a “layer diagram” within VS 2010 to enforce clean layering within your applications.  This enables you to enforce a compiler error if someone inadvertently violates a layer design rule.

  • Collapse Selection in Solution Explorer Extension: Useful VS 2010 extension that enables you to quickly collapse “child nodes” within the Visual Studio Solution Explorer.  If you have deeply nested project structures this extension is useful.

Silverlight and Windows Phone 7

Hope this helps,

Scott

출처 : http://weblogs.asp.net/scottgu/archive/2010/05/20/may-20th-links-asp-net-mvc-asp-net-net-4-vs-2010-silverlight.aspx


posted by Sunny's
2010. 5. 13. 10:23 ASP.NET

Abstract:
In this article we are going to demonstrate jqGrid, JQuery Grid plugin which is used to display tabular data on the form. The article will also discuss how to export the Grid to the Excel format.
Why JQuery Grid Plugin?

You can always use the plain vanilla HTML code to create your tables but JQuery Grid gives you the ability perform sorting, paging, searching and many other operations which are very cumbersome to write.

Setting Up the Project:

We are using ASP.NET MVC 1.0 for our demo. First, you can download the JQuery library and the JGrid library from the following URLs:

1) JQuery
2) JGrid

The JGrid documentation explains how and where to put all the .js files. If you find it hard to follow then just download the source code at the end of this article and set up your project similar to the download sample.

Populating Grid with Data:

Before we start retrieving products from the database we should make a reference to all the required scripts in our page. Since, we are using master pages we will include all the script and CSS references in the master page as shown below:

1  <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
2     <link href="../../Content/ui.jqgrid.css" rel="stylesheet" type="text/css" />
3     <script src="../Scripts/jquery-1.3.2.js" type="text/javascript"></script>
4     <script src="../Scripts/jquery.jqGrid.js" type="text/javascript"></script>
5     <script src="../../Scripts/Site.js" type="text/javascript"></script>


After creating all the references our next task is to populate the Grid with data. We will be using the Northwind database "Products" table. Here is our simple repository which returns all the products from the Products table as a List<Product>.

01  public class ProductRepository : IProductRepository
02     {
03         public List<Product> GetAll()
04         {
05             using(var db = new NorthwindDataContext())
06             {
07                 return (from p in db.Products
08                        select p).ToList();
09             }
10         }
11     }
  

The loadProducts JavaScript function is responsible for populating the View with the data.

01 <script language="javascript" type="text/javascript">
02     // load the products
03     loadProducts();
04 </script> 
05 <% using (Html.BeginForm(new { Action = "ExportToExcel" }))
06  {%>
07    
08 <table id="list"></table>
09 <input type="submit" value="Export to Excel" />
10 <%
11         
12  }%>


Let's take a look at the loadProducts method.

01 function loadProducts()
02 {
03     jQuery(document).ready(function() {
04         jQuery("#list").jqGrid({
05             url: '/Home/GetProducts/',
06             datatype: 'json',
07             mtype: 'GET',
08             colNames: ['Id', 'Name', 'QuantityPerUnit',"UnitPrice"],
09             colModel: [
10           { name: 'Id', index: 'Id', width: 40, align: 'left' },
11           { name: 'Name', index: 'Name', width: 40, align: 'left' },
12           { name: 'QuantityPerUnit', index: 'QuantityPerUnit', width: 200, align: 'left' },
13           { name: 'UnitPrice', index: 'UnitPrice', width: 200, align: 'left' }],
14             rowNum: 10,
15             rowList: [5, 10, 20, 50],
16             sortname: 'Id',
17             sortorder: "desc",
18             viewrecords: true,
19             caption: 'My first grid'
20         });
21     });
22 }


The above code assigns different values to the jqGrid. The url attribute represents the controller action that will be fired. The colNames represent the header text of the table that will be displayed. The colModel refers to the individual grid columns as an array of properties.  

Now, let's see what the controller looks like:

01  public ActionResult GetProducts(string sidx, string sord, int page, int rows)
02         {
03   var products = _productRepository.GetAll();
04             var totalPages = 1; // we'll implement later
05             var totalRecords = 3; // implement later
06             var jsonData = new
07                                {
08                                    total = totalPages,
09                                    page = page,
10                                    records = totalRecords,
11                                    rows = (from p in products
12                                            select new
13                                                       {
14                                                           id = p.ProductID,
15                                                           cell = new string[]
16                                                                      {
17                                                                          p.ProductID.ToString(), p.ProductName,
18                                                                          p.ProductName
19                                                                      }
20                                                       }).ToArray()
21                                };
22             return Json(jsonData);
23 }


The _productRepository.GetAll() method is responsible for fetching all the products from the Products table. Finally, we created an Anonymous type jsonData which contains the properties required by the jqGrid. The rows collection contains an object with id property and cells collection.

When you run the above example you will see the following output:



The above image shows that Grid is rendered on the page successfully. There are few columns which are not displayed because they were not included in the jqGrid column collection. 

The code in the GetProducts action of the HomeController is very nasty. We should move this code to a different place where it can be reused.

Creating ToJsonForjqGrid<T> Extension Method:

The purpose of ToJsonForjqGrid<T> extension method is to convert a List<T> collection into a format supported by the jqGrid.

01   public static object ToJsonForjqGrid<T>(this List<T> list,string primaryKey,string[] columnNames) where T : new()
02         {
03             if(list.Count() == 0)
04                 throw new ArgumentException("List does not contain any items!");
05             var jsonData = new
06                                {
07                                    
08                                    rows = (from p in list
09                                           select new
10                                         {
11                                             id = p.GetPropertyValue(primaryKey),
12                                             cell = p.GetPropertyValues(columnNames)       
13                                         }).ToArray()                              
14                                };
15             return jsonData; 
16         }


ToJsonForJqGrid<T> takes two arguments. The first argument is the primary key of the object which will be assigned to the id property of the row. The second argument is the columnNames[] which contains the name of the columns to be included in the jqGrid.

And here is the GetProducts action using the ToJsonForJqGrid<T> method.

1  public ActionResult GetProducts(string sidx, string sord, int page, int rows)
2         {
3             var jsonData = _productRepository.GetAll().ToJsonForjqGrid("ProductID", new[] { "ProductID", "ProductName" });
4             return Json(jsonData);
5         }


And the result is shown below:



If we need to include a couple of more columns we can add the names in the string[] collection for the columnNames parameter to the ToJsonForjqGrid<T> method.

1 public ActionResult GetProducts(string sidx, string sord, int page, int rows)
2         {
3             var jsonData = _productRepository.GetAll().ToJsonForjqGrid("ProductID", new[] { "ProductID", "ProductName", "QuantityPerUnit","UnitPrice" });
4             return Json(jsonData);
5         }


A little better!

And here is the result:



Exporting Grid to Excel:

When the export to excel button is clicked the form is submitted and "ExportToExcel" action is fired.

01  public ActionResult ExportToExcel()
02         {
03             var products = _productRepository.GetAll();
04             var grid = new GridView();
05             grid.DataSource = from p in products
06                               select new
07                                          {
08                                              ProductName = p.ProductName,
09                                              SomeProductId = p.ProductID
10                                          };
11             grid.DataBind();
12             Response.ClearContent();
13             Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
14             Response.ContentType = "application/excel";
15             StringWriter sw = new StringWriter();
16             HtmlTextWriter htw = new HtmlTextWriter(sw);
17             grid.RenderControl(htw);
18             Response.Write(sw.ToString());
19             Response.End();
20             return View("Index");
21         }


NOTE: You should not put the export to excel code right into the controller action. Create a ExportToExcel service and use that to perform the exportation task.

Inside the ExportToExcel action we simply retrieve the products from the database and creates an anonymous type collection and assign to the GridView control. Later the GridView control is rendered to the HtmlTextWriter and send as an attachement with the response.



Conclusion:

In this article we learned how to use jqGrid to display data from the database. We also learned how to export the grid to excel.

References:

1) Using JQuery Grid with ASP.NET MVC

[Download Sample]

posted by Sunny's
2010. 5. 11. 11:32 ASP.NET

페이지를 작성하다가 이상한점이 생겼다.

 디자이너가 작업한 내용과 내가 만든 결과물이 틀리게 나오는것이다.

 문제는 CSS파일에 있는것 같았다.

 어떤 스타일은 적용이 되는데 어떤 스타일은 적용이 되지 않았다.

 web.config파일의 내용을 수정해 주면 해결이 된다.

    <globalization 
            requestEncoding="euc-kr"
            responseEncoding="euc-kr"
   />

utf-8이라고 되어있는부분을 euc-kr로 바꿔주면 깔끔하게 해결된다.

 

이런 짜잘한 것들이 작업을 얼마나 방해 하는지 느껴보지 못한 사람은 모를것이다 -.-;;

posted by Sunny's
2010. 5. 7. 10:04 ASP.NET

ASP.NET

ASP.NET MVC

  • Code Snippets for ASP.NET MVC 2 in VS 2010: Raj Kaimal documents some of the new code snippets for ASP.NET MVC 2 that are now built-into Visual Studio 2010.  Read this article to learn how to do common scenarios with fewer keystrokes.

Visual Studio 2010

  • SharePoint Development with VS 2010: Beth Massi links to a bunch of nice “How do I?” videos that that demonstrate how to use the SharePoint development support built-into VS 2010.

  • Using the WPF Tree Visualizer in VS 2010: Zain blogs about the new WPF Tree Visualizer supported by the VS 2010 debugger.  This makes it easier to visualize WPF control hierarchies within the debugger.

  • TFS 2010 Power Tools Released: Brian Harry blogs about the cool new TFS 2010 extensions released with this week’s TFS 2010 Power Tools release.

  • What is New with T4 in VS 2010: T4 is the name of Visual Studio’s template-based code generation technology.  Lots of scenarios within VS 2010 now use T4 for code generation customization. Two examples are ASP.NET MVC Views and EF4 Model Generation.  This post describes some of the many T4 infrastructure improvements in VS 2010.

Hope this helps,

Scott

posted by Sunny's
2009. 6. 26. 09:29 ASP.NET


Here is the latest in my link-listing series.  Also check out my ASP.NET Tips, Tricks and Tutorials page and Silverlight Tutorials page for links to popular articles I've done myself in the past.

You can also now follow me on twitter (@scottgu) where I also post links and small posts.

ASP.NET

  • GridView Confirmation Box using jQuery: Mohammed Azam has a nice post that describes how to implement model confirmation UI using jQuery.  This is particularly useful for scenarios like saving or deleting data.

AJAX

  • ASP.NET 4.0 AJAX – Client Templates: Damien White has a great post that describes the new client templating support in ASP.NET AJAX.  This provides an easy and powerful way to dynamically create rich HTML UI on the client.

  • ASP.NET 4.0 AJAX - Data Binding: Damien White continues his great ASP.NET AJAX series with this article that describes the new client-side data binding features in the new version of ASP.NET AJAX. 

ASP.NET MVC

  • DataAnnotations and ASP.NET MVC: Brad Wilson (a dev on the ASP.NET MVC team) has a nice post that describes how to use DataAnnotations to annotate model objects, and then use a model binder to automatically validate them when accepting form posted input.  DataAnnotation support will be built-in with the next version of ASP.NET MVC.

Visual Studio

Hope this helps,

Scott

posted by Sunny's
prev 1 2 3 next