https://docs.microsoft.com/ko-kr/dotnet/csharp/tutorials/attributes

 

특성 - C#

C#에서 특성이 작동하는 방식을 알아봅니다.

docs.microsoft.com

사용안하는 메소드 표시 방법

[Obsolete]
public class MyClass
{

}

 

[Obsolete("ThisClass is obsolete. Use ThisClass2 instead.")]
public class ThisClass
{

}

 

https://docs.microsoft.com/ko-kr/nuget/tools/package-manager-ui

c#에서 Json 파싱하기

NuGet 패키지 를 통해서 설치하기

 

설치 하 고 Visual Studio에서 NuGet 패키지 관리

Visual Studio에서 NuGet 패키지 관리자 UI를 사용 하 여 NuGet 패키지 사용에 대 한 지침입니다.

docs.microsoft.com

비주얼 스튜디오에서  Nuget 패키지 관리자 실행

Json.NET

Serialize JSON

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
//   "Name": "Apple",
//   "Expiry": "2008-12-28T00:00:00",
//   "Sizes": [
//     "Small"
//   ]
// }

Deserialize JSON

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys

LINQ to JSON

JArray array = new JArray();
array.Add("Manual text");
array.Add(new DateTime(2000, 5, 23));

JObject o = new JObject();
o["MyArray"] = array;

string json = o.ToString();
// {
//   "MyArray": [
//     "Manual text",
//     "2000-05-23T00:00:00"
//   ]
// }

파싱예제

아래와 같은 JSON 형태

"class": "go.GraphLinksModel",
  "linkKeyProperty": "stepId",
  "modelData": {"position":"-5 -5"},
  "nodeDataArray": [ 
{"key":11, "category":"start", "text":"Start", "loc":"288 109"},
{"key":101, "category":"message", "text":"Message", "items":[ {"name":"Name", "value":"Message"},{"name":"Type", "value":"Step"},{"name":"Category", "value":"대분류"},{"name":"Size", "value":"120"},{"name":"Max Length", "value":"20"} ], "loc":"292 181"}
 ],
  "linkDataArray": [ {"from":11, "to":101, "stepId":-1, "items":[ {"name":"link", "value":"value1"},{"name":"propery1", "value":"value1"} ], "points":[288,129.5,288,139.5,288,147.1257080078125,292,147.1257080078125,292,154.751416015625,292,164.751416015625]} 

        private void Form1_Load(object sender, EventArgs e)
        {
            string s = this.textBox1.Text;
            //var m = JsonConvert.DeserializeObject<Dictionary<string, object>>(s);
            //if (m.TryGetValue("nodeDataArray", out result))
            //{
            //    var ss = result;
            //}
            //object result = "";

            JObject jo = JObject.Parse(s);
            var a = jo.SelectToken("nodeDataArray");
            var cnt = a.Count();
            foreach (var item in a)
            {
                var key = item.SelectToken("key").ToString();
                var category = item.SelectToken("category").ToString();
                var text = item.SelectToken("text").ToString();
                var items = item.SelectToken("items");

                if(items != null)
                {
                    foreach (var token in items)
                    {
                        var name = String.Format("{0}", token.SelectToken("name"));
                        var value = String.Format("{0}", token.SelectToken("value"));
                    }
                }
            }

        }

 

 

오픈소스를 이용해서 RTF 문서를 HTML로 변경합니다.

 

소스경로

http://www.codeproject.com/Articles/27431/Writing-Your-Own-RTF-Converter

 

변경가능한 항목

image

 

소스 내 구성된 프로젝트

image 

 

샘플실행

image

 

여기서 좋은점은 RTF 파일에 붙여넣기 또는 삽입한 이미지를 추출 할 수 있다.

image

 

 private void ToHtmlButtonClick(object sender, EventArgs e)
        {
            try
            {
                IRtfDocument rtfDocument = RtfInterpreterTool.BuildDoc(ConversionText);
                RtfHtmlConverter htmlConverter = new RtfHtmlConverter(rtfDocument);
                textBox.Text = htmlConverter.Convert();
                var q = htmlConverter.DocumentImages;

                // logger
                RtfInterpreterListenerFileLogger logger =
                   new RtfInterpreterListenerFileLogger(@"c:\temp\RtfInterpreter.log");

                // image converter
                // convert all images to JPG
                RtfVisualImageAdapter imageAdapter = new RtfVisualImageAdapter(ImageFormat.Jpeg);
                RtfImageConvertSettings imageConvertSettings =
                        new RtfImageConvertSettings(imageAdapter);
                imageConvertSettings.ImagesPath = @"c:\temp\images\";
                imageConvertSettings.ScaleImage = true; // scale images
                RtfImageConverter imageConverter = new RtfImageConverter(imageConvertSettings);

                // interpreter
                RtfInterpreterTool.Interpret(ConversionText, logger, imageConverter);
                //RtfInterpreterTool.Interpret(rtfStream, logger, imageConverter);
            }
            catch (Exception exception)
            {
                MessageBox.Show(this, "Error " + exception.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        } // ToHtmlButtonClick

 

끝.

 RicherTextBox  편집양식 그대로 저장하기 위한 예제 입니다. 이미지도 같이 저장되게요...

RicherTextBox  의 RTF 구조를 데이터 베이스에 byte 형태로 저장해서 불러온다.

일단 http://www.codeproject.com/Articles/24443/RicherTextBox 가서

 

RicherTextBox   편집기 하나를 받았다.

 

여기에 RTF 저장 및 불러 오기만 구현했음

 

RicherTextBox_demo_jaedoo.zip


*데이터베이스 저장은 MDF (MS -SQL) 와 엔티티6으로 저장하였습니다.

목록조회

 private void button2_Click(object sender, EventArgs e)

{
    Database1Entities entities = new Database1Entities();
    list = entities.TestTable.ToList();
    this.dataGridView1.DataSource = list;
}



등록화면

붙여넣기도 됨

 

저장하기 소스

private void RicherTextBox1_dbSaveClick_click(object sender, string Rtf)
{
    Database1Entities entities = new Database1Entities();
    TestTable tt = new TestTable();
    RichTextBox rt = sender as RichTextBox;
    tt.Contents = rt.Text;
    ASCIIEncoding encoding = new ASCIIEncoding();
 
    byte[] array = encoding.GetBytes(Rtf);
    tt.ObjectContents = array;
    tt.CreateDate = DateTime.Now;
    entities.TestTable.Add(tt);
    entities.SaveChanges();
 
    MessageBox.Show("등록완료");
    this.DialogResult = DialogResult.OK;
    this.Close();
}

불러오기

더블클릭해서 불러온상태

private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    TestTable tt = list[e.RowIndex] as TestTable;
 
    Form2 mf = new Form2(tt);
    if (mf.ShowDialog() == DialogResult.OK)
    {
        button2.PerformClick();
    }
}
 
private void Form2_Load(object sender, EventArgs e)
{
    richerTextBox1.dbSaveClick_click += RicherTextBox1_dbSaveClick_click;
 
    if (this.tt != null)
    {
     
        byte[] contentBytes = tt.ObjectContents;
        richerTextBox1.SetByteText(contentBytes);
    }
}


오라클 클라이언트 드라이버등등 기타 여러가지의 이유로 32비트 DLL이 실행되어야하는 경우가 있다 이때 설정하는 방법

 

image

 

image

 

 

image

너무간단해서 소스참고

    public partial class EnumFrm : Form
    {
        public enum UserLevel { Guest = -1, User = 0, Admin = 1 };

        public EnumFrm()
        {
            InitializeComponent();
            
            //enum 을 바인딩한다.
            this.c1Combo1.DataSource = Enum.GetNames(typeof(UserLevel));
        }

        private void c1Button1_Click(object sender, EventArgs e)
        {
            //콤보박스의 enum 값을 가져온다.
            var result = Enum.Parse(typeof(UserLevel), c1Combo1.SelectedText,false);
        }
    }

GroupBox내에 있는 라디오 버튼의 체크된 값(Tag)을 가지고 온다.

매번 가져오기 귀찮아서 ㅡ_ㅡ;

image

namespace WindowsFormsApplication1
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
            this.groupBox1.SetRadioBoxValue("0001"); //값 세팅
        }

        private void button1_Click(object sender, EventArgs e)
        {
           var q= this.groupBox1.GetRadioBoxValue(); //체크된 박스의 tag값 읽어오기
           this.c1TextBox1.Text = q.ToString();
        }
    }
}

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public static class ControlExtention
    {
        /// <summary>
        /// Tag로 세팅된 값을 읽어온다.
        /// </summary>
        /// <param name="groupBox">The group box.</param>
        /// <returns></returns>
        public static object GetRadioBoxValue(this GroupBox groupBox)
        {
            try
            {
                foreach (Control item in groupBox.Controls)
                {
                    if (item.GetType() == typeof(RadioButton))
                    {
                        if (((RadioButton)item).Checked)
                        {
                            return item.Tag.ToString();
                        }
                    }
                }

                return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Tag로 세팅된 저장한다.
        /// </summary>
        /// <param name="groupBox">The group box.</param>
        /// <returns></returns>
        public static void SetRadioBoxValue(this GroupBox groupBox , string tagValue)
        {

                foreach (Control item in groupBox.Controls)
                {
                    if (item.GetType() == typeof(RadioButton))
                    {
                        if (((RadioButton)item).Tag.ToString() == tagValue )
                        {
                            ((RadioButton)item).Checked = true;
                            return;
                        }
                    }
                }
            
        }//End For


    }
}

확장메서드

http://msdn.microsoft.com/ko-kr/library/bb383977.aspx

c#

image

아래와 같이 생성

            string controlName = "WindowsFormsApplication1.UserControl1"; 

            Assembly assembly = Assembly.GetExecutingAssembly();
            Type t = assembly.GetType(controlName);

            UserControl obj = (UserControl)Activator.CreateInstance(t);
 

프로젝트가 다른경우! 아래와 같이 처리한다.

image

void Form2_Load(object sender, EventArgs e)
{

    string controlName = "ClassLibrary1.UserControl1";
    string dllPath = string.Format("{0}\\{1}", 
Application.StartupPath, "ClassLibrary1.dll"); System.Runtime.Remoting.ObjectHandle oh
= Activator.CreateInstanceFrom(dllPath, "ClassLibrary1.UserControl1"); ClassLibrary1.UserControl1 st = (ClassLibrary1.UserControl1)oh.Unwrap(); st.TestMethod(); }
 
 

WPF

  string fullUri = string.Format("{0};component\\{1}.xaml", assamName, userControlName);
  var p = (UserControl)System.Windows.Application.LoadComponent(
                   new Uri(fullUri, System.UriKind.RelativeOrAbsolute));

 

List<T>로 다 되지만 이런게 있다고 알아두자

Queue, Stack 로 나름 장점이 있음 ㅋ

 

      List<string> list = new List<string>();
            list.Add("kojaedoo1");
            list.Add("kojaedoo2");
            list.Add("kojaedoo3");
            list.Add("kojaedoo4");

            Console.WriteLine("List--------------------------------");
            for (int i = list.Count-1; 0 <= i; i--)
            {
                Console.WriteLine(list[i]);
                //list.RemoveAt(i); //항목 제거하기
            
            }
            list.Reverse();
            Console.WriteLine("List Reverse-------------------------");
            for (int i = list.Count - 1; 0 <= i; i--)
            {
                Console.WriteLine(list[i]);

            }

            //개체의 선입선출(FIFO) 컬렉션을 나타냅니다.
            Queue<string> jobQueue = new Queue<string>();
            jobQueue.Enqueue("kojaedoo1");
            jobQueue.Enqueue("kojaedoo2");
            jobQueue.Enqueue("kojaedoo3");
            jobQueue.Enqueue("kojaedoo4");


          

            Console.WriteLine("Queue--------------------------------");
            for (int i = jobQueue.Count; 0 < jobQueue.Count; i--)
            {
                Console.WriteLine(jobQueue.Dequeue()); //Queue에서 개체를 제거하면서 반환
            }




            //개체의 LIFO(후입선출) 컬렉션을 나타냅니다.
            Stack<string> numbers = new Stack<string>();
            numbers.Push("kojaedoo1");
            numbers.Push("kojaedoo2");
            numbers.Push("kojaedoo3");
            numbers.Push("kojaedoo4");
            numbers.Push("kojaedoo5");

            Console.WriteLine("Stack--------------------------------");
            for (int i = numbers.Count; 0 < numbers.Count; i--)
            {
                Console.WriteLine(numbers.Pop()); //Stack에서 개체를 제거하면서 반환
            }

+ Recent posts