Showing posts with label CSharp. Show all posts
Showing posts with label CSharp. Show all posts
2011/10/14
C#에서 SQLite 사용하기
C#에 대해서 잘 알지는 못하고 요즘 조금 관심을 두고 있는데 C#의 데이터베이스 관련하여 모르는 상태에서 SQLite 의 예제와 관련 정보를 찾아 SQLite를 연결하여 테스트 해 보았다.
우선 C#에서 SQLite를 사용하려면 아래 사이트를 통해 개발 환경에 맞는 파일을 다운 받아야 한다.
System.Data.SQLite Download Page
내려받은 파일들 중 System.Data.SQLite.dll 와 System.Data.SQLite.Linq.dll 을 Add Reference... 를 통해 추가한다. 테스트에 사용한 코드는 아래와 같다.
C#은 C++ 에서의 방법과 많이 다른 것 같다. 효과적으로 사용하기 위해서는 C#의 데이터베이스에 대한 공부가 필요할 것 같다.&
Original Post : http://neodreamer-dev.tistory.com/595
우선 C#에서 SQLite를 사용하려면 아래 사이트를 통해 개발 환경에 맞는 파일을 다운 받아야 한다.
System.Data.SQLite Download Page
내려받은 파일들 중 System.Data.SQLite.dll 와 System.Data.SQLite.Linq.dll 을 Add Reference... 를 통해 추가한다. 테스트에 사용한 코드는 아래와 같다.
string strQuery;
textResult.Text = "Begin...\n";
SQLiteConnectionStringBuilder SQLiteConString
= new SQLiteConnectionStringBuilder();
SQLiteConString.DataSource = "test.db";
SQLiteConnection SQLite3Con
= new SQLiteConnection(SQLiteConString.ToString());
SQLite3Con.Open();
bool bPrevStepSuccess = false;
textResult.AppendText(" Try to connect with test.db ...");
if (SQLite3Con.State == ConnectionState.Open)
{
textResult.AppendText("OK\n");
// 테이블 생성
strQuery = "CREATE TABLE IF NOT EXISTS TestTable ("
+ " name VARCHAR(20)"
+ " ,age int"
+ " ,country VARCHAR(20)"
+ ")";
SQLiteCommand SQLite3Cmd = SQLite3Con.CreateCommand();
SQLite3Cmd.CommandText = strQuery;
try
{
SQLite3Cmd.ExecuteNonQuery();
textResult.AppendText(" Test Table Create ... OK\n");
bPrevStepSuccess = true;
}
catch (System.Data.SQLite.SQLiteException ex)
{
int nResult = SQLite3Con.ResultCode();
textResult.AppendText(" Test Table Create ... FAIL, Error Msg : "
+ ex.Message + "\n");
bPrevStepSuccess = false;
}
if (bPrevStepSuccess)
{
// Insert
textResult.AppendText(" Inserting ...\n");
strQuery = "INSERT INTO TestTable (name, age, country) VALUES (?,?,?);";
SQLite3Cmd.CommandText = strQuery;
SQLiteParameter paramName = SQLite3Cmd.CreateParameter();
SQLite3Cmd.Parameters.Add(paramName);
SQLiteParameter paramAge = SQLite3Cmd.CreateParameter();
SQLite3Cmd.Parameters.Add(paramAge);
SQLiteParameter paramCountry = SQLite3Cmd.CreateParameter();
SQLite3Cmd.Parameters.Add(paramCountry);
for (int i = 0; i < 10; ++i)
{
paramName.Value = "Name " + i.ToString();
paramAge.Value = 20 + i;
paramCountry.Value = "None";
int InsertRow = SQLite3Cmd.ExecuteNonQuery();
if (InsertRow == 1)
{
textResult.AppendText(" Insert ... OK\n");
}
else
{
textResult.AppendText(" Insert ... FAIL\n");
}
}
strQuery = "SELECT COUNT(*) FROM TestTable;";
SQLite3Cmd.Parameters.Clear();
SQLite3Cmd.CommandText = strQuery;
using (SQLiteDataReader SQLite3Reader = SQLite3Cmd.ExecuteReader())
{
if (SQLite3Reader.Read())
{
string strRow = " Row Count ... "
+ SQLite3Reader.GetValue(0).ToString() + "\n";
textResult.AppendText(strRow);
}
}
// Selecting
textResult.AppendText(" Selecting ...\n");
strQuery = "SELECT * FROM TestTable;";
SQLite3Cmd.Parameters.Clear();
SQLite3Cmd.CommandText = strQuery;
using (SQLiteDataReader SQLite3Reader = SQLite3Cmd.ExecuteReader())
{
while (SQLite3Reader.Read())
{
string strRow = " "
+ SQLite3Reader.GetValue(0).ToString() + " "
+ SQLite3Reader.GetValue(1).ToString() + " "
+ SQLite3Reader.GetValue(2).ToString()
+ "\n";
textResult.AppendText(strRow);
}
}
// Updating...
textResult.AppendText(" Updating ...\n");
strQuery = "UPDATE TestTable SET country=@country WHERE age<@age;";
SQLite3Cmd.CommandText = strQuery;
paramCountry.ParameterName = "@country";
paramCountry.Value = "KOREA";
SQLite3Cmd.Parameters.Add(paramCountry);
paramAge.ParameterName = "@age";
paramAge.Value = 25;
SQLite3Cmd.Parameters.Add(paramAge);
int nUpdated = SQLite3Cmd.ExecuteNonQuery();
string strMsg = " Updated Row(s) Count ... "
+ nUpdated.ToString() + "\n";
textResult.AppendText(strMsg);
// Deleting...
textResult.AppendText(" Deleting ...\n");
strQuery = "DELETE FROM TestTable WHERE age < @age;";
SQLite3Cmd.Parameters.Clear();
SQLite3Cmd.CommandText = strQuery;
paramAge.ParameterName = "@age";
paramAge.Value = 25;
SQLite3Cmd.Parameters.Add(paramAge);
int nDeleted = SQLite3Cmd.ExecuteNonQuery();
strMsg = " Deleted Row(s) Count ... "
+ nDeleted.ToString() + "\n";
textResult.AppendText(strMsg);
// Drop Table
strQuery = "DROP TABLE IF EXISTS TestTable;";
SQLite3Cmd.Parameters.Clear();
SQLite3Cmd.CommandText = strQuery;
SQLite3Cmd.ExecuteNonQuery();
textResult.AppendText(" Test Table dropped ... OK\n");
}
}
else
{
textResult.AppendText("FAIL\n");
}
SQLite3Con.Close();
textResult.AppendText("Finish.");
C#은 C++ 에서의 방법과 많이 다른 것 같다. 효과적으로 사용하기 위해서는 C#의 데이터베이스에 대한 공부가 필요할 것 같다.&
Original Post : http://neodreamer-dev.tistory.com/595
Labels:
c#
,
CSharp
,
SQLite
,
System.Data.SQLite
,
TistoryOldPost
2011/10/11
[C#] Form App 의 System Menu에 사용자 메뉴 추가하기
C#의 Windows Form Application에서 System 메뉴에 사용자 메뉴를 추가하는 방법이다. 인터넷을 통해 알게된 방법으로 Add System Menu Items to a Form using Windows API 글을 보고 알게 되었다. C# 에서의 Win32 API 사용과 메세지 핸들링에 대한 지식을 알고 있어야 겠다. C++에서는 API 사용이 쉬웠는데 그 C#에서는 다소 복잡해 보인다.
<
Original Post : http://neodreamer-dev.tistory.com/587
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
// For Custom System Menu
// using System;
// using System.Windows.Forms;
// using System.Runtime.InteropServices;
namespace MyFormApp
{
public partial class frmMain : Form
{
#region Win32 API Stuff
// Define the Win32 API methods we are going to use
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern bool InsertMenu(IntPtr hMenu, Int32 wPosition,
Int32 wFlags, Int32 wIDNewItem, string lpNewItem);
/// Define our Constants we will use
public const Int32 WM_SYSCOMMAND = 0x112;
public const Int32 MF_SEPARATOR = 0x800;
public const Int32 MF_BYPOSITION = 0x400;
public const Int32 MF_STRING = 0x000;
#endregion
// The constants we'll use to identify our custom system menu items
public const Int32 _SettingsSysMenuID = 1000;
public const Int32 _AboutSysMenuID = 1001;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
/// Get the Handle for the Forms System Menu
IntPtr systemMenuHandle = GetSystemMenu(this.Handle, false);
/// Create our new System Menu items just before the Close menu item
// Add a menu seperator
InsertMenu(systemMenuHandle, 5, MF_BYPOSITION | MF_SEPARATOR,
0, string.Empty);
// Add Settings Menu
InsertMenu(systemMenuHandle, 6, MF_BYPOSITION,
_SettingsSysMenuID, "Settings...");
// Add About Menu
InsertMenu(systemMenuHandle, 7, MF_BYPOSITION,
_AboutSysMenuID, "About...");
}
protected override void WndProc(ref Message m)
{
// Check if a System Command has been executed
if (m.Msg == WM_SYSCOMMAND)
{
/// Execute the appropriate code for
/// the System Menu item that was clicked
switch (m.WParam.ToInt32())
{
case _SettingsSysMenuID:
MessageBox.Show("\"Settings\" was clicked");
break;
case _AboutSysMenuID:
MessageBox.Show("\"About\" was clicked");
break;
}
}
base.WndProc(ref m);
}
}
}
실행 결과 화면
Original Post : http://neodreamer-dev.tistory.com/587
Labels:
c#
,
CSharp
,
Form Programing
,
TistoryOldPost
,
폼프로그래밍
2011/08/19
[C#] XML 다루는 간단한 소스
C#을 공부하면서 XML 다루게 되면서 알게된 내용으로 기록용으로 정리해 보았다.
아래 소스는 간단하게 XML 데이터를 저장하고 읽어들이는 소스이다.
XmlDocument 나 XmlNode Class 에는 위의 코드에서 사용한 것 보다 더 많은 기능을 갖고 있다. 자세한 기능들에 대해서는 따로 공부를 해 봐야 겠다.
&
Original Post : http://neodreamer-dev.tistory.com/566
아래 소스는 간단하게 XML 데이터를 저장하고 읽어들이는 소스이다.
// Writting
XmlDocument xmlDoc = new XmlDocument();
XmlNode nodeItems = xmlDoc.CreateNode("element", "Items", "");
foreach (ListViewItem item in ListView.Items)
{
XmlNode nodeItem = xmlDoc.CreateNode("element", "Item", "");
XmlNode nodeFind = xmlDoc.CreateNode("element", "Find", "");
nodeFind.InnerText = "...";
XmlNode nodeReplace = xmlDoc.CreateNode("element", "Replace", "");
nodeReplace.InnerText = "...";
nodeItem.AppendChild(nodeFind);
nodeItem.AppendChild(nodeReplace);
nodeItems.AppendChild(nodeItem);
}
xmlDoc.AppendChild(nodeItems);
xmlDoc.Save(saveFileDialog.FileName);
<Items>
<Item>
<Find>a1</Find>
<Replace>b1</Replace>
</Item>
<Item>
<Find>a2</Find>
<Replace>b2</Replace>
</Item>
</Items>
// Reading
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(openFileDialog.FileName);
XmlNode nodeItems = xmlDoc.FirstChild;
foreach (XmlNode nodeItem in nodeItems)
{
string strFind = nodeItem.FirstChild.InnerText;
string strReplace = nodeItem.LastChild.InnerText;
}
XmlDocument 나 XmlNode Class 에는 위의 코드에서 사용한 것 보다 더 많은 기능을 갖고 있다. 자세한 기능들에 대해서는 따로 공부를 해 봐야 겠다.
&
Original Post : http://neodreamer-dev.tistory.com/566
2011/07/28
[C#] Form 디자이너 클래스는 가장 먼저 선언 되어야 하네...
메인 폼의 클래스 위에 습관처럼 다른 클래스는 선언 하였다. 그리고 Form 디자인 창을 열었더니 아래와 같은 에러 메시지를 만났다.
"The class frmMain can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file. Move the class code so that it is the first class in the file and try loading the designer again."
C++에서의 습관으로 메인 클래스 위에 다른 작은 구조체나 클래스를 선언하여 사용하였는데 Windows Form을 사용하는 C# 프로그래밍에서는 Visual Studio에서 지원하는 디자이너를 사용하려면 그렇게 사용할 수가 없다. 좀 불편
Original Post : http://neodreamer-dev.tistory.com/558
"The class frmMain can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file. Move the class code so that it is the first class in the file and try loading the designer again."
C++에서의 습관으로 메인 클래스 위에 다른 작은 구조체나 클래스를 선언하여 사용하였는데 Windows Form을 사용하는 C# 프로그래밍에서는 Visual Studio에서 지원하는 디자이너를 사용하려면 그렇게 사용할 수가 없다. 좀 불편
Original Post : http://neodreamer-dev.tistory.com/558
[C#] 경로 요소 분리하기
C++ 에는 _splitpath 라는 멋진 함수가 있어서 전체 경로에서 구성 요소(드라이브, 패스, 파일명, 확장자)를 분리할 수 있었다.
C#에서 이용할 수 있는 함수가 있나 찾아 보았는데 함수는 없고 보다 많은 기능을 포함하고 있는 객체를 찾았다.
System.IO.Path 인데 이 녀석은 경로에 관련한 많은 기능을 담고 있다.
아래 코드는 MSDN에서 발췌해 온 예제 코드 이다.
public static void Main()
{
string path1 = @"c: emp\MyTest.txt";
string path2 = @"c: emp\MyTest";
string path3 = @"temp";
if (Path.HasExtension(path1))
{
Console.WriteLine("{0} has an extension.", path1);
}
if (!Path.HasExtension(path2))
{
Console.WriteLine("{0} has no extension.", path2);
}
if (!Path.IsPathRooted(path3))
{
Console.WriteLine("The string {0} contains no root information.", path3);
}
Console.WriteLine("The full path of {0} is {1}.", path3, Path.GetFullPath(path3));
Console.WriteLine("{0} is the location for temporary files.", Path.GetTempPath());
Console.WriteLine("{0} is a file available for use.", Path.GetTempFileName());
/* This code produces output similar to the following:
* c: emp\MyTest.txt has an extension.
* c: emp\MyTest has no extension.
* The string temp contains no root information.
* The full path of temp is D:\Documents and Settings\cliffc\...\Debug emp.
* D:\Documents and Settings\cliffc\Local Settings\Temp...\ is the location for temporary files.
* D:\Documents and Settings\cliffc\Local Settings\Temp... temp3D.tmp is a file available for use.
*/
}
MSDN의 Path 클래스 설명 페이지 <
Original Post : http://neodreamer-dev.tistory.com/557
Labels:
_splitpath
,
c#
,
CSharp
,
Path Class
,
System.IO.Path
,
TistoryOldPost
[C#] Drag&Drop 으로 파일 받기
특정 컨트롤에서 Drag&Drop 으로 파일을 받으려면 우선 해당 컨트롤의 AllowDrop 옵션을 True로 설정한다.
그리고 컨트롤의 DragOver 와 DragDrop 이벤트 핸들러를 작성한다.
아래 코드는 간단하게 구현 해본 Drag&Drop 이다.
private void lvFiles_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.All;
}
private void lvFiles_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
for (int i = 0; i < files.Count(); ++i)
{
lvFiles.Items.Add(files[i]);
}
string strMsg = files.Count().ToString() + " File(s) dropped!!";
MessageBox.Show(strMsg);
}
<
Original Post : http://neodreamer-dev.tistory.com/555
Labels:
c#
,
CSharp
,
Drag&Drop
,
DragOver
,
TistoryOldPost
2011/07/27
Editplus에 C# 설정하기
C#을 잠깐 보면서 어는 서적이든 처음에 Console 프로그래밍에 대해서 언급을 하고 있는데 이 때문에 덩치큰 Visual Studio를 실행하는 것이 싫어 일반 편집기에서 하는 방법을 알아보았다. 물론 명령줄을 이용하면 되는데 조금 편리하게 사용하기 위해 편집기 옵션을 이용하였다.
Editplus 의 사용자 툴을 등록하고 사용하므로써 편하게 컴파일과 실행을 할 수 있다.
아래 두 툴 설정을 추가하면 된다.
Menu Text: C# Compile
Command: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe
Argument: $(FileName)
Initial Directory: $(FileDir)
Menu Text: C# Run
Command: cmd
Argument: /c $(FileNameNoExt)
Initial Directory: $(FileDir)
위와 같이 설정하면 다른 설정이 없을 경우 Ctrl + 1과 Ctrl + 2로 할당된다.
설정을 마치고 C# 파일을 생성하고 아래와 같은 코드를 입력하였다.
코드를 작성하고 Ctrl + 1로 컴파일하고 Ctrl + 2로 실행을하면 간단한 C# 프로그램을 테스트할 수 있다.
<
Original Post : http://neodreamer-dev.tistory.com/553
Editplus 의 사용자 툴을 등록하고 사용하므로써 편하게 컴파일과 실행을 할 수 있다.
아래 두 툴 설정을 추가하면 된다.
Menu Text: C# Compile
Command: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe
Argument: $(FileName)
Initial Directory: $(FileDir)
Menu Text: C# Run
Command: cmd
Argument: /c $(FileNameNoExt)
Initial Directory: $(FileDir)
위와 같이 설정하면 다른 설정이 없을 경우 Ctrl + 1과 Ctrl + 2로 할당된다.
설정을 마치고 C# 파일을 생성하고 아래와 같은 코드를 입력하였다.
using System;
class MyCSharpApp
{
public static void Main()
{
Console.WriteLine("Hello! C# World");
}
}
코드를 작성하고 Ctrl + 1로 컴파일하고 Ctrl + 2로 실행을하면 간단한 C# 프로그램을 테스트할 수 있다.
<
Original Post : http://neodreamer-dev.tistory.com/553
Subscribe to:
Posts
(
Atom
)