posted by 권오성의 Biomedical Engineering 2007. 10. 10. 11:25
사용자 삽입 이미지

입사 후 웹관련 분야에서 일하고 싶었는데 본의 아니게 임베디드 장비 개발회사로 취업하여 장비와 맞물린 개발업무를 하고 있습니다.
'C#은 웹 전문언어야~'라고 생각하고 있었는데 얼마전 VOIP, IPTV 개발회사를 방문해보니 의외로 C#으로 개발하고 있는 회사가 많다는걸 알게 되었습니다. 특히 젊은 사장의 경우 말입니다.
다시 한번 C#의 무궁무진한 개발분야를 염두해 두시라고 올려봅니다.
posted by 써니루루 2007. 7. 19. 02:38
간단히 .NET 2.0 C# Windows form 으로 개발한 적금 계산하는 프로그램입니다.

적금이 얼마나 될지 궁금한 일이 많은데 가끔씩 한번 찾아보게 되서 동료가 만든 프로그램을 올려봅니다.

짧은 시간에 짠거라 많은 기능은 기대하지 말아주세용;
posted by 써니루루 2007. 7. 17. 20:21

제곱근을 구하기 위해서는 다음과 같은 공식을 만족합니다.


x = root(a) 라면

x^2 = a 입니다.

따라서 x = a/x가 됩니다.

이에 의해서

임의의 x에 의해서 a의 제곱근 값은

x < root(a) < a/x 거나
a/x < root(a) <x 의 범위에 있게 됩니다.

따라서 a와 a/x의 평균값을 구하는

(a+b)/2 공식을 이용해 x = (x + a/x)/2 의 식을 이용하면

대부분의 수는 10번을 돌기 이전에 루트 값을 구할 수 있습니다.

간단하게 아래 C#으로 코딩해본 소스입니다.

using System;
using System.Collections.Generic;
using System.Text;

namespace Sqrt
{
    class SqrtMain
    {
        static double Sqrt(double aa, double xx)
        {
            try
            {
                for (int i = 0; i < 10; i++)
                    Console.WriteLine(xx = (xx + aa / xx) / 2);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return xx;
        }

        static void Main(string[] args)
        {
            Console.WriteLine(Sqrt(2341, 3));
        }
    }
}

posted by 써니루루 2007. 7. 16. 23:30
마방진 클래스다이어그램


오늘 1시간 시험으로 봤던 마방진 홀수 / 마방진 4의 배수 알고리즘을 이용한 마방진 소스

조금은 어렵지만 한번 분석해보시길 ^ ^

.NET 2.0 C# Console 응용 프로그램으로 제작했습니다.

사용 IDE는 Visual studio 2007 orcas


posted by 써니루루 2007. 7. 16. 17:35
11을 입력하면 1이 2개
그래서 12가 출력되고 다음은

1이 1개 2가 1개 이므로
1121이 출력되고

1이 2개 2가 1개 1이 1개 이므로
122111 이런식으로 증가되는 숫자 계산이 개미퀴즈이다.

이를 코딩으로 옮기는 작업..;
사용자 삽입 이미지


소스가 어렵지만;;

posted by 써니루루 2007. 7. 16. 16:30
클래스 다이어그램
예전에 짜본 야구게임 다시한번 짜봤다.

소스코드는 넘 쪼개놔서 압축해서 올렸으니 참고하시길..

Visual studio 2007 Orcas로 개발했으면 .NET Framework 2.0을 기준으로 제작했습니다.
posted by 써니루루 2007. 5. 27. 19:29
Gmail Form

Gmail Form


말은 상당히 거창하다 - _-;;

참고 주소는 http://aspalliance.com/867 요기를 보면되며..

사실 .NET을 해본  사람이라면 .NET에서 제공하는 SMTP메일 클라이언트를 이용해서 메일을 보내는 소스코드가 얼마나 간단히 나오는지 알 것이다.

이 예제도 마찬가지로 상당히 짧은 코드지만 Gmail의 SMTP를 이용해보려고 삽질(?)한 노력이 보일것이다;

하지만 결론부터 얘기하자면 실패했다는것 ㅠㅠ

Google Mail의 기본 SMTP 포트는 465로 되어있는 것을 확인했다.

하지만 메일이 전송되지 않길래 무슨문젤까 하고 google.com의 검색으로 외국을 긁어나가기 시작했다..

포트를 587로 바꾸라고? -_ -;;

바꿔서도 해봤다..

안된다 ㅠㅠ

누가 해결하신분은 도움을 주시길..

물론 gmail의 smtp를 안쓰고 로컬에 있는 iis의 smtp를 이용하면 간단히 해결되는 문제지만;;

목적이 gmail의 smtp를 훔쳐쓰는 것이기에 -ㅁ-;; ㅋㅋ

아래는 본인이 삽질(?)한 소스코드이다~

less..

 


Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Google Form Mailer</title>
</head>
<body>
    <form id="GMailForm" runat="server">
    <div>
   
    <table style="border-collapse:collapse;" width="400" cellpadding="5" cellspacing="0">
        <tr>
            <th colspan="2">
            Google Form mail
            </th>
        </tr>
        <tr>
            <td style="width: 150px; text-align: right">
                E-mail to :
           
            </td>
            <td>
                <asp:TextBox ID="txtMailTo" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td style="width: 150px; text-align: right">
                Subject :</td>
            <td>
                <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td>
        </tr>
        <tr>
            <td style="width: 150px; text-align: right">
                Contents :
            </td>
            <td>
                <asp:TextBox ID="txtContents" runat="server" Rows="5" TextMode="MultiLine"></asp:TextBox></td>
        </tr>
        <tr>
            <td align="center" colspan="2">
                <asp:Button ID="btnMailSend" runat="server" OnClick="btnMailSend_Click" Text="Send mail" /></td>
        </tr>
    </table>
   
    </div>
    </form>
</body>
</html>




Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Net;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
    /// <summary>
    /// E-mail Message class
    /// </summary>
    private MailMessage Mail = null;

    /// <summary>
    /// Network base authentication
    /// </summary>
    private NetworkCredential AuthInfo = null;

    /// <summary>
    /// SMTP Mail Sender
    /// </summary>
    private SmtpClient Smtp = null;

    /// <summary>
    /// Email address
    /// </summary>
    private string sMailFrom = "";

    /// <summary>
    /// smtp login id
    /// </summary>
    private string sLoginID = "";

    /// <summary>
    /// smtp login password
    /// </summary>
    private string sLoginPass = "";

    /// <summary>
    /// Default Page load script
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        sMailFrom = "sunyruru@gmail.com";
        sLoginID = "sunyruru";
        sLoginPass = "****";
    }

    /// <summary>
    /// Mail Send button event script
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnMailSend_Click(object sender, EventArgs e)
    {
        // Email message set
        Mail = new MailMessage(sMailFrom, txtMailTo.Text.Trim());
        Mail.Subject = txtSubject.Text;
        Mail.Body = txtContents.Text;


        // Authentication to SMTP Service
        AuthInfo = new NetworkCredential(sLoginID.Trim() + "@gmail.com", sLoginPass.Trim());

        // SMTP Sender
        Smtp = new SmtpClient();

        try
        {
            Smtp.Host = "smtp.google.com"; // SMTP Host
            Smtp.Port = 465; // SMTP Port
            Smtp.UseDefaultCredentials = false;
            Smtp.Credentials = AuthInfo;
            Smtp.EnableSsl = true; // Use SSL Secure connection

            Smtp.Send(Mail); // Send email message
        }
        catch (System.Net.Mail.SmtpFailedRecipientsException ex) { PrintError(ex.Message); }
        catch (System.Net.Mail.SmtpException ex) { PrintError(ex.Message); }
        catch (ObjectDisposedException ex) { PrintError(ex.Message); }
        catch (InvalidOperationException ex) { PrintError(ex.Message); }
        catch (ArgumentNullException ex) { PrintError(ex.Message); }
        catch (ArgumentOutOfRangeException ex) { PrintError(ex.Message); }
        catch (ArgumentException ex) { PrintError(ex.Message); }
        catch (Exception ex) { PrintError(ex.Message); }
    }

    /// <summary>
    /// Javascript error message popup
    /// </summary>
    /// <param name="ErrorMessage"></param>
    protected void PrintError(string ErrorMessage)
    {
        Response.Write("<script>\n");
        Response.Write("alert('" + ErrorMessage + "')");
        Response.Write("</script>\n");
    }
}



less..


귀차니즘이 있으시다면...

아래 압축파일로 ;;

RURU_test_Mail_GmailSmtp.zip

ASP.NET 웹페이지

posted by 써니루루 2007. 5. 22. 23:17
        Response.Cache.SetExpires(DateTime.Now.AddSeconds(0));
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetValidUntilExpires(true);
        Response.Cache.SetNoServerCaching();

브라우져의 페이지가 자주 바뀌는 페이지는 브라우져 캐쉬를 무효화 해야할 경우가 생긴다.

이런 때에는 Page_Load 부분에 위와 같은 구문을 넣어보자..

posted by 써니루루 2007. 5. 16. 16:05

<%@ Control Language="C#" ClassName="postImage" %>
<%@ Import Namespace="System.IO" %>


<script runat="server">

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile == true)
        {
            string upDir = Server.MapPath(".") + "\\upload\\";
           
            DirectoryInfo di = new DirectoryInfo(upDir);
            if (di.Exists == false)
                di.Create();

            string fName = FileUpload1.FileName;
            string fFullName = upDir + fName;
            FileInfo fInfo = new FileInfo(fFullName);

            if (fInfo.Exists == true)
            {
                int findex = 0;
                string fExt = fInfo.Extension;
                string fRealName = fName.Replace(fExt, "");

                string newFileName = "";
                do
                {
                    findex++;
                    newFileName = fRealName + "_" + findex.ToString() + fExt;
                    fInfo = new FileInfo(upDir + newFileName);
                } while (fInfo.Exists);

                fFullName = upDir + newFileName;
                fName = newFileName;
            }

            FileUpload1.PostedFile.SaveAs(fFullName);
            fInfo = new FileInfo(fFullName);

            Panel1.Visible = true;
            lblMessage.Text = "업로드 된 파일 : " + fFullName + "\n<br />";
            /*lblMessage.Text += "업로드 사이즈 : "
                + Convert.ToString(int.Parse(Convert.ToString(float.Parse(fInfo.Length.ToString()) / 1024.0f)))
                + "KB";*/
            Image1.ImageUrl = "../upload/" + fName;
            HiddenField1.Value = "upload/" + fName;
        }
        else
        {
            Panel1.Visible = true;
            lblMessage.Text = "업로드 할 파일이 존재하지 않습니다.";
        }
    }

</script>


<div class="titleText">이미지를 등록해주세요</div>
<br />
<div class="noticeText">* 이미지는 명함, 반명함 사진으로 확장자는<br /> gif, jpg, png 등으로만 올려주시기 바랍니다.</div>
<br />
<div id="fileImage">
    <asp:FileUpload ID="FileUpload1" runat="server" Width="200px" />&nbsp;<br />
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="사진 파일 올리기" /><br />
</div>
<p></p>
<asp:Panel ID="Panel1" runat="server" Height="50px" Width="298px" Visible="False">
    <asp:Label ID="lblMessage" runat="server"></asp:Label><br />
    <asp:Image ID="Image1" runat="server" Width="130" /><br /><br />
    </asp:Panel>
<asp:HiddenField ID="HiddenField1" runat="server" />


간단하게 만들었던 이미지 업로드 컨트롤 *.ascx 파일로 만들어두면 편하다.

참 급조로 만든거라 상당히 부실한 -_ -;;;

요래 코딩하면 안되는뎅;;

반성 반성~


만약에 업로드하는 부분만 메소드로 뺀다면 ...

    /// <summary>
    /// 이미지를 업로드 한 후 저장된 파일 경로를 반환한다.
    /// </summary>
    /// <param name="FileUp">업로드 컨트롤</param>
    /// <param name="SubCode">과목코드</param>
    /// <returns></returns>
    protected string ImageUpload(FileUpload FileUp, int SubCode)
    {
        string ret = "";        // 반환할 문자열
        string upDir = "";      // 업로드할 파일 저장 위치
        string fName = "";      // 업로드된 실제 파일명
        string fFullName = "";  // 저장할 파일의 풀 경로
        string fExt = "";       // 파일의 확장자명
        string fRealName = "";  // 파일의 확장자를 뺀 실제 파일명
        string newFileName = "";// 새로 만들어질 파일명

        int findex = 0; // 파일의 인덱스번호
       
       
        System.IO.DirectoryInfo di = null;
        System.IO.FileInfo fInfo = null;
       
        // 파일이 있나?
        if (FileUp.HasFile == true)
        {
            // 저장할 경로
            upDir = Server.MapPath("..") + "\\upload\\exam\\" + SubCode.ToString();
           
            // 경로에 디렉토리가 없으면 만든다.
            di = new System.IO.DirectoryInfo(upDir); // 디렉토리를 다룰 연장
            if (di.Exists == false)
                di.Create();

            // 업로드 된 파일을 가지고 저장할 파일의 풀 경로를 만들어낸다.
            fName = fileup.FileName;
            fFullName = upDir + fName;
            fInfo = new System.IO.FileInfo(fFullName); // 파일을 다룰 연장

            // 이미 해당하는 파일이 있으면
            if (fInfo.Exists == true)
            {
                fExt = fInfo.Extension;
                fRealName = fName.Replace(fExt, "");

                // 루프를 돌면서 실제 저장될 파일명을 결정한다.
                do
                {
                    findex++;
                    newFileName = fRealName + "_" + findex.ToString() + fExt;
                    fInfo = new System.IO.FileInfo(upDir + newFileName);
                } while (fInfo.Exists);

                fFullName = upDir + newFileName;
                fName = newFileName;
            }

            FileUp.PostedFile.SaveAs(fFullName);
            fInfo = new System.IO.FileInfo(fFullName);

            ret = "../upload/" + fName;
        }
       
        return ret;
    }

posted by 써니루루 2007. 3. 28. 12:53

.NET Remoting이란?

  • RPC(Remote Procedure Call)

    • 클라이언트가 원격지에 존재하는 함수를 호출한 후, 그 결과를 원격지로부터 받아내는 기술
  • 리모팅(Remotion)
    • 리모팅은 서비스 개념을 포함한다
    • 원격 서버가 클라이언트에게 서비스(Service)를 제공한다.
  • 닷넷 리모팅에서 소개되는 기술
    • 원격 객체(Remote Object)
    • 원격 객체를 대신하는 클라이언트 프록시 객체(Proxy Object)
    • 마샬링(Marshaling), 언마샬링(Unmarshaling)
    • 직렬화(Serialization), 역직렬화(Deserialization)
    • 네트워크 통신을 위한 체널(Channel)
    • 네트워크로 전송되는 데이터를 인코딩하는 포멧터(Formatter)

.NET Remoting의 구성요소

  • 서버원격 시스템의 구성
    • 원격 클래스와 원격 객체
    • 채널(Channel)
    • 포멧터(Formatter)
      • 데이터를 해석하기 편리하고 전송하기 좋은 형식으로 인코딩 또는 디코딩해야 하는데 이 역할을 담당하는 것이 포멧터이다.
  • .NET Remoting에서 제공해주는 포멧터
    • 포멧터(SoapFormatter)
      • 데이터를 XML 형식의 SOAP 방식으로 인코딩
    • Binary 포멧터(BinaryFormatter)
      • 말그대로 Binary 형식으로 인코딩하기 때문에 인코딩 속도면에서 효율적이지만, 이기종간의 통신 포멧인 SOAP을 이용하는 것이 좋다.
  • 클라이언트 원격 시스템의 구성 요소
    • 프록시 객체(Proxy Object)
      • 원격 시스템에서 클라이언트와 서버 사이를 넘나드는 참조값
    • 채널(Channel)
      • 클라이언트와 원격 서버와 통신하기 위해 존재
    • 포멧터(Formatter)
  • .NET Remoting에서 지원하는 채널의 종류
    • HTTP 채널(HttpChannel)
    • TCP 채널(TcpChannel)
원격 시스템의 구조

원격 시스템의 구조 다이어그램




.NET Remoting의 가장 간단한 예(서버)

  • 원격 서버 프로그램 작성 과정
    • 원격 클래스 작성
    • 원격 서버 프로그램 작성
    • 클라이언트 프로그램 작성
  • 원격 클래스 작성
    • 일단 클래스와 동일하지만 MarshalByRefObject 를 상속받는 것만 다르다

예제 : 원격 클래스 Server/Hello.cs

/**

서비스할 원격 클래스

**/

using System;

public class Hello : MarshalByRefObject

{

public Hello()

{

Console.WriteLine("Hello 생성자 호출");

}

public String SayHello(String name)

{

Console.WriteLine("Hello의 SayHello() 메서드 호출, 매개변수:{0}", name);

return "안녕하세요! [" + name + "] 님";

}

~Hello()

{

Console.WriteLine("Hello 소멸자 호출");

}

}

/***

c:csharpchap14ex01Server> csc /target:library /out:Hello.dll Hello.cs

***/



예제 : 리모트 서버 /Server/HelloServer.cs

/**

원격 클래스를 서비스하는 간단한 서버 프로그램

**/

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

public class HelloServer

{

public static void Main()

{

TcpChannel channel = new TcpChannel(9009);

ChannelServices.RegisterChannel(channel, false);

RemotingConfiguration.RegisterWellKnownServiceType(

Type.GetType("Hello, Hello"),

"BaboHello",

WellKnownObjectMode.SingleCall);

System.Console.WriteLine("서버를 멈추려면 Enter를 누르세요!");

System.Console.ReadLine();

}

}

/***

c:csharpchap14ex01Server> csc /r:Hello.dll HelloServer.cs

c:csharpchap14ex01Server> HelloServer

서버를 멈추려면 Enter를 누르세요!

[참고] .NET Framework 1.0과 1.1에서는 ChannelServices.RegisterChannel(channel)과 같은 방식으로 사용하였다. 하지만 채널만을 입력받는 이 함수는 2.0에서 Obsolete되었다.

이 함수대신 ChannelServices.RegisterChannel(channel, false)와 같이 사용해야 한다. 첫번째 매개변수는 이전과 같이 채널이며 두번째 매개변수는 보안설정이 있는지 없는지를 나타낸다.

***/





예: 원격 클라이언트 Client/HelloClient.cs

/**

원격 서비스를 이용하는 간단한 클라이언트 프로그램

**/

using System;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Tcp;

public class HelloClient

{

public static int Main(string[] args)

{

TcpChannel channel = new TcpChannel();

ChannelServices.RegisterChannel(channel, false);

object obj = Activator.GetObject(typeof(Hello),

"tcp://localhost:9009/BaboHello");

Hello h = (Hello)obj;

Console.WriteLine(h.SayHello("홍길동"));

return 0;

}

}

/***

1. 원격 클라이언트 실행

c:csharpchap14ex01Client> csc /r:Hello.dll HelloClient.cs

c:csharpchap14ex01Client> HelloClient

안녕하세요! [홍길동] 님

c:csharpchap14ex01Client> HelloClient

안녕하세요! [홍길동] 님

2. 원격 서버 프로그램 (클라이언트 접속후)

c:csharpchap14ex01Server> HelloServer

서버를 멈추려면 Enter를 누르세요!

Hello 생성자 호출

Hello의 SayHello() 메서드 호출, 매개변수:홍길동

Hello 생성자 호출

Hello의 SayHello() 메서드 호출, 매개변수:홍길동

3. 원격 서버 프로그램이 종료했을 때

c:csharpchap14ex01Server> HelloServer

서버를 멈추려면 Enter를 누르세요!

Hello 생성자 호출

Hello의 SayHello() 메서드 호출, 매개변수:홍길동

Hello 생성자 호출

Hello의 SayHello() 메서드 호출, 매개변수:홍길동

Hello 소멸자 호출

Hello 소멸자 호출

[참고]

클라이언트 프로그램을 컴파일하고 실행하기 위해서는 서버의 Hello.dll이 필요하다. 여기서는 여러분이 수동으로 클라이언트의 디렉토리에 복사해주어야 한다.

***/




예제를 사용하는 법 :

1. Hello 원격 클래스를 먼저 컴파일해서 dll 파일로 만든다.
2. 리모트 서비스를 작성해서 띄워놓는다.
3. 리모트 클라이언트를 띄워서 리모트 서비스측에 원격 객체가 생성되는지 확인한다.