실습 : 방명록

2009. 12. 16. 20:44

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.



- 사용자의 로컬 파일 선택 가능
- Stream 클래스를 통해서 응용 프로그램에서 사용 가능
- 다중 파일 선택 및 확장자 제한 가능
- 주 사용분야 :
    - 파일업로드 : WebClient 또는 HttpWebRequest 사용
    - 로컬 이미지 보기 : <Image /> 사용
    - 로컬 미디어 실행 : <MediaElement /> 사용







"파일 업로드" 실습을 하기 위하여 아래그림과 같이 '솔루션 탐색기'에서 "Files"라는 이름의 '새 폴더'를 추가한다. 그리고 아래그림과 같이 '새 항목 추가'로 "FileUploadHandler.ashx"라는 이름으로 '제네릭 처리기'형식의 파일을 하나 추가한다.


















[MainPage.xaml]


<UserControl x:Class="RiaOpenFileDialog.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"

    d:DesignHeight="300" d:DesignWidth="400">

 

    <Grid x:Name="LayoutRoot" Background="White">

        <Button x:Name="btnFileUpload" Content="파일 업로드" Width="100" Height="30" />

    </Grid>

</UserControl>

 

 








[MainPage.xaml.cs]


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.IO;

 

namespace RiaOpenFileDialog

{

    public partial class MainPage : UserControl

    {

        public MainPage()

        {

            InitializeComponent();

            btnFileUpload.Click += new RoutedEventHandler(btnFileUpload_Click);

        }

 

        void btnFileUpload_Click(object sender, RoutedEventArgs e)

        {

            OpenFileDialog ofd = new OpenFileDialog(); // 파일 선택

            ofd.Filter = "모든 파일|*.*";

            ofd.Multiselect = false;

 

            bool? r = ofd.ShowDialog();

            if (r.HasValue && r == true)

            {

                this.btnFileUpload.IsEnabled = false; // 업로드되는 동안 비활성화

                UriBuilder url = new UriBuilder("http://localhost:2654/FileUploadHandler.ashx");

                url.Query = string.Format("FileName={0}", ofd.File.Name);

 

                Stream stream = ofd.File.OpenRead(); // 파일을 스트림 개체로 읽어서,

                WebClient client = new WebClient(); // 원격지 서버로 데이터 전송

 

                client.OpenWriteCompleted += delegate(object ss, OpenWriteCompletedEventArgs ee)

                {

                    byte[] buffer = new byte[4096]; // 4096 바이트 단위로 서버로 전송(제네릭 처리기)

                    int len = stream.Read(buffer, 0, buffer.Length);

 

                    while (len > 0)

                    {

                        ee.Result.Write(buffer, 0, len);

 

                        len = stream.Read(buffer, 0, buffer.Length);

                    }

                    ee.Result.Close();

                    stream.Close();

                    this.btnFileUpload.IsEnabled = true; // 활성화

                }; // end OpenWriteCompleted

 

                client.OpenWriteAsync(url.Uri); // 업로드 진행

            } // end if

        } // end Click

    }

}

 

 









[FileUploadHandler.ashx.cs]


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.IO;

 

namespace RiaOpenFileDialog.Web

{

    /// <summary>

    /// Summary description for FileUploadHandler

    /// </summary>

    public class FileUploadHandler : IHttpHandler

    {

 

        public void ProcessRequest(HttpContext context)

        {

            string strFileName = context.Request.QueryString["FileName"]; // 실버라이트에서 넘겨줄 이름

            string strDir = String.Format("{0}/{1}", context.Server.MapPath("~/Files"), strFileName); // 경로

            // 4096바이트 단위로 끊어서 저장

            using (FileStream fs = File.Create(strDir))

            {

                byte[] buffer = new byte[4096];

                int len = context.Request.InputStream.Read(buffer, 0, buffer.Length);

 

                while (len > 0)

                {

                    fs.Write(buffer, 0, len); // 버퍼에 담긴 값을 해당 경로에 저장

                    len = context.Request.InputStream.Read(buffer, 0, buffer.Length);

                }

            }

        }

 

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}

 










[실행결과]


















아래그림과 같이 "솔루션 탐색기"에서 "모든 파일 표시"버튼을 마우스로 클릭해보면(새로 고침 버튼도 클릭) 아래와 같이 해당 파일이 업로드 된 것을 확인할 수 있다.












Posted by holland14
:




- 웹브라우저 쿠키와 비슷하게 실버라이트에서 사용하는 사용자 컴퓨터에 저장되는 임시 데이터 저장 공간

- 1~50MB 정도의 공간을 사용 가능
    - 사용자의 허락하에 50MB 사용 가능

- 실버라이트 응용 프로그램의 간단한 상태 관리를 위해서 주로 사용

- 실버라이트에서는 '세션', '쿠키'를 사용할 수 없다.








[MainPage.xaml]


<UserControl x:Class="RiaIsolatedStorage.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"

    d:DesignHeight="300" d:DesignWidth="400">

 

    <Grid x:Name="LayoutRoot" Background="White">

        <StackPanel Orientation="Horizontal">

            <TextBlock Text="마지막 방문 시간 : " />

            <TextBlock x:Name="lblLastVisit" />

        </StackPanel>

        <StackPanel>

            <Button x:Name="btnAddSpace" Content="저장 공간 늘리기" />

        </StackPanel>

    </Grid>

</UserControl>

 

 








[MainPage.xaml.cs]


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.IO.IsolatedStorage;

 

namespace RiaIsolatedStorage

{

    public partial class MainPage : UserControl

    {

        public MainPage()

        {

            InitializeComponent();

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);

            btnAddSpace.Click += new RoutedEventHandler(btnAddSpace_Click);

        }

        void btnAddSpace_Click(object sender, RoutedEventArgs e)

        {

            // 저장 공간 늘리기

            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication(); // 현재 공간 가져오기

            MessageBox.Show("현재 : " + isf.AvailableFreeSpace.ToString()); // 현재값 출력

            long newSize = isf.AvailableFreeSpace + 1048576;

            isf.IncreaseQuotaTo(newSize);

        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)

        {

            // 마지막 방문 정보가 격리 저장소에 들어있으면 출력, 새롭게 등록

            IsolatedStorageSettings iss = IsolatedStorageSettings.ApplicationSettings;

            if (iss.Contains("keyLast"))

            {

                lblLastVisit.Text = iss["keyLast"].ToString(); // 이전에 기록된 출력

                SetLastVisit(iss);

            }

            else

            {

                SetLastVisit(iss); // 처음 방문 또는 이전 방문 정보가 제거되었다면...

            }

        }

        private static void SetLastVisit(IsolatedStorageSettings iss)

        {

            iss["keyLast"] = DateTime.Now; // 현재시간으로 재설정

        }

    }

}

 

 


















Posted by holland14
:




아래 그림과 같이 '솔루션 탐색기'에서 '새 항목 추가'를 하여 "Silverlight Child Window"형식의 파일을 하나 추가한다.(파일명은 기본값으로 한다.)
















[MainPage.xaml]


<UserControl x:Class="RiaChildWindow.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"

    d:DesignHeight="300" d:DesignWidth="400">

 

    <Grid x:Name="LayoutRoot" Background="White">

        <StackPanel>

            <Button x:Name="btnOpen" Content="ChildWindow 열기" />

            <Button x:Name="btnCode" Content="코드기반으로 자식창 열기" />

        </StackPanel>

    </Grid>

</UserControl>

 

 








[MainPage.xaml.cs]


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

 

namespace RiaChildWindow

{

    public partial class MainPage : UserControl

    {

        public MainPage()

        {

            InitializeComponent();

            btnOpen.Click += new RoutedEventHandler(btnOpen_Click);

            btnCode.Click += new RoutedEventHandler(btnCode_Click);

        }

 

        void btnCode_Click(object sender, RoutedEventArgs e)

        {

            ChildWindow cw = new ChildWindow();

            Button btn = new Button();

            btn.Content = "버튼";

            btn.Width = 100; btn.Height = 100;

            cw.Content = btn; cw.Title = " 버튼 출력";

            cw.Show();

        }

 

        void btnOpen_Click(object sender, RoutedEventArgs e)

        {

            // ChildWindow 열기

            ChildWindow1 cw1 = new ChildWindow1();

            cw1.Show();

            // 무명 메서드 => 람다식

            cw1.Closed += (ss, ee) =>

            {

                bool? r = cw1.DialogResult;

                if (r != null)

                {

                    if (Convert.ToBoolean(r))

                    {

                        MessageBox.Show("확인을 클릭");

                    }

                    else

                    {

                        MessageBox.Show("취소를 클릭");

                    }

                }

            };

        }

    }

}

 

 








[ChildWindow1.xaml]


<controls:ChildWindow x:Class="RiaChildWindow.ChildWindow1"

           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

           xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"

           Width="400" Height="300"

           Title="ChildWindow1">

    <Grid x:Name="LayoutRoot" Margin="2">

        <Grid.RowDefinitions>

            <RowDefinition />

            <RowDefinition Height="Auto" />

        </Grid.RowDefinitions>

 

        <Button x:Name="CancelButton" Content="취소" Click="CancelButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,0,0" Grid.Row="1" />

        <Button x:Name="OKButton" Content="확인" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,79,0" Grid.Row="1" />

 

    </Grid>

</controls:ChildWindow>

 
























Posted by holland14
:



Popup 컨트롤 - 팝업창을 띄울 수 있는 영역 제공





아래 그림과 같이 '솔루션 탐색기'에서 "이미지파일"인 "img0"파일을 붙여넣는다.











[MainPage.xaml]


<UserControl x:Class="RiaPopup.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"

    d:DesignHeight="300" d:DesignWidth="400">

 

    <Grid x:Name="LayoutRoot" Background="White">

        <StackPanel>

            <Button x:Name="btnAdd" Content="방명록 글쓰기(팝업창 열기)" />

            <Button x:Name="btnCode" Content="코드기반으로 팝업창 열기" />

        </StackPanel>

 

        <Popup x:Name="myPopup" IsOpen="False" HorizontalOffset="20" VerticalOffset="20">

            <Border BorderBrush="Red" BorderThickness="2" Width="320" Height="240">

                <StackPanel>

                    <TextBlock Text="이름 : " />

                    <TextBlock Text="내용 : " />

                    <Button x:Name="btnClose" Content="팝업창 닫기" />

                </StackPanel>

            </Border>

        </Popup>

    </Grid>

</UserControl>

 

 







[MainPage.xaml.cs]


using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Windows.Controls.Primitives;

using System.Windows.Media.Imaging;

 

namespace RiaPopup

{

    public partial class MainPage : UserControl

    {

        public MainPage()

        {

            InitializeComponent();

            btnAdd.Click += new RoutedEventHandler(btnAdd_Click);

            btnClose.Click += new RoutedEventHandler(btnClose_Click);

            btnCode.Click += new RoutedEventHandler(btnCode_Click);

        }

               

        void btnCode_Click(object sender, RoutedEventArgs e)

        {

            Popup p = new Popup();

            Image i = new Image();

            i.Source = new BitmapImage(new Uri("img0.jpg", UriKind.Relative));

            i.Width = 320;

            i.Height = 240;

            //i.MouseLeftButtonDown += new MouseButtonEventHandler(i_MouseLeftButtonDown);

            i.MouseLeftButtonDown += delegate(object ss, MouseButtonEventArgs ee) { p.IsOpen = false; };

            p.Child = i; // 이미지 등록

            p.IsOpen = true; // 오픈

        }

 

        //void i_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)

        //{

        //    p.IsOpen = false;

        //}

 

        void btnClose_Click(object sender, RoutedEventArgs e)

        {

            this.myPopup.IsOpen = false; // 닫기

        }

 

        void btnAdd_Click(object sender, RoutedEventArgs e)

        {

            this.myPopup.IsOpen = true; // 열기

        }

    }

}

 

 



















Posted by holland14
:


Microsoft의 무료 실버라이트 배포 공간

- http://silverlight.live.com/
    - 라이브계정(핫메일계정/MSN패스포트계정)으로 위 URL에 로그인
- Manage Applications
    - 클릭 후 XAP 파일 업로드
- Configure this Application:
    - 설정 사항 편집
- Add this Application to a Web Page:
    - <iframe /> 영역을 카피 후 블로그/홈페이지에 인클루드









Posted by holland14
:



IIS 웹 서버에 MIME 타입 추가하기

- IIS 6.0에는 아래 3개의 MIME 타입을 추가해야 함
    - .xaml
        - application/xaml + xml

    - .xap
        - application/x-silverlight-app

    - .xbap
        - application/x-ms-xbap





- 배포시 해당파일이 DB와 연결되어 있지 않다면 "***TestPage.html"파일, "Silverlight.js"파일, "ClientBin폴더"파일 3개만 올리면(업로드하면) 된다.


- 해당 웹사이트의  '속성' ->  'HTTP헤더' -> "MIME형식"에  위의 3개(.xaml/.xap/.xbap)의 타입이 등록되어 있어야만 클라이언트 측에서 실행이 된다.(등록이 되어있지 않다면 "MIME형식"에 위의 3개(.xaml/.xap/.xbap)의 타입을 추가해줘야 실행된다.)







로컬에서 완성된 버전을 원격으로

- 배포 순서
    - 로컬 프로젝트 완성
        - RiaMemo
    - FTP를 통한 웹 사이트 소스 배포
        - http://silverlight.redplus.net/RiaMemo/
    - ASP.NET 웹 사이트 설정
        - ASP.NET 2.0 웹 공유(가상 디렉터리 설정)
    - 실행 후 테스트





- "웹서비스"와 "WCF"를 통해 만들어진 DB가 연동되어 있는 파일을 배포하려면(DB 입/출력을 해주려면...), 해당 파일의 '속성'으로 들어가서 '웹 공유'를 걸어줘야 한다.(ASP.NET 2.0 버전으로 걸어줘야 한다.) 이 외에도 해당 파일(의 DB)을 만들었던 "SQL Server"의 버전이 다르거나, 해당 파일의 "Web.config"파일의 버전이 다를 경우(예를 들어, 해당파일은 .NET Framework 4.0버전으로 만들어졌지만, 사용자측은 .NET Framework 4.0버전이 안깔려있을 경우)로 인해 해당파일이 실행(DB입/출력)되지 않을 경우 같은 버전의 "SQL Server"와 ".NET Framework"을 깔아주면 실행된다.(아직까지는 파일을 만들때는 .NET Framework 3.5로 만들어줘라!)










Posted by holland14
:

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

Silverlight에 WCF연동

2009. 12. 14. 12:17

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.

Silverlight에 WebService연동

2009. 12. 11. 13:27

보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.