Skip to content

Instantly share code, notes, and snippets.

@masaru-b-cl
Created February 14, 2012 08:22
Show Gist options
  • Save masaru-b-cl/1824793 to your computer and use it in GitHub Desktop.
Save masaru-b-cl/1824793 to your computer and use it in GitHub Desktop.
DynamicFixedRecord - 固定長文字列を長さで区切って各項目に分割する
bin/
obj/
*.user
*.suo
<?xml version="1.0"?>
<configuration>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/></startup></configuration>
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("DynamicFixedRecord")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DynamicFixedRecord")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("ef2fa4c3-822a-4af3-960e-803d36421a41")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{CA8B070D-4C19-41E4-A715-87609011BB09}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DynamicFixedRecord</RootNamespace>
<AssemblyName>DynamicFixedRecord</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
<PlatformTarget>x86</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual C# Express 2010
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DynamicFixedRecord", "DynamicFixedRecord.csproj", "{CA8B070D-4C19-41E4-A715-87609011BB09}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CA8B070D-4C19-41E4-A715-87609011BB09}.Debug|x86.ActiveCfg = Debug|x86
{CA8B070D-4C19-41E4-A715-87609011BB09}.Debug|x86.Build.0 = Debug|x86
{CA8B070D-4C19-41E4-A715-87609011BB09}.Release|x86.ActiveCfg = Release|x86
{CA8B070D-4C19-41E4-A715-87609011BB09}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Collections.Specialized;
namespace DynamicFixedRecord
{
public static class StringExtensions
{
public static dynamic AsDynamic(this string fixedRecord)
{
return new DynamicFixedRecord(fixedRecord);
}
}
public class DynamicFixedRecord : DynamicObject
{
private NameValueCollection source;
private string fixedRecord;
public DynamicFixedRecord(string fixedRecord)
{
this.source = new NameValueCollection();
this.fixedRecord = fixedRecord;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var value = source[binder.Name];
result = new StringMember(value);
return true;
}
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
var startIndex = 0;
source.Clear();
foreach (var item in binder.CallInfo.ArgumentNames.Zip(args, (key, value) => new { key, value }))
{
var length = Int32.Parse(item.value.ToString());
source.Add(item.key, fixedRecord.Substring(startIndex, length));
startIndex += length;
}
result = this;
return true;
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
if (binder.Type != typeof(string))
{
result = null;
return false;
}
else
{
result = this.ToString();
return true;
}
}
public override string ToString()
{
return string.Join(", ", source.Cast<string>().Select(key => key + ":" + source[key]));
}
}
class StringMember : DynamicObject
{
readonly string value;
public StringMember(string value)
{
this.value = value;
}
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
var defaultValue = args.First();
try
{
result = (value == null)
? defaultValue
: Convert.ChangeType(value, defaultValue.GetType());
}
catch (FormatException)
{
result = defaultValue;
}
return true;
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
try
{
var type = (binder.Type.IsGenericType && binder.Type.GetGenericTypeDefinition() == typeof(Nullable<>))
? binder.Type.GetGenericArguments().First()
: binder.Type;
result = (value == null)
? null
: type == typeof(DateTime)
? DateTime.ParseExact(value, new[] { "yyyyMMdd", "yyyy/MM/dd", "yyMMdd", "yy/MM/dd" }, null, System.Globalization.DateTimeStyles.None)
: Convert.ChangeType(value, binder.Type);
}
catch (FormatException)
{
result = null;
}
return true;
}
public override string ToString()
{
return value ?? "";
}
}
public class Program
{
public static void Main(string[] args)
{
var record = "A0120120214".AsDynamic();
record(col1: 1, col2: 2, col3: 8);
string col1 = record.col1;
Console.WriteLine(col1);
int col2 = record.col2;
Console.WriteLine(col2);
DateTime col3 = record.col3;
Console.WriteLine(col3);
Console.WriteLine(record);
}
}
}
@masaru-b-cl
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment