블로그 이미지
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

2011. 11. 5. 01:42 ASP.NET

Entity Framework를 사용하는 웹 프로젝트에서 필요로 하는 네임스페이스 및 어셈블리에 대한 참조가 RTM 버전의 루트 Web.config 파일에서 제거되었습니다. 따라서 시험판 버전의 ASP.NET 4를 사용하여 만들었으며 Entity Framework를 사용하는 웹 응용 프로그램뿐만 아니라 EntityDataSource를 사용하는 Dynamic Data 웹 사이트가 실패하고 컴파일 오류를 보고합니다.

이 문제를 해결하려면

누락된 어셈블리 및 네임스페이스 참조를 응용 프로그램의 Web.config 파일에 삽입할 수 있습니다. 다음 예제에서는 응용 프로그램 수준의 Web.config 파일에 수동으로 삽입해야 할 어셈블리 및 네임스페이스 요소를 보여 줍니다.


<system.web>

<compilation>
<assemblies>
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Web.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>

<pages>
<namespaces>
<add namespace="System.Data.Entity.Design" />
<add namespace="System.Data.Linq" />
</namespaces>
</pages>

</system.web>


posted by Sunny's
2011. 7. 12. 13:07 ASP.NET
Just return a JsonResult.
Here is an example I am using in production:
public partial class StudentController : BaseController {
    public StudentController(RESTContext portalContext)
        : base(portalContext) { }

    [HttpGet, Url("organizations/{organizationId?}/students")]
    public virtual JsonResult List(Guid? organizationId) {
        if (organizationId != RESTContext.OrganizationId)
            throw new HttpNotAuthorizedException();

        var query = RESTContext.GetQuery<IQuery<StudentCasesReport>>()
            .Where(x => x.OrganizationId, organizationId)
            .OrderBy(x => x.LastName, SortOrder.Ascending);
        var cases = query.Execute(IsolationLevel.ReadUncommitted);

        return Json(cases, JsonRequestBehavior.AllowGet);
    }

    [HttpGet, Url("organizations/{organizationId?}/students/{studentId?}")]
    public virtual JsonResult Get(Guid? organizationId, Guid? studentId) {
        if (studentId.IsNull())
            throw new HttpNotFoundExecption();

        if (organizationId != RESTContext.OrganizationId)
            throw new HttpNotModifiedException();

        var query = RESTContext.GetQuery<IQuery<StudentCasesReport>>()
            .Where(x => x.OrganizationId, organizationId)
            .Where(x => x.StudentCaseId, studentId)
            .OrderBy(x => x.LastName, SortOrder.Ascending);
        var cases = query.Execute(IsolationLevel.ReadUncommitted).FirstOrDefault();

        if (cases.IsNull())
            throw new HttpNotFoundExecption();

        return Json(cases, JsonRequestBehavior.AllowGet);
    }
}
posted by Sunny's
2011. 6. 27. 15:11 ASP.NET

 

Json.NET is a popular high-performance JSON framework for .NET


Features

-Flexible JSON serializer to convert .NET objects to JSON and back again
-LINQ to JSON for manually reading and writing JSON
-High performance, faster than .NET's built-in JSON serializers
-Writes indented, easy to read JSON
-Convert JSON to and from XML
-Supports Silverlight and Windows Phone

The JSON serializer is a good choice when the JSON you are reading or writing maps closely to a .NET class. The serializer automatically reads and writes JSON for the class.

LINQ to JSON is good for situations where you are only interested in getting values from JSON, you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects. LINQ to JSON allows you to easily read, create and modify JSON in .NET.

NuGet

Download Json.NET from CodePlex or install using NuGet

NuGet

Documentation

Find guides for getting started and comprehensive API Documentation at http://james.newtonking.com/projects/json/help/

My Blog

My blog can be found at http://james.newtonking.com where I post news and updates about Json.NET.

My Twitter

My twitter account can be found at @JamesNK

Donate

Json.NET is a free open source project that I have developed in my personal time. I really appreciate your feedback and support for Json.NET and its future development.

posted by Sunny's
2011. 6. 27. 09:25 ASP.NET

.NET 용 Facebook API Developoer Toolkit
http://facebooktoolkit.codeplex.com/



Please note: After several months of analysis and recent discussions with Microsoft we have decided to discontinue support of this library. The library grew to the point that it is hard to maintain and was designed when Facebook's api was different and types of applications being developed were different. We have considered changes that would make things easier, but after discussion with Microsoft and after examining the new sdk that has been published by some of our colleagues in the community, we feel that the new library provides a very solid and flexible approach to building facebook apps and seems that it will be easier to maintain moving forward. We are planning to lend our support however we can to the new sdk listed below. Thanks to everyone who has invested their time and effort into supporting this library over the years. I am sure that the leaders of the new library would appreciate the feedback and support that we have gotten.

New SDK can be found here: http://facebooksdk.codeplex.com/documentation

The new SDK has been completely retooled and it incorporates Facebook’s latest capabilities like the Graph API and REST API Calls. You will also find useful sample apps to get you started such as:
*
ASP.NET MVC Sample
*WebForms iFrame Sample
*Silverlight 4 Out of Browser Sample
*Silverlight 4 In Browser Sample
*Windows Phone 7 Sample
posted by Sunny's
2011. 6. 24. 14:59 ASP.NET

Last week I blogged about the new ASP.NET MVC 3 Tools Update, and then followed it up with a detailed post that covered using the EF Code First and the new Data Scaffolding features in it.

Today’s blog post is a continuation of this series and covers some of the new HTML5 improvements with the ASP.NET MVC 3 Tools Update release.

Project Template Support for HTML5 Semantic Markup

The ASP.NET MVC 3 Tools Update adds support for you to optionally use HTML5 semantic markup when creating new ASP.NET MVC 3 projects. You can specify this by checking the “Use HTML5 semantic markup” checkbox when creating new projects:

SNAGHTML10f01f0d

Selecting this checkbox option does two things:

1) It causes VS 2010 to use HTML5 semantic markup elements like <header>, <footer>, <section> and <nav> within the default layout.cshtml file that is generated. This is instead of just using <div> elements for header/footer/navigation elements – which is the default behavior if the HTML5 semantic checkbox isn’t selected (and the same behavior that we have shipped earlier).

2) It causes VS 2010 to reference the modernizr.js JavaScript library by default within the layout.cshtml – which among other things will allow you to use CSS to style HTML5 semantic markup elements even with older browsers like IE6 (ensuring your site still works for older browsers).

Understanding Semantic HTML5 Markup

HTML5 introduces a number of new elements and APIs that introduce new behavioral capability (features like <video>, <canvas>, <svg>, etc).

HTML5 also introduces new elements (like <section>, <article>, <aside>, <header>, and <nav>) that enable you to enrich the semantic meaning and structure of your content and pages. These features allow you to write your pages so that you don’t have to use opaque <div> elements to structure everything, and instead they allow you to better express the semantic meaning of your content. This makes your code a little cleaner to read, and long-term will hopefully enable browsers and search engines to better understand your markup and provide even richer experiences.

When you create a new ASP.NET MVC 3 Project with the “Use HTML5 semantic markup” checkbox selected, Visual Studio will use semantic HTML instead of <div> elements (where appropriate) within the layout.cshtml file that is generated for the new project. This means that the top of the site is wrapped in a <header> element, navigation links are surrounded by a <nav> element, and the footer is encapsulated within a <footer> element.

Learn more about Semantic HTML5 Markup

Bruce Lawson and Remy Sharp have a great Introducing HTML5 book that covers (among other new HTML5 features) how you can take advantage of semantic HTML5 markup:

image

You can also read Emily Lewis’ Using HTML5’s New Semantic Tags Today article on MSDN’s ScriptJunkie site to learn more about the role of HTML5 semantic markup and see a practical example of it in action.

HTML5 Intellisense within VS 2010 SP1

With VS 2010 SP1, you can now change the “Target Schema for Validation” drop-down within the Text Editor toolbar to target HTML5 with intellisense:

image

When you select HTML5 as your validation target, the HTML intellisense engine within Visual Studio will provide appropriate intellisense for the new HTML5 elements and attributes. This is true for both behavioral elements like <canvas> and <video> as well as semantic elements like <article> and <nav>:

SNAGHTML1115b0b2

Note: the next release of VS will default to honoring the <!DOCTYPE> at the top of the page when driving intellisense, and then allow you to specify a default standard to use when it isn’t present (or when you are editing within user controls, or partial/editor templates). With VS 2010 and earlier versions of Visual Studio you have to explicitly set which HTML version you want to target.

Modernizr.js Library

Semantic HTML5 markup is now supported by all modern browser vendors, and you can use standard CSS techniques to stylize and customize pages built with it.

One challenge, though, is that there are still a lot of older browsers out there – and browsers like IE6 by default don’t allow you to stylize semantic HTML5 elements using CSS. The semantic HTML5 site that looks beautiful in a modern browser might end up looking broken unless you use a library that enables you to work around this limitation.

Modernizr.js

Modernizr is a small and elegant open-source JavaScript library that helps you take advantage of emerging web technologies (HTML5, CSS3) while still maintaining a level of compatibility with older browsers that may not yet support these new capabilities. You can learn more about Modernizr from the http://modernizr.com/ website.

Starting with the ASP.NET MVC 3 Tools Update, we are now shipping Modernizr with ASP.NET MVC 3, and adding it by default to all new ASP.NET MVC 3 projects. If you select the “Use HTML5 semantic markup” checkbox when creating new ASP.NET MVC 3 projects, Visual Studio will also add a reference to the Modernizr.js library by default within your layout.cshtml template:

image

Modernizr.js and using CSS with Semantic HTML5 on older Browsers

Including the above Modernizr.js script reference will enable you to use CSS to stylize semantic HTML5 elements – and have it work both in modern browsers (where it is natively supported), as well as older ones (including IE6). Among other things, Modernizr is smart enough to run a little script that will cause older browsers to honor CSS rules with unknown elements they encounter.

You can see the benefit Modernizr brings with this by running the default ASP.NET MVC 3 project that is created using IE9. If you use the default IE9 rendering mode (which supports Semantic HTML5 elements) the site will look like below, and use the browser’s built-in CSS support for semantic HTML5:

SNAGHTML112b7c79

If you enable “Compatibility View” within the browser (the second icon at the top of IE’s navigation bar) – you’ll see a “downlevel” rendering of the page (just like what IE6/7/8 users would see). Modernizr allows our CSS rules to work in this downlevel mode – despite the older IE rendering engine not natively supporting elements like <header>, <footer>, <nav>, <section>, etc:

SNAGHTML112e4acf

If we had not included Modernizr.js on the page, visitors to the site using older browsers would have instead seen something broken like this:

SNAGHTML1130d736

As you can see – Modernizr provides a big improvement over what users with older browser would have otherwise seen! Best of all, we didn’t have to write any code or author an alternative CSS style-sheet to get this to work. And we are using HTML5 Semantic Markup throughout the site.

Using Modernizr to Detect Browser Capabilities

The above Semantic HTML5 markup example is just one of the nice benefits that Modernizr brings.

Modernizr also makes it easy to check for browser capabilities (without you having to hard-code browser versions into code), and enables you to easily detect and light-up if a specific feature is supported. You can learn more about how this works on the http://modernizr.com web-site.

Justin Schwartzenberger has a nice blog post that shows this in action, and highlights How to use Modernizr with ASP.NET MVC 3 to store user data via HTML5 localstorage. His tutorial shows an end-to-end ASP.NET MVC 3 sample where he uses HTML5’s localstorage feature if it is available, and falls back to just using cookies on older browsers.

Summary

The new ASP.NET MVC 3 Tooling Update is full of goodness. If you haven’t already downloaded and installed it I highly recommend you do so. You can run the ASP.NET MVC 3 installer on the http://asp.net/mvc site to make sure you have the latest version.

The HTML5 Semantic Markup improvements in ASP.NET MVC 3 enable you to start designing sites that take better advantage of HTML5 and modern browsers. Using Modernizr.js you can also have these sites continue to work with older browsers, and optionally light-up only when new features are enabled.

Hope this helps,

Scott

P.S. I am also now using Twitter for quick updates and to share links. Follow me at: twitter.com/scottgu

posted by Sunny's
2011. 5. 16. 09:09 ASP.NET

ASP.NET MVC 3 supports a new view-engine option called “Razor” (in addition to continuing to support/enhance the existing .aspx view engine).  Razor minimizes the number of characters and keystrokes required when writing a view template, and enables a fast, fluid coding workflow.

Unlike most template syntaxes, with Razor you do not need to interrupt your coding to explicitly denote the start and end of server blocks within your HTML. The Razor parser is smart enough to infer this from your code. This enables a compact and expressive syntax which is clean, fast and fun to type.

You can learn more about Razor from some of the blog posts I’ve done about it over the last last 9 months:

Today’s blog post covers a cool feature of Razor that a lot of people don’t know about – which is the ability to define re-usable helper methods using the @helper syntax.

Simple @helper method scenario

The @helper syntax within Razor enables you to easily create re-usable helper methods that can encapsulate output functionality within your view templates.  They enable better code reuse, and can also facilitate more readable code.  Let’s look at a super-simple scenario of how the @helper syntax can be used. 

Code before we define a @helper method

Let’s look at a simple product listing scenario where we list product details, and output either the price of the product – or the word “FREE!” if the item doesn’t cost anything:

image

The above code is fairly straight-forward, and Razor’s syntax makes it easy to integrate server-side C# code within the HTML. 

One place that is a little messy, though, is the if/else logic for the price.  We will likely output prices elsewhere within the site (or within the same page), and duplicating the above logic everywhere would be error-prone and hard to maintain.  Scenarios like this are prime candidates to extract and refactor into helper methods using the @helper syntax.

Refactoring the above sample using the @helper syntax

Let’s extract the price output logic, and encapsulate it within a helper method that we’ll name “DisplayPrice”.  We can do this by re-writing the sample to the code below:

image

We’ve used the @helper syntax above to define a reusable helper method named “DisplayPrice”.  Just like a standard C#/VB method, it can contain any number of arguments (you can also define the arguments to be either nullable or optional).  Unlike standard C#/VB methods, though, @helper methods can contain both content and code, and support the full Razor syntax within them – which makes it really easy to define and encapsulate rendering/formatting helper methods:

SNAGHTML20fae4df

You can invoke @helper methods just like you would a standard C# or VB method:

SNAGHTML20fcdc86

Visual Studio will provide code intellisense when invoking the method:

image

Reusing @helpers across multiple views

In the example above, we defined our @helper method within the same view template as the code that called it.  Alternatively, we can define the @helper method outside of our view template, and enable it to be re-used across all of the view templates in our project.

We can accomplish this by saving our @helper methods within .cshtml/.vbhtml files that are placed within a \App_Code directory that you create at the root of a project.  For example, below I created a “ScottGu.cshtml” file within the \App_Code folder, and defined two separate helper methods within the file (you can have any number of helper methods within each file):

SNAGHTML2107b6ae

Once our helpers are defined at the app level, we can use them within any view template of our application. 

The ScottGu.cshtml template in the \App_Code folder above will logically compile down to a class called “ScottGu” with static members of “DisplayPrice” and “AnotherHelper” within it.  We can re-write our previous sample to call it using the code below:

SNAGHTML210d65c1

Visual Studio will provide code intellisense when calling app-level helpers like this:

image

May 15th Update: One issue that a few people have pointed out is that when a @helper is saved within the \app_code directory, you don’t by default get access to the ASP.NET MVC Html helper methods within it (e.g. Html.ActionLink(), Html.TextBox(), etc).  You do get access to the built-in HTML helper methods when they are defined in the same file as your views.  This is not supported out of the box, though, when the helpers are within the \app_code directory - we’ll add this in the next release.  Paul Stovall has a nice helper class that you can use in the meantime to access and use the built-in Html helper methods within @helper methods you define in the \app_code directory.  You can learn how to use it here.

Summary

Razor’s @helper syntax provides a convenient way to encapsulate rendering functionality into helper methods that you can re-use within individual view templates, or across all view templates within a project. 

You can use this functionality to write code that is even cleaner and more maintainable. 

Hope this helps,

Scott


출처 : http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

posted by Sunny's
2011. 5. 13. 09:59 ASP.NET
출처 : http://msdn.microsoft.com/ko-kr/library/93bskf9z.aspx

인터넷 같은 공용 네트워크에서는 엔터티 간의 보안 통신 수단을 제공하지 않습니다. 이러한 네트워크를 통한 통신은 권한이 없는 제3자가 읽거나 수정하기 쉽습니다. 파일 암호화 및 로컬 디스크에 대한 암호화 외에도 암호화를 사용하면 보안되지 않은 채널에 대해 보안 통신 방법을 만들어 데이터 무결성 및 인증 기능을 제공할 수 있습니다.

.NET Framework 암호화 네임스페이스의 클래스에서는 암호화의 세부 사항 대부분을 관리해 줍니다. 이 중 일부 클래스는 관리되지 않는 Microsoft CryptoAPI에 대한 래퍼인 반면, 일부는 완전하게 관리되는 구현 클래스입니다. 암호화에 익숙하지 않은 사용자도 이러한 클래스를 사용할 수 있습니다. 암호화 알고리즘 클래스 중 하나의 새 인스턴스를 만들 때 키는 사용하기 쉽도록 자동으로 생성되며 기본 속성은 가능한 한 안전하고 보안이 유지되도록 설정됩니다.

암호화 개요

비대칭 암호화, 대칭 암호화, 디지털 서명 및 암호화 해시 같은 암호화의 주요 개념에 대해 간단히 설명합니다.

.NET Framework 암호화 모델

기본 클래스 라이브러리에서 암호화가 구현되는 방식에 대해 설명합니다.

암호화 작업

기본 클래스 라이브러리를 사용하여 특정 암호화 작업을 수행하는 방법에 대해 설명합니다.

연습: 암호화 응용 프로그램 만들기

기본 암호화 및 해독 작업을 보여 줍니다.

CNG(Cryptography Next Generation) 보안 통신 예제

CNG(Cryptography Next Generation) 클래스, 명명된 파이프 전송 및 대화형 콘솔 창을 사용하여 중간자 개입 공격을 막는 암호화 솔루션을 모델링합니다.

암호화 클래스 구성

암호화 클래스에 알고리즘 이름을 매핑하고 암호화 알고리즘에 개체 식별자를 매핑하는 방법에 대해 설명합니다.

System.Security.Cryptography.Pkcs 정보

CMS(Cryptographic Message Syntax) 및 PKCS #7(Public-Key Cryptography Standards #7) 표준의 관리 코드 구현을 포함하는 네임스페이스에 대해 설명합니다. 이 단원에서는 개발자에 대한 내용을 다룹니다.

System.Security.Cryptography.Pkcs 사용

System.Security.Cryptography.Pkcs 네임스페이스를 사용하여 CMS(Cryptographic Message Syntax) 및 PKCS #7(Public-Key Cryptography Standards #7) 표준을 사용자 응용 프로그램으로

posted by Sunny's
2011. 5. 12. 13:54 ASP.NET


REST stands for Representational State Transfer. It is an architecture designed to represent resources via standard HTTP URIs and Verbs. REST provides a uniform interface for identifying resources, manipulating resources through representations, and including metadata that can make messages self-describing. REST is not tied to any platform or technology but is done on the Web using HTTP.


The following HTTP verbs may be used when creating RESTful services:

GET - Requests a specific representation of a resource
PUT - Create or update a resoure with the supplied representation
DELETE - Delete the specified resource
POST - Submit data to be processed by the identified resource
HEAD - Similar to GET but only retrieves headers
OPTIONS - Returns the methods supported by the identified resource

In this article I'll show how to build a "Notes" (a.k.a. "reminders") RESTful WCF service and consume it using jQuery / JSON from the client. We'll see how to create the service interface, what decorations (Attributes) are required, what's required in the web.config settings, how to make the jQuery $ajax calls to the service, and how to handle the server side logic with a small SQLite database. Everything in the downloadable solution is included - you need only unzip it and it should "work out of the box".

In order to create a WCF service, you can start with a standard ASP.NET Web Application project and add a new WCF Service.

To Create a complete WCF REST service, you start with the interface. Here's mine:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Script.Services;

namespace RESTFulNotes
{

    [ServiceContract]
    public interface IService1
    {
         //GetNotes: method to get all Notes. In this UriTemplate there is tag querystring item  ={tag} allows us to filter note by category name
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "Notes?tag={tag}")]
        [OperationContract]
        Notes FindNotes(string tag);

        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "Notes/{ID}")]
        [OperationContract]
        Note GetNote(string ID);

        [WebInvoke(Method = "PUT", ResponseFormat = WebMessageFormat.Json, UriTemplate = "Notes/{ID}")]
        [OperationContract]
        string PutNote(Note Noteobj, string ID);

        [WebInvoke(Method = "DELETE", UriTemplate = "Notes/{ID}")]
        [OperationContract]
        void DeleteNote(string ID);
      }

    // Use a data contract as illustrated in the sample below to add composite types to service operations
    [DataContract]
    public class Note
    {
         [DataMember]
        public int ID { get; set; }
        [DataMember]
        public string Category { get; set; }
        [DataMember]
        public string Subject { get; set; }
        [DataMember]
        public string NoteText { get; set; }
    }

     [CollectionDataContract]
    public class Notes : List<Note>
    {
         public Notes() { }
        public Notes(List<Note> Notes) : base(Notes) { }
    }
}

Note that the WebInvoke decoration is the key item here. It defines the Method, the ResponseFormat, and the custom UriTemplate you want to use. With this information, the WCF runtime is able to handle everything - all you need to do is implement the methods in server-side code, and call them correctly from client script in your consumer page.

With the IService1 interface complete and all attributes correctly marked, we're now ready to implement our interface:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.Net;
using System.ServiceModel.Activation;
using System.Web;


namespace RESTFulNotes
{
  
    [AspNetCompatibilityRequirements(RequirementsMode =AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service1 : IService1
    {
         private SQLiteConnection conn;
        Service1()
        {
            conn = Global.conn;
        }
      
         #region IService1 Members

        public Notes FindNotes(string tag)
        {
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
            Notes notes = new Notes();
            string Sql = "SELECT * FROM NOTE WHERE CATEGORY=@TAG";
            SQLiteCommand cmd = new SQLiteCommand(Sql, conn);
             cmd.Parameters.AddWithValue("@TAG", tag);
            SQLiteDataAdapter da = new SQLiteDataAdapter(Sql, conn);
            da.SelectCommand = cmd;
            DataTable dt = new DataTable();
             da.Fill(dt);
            Note note;
             if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {

                    note = new Note();
                    note.ID = Convert.ToInt32(row["ID"]);
                    note.Category = (string) row["Category"];
                    note.Subject = (string) row["Subject"];
                    note.NoteText = (string) row["NoteText"];
                     notes.Add(note);
                 }
             }
             return notes;
        }

         public Note GetNote(string ID)
        {
            string Sql = "SELECT * FROM NOTE WHERE ID=@ID";
            SQLiteCommand cmd = new SQLiteCommand(Sql, conn);
             cmd.Parameters.AddWithValue("@ID", int.Parse(ID));
            SQLiteDataAdapter da = new SQLiteDataAdapter(Sql, conn);
            da.SelectCommand = cmd;
            DataTable dt = new DataTable();
             da.Fill(dt);
            Note note=null;
            if (dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                note = new Note();
                note.ID = Convert.ToInt32(row["ID"]);
                note.Category = (string)row["Category"];
                note.Subject = (string)row["Subject"];
                note.NoteText = (string)row["NoteText"];
            }
            
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;
             return note;
        }

         public string PutNote(Note  note, string ID)
        {
            String Sql = "INSERT INTO NOTE (CATEGORY,SUBJECT,NOTETEXT) VALUES(@CATEGORY,@SUBJECT,@NOTETEXT)";
            SQLiteCommand cmd = new SQLiteCommand(Sql, conn);

             cmd.Parameters.AddWithValue("@CATEGORY", note.Category);
             cmd.Parameters.AddWithValue("@SUBJECT", note.Subject);
             cmd.Parameters.AddWithValue("@NOTETEXT", note.NoteText);
             if(cmd.Connection.State ==ConnectionState.Closed)
            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.CommandText = "SELECT MAX(ID) FROM NOTE";
            var id = cmd.ExecuteScalar();
            int retval = Convert.ToInt32(id);
             cmd.Connection.Close();
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Created;
            return "ID=" + retval.ToString();
        }

        public void DeleteNote(string ID)
        {
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Found;
          // delete the database row here
         }

         #endregion
    }
}


The actual SQLite connection is defined in global.asax.cs:

public static SQLiteConnection conn;
        void Application_Start(object sender, EventArgs e)
        {
            string cestring = "Data Source=" + HttpContext.Current.Server.MapPath("~/App_Data/Notes.db") + ";version=3";
            conn = new SQLiteConnection(cestring);
        }

This ensures that we get a path to the Notes.db SQLite database file no matter how we've deployed or unzipped the app.

The web.config requirements once the service methods are all implemented is as follows:

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="Windows" />
    <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="EndpointBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="RESTFulNotes.Service1">
        <endpoint address="" binding="webHttpBinding" contract="RESTFulNotes.IService1" behaviorConfiguration="EndpointBehavior">      
        </endpoint>
      </service>
    </services>
  </system.serviceModel>  
</configuration>

Now let's switch over to the Default.aspx page, where all the action is in client script:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="RESTFulNotes._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script src="Scripts/JSon.js" type="text/javascript"></script>
      <script type="text/javascript">
          var Type;
          var Url;
          var Data;
          var ContentType;
          var DataType;
          var ProcessData;
          var method;
          //Generic function to call ASMX/WCF  Service
          function CallService() {
               $.ajax({
                   type: Type, //GET,POST,PUT or DELETE verb
                  url: Url, // Location of the service
                  data: Data, //Data to be sent to server
                  contentType: ContentType, // content type sent to server
                  dataType: DataType, //Expected data format from server
                  processdata: ProcessData, //True or False
                  success: function (msg) {  //On Successful service call
                      ServiceSucceeded(msg);
                  },
                  error: ServiceFailed // function When Service call fails
              });
          }

          function ServiceFailed(result) {
               alert('Service call failed: ' + result.status + '' + result.statusText);
             Type = null; Url = null; Data = null; ContentType = null; DataType = null; ProcessData = null;
          }

          function GetNote() {
              var ID = "5";
             Type = "POST";
              Url = "Service1.svc/Notes/" + ID;
               //Data = '{"ID": "' + ID + '"}';
              ContentType = "application/json; charset=utf-8";
              DataType = "json";
              ProcessData = false;
              method = "GetNote";
              CallService();
          }
          
          function FindNotes() {
             Type = "POST";
              var tag = "Chores";
              Url = "Service1.svc/Notes?tag=" + tag;
              Data = '{"tag": "' + tag + '"}';
              ContentType = "application/json; charset=utf-8";
              DataType = "json";
              ProcessData = true;
              method = "FindNotes";
              CallService();
          }

          function CreateNote() {
             Type = "PUT";
              Url = "Service1.svc/Notes/0";
              var msg2 = {  "Category" : "Chores", "Subject": "To Remember", "NoteText": "Get Milk!" };
              Data = JSON.stringify(msg2);
              ContentType = "application/json; charset=utf-8";
              DataType = "json";
              ProcessData = true;
              method = "CreateNote";
              CallService();
          }


          function ServiceSucceeded(result) {
               if (DataType == "json") {

                   if (method == "CreateNote") {
                       document.getElementById("display").innerHTML = "CREATED: " + result;
                   }
                   else if (method == "GetNote") {
                  resultObject = result.GetNoteResult;
                      var string = " ID:" + result.ID + "<br/>" + "CATEGORY: " + result.Category + "<br/>" + "SUBJECT: " + result.Subject + "<br/>NOTE: " + result.NoteText;
                       document.getElementById("display").innerHTML = string;
                   }

                    else if (method == "FindNotes") {
                    var string="";
                      resultObject = result;

                       for( result in resultObject){
                          string += " ID:" + resultObject[result].ID + "<br/>" + "CATEGORY: " + resultObject[result].Category + "<br/>" + "SUBJECT: " + resultObject[result].Subject + "<br/>NOTE: " + resultObject[result].NoteText + "<Br/>";
                       }
                        document.getElementById("display").innerHTML = string;
                  }

              }
          }

          function ServiceFailed(xhr) {
               alert("FAIL" +xhr.responseText);
               if (xhr.responseText) {
                  var err = xhr.responseText;
                   if (err)
                       error(err);
                   else
                      error({ Message: "Unknown server error." })
               }
               return;
          }

          $(document).ready(
         function () {
             //   CreateNote();
             // GetNote();
             FindNotes();
         }
         );
        
    </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <div id="display">    
    </div>
</asp:Content>

You can see above that I have two script tags defined, one to the google jQuery CDN, and the other to Crockford's Json.js hosted locally.

The business logic in the last script section includes a "genericized" jQuery $ajax call:

           var Type;
          var Url;
          var Data;
          var ContentType;
          var DataType;
          var ProcessData;
          var method;
          //Generic function to call ASMX/WCF  Service
          function CallService() {
               $.ajax({
                   type: Type, //GET,POST,PUT or DELETE verb
                  url: Url, // Location of the service
                  data: Data, //Data to be sent to server
                  contentType: ContentType, // content type sent to server
                  dataType: DataType, //Expected data format from server
                  processdata: ProcessData, //True or False
                  success: function (msg) {  //On Successful service call
                      ServiceSucceeded(msg);
                  },
                  error: ServiceFailed // function When Service call fails
              });
          }

The above allows us to set parameters and make service calls for any method.

I have a ServiceSucceeded function that handles display of results for various method calls, and a ServiceFailed function to show any error messages.

$(document).ready {... } is where you can experiment with whatever function you want to try.

The other functions are just "set ups" for the CallService method. I did not create a fancy jQuery UI for this as it is outside the scope of the article. Ambitious programmers will want to use the jQuery Templating mechanism to populate grids, etc with results.

You can download the fully  functional Visual Studio 2010 Solution which includes the standalone System.Data.Sqlite assembly (this is a mixed - mode assembly which has both the ADO.NET provider and the actual C++ database engine), as well as the sample Notes.db database.



출처 : http://www.eggheadcafe.com/tutorials/aspnet/b480ba4e-b59c-43d4-ac4b-2990ca19daec/restful-aspnet-wcf--jquery--json-service-with-get-post-put-and-delete.aspx


posted by Sunny's
2010. 12. 14. 15:00 ASP.NET

WebMatrix 아니라, Visual Studio에서도 개발이 가능 하다고요?

! – 코난이가 꾸준히 말씀 드린 것처럼, WebMatrix 자체만으로도 충분히 웹사이트 개발을 위한 기술들을 제공하고 있습니다. 아울러, 개발자와 함께 자연스럽게 상위 기술로 이어질 있는 단계를 제공하지요.

- IIS 경우는 윈도우 서버의 IIS 웹서버로
- SQLCE
SQL서버로 완전한 마이그레이션을

- WebMatrix
ASP.NET Web Pages Razor Syntax Visual Studio ASP.NET MVC Razor

아래 내용들을 참고하시면 많은 도움이 되실 거에요.


참고자료

ASP.NET Web Pages에서 MVC로의 자연스러운 연결 - Helper MVC에서 사용해 보자
Razor WebMatrix 대해 후닥닥 적어본 FAQ Razor 벗겨먹기~
WebMatrix 단순 개발 도구가 아니라 스택(Stack)이다?

~ 그렇다면, WebMatrix에서도 되는데~ Visual Studio 이용하나요?
-
통합 개발 환경
-
인텔리 센스 기능
- Visual Studio
이용한 디버깅

좀더 상세히 알아 보도록 하겠습니다.


통합 개발 환경(IDE)
아마, 코난이의 포스트를 보시는 분들은 비주얼 스튜디오가 어떤건지 알고 계실거에요. 단순한 웹사이트 개발과 달리 엔터프라이즈 환경의 개발은 다양한 기술요소나 다양한 서비스와의 연계, 비즈니스 레이어 구축, SQL서버는 물론 다양한 이기종 DBMS와의 연계를 필요로 합니다. 통합 개발 환경의 필요성에 대해서는 이미 알고 계시리라 생각합니다.


인텔리 센스(IntelliSense)
WebMatrix 코드 하일라이팅(Code Highlighting) 제공하지만, 아쉽게도 인텔리센스 기능은 제공하지 않죠. Visual Studio 이용하실 경우 인텔리 센스 기능을 이용 가능한 장점이 있습니다.

image

요렇게 쩜과 함께 우리를 도와주는 인텔리 센스가 cshtml에서 동작합니다.


디버깅 기능 사용

WebMatrix
에서 Visual Studio 이용하시게 되는, 가장 중요한 이슈가 아닐까 예상합니다. 기존 ASP.NET 디버깅 경험을 그대로 이용 가능합니다. 말이 필요 없네요.

image

중단점(Break Point) 찍고 단계별로 추적이 가능합니다. 아래 샘플을 만들어 두었으니 도움 되시길 바랍니다.
그럼~ 저와 함께 설치하고 직접 이용해 보시죠
~


Visual Studio
이용한 ASP.NET Web Pages Razor 프로그래밍 - 설치

image

http://go.microsoft.com/fwlink/?LinkID=205867 경로에서  플랫폼 설치 관리자(WPI-Web Platform Installer) 설치합니다. 우측 “Add” 누르고 아래의 “Install”하시면 잠시 완료됩니다.(MVC 함께 정확히, 설치되는 Visual Studio Tool 이름은 “Microsoft ASP.NET Web Pages – Visual Studio 2010 Tools” 입니다.

image

Visual Studio에서 File – New – Web Site 실행합니다.(제가 영문판 이용 중이라쿨럭)

image

기본 프로젝트와 cshtml 나오죠. 그냥 F5 눌러서 실행하시면 cshtml – ASP.NET Web Pages Razor 실행되는게 보이실 겁니다.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
@ServerInfo.GetHtml()

    </body>
</html>

조금 코드를 볼까요? 내용을 지우고, 이렇게 ServerInfo 찍어 보시죠. 참고로, 여기에서 인텔리센스 기능을 맛보셔도 좋을 합니다.

image

인텔리 센스 기능 확인 가능

이제 기다려 보셨던 바로 기능! 디버깅을 진행해 보시죠.

@{
    var showToday = true;
    if(showToday)
    {
        @DateTime.UtcNow;
    }
    else
    {
        @DateTime.Now;
    }     
}

<h2>HTML 조합 반복문</h2>
@{
    <ul>
    @foreach (string item in Request.ServerVariables)
    {
        <li>@item</li>   
    }
    </ul>
}

이런 코드를 실행하겠습니다. 대충~ 맨위 if 구문에 중단점(Break Point) 찍으시고 F5 눌러 실행해 보시면?

image

걸렸죠? F11눌러서 Step Into 하시면 감동의 Razor 디버깅!!!

어떠세요? WebMatrix 이용한 Razor 개발 경험을 그대로 Visual Studio 가져간다!!! – 조금 감이 오시나요?

조금 앞으로 나가시면, ASP.NET MVC에서 Razor 구문을 그대로 이용해 개발도 가능해 진다는거!!!

한번 말씀 드리지만

WebMatrix 통해 개발하는 ASP.NET Web Pages 몇번 소개해 드린 것처럼, 자연스러운 상위 기술과의 연계와 개발에 대한 커리어 확장을 기본적인 Seamless 컨셉으로 녹이고 있습니다

- IIS 경우는 윈도우 서버의 IIS 웹서버로

- SQLCE SQL서버로 완전한 마이그레이션을

- WebMatrix ASP.NET Web Pages Razor Syntax Visual Studio ASP.NET MVC Razor

저와 함께 WebMatrix & Razor 개발이 어디까지 가게 될지 한번 같이 지켜 보시는건 어떨까요? ^_^
좋은 하루 되세요~

참고자료
ASP.NET Web Pages에서 MVC로의 자연스러운 - Helper MVC에서 사용해 보자
Razor WebMatrix 대해 후닥닥 적어본 FAQ Razor 벗겨먹기~
WebMatrix 단순 개발 도구가 아니라 스택(Stack)이다?

출처 : http://blogs.msdn.com/b/eva/archive/2010/12/14/visual-studio-asp-net-web-pages-razor.aspx
posted by Sunny's
2010. 11. 17. 09:19 ASP.NET
몇일 쉬었더니 엄청나게 많은 콘텐츠가 올라 왔습니다.
News+를 실시간으로 받아보고 싶으신 분들은 Twitter @winkey7을 지금 팔로우 해주세요
오늘은 ASP.NET MVC에 관한 정보가 많이 올라왔습니다. 
다음 호 부터는 좀 더 보시기 좋게 정리해서 올려 드리도록 하겠습니다.
그럼 링크 드립니다. ^^

SharePoint 2010 BrowserCapabilitiesPanel control

Learn 8pen via Silverlight Demo

WP7 Panorama: Smoothly fading the background (and enabling fading when changing, too)

JEANS

ASP.NET Ajax will not be left behind the HTML5 rush

MVC 3 RC Enhancements

Code Gallery Tools App

Microsoft Code Sample for developers

ASP.NET MVC 3: Server-Side Comments with Razor

In Honor of Silverlight NOT Dying….

ASP.NET MVC 3: Server-Side Comments with Razor

Using the Entity Framework to Reduce Network Latency to SQL Azure

Windows Azure Storage Client Library: CloudBlob.DownloadToFile() may not entirely overwrite file contents

Visual Studio improves Help Viewer for Visual Studio 2010 Service Pack 1

A few quick ASP.NET MVC 3 Installation Notes

A few quick ASP.NET MVC 3 Installation Notes

Razor Template in ASP.NET MVC 3

MVC's IgnoreRoute syntax

Thought Leaders in the Cloud: Talking with Jonathan Ellis, Co-Founder of Riptano

New Microsoft Whitepaper Outlines the Economics of Cloud Computing

Real World Windows Azure: Interview with Jeff Yoshimura, Head of Product Marketing, Zuora

2 of 10 - Make sure your buttons are visible, even when the keyboard is displayed.

Take advantage of Windows Summit 2010 to learn about IE9

Elsewhere on the Web

Denali and Juneau

My TechEd Europe 2010 Presentations

Join the TFS development team and help shape the ALM industry

Help improve MSDN – give them your feedback

Join the TFS development team and help shape the ALM industry

TFS2010: Update Activity Logging Cleanup Interval

Asynchrony in C# 5 Part Six: Whither async?

How Do I: Save Images to the Pictures Hub and Retrieve them back from the Hub in a Windows Phone 7 Application?

How do I: Use Push Notifications in a Windows Phone 7 Application?

WCF HTTP URL ACL Utility Scripts

Windows Server AppFabric DB Reset Powershell Script

Retention Policy for document library in SharePoint 2010

SEO Toolkit for SharePoint?

New Whitepaper Details the Windows Azure Programming Model

Breaking Change for Windows Azure Drive Beta in Guest OS 1.8 and 2.0

Breaking Change for Windows Azure Drive Beta in Guest OS 1.8 and 2.0

ASP.NET Web Application: Publish/Package Tokenizing Parameters

Introduction to jQuery for ASP.NET Developers

Announcing the ASP.NET MVC 3 Release Candidate

Windows Azure Diagnostics Viewer

Thought Leaders in the Cloud:  Talking with Charlton Barreto, Technology Strategist at Intel

Web Page Performance in a Standards Compliant and Interoperable way

Simple Semantics With Microformats, Part 4

TFS Integration Platform – New Migration templates for SfTS Team Project Process Template

Windows Azure Diagnostics Monitor


출처 : http://youngwook.com/tag/NEWS+
posted by Sunny's
prev 1 2 3 next