일단 아래의 처럼 네이버 메일 > 환경설정 SMTP 에서 사용함으로 바꿧다는 가정하에

아래의 간단한 코드에 메일이 안가는 경우가 있음 그것은 바로 

중국에서 하도 털어서 2단계 인증 해놨는데...

네이버 2단계 인증 이거 하면 안감!  이거 해지해야함

            MailMessage sendMail = new MailMessage();           // System.Net.Mail
            sendMail.From = new MailAddress("보내는사람@naver.com");        // 보내는 사람
            sendMail.To.Add(new MailAddress("받는사람@naver.com"));       // 받는 사람
            sendMail.Subject = message.Subject;                   // 메일 제목
            sendMail.SubjectEncoding = System.Text.Encoding.UTF8;
            sendMail.Body = message.Body;
            sendMail.BodyEncoding = System.Text.Encoding.UTF8;

            SmtpClient client = new SmtpClient("smtp.naver.com" , 587);
            client.UseDefaultCredentials = true;
            client.EnableSsl = true;
            //client.Timeout = 10000;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential("네이버아이디", "비밀번호");
            client.Send(sendMail);

System.Net.Mail.SmtpException

  메시지=The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 

 

 

웹클라이언트로 데이터서비스 파일업로드 하기

 

버튼클릭시 작동되는 모습 비동기로 업로드하고 있다.

        private void button1_Click(object sender, RoutedEventArgs e)
        {

            var urlString = "http://localhost:51059/WcfDataService1.svc/UploadFile";
            
            var webClient = new WebClient();  

            Debug.WriteLine("업로드 시작");
            webClient.UploadFileAsync(new Uri(urlString) , "POST", @"C:\temp\2pm.mp3");
            webClient.UploadProgressChanged += new UploadProgressChangedEventHandler(webClient_UploadProgressChanged);
            webClient.UploadFileCompleted +=new UploadFileCompletedEventHandler(webClient_UploadFileCompleted);      

        }

UploadProgressChanged는 상태바 표시를 위해 값을 반영하고 있다.

UploadFileCompleted 는 완료되고 나서 작업을 수행 할 수 있다.

        void webClient_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
        {
            // Displays the operation identifier, and the transfer progress.
            Console.WriteLine("{0}    uploaded {1} of {2} bytes. {3} % complete...",
                (string)e.UserState,
                e.BytesSent,
                e.TotalBytesToSend,
                e.ProgressPercentage);
            progressBar1.Value = e.ProgressPercentage;

        }

        void webClient_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
        {            
            
            MessageBox.Show("완료");
        }

 

지금부터는 서버측 DataService 임

소스는 간단하니 보면 다 압니다.

namespace WebApplication1
{
    public class WcfDataService1 : DataService<커스텀Entities>
    {
        // 이 메서드는 서비스 전반적인 정책을 초기화하는 데 한 번만 호출됩니다.
        public static void InitializeService(DataServiceConfiguration config)
        {
            // TODO: 규칙을 설정하여 어떤 엔터티 집합과 서비스 작업을 표시할 수 있고 업데이트할 수 있는지 등을 표시합니다.
            // 예제:
            config.SetEntitySetAccessRule("*", EntitySetRights.All);

            //WebInvoke, WebGet 따로 권한설정
            config.SetServiceOperationAccessRule("ContactidTest", ServiceOperationRights.AllRead); 
            config.SetServiceOperationAccessRule("UploadFile", ServiceOperationRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }

        [WebInvoke]
        public void UploadFile()
        {
            if (HttpContext.Current != null)
            {
                var request = HttpContext.Current.Request;

                for (int i = 0; i < request.Files.Count; i++)
                {
                    var file = request.Files[i];
                    var inputValues = new byte[file.ContentLength];

                    using (var requestStream = file.InputStream)
                    {
                        requestStream.Read(inputValues, 0, file.ContentLength);
                    }

                    File.WriteAllBytes(@"c:\temp\server\" + file.FileName, inputValues);
                 }
            }
        } 
    }
}

4메가 이상 또 안올라간다.! 딱 봐도 설정문제임

넉넉하게 줬다.

<httpRuntime  maxRequestLength="302100" ></httpRuntime>

 

그래도 안올라감! 데이터서비스의 바인딩값을 높였다. 잘됨

<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  <services>
    <service name="WebApplication1.WcfDataService1">
      <endpoint binding="webHttpBinding" bindingConfiguration="higherMessageSize" contract="System.Data.Services.IRequestHandler">
      </endpoint>
    </service>  
  </services>
  <bindings>
    <webHttpBinding>
      <binding name="higherMessageSize" openTimeout="00:10:00" maxBufferSize="65536" maxBufferPoolSize="65536" maxReceivedMessageSize="500000000" transferMode="Streamed">
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
      </binding>
      <binding name="NewBinding0" />
    </webHttpBinding>
  </bindings>
</system.serviceModel>

Control..::.Invoke 메서드

method
형식: System..::.Delegate

args 매개 변수에 있는 매개 변수의 수 및 형식과 동일한 매개 변수를 갖는 메서드의 대리자입니다.

args
형식: array<System..::.Object>[]()[]

지정된 메서드에 인수로 전달하는 개체의 배열입니다. 메서드가 인수를 사용하지 않으면 이 매개 변수는 nullNothingnullptrNull 참조(Visual Basic의 경우 Nothing)이 될 수 있습니다.

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;

   public class MyFormControl : Form
   {
      public delegate void AddListItem(String myString);
      public AddListItem myDelegate;
      private Button myButton;
      private Thread myThread;
      private ListBox myListBox;
      public MyFormControl()
      {
         myButton = new Button();
         myListBox = new ListBox();
         myButton.Location = new Point(72, 160);
         myButton.Size = new Size(152, 32);
         myButton.TabIndex = 1;
         myButton.Text = "Add items in list box";
         myButton.Click += new EventHandler(Button_Click);
         myListBox.Location = new Point(48, 32);
         myListBox.Name = "myListBox";
         myListBox.Size = new Size(200, 95);
         myListBox.TabIndex = 2;
         ClientSize = new Size(292, 273);
         Controls.AddRange(new Control[] {myListBox,myButton});
         Text = " 'Control_Invoke' example ";
         myDelegate = new AddListItem(AddListItemMethod);
      }
      static void Main()
      {
         MyFormControl myForm = new MyFormControl();
         myForm.ShowDialog();
      }
      public void AddListItemMethod(String myString)
      {
            myListBox.Items.Add(myString);
      }
      private void Button_Click(object sender, EventArgs e)
      {
         myThread = new Thread(new ThreadStart(ThreadFunction));
         myThread.Start();
      }
      private void ThreadFunction()
      {
         MyThreadClass myThreadClassObject  = new MyThreadClass(this);
         myThreadClassObject.Run();
      }
   }
   public class MyThreadClass
   {
      MyFormControl myFormControl1;
      public MyThreadClass(MyFormControl myForm)
      {
         myFormControl1 = myForm;
      }
      String myString;

      public void Run()
      {


         for (int i = 1; i <= 5; i++)
         {
            myString = "Step number " + i.ToString() + " executed";
            Thread.Sleep(400);
            // Execute the specified delegate on the thread that owns
            // 'myFormControl1' control's underlying window handle with
            // the specified list of arguments.
            myFormControl1.Invoke(myFormControl1.myDelegate,
                                   new Object[] {myString});
         }
      }
   }

 

 

 

ProgressBar 업데이트 시키기

image

 

image

image

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Threading;
using System.Diagnostics;

//버튼클릭스 progressBar 를 업데이트 합니다.
namespace DevWindowForm
{

    //델리게이트 생성
    delegate void myDelegate(int i , int max);
  

    public partial class Form1 : Form
    {
        //스레드생성
        System.Threading.ThreadStart ts;
        System.Threading.Thread myThread;
        
        public Form1()
        {
            InitializeComponent();

          
        }

        //progressBar를 업데이트 합니다
        //덱스트박스에 값을 출력합니다.
        private void updateProgress(int _Value, int _Max)
        {
          
            this.progressBar1.Maximum = _Max;
            progressBar1.Value = _Value;
            this.textBoxComment.Text += _Value.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ts = new ThreadStart(UpdateNum);
            myThread = new Thread(ts);
            myThread.Start();
        }


        private void UpdateNum() {

            int t_i = 0;
            while (t_i < 1000) {
                try
                {
                    //델리게이트호출
                    this.Invoke(new myDelegate(updateProgress), new object[] { t_i, 1000 });

                    Thread.Sleep(10);
                    
                }
                catch (Exception ex)
                {
                    break;
                }               
            
            }
        
        }



    }
}

폼에 있는 콘크롤들은 폼이 사용하고 있는 스레드에서만 접근이 가능합니다

즉 Main thread에서만 접근아 가능 합니다

그렌데 M이란 class에서 새로은 thread로 들어오는 데이타를

Form콘트롤에 넣을려면

Invoke를 사용하여여 합니다

----------------------------

delegate void add_msg()

----------------------------

class A

private string m_data ;

public indata (string data)

{

    this.m_data=data;  //전역변수에 데이타 저장

    add_msg addmsg=new add_msg(AddMSG); //델리게이트 선언

    addmsg.Invoke(addmsg);       .//인보크 호출

}

private form_InData()

{

   textBox1.AppendText(m_data);

}

이런식으로 해야 합니다..

출처:

http://www.devpia.com/Forum/BoardView.aspx?no=64377&ref=64358&page=1&forumname=CSHARP_QA&stype=&KeyW=invoke&KeyR=title

[파일업로드]

어플리케이션에서 웹서버로 파일전송하기~

app 프로그램 코드

  try
   {
    string stringUrl="http://localhost/FileUpload/Upload.aspx";
    System.Net.WebClient webClient = new System.Net.WebClient();
    byte[] responseArray =webClient.UploadFile(stringUrl , "POST", this.label1.Text);  

/*

System.Text.Encoding.ASCII.GetString(responseArray); 를 실행하면 파일 업로드한 웹페이지를 받아옵니다. 그러타면... 중복파일이 있다면 중복처리를 한다음에  변경된 파일 네임을 돌려주면 되겠따;;;

# System.Text.Encoding.ASCII.GetString(responseArray);  어라 한글깨졌네

아래처럼하니깐 한글이 안깨진다

this.textBox1.Text = System.Text.UTF8Encoding.UTF8.GetString(responseArray);

*/

    this.label2.Text = System.Text.Encoding.ASCII.GetString(responseArray);

   }
   catch(System.Exception error)
   {
    MessageBox.Show( error.ToString() );
   }

http://localhost/FileUpload/Upload.aspx코드

  private void Page_Load(object sender, System.EventArgs e)
  {

    // 여기에 사용자 코드를 배치하여 페이지를 초기화합니다.

foreach(string f in Request.Files.AllKeys)
   {

    HttpPostedFile file = Request.Files[f];
    file.SaveAs(@"C:\Documents and Settings\Administrator\My Documents\Visual Studio Projects\GenealogicalWEBSITE\FileUpload\" + file.FileName);

  }

+ Recent posts