'IT/C#'에 해당되는 글 16건

  1. 2013.03.05 EvnetLog 쓰기
  2. 2013.03.04 .NET Remoting 그리고 동적Query
  3. 2012.09.15 LINQ to DataTable
  4. 2012.08.24 XML을 DataTable로
  5. 2012.08.20 XML과 CLASS 사이의 변환 C#
  6. 2012.06.29 레지스트리에 내용 쓰기

EvnetLog 쓰기

IT/C# 2013. 3. 5. 10:56
try ~ catch 구문과 함께 Exception 발생 시 이벤트로그를 남길 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Diagnostics;
using System.Threading;
 
class MySample{
 
    public static void Main(){
 
        // Create the source, if it does not already exist.
        if(!EventLog.SourceExists("MySource"))
        {
             //An event log source should not be created and immediately used.
             //There is a latency time to enable the source, it should be created
             //prior to executing the application that uses the source.
             //Execute this sample a second time to use the new source.
            EventLog.CreateEventSource("MySource", "MyNewLog");
            Console.WriteLine("CreatedEventSource");
            Console.WriteLine("Exiting, execute the application a second time to use the source.");
            // The source is created.  Exit the application to allow it to be registered.
            return;
        }
 
        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "MySource";
 
        // Write an informational entry to the event log.   
        myLog.WriteEntry("Writing to event log.");
 
    }
}

[출처] http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx MSDN =^^=
Posted by lI헐헐Il
,

http://msdn.microsoft.com/ko-kr/library/system.marshalbyrefobject.aspx#inheritanceContinued

링크 확인 .NET Remoting 관련 MSDN

 

http://blog.daum.net/overview/8721538

동적쿼리

Posted by lI헐헐Il
,

LINQ to DataTable

IT/C# 2012. 9. 15. 13:41
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Bind the System.Windows.Forms.DataGridView object
// to the System.Windows.Forms.BindingSource object.
dataGridView.DataSource = bindingSource;
 
// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);
 
DataTable orders = ds.Tables["SalesOrderHeader"];
 
// Query the SalesOrderHeader table for orders placed
// after August 8, 2001.
IEnumerable<DATAROW> query =
    from order in orders.AsEnumerable()
    where order.Field<DATETIME>("OrderDate") > new DateTime(2001, 8, 1)
    select order;
 
// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DATAROW>();
 
// Bind the table to a System.Windows.Forms.BindingSource object,
// which acts as a proxy for a System.Windows.Forms.DataGridView object.
bindingSource.DataSource = boundTable;
<P>
orders.AsEnumerable()
<P>order.Field("OrderDate") </P>
<P>DataTable boundTable = query.CopyToDataTable();


orders.AsEnumerable()

order.Field("OrderDate")

DataTable boundTable = query.CopyToDataTable();

 

이부분 주목하자. DataTable에 대한 LINQ는 AsEnumerable() 확장 메소드를 통해 DataTable을 열거가능한 형으로 리턴받는다. LINQ로 쿼리해온 데이터는 CopyToDataTable() 메소드를 통해 DataTable로 변환할 수 있다.


 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
DataSet dsProduct = new DataSet();
DataSet dsProductDescription = new DataSet();
 
dsProduct = dbClass.SelectDetail("SELECT ProductID, Name, ProductNumber, ListPrice FROM Production.Product");
dsProductDescription = dbClass.SelectDetail("SELECT ProductDescriptionID, Description FROM Production.ProductDescription");
 
var queryProduct = from order in dsProduct.Tables[0].AsEnumerable()
           join desc in dsProductDescription.Tables[0].AsEnumerable() on order.Field<INT>("ProductID") equals desc.Field<INT>("ProductDescriptionID")
           select new
          {
                ProductID = order.Field<INT>("ProductID"),
                Name = order.Field<STRING>("Name"),
                ProductNumber = order.Field<STRING>("ProductNumber"),
                ListPrice = order.Field<DECIMAL>("ListPrice"),
                Description = desc.Field<STRING>("Description")
           };
 
  foreach (var obj in queryProduct)
  {
         Console.WriteLine("{0}, {1}, {2}, {3}, {4}", obj.ProductID, obj.ProductNumber, obj.Name, obj.ListPrice, obj.Description);
   }

두 개의 IEnumerable<T> 개체를 Join할 수 있다. SQL과 흡사하나 결과를 익명타입으로 받는 점, on 구문 내의 equals등이 다르다.
첨부파일은 MSDN에서 제공하는 C# 101 LINQ Sample이다.

 

101 LINQ Samples.zip

 

Posted by lI헐헐Il
,

XML을 DataTable로

IT/C# 2012. 8. 24. 16:40
1
2
3
4
System.Xml.XmlDocument xdoc = new System.Xml.XmlDocument();
xdoc.LoadXml(xml);
XmlNodeList xnl = xdoc.GetElementsByTagName("SessionID");
XmlNodeList OpCode = xdoc.GetElementsByTagName("opcode");

위와 같이 복잡하게 XML을 파싱하지말고, 간단히 DataSet에 DataTable 형태로 정리해보자.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.Data;
using System.IO;
using System.Xml;
 
namespace XML2DataTable
{
    class Program
    {
        String strXml @"<coninfo><header><programcd>S1230</programcd><usrnm>Richard Park</usrnm></header><info><dept>12</dept></info></coninfo>";
        DataSet ds = new DataSet("xmlDS");
        TextReader txtReader = new StringReader(strXML);
        XmlReader reader = new XmlTextReader(txtReader);
        ds.ReadXml(reader);
 
        string strXmlElement = ds.Tables["header"].Rows[0]["programcd"].ToString().Trim();
       // []안의 string Index는 대소문자 구분이다.
    }
}


간단하게 Parsing하여 DataTable 형태로 편하게 불러다 쓰자!!

Posted by lI헐헐Il
,

XmlDsigXsltTransform Class

http://msdn.microsoft.com/ko-kr/library/system.security.cryptography.xml.xmldsigxslttransform%28v=VS.90%29.aspx

 

XmlSerializer Class

http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization

 

기본적으로 XML을 Class 형태로 바꾸는 데에는 xds.exe나 XsdObjectGen.exe를 사용한 방법이 있다. 하지만 이는 Runtime에 실행되는 방법은 아니어서 현재의 목적과는 다르다. 위의 XmlDsigXsltTransform은 뭐하는 애인지도 아직 감이 안오고, XmlSerializer는 감은 오지만 미리 해당하는 Class를 선언해두어야하는 녀석이다.

 

Runtime-based로 넘겨받은 XML 메시지에 해당하는 Class를 동적으로 생성해주고, Property 형태로 간단하게 불러쓸 수 있는 방법이 없나 찾고 있다.

Posted by lI헐헐Il
,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
 
namespace Registry_Handle
{
    class Program
    {
        static void Main(string[] args)
        {
            string regSubKey = "Software\\myTestKey";
 
            RegistryKey rk = Registry.LocalMachine.OpenSubKey(regSubKey, true);
 
            if (rk == null)
            {
                rk = Registry.LocalMachine.CreateSubKey(regSubKey);
                 
            }
             
            string[] strData = new string[] { "aaa", "bbb", "ccc" };   
            rk.SetValue("asdfqwer", strData);
            string[] regStr = rk.GetValue("asdfqwer") as string[];
 
            Console.WriteLine(regStr[1]);
            Console.ReadLine();
 
            Registry.LocalMachine.DeleteSubKey(regSubKey);
        }
    }
}
Posted by lI헐헐Il
,