반응형
//--------------------서버주소 가져오기-----------------------------------

using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;

IPHostEntry IPHost = Dns.Resolve(Dns.GetHostName());
IPAddress addr = IPHost.AddressList[0];
IPHost.AddressList[0].ToString();

==================↓한줄요약===================================
IPAddress addr = Dns.Resolve(Dns.GetHostName()).AddressList[0];

//--------------------클라이언트 주소가져오기-----------------------------

Response.Write(Request.ServerVariables["REMOTE_HOST"]);
반응형
//========================================
//↓↓ASP.NET1.1에서 파일업로드
//========================================
protected void saveFile()
{
    string FileName = FileUpload.PostedFile.FileName;
    if (FileName != null || FileName != string.Empty)
    {
        Session["myupload"] = FileUpload;
    }
    HtmlInputFile hif = (HtmlInputFile)Session["myupload"];
    string storePath = "d:\\momo13";
    if (Directory.Exists(storePath))
        Directory.CreateDirectory(storePath);
    hif.PostedFile.SaveAs(storePath + "/" + Path.GetFileName(hif.PostedFile.FileName));
    lblMsg.Text = "업로드";
}

//========================================
//↓↓ASP.NET2.0에서 파일업로드
//========================================
protected void saves1()
{
    if (FileUpload1.HasFile)
    {
        
        DirectoryInfo di = new DirectoryInfo(upDir);
        if (!di.Exists)
            di.Create();
        string fName = FileUpload1.FileName;
        string fFullName = upDir + fName;
        FileInfo fInfo = new FileInfo(fFullName);
        if (fInfo.Exists)
        {
            int fIndex = 0;
            string fExtension = fInfo.Extension;
            string fRealName = fName.Replace(fExtension, "");
            string newFileName = "";
            do
            {
                fIndex++;
                newFileName = fRealName + "_" + fIndex.ToString() + fExtension;
                fInfo = new FileInfo(upDir + "\\" + newFileName);
            }
            while (fInfo.Exists);
            fFullName = upDir + "\\" + newFileName;
        }
        FileUpload1.PostedFile.SaveAs(fFullName);
        lblMsg.Text = "업로드된 파일 : " + fFullName;
    }
    else
    {
        lblMsg.Text = "업로드할 파일이 존재하지 않습니다.";
    }
}

반응형
string strSql = "Select * From country_def";
OracleCommand cmd = new OracleCommand(strSql,dbConn.OraConn());
cmd.Connection.Open();
OracleDataReader rd = cmd.ExecuteReader();
dpCountry.DataSource = rd;
dpCountry.DataValueField = "country_cd";
dpCountry.DataTextField = "country_name";
dpCountry.DataBind();
rd.Close();
cmd.Connection.Close();
----------------------------------------------------------------------
기초적인 내용인데 자주 까먹는다. ㅠ_ㅠ
반응형
ASP.NET에서는 Response.WriteFile() 이라는 함수를 이용해서 파일(바이너리)을 스트림으로 내려보낼 수 있다.
사용 방법은 간단하다.

 

    Response.AddHeader("Content-Disposition", "attachment;filename=\"123.zip\"");
    Response.ContentType = "application/octet-stream";

    Response.WriteFile("C:\\123.zip");

 

즉, URL로 접근이 가능하지 않은 파일을 이와 같은 방법을 통해 동적으로 내려보낼 수 있다.
그런데, 이 파일의 크기가 100MB이상의 대용량인 경우에는 웹 서버에서 에러가 발생하고 다운로드가 안될 수 있다.
그럴 때는 아래 링크를 참조하자.

 

http://support.microsoft.com/kb/812406 

반응형
※닷넷에서 한글파라미터는 인식이 되지 않는 경우가 있기 때문에 인코딩 디코딩 해준다.
   특히 띄워쓰기 포함된 한글파라미터는 반드시 인코딩 디코딩 해주어야 한다.

//보내는 쪽 url파라미터
group = HttpUtility.UrlEncode(group);
//받는 쪽 url파라미터
group = HttpUtility.UrlDecode(Request.Params["group"].ToString().Trim());

※참조한 원문 
HttpUtility.UrlEncode("홍길동", System.Text.Encoding.GetEncoding("euc-kr")) 

반응형
// FTP UPLOAD
using System.IO;
using System.Net;

 

/// <summary>
    ///  FTP 업로드
    /// </summary>
    /// <returns></returns>
    private bool Media_FtpUpload()
    {
        try
        {
            string strFTP_URL = @"ftp://123.123.123.123:1234/";
            string strFTP_ID = "id";
            string strFTP_PW = "pw";

            // 선택파일의 이진 데이터 생성
            byte[] fileData = new byte[file1.PostedFile.ContentLength];

            // 파일정보를 바이너리에 저장
            BinaryReader br = new BinaryReader(file1.PostedFile.InputStream);
            br.Read(fileData, 0, fileData.Length);
            br.Close();

            WebClient request = new WebClient();

            // FTP 로 접속
            request.Credentials = new NetworkCredential(strFTP_ID, strFTP_PW);

            // FTP 로 데이터 업로드
            byte[] newFileData = request.UploadData(strFTP_URL + file1.FileName, fileData);

            lblMsg.Text = strFTP_URL + file1.FileName;

            return true;
        }

        catch
        {
            return false;
        }
    }

    /// <summary>
    /// FTP 다운로드
    /// </summary>
    /// <returns></returns>
    private bool Media_FtpDownload()
    {
        try
        {
            string strFTP_URL = @"ftp://123.123.123.123:1234/";
            string strFTP_ID = "id";
            string strFTP_PW = "pw";

            WebClient request = new WebClient();

            request.Credentials = new NetworkCredential(strFTP_ID, strFTP_PW);

            // FTP 로 부터 데이터 다운로드 
            byte[] newFileData = request.DownloadData(lblMsg.Text);

            string strFileName = lblMsg.Text.Substring(lblMsg.Text.LastIndexOf("/") + 1);

            // 특정 폴더로 파일생성
            FileStream newFile = new FileStream(@"C:\media\" + strFileName, FileMode.Create);

            // 파일쓰기
            newFile.Write(newFileData, 0, newFileData.Length);

            // 파일닫기
            newFile.Close();

            return true;
        }
        catch
        {
            return false;
        }
    }
[출처] [ASP.NET 1.1] FTP 업로드 / 다운로드|작성자 보리
http://blog.naver.com/bori29?Redirect=Log&logNo=130031228382
반응형
//이미지 파일 저장
private void imageCreate(string pathname)
{
string filepath = "";
WebClient clt = new WebClient();
//받아올 경로
string url = imgpath + pathname + "/";
if (Directory.Exists(paths+pathname)==false)
Directory.CreateDirectory(paths+pathname);
clt.DownloadFile(url+aryimg[arycnt],paths + filepath+ aryimg[arycnt]);
}
----------------------------------------------------------------------------
WebClient를 통해서 웹에 공개된 이미지를 다운로드.
반응형
닷넷2003버전에서 데이터그리드 사용시 라디오버튼에 그룹이 자동으로 
지정되기 때문에 (각각 고유의 그룹명으로 자동생성됨) 아래와 같은 과정을 통해서
라디오버튼컨트롤을 생성해주어야 한다.

①라디오버튼을 적용할 데이터그리드 필드를 아래와 같이 우선 정의한다.(aspx테그에추가)
<asp:TemplateColumn>
<ItemStyle HorizontalAlign="Center" Width="20px"></ItemStyle>
<ItemTemplate>
<asp:Literal runat="server" ID="cbcheck"></asp:Literal>
</ItemTemplate>
</asp:TemplateColumn>
②데이터그리드의 ItemDataBound이벤트에 아래와 같이 이벤트를 작성(cs폼에추가)
string radioFormat = "<input type=radio name='cbcheck' value='{0}' {1}>";
if( e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem 
    || e.Item.ItemType == ListItemType.SelectedItem )
{
DataRowView drv = e.Item.DataItem as DataRowView;
Literal cbcheck = e.Item.FindControl("cbcheck") as Literal;
cbcheck.Text = String.Format(radioFormat,e.Item.ItemIndex,"");
}
반응형
// 오늘 날짜를 가져오는 방법: (3월 8일 목요일)
DateTime today = DateTime.Today;

// 1일 날짜를 가져오는 방법: (3월 1일 목요일)
DateTime first_day = today.AddDays(1 - today.Day);

// 첫번째 주의 일요일을 가져오는 방법: (2월 25일 일요일)
DateTime first_sunday = first_day.AddDays(0 - (int)(first_day.DayOfWeek));

// 첫번째 주의 일수를 가져오는 방법: (3일)
int first_week_day_count = 7 - (int)(first_day.DayOfWeek);

// 말일 날짜를 가져오는 방법: (3월 31일 토요일)
DateTime last_day = today.AddMonths(1).AddDays(0 - today.Day);

// 마지막 주의 일요일을 가져오는 방법: (3월 25일 일요일)
DateTime last_sunday = last_day.AddDays(0 - (int)(last_day.DayOfWeek));

// 마지막 주의 일수를 가져오는 방법: (7일)
int last_week_day_count = last_day.DayOfYear - last_sunday.DayOfYear + 1;

// 이번 달의 주수를 가져오는 방법: (5주)
int this_month_week_count = ((last_sunday.DayOfYear - first_sunday.DayOfYear) / 7) + 1;


//날짜변환 관련
DateTime HHMMSS = DateTime.Parse(row["DUTY_TIME"].ToString());
string StrHHMMSS = HHMMSS.ToString("yyyy-MM-dd HH:mm:ss");
string StrHHMMSS = HHMMSS.ToString("HH:mm:ss"); 
string strDate = DateTime.Now.ToString("yyyyMMddHHmm");      
반응형

asp.net 와 자바등의 이기종간 데이터를 교환하는 방법은
XML에 기반한 soap통신을 통해서 가능하다.
DIME등의 방식이 있지만 개인적으로 테스트에 성공하지 못했고
인터넷에서 DIME보다 MTOM방식을 권장하고 있으므로
MTOM방식으로 구현해 보았다.

1)iis 상에 .net으로 바이너리 데이터를 반환하는 웹서비스를 구축한다.

byte[] response;
response = File.ReadAllBytes(filePath);
return response;

2)솔루션탐색기에서 WSE setting 3.0을 실행한다.

①General 탭
      Enable this project for Web Services Enhancements 체크
      Enable Microsoft Web Services Enhancement Soap Protocol Factory 체크
②Messaging 탭
      Server Mode 선택(optional,always중 택일이지만 always로 선택)
③Policy 탭(※ 세팅하지 않아도 된다.)
      Enable Policy 체크
      Policy 추가한다.(설정법은 각 별개)

3)컴파일 하여 웹(iis)에 게시한다.
--↑여기까지 서버세팅--------------------------------------------------------------------
4)클라이언트 프로그램에 WSE setting 3.0을 실행한다.

①General 탭은 서버와 동일

②Messaging탭
      Client Mode(On)선택
      Server Mode 동작시키지 않음(서버로 활용하지 않을 것이므로)
③Policy 탭
      웹서비스 서버에 Policy가 설정되어 있다면 동일하게 세팅한다.

5)웹서비스를 웹참조 한다.
6)웹서비스로 부터 데이터를 수신&저장을 구현

localhost.BinaryDataMTOMServiceWse response;
response = new localhost.BinaryDataMTOMServiceWse();
byte[] data = response.GetFile(fileName);
File.WriteAllBytes(savePath, data);
※ localhost : 웹참조된 MTOM서비스 명


 

+ Recent posts