posted by 준치 2018. 3. 7. 21:47

xml을 사용하다 보니 enter가 들어간 데이터 때문에 문제가 발생하는 경우가 종종 발생한다..


xml node 값을 받아서 바로 랜더링 할 경우였다.


그래서 검색 고고씽...


해결방법

1. string result = xmldom.SelectSingleNode("DATA/INFO").InnerText.Replace(Environment.NewLine, "<br />");


2. string result = Regex.Replace(input, @"\r\n?|\n", "<br />");


출처: <http://stackoverflow.com/questions/8084173/replaceenvironment-newline-br-works-on-localhost-but-not-when-i-upload>


오늘도 화이팅~

posted by 준치 2018. 2. 1. 17:11

c# 으로 문자열 앞에 0을 채워야 할 경우가 있고... 특정 문자를 채워야 할 때가있다...


이럴때 PadLeft 또는 PadRight 를 사용하면 된다.


사용 방법


string str = "test";

char pad = '0';


str.PadLeft(전체 자릿수 , pad)

또는

str.PadRight(전체 자릿수 , pad)


전체 자릿수에 10 넣을 경우 결과 값

- str.PadLeft(전체 자릿수 , pad) : 000000test

- str.PadRight(전체 자릿수 , pad) : test000000


사용할때 마다 검색 한듯.... 


출처 : https://msdn.microsoft.com/ko-kr/library/36f2hz3a(v=vs.110).aspx

출처 : https://msdn.microsoft.com/ko-kr/library/92h5dc07(v=vs.110).aspx


ToString을 사용하는 방법도 있다.


참고 : https://msdn.microsoft.com/ko-kr/library/dd260048(v=vs.110).aspx


오늘도 화이팅...

posted by 준치 2010. 7. 19. 14:56
int aaa = 123456789;
string money = String.Format("{0:#,###}", aaa);
writer.WriteLine(money);

저렇게해서 찍으면...ㅎㅎ

123,456,789  이렇게 나와요..ㅎㅎㅎ
posted by 준치 2009. 3. 11. 01:59
수치 소수점 이하 값을 버리려면 Math클래스의 정적 메소드 Floor를 사용하고 반올림할 경우에는 Ceiling을 사용합니다. 즉, Floor는 마지막 수가 작은 값이면 잘라버리고 Ceiling은 보다 큰 값이면 반올림한다는 것입니다.

사용방법은 아래와 같습니다.

   Math.Floor(Decimal)
   Math.Ceiling(Decimal)

파라미터에 Decimal형을 사용하는데 이는 .NET Framework 2.0이후부터 지원하게 되었고 Double형도 사용할 수 있습니다.

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

namespace Math1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Math메소드로 소수점 처리 방법");
            decimal pf = Math.Floor(1.7m);
            Console.WriteLine(pf);

            decimal pc = Math.Ceiling(1.7m);
            Console.WriteLine(pc);
        }
    }


<결과>
Math메소드로 소수점 처리 방법
1
2

[참고] 소수점 2자리단위로 정리하고 싶은 경우

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

namespace Math2
{
    class Program
    {
        static void Main(string[] args)
        {
            decimal v = 1.34m;

            v *= 10;
            Console.WriteLine("1.34m *= 10 = {0}", v);

            v = Math.Floor(v);
            v /= 10;
            Console.WriteLine("Result = {0}", v);
        }
    }


출처 : http://www.01kim.kr/bbs/cstips/page/3
posted by 준치 2009. 2. 10. 13:09

HttpBrowserCapabilities brow;

brow = HttpContext.Current.Request.Browser;

public browser()
{
if (brow.Browser == "IE")
{
if (brow.MajorVersion >= 8)
{
            }
 else if (brow.MajorVersion == 7)
            {
                s = brow.MajorVersion.ToString();
             }
             else if (brow.MajorVersion <= 6)
             {
                s = brow.MajorVersion.ToString();
             }
}

else if (brow.Browser == "Firefox")
{
if (brow.MajorVersion >= 3)
            {
                s = brow.MajorVersion.ToString();
             }
   
}
}
posted by 준치 2008. 11. 7. 22:24
현재 도메인을 찾을하고 하다가 찾은거...될랑가..아직 한해봤는데..ㅋㅋㅋㅋㅋ
  1. ///Get the sub-domain from the provided URL
  2. /// </summary>
  3. /// <param name="url">URL to retrieve sub-domain from</param>
  4. /// <returns></returns>
  5. public static string RetrieveSubDomain(Uri url)
  6. {
  7.     string subDomain = "";
  8.     if (url.HostNameType == UriHostNameType.Dns && (!(url.HostNameType == UriHostNameType.Unknown)))
  9.     {
  10.         string host = url.Host;
  11.         int length = host.Split('.').Length;
  12.         if (length > 2)
  13.         {
  14.             int last = host.LastIndexOf(".");
  15.             int idx = host.LastIndexOf(".", last - 1);
  16.             subDomain = host.Substring(0, idx);
  17.         }
  18.     }
  19.  
  20.     return subDomain;
  21. }


///Get the sub-domain from the provided URL
/// </summary>
/// <param name="url">URL to retrieve sub-domain from</param>
/// <returns></returns>
public static string RetrieveSubDomain(Uri url)
{
    string subDomain = "";
    if (url.HostNameType == UriHostNameType.Dns && (!(url.HostNameType == UriHostNameType.Unknown)))
    {
        string host = url.Host;
        int length = host.Split('.').Length;
        if (length > 2)
        {
            int last = host.LastIndexOf(".");
            int idx = host.LastIndexOf(".", last - 1);
            subDomain = host.Substring(0, idx);
        }
    }

    return subDomain;
}

SQL
posted by 준치 2008. 11. 6. 02:25

C#은 mysql커넥터 없이는 mysql을 사용할 수 없습니다
주로 mssql과 연동하여 사용하는데 필자는 꼭 반드시 미친듯이 mysql을 사용해야 했으므로
그 사용예제를 올려봅니다 ^^

먼저 첨부된 파일을 C# 라이브러리에 추가하고..
상단에

MySql.Data.MySqlClient가 using 되어 있어야 합니다.

그리고 첫번째 예제

public void MyMathod(){

      MySqlConnection connection;
      connection = new MySqlConnection();

      string connectionString =             "server=127.0.0.1;database=MY_DB;uid=MY_ID;pwd=MY_PW;";

            connection.ConnectionString = connectionString;

            try
            {

                string commandStirng = "select * from test";

                MySqlDataAdapter DBAdapter = new MySqlDataAdapter(commandStirng, connection);
                DataSet DS = new DataSet();
                DBAdapter.Fill(DS, "test");

                dataGridView1.DataSource = DS.Tables["test"].DefaultView;
                //MessageBox.Show("연결됨");

            }
            catch (Exception E)
            {
                MessageBox.Show(E.ToString());
            }
            finally
            {
                connection.Close();
            }
}

기본 골격이고 신경써야 할 부분은 형광색 부분입니다.
1. 127.0.0.1 : Mysql이 설치된 원격지의 데이터베이스 IP어드레스 입니다.
2. MY_DB : 사용할 데이터베이스명
3. MY_ID : 데이터베이스 사용 ID
4. MY_PW : 데이터베이스 사용 PASSWORD
5. select * from test : 데이터베이스에 질의할 쿼리(본 예제는 Select로만 응용가능합니다)
예) select * from test where field1 = 1;
     select * from test order by field2 desc;
6. test : DBAdapter와 DS.Tables에 쿼리에 질의한 테이블 명을 적어 줍니다.
예) select * from angpang; //테이블 명이 angpang 입니다.
    .............................
    string commandStirng = "select * from angpang";

                MySqlDataAdapter DBAdapter = new MySqlDataAdapter(commandStirng,         connection);
                DataSet DS = new DataSet();
                DBAdapter.Fill(DS, "angpang");

                dataGridView1.DataSource = DS.Tables["angpang"].DefaultView;
                //MessageBox.Show("연결됨");
    .............................

7. dataGridView1 : 주로 결과값은 데이터그리드 뷰 컨트롤과 많이 사용합니다. 데이터그리드 뷰를 추가하여 Name 속성을 맞춰주면 결과값이 보여질 것입니다.

시간나면 Update 쿼리 응용법, Insert 쿼리 응용법, 데이터그리드뷰를 효율적으로 쓰는방법,
데이터베이스에 이미지를 2진코드로 저장하여 활용하는법 등을 기술해 보겠습니다.
감사합니다 ^^

posted by 준치 2008. 10. 31. 17:09

public ICredentials Credentials { get; set; }


 public static void Main()
    {          
        try {

            WebClient client = new WebClient();

              client.Credentials = CredentialCache.DefaultCredentials;
   
            Byte[] pageData = client.DownloadData("http://www.contoso.com");
            string pageHtml = Encoding.ASCII.GetString(pageData);
            Console.WriteLine(pageHtml);

        } catch (WebException webEx) {
            Console.Write(webEx.ToString());
        }
    }   
posted by 준치 2008. 10. 25. 20:57

참나...간단한 날짜 변환거 가지고 삽질하다가 찾아서 퍼왔네...
--------------------------------------------------------------------------------
-- Date Add, Adddays, Addmonths
--------------------------------------------------------------------------------
    DateTime dtTomorrow;
    dtTomorrow = DateTime.Today.AddDays(1);
    --------------------------------------------------------------------------------
    DateTime dtTomorrow;
    TimeSpan tsOneDay;
    tsOneDay = new TimeSpan(1, 0, 0, 0);
    dtTomorrow = DateTime.Today.Add(tsOneDay);
   
    AddMonths(1);
    --------------------------------------------------------------------------------
    int intDuration;
    TimeSpan tsDuration;
    tsDuration = new DateTime(2002, 2, 15) - new DateTime(2002, 2, 10);
    intDuration = tsDuration.Days;

--------------------------------------------------------------------------------
-- Date Convert
--------------------------------------------------------------------------------
    DateTime x = DateTime.Now.Date;
    TextBox1.Text = x.ToString();
    string s=TextBox1.Text;
    TextBox2.Text=Convert.ToDateTime(s).ToString("yyyy-MM-dd");
    //for example input date current date value is --- 21-12-2007 00:00:00
    //Converted format output is ----- 2007-12-21
   
    --------------------------------------------------------------------------------
    DateTime date1, date2;
    bool date1OK, date2OK;
    date1 = new DateTime(1,1,1);
    date2 = new DateTime(1,1,1);
    try {
     date1 = Convert.ToDateTime(Date1.Text);
     date1OK=true;
    }
    catch {
     date1OK = false;
    }
   
    --------------------------------------------------------------------------------
    //Date format conversion
    //e.g. 23/05/2007 into 2007-05-23
    String FromDate = Txt_FromDate.Text;
    DateTime DT_FromDate = DateTime.Parse(FromDate);
    FromDate = DT_FromDate.ToString("yyyy-MM-dd");
   
    --------------------------------------------------------------------------------
    DateTime MyDateTime = Convert.ToDateTime("16:25:05");
    lblDateOut.Text = Convert.ToString(MyDateTime);
   
    --------------------------------------------------------------------------------
    time.Text=DateTime.Now.Hour.ToString() + ":" +  DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString();

    --------------------------------------------------------------------------------
    In that case write a simple utility (I have them for integers, decimal etc) that uses regular expressions to validate the date
    Regx.ValidationExpression=@"^(([1-9])|(0[1-9])|(1[0-2]))\/((0[1-9])|([1-31]))\/((\d{2})|(\d{4}))$";
    if it is a match then it is a date and so can perform quickly the day is valid for the month. It will still be a lot quicker than try catch blocks

--------------------------------------------------------------------------------
-- Date Add, Adddays, Addmonths
--------------------------------------------------------------------------------
    DateTime dt = DateTime.Now.Date;
    Response.Write("DateTime.Now.Date = " + dt.ToString() + "<br/>");
    string strDate = "2007/05/01";
    Response.Write("Convert.ToDateTime(\"2007/05/01\") = " + Convert.ToDateTime(strDate).ToString() + "<br/>");
    string strDate1 = "2007.05.01";
    Response.Write("Convert.ToDateTime(\"2007.05.01\") = " + Convert.ToDateTime(strDate1).ToString() + "<br/>");
    string strDate2 = "2007-05-01";
    Response.Write("Convert.ToDateTime(\"2007-05-01\") = " + Convert.ToDateTime(strDate2).ToString() + "<br/>");
    string strDate3 = "2007 05 01";
    Response.Write("Convert.ToDateTime(\"2007 05 01\") = " + Convert.ToDateTime(strDate3).ToString() + "<br/>");
출력 )
    DateTime.Now.Date = 2007-05-22 오전 12:00:00
    Convert.ToDateTime("2007/05/01") = 2007-05-01 오전 12:00:00
    Convert.ToDateTime("2007.05.01") = 2007-05-01 오전 12:00:00
    Convert.ToDateTime("2007-05-01") = 2007-05-01 오전 12:00:00
    Convert.ToDateTime("2007 05 01") = 2007-05-01 오전 12:00:00
결과 )
    [/],[.],[-],[ ]  문자들로 구분을 지어주면 DateTime 형태로 변환이 가능하나
    [,], [%],[\],[_],[^]... 등등의 기호와 일반적으로 Sql 에서 변환이 가능한  숫자 8자리는 변경이 되질 않았다.

posted by 준치 2008. 10. 17. 10:46

간단한 C# 디비연결....ㅎㅎㅎㅎ

ADO.NET
     Contents

Object Model
 
기본  Data Access
C#

- 연결 설정
 
using System.Data;
using System.Data.SqlClient;
 // ...
public void Openning()
{

string ConnectionString = "server=localhost;database=dbTest;uid=sa;pwd=sa";
SqlConnection Connect = new SqlConnection(ConnectionString);
Connect.Open();
Connect.Close();

} 

- Update 
// ExecuteNonQuery
public void Updating()
{

string ConnectionString = "server=localhost;database=dbTest;uid=sa;pwd=sa";
SqlConnection Connect = new SqlConnection(ConnectionString);
string strInsertSQL = "Insert Into tblTest( Id, col2) Values(1,11)";
SqlCommand Command = new SqlCommand(strInsertSQL, Connect);
Connect.Open();
Command.ExecuteNonQuery();
Connect.Close();

}
 

- Query 1 
// ExecuteScalar

public void Quering1()

{

string ConnectionString = "server=localhost;database=dbTest;uid=sa;pwd=sa";
SqlConnection Connect = new SqlConnection(ConnectionString);
string strSelectSQL = "Select count(tblTest.Id) From tblTest";
SqlCommand Command = new SqlCommand(strSelectSQL, Connect);
Connect.Open();
int count = (int)Command.ExecuteScalar();
Connect.Close();
// ...

}

 

- Query 2 
// ExecuteReader // forward-only stream
public void Quering2()
{

string ConnectionString = "server=localhost;database=dbTest;uid=sa;pwd=sa";
SqlConnection Connect = new SqlConnection(ConnectionString);
string strSelectSQL = "Select tblTest.Id, tblTest.col2 From tblTest";
SqlCommand Command = new SqlCommand(strSelectSQL, Connect);
Connect.Open();
SqlDataReader Reader= Command.ExecuteReader();// forward-only stream

while(Reader.Read())
{

string strId = Reader["Id"].ToString();
string strcol2 = Reader["col2"].ToString();
Console.WriteLine("{0}:{1}", strId, strcol2);

}

Connect.Close();

}

- 예외 처리 

- 기타 

DataSet 과 DataAdapter
- 비 연결성 Data 조작 제공

- Query 3 
// SqlDataAdapter  &  DataSet

public void Quering3()

{

 string ConnectionString = "server=localhost;database=dbTest;uid=sa;pwd=sa";
 SqlConnection Connect = new SqlConnection(ConnectionString);
 string strSelectSQL = "Select tblTest.Id, tblTest.col2 From tblTest";
 SqlCommand Command = new SqlCommand(strSelectSQL, Connect);
 DataSet ds = new DataSet();
 SqlDataAdapter aDataAdapter = new SqlDataAdapter(strSelectSQL,Connect);
 Connect.Open();
 aDataAdapter.Fill(ds);
 Connect.Close();

 foreach(DataTable aTable in ds.Tables)
 {
  foreach(DataRow aRow in aTable.Rows)
  {
   string strId = aRow["Id"].ToString().Trim();
   string strcol2 = aRow["col2"].ToString().Trim();
   Console.WriteLine("{0}:{1}", strId, strcol2);
  }
 }
}