2013년 1월 25일 금요일

C# 프로그램 실행경로 알아 내기


C#에서 현재 경로를 알아내는 방법은 여러가지가 있다.
  • System.Environment.CurrentDirectory
  • System.IO.Directory.GetCurrentDirectory()
  • Application.StartupPath
위의 각 방법들에 대해서 살펴보자.

1. System.Environment.CurrentDirectory
가장 쉽게 현재 실행 경로를 알아낼 수 있는 방법이다. 하지만 이 방법은 Register에 등록된 프로그램으로 실행되면 다른 값을 출력한다. 이때는 3번 Application.StartupPath를 이용해야 한다.
루트일 경우에는 ‘\’ 반환, 그 외의 경우에는 폴더명까지만 반환한다. 다음은 호출하였을 경우의 결과 값이다.

2. System.IO.Directory.GetCurrentDirectory()
1번과 동일하다.

3. Application.StartupPath
위의 Register에 등록되었을 때도 정상적으로 자신의 시작 경로를 반환한다. 하지만 이는 Window Forms를 사용할 때만 Application 클래스를 사용할 수 있기 때문에 Console 기반 혹은, 클래스 라이브러리 기반에서는 사용이 불가능하다.

Tip. Application.ExecutablePath
현재 실행된 어플리케이션의 실행 파일의 위치이다. 이 정보는 현재 경로가 아니기 때문에 변경되지 않는다. 다음은 호출하였을 경우의 결과 값이다.

위의 방법들을 조합하여 가져올 수 있다.

2013년 1월 24일 목요일

vsto outlook MAPIFolder getfolder

vsto outlook MAPIFolder getfolder



Util.subFolder(this.Application, "\\\\test1\\폴더99\\서브폴더99", "서브폴더999");



public static Microsoft.Office.Interop.Outlook.MAPIFolder GetMFolder(string folderPath, Microsoft.Office.Interop.Outlook.Folders folders)
        {
            //string dir = folderPath.Substring(0, folderPath.Substring(4).IndexOf("\\") + 4);
            string dir = folderPath.Substring(0, folderPath.Substring(7).IndexOf("\\") + 7); //\\test1 길이만큼 7
            try
            {
                foreach (Microsoft.Office.Interop.Outlook.MAPIFolder mf in folders)
                {
                    if (!(mf.FullFolderPath.StartsWith(dir))) continue;
                    if (mf.FullFolderPath == folderPath) return mf;
                    else
                    {
                        Microsoft.Office.Interop.Outlook.MAPIFolder temp = GetMFolder(folderPath, mf.Folders);
                        if (temp != null)
                            return temp;
                    }
                }
                return null;
            }
            catch { return null; }
        }



//서브 폴더만들기
        public static bool subFolder(Outlook.Application application, string targetfolder, string foldername)
        {
            bool ret = false;
            Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
            Microsoft.Office.Interop.Outlook.Folder fShareFolder = getFolder(nameSpace.Folders, "test1");
            Outlook.MAPIFolder folderInbox = fShareFolder;

            //Outlook.Folders inboxFolders = folderInbox.Folders;
            Microsoft.Office.Interop.Outlook._Folders oFolders;
            oFolders = folderInbox.Folders;
            Microsoft.Office.Interop.Outlook.MAPIFolder findFolder = null;
            findFolder = GetMFolder(targetfolder, fShareFolder.Folders);          
            Outlook.Folders inboxFolders = findFolder.Folders;
            Outlook.MAPIFolder subfolderInbox = null;

            try
            {
                subfolderInbox = inboxFolders.Add(foldername, Outlook.OlDefaultFolders.olFolderInbox);
                ret = true;
            }
            catch (COMException exception)
            {
                //if (exception.ErrorCode == -2147352567)
                //    //  Cannot create the folder.
                //    System.Windows.Forms.MessageBox.Show(exception.Message);
            }
            if (subfolderInbox != null) Marshal.ReleaseComObject(subfolderInbox);
            if (inboxFolders != null) Marshal.ReleaseComObject(inboxFolders);
            if (folderInbox != null) Marshal.ReleaseComObject(folderInbox);
            if (nameSpace != null) Marshal.ReleaseComObject(nameSpace);
            return ret;
        }




private MAPIFolder GetFolder(string folderPath, Folders folders)
{
    string dir = folderPath.Substring(0, folderPath.Substring(4).IndexOf("\\") + 4);
    try
    {
        foreach (MAPIFolder mf in folders)
        {
            if (!(mf.FullFolderPath.StartsWith(dir))) continue;
            if (mf.FullFolderPath == folderPath) return mf;
            else
            {
                MAPIFolder temp = GetFolder(folderPath, mf.Folders);
                if (temp != null)
                    return temp;
            }
        }
        return null;
    }
    catch { return null; }
}

C# sqlserverce create database / table




How to create a SQL Server CE 3.5 database utilisting a .NET CF 3.5 extension method:
1. Add a semi colon delimited resource file to your .NET CF mobile project.
  1. CREATE TABLE OrderHeader(  
  2. [ID] uniqueidentifier not null,  
  3. [CustomerID] uniqueidentifier not null,  
  4. [ReqestedDlvryDate] datetime not null,  
  5. [Comments] nvarchar(1000),  
  6. [CreateDate] datetime not null,  
  7. [CreatedByID] uniqueidentifier not null,  
  8. [LastEditDate] datetime null,  
  9. [LastEditBy] uniqueidentifier not null,  
  10. CONSTRAINT [PK_OrderHeader] PRIMARY KEY  ( [ID] )  
  11. );  
  12.   
  13. CREATE TABLE OrderDetail(  
  14. [ID] uniqueidentifier not null,  
  15. [OrderID] uniqueidentifier not null,  
  16. [ProductID] uniqueidentifier not null,  
  17. [Qty] int not null,  
  18. CONSTRAINT [PK_OrderDetail] PRIMARY KEY  ( [ID] ),  
  19. CONSTRAINT [FK_OrderHeader] FOREIGN KEY([OrderID]) REFERENCES [OrderHeader]([ID])  
  20. );  
2. Add an extension method on System.Data.SqlServerCE.SqlCeEngine to create the
database based on the semi colon delimited string passed in from the resorce file:
  1. using System;  
  2. using System.Data;  
  3. using System.Data.Common;  
  4. using System.Data.SqlServerCe;  
  5. using System.Collections.Generic;  
  6. using System.IO;  
  7. using System.Linq;  
  8. using System.Text;  
  9.   
  10. namespace SQLCEDatabaseDemo.ExtensionMethods  
  11. {  
  12.     public static class Extensions   
  13.     {  
  14.         public static bool CreateDatabase(this SqlCeEngine sqlceDB, string commands)   
  15.         {   
  16.             bool success = false;   
  17.             SqlCeConnection sqlCon = null;   
  18.             try   
  19.             {   
  20.                 sqlCon = new SqlCeConnection(sqlceDB.LocalConnectionString);   
  21.                 if (!System.IO.File.Exists(sqlCon.DataSource))   
  22.                 {   
  23.                     sqlceDB.CreateDatabase();   
  24.                     sqlCon.Open();   
  25.                     string[] sqlStatements = commands.Split(';');   
  26.                     SqlCeCommand cmd = sqlCon.CreateCommand();   
  27.                       
  28.                     foreach (string cmdText in sqlStatements)   
  29.                     {   
  30.                         if (!String.IsNullOrEmpty(cmdText.Trim()))   
  31.                         {   
  32.                             cmd.CommandText = cmdText; cmd.ExecuteNonQuery();   
  33.                         }   
  34.                     } success = true;   
  35.                 }   
  36.             }   
  37.             finally   
  38.             {   
  39.                 if (sqlCon != null)   
  40.                 {   
  41.                     sqlCon.Close(); sqlCon.Dispose();   
  42.                 }   
  43.             } return success;   
  44.         }   
  45.           
  46.         public static void DeleteDatabase(this SqlCeEngine sqlceDB, string path)   
  47.         {   
  48.             System.IO.File.Delete(path);   
  49.         }   
  50.     }  
  51. }  
3. Execute using the following code
  1. string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);  
  2. string con = String.Format("data source='{0}\\testdb.sdf'; mode=Exclusive;", path);  
  3. using(System.Data.SqlServerCe.SqlCeEngine eng = new System.Data.SqlServerCe.SqlCeEngine(con))  
  4. {  
  5.     if (eng.CreateDatabase(Properties.Resources.CreateSchema))  
  6.     {      
  7.         MessageBox.Show("DB created successfully");  
  8.     }  
  9. }  

http://www.nickharris.net/2010/03/how-to-create-a-sqlceengine-createdatabase-extension-method-using-the-net-compact-framework-3-5-and-sql-compact-edition-3-5/