[C#][Maya][Python] Maya commandPort for external communication / 利用 commandPort 命令讓外部程式與 Maya 溝通

December 28th, 2011 Phanix

利用 tcp client connection 或 socket connection 來跟 Maya 溝通
Read the rest of this entry / 繼續閱讀 »

[C#] XMLWriter Encoding Issue / XMLWriter 控制文字編碼

December 26th, 2011 Phanix

一般狀況下,如果不是很在意使用 XMLWriter 後輸出的文字編碼是哪一種的話,可以很簡單地用下面的方式完成

StringBuilder sb = new StringBuilder();
XmlWriter writer = XmlWriter.Create(sb);

writer.WriteStartDocument();
//補上 xml 內容, 用 writer.WriteStartElement() 等完成
writer.WriteEndDocument();

writer.Flush();

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(sb.ToString());

但是可以發現到這樣子所輸出的 XML 文件是變成 UTF-16 encoding。雖然有 XmlWriterSettings 這東西可以去設定 XMLWriter 的編碼,不過看起來好像是有些問題,輸出的 XML 結果依舊是 UTF-16。

解決的方法是用 MemoryStream 與 XMLTextWriter。

MemoryStream stream = new MemoryStream();
XmlWriter writer = new XmlTextWriter(stream, Encoding.UTF8);

writer.WriteStartDocument();
//補上 xml 內容, 用 writer.WriteStartElement() 等完成
writer.WriteEndDocument();

writer.Flush();

StreamReader reader = new StreamReader(stream, Encoding.UTF8, true);
stream.Seek(0, SeekOrigin.Begin);
string result = reader.ReadToEnd();

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(result);

[C#] Unix Timestamp

July 26th, 2011 Phanix

因為 Facebook 上頭記錄時間是用 Unix Timestamp,所以來看一下怎麼做。

Read the rest of this entry / 繼續閱讀 »

C# 處理 facebook JSON Serialized Data

July 19th, 2011 Phanix

當透過 access token 去 facebook 抓取資料時,回傳的資料將以 JSON 的方式編碼,在 C# 裡頭可以用 JavaScriptSerializer 來處理,下面是個很懶惰的處理方式,不需要另外先去設計與宣告一個符合 facebook JSON 格式的 class object 來儲存資料,反正需要的時候再來針對 Key 另外處理即可。

Read the rest of this entry / 繼續閱讀 »

.NET 取得 windows 帳號資訊

June 20th, 2011 Phanix

取得登入帳號

Environment.UserName




取得帳號等有儲存在本機上的資訊

using System.Security.Principal;
using System.Threading;

//-----

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);

WindowsPrincipal myPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;

WindowsIdentity myIdentity = (WindowsIdentity)myPrincipal.Identity;

Console.WriteLine("IdentityType: " + myIdentity.ToString());
Console.WriteLine("Name: {0}", myIdentity.Name);
Console.WriteLine("Member of Users? {0}", myPrincipal.IsInRole(WindowsBuiltInRole.User));
Console.WriteLine("Member of Administrators? {0}", myPrincipal.IsInRole(WindowsBuiltInRole.Administrator));
Console.WriteLine("Authenticated: {0}", myIdentity.IsAuthenticated);
Console.WriteLine("Anonymous: {0}", myIdentity.IsAnonymous);




取得帳號等有儲存在本機上的資訊 – II

使用 Win32 API

using System.Runtime.InteropServices;

//-----
[DllImport("Advapi32.dll", EntryPoint="GetUserName",  ExactSpelling=false, SetLastError=true)]
static extern bool GetUserName([MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer,
						[MarshalAs(UnmanagedType.LPArray)] Int32[] nSize );

//-----
byte[] str = new byte[256];
Int32[] len = new Int32[1];
len[0] = 256;
GetUserName(str, len);
MessageBox.Show(System.Text.Encoding.ASCII.GetString(str));

string a = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

MessageBox.Show(a.ToString());




LDAP

這是可以取得最詳細資訊的方法

using System.DirectoryServices;

//-----

string principal = Environment.UserName;
string filter = string.Format("(&(ObjectClass={0})(sAMAccountName={1}))", "person", principal);
string[] properties = new string[] { "fullname" };

//用匿名登入,理論上LDAP都會允許,但只有 read 權限
DirectoryEntry adRoot = new DirectoryEntry("LDAP://yourdomain.com", null, null, AuthenticationTypes.Secure);
DirectorySearcher searcher = new DirectorySearcher(adRoot);
searcher.SearchScope = SearchScope.Subtree;
searcher.ReferralChasing = ReferralChasingOption.All;
searcher.PropertiesToLoad.AddRange(properties);
searcher.Filter = filter;
SearchResult result = searcher.FindOne();
DirectoryEntry directoryEntry = result.GetDirectoryEntry();

string displayName = directoryEntry.Properties["displayName"][0].ToString();
string firstName = directoryEntry.Properties["givenName"][0].ToString();
string lastName = directoryEntry.Properties["sn"][0].ToString();
string email = directoryEntry.Properties["mail"][0].ToString();
string department = directoryEntry.Properties["department"][0].ToString();
string description = directoryEntry.Properties["description"][0].ToString();

C# window form drawing over other controls / 在 window form 中繪製圖形並疊在控制項上

February 23rd, 2011 Phanix

本文以中英夾雜並陳

This article is interleaved with Chinese and English.

本來還想在網路上看能不能找到答案的, 結果只有找到一些可能的提示… 不過最後還是摸索出來了啦 :D

At the beginning, I hope to scrounge the solution from Internet, but after hours of searching, I only find some possible hints. Anyway, here’s the solution.

Read the rest of this entry / 繼續閱讀 »

C# Windows form 透明 panel (transparent panel)

February 18th, 2011 Phanix
using System.Windows.Forms;

namespace XXX_namespace
{
    ///

    /// A transparent control.
    /// 

    public class TransparentPanel : Panel
    {
        public TransparentPanel()
        {
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams createParams = base.CreateParams;
                createParams.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT
                return createParams;
            }
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            // Do not paint background.
        }
    }
}

Drag a virtual file from C# winform to Explorer and other applications

May 24th, 2010 Phanix

從 c# winform 上拖曳一個 virtual file (比方說一個 label)到 explorer 或其他程式(例如 ultraedit, photoshop)開啟

Read the rest of this entry / 繼續閱讀 »

Calling Managed .NET C# COM Objects from Unmanaged C++

February 8th, 2010 Phanix

從 VC++ 中呼叫 C# 所寫的 COM 物件,主要的可以分成三項需要注意的事情。

1. 怎麼讓 C# class library 在編譯出 DLL 的同時同時產生 COM 物件
2. 怎麼讓系統認得這個這個 COM 物件
3. 怎麼在 VC++ 中用這個 COM 物件

這個網頁裡頭寫得非常清楚,同時還有範例下載。

[C#] Threading with Parameters / 帶參數的執行緒

December 10th, 2009 Phanix

主要有兩種方式,第一種為使用 ParameterizedThreadStart,但是這不是一個安全的方式。第二種方法是將要交給執行緒執行的方法與參數封裝到類別裡頭去,建立該類別的 Instance 之後就可以交給執行緒去執行,以下為 sample code… (另外要注意的是 Threading.Join() 的使用)

using System;
using System.Threading;

//ThreadWithState 類別裡包含執行任務的方法
public class ThreadWithState {
    //要用到的屬性,也就是我們要傳遞的參數
    private string boilerplate;
    private int value;

    //包含參數的 Constructor
    public ThreadWithState(string text, int number)
    {
        boilerplate = text;
        value = number;
    }

    //要丟給執行緒執行的方法,無 return value 就是為了能讓ThreadStart來呼叫
    public void ThreadProc()
    {
        //這裡就是要執行的任務, 只顯示一下傳入的參數
         Console.WriteLine(boilerplate, value);
    }
}

//Main entrance
public class Example {
    public static void Main()
    {
        //實例化ThreadWithState類別,為執行緒提供參數
        ThreadWithState tws = new ThreadWithState(
            "This report displays the number {0}.", 42);

        // 創建執行任務的執行緒,並執行
        Thread t = new Thread(new ThreadStart(tws.ThreadProc));
        t.Start();
        Console.WriteLine("Main thread does some work, then waits.");
        t.Join();
        Console.WriteLine(
            "Independent task has completed; main thread ends.");
    }
}