반응형

XSSFCellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();

 

//셀 배경색 지정 (FillPattern, SetFillForegroundColor)

style.FillPattern = FillPattern.SolidForeground;

byte[] rgb = new byte[]{255,255,255}; //셀색상 RGB로 설정
style.SetFillForegroundColor(new XSSFColor(rgb));

 

//셀 align, verticalAlign

style.Alignment = HorizontalAlignment.Center;
style.VerticalAlignment = VerticalAlignment.Center;

 

//셀 테두리 UP,BOTTOM,LEFT,RIGHT

style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;

 

cell.CellStyle = style; //cell => ICell

반응형

//c#(asp.net)

public class myInfo{

    public string p01{get; set;}

    public string p02{get; set;}

}

[WebMethod]
public static string methodName(myInfo info)

 

//js

let minfo = {};
minfo.p01 = 'p01_value';
minfo.p02 = 'p02_value';

 

let jsonPrm = {};
jsonPrm['info'] = minfo;

 

$.ajax({
        type: "POST",
        url: "popup01.aspx/updateOrgMaster",
        data: JSON.stringify(jsonPrm),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (msg) {});

 

 

※참고 : Pass JSON data object from jQuery AJAX to WebMethod in ASP.Net (aspsnippets.com)

반응형

복잡한 문제를 해결해야했다.

현상황은 다음과 같다.

두대의 iis가 있다. 한쪽은 WebServer이고 다른한쪽은 ImageServer이다.

골때리는 점은 Web에서 Img로 파일을 업로드할때 파일공유방식으로 전송하고 있다는 점이다.

Web이 \\ImgServerPath 와같이 공유폴더로 접근해서 파일을 업로드하고있다.


문제는 Web서버를 한대 증설하면서 공유폴더방식으로 접근이 안된다는 점이다. GUI단에서는 작업이 되지만

IIS수준에서는 붙지 않아서 파일업로드를 못하고 있다. 이를 해결하기 위해 잔머리를 굴렸다.


그러다가 파일을 Base64String으로 변환해서 POST전송하면 되겠다는 아이디어를 떠올렸다.

어차피 ImgServer도 IIS이므로 동일한 환경으로 세팅이 가능하기에 Img에도 asp.net을 구축할 수 있다.


구현단계에서 발견한 추가문제가 있었다.

5MB이상용량의 파일을 전송할 수가 없었다. 10M이상의 파일을 업로드 하지 못하기 때문에 이를 해결하기 위해 머리를 또 굴렸다.

Base64로 변환된 String은 길이기 길기때문에 잘릴 수도 있겠다 싶었다.

그래서 Base64를 압축해서 전송하면되겠다는 두번째 아이디어를 떠올렸다. 이문제를 며칠 동안 찾아 해맸다.


그리고 해결했다.


절차를 다시 정리하면 다음과 같다.

    1. 파일을 MemoryStream으로 변환(MemoryStream생성과정에 GZipStream을 통해 압축)

    2. MemoryStream을 Base64로 변환

    3. Base64문자열을 POST로 전송

    4. POST로 받은 문자열을 파일로 변환


※ using System.IO.Compression; //GZipStream을 사용하기 위한 선언


A)파일전송


           HttpFileCollection addFile = HttpContext.Current.Request.Files;


           string url = "http://ImgServer.url/Data_send.aspx";

           string sFiles_Name = "";


           string postParm = "";

           string tmpParm = "";

           for (int i = 0; i < addFile.Count; i++)

           {

               HttpPostedFile postedFile = addFile[i];

               if (postedFile.ContentLength > 0)

               {

                   sFiles_Name = postedFile.FileName;

                   Stream sm = postedFile.InputStream;

                   BinaryReader br = new BinaryReader(sm);

                   byte[] byt = br.ReadBytes((Int32)sm.Length);

                   sm.Dispose();

                   br.Close();


                   string base64 = "";

                   

                   using(MemoryStream ms = new MemoryStream())

                   {

                       using (BufferedStream bs = new BufferedStream(new GZipStream(ms, CompressionMode.Compress), (64 * 1024)))

                       {

                           bs.Write(byt, 0, byt.Length);

                       }

                       base64 = Convert.ToBase64String(ms.ToArray());

                   }

                   tmpParm += base64 + '#'; //#은 파일구분자(여러개의 파일을 추가했을경우)

               }

           //POST 파라미터 

           postParm = string.Format("save_data={0}", tmpParm);


           try

           {

               //POST전송

               byte[] datatCategory = UTF8Encoding.UTF8.GetBytes(postParm);

               HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

               req.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

               req.Method = "POST";

               req.ContentLength = datatCategory.Length;

               Stream requestStream = req.GetRequestStream();

               requestStream.Write(datatCategory, 0, datatCategory.Length);

               requestStream.Close();

               HttpWebResponse httpWebResponse = (HttpWebResponse)req.GetResponse();

               StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("UTF-8"));

               string rtn = streamReader.ReadToEnd();

               streamReader.Close();

               httpWebResponse.Close();

           }

           catch (Exception ex)

           {

               //throw ex;

           }


B)파일수신(string url = "http://ImgServer.url/Data_send.aspx";에 해당)


           HttpFileCollection addFile = HttpContext.Current.Request.Files;


           string save_data = "";

            

           try

           {

               save_data = Request.Form["save_data"].Replace(" ", "+");    //Replace해줘야함 "+"문자가 " "으로 변환되서 넘어옴

           }

           catch (Exception ex)

           {

               save_data = "";

               Response.Write(ex.Message);

               return;

           }

           

           if (save_data != null && save_data != "")

           {

               string[] aryFiles = save_data.Split("#");

               string svrPath = Server.MapPath(".").Replace("\\", "/");

               for (int i = 0; i < aryFiles.Length - 1; i++)

               {

                   byte[] bytData = Convert.FromBase64String(aryFiles[i]);

                       try

                       {

                           DirectoryInfo di = new DirectoryInfo(svrPath + "/folder");

                           if (!di.Exists)

                           {

                               di.Create();

                           }


                           using(MemoryStream ms = new MemoryStream(bytData))

                           {

                               using(MemoryStream dms = new MemoryStream())

                               {

                                   using(BufferedStream bs = new BufferedStream(new GZipStream(ms, CompressionMode.Decompress),(64*1024)))

                                   {

                                       bs.CopyTo(dms);

                                   }        

                                   using (FileStream fs = new FileStream(svrPath + "/folder/save_filename.file", FileMode.Create, System.IO.FileAccess.Write))

                                   {

                                       byte[] bt = dms.ToArray();

                                       dms.Read(bt, 0, (int)dms.Length);

                                       fs.Write(bt, 0, bt.Length);

                                       fs.Flush();

                                   }

                               }

                           }

                       }

                       catch(Exception ex)

                       {

                           Response.Write("false : " + ex.Message);

                           return;

                       }

               }

               Response.Write("true");

           }



※ 참고 : http://toreaurstad.blogspot.com/2014/01/compressing-byte-array-in-c-with.html

반응형

System.Web.UI.WebControls.Image obj = new System.Web.UI.WebControls.Image();

System.IO.MemoryStream ms = new System.IO.MemoryStream();

bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

obj.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray(), 0, ms.ToArray().Length);


기존에는 

Response.BinaryWrite(ms.ToArray());

으로 이미지를 aspx로 뿌리는 방식을 썼었는데 한번에 하나의 파일밖에 뿌릴 수 없어서 방법을 찾아봤다.


출처 : https://www.codeproject.com/Questions/642132/asp-net-displaying-image-from-MemoryStream

반응형

aspx단에 Panel컨트롤 생성

<asp:Panel ID="pnl" runat="server"></asp:Panel>




System.Web.UI.WebControls.Image obj = new System.Web.UI.WebControls.Image();

System.IO.MemoryStream ms = new System.IO.MemoryStream();

bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

obj.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(ms.ToArray(), 0, ms.ToArray().Length);

obj.ID = "img" + ii.ToString();

pnl.Controls.Add(objImg);


Panel에 Image컨트롤을 추가하는 방식

반응형

byte[] data = null;

using (var br = new BinaryReader(uploadfile.PostedFile.InputStream))

{

data = br.ReadBytes(uploadfile.PostedFile.ContentLength);

}

#####################################################


byte[] data를 MemoryStream등으로 변환해서 쓸 수 있다ㅏ.

반응형
public static void Main()
{
    string data = "%B3%F3%C7%F9";
    byte[] bData = new byte[data.Length / 3];
    for (int i = 0; i < data.Length; i += 3)
    {
        int pos = i / 3;            
        bData[pos] = Convert.ToByte(data.Substring(i + 1, 2), 16);
    }
    data = System.Text.Encoding.GetEncoding("euc-kr").GetString(bData);
    Console.WriteLine(data);
}


출처 : https://stackoverflow.com/questions/47193248/decoding-code-string-to-utf8-and-string


파라미터를 EUC-KR로 넘겨서 받아오는 과정에 디코딩이 제대로 안되는 바람에 애를 먹었다.

한글 인코딩 문자를 변환하는 방법을 출처에서 찾았다.



//추가 방법

public static void Main()
{
    byte[] buffer = Request.BinaryRead(Request.TotalBytes);
    string url = System.Web.BinaryRead(Request.TotalBytes);
}

출처 : http://blog.naver.com/PostView.nhn?blogId=doksajokyo&logNo=220835329973&parentCategoryNo=6&categoryNo=&viewDate=&isShowPopularPosts=true&from=search

반응형

굉장히 간단한 내용이다.

AJAX로 사용하는 요즘은 거의 사용할 일이 없는 태크닉인데

asp.net 2.0으로 구축된 사이트를 유지보수하다 보니 발생하는 귀찮음 때문에 찾아보다가 주저리 주저리 써본다.


Page.aspx에 


<asp:Label ID="lbl01" runat="server"></asp:Label>

<asp:Label ID="lbl02" runat="server"></asp:Label>

<asp:Label ID="lbl03" runat="server"></asp:Label>

<asp:Label ID="lbl04" runat="server"></asp:Label>

<asp:Label ID="lbl05" runat="server"></asp:Label>


와 같이 Label컨트롤을 순차적으로 생성 돼있다.

이 Label들에 값들을 일일이 코딩해주려니 귀찮고  for문등을 이용해서 자동으로 값을 넣고 싶은데 방법을 잘모르겠고...


여튼 해결 방법은 다음과 같다.

((Label)Page.FindControl(id)).Text = _txt;

굉장히 단순하다.

이를 응용해서 for문으로 값을 넣는다면

string[] _values = {"1","2","3","4","5"};

의 값을 자동으로 넣는다고 가정해보자.

for(int i = 0; i < 5; i++)

{

((Label)Page.FindControl("lbl0" + (i + 1).toString() )).Text = _values[i];

}

이런식으로 처리하면 매우 간단하다. 

여튼 핵심은 Page.FindControl("ID")가 돼겠다.



반응형

실버라이트에 ArcGIS를 사용하여 지도서비스를 올리는 프로젝트를 진행중이다.

기존 테스트 서버에서 운용서버로 자료를 이관하던 중 ArcGIS의 맵데이터가 연동이 안돼는 사태가 발생하여 며칠을 허비했다.

원인은 웹서버에 ArcGIS관련 인증관련 설정을 누락했기 때문이었다.


clientaccesspolicy.xml


crossdomain.xml


위 파일들을 iis 루트에 복사해야한다. ("C:\inetpub\wwwroot")

크로스도메인접근 허용관련이라고 하니 ArcGIS & asp.net관련 프로젝트에서 빼먹지 않도록 해야한다.

반응형

asp.net2.0을 사용하고 있다면 부족한 기능에 좌절하는 경우가 종종있다.

특히 그래프 기능인데 2.0에서 사용할 수 있는 그래프가 많지 않다. OpenFlashChart를 사용했다가

일부 기능에 문제가 있어서 대체가능한 그래프를 찾느라 아주 애먹은 적이 있는데 우연히 Zed를 찾아서 

활용할 수 있었다.


ZedGraphTest.zip


첨부한 파일은 ZedGraph의 간단한 활용 소스이다. \bin폴더안에 ZedGraph.dll파일이 포함되어 있으니 이를 활용하면 된다.

셈플소스를 보면 간단하게나마 구조를 파악할 수 있으니 활용해보자.

+ Recent posts