반응형

<TextBox GotFocus="TextBox_GotFocus" ... / >

using System.Windows.Threading;

private void TextBox_GotFocus(object sender, RoutedEventArgs e)

{

    Dispatcher.CurrentDispatcher.BeginInvoke

    (

        DispatcherPriority.ContextIdle,

        new Action

        (

            delegate

            {

                (sender as TextBox).SelectAll();

            }

        )

    );                 

}



출처: https://shine10e.tistory.com/60 [열이 Blog : )]

반응형

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

현상황은 다음과 같다.

두대의 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

반응형


    For i = 1 To 100

        rg = "A" & i

        rg2 = rg & ":" & rg

        cl = Sheet1.Range(rg2).Interior.Color

        If cl = 2862825 Then

            Cells(i, 4) = ""

        End If

    Next i


1에서 100번째 열까지의 첫번째셀(A1~A100)의 색상을 확인해서

셀의 색상값이 2862825일때 셀의 값을 변경하는 매크로이다.


참고로 색상을 인식할때 범위(Range("A1:A100"))과같은 방식으로 지정하는데

예제의 내용은 각1개의 셀의 컬러만 인식하도록 했다.

다시말해 Range("A1:A1")으로 반복되는 내용이다.

반응형

# The following options will be passed to all MySQL clients
[client]
#password = your_password
port = 3306
socket = /tmp/mysql.sock

# The MySQL server
[mysqld]
port = 3306
socket = /tmp/mysql.sock
basedir = /var/www/mariadb/
datadir = /var/www/mariadb/data
skip-external-locking
key_buffer_size = 384M
max_allowed_packet = 1M
table_open_cache = 512
sort_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 8M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size = 32M
# Try number of CPU's*2 for thread_concurrency
thread_concurrency = 8




# Don't listen on a TCP/IP port at all.
skip-networking

# required unique id between 1 and 2^32 - 1
server-id = 1

# Uncomment the following if you are using BDB tables
#bdb_cache_size = 4M
#bdb_max_lock = 10000

# Uncomment the following if you are using InnoDB tables
innodb_data_home_dir = /var/www/mariadb/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = /var/www/mariadb/data
#You can set .._buffer_pool_size up to 50 - 80 %
# of RAM but beware of setting memory usage too high
innodb_buffer_pool_size = 16M
#innodb_additional_mem_pool_size = 2M
# Set .._log_file_size to 25 % of buffer pool size
innodb_log_file_size = 5M
innodb_log_buffer_size = 8M
innodb_flush_log_at_trx_commit = 1
innodb_lock_wait_timeout = 50

[mysqldump]
quick
max_allowed_packet = 16M

[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates

[isamchk]
key_buffer = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[myisamchk]
key_buffer_size = 20M
sort_buffer_size = 20M
read_buffer = 2M
write_buffer = 2M

[mysqlhotcopy]
interactive-timeout

반응형

export JAVA_HOME=/home/user/jdk1.5.0_22

export USER_HOME=/home/user/apache-tomcat-5.5.36/webapps/ROOT/WEB-INF

export CLASSPATH=.:$USER_HOME/lib/ojdbc14.jar:$USER_HOME/lib/activation-1.1.jar


EXEC_NAME=ServiceName


PROC=`ps -ef | grep $EXEC_NAME | grep -v grep`

if [ "$PROC" != "" ];

then

echo "processing."

else

echo "not processed."

cd $USER_HOME/services/SoapTran/


$JAVA_HOME/bin/java -cp $CLASSPATH -classpath $CLASSPATH java_class_pack.$EXEC_NAME $1

fi

반응형


사직동의 셀을 아래의 삼청동과 부암동 처럼 셀병합해야하는 경우가 생겼다. 각동들의 ROW숫자는 동일하고  각동은 

각 13건씩의 ROW를 가지고 있으며 반복해야할 카운트(동의 수)도 정해져있다. 그리고 병합해야할 셀은 C컬럼이다.

매크로 만들기를 한 후 코드부분에


For i = 1 To 100

    Range(Cells(((i * 13) - 12), 3), Cells(((i * 13) + 1), 3)).Merge

Next i

이렇게 작성하면 된다.

For문이기 때문에 이명령을 100번 반복한다. 100번동안 13열씩 병합하게된다. 참고로 Cells(i*13),3)에서 3이 C컬럼을 의미한다.


Sub Merge()
    va = "첫번째 셀내용"
    stno = 1
    edno = 0
    '헤더가 1ROW셀이므로 2ROW셀부터 병합체크
    For i = 2 To 100
        vb = LTrim(RTrim(Cells(i, 1)))
        If va <> vb Then
            edno = i - 1
            Range(Cells(stno, 1), Cells(edno, 1)).Merge
            stno = i
        End If
        va = LTrim(RTrim(Cells(i, 1)))
    Next i
End Sub





+ Recent posts