Archive for the ‘C#’ Category

WPF におけるパッケージの URI

2013年3月9日

http://msdn.microsoft.com/ja-jp/library/vstudio/aa970069.aspx

test.jpg

this.Image1.Source = new BitmapImage(new Uri("pack://application:,,,/test.jpg"));

SqlDataSource.Select

2013年2月5日

http://msdn.microsoft.com/ja-jp/library/system.web.ui.webcontrols.sqldatasource.select.aspx

var x = AccessDataSource1.Select(DataSourceSelectArguments.Empty);
var str = (string)(((System.Data.DataView)(x)).Table.Rows[0][0]);

Compress & Decompress

2013年1月28日

 

using System;
using System.IO;
using System.IO.Compression;

 

// 文字列をバイナリーに符号化し、Base64で変換する

public static string compress(string src)
{
    string encodedString = null;
    byte[] byteArraySource = Encoding.Unicode.GetBytes(src);
    using (var memStream = new MemoryStream())
    using (var compressedStream = new DeflateStream(memStream, CompressionMode.Compress))
    {
        compressedStream.Write(byteArraySource, 0, byteArraySource.Length);
        compressedStream.Close();
        encodedString = System.Convert.ToBase64String(memStream.ToArray());
    }
    return encodedString;
}

// Base64の文字列をバイナリ―に変換し、それを復号化する。

public static string deCompress(string encodedStr)
{
    string decodedString = null;
    byte[] byteArray = System.Convert.FromBase64String(encodedStr);
    using (var memStream = new MemoryStream(byteArray))
    using (var decompressedStream = new DeflateStream(memStream, CompressionMode.Decompress))
    {
        byte[] resBytes = new byte[4096];
        int count = 0;
        int offset = 0;
        while (true)
        {
            count = decompressedStream.Read(resBytes, offset, resBytes.Count() – offset);
            if (count == 0) break;
            offset += count;
            decodedString = Encoding.Unicode.GetString(resBytes);
        }
    }
    string trimStr = decodedString.TrimEnd(new char[]{(char)0});
    return trimStr;
}

ASP.Net 4.0 Routing

2012年12月30日

Global.aspx.cs に RegisterRoutes を追加。

void Application_Start(object sender, EventArgs e)
{
    // アプリケーションのスタートアップで実行するコードです
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    AuthConfig.RegisterOpenAuth();

    RegisterRoutes(RouteTable.Routes);
}

// これは例です。
void RegisterRoutes(RouteCollection routes)
{
    // Register a route for Categories/All
    routes.MapPageRoute(
       "All Categories",      // Route name
       "Categories/All",      // Route URL
       "~/AllCategories.aspx" // Web page to handle route
    );

    // Route to handle Categories/{CategoryName}.
    // The {*CategoryName} instructs the route to match all content after the first slash, which is needed b/c
    //  some category names contain a slash, as in the category "Meat/Produce"
    // See http://forums.asp.net/p/1417546/3131024.aspx for more information
    routes.MapPageRoute(
       "View Category",               // Route name
       "Categories/{*CategoryName}",  // Route URL
       "~/CategoryProducts.aspx"      // Web page to handle route
    );

    // Register a route for Products/{ProductName}
    routes.MapPageRoute(
       "View Product",           // Route name
       "Products/{ProductName}", // Route URL
       "~/ViewProduct.aspx"      // Web page to handle route
    );

    // Register a route for Products/{ProductName}
    routes.MapPageRoute(
       "View Product2",           // Route name
       "Products/Test/{P1}/{P2}/{P3}", // Route URL
       "~/Test.aspx"      // Web page to handle route
    );
}


CategoryProducts.aspx.cs

/Categories/X1/X2/CategoryName とした場合、
data=”X1/X2/CategoryName”となる。

public partial class CategoryProducts : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var data = Page.RouteData.Values["CategoryName"];
    }
}


Test.aspx.cs

/Products/Test/X1/X2/X3 とした場合、
data=”X1”, data2=”X2”, data3=”X3” となる。

protected void Page_Load(object sender, EventArgs e)
{
    var data = Page.RouteData.Values["P1"];
    var data2 = Page.RouteData.Values["P2"];
    var data3 = Page.RouteData.Values["P3"];
}

リソース

2012年10月22日

MSDN リソース ファイルより抜粋

ビルド アクション

  • [リソース]。 このビルド アクションにより、ファイルをプロジェクト アセンブリに埋め込みます。 このオプションはアプリケーション プロジェクトおよびライブラリ プロジェクトで使用でき、アセンブリをアプリケーション パッケージの内部または外部に配置できます。

  • [コンテンツ]。 このビルド アクションでは、ファイルをプロジェクト アセンブリに埋め込まずに、アプリケーション パッケージに含めます。 このオプションは、パッケージ内の複数のアセンブリで共有されるリソース ファイルに対して使用します。

  • None。 このビルド アクションでは、ファイルをアプリケーション パッケージにもアセンブリにも含めません。 このオプションは、オンデマンドで取得するリソース ファイルに対して使用します。 オンデマンド ファイルは通常、サーバー上のアプリケーション パッケージと同じ場所に配置します。

  •  

  • 絶対 URI と相対 URI

  • Silverlight では、絶対 URI と相対 URI をサポートしており、相対 URI を使用したファイル検索のためのフォールバック機構が用意されています。

    絶対 URI ではリソース ファイルの正確な位置を指定するため、フォールバック機構は機能しません。 たとえば、"http://www.contoso.com/resources/OnDemand.png" は指定ドメインのリソース フォルダー内のファイルを表しています。 アプリケーション パッケージのホスト ドメイン以外のドメインに置かれているリソース ファイルを指定するには、絶対 URI を使用する必要があります。

    相対 URI では、アプリケーション ルートまたは参照元の XAML ファイルを基準としたリソース ファイルの相対位置が指定されます。

    アプリケーション ルートを基準とした相対 URI

  • スラッシュで始まる相対 URI は、アプリケーション ルートを基準とした相対位置を表します。 たとえば、"/resources/image.png" と記述します。

    アプリケーション ルートとは、アプリケーション パッケージのルート フォルダー、またはサーバー上のアプリケーション パッケージの場所を指します。 相対 URI のフォールバック機構により、まずアプリケーション パッケージが検索され、次にサーバーが検索されます。 先頭のスラッシュの後ろにパスを含めた場合は、両方の場所で同じフォルダー階層が検索されます。

  • 他のアセンブリの URI

  • 参照元の XAML を格納しているアセンブリ以外のアセンブリに埋め込まれているリソース ファイルを参照することもできます。 この場合、URI 形式は "/assemblyShortName;component/resourceLocation" となります。 たとえば、"/SilverlightLibraryAssembly;component/image.png" と記述します。 先頭のスラッシュと component キーワード (後ろにスラッシュが続く) が必要なことに注意してください。

    他の埋め込みリソースと同様に、この URI 形式では ResourceManager クラスによるフォールバック機構が使用されます。

リソース ディクショナリ

Visual Studio 無しで、XAP ファイルを Windows Phone に配置するには

2012年10月20日

注意:
XAPファイルを Windows Phone に登録するためには、端末のロック解除がひつようです。そのためには、AppHub への登録(有料)が必要です。

開発途中の XAP ファイルを他の人にテストしてもらう際に、Visual Studio をインストールせずに Windows Phone に配置して、動作確認を行うことができます。

  1. Windows Phone SDK 7.1 をインストールします。
  2. Windows Phone をUSBで接続します。
  3. C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Tools\XAP DeploymentのXapDeploy.exe を起動します。
  4. 次のアプリケーションが起動しますので、XAPファイルを指定して、配置ボタンを押します。

image

すると、インストールが行われ、Windows Phone のアプリケーションリストに、アイコンが現れます。以上の手順により、Visual Studio 無しに、動作確認 を行うことができます。

Windows Phone SDK 7.1はこちら

http://www.microsoft.com/ja-jp/download/details.aspx?id=27570

Windows Phone SDK 7.1.1 更新プログラム はこちら

http://www.microsoft.com/ja-jp/download/details.aspx?id=29233

注意:
端末のロック解除のために、AppHub への登録が必要です。

A5p4pAmCQAAAE68

2.10 でリジェクトされたのだけど、原因がわかりません・・・IS12Tでテストしていただける人募集中 #wp7dev_jp

2012年10月20日

トライアスロン1種目目でまだ走っていますが、2.10 でリジェクトされてしまいました T T

2.10
Requirements Expected Result
Your application and metadata must have distinct, substantial and legitimate content and purpose. Your application must provide functionality other than launching a webpage.

Comments: Fail per Microsoft instruction. Please consider using the Beta option for submissions of this type.

どうもテスト側では、何も動いていないような感じがしています。

1つ心当たりがあって、デバイスはNokia Lumia 800 のカメラの Point Focus 機能(特定の場所にフォーカスを合わせる機能) を使っています。ひょっとして、Point Focus 機能がない機種だと、動作しないのかな・・・

ということで、Nokia Lumia 800以外でテストしていただける人募集中。マーケットプレースに、ベータ登録してありますので、メールアドレスを教えていただければ、アクセス設定します。
m_ _m

Windows Phone のデバイスID, 匿名 LiveID の取得

2012年10月17日

環境: Windows Phone 7.1

http://msdn.microsoft.com/ja-jp/library/microsoft.phone.info.deviceextendedproperties.trygetvalue(v=vs.92).aspx

より、重要なところを抜粋。

Windows Phone OS 7.1 では、DeviceExtendedProperties のプロパティはほとんどが廃止されました。代わりに新しい DeviceStatus クラスを使用する必要があります。ただし、場合によっては、廃止されていない DeviceExtendedProperties のプロパティを引き続き使用できます。

DeviceStatus クラス

ApplicationCurrentMemoryUsage
現在のアプリケーションのメモリ使用量をバイト単位で返します。

パブリック プロパティApplicationMemoryUsageLimit
アプリケーション プロセスで割り当てることができるメモリの最大容量をバイト単位で返します。

パブリック プロパティApplicationPeakMemoryUsage
現在のアプリケーションの最大メモリ使用量をバイト単位で返します。

パブリック プロパティDeviceFirmwareVersion
デバイスで実行されているファームウェアのバージョンを返します。

パブリック プロパティDeviceHardwareVersion
デバイスで実行されているハードウェアのバージョンを返します。

パブリック プロパティDeviceManufacturer
デバイスの製造元の名前を返します。

パブリック プロパティDeviceName
デバイス名を返します。

パブリック プロパティDeviceTotalMemory
デバイスの物理 RAM サイズをバイト単位で返します。

パブリック プロパティIsKeyboardDeployed
ユーザーがデバイスの物理ハードウェア キーボードを開いたかどうかを示します。

パブリック プロパティIsKeyboardPresent
デバイスに物理ハードウェア キーボードが含まれるかどうかを示します。

パブリック プロパティPowerSource
デバイスが現在バッテリー電源で実行されているか、外部電源に接続されているかを示します。


DeviceExtendedProperties クラス

DeviceUniqueId

バイト配列。長さは 20 バイトです。

デバイスの一意のハッシュ コード。この値は、すべてのアプリケーションに共通する定数であり、デバイスのオペレーティング システムが新しいバージョンに更新されても変わりません。デバイス ID はデバイスの所有権が移った場合でも変更されないため、アプリケーションでこの値を使用することによってユーザーを識別することはできません。

ID_CAP_IDENTITY_DEVICE権限が必要となります。


一意のデバイス ID、製造元名、モデル名など、デバイス固有の情報を取得する方法

Getting to System Information on Windows Phone 7 より

一意のデバイス ID、製造元名、モデル名など、デバイス固有の情報を取得するには、 ID_CAP_IDENTITY_DEVICE権限が必要です。

object temp = null;
DeviceManufacturer = (DeviceExtendedProperties.TryGetValue("DeviceManufacturer", out temp)) ? (temp as string) : String.Empty;

DeviceName = (DeviceExtendedProperties.TryGetValue("DeviceName", out temp) ? (temp as string) : string.Empty);

DeviceUniqueID = (DeviceExtendedProperties.TryGetValue("DeviceUniqueID", out temp) ? (temp as byte[]) : new byte[0]);

DeviceFirmwareVersion = (DeviceExtendedProperties.TryGetValue("DeviceFirmwareVersion", out temp) ? (temp as string) : String.Empty);

DeviceHardwareVersion = (DeviceExtendedProperties.TryGetValue("DeviceHardwareVersion", out temp) ? (temp as string) : String.Empty);

DeviceTotalMemory = (long)DeviceExtendedProperties.GetValue("DeviceTotalMemory");

ApplicationCurrentMemoryUsage = (long) DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage");

ApplicationPeakMemoryUsage = (long) DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");


匿名 LiveID を取得する方法

Windows Phone 7 – How to find the device unique id windows live anonymous Id and manufacturer より

匿名Live ID を取得するには、ID_CAP_IDENTITY_USER権限が必要です。

private readonly int ANIDLength = 32;  
private readonly int ANIDOffset = 2; 

string result = string.Empty; 

object anid; 

if (UserExtendedProperties.TryGetValue("ANID", out anid))  
  {
if (anid != null && anid.ToString().Length  >=
    (ANIDLength + ANIDOffset ))
    {
      result = anid.ToString().Substring(ANIDOffset, ANIDLength);  
    }
  }

C# で、MouseDragElementBehavior を設定する

2012年10月12日

環境 Windows Phone 7 + Visual Studio 2010

using Microsoft.Expression.Interactivity.Layout;
using System.Windows.Interactivity;
using System.Windows.Input;

var v = new MouseDragElementBehavior();
v.Attach(p);
v.DragFinished += new MouseEventHandler(v_DragFinished);

Path を C# で構成する

2012年10月8日

環境: WIndows Phone 7 + Visual Studio 2010

WPF だと、Expression Blend などで次のように簡単に Path を自動生成してくれます。

<Path x:Name="path" Data="M183.66667,86.666667 C189.39235,102.51222 195.97031,115.69911 204.00303,124.34783 189.46184,124.37625 176.55191,127.63058 166.26051,130.07866 177.67961,136.62725 192.00787,141.50314 209.25719,141.39676 203.19164,149.57713 198.0335,156.49435 192.99912,166.33255 202.42621,162.74626 210.94614,156.64738 218.66605,148.33266 L222.66553,167.66588 C225.54016,165.52929 227.12504,154.35884 228.999,141.99936 234.06358,144.63928 238.15358,153.77991 241.33226,168.99921 L243.66592,167.99921 C241.1493,155.99855 236.78856,146.70538 230.66566,139.99937 241.69194,144.10578 251.73257,143.90948 260.99883,140.3327 255.36431,137.34626 248.38965,134.93892 240.33229,132.99941 250.52631,127.61701 259.03319,119.28195 265.66548,107.66621 L234.3321,118.99948 C236.99567,104.86417 236.63427,91.185053 232.99878,77.999712 226.74482,85.30016 221.8588,98.979918 218.33224,118.99948 209.59223,103.54312 197.83014,93.109381 183.66667,86.666667 z" Fill="red" Height="100" Stretch="Fill" Stroke="Red" RenderTransformOrigin="0.5,0.5"  Width="100" Margin="159,30,197,477">

Windows 環境だと、次のように PathGeometry.Parse でパースできるので、Expression Blend でデザインしたデータを C# で簡単に再利用することができます。

            const string PathData = “M248,64 C236.5247,64.625058 225.71435,67.192184 215.5,71.5 L207.5,95.5 191.5,79.5 C179.10929,77.102304 168.53048,80.027027 159.5,87.5 159.50162,99.540561 161.46431,108.60788 167.5,111.5 L183.5,119.5 159.5,135.5 C160.12292,156.23214 162.17492,169.92602 167.5,167.5 172.91066,172.67869 180.71148,173.07705 191.5,167.5 L207.5,151.5 C203.2411,162.05534 202.55968,170.46419 207.5,175.5 219.38597,184.51719 230.14356,187.65745 239.5,183.5 L255.5,167.5 C252.80927,155.47101 245.02601,144.74873 231.5,135.5 L263.5,143.5 C272.5318,139.39663 278.23003,131.78108 279.5,119.5 276.83333,114.16667 274.16667,108.83333 271.5,103.5 262.70483,100.69259 251.88845,100.91719 239.5,103.5 248.65115,105.75263 260.3255,80.446287 248,64 z”;
            var g = PathGeometry.Parse(PathData);

ところが、Windows Phone 環境だと、 Path.Parse が提供されていないのと、Object.Clone がないので、次のようにべたに書かざるを得なくなります。

private Path CreatePath()
{
    var pf = new PathFigure();
    pf.StartPoint = new Point(183.66667, 86.666667);
   
    var b1 = new BezierSegment(); // C189.39235,102.51222 195.97031,115.69911 204.00303,124.34783
    b1.Point1 = new Point(189.39235, 102.51222);
    b1.Point2 = new Point(195.97031, 115.69911);
    b1.Point3 = new Point(204.00303, 124.34783);
    pf.Segments.Add(b1);
    var b2 = new BezierSegment();  // 189.46184,124.37625 176.55191,127.63058 166.26051,130.07866
    b2.Point1 = new Point(189.46184, 124.37625);
    b2.Point2 = new Point(176.55191, 127.63058);
    b2.Point3 = new Point(166.26051, 130.07866);
    pf.Segments.Add(b2);
    var b3 = new BezierSegment();  // 177.67961,136.62725 192.00787,141.50314 209.25719,141.39676 
    b3.Point1 = new Point(177.67961, 136.62725);
    b3.Point2 = new Point(192.00787, 141.50314);
    b3.Point3 = new Point(209.25719, 141.39676);
    pf.Segments.Add(b3);
    var b4 = new BezierSegment();  // 203.19164,149.57713 198.0335,156.49435 192.99912,166.33255
    b4.Point1 = new Point(203.19164, 149.57713);
    b4.Point2 = new Point(198.0335, 156.49435);
    b4.Point3 = new Point(192.99912, 166.33255);
    pf.Segments.Add(b4);
    var b5 = new BezierSegment();  // 202.42621,162.74626 210.94614,156.64738 218.66605,148.33266
    b5.Point1 = new Point(202.42621, 162.74626);
    b5.Point2 = new Point(210.94614, 156.64738);
    b5.Point3 = new Point(218.66605, 148.33266);
    pf.Segments.Add(b5);

    // L222.66553,167.66588
    var l1 = new LineSegment();
    l1.Point = new Point(222.66553,167.66588 );
    pf.Segments.Add(l1);

    var b6 = new BezierSegment();  // C225.54016,165.52929 227.12504,154.35884 228.999,141.99936 
    b6.Point1 = new Point(225.54016, 165.52929);
    b6.Point2 = new Point(227.12504, 154.35884);
    b6.Point3 = new Point(228.999, 141.99936);
    pf.Segments.Add(b6);

    var b7 = new BezierSegment();  // 234.06358,144.63928 238.15358,153.77991 241.33226,168.99921 
    b7.Point1 = new Point(234.06358, 144.63928);
    b7.Point2 = new Point(238.15358, 153.77991);
    b7.Point3 = new Point(241.33226, 168.99921);
    pf.Segments.Add(b7);

    // L243.66592,167.99921
    var l2 = new LineSegment();
    l2.Point = new Point(243.66592, 167.99921);
    pf.Segments.Add(l2);

    var b8 = new BezierSegment();  // C241.1493,155.99855 236.78856,146.70538 230.66566,139.99937  
    b8.Point1 = new Point(241.1493, 155.99855);
    b8.Point2 = new Point(236.78856, 146.70538);
    b8.Point3 = new Point(230.66566, 139.99937);
    pf.Segments.Add(b8);

    var b9 = new BezierSegment();  // 241.69194,144.10578 251.73257,143.90948 260.99883,140.3327
    b9.Point1 = new Point(241.69194, 144.10578);
    b9.Point2 = new Point(251.73257, 143.90948);
    b9.Point3 = new Point(260.99883, 140.3327);
    pf.Segments.Add(b9);

    var b10 = new BezierSegment();  // 255.36431,137.34626 248.38965,134.93892 240.33229,132.99941 
    b10.Point1 = new Point(255.36431, 137.34626);
    b10.Point2 = new Point(248.38965, 134.93892);
    b10.Point3 = new Point(240.33229, 132.99941);
    pf.Segments.Add(b10);

    var b11 = new BezierSegment();  // 250.52631,127.61701 259.03319,119.28195 265.66548,107.66621  
    b11.Point1 = new Point(250.52631, 127.61701);
    b11.Point2 = new Point(259.03319, 119.28195);
    b11.Point3 = new Point(265.66548,107.66621);
    pf.Segments.Add(b11);

    // L234.3321,118.99948
    var l3 = new LineSegment();
    l3.Point = new Point(234.3321, 118.99948);
    pf.Segments.Add(l3);

    var b12 = new BezierSegment();  // C236.99567,104.86417 236.63427,91.185053 232.99878,77.999712      
    b12.Point1 = new Point(236.99567, 104.86417);
    b12.Point2 = new Point(236.63427, 91.185053);
    b12.Point3 = new Point(232.99878, 77.999712);
    pf.Segments.Add(b12);
    var b13 = new BezierSegment();  // 226.74482,85.30016 221.8588,98.979918 218.33224,118.99948
    b13.Point1 = new Point(226.74482, 85.30016);
    b13.Point2 = new Point(221.8588, 98.979918);
    b13.Point3 = new Point(218.33224, 118.99948);
    pf.Segments.Add(b13);
    var b14 = new BezierSegment();  // 209.59223,103.54312 197.83014,93.109381 183.66667,86.666667
    b14.Point1 = new Point(209.59223, 103.54312);
    b14.Point2 = new Point(197.83014, 93.109381);
    b14.Point3 = new Point(183.66667, 86.666667);
    pf.Segments.Add(b14);

    PathFigureCollection pfc = new PathFigureCollection();
    pfc.Add(pf);

    PathGeometry pg = new PathGeometry();
    pg.Figures = pfc;
    var path = new Path();
    path.RenderTransformOrigin = new Point(0.5, 0.5);
    path.StrokeThickness = 3;
    path.Stroke = new SolidColorBrush(Colors.Red);
    path.Width = 100;
    path.Height = 100;
    path.Fill = new SolidColorBrush(Colors.Orange);
    path.Data = pg;
    path.Stretch = Stretch.Fill;
    var ct = new CompositeTransform();
    path.RenderTransform = ct;

    return path;
}

赤いモミジが WPF、オレンジのモミジが C# で実装したものです。

image

Windows Phone では、システムの肥大化を防ぐために API を絞っていますが、Clone は削らないでほしかった・・・