mysql-connector-net-6.4.3/0000755000175000017500000000000011127003600016153 5ustar directhexdirecthexmysql-connector-net-6.4.3/MySQLClient.sln0000644000175000017500000004455411127003600021011 0ustar directhexdirecthex Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data", "Source\MySql.Data\MySql.Data.csproj", "{E9DF5ED1-4CBD-4226-B931-9A51610AC14D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data.Tests", "Tests\MySql.Data.Tests\MySql.Data.Tests.csproj", "{F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Web", "Source\MySql.Web\MySql.Web.csproj", "{C28B1166-1380-445D-AEC1-8A18B990DD18}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Web.Tests", "Tests\MySql.Web.Tests\MySql.Web.Tests.csproj", "{83462D15-E576-4079-BBC9-9EE1CF0B24DD}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data.Entity", "Source\MySql.Data.Entity\MySql.Data.Entity.csproj", "{EDED3135-95D2-4BCE-A810-F3F2AD7935B7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data.Entity.Tests", "Tests\MySql.Data.Entity.Tests\MySql.Data.Entity.Tests.csproj", "{D37B3572-767F-4622-A835-844B0EBEFD5B}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.VisualStudio", "Source\MySql.VisualStudio\MySql.VisualStudio.csproj", "{DC3517FF-AC26-4755-9B7A-EF658FF69593}" EndProject Project("{930C7802-8A8C-48F9-8165-68863BCCD9DD}") = "Installer", "Installer\Installer.wixproj", "{F533FC43-6C05-4A64-8AF6-72B690EB06C3}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Commercial|Any CPU = Commercial|Any CPU Commercial|Mixed Platforms = Commercial|Mixed Platforms Commercial|x64 = Commercial|x64 Commercial|x86 = Commercial|x86 Debug|Any CPU = Debug|Any CPU Debug|Mixed Platforms = Debug|Mixed Platforms Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 GPL|Any CPU = GPL|Any CPU GPL|Mixed Platforms = GPL|Mixed Platforms GPL|x64 = GPL|x64 GPL|x86 = GPL|x86 Release|Any CPU = Release|Any CPU Release|Mixed Platforms = Release|Mixed Platforms Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|Any CPU.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|Any CPU.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|Mixed Platforms.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|Mixed Platforms.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|x64.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|x86.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|Any CPU.Build.0 = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|x64.ActiveCfg = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|x86.ActiveCfg = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|Any CPU.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|Any CPU.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|Mixed Platforms.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|Mixed Platforms.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|x64.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|x86.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|Any CPU.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|Any CPU.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|Mixed Platforms.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|x64.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|x86.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Commercial|Any CPU.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Commercial|Any CPU.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Commercial|Mixed Platforms.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Commercial|Mixed Platforms.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Commercial|x64.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Commercial|x86.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|Any CPU.Build.0 = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|x64.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|x86.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.GPL|Any CPU.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.GPL|Any CPU.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.GPL|Mixed Platforms.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.GPL|Mixed Platforms.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.GPL|x64.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.GPL|x86.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|Any CPU.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|Any CPU.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|Mixed Platforms.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|x64.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|x86.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Commercial|Any CPU.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Commercial|Any CPU.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Commercial|Mixed Platforms.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Commercial|Mixed Platforms.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Commercial|x64.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Commercial|x86.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|Any CPU.Build.0 = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|x64.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|x86.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.GPL|Any CPU.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.GPL|Any CPU.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.GPL|Mixed Platforms.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.GPL|Mixed Platforms.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.GPL|x64.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.GPL|x86.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|Any CPU.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|Any CPU.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|Mixed Platforms.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|x64.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|x86.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Commercial|Any CPU.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Commercial|Any CPU.Build.0 = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Commercial|Mixed Platforms.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Commercial|Mixed Platforms.Build.0 = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Commercial|x64.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Commercial|x86.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Debug|Any CPU.Build.0 = Debug|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Debug|x64.ActiveCfg = Debug|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Debug|x86.ActiveCfg = Debug|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.GPL|Any CPU.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.GPL|Any CPU.Build.0 = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.GPL|Mixed Platforms.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.GPL|Mixed Platforms.Build.0 = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.GPL|x64.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.GPL|x86.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Release|Any CPU.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Release|Any CPU.Build.0 = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Release|Mixed Platforms.Build.0 = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Release|x64.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Release|x86.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Commercial|Any CPU.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Commercial|Any CPU.Build.0 = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Commercial|Mixed Platforms.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Commercial|Mixed Platforms.Build.0 = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Commercial|x64.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Commercial|x86.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Debug|Any CPU.Build.0 = Debug|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Debug|x64.ActiveCfg = Debug|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Debug|x86.ActiveCfg = Debug|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.GPL|Any CPU.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.GPL|Any CPU.Build.0 = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.GPL|Mixed Platforms.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.GPL|Mixed Platforms.Build.0 = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.GPL|x64.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.GPL|x86.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Release|Any CPU.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Release|Any CPU.Build.0 = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Release|Mixed Platforms.Build.0 = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Release|x64.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Release|x86.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Commercial|Any CPU.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Commercial|Any CPU.Build.0 = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Commercial|Mixed Platforms.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Commercial|Mixed Platforms.Build.0 = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Commercial|x64.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Commercial|x86.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Debug|Any CPU.Build.0 = Debug|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Debug|x64.ActiveCfg = Debug|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Debug|x86.ActiveCfg = Debug|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.GPL|Any CPU.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.GPL|Any CPU.Build.0 = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.GPL|Mixed Platforms.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.GPL|Mixed Platforms.Build.0 = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.GPL|x64.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.GPL|x86.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Release|Any CPU.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Release|Any CPU.Build.0 = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Release|Mixed Platforms.Build.0 = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Release|x64.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Release|x86.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Commercial|Any CPU.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Commercial|Any CPU.Build.0 = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Commercial|Mixed Platforms.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Commercial|Mixed Platforms.Build.0 = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Commercial|x64.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Commercial|x86.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|Any CPU.Build.0 = Debug|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|x64.ActiveCfg = Debug|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|x86.ActiveCfg = Debug|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.GPL|Any CPU.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.GPL|Any CPU.Build.0 = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.GPL|Mixed Platforms.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.GPL|Mixed Platforms.Build.0 = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.GPL|x64.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.GPL|x86.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|Any CPU.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|Any CPU.Build.0 = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|Mixed Platforms.Build.0 = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|x64.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|x86.ActiveCfg = Release|Any CPU {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|Any CPU.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|Any CPU.Build.0 = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|Mixed Platforms.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|Mixed Platforms.Build.0 = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|x64.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|x86.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|x86.Build.0 = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Debug|Any CPU.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Debug|Mixed Platforms.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Debug|Mixed Platforms.Build.0 = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Debug|x64.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Debug|x86.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Debug|x86.Build.0 = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|Any CPU.ActiveCfg = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|Any CPU.Build.0 = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|Mixed Platforms.ActiveCfg = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|Mixed Platforms.Build.0 = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|x64.ActiveCfg = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|x86.ActiveCfg = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|x86.Build.0 = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Release|Any CPU.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Release|Mixed Platforms.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Release|Mixed Platforms.Build.0 = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Release|x64.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Release|x86.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Release|x86.Build.0 = Commercial|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal mysql-connector-net-6.4.3/Tests/0000755000175000017500000000000011127003600017255 5ustar directhexdirecthexmysql-connector-net-6.4.3/Tests/MySql.Web.Tests/0000755000175000017500000000000011127003600022137 5ustar directhexdirecthexmysql-connector-net-6.4.3/Tests/MySql.Web.Tests/BaseTest.cs0000644000175000017500000001161711127003600024206 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12 // The copyright was assigned and transferred under the terms of // the MySQL Contributor License Agreement (CLA) using NUnit.Framework; using MySql.Data.MySqlClient; using System.Data; using System.Configuration; using System.Reflection; using System; using System.Web.Configuration; using System.Collections.Specialized; using System.Diagnostics; using MySql.Data.MySqlClient.Tests; using System.Resources; using MySql.Web.Common; using MySql.Web.Security; namespace MySql.Web.Tests { public class BaseWebTest : BaseTest { protected override void LoadStaticConfiguration() { base.LoadStaticConfiguration(); ConnectionStringSettings css = new ConnectionStringSettings(); css.ConnectionString = String.Format( "server={0};uid={1};password={2};database={3};pooling=false", BaseTest.host, BaseTest.user, BaseTest.password, BaseTest.database0); css.Name = "LocalMySqlServer"; Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.ConnectionStrings.ConnectionStrings.Add(css); MembershipSection ms = (MembershipSection)config.SectionGroups["system.web"].Sections["membership"]; ms.DefaultProvider = "MySQLMembershipProvider"; ProviderSettings ps = new ProviderSettings(); ps.Name = "MySQLMembershipProvider"; Assembly a = Assembly.GetAssembly(typeof(MySQLMembershipProvider)); ps.Type = "MySql.Web.Security.MySQLMembershipProvider, " + a.FullName; ps.Parameters.Add("connectionStringName", "LocalMySqlServer"); ps.Parameters.Add("enablePasswordRetrieval", "false"); ps.Parameters.Add("enablePasswordReset", "true"); ps.Parameters.Add("requiresQuestionAndAnswer", "true"); ps.Parameters.Add("applicationName", "/"); ps.Parameters.Add("requiresUniqueEmail", "false"); ps.Parameters.Add("passwordFormat", "Hashed"); ps.Parameters.Add("maxInvalidPasswordAttempts", "5"); ps.Parameters.Add("minRequiredPasswordLength", "7"); ps.Parameters.Add("minRequiredNonalphanumericCharacters", "1"); ps.Parameters.Add("passwordAttemptWindow", "10"); ps.Parameters.Add("passwordStrengthRegularExpression", ""); ms.Providers.Add(ps); RoleManagerSection rs = (RoleManagerSection)config.SectionGroups["system.web"].Sections["roleManager"]; rs.DefaultProvider = "MySQLRoleProvider"; rs.Enabled = true; ps = new ProviderSettings(); ps.Name = "MySQLRoleProvider"; a = Assembly.GetAssembly(typeof(MySQLRoleProvider)); ps.Type = "MySql.Web.Security.MySQLRoleProvider, " + a.FullName; ps.Parameters.Add("connectionStringName", "LocalMySqlServer"); ps.Parameters.Add("applicationName", "/"); rs.Providers.Add(ps); config.Save(); ConfigurationManager.RefreshSection("connectionStrings"); ConfigurationManager.RefreshSection("system.web/membership"); ConfigurationManager.RefreshSection("system.web/roleManager"); } public override void Setup() { base.Setup(); for (int ver = 1; ver <= SchemaManager.Version; ver++) LoadSchema(ver); } protected void LoadSchema(int version) { if (version < 1) return; MySQLMembershipProvider provider = new MySQLMembershipProvider(); ResourceManager r = new ResourceManager("MySql.Web.Properties.Resources", typeof(MySQLMembershipProvider).Assembly); string schema = r.GetString(String.Format("schema{0}", version)); MySqlScript script = new MySqlScript(conn); script.Query = schema; script.Execute(); } } } mysql-connector-net-6.4.3/Tests/MySql.Web.Tests/ProfileTests.cs0000644000175000017500000002603411127003600025116 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12 // The copyright was assigned and transferred under the terms of // the MySQL Contributor License Agreement (CLA) using NUnit.Framework; using System.Web.Security; using System.Collections.Specialized; using System.Data; using System; using System.Configuration.Provider; using System.Configuration; using MySql.Web.Profile; using System.Web.Profile; using System.Reflection; namespace MySql.Web.Tests { [TestFixture] public class ProfileTests : BaseWebTest { private MySQLProfileProvider InitProfileProvider() { MySQLProfileProvider p = new MySQLProfileProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); p.Initialize(null, config); return p; } [Test] public void SettingValuesCreatesAnAppAndUserId() { MySQLProfileProvider provider = InitProfileProvider(); SettingsContext ctx = new SettingsContext(); ctx.Add("IsAuthenticated", false); ctx.Add("UserName", "user1"); SettingsPropertyValueCollection values = new SettingsPropertyValueCollection(); SettingsProperty property1 = new SettingsProperty("color"); property1.PropertyType = typeof(string); property1.Attributes["AllowAnonymous"] = true; SettingsPropertyValue value = new SettingsPropertyValue(property1); value.PropertyValue = "blue"; values.Add(value); provider.SetPropertyValues(ctx, values); DataTable dt = FillTable("SELECT * FROM my_aspnet_Applications"); Assert.AreEqual(1, dt.Rows.Count); dt = FillTable("SELECT * FROM my_aspnet_Users"); Assert.AreEqual(1, dt.Rows.Count); dt = FillTable("SELECT * FROM my_aspnet_Profiles"); Assert.AreEqual(1, dt.Rows.Count); values["color"].PropertyValue = "green"; provider.SetPropertyValues(ctx, values); dt = FillTable("SELECT * FROM my_aspnet_Applications"); Assert.AreEqual(1, dt.Rows.Count); dt = FillTable("SELECT * FROM my_aspnet_Users"); Assert.AreEqual(1, dt.Rows.Count); dt = FillTable("SELECT * FROM my_aspnet_Profiles"); Assert.AreEqual(1, dt.Rows.Count); } [Test] public void AnonymousUserSettingNonAnonymousProperties() { MySQLProfileProvider provider = InitProfileProvider(); SettingsContext ctx = new SettingsContext(); ctx.Add("IsAuthenticated", false); ctx.Add("UserName", "user1"); SettingsPropertyValueCollection values = new SettingsPropertyValueCollection(); SettingsProperty property1 = new SettingsProperty("color"); property1.PropertyType = typeof(string); property1.Attributes["AllowAnonymous"] = false; SettingsPropertyValue value = new SettingsPropertyValue(property1); value.PropertyValue = "blue"; values.Add(value); provider.SetPropertyValues(ctx, values); DataTable dt = FillTable("SELECT * FROM my_aspnet_Applications"); Assert.AreEqual(0, dt.Rows.Count); dt = FillTable("SELECT * FROM my_aspnet_Users"); Assert.AreEqual(0, dt.Rows.Count); dt = FillTable("SELECT * FROM my_aspnet_Profiles"); Assert.AreEqual(0, dt.Rows.Count); } [Test] public void StringCollectionAsProperty() { ProfileBase profile = ProfileBase.Create("foo", true); ResetAppId(profile.Providers["MySqlProfileProvider"] as MySQLProfileProvider); StringCollection colors = new StringCollection(); colors.Add("red"); colors.Add("green"); colors.Add("blue"); profile["FavoriteColors"] = colors; profile.Save(); DataTable dt = FillTable("SELECT * FROM my_aspnet_Applications"); Assert.AreEqual(1, dt.Rows.Count); dt = FillTable("SELECT * FROM my_aspnet_Users"); Assert.AreEqual(1, dt.Rows.Count); dt = FillTable("SELECT * FROM my_aspnet_Profiles"); Assert.AreEqual(1, dt.Rows.Count); // now retrieve them SettingsPropertyCollection getProps = new SettingsPropertyCollection(); SettingsProperty getProp1 = new SettingsProperty("FavoriteColors"); getProp1.PropertyType = typeof(StringCollection); getProp1.SerializeAs = SettingsSerializeAs.Xml; getProps.Add(getProp1); MySQLProfileProvider provider = InitProfileProvider(); SettingsContext ctx = new SettingsContext(); ctx.Add("IsAuthenticated", true); ctx.Add("UserName", "foo"); SettingsPropertyValueCollection getValues = provider.GetPropertyValues(ctx, getProps); Assert.AreEqual(1, getValues.Count); SettingsPropertyValue getValue1 = getValues["FavoriteColors"]; StringCollection outValue = (StringCollection)getValue1.PropertyValue; Assert.AreEqual(3, outValue.Count); Assert.AreEqual("red", outValue[0]); Assert.AreEqual("green", outValue[1]); Assert.AreEqual("blue", outValue[2]); } [Test] public void AuthenticatedDateTime() { ProfileBase profile = ProfileBase.Create("foo", true); ResetAppId(profile.Providers["MySqlProfileProvider"] as MySQLProfileProvider); DateTime date = DateTime.Now; profile["BirthDate"] = date; profile.Save(); SettingsPropertyCollection getProps = new SettingsPropertyCollection(); SettingsProperty getProp1 = new SettingsProperty("BirthDate"); getProp1.PropertyType = typeof(DateTime); getProp1.SerializeAs = SettingsSerializeAs.Xml; getProps.Add(getProp1); MySQLProfileProvider provider = InitProfileProvider(); SettingsContext ctx = new SettingsContext(); ctx.Add("IsAuthenticated", true); ctx.Add("UserName", "foo"); SettingsPropertyValueCollection getValues = provider.GetPropertyValues(ctx, getProps); Assert.AreEqual(1, getValues.Count); SettingsPropertyValue getValue1 = getValues["BirthDate"]; Assert.AreEqual(date, getValue1.PropertyValue); } /// /// We have to manually reset the app id because our profile provider is loaded from /// previous tests but we are destroying our database between tests. This means that /// our provider thinks we have an application in our database when we really don't. /// Doing this will force the provider to generate a new app id. /// Note that this is not really a problem in a normal app that is not destroying /// the database behind the back of the provider. /// /// private void ResetAppId(MySQLProfileProvider p) { Type t = p.GetType(); FieldInfo fi = t.GetField("app", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.GetField); object appObject = fi.GetValue(p); Type appType = appObject.GetType(); PropertyInfo pi = appType.GetProperty("Id"); pi.SetValue(appObject, -1, null); } [Test] public void AuthenticatedStringProperty() { ProfileBase profile = ProfileBase.Create("foo", true); ResetAppId(profile.Providers["MySqlProfileProvider"] as MySQLProfileProvider); profile["Name"] = "Fred Flintstone"; profile.Save(); SettingsPropertyCollection getProps = new SettingsPropertyCollection(); SettingsProperty getProp1 = new SettingsProperty("Name"); getProp1.PropertyType = typeof(String); getProps.Add(getProp1); MySQLProfileProvider provider = InitProfileProvider(); SettingsContext ctx = new SettingsContext(); ctx.Add("IsAuthenticated", true); ctx.Add("UserName", "foo"); SettingsPropertyValueCollection getValues = provider.GetPropertyValues(ctx, getProps); Assert.AreEqual(1, getValues.Count); SettingsPropertyValue getValue1 = getValues["Name"]; Assert.AreEqual("Fred Flintstone", getValue1.PropertyValue); } /// /// Bug #41654 FindProfilesByUserName error into Connector .NET /// [Test] public void GetAllProfiles() { ProfileBase profile = ProfileBase.Create("foo", true); ResetAppId(profile.Providers["MySqlProfileProvider"] as MySQLProfileProvider); profile["Name"] = "Fred Flintstone"; profile.Save(); SettingsPropertyCollection getProps = new SettingsPropertyCollection(); SettingsProperty getProp1 = new SettingsProperty("Name"); getProp1.PropertyType = typeof(String); getProps.Add(getProp1); MySQLProfileProvider provider = InitProfileProvider(); SettingsContext ctx = new SettingsContext(); ctx.Add("IsAuthenticated", true); ctx.Add("UserName", "foo"); int total; ProfileInfoCollection profiles = provider.GetAllProfiles( ProfileAuthenticationOption.All, 0, 10, out total); Assert.AreEqual(1, total); } } } mysql-connector-net-6.4.3/Tests/MySql.Web.Tests/MySql.Web.Tests.csproj0000644000175000017500000001035411127003600026246 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {83462D15-E576-4079-BBC9-9EE1CF0B24DD} Library Properties MySql.Web.Tests MySql.Web.Tests 3.5 v4.0 false publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false true true full false bin\Debug\ DEBUG;TRACE prompt 4 AllRules.ruleset pdbonly true bin\Release\ TRACE prompt 4 AllRules.ruleset Properties\VersionInfo.cs {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} MySql.Data {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4} MySql.Data.Tests {C28B1166-1380-445D-AEC1-8A18B990DD18} MySql.Web mysql-connector-net-6.4.3/Tests/MySql.Web.Tests/RoleManagement.cs0000644000175000017500000002046711127003600025375 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12 // The copyright was assigned and transferred under the terms of // the MySQL Contributor License Agreement (CLA) using NUnit.Framework; using System.Web.Security; using System.Collections.Specialized; using System.Data; using System; using System.Configuration.Provider; using MySql.Web.Security; namespace MySql.Web.Tests { [TestFixture] public class RoleManagement : BaseWebTest { private MySQLMembershipProvider membershipProvider; private MySQLRoleProvider roleProvider; [SetUp] public override void Setup() { base.Setup(); execSQL("DROP TABLE IF EXISTS mysql_membership"); execSQL("DROP TABLE IF EXISTS mysql_roles"); membershipProvider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); membershipProvider.Initialize(null, config); } [Test] public void CreateAndDeleteRoles() { roleProvider = new MySQLRoleProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); roleProvider.Initialize(null, config); // Add the role roleProvider.CreateRole("Administrator"); string[] roles = roleProvider.GetAllRoles(); Assert.AreEqual(1, roles.Length); Assert.AreEqual("Administrator", roles[0]); // now delete the role roleProvider.DeleteRole("Administrator", false); roles = roleProvider.GetAllRoles(); Assert.AreEqual(0, roles.Length); } private void AddUser(string username, string password) { MembershipCreateStatus status; membershipProvider.CreateUser(username, password, "foo@bar.com", null, null, true, null, out status); if (status != MembershipCreateStatus.Success) Assert.Fail("User creation failed"); } [Test] public void AddUserToRole() { roleProvider = new MySQLRoleProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); roleProvider.Initialize(null, config); AddUser("eve", "eveeve!"); roleProvider.CreateRole("Administrator"); roleProvider.AddUsersToRoles(new string[] { "eve" }, new string[] { "Administrator" }); Assert.IsTrue(roleProvider.IsUserInRole("eve", "Administrator")); roleProvider.RemoveUsersFromRoles(new string[] { "eve" }, new string[] { "Administrator" }); Assert.IsFalse(roleProvider.IsUserInRole("eve", "Administrator")); } /// /// Bug #38243 Not Handling non existing user when calling AddUsersToRoles method /// [Test] public void AddNonExistingUserToRole() { roleProvider = new MySQLRoleProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); roleProvider.Initialize(null, config); roleProvider.CreateRole("Administrator"); roleProvider.AddUsersToRoles(new string[] { "eve" }, new string[] { "Administrator" }); Assert.IsTrue(roleProvider.IsUserInRole("eve", "Administrator")); } private void AttemptToAddUserToRole(string username, string role) { try { roleProvider.AddUsersToRoles(new string[] { username }, new string[] { role }); } catch (ArgumentException) { } } [Test] public void IllegalRoleAndUserNames() { roleProvider = new MySQLRoleProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); roleProvider.Initialize(null, config); AttemptToAddUserToRole("test", null); AttemptToAddUserToRole("test", ""); roleProvider.CreateRole("Administrator"); AttemptToAddUserToRole(null, "Administrator"); AttemptToAddUserToRole("", "Administrator"); } [Test] public void AddUserToRoleWithRoleClass() { Roles.CreateRole("Administrator"); MembershipCreateStatus status; Membership.CreateUser("eve", "eve1@eve", "eve@boo.com", "question", "answer", true, null, out status); Assert.AreEqual(MembershipCreateStatus.Success, status); Roles.AddUserToRole("eve", "Administrator"); Assert.IsTrue(Roles.IsUserInRole("eve", "Administrator")); } [Test] public void IsUserInRoleCrossDomain() { MySQLMembershipProvider provider = new MySQLMembershipProvider(); NameValueCollection config1 = new NameValueCollection(); config1.Add("connectionStringName", "LocalMySqlServer"); config1.Add("applicationName", "/"); config1.Add("passwordStrengthRegularExpression", "bar.*"); config1.Add("passwordFormat", "Clear"); provider.Initialize(null, config1); MembershipCreateStatus status; provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status); MySQLMembershipProvider provider2 = new MySQLMembershipProvider(); NameValueCollection config2 = new NameValueCollection(); config2.Add("connectionStringName", "LocalMySqlServer"); config2.Add("applicationName", "/myapp"); config2.Add("passwordStrengthRegularExpression", ".*"); config2.Add("passwordFormat", "Clear"); provider2.Initialize(null, config2); roleProvider = new MySQLRoleProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); roleProvider.Initialize(null, config); MySQLRoleProvider r2 = new MySQLRoleProvider(); NameValueCollection configr2 = new NameValueCollection(); configr2.Add("connectionStringName", "LocalMySqlServer"); configr2.Add("applicationName", "/myapp"); r2.Initialize(null, configr2); roleProvider.CreateRole("Administrator"); roleProvider.AddUsersToRoles(new string[] { "foo" }, new string[] { "Administrator" }); Assert.IsFalse(r2.IsUserInRole("foo", "Administrator")); } } } mysql-connector-net-6.4.3/Tests/MySql.Web.Tests/SchemaTests.cs0000644000175000017500000003216011127003600024713 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12 // The copyright was assigned and transferred under the terms of // the MySQL Contributor License Agreement (CLA) using NUnit.Framework; using MySql.Web.Security; using System.Collections.Specialized; using MySql.Data.MySqlClient; using System.Resources; using System.Data; using System; using System.IO; using System.Configuration.Provider; using System.Web.Security; using MySql.Web.Common; using System.Configuration; namespace MySql.Web.Tests { [TestFixture] public class SchemaTests : BaseWebTest { [SetUp] public override void Setup() { base.Setup(); DropAllTables(); } private void DropAllTables() { DataTable dt = conn.GetSchema("Tables"); foreach (DataRow row in dt.Rows) execSQL(String.Format("DROP TABLE IF EXISTS {0}", row["TABLE_NAME"])); } /// /// Bug #37469 autogenerateschema optimizing /// [Test] public void SchemaCheck() { for (int i = 0; i <= SchemaManager.Version; i++) { DropAllTables(); MySQLMembershipProvider provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordFormat", "Clear"); if (i > 0) for (int x = 1; x <= i; x++) LoadSchema(x); try { provider.Initialize(null, config); if (i < SchemaManager.Version) Assert.Fail("Should have failed"); } catch (ProviderException) { if (i == SchemaManager.Version) Assert.Fail("This should not have failed"); } } } /// /// Bug #36444 'autogenerateschema' produces tables with 'random' collations /// [Test] public void CurrentSchema() { execSQL("set character_set_database=utf8"); LoadSchema(1); LoadSchema(2); LoadSchema(3); LoadSchema(4); MySqlCommand cmd = new MySqlCommand("SELECT * FROM my_aspnet_SchemaVersion", conn); object ver = cmd.ExecuteScalar(); Assert.AreEqual(4, ver); cmd.CommandText = "SHOW CREATE TABLE my_aspnet_membership"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string createSql = reader.GetString(1); Assert.IsTrue(createSql.IndexOf("CHARSET=utf8") != -1); } } [Test] public void UpgradeV1ToV2() { LoadSchema(1); MySqlCommand cmd = new MySqlCommand("SHOW CREATE TABLE mysql_membership", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string createTable = reader.GetString(1); int index = createTable.IndexOf("COMMENT='1'"); Assert.AreNotEqual(-1, index); } LoadSchema(2); cmd = new MySqlCommand("SHOW CREATE TABLE mysql_membership", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string createTable = reader.GetString(1); int index = createTable.IndexOf("COMMENT='2'"); Assert.AreNotEqual(-1, index); } } private void LoadData() { LoadSchema(1); LoadSchema(2); execSQL(@"INSERT INTO mysql_membership (pkid, username, password, applicationname, lastactivitydate) VALUES('1', 'user1', '', 'app1', '2007-01-01')"); execSQL(@"INSERT INTO mysql_membership (pkid, username, password, applicationname, lastactivitydate) VALUES('2', 'user2', '', 'app1', '2007-01-01')"); execSQL(@"INSERT INTO mysql_membership (pkid, username, password, applicationname, lastactivitydate) VALUES('3', 'user1', '', 'app2', '2007-01-01')"); execSQL(@"INSERT INTO mysql_membership (pkid, username, password, applicationname, lastactivitydate) VALUES('4', 'user2', '', 'app2', '2007-01-01')"); execSQL(@"INSERT INTO mysql_roles VALUES ('role1', 'app1')"); execSQL(@"INSERT INTO mysql_roles VALUES ('role2', 'app1')"); execSQL(@"INSERT INTO mysql_roles VALUES ('role1', 'app2')"); execSQL(@"INSERT INTO mysql_roles VALUES ('role2', 'app2')"); execSQL(@"INSERT INTO mysql_UsersInRoles VALUES ('user1', 'role1', 'app1')"); execSQL(@"INSERT INTO mysql_UsersInRoles VALUES ('user2', 'role2', 'app1')"); execSQL(@"INSERT INTO mysql_UsersInRoles VALUES ('user1', 'role1', 'app2')"); execSQL(@"INSERT INTO mysql_UsersInRoles VALUES ('user2', 'role2', 'app2')"); LoadSchema(3); Assert.IsFalse(TableExists("mysql_membership")); Assert.IsFalse(TableExists("mysql_roles")); Assert.IsFalse(TableExists("mysql_usersinroles")); } [Test] public void CheckAppsUpgrade() { LoadData(); DataTable apps = FillTable("SELECT * FROM my_aspnet_Applications"); Assert.AreEqual(2, apps.Rows.Count); Assert.AreEqual(1, apps.Rows[0]["id"]); Assert.AreEqual("app1", apps.Rows[0]["name"]); Assert.AreEqual(2, apps.Rows[1]["id"]); Assert.AreEqual("app2", apps.Rows[1]["name"]); } [Test] public void CheckUsersUpgrade() { LoadData(); DataTable dt = FillTable("SELECT * FROM my_aspnet_Users"); Assert.AreEqual(4, dt.Rows.Count); Assert.AreEqual(1, dt.Rows[0]["id"]); Assert.AreEqual(1, dt.Rows[0]["applicationId"]); Assert.AreEqual("user1", dt.Rows[0]["name"]); Assert.AreEqual(2, dt.Rows[1]["id"]); Assert.AreEqual(1, dt.Rows[1]["applicationId"]); Assert.AreEqual("user2", dt.Rows[1]["name"]); Assert.AreEqual(3, dt.Rows[2]["id"]); Assert.AreEqual(2, dt.Rows[2]["applicationId"]); Assert.AreEqual("user1", dt.Rows[2]["name"]); Assert.AreEqual(4, dt.Rows[3]["id"]); Assert.AreEqual(2, dt.Rows[3]["applicationId"]); Assert.AreEqual("user2", dt.Rows[3]["name"]); } [Test] public void CheckRolesUpgrade() { LoadData(); DataTable dt = FillTable("SELECT * FROM my_aspnet_Roles"); Assert.AreEqual(4, dt.Rows.Count); Assert.AreEqual(1, dt.Rows[0]["id"]); Assert.AreEqual(1, dt.Rows[0]["applicationId"]); Assert.AreEqual("role1", dt.Rows[0]["name"]); Assert.AreEqual(2, dt.Rows[1]["id"]); Assert.AreEqual(1, dt.Rows[1]["applicationId"]); Assert.AreEqual("role2", dt.Rows[1]["name"]); Assert.AreEqual(3, dt.Rows[2]["id"]); Assert.AreEqual(2, dt.Rows[2]["applicationId"]); Assert.AreEqual("role1", dt.Rows[2]["name"]); Assert.AreEqual(4, dt.Rows[3]["id"]); Assert.AreEqual(2, dt.Rows[3]["applicationId"]); Assert.AreEqual("role2", dt.Rows[3]["name"]); } [Test] public void CheckMembershipUpgrade() { LoadData(); DataTable dt = FillTable("SELECT * FROM my_aspnet_Membership"); Assert.AreEqual(4, dt.Rows.Count); Assert.AreEqual(1, dt.Rows[0]["userid"]); Assert.AreEqual(2, dt.Rows[1]["userid"]); Assert.AreEqual(3, dt.Rows[2]["userid"]); Assert.AreEqual(4, dt.Rows[3]["userid"]); } [Test] public void CheckUsersInRolesUpgrade() { LoadData(); DataTable dt = FillTable("SELECT * FROM my_aspnet_UsersInRoles"); Assert.AreEqual(4, dt.Rows.Count); Assert.AreEqual(1, dt.Rows[0]["userid"]); Assert.AreEqual(1, dt.Rows[0]["roleid"]); Assert.AreEqual(2, dt.Rows[1]["userid"]); Assert.AreEqual(2, dt.Rows[1]["roleid"]); Assert.AreEqual(3, dt.Rows[2]["userid"]); Assert.AreEqual(3, dt.Rows[2]["roleid"]); Assert.AreEqual(4, dt.Rows[3]["userid"]); Assert.AreEqual(4, dt.Rows[3]["roleid"]); } /// /// Bug #39072 Web provider does not work /// [Test] public void AutoGenerateSchema() { MySQLMembershipProvider provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("autogenerateschema", "true"); config.Add("applicationName", "/"); config.Add("passwordFormat", "Clear"); provider.Initialize(null, config); MembershipCreateStatus status; MembershipUser user = provider.CreateUser("boo", "password", "email@email.com", "question", "answer", true, null, out status); } [Test] public void SchemaTablesUseSameEngine() { DropAllTables(); for (int x = 1; x <= SchemaManager.Version; x++) LoadSchema(x); string query = string.Format("SELECT TABLE_NAME, ENGINE FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{0}'", conn.Database); MySqlCommand cmd = new MySqlCommand(query, conn); string lastEngine = null; string currentEngine; using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { currentEngine = reader.GetString("ENGINE"); if (string.IsNullOrEmpty(lastEngine)) { lastEngine = currentEngine; } Assert.AreEqual(lastEngine, currentEngine); } } } [Test] [ExpectedException(typeof(ArgumentException))] public void InitializeInvalidConnStringThrowsArgumentException() { Configuration configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); string connStr = configFile.ConnectionStrings.ConnectionStrings["LocalMySqlServer"].ConnectionString; string fakeConnectionString = connStr.Replace("database", "fooKey"); try { configFile.ConnectionStrings.ConnectionStrings["LocalMySqlServer"].ConnectionString = fakeConnectionString; configFile.Save(); ConfigurationManager.RefreshSection("connectionStrings"); MySQLMembershipProvider provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); provider.Initialize(null, config); } finally { configFile.ConnectionStrings.ConnectionStrings["LocalMySqlServer"].ConnectionString = connStr; configFile.Save(); ConfigurationManager.RefreshSection("connectionStrings"); } } } } mysql-connector-net-6.4.3/Tests/MySql.Web.Tests/App.config0000644000175000017500000000230211127003600024043 0ustar directhexdirecthex mysql-connector-net-6.4.3/Tests/MySql.Web.Tests/UserManagement.cs0000644000175000017500000007231711127003600025413 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12 // The copyright was assigned and transferred under the terms of // the MySQL Contributor License Agreement (CLA) using NUnit.Framework; using System.Web.Security; using System.Collections.Specialized; using System.Data; using System; using System.Configuration.Provider; using MySql.Web.Security; using MySql.Data.MySqlClient; namespace MySql.Web.Tests { [TestFixture] public class UserManagement : BaseWebTest { private MySQLMembershipProvider provider; [SetUp] public override void Setup() { base.Setup(); execSQL("DROP TABLE IF EXISTS mysql_membership"); } private void CreateUserWithFormat(MembershipPasswordFormat format) { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", format.ToString()); provider.Initialize(null, config); // create the user MembershipCreateStatus status; provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status); Assert.AreEqual(MembershipCreateStatus.Success, status); // verify that the password format is hashed. DataTable table = FillTable("SELECT * FROM my_aspnet_Membership"); MembershipPasswordFormat rowFormat = (MembershipPasswordFormat)Convert.ToInt32(table.Rows[0]["PasswordFormat"]); Assert.AreEqual(format, rowFormat); // then attempt to verify the user Assert.IsTrue(provider.ValidateUser("foo", "barbar!")); } [Test] public void CreateUserWithHashedPassword() { CreateUserWithFormat(MembershipPasswordFormat.Hashed); } [Test] public void CreateUserWithEncryptedPasswordWithAutoGenKeys() { try { CreateUserWithFormat(MembershipPasswordFormat.Encrypted); } catch (ProviderException) { } } [Test] public void CreateUserWithClearPassword() { CreateUserWithFormat(MembershipPasswordFormat.Clear); } /// /// Bug #34792 New User/Changing Password Validation Not working. /// [Test] public void ChangePassword() { CreateUserWithHashedPassword(); try { provider.ChangePassword("foo", "barbar!", "bar2"); Assert.Fail(); } catch (ArgumentException ae1) { Assert.AreEqual("newPassword", ae1.ParamName); Assert.IsTrue(ae1.Message.Contains("length of parameter")); } try { provider.ChangePassword("foo", "barbar!", "barbar2"); Assert.Fail(); } catch (ArgumentException ae1) { Assert.AreEqual("newPassword", ae1.ParamName); Assert.IsTrue(ae1.Message.Contains("alpha numeric")); } // now test regex strength testing bool result = provider.ChangePassword("foo", "barbar!", "zzzxxx!"); Assert.IsFalse(result); // now do one that should work result = provider.ChangePassword("foo", "barbar!", "barfoo!"); Assert.IsTrue(result); provider.ValidateUser("foo", "barfoo!"); } /// /// Bug #34792 New User/Changing Password Validation Not working. /// [Test] public void CreateUserWithErrors() { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", "Hashed"); provider.Initialize(null, config); // first try to create a user with a password not long enough MembershipCreateStatus status; MembershipUser user = provider.CreateUser("foo", "xyz", "foo@bar.com", null, null, true, null, out status); Assert.IsNull(user); Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status); // now with not enough non-alphas user = provider.CreateUser("foo", "xyz1234", "foo@bar.com", null, null, true, null, out status); Assert.IsNull(user); Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status); // now one that doesn't pass the regex test user = provider.CreateUser("foo", "xyzxyz!", "foo@bar.com", null, null, true, null, out status); Assert.IsNull(user); Assert.AreEqual(MembershipCreateStatus.InvalidPassword, status); // now one that works user = provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status); Assert.IsNotNull(user); Assert.AreEqual(MembershipCreateStatus.Success, status); } [Test] public void DeleteUser() { CreateUserWithHashedPassword(); Assert.IsTrue(provider.DeleteUser("foo", true)); DataTable table = FillTable("SELECT * FROM my_aspnet_Membership"); Assert.AreEqual(0, table.Rows.Count); table = FillTable("SELECT * FROM my_aspnet_Users"); Assert.AreEqual(0, table.Rows.Count); CreateUserWithHashedPassword(); provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); provider.Initialize(null, config); Assert.IsTrue(Membership.DeleteUser("foo", false)); table = FillTable("SELECT * FROM my_aspnet_Membership"); Assert.AreEqual(0, table.Rows.Count); table = FillTable("SELECT * FROM my_aspnet_Users"); Assert.AreEqual(1, table.Rows.Count); } [Test] public void FindUsersByName() { CreateUserWithHashedPassword(); int records; MembershipUserCollection users = provider.FindUsersByName("F%", 0, 10, out records); Assert.AreEqual(1, records); Assert.AreEqual("foo", users["foo"].UserName); } [Test] public void FindUsersByEmail() { CreateUserWithHashedPassword(); int records; MembershipUserCollection users = provider.FindUsersByEmail("foo@bar.com", 0, 10, out records); Assert.AreEqual(1, records); Assert.AreEqual("foo", users["foo"].UserName); } [Test] public void TestCreateUserOverrides() { try { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status); int records; MembershipUserCollection users = Membership.FindUsersByName("F%", 0, 10, out records); Assert.AreEqual(1, records); Assert.AreEqual("foo", users["foo"].UserName); Membership.CreateUser("test", "barbar!", "myemail@host.com", "question", "answer", true, out status); users = Membership.FindUsersByName("T%", 0, 10, out records); Assert.AreEqual(1, records); Assert.AreEqual("test", users["test"].UserName); } catch (Exception ex) { Assert.Fail(ex.Message); } } [Test] public void NumberOfUsersOnline() { int numOnline = Membership.GetNumberOfUsersOnline(); Assert.AreEqual(0, numOnline); MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status); Membership.CreateUser("foo2", "barbar!", null, "question", "answer", true, out status); numOnline = Membership.GetNumberOfUsersOnline(); Assert.AreEqual(2, numOnline); } [Test] public void UnlockUser() { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status); Assert.IsFalse(Membership.ValidateUser("foo", "bar2")); Assert.IsFalse(Membership.ValidateUser("foo", "bar3")); Assert.IsFalse(Membership.ValidateUser("foo", "bar3")); Assert.IsFalse(Membership.ValidateUser("foo", "bar3")); Assert.IsFalse(Membership.ValidateUser("foo", "bar3")); // the user should be locked now so the right password should fail Assert.IsFalse(Membership.ValidateUser("foo", "barbar!")); MembershipUser user = Membership.GetUser("foo"); Assert.IsTrue(user.IsLockedOut); Assert.IsTrue(user.UnlockUser()); user = Membership.GetUser("foo"); Assert.IsFalse(user.IsLockedOut); Assert.IsTrue(Membership.ValidateUser("foo", "barbar!")); } [Test] public void GetUsernameByEmail() { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", "foo@bar.com", "question", "answer", true, out status); string username = Membership.GetUserNameByEmail("foo@bar.com"); Assert.AreEqual("foo", username); username = Membership.GetUserNameByEmail("foo@b.com"); Assert.IsNull(username); username = Membership.GetUserNameByEmail(" foo@bar.com "); Assert.AreEqual("foo", username); } [Test] public void UpdateUser() { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, out status); Assert.AreEqual(MembershipCreateStatus.Success, status); MembershipUser user = Membership.GetUser("foo"); user.Comment = "my comment"; user.Email = "my email"; user.IsApproved = false; user.LastActivityDate = new DateTime(2008, 1, 1); user.LastLoginDate = new DateTime(2008, 2, 1); Membership.UpdateUser(user); MembershipUser newUser = Membership.GetUser("foo"); Assert.AreEqual(user.Comment, newUser.Comment); Assert.AreEqual(user.Email, newUser.Email); Assert.AreEqual(user.IsApproved, newUser.IsApproved); Assert.AreEqual(user.LastActivityDate, newUser.LastActivityDate); Assert.AreEqual(user.LastLoginDate, newUser.LastLoginDate); } private void ChangePasswordQAHelper(MembershipUser user, string pw, string newQ, string newA) { try { user.ChangePasswordQuestionAndAnswer(pw, newQ, newA); Assert.Fail("This should not work."); } catch (ArgumentNullException ane) { Assert.AreEqual("password", ane.ParamName); } catch (ArgumentException) { Assert.IsNotNull(pw); } } [Test] public void ChangePasswordQuestionAndAnswer() { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, out status); Assert.AreEqual(MembershipCreateStatus.Success, status); MembershipUser user = Membership.GetUser("foo"); ChangePasswordQAHelper(user, "", "newQ", "newA"); ChangePasswordQAHelper(user, "barbar!", "", "newA"); ChangePasswordQAHelper(user, "barbar!", "newQ", ""); ChangePasswordQAHelper(user, null, "newQ", "newA"); bool result = user.ChangePasswordQuestionAndAnswer("barbar!", "newQ", "newA"); Assert.IsTrue(result); user = Membership.GetUser("foo"); Assert.AreEqual("newQ", user.PasswordQuestion); } [Test] public void GetAllUsers() { MembershipCreateStatus status; // first create a bunch of users for (int i=0; i < 100; i++) Membership.CreateUser(String.Format("foo{0}", i), "barbar!", null, "question", "answer", true, out status); MembershipUserCollection users = Membership.GetAllUsers(); Assert.AreEqual(100, users.Count); int index = 0; foreach (MembershipUser user in users) Assert.AreEqual(String.Format("foo{0}", index++), user.UserName); int total; users = Membership.GetAllUsers(2, 10, out total); Assert.AreEqual(10, users.Count); Assert.AreEqual(100, total); index = 0; foreach (MembershipUser user in users) Assert.AreEqual(String.Format("foo2{0}", index++), user.UserName); } private void GetPasswordHelper(bool requireQA, bool enablePasswordRetrieval, string answer) { MembershipCreateStatus status; provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("requiresQuestionAndAnswer", requireQA ? "true" : "false"); config.Add("enablePasswordRetrieval", enablePasswordRetrieval ? "true" : "false"); config.Add("passwordFormat", "clear"); config.Add("applicationName", "/"); config.Add("writeExceptionsToEventLog", "false"); provider.Initialize(null, config); provider.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, null, out status); try { string password = provider.GetPassword("foo", answer); if (!enablePasswordRetrieval) Assert.Fail("This should have thrown an exception"); Assert.AreEqual("barbar!", password); } catch (MembershipPasswordException) { if (requireQA && answer != null) Assert.Fail("This should not have thrown an exception"); } catch (ProviderException) { if (requireQA && answer != null) Assert.Fail("This should not have thrown an exception"); } } [Test] public void GetPassword() { GetPasswordHelper(false, false, null); GetPasswordHelper(false, true, null); GetPasswordHelper(true, true, null); GetPasswordHelper(true, true, "blue"); } /// /// Bug #38939 MembershipUser.GetPassword(string answer) fails when incorrect answer is passed. /// [Test] public void GetPasswordWithWrongAnswer() { MembershipCreateStatus status; provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("requiresQuestionAndAnswer", "true"); config.Add("enablePasswordRetrieval", "true"); config.Add("passwordFormat", "Encrypted"); config.Add("applicationName", "/"); provider.Initialize(null, config); provider.CreateUser("foo", "barbar!", "foo@bar.com", "color", "blue", true, null, out status); MySQLMembershipProvider provider2 = new MySQLMembershipProvider(); NameValueCollection config2 = new NameValueCollection(); config2.Add("connectionStringName", "LocalMySqlServer"); config2.Add("requiresQuestionAndAnswer", "true"); config2.Add("enablePasswordRetrieval", "true"); config2.Add("passwordFormat", "Encrypted"); config2.Add("applicationName", "/"); provider2.Initialize(null, config2); try { string pw = provider2.GetPassword("foo", "wrong"); Assert.Fail("Should have failed"); } catch (MembershipPasswordException) { } } [Test] public void GetUser() { MembershipCreateStatus status; Membership.CreateUser("foo", "barbar!", null, "question", "answer", true, out status); MembershipUser user = Membership.GetUser(1); Assert.AreEqual("foo", user.UserName); // now move the activity date back outside the login // window user.LastActivityDate = new DateTime(2008, 1, 1); Membership.UpdateUser(user); user = Membership.GetUser("foo"); Assert.IsFalse(user.IsOnline); user = Membership.GetUser("foo", true); Assert.IsTrue(user.IsOnline); // now move the activity date back outside the login // window again user.LastActivityDate = new DateTime(2008, 1, 1); Membership.UpdateUser(user); user = Membership.GetUser(1); Assert.IsFalse(user.IsOnline); user = Membership.GetUser(1, true); Assert.IsTrue(user.IsOnline); } [Test] public void FindUsers() { MembershipCreateStatus status; for (int i=0; i < 100; i++) Membership.CreateUser(String.Format("boo{0}", i), "barbar!", null, "question", "answer", true, out status); for (int i=0; i < 100; i++) Membership.CreateUser(String.Format("foo{0}", i), "barbar!", null, "question", "answer", true, out status); for (int i=0; i < 100; i++) Membership.CreateUser(String.Format("schmoo{0}", i), "barbar!", null, "question", "answer", true, out status); MembershipUserCollection users = Membership.FindUsersByName("fo%"); Assert.AreEqual(100, users.Count); int total; users = Membership.FindUsersByName("fo%", 2, 10, out total); Assert.AreEqual(10, users.Count); Assert.AreEqual(100, total); int index = 0; foreach (MembershipUser user in users) Assert.AreEqual(String.Format("foo2{0}", index++), user.UserName); } [Test] public void CreateUserWithNoQA() { MembershipCreateStatus status; provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("requiresQuestionAndAnswer", "true"); config.Add("passwordFormat", "clear"); config.Add("applicationName", "/"); provider.Initialize(null, config); try { provider.CreateUser("foo", "barbar!", "foo@bar.com", "color", null, true, null, out status); Assert.Fail(); } catch (Exception ex) { Assert.IsTrue(ex.Message.StartsWith("Password answer supplied is invalid")); } try { provider.CreateUser("foo", "barbar!", "foo@bar.com", "", "blue", true, null, out status); Assert.Fail(); } catch (Exception ex) { Assert.IsTrue(ex.Message.StartsWith("Password question supplied is invalid")); } } [Test] public void MinRequiredAlpha() { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("minRequiredNonalphanumericCharacters", "3"); provider.Initialize(null, config); MembershipCreateStatus status; MembershipUser user = provider.CreateUser("foo", "pw!pass", "email", null, null, true, null, out status); Assert.IsNull(user); user = provider.CreateUser("foo", "pw!pa!!", "email", null, null, true, null, out status); Assert.IsNotNull(user); } /// /// Bug #35332 GetPassword() don't working (when PasswordAnswer is NULL) /// [Test] public void GetPasswordWithNullValues() { MembershipCreateStatus status; provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("requiresQuestionAndAnswer", "false"); config.Add("enablePasswordRetrieval", "true"); config.Add("passwordFormat", "clear"); config.Add("applicationName", "/"); provider.Initialize(null, config); MembershipUser user = provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status); Assert.IsNotNull(user); string pw = provider.GetPassword("foo", null); Assert.AreEqual("barbar!", pw); } /// /// Bug #35336 GetPassword() return wrong password (when format is encrypted) /// [Test] public void GetEncryptedPassword() { MembershipCreateStatus status; provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("requiresQuestionAndAnswer", "false"); config.Add("enablePasswordRetrieval", "true"); config.Add("passwordFormat", "encrypted"); config.Add("applicationName", "/"); provider.Initialize(null, config); MembershipUser user = provider.CreateUser("foo", "barbar!", "foo@bar.com", null, null, true, null, out status); Assert.IsNotNull(user); string pw = provider.GetPassword("foo", null); Assert.AreEqual("barbar!", pw); } /// /// Bug #42574 ValidateUser does not use the application id, allowing cross application login /// [Test] public void CrossAppLogin() { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", "Clear"); provider.Initialize(null, config); MembershipCreateStatus status; provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status); MySQLMembershipProvider provider2 = new MySQLMembershipProvider(); NameValueCollection config2 = new NameValueCollection(); config2.Add("connectionStringName", "LocalMySqlServer"); config2.Add("applicationName", "/myapp"); config2.Add("passwordStrengthRegularExpression", ".*"); config2.Add("passwordFormat", "Clear"); provider2.Initialize(null, config2); bool worked = provider2.ValidateUser("foo", "bar!bar"); Assert.AreEqual(false, worked); } /// /// Bug #41408 PasswordReset not possible when requiresQuestionAndAnswer="false" /// [Test] public void ResetPassword() { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", "Clear"); config.Add("requiresQuestionAndAnswer", "false"); provider.Initialize(null, config); MembershipCreateStatus status; provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status); MembershipUser u = provider.GetUser("foo", false); string newpw = provider.ResetPassword("foo", null); } /// /// Bug #59438 setting Membership.ApplicationName has no effect /// [Test] public void ChangeAppName() { provider = new MySQLMembershipProvider(); NameValueCollection config = new NameValueCollection(); config.Add("connectionStringName", "LocalMySqlServer"); config.Add("applicationName", "/"); config.Add("passwordStrengthRegularExpression", "bar.*"); config.Add("passwordFormat", "Clear"); provider.Initialize(null, config); MembershipCreateStatus status; provider.CreateUser("foo", "bar!bar", null, null, null, true, null, out status); Assert.IsTrue(status == MembershipCreateStatus.Success); MySQLMembershipProvider provider2 = new MySQLMembershipProvider(); NameValueCollection config2 = new NameValueCollection(); config2.Add("connectionStringName", "LocalMySqlServer"); config2.Add("applicationName", "/myapp"); config2.Add("passwordStrengthRegularExpression", "foo.*"); config2.Add("passwordFormat", "Clear"); provider2.Initialize(null, config2); provider2.CreateUser("foo2", "foo!foo", null, null, null, true, null, out status); Assert.IsTrue(status == MembershipCreateStatus.Success); provider.ApplicationName = "/myapp"; Assert.IsFalse(provider.ValidateUser("foo", "bar!bar")); Assert.IsTrue(provider.ValidateUser("foo2", "foo!foo")); } [Test] public void GetUserLooksForExactUsername() { MembershipCreateStatus status; Membership.CreateUser("code", "thecode!", null, "question", "answer", true, out status); MembershipUser user = Membership.GetUser("code"); Assert.AreEqual("code", user.UserName); user = Membership.GetUser("co_e"); Assert.IsNull(user); } [Test] public void GetUserNameByEmailLooksForExactEmail() { MembershipCreateStatus status; Membership.CreateUser("code", "thecode!", "code@mysql.com", "question", "answer", true, out status); string username = Membership.GetUserNameByEmail("code@mysql.com"); Assert.AreEqual("code", username); username = Membership.GetUserNameByEmail("co_e@mysql.com"); Assert.IsNull(username); } } } mysql-connector-net-6.4.3/Tests/MySql.Web.Tests/Properties/0000755000175000017500000000000011127003600024273 5ustar directhexdirecthexmysql-connector-net-6.4.3/Tests/MySql.Web.Tests/Properties/AssemblyInfo.cs0000644000175000017500000000425611127003600027224 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MySql.Web.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Oracle")] [assembly: AssemblyProduct("MySql.Web.Tests")] [assembly: AssemblyCopyright("Copyright © 2004, 2010, Oracle and/or its affiliates. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5ea74c78-c679-464f-99ba-ae1b0b54550b")] mysql-connector-net-6.4.3/Tests/MySql.Web.Tests/TestProfile.cs0000644000175000017500000000474511127003600024740 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12 // The copyright was assigned and transferred under the terms of // the MySQL Contributor License Agreement (CLA) using System; using System.Collections.Generic; using System.Text; using System.Web.Profile; using System.Web.Security; namespace MySql.Web.Tests { public class TestProfile : ProfileBase { public static TestProfile GetUserProfile(string username, bool auth) { return Create(username, auth) as TestProfile; } public static TestProfile GetUserProfile(bool auth) { return Create(Membership.GetUser().UserName, auth) as TestProfile; } [SettingsAllowAnonymous(false)] public string Description { get { return base["Description"] as string; } set { base["Description"] = value; } } [SettingsAllowAnonymous(false)] public string Location { get { return base["Location"] as string; } set { base["Location"] = value; } } [SettingsAllowAnonymous(false)] public string FavoriteMovie { get { return base["FavoriteMovie"] as string; } set { base["FavoriteMovie"] = value; } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/0000755000175000017500000000000011127003600023546 5ustar directhexdirecthexmysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/DataTypeTests.cs0000644000175000017500000001261511127003600026640 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using System.Linq; using MySql.Data.MySqlClient; using NUnit.Framework; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using System.Data.Objects; using System.Globalization; namespace MySql.Data.Entity.Tests { [TestFixture] public class DataTypeTests : BaseEdmTest { /// /// Bug #45457 DbType Time is not supported in entity framework /// [Test] public void TimeType() { using (testEntities context = new testEntities()) { TimeSpan birth = new TimeSpan(11,3,2); Child c = new Child(); c.Id = 20; c.EmployeeID = 1; c.FirstName = "first"; c.LastName = "last"; c.BirthTime = birth; c.Modified = DateTime.Now; context.AddToChildren(c); context.SaveChanges(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM EmployeeChildren WHERE id=20", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(birth, dt.Rows[0]["birthtime"]); } } /// /// Bug #45077 Insert problem with Connector/NET 6.0.3 and entity framework /// Bug #45175 Wrong SqlType for unsigned smallint when generating Entity Framework Model /// [Test] public void UnsignedValues() { using (testEntities context = new testEntities()) { var row = context.Children.First(); context.Detach(row); context.Attach(row); } } /// /// Bug #44455 insert and update error with entity framework /// [Test] public void DoubleValuesNonEnglish() { CultureInfo curCulture = Thread.CurrentThread.CurrentCulture; CultureInfo curUICulture = Thread.CurrentThread.CurrentUICulture; CultureInfo newCulture = new CultureInfo("da-DK"); Thread.CurrentThread.CurrentCulture = newCulture; Thread.CurrentThread.CurrentUICulture = newCulture; try { using (testEntities context = new testEntities()) { Child c = new Child(); c.Id = 20; c.EmployeeID = 1; c.FirstName = "Bam bam"; c.LastName = "Rubble"; c.BirthWeight = 8.65; c.Modified = DateTime.Now; context.AddToChildren(c); context.SaveChanges(); } } finally { Thread.CurrentThread.CurrentCulture = curCulture; Thread.CurrentThread.CurrentUICulture = curUICulture; } } /// /// Bug #46311 TimeStamp table column Entity Framework issue. /// [Test] public void TimestampColumn() { DateTime now = DateTime.Now; using (testEntities context = new testEntities()) { Child c = context.Children.First(); DateTime dt = c.Modified; c.Modified = now; context.SaveChanges(); c = context.Children.First(); dt = c.Modified; Assert.AreEqual(now, dt); } } /// /// Bug #48417 Invalid cast from 'System.String' to 'System.Guid' /// [Test] public void GuidType() { using (testEntities context = new testEntities()) { DataTypeTest dtt = context.DataTypeTests.First(); string guidAsChar = dtt.idAsChar; Assert.AreEqual(0, String.Compare(guidAsChar, dtt.id.ToString(), true)); Assert.AreEqual(0, String.Compare(guidAsChar, dtt.id2.ToString(), true)); } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Model1.Designer.cs0000644000175000017500000002136211127003600026761 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // //------------------------------------------------------------------------------ using System; using System.Data.Objects; using System.Data.Objects.DataClasses; using System.Data.EntityClient; using System.ComponentModel; using System.Xml.Serialization; using System.Runtime.Serialization; [assembly: EdmSchemaAttribute()] namespace MySql.Data.Entity.Tests { #region Contexts /// /// No Metadata Documentation available. /// public partial class Model1Container : ObjectContext { #region Constructors /// /// Initializes a new Model1Container object using the connection string found in the 'Model1Container' section of the application configuration file. /// public Model1Container() : base("name=Model1Container", "Model1Container") { OnContextCreated(); } /// /// Initialize a new Model1Container object. /// public Model1Container(string connectionString) : base(connectionString, "Model1Container") { OnContextCreated(); } /// /// Initialize a new Model1Container object. /// public Model1Container(EntityConnection connection) : base(connection, "Model1Container") { OnContextCreated(); } #endregion #region Partial Methods partial void OnContextCreated(); #endregion #region ObjectSet Properties /// /// No Metadata Documentation available. /// public ObjectSet Animals { get { if ((_Animals == null)) { _Animals = base.CreateObjectSet("Animals"); } return _Animals; } } private ObjectSet _Animals; /// /// No Metadata Documentation available. /// public ObjectSet Shelters { get { if ((_Shelters == null)) { _Shelters = base.CreateObjectSet("Shelters"); } return _Shelters; } } private ObjectSet _Shelters; #endregion #region AddTo Methods /// /// Deprecated Method for adding a new object to the Animals EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToAnimals(Animal animal) { base.AddObject("Animals", animal); } /// /// Deprecated Method for adding a new object to the Shelters EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToShelters(Shelter shelter) { base.AddObject("Shelters", shelter); } #endregion } #endregion #region Entities /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="Model1", Name="Animal")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Animal : EntityObject { #region Factory Method /// /// Create a new Animal object. /// /// Initial value of the Id property. /// Initial value of the Name property. /// Initial value of the ShelterId property. public static Animal CreateAnimal(global::System.Int32 id, global::System.String name, global::System.Int32 shelterId) { Animal animal = new Animal(); animal.Id = id; animal.Name = name; animal.ShelterId = shelterId; return animal; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Name { get { return _Name; } set { OnNameChanging(value); ReportPropertyChanging("Name"); _Name = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Name"); OnNameChanged(); } } private global::System.String _Name; partial void OnNameChanging(global::System.String value); partial void OnNameChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 ShelterId { get { return _ShelterId; } set { OnShelterIdChanging(value); ReportPropertyChanging("ShelterId"); _ShelterId = StructuralObject.SetValidValue(value); ReportPropertyChanged("ShelterId"); OnShelterIdChanged(); } } private global::System.Int32 _ShelterId; partial void OnShelterIdChanging(global::System.Int32 value); partial void OnShelterIdChanged(); #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="Model1", Name="Shelter")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Shelter : EntityObject { #region Factory Method /// /// Create a new Shelter object. /// /// Initial value of the Id property. public static Shelter CreateShelter(global::System.Int32 id) { Shelter shelter = new Shelter(); shelter.Id = id; return shelter; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); #endregion } #endregion } mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/BaseEdmTest.cs0000644000175000017500000001250111127003600026234 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12 // The copyright was assigned and transferred under the terms of // the MySQL Contributor License Agreement (CLA) using MySql.Data.MySqlClient; using System.Data; using System.Configuration; using System.Reflection; using System; using System.Collections.Specialized; using System.Diagnostics; using MySql.Data.MySqlClient.Tests; using System.Resources; using System.Xml; using System.IO; using NUnit.Framework; using System.Text; using System.Data.EntityClient; using MySql.Data.Entity.Tests.Properties; namespace MySql.Data.Entity.Tests { public class BaseEdmTest : BaseTest { protected override void LoadStaticConfiguration() { base.LoadStaticConfiguration(); Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); string filename = config.FilePath; database0 = database1 = "test"; XmlDocument configDoc = new XmlDocument(); configDoc.PreserveWhitespace = true; configDoc.Load(filename); XmlElement configNode = configDoc["configuration"]; configNode.RemoveAll(); XmlElement systemData = (XmlElement)configDoc.CreateNode(XmlNodeType.Element, "system.data", ""); XmlElement dbFactories = (XmlElement)configDoc.CreateNode(XmlNodeType.Element, "DbProviderFactories", ""); XmlElement provider = (XmlElement)configDoc.CreateNode(XmlNodeType.Element, "add", ""); provider.SetAttribute("name", "MySQL Data Provider"); provider.SetAttribute("description", ".Net Framework Data Provider for MySQL"); provider.SetAttribute("invariant", "MySql.Data.MySqlClient"); string fullname = String.Format("MySql.Data.MySqlClient.MySqlClientFactory, {0}", typeof(MySqlConnection).Assembly.FullName); provider.SetAttribute("type", fullname); dbFactories.AppendChild(provider); systemData.AppendChild(dbFactories); configNode.AppendChild(systemData); configDoc.Save(filename); ConfigurationManager.RefreshSection("system.data"); } [SetUp] public override void Setup() { base.Setup(); ResourceManager r = new ResourceManager("MySql.Data.Entity.Tests.Properties.Resources", typeof(BaseEdmTest).Assembly); string schema = r.GetString("schema"); MySqlScript script = new MySqlScript(conn); script.Query = schema; script.Execute(); // now create our procs schema = r.GetString("procs"); script = new MySqlScript(conn); script.Delimiter = "$$"; script.Query = schema; script.Execute(); MySqlCommand cmd = new MySqlCommand("DROP DATABASE IF EXISTS `modeldb`", rootConn); cmd.ExecuteNonQuery(); } [TearDown] public override void Teardown() { MySqlCommand cmd = new MySqlCommand("DROP DATABASE IF EXISTS `modeldb`", rootConn); cmd.ExecuteNonQuery(); base.Teardown(); } private EntityConnection GetEntityConnection() { string connectionString = String.Format( "metadata=TestDB.csdl|TestDB.msl|TestDB.ssdl;provider=MySql.Data.MySqlClient; provider connection string=\"{0}\"", GetConnectionString(true)); EntityConnection connection = new EntityConnection(connectionString); return connection; } protected void CheckSql(string sql, string refSql) { StringBuilder str1 = new StringBuilder(); StringBuilder str2 = new StringBuilder(); foreach (char c in sql) if (!Char.IsWhiteSpace(c)) str1.Append(c); foreach (char c in refSql) if (!Char.IsWhiteSpace(c)) str2.Append(c); Assert.AreEqual(0, String.Compare(str1.ToString(), str2.ToString(), true)); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/CanonicalFunctions.cs0000644000175000017500000002352211127003600027661 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using NUnit.Framework; using System.Data.Objects; using System.Linq; namespace MySql.Data.Entity.Tests { [TestFixture] public class CanonicalFunctions : BaseEdmTest { private EntityConnection GetEntityConnection() { string connectionString = String.Format( "metadata=TestDB.csdl|TestDB.msl|TestDB.ssdl;provider=MySql.Data.MySqlClient; provider connection string=\"{0}\"", GetConnectionString(true)); EntityConnection connection = new EntityConnection(connectionString); return connection; } [Test] public void Bitwise() { using (testEntities context = new testEntities()) { ObjectQuery q = context.CreateQuery("BitwiseAnd(255,15)"); foreach (int i in q) Assert.AreEqual(15, i); q = context.CreateQuery("BitwiseOr(240,31)"); foreach (int i in q) Assert.AreEqual(255, i); q = context.CreateQuery("BitwiseXor(255,15)"); foreach (int i in q) Assert.AreEqual(240, i); } } [Test] public void CurrentDateTime() { DateTime current = DateTime.Now; using (testEntities context = new testEntities()) { ObjectQuery q = context.CreateQuery("CurrentDateTime()"); foreach (DateTime dt in q) { Assert.AreEqual(current.Year, dt.Year); Assert.AreEqual(current.Month, dt.Month); Assert.AreEqual(current.Day, dt.Day); // we don't check time as that will be always be different } } } [Test] public void YearMonthDay() { using (testEntities context = new testEntities()) { ObjectQuery q = context.CreateQuery( @"SELECT c.DateBegan, Year(c.DateBegan), Month(c.DateBegan), Day(c.DateBegan) FROM Companies AS c WHERE c.Id=1"); foreach (DbDataRecord record in q) { Assert.AreEqual(1996, record[1]); Assert.AreEqual(11, record[2]); Assert.AreEqual(15, record[3]); } } } [Test] public void HourMinuteSecond() { using (testEntities context = new testEntities()) { ObjectQuery q = context.CreateQuery( @"SELECT c.DateBegan, Hour(c.DateBegan), Minute(c.DateBegan), Second(c.DateBegan) FROM Companies AS c WHERE c.Id=1"); foreach (DbDataRecord record in q) { Assert.AreEqual(5, record[1]); Assert.AreEqual(18, record[2]); Assert.AreEqual(23, record[3]); } } } [Test] public void IndexOf() { using (testEntities context = new testEntities()) { ObjectQuery q = context.CreateQuery(@"IndexOf('needle', 'haystackneedle')"); foreach (int index in q) Assert.AreEqual(9, index); q = context.CreateQuery(@"IndexOf('haystack', 'needle')"); foreach (int index in q) Assert.AreEqual(0, index); } } [Test] public void LeftRight() { using (testEntities context = new testEntities()) { string entitySQL = "CONCAT(LEFT('foo',3),RIGHT('bar',3))"; ObjectQuery query = context.CreateQuery(entitySQL); foreach (string s in query) Assert.AreEqual("foobar", s); entitySQL = "CONCAT(LEFT('foobar',3),RIGHT('barfoo',3))"; query = context.CreateQuery(entitySQL); foreach (string s in query) Assert.AreEqual("foofoo", s); entitySQL = "CONCAT(LEFT('foobar',8),RIGHT('barfoo',8))"; query = context.CreateQuery(entitySQL); foreach (string s in query) Assert.AreEqual("foobarbarfoo", s); } } [Test] public void Length() { using (testEntities context = new testEntities()) { string entitySQL = "Length('abc')"; ObjectQuery query = context.CreateQuery(entitySQL); foreach (int len in query) Assert.AreEqual(3, len); } } [Test] public void Trims() { using (testEntities context = new testEntities()) { ObjectQuery query = context.CreateQuery("LTrim(' text ')"); foreach (string s in query) Assert.AreEqual("text ", s); query = context.CreateQuery("RTrim(' text ')"); foreach (string s in query) Assert.AreEqual(" text", s); query = context.CreateQuery("Trim(' text ')"); foreach (string s in query) Assert.AreEqual("text", s); } } [Test] public void Round() { using (testEntities context = new testEntities()) { ObjectQuery q = context.CreateQuery(@" SELECT o.Id, o.Freight, Round(o.Freight) AS [Rounded Freight], Floor(o.Freight) AS [Floor of Freight], Ceiling(o.Freight) AS [Ceiling of Freight] FROM Orders AS o WHERE o.Id=1"); foreach (DbDataRecord r in q) { Assert.AreEqual(1, r[0]); Assert.AreEqual(65.3, r[1]); Assert.AreEqual(65, r[2]); Assert.AreEqual(65, r[3]); Assert.AreEqual(66, r[4]); } } } [Test] public void Substring() { using (testEntities context = new testEntities()) { ObjectQuery query = context.CreateQuery("SUBSTRING('foobarfoo',4,3)"); query = context.CreateQuery("SUBSTRING('foobarfoo',4,30)"); foreach (string s in query) Assert.AreEqual("barfoo", s); } } [Test] public void ToUpperToLowerReverse() { using (testEntities context = new testEntities()) { ObjectQuery q = context.CreateQuery( @"SELECT ToUpper(c.Name),ToLower(c.Name), Reverse(c.Name) FROM Companies AS c WHERE c.Id=1"); foreach (DbDataRecord r in q) { Assert.AreEqual("HASBRO", r[0]); Assert.AreEqual("hasbro", r[1]); Assert.AreEqual("orbsaH", r[2]); } } } [Test] public void Replace() { using (testEntities context = new testEntities()) { ObjectQuery q = context.CreateQuery( @"Replace('abcdefghi', 'def', 'zzz')"); foreach (string s in q) Assert.AreEqual("abczzzghi", s); } } #if CLR4 [Test] public void CanRoundToNonZeroDigits() { using (testEntities context = new testEntities()) { DbDataRecord order = context.CreateQuery(@" SELECT o.Id, o.Freight, Round(o.Freight, 2) AS [Rounded Freight] FROM Orders AS o WHERE o.Id=10").First(); Assert.AreEqual(350.54721, order[1]); Assert.AreEqual(350.55, order[2]); } } #endif } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/SetOperators.cs0000644000175000017500000000763511127003600026542 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using NUnit.Framework; using System.Data.Objects; using System.Linq; using MySql.Data.Entity.Tests.Properties; namespace MySql.Data.Entity.Tests { [TestFixture] public class SetOperators : BaseEdmTest { [Test] public void Any() { MySqlDataAdapter da = new MySqlDataAdapter( @"SELECT a.id FROM authors a WHERE NOT EXISTS(SELECT * FROM books b WHERE b.author_id=a.id)", conn); DataTable dt = new DataTable(); da.Fill(dt); int i = 0; // find all authors that are in our db with no books using (testEntities context = new testEntities()) { var authors = from a in context.Authors where !a.Books.Any() select a; string sql = authors.ToTraceString(); CheckSql(sql, SQLSyntax.Any); foreach (Author a in authors) Assert.AreEqual(dt.Rows[i++]["id"], a.Id); } } [Test] public void FirstSimple() { MySqlCommand cmd = new MySqlCommand("SELECT id FROM orders", conn); int id = (int)cmd.ExecuteScalar(); using (testEntities context = new testEntities()) { var q = from o in context.Orders select o; Order order = q.First() as Order; Assert.AreEqual(id, order.Id); } } [Test] public void FirstPredicate() { MySqlCommand cmd = new MySqlCommand("SELECT id FROM orders WHERE freight > 100", conn); int id = (int)cmd.ExecuteScalar(); using (testEntities context = new testEntities()) { var q = from o in context.Orders where o.Freight > 100 select o; Order order = q.First() as Order; Assert.AreEqual(id, order.Id); } } [Test] public void Distinct() { using (testEntities context = new testEntities()) { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Companies LIMIT 2", conn); DataTable dt = new DataTable(); da.Fill(dt); int i = 0; var query = context.Companies.Top("2"); foreach (Company c in query) { Assert.AreEqual(dt.Rows[i++]["id"], c.Id); } } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/TestModel.edmx0000644000175000017500000011167111127003600026334 0ustar directhexdirecthex mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/DeleteTests.cs0000644000175000017500000000555511127003600026334 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using NUnit.Framework; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using System.Data.Objects; namespace MySql.Data.Entity.Tests { [TestFixture] public class DeleteTests : BaseEdmTest { [Test] public void SimpleDeleteAllRows() { using (testEntities context = new testEntities()) { foreach (Toy t in context.Toys) context.DeleteObject(t); context.SaveChanges(); EntityConnection ec = context.Connection as EntityConnection; MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM toys", (MySqlConnection)ec.StoreConnection); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(0, dt.Rows.Count); } } [Test] public void SimpleDeleteRowByParameter() { using (testEntities context = new testEntities()) { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM toys WHERE minage=3", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.IsTrue(dt.Rows.Count > 0); ObjectQuery toys = context.Toys.Where("it.MinAge = @age", new ObjectParameter("age", 3)); foreach (Toy t in toys) context.DeleteObject(t); context.SaveChanges(); dt.Clear(); da.Fill(dt); Assert.AreEqual(0, dt.Rows.Count); } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Paging.cs0000644000175000017500000001073411127003600025307 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Tests; using System.Linq; using System.Data.EntityClient; using System.Data.Common; using NUnit.Framework; using System.Data.Objects; using MySql.Data.Entity.Tests.Properties; namespace MySql.Data.Entity.Tests { [TestFixture] public class Paging : BaseEdmTest { [Test] public void Top() { using (testEntities context = new testEntities()) { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Companies LIMIT 2", conn); DataTable dt = new DataTable(); da.Fill(dt); int i = 0; var query = context.Companies.Top("2"); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.Top); foreach (Company c in query) { Assert.AreEqual(dt.Rows[i++]["id"], c.Id); } } } [Test] public void Skip() { using (testEntities context = new testEntities()) { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Companies LIMIT 3,20", conn); DataTable dt = new DataTable(); da.Fill(dt); int i = 0; var query = context.Companies.Skip("it.Id", "3"); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.Skip); foreach (Company c in query) { Assert.AreEqual(dt.Rows[i++]["id"], c.Id); } } } [Test] public void SkipAndTakeSimple() { using (testEntities context = new testEntities()) { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Companies LIMIT 2,2", conn); DataTable dt = new DataTable(); da.Fill(dt); int i = 0; var query = context.Companies.Skip("it.Id", "2").Top("2"); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.SkipAndTakeSimple); foreach (Company c in query) { Assert.AreEqual(dt.Rows[i++]["id"], c.Id); } Assert.AreEqual(2, i); } } /// /// Bug #45723 Entity Framework DbSortExpression not processed when using Skip & Take /// [Test] public void SkipAndTakeWithOrdering() { using (testEntities context = new testEntities()) { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Companies ORDER BY Name DESC LIMIT 2,2", conn); DataTable dt = new DataTable(); da.Fill(dt); int i = 0; var query = context.Companies.OrderByDescending(q => q.Name).Skip(2).Take(2); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.SkipAndTakeWithOrdering); foreach (Company c in query) Assert.AreEqual(dt.Rows[i++]["Name"], c.Name); } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Model1.edmx0000644000175000017500000001017011127003600025545 0ustar directhexdirecthex mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Model2.Designer.cs0000644000175000017500000002765311127003600026773 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.5446 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ [assembly: global::System.Data.Objects.DataClasses.EdmSchemaAttribute()] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("juliotestsModel", "FK_ORDER_CUSTOMER", "customer", global::System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(MySql.Data.Entity.Tests.customer), "order", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(MySql.Data.Entity.Tests.order))] // Original file name: // Generation date: 6/29/2011 12:13:52 PM namespace MySql.Data.Entity.Tests { /// /// There are no comments for model2Entities in the schema. /// public partial class model2Entities : global::System.Data.Objects.ObjectContext { /// /// Initializes a new model2Entities object using the connection string found in the 'model2Entities' section of the application configuration file. /// public model2Entities() : base("name=model2Entities", "model2Entities") { this.OnContextCreated(); } /// /// Initialize a new model2Entities object. /// public model2Entities(string connectionString) : base(connectionString, "model2Entities") { this.OnContextCreated(); } /// /// Initialize a new model2Entities object. /// public model2Entities(global::System.Data.EntityClient.EntityConnection connection) : base(connection, "model2Entities") { this.OnContextCreated(); } partial void OnContextCreated(); /// /// There are no comments for customer in the schema. /// public global::System.Data.Objects.ObjectQuery customer { get { if ((this._customer == null)) { this._customer = base.CreateQuery("[customer]"); } return this._customer; } } private global::System.Data.Objects.ObjectQuery _customer; /// /// There are no comments for order in the schema. /// public global::System.Data.Objects.ObjectQuery order { get { if ((this._order == null)) { this._order = base.CreateQuery("[order]"); } return this._order; } } private global::System.Data.Objects.ObjectQuery _order; /// /// There are no comments for customer in the schema. /// public void AddTocustomer(customer customer) { base.AddObject("customer", customer); } /// /// There are no comments for order in the schema. /// public void AddToorder(order order) { base.AddObject("order", order); } } /// /// There are no comments for juliotestsModel.customer in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="juliotestsModel", Name="customer")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class customer : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new customer object. /// /// Initial value of Id. public static customer Createcustomer(int id) { customer customer = new customer(); customer.Id = id; return customer; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for order in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("juliotestsModel", "FK_ORDER_CUSTOMER", "order")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection order { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("juliotestsModel.FK_ORDER_CUSTOMER", "order"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("juliotestsModel.FK_ORDER_CUSTOMER", "order", value); } } } } /// /// There are no comments for juliotestsModel.order in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="juliotestsModel", Name="order")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class order : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new order object. /// /// Initial value of Id. /// Initial value of Order_Date. public static order Createorder(int id, global::System.DateTime order_Date) { order order = new order(); order.Id = id; order.Order_Date = order_Date; return order; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property Order_Date in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.DateTime Order_Date { get { return this._Order_Date; } set { this.OnOrder_DateChanging(value); this.ReportPropertyChanging("Order_Date"); this._Order_Date = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Order_Date"); this.OnOrder_DateChanged(); } } private global::System.DateTime _Order_Date; partial void OnOrder_DateChanging(global::System.DateTime value); partial void OnOrder_DateChanged(); /// /// There are no comments for customer in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("juliotestsModel", "FK_ORDER_CUSTOMER", "customer")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public customer customer { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("juliotestsModel.FK_ORDER_CUSTOMER", "customer").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("juliotestsModel.FK_ORDER_CUSTOMER", "customer").Value = value; } } /// /// There are no comments for customer in the schema. /// [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference customerReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("juliotestsModel.FK_ORDER_CUSTOMER", "customer"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("juliotestsModel.FK_ORDER_CUSTOMER", "customer", value); } } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/LinqTests.cs0000644000175000017500000000454111127003600026027 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using NUnit.Framework; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using System.Linq; namespace MySql.Data.Entity.Tests { /// /// Summary description for BlobTests. /// [TestFixture] public class LinqTests : BaseEdmTest { public override void Setup() { base.Setup(); } private EntityConnection GetEntityConnection() { string connectionString = String.Format( "metadata=TestDB.csdl|TestDB.msl|TestDB.ssdl;provider=MySql.Data.MySqlClient; provider connection string=\"{0}\"", GetConnectionString(true)); EntityConnection connection = new EntityConnection(connectionString); return connection; } [Test] public void SelectSingleColumnNoParameter() { /* using (TestModel ctxt = new TestModel()) { var query = from c in db.Employee where c.LastName == "Flintstone" select c; foreach (Employee c in query) Console.WriteLine(" {0}", c.LastName); }*/ } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/InsertTests.cs0000644000175000017500000000733311127003600026372 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using NUnit.Framework; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using System.Data.Objects; namespace MySql.Data.Entity.Tests { [TestFixture] public class InsertTests : BaseEdmTest { [Test] public void InsertSingleRow() { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM companies", conn); DataTable dt = new DataTable(); da.Fill(dt); DataRow lastRow = dt.Rows[dt.Rows.Count - 1]; int lastId = (int)lastRow["id"]; DateTime dateBegan = DateTime.Now; using (testEntities context = new testEntities()) { Company c = new Company(); c.Id = 23; c.Name = "Yoyo"; c.NumEmployees = 486; c.DateBegan = dateBegan; c.Address.Address = "212 My Street."; c.Address.City = "Helena"; c.Address.State = "MT"; c.Address.ZipCode = "44558"; context.AddToCompanies(c); int result = context.SaveChanges(); DataTable afterInsert = new DataTable(); da.Fill(afterInsert); lastRow = afterInsert.Rows[afterInsert.Rows.Count - 1]; Assert.AreEqual(dt.Rows.Count + 1, afterInsert.Rows.Count); Assert.AreEqual(lastId+1, lastRow["id"]); Assert.AreEqual("Yoyo", lastRow["name"]); Assert.AreEqual(486, lastRow["numemployees"]); DateTime insertedDT = (DateTime)lastRow["dateBegan"]; Assert.AreEqual(dateBegan.Date, insertedDT.Date); Assert.AreEqual("212 My Street.", lastRow["address"]); Assert.AreEqual("Helena", lastRow["city"]); Assert.AreEqual("MT", lastRow["state"]); Assert.AreEqual("44558", lastRow["zipcode"]); } } [Test] public void CanInsertRowWithDefaultTimeStamp() { using (testEntities context = new testEntities()) { // The default timestamp is in the CreatedDate column. Product product = new Product(); product.Name = "Coca Cola"; context.AddToProducts(product); context.SaveChanges(); Assert.AreEqual(DateTime.Today.Day, product.CreatedDate.Day); } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/RestrictionOperators.cs0000644000175000017500000002013211127003600030277 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using NUnit.Framework; using System.Data.Objects; using System.Collections.Generic; using MySql.Data.Entity.Tests.Properties; namespace MySql.Data.Entity.Tests { [TestFixture] public class RestrictionOperators : BaseEdmTest { [Test] public void SimpleSelect() { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Toys", conn); DataTable toys = new DataTable(); da.Fill(toys); int i = 0; using (testEntities context = new testEntities()) { var query = context.CreateQuery("SELECT VALUE c FROM Toys AS c"); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.SimpleSelect); foreach (Toy t in query) { Assert.AreEqual(toys.Rows[i++]["name"], t.Name); } } } [Test] public void SimpleSelectWithFilter() { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Toys WHERE minage=4", conn); DataTable toys = new DataTable(); da.Fill(toys); int i = 0; using (testEntities context = new testEntities()) { var query = context.CreateQuery("SELECT VALUE t FROM Toys AS t WHERE t.MinAge=4"); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.SimpleSelectWithFilter); foreach (Toy t in query) Assert.AreEqual(toys.Rows[i++]["name"], t.Name); } } [Test] public void SimpleSelectWithParam() { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Toys WHERE minage>3", conn); DataTable toys = new DataTable(); da.Fill(toys); int i = 0; using (testEntities context = new testEntities()) { var query = context.CreateQuery("SELECT VALUE t FROM Toys AS t WHERE t.MinAge>@age"); query.Parameters.Add(new ObjectParameter("age", 3)); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.SimpleSelectWithParam); foreach (Toy t in query) { Assert.AreEqual(toys.Rows[i++]["name"], t.Name); } } } [Test] public void WhereLiteralOnRelation() { MySqlDataAdapter da = new MySqlDataAdapter("SELECT id FROM Companies WHERE city = 'Dallas'", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE c FROM Companies AS c WHERE c.Address.City = 'Dallas'"; ObjectQuery query = context.CreateQuery(eSql); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.WhereLiteralOnRelation); int i = 0; foreach (Company c in query) Assert.AreEqual(dt.Rows[i++]["id"], c.Id); } } [Test] public void SelectWithComplexType() { MySqlDataAdapter da = new MySqlDataAdapter("SELECT c.LastName FROM Employees AS c WHERE c.Age > 20", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { string eSql = @"SELECT c.LastName FROM Employees AS c WHERE c.Age > 20"; ObjectQuery query = context.CreateQuery(eSql); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.SelectWithComplexType); int i = 0; foreach (DbDataRecord s in query) Assert.AreEqual(dt.Rows[i++][0], s.GetString(0)); } } [Test] public void WhereWithRelatedEntities1() { MySqlDataAdapter da = new MySqlDataAdapter( "SELECT c.* FROM Toys t LEFT JOIN Companies c ON c.id=t.SupplierId WHERE c.State='TX'", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE t FROM Toys AS t WHERE t.Supplier.Address.State = 'TX'"; ObjectQuery query = context.CreateQuery(eSql); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.WhereWithRelatedEntities1); int i = 0; foreach (Toy t in query) { Assert.AreEqual(dt.Rows[i++]["id"], t.Id); } } } [Test] public void WhereWithRelatedEntities2() { MySqlDataAdapter da = new MySqlDataAdapter( @"SELECT c.* FROM Toys t LEFT JOIN Companies c ON c.Id=t.SupplierId WHERE c.State<>'TX' AND c.State<>'AZ'", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { string eSql = @"SELECT VALUE t FROM Toys AS t WHERE t.Supplier.Address.State<>'TX' AND t.Supplier.Address.State <> 'AZ'"; ObjectQuery query = context.CreateQuery(eSql); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.WhereWithRelatedEntities2); int i = 0; foreach (Toy t in query) { Assert.AreEqual(dt.Rows[i++]["id"], t.Id); } } } [Test] public void Exists() { MySqlDataAdapter da = new MySqlDataAdapter( @"SELECT c.* FROM Companies c WHERE EXISTS (SELECT * FROM Toys t WHERE t.SupplierId=c.Id && t.MinAge < 4)", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { string eSql = @"SELECT VALUE c FROM Companies AS c WHERE EXISTS( SELECT p FROM c.Toys AS p WHERE p.MinAge < 4)"; ObjectQuery query = context.CreateQuery(eSql); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.Exists); int i = 0; foreach(Company c in query) Assert.AreEqual(dt.Rows[i++]["id"], c.Id); } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/RelationalOperators.cs0000644000175000017500000001005711127003600030071 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using NUnit.Framework; using System.Data.Objects; using MySql.Data.Entity.Tests.Properties; using System.Linq; namespace MySql.Data.Entity.Tests { [TestFixture] public class RelationalOperators : BaseEdmTest { [Test] public void Except() { /* using (TestDB.TestDB db = new TestDB.TestDB()) { var q = from c in db.Companies where var query = from o in db.Orders where o.StoreId = 3 select o; var result = query.First(); }*/ } [Test] public void Intersect() { } [Test] public void CrossJoin() { } [Test] public void Union() { } [Test] public void UnionAll() { using (testEntities context = new testEntities()) { MySqlDataAdapter da = new MySqlDataAdapter( "SELECT t.Id FROM Toys t UNION ALL SELECT c.Id FROM Companies c", conn); DataTable dt = new DataTable(); da.Fill(dt); string entitySQL = @"(SELECT t.Id, t.Name FROM Toys AS t) UNION ALL (SELECT c.Id, c.Name FROM Companies AS c)"; ObjectQuery query = context.CreateQuery(entitySQL); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.UnionAll); int i = 0; foreach (DbDataRecord r in query) { i++; } Assert.AreEqual(dt.Rows.Count, i); } } /// /// Bug #60652 Query returns BLOB type but no BLOBs are in the database. /// [Test] public void UnionAllWithBitColumnsDoesNotThrow() { using (testEntities entities = new testEntities()) { // Here, Computer is the base type of DesktopComputer, LaptopComputer and TabletComputer. // LaptopComputer and TabletComputer include the bit fields that would provoke // an InvalidCastException (byte[] to bool) when participating in a UNION // created internally by the Connector/Net entity framework provider. var computers = from c in entities.Computers select c; foreach (Computer computer in computers) { Assert.NotNull(computer); Assert.IsTrue(computer.Id > 0); } } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/MySql.Data.Entity.Tests.csproj0000644000175000017500000001532111127003600031263 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {D37B3572-767F-4622-A835-844B0EBEFD5B} Library Properties MySql.Data.Entity.Tests MySql.Data.Entity.Tests v4.0 512 3.5 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false bin\Debug\ DEBUG;TRACE prompt 4 AllRules.ruleset pdbonly true bin\Release\ TRACE prompt 4 AllRules.ruleset Properties\VersionInfo.cs True True Model1.edmx True True Model2.edmx True True SQLSyntax.resx True True TestModel.edmx EntityModelCodeGenerator Model2.Designer.cs Designer ResXFileCodeGenerator SQLSyntax.Designer.cs EntityModelCodeGenerator Model1.Designer.cs EntityModelCodeGenerator TestModel.Designer.cs {EDED3135-95D2-4BCE-A810-F3F2AD7935B7} MySql.Data.Entity {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} MySql.Data {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4} MySql.Data.Tests mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/SchemaInformation.cs0000644000175000017500000031564011127003600027514 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.4900 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ [assembly: global::System.Data.Objects.DataClasses.EdmSchemaAttribute()] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("Store", "TableOrViewColumn", "Parent", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(Store.TableOrView), "Column", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Store.Column))] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("Store", "TableOrViewConstraint", "Parent", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(Store.TableOrView), "Constraint", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Store.Constraint))] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("Store", "TableOrViewConstraintColumn", "Constraint", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Store.TableOrViewColumnConstraint), "Column", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Store.Column))] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("Store", "ConstraintForeignKey", "Constraint", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(Store.ForeignKeyConstraint), "ForeignKey", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Store.ForeignKey))] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("Store", "ToForeignKeyColumn", "ForeignKey", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Store.ForeignKey), "Column", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(Store.Column))] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("Store", "FromForeignKeyColumn", "ForeignKey", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Store.ForeignKey), "Column", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(Store.Column))] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("Store", "RoutineParameter", "Routine", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(Store.Routine), "Parameter", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(Store.Parameter))] // Original file name: SchemaInformation.cs // Generation date: 2/11/2009 2:18:33 PM namespace Store { /// /// There are no comments for SchemaInformation in the schema. /// public partial class SchemaInformation : global::System.Data.Objects.ObjectContext { /// /// Initializes a new SchemaInformation object using the connection string found in the 'SchemaInformation' section of the application configuration file. /// public SchemaInformation() : base("name=SchemaInformation", "SchemaInformation") { this.OnContextCreated(); } /// /// Initialize a new SchemaInformation object. /// public SchemaInformation(string connectionString) : base(connectionString, "SchemaInformation") { this.OnContextCreated(); } /// /// Initialize a new SchemaInformation object. /// public SchemaInformation(global::System.Data.EntityClient.EntityConnection connection) : base(connection, "SchemaInformation") { this.OnContextCreated(); } partial void OnContextCreated(); /// /// There are no comments for Tables in the schema. /// public global::System.Data.Objects.ObjectQuery Tables { get { if ((this._Tables == null)) { this._Tables = base.CreateQuery
("[Tables]"); } return this._Tables; } } private global::System.Data.Objects.ObjectQuery
_Tables; /// /// There are no comments for TableColumns in the schema. /// public global::System.Data.Objects.ObjectQuery TableColumns { get { if ((this._TableColumns == null)) { this._TableColumns = base.CreateQuery("[TableColumns]"); } return this._TableColumns; } } private global::System.Data.Objects.ObjectQuery _TableColumns; /// /// There are no comments for TableConstraints in the schema. /// public global::System.Data.Objects.ObjectQuery TableConstraints { get { if ((this._TableConstraints == null)) { this._TableConstraints = base.CreateQuery("[TableConstraints]"); } return this._TableConstraints; } } private global::System.Data.Objects.ObjectQuery _TableConstraints; /// /// There are no comments for TableForeignKeys in the schema. /// public global::System.Data.Objects.ObjectQuery TableForeignKeys { get { if ((this._TableForeignKeys == null)) { this._TableForeignKeys = base.CreateQuery("[TableForeignKeys]"); } return this._TableForeignKeys; } } private global::System.Data.Objects.ObjectQuery _TableForeignKeys; /// /// There are no comments for Views in the schema. /// public global::System.Data.Objects.ObjectQuery Views { get { if ((this._Views == null)) { this._Views = base.CreateQuery("[Views]"); } return this._Views; } } private global::System.Data.Objects.ObjectQuery _Views; /// /// There are no comments for ViewColumns in the schema. /// public global::System.Data.Objects.ObjectQuery ViewColumns { get { if ((this._ViewColumns == null)) { this._ViewColumns = base.CreateQuery("[ViewColumns]"); } return this._ViewColumns; } } private global::System.Data.Objects.ObjectQuery _ViewColumns; /// /// There are no comments for ViewConstraints in the schema. /// public global::System.Data.Objects.ObjectQuery ViewConstraints { get { if ((this._ViewConstraints == null)) { this._ViewConstraints = base.CreateQuery("[ViewConstraints]"); } return this._ViewConstraints; } } private global::System.Data.Objects.ObjectQuery _ViewConstraints; /// /// There are no comments for ViewForeignKeys in the schema. /// public global::System.Data.Objects.ObjectQuery ViewForeignKeys { get { if ((this._ViewForeignKeys == null)) { this._ViewForeignKeys = base.CreateQuery("[ViewForeignKeys]"); } return this._ViewForeignKeys; } } private global::System.Data.Objects.ObjectQuery _ViewForeignKeys; /// /// There are no comments for Functions in the schema. /// public global::System.Data.Objects.ObjectQuery Functions { get { if ((this._Functions == null)) { this._Functions = base.CreateQuery("[Functions]"); } return this._Functions; } } private global::System.Data.Objects.ObjectQuery _Functions; /// /// There are no comments for FunctionParameters in the schema. /// public global::System.Data.Objects.ObjectQuery FunctionParameters { get { if ((this._FunctionParameters == null)) { this._FunctionParameters = base.CreateQuery("[FunctionParameters]"); } return this._FunctionParameters; } } private global::System.Data.Objects.ObjectQuery _FunctionParameters; /// /// There are no comments for Procedures in the schema. /// public global::System.Data.Objects.ObjectQuery Procedures { get { if ((this._Procedures == null)) { this._Procedures = base.CreateQuery("[Procedures]"); } return this._Procedures; } } private global::System.Data.Objects.ObjectQuery _Procedures; /// /// There are no comments for ProcedureParameters in the schema. /// public global::System.Data.Objects.ObjectQuery ProcedureParameters { get { if ((this._ProcedureParameters == null)) { this._ProcedureParameters = base.CreateQuery("[ProcedureParameters]"); } return this._ProcedureParameters; } } private global::System.Data.Objects.ObjectQuery _ProcedureParameters; /// /// There are no comments for Tables in the schema. /// public void AddToTables(Table table) { base.AddObject("Tables", table); } /// /// There are no comments for TableColumns in the schema. /// public void AddToTableColumns(Column column) { base.AddObject("TableColumns", column); } /// /// There are no comments for TableConstraints in the schema. /// public void AddToTableConstraints(Constraint constraint) { base.AddObject("TableConstraints", constraint); } /// /// There are no comments for TableForeignKeys in the schema. /// public void AddToTableForeignKeys(ForeignKey foreignKey) { base.AddObject("TableForeignKeys", foreignKey); } /// /// There are no comments for Views in the schema. /// public void AddToViews(View view) { base.AddObject("Views", view); } /// /// There are no comments for ViewColumns in the schema. /// public void AddToViewColumns(Column column) { base.AddObject("ViewColumns", column); } /// /// There are no comments for ViewConstraints in the schema. /// public void AddToViewConstraints(Constraint constraint) { base.AddObject("ViewConstraints", constraint); } /// /// There are no comments for ViewForeignKeys in the schema. /// public void AddToViewForeignKeys(ForeignKey foreignKey) { base.AddObject("ViewForeignKeys", foreignKey); } /// /// There are no comments for Functions in the schema. /// public void AddToFunctions(Function function) { base.AddObject("Functions", function); } /// /// There are no comments for FunctionParameters in the schema. /// public void AddToFunctionParameters(Parameter parameter) { base.AddObject("FunctionParameters", parameter); } /// /// There are no comments for Procedures in the schema. /// public void AddToProcedures(Procedure procedure) { base.AddObject("Procedures", procedure); } /// /// There are no comments for ProcedureParameters in the schema. /// public void AddToProcedureParameters(Parameter parameter) { base.AddObject("ProcedureParameters", parameter); } } /// /// There are no comments for ComplexType Store.TypeSpecification in the schema. /// [global::System.Data.Objects.DataClasses.EdmComplexTypeAttribute(NamespaceName="Store", Name="TypeSpecification")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class TypeSpecification : global::System.Data.Objects.DataClasses.ComplexObject { /// /// Create a new TypeSpecification object. /// /// Initial value of TypeName. /// Initial value of Collation. /// Initial value of CharacterSet. /// Initial value of IsMultiSet. public static TypeSpecification CreateTypeSpecification(string typeName, Collation collation, CharacterSet characterSet, bool isMultiSet) { TypeSpecification typeSpecification = new TypeSpecification(); typeSpecification.TypeName = typeName; typeSpecification.Collation = global::System.Data.Objects.DataClasses.StructuralObject.VerifyComplexObjectIsNotNull(collation, "Collation"); typeSpecification.CharacterSet = global::System.Data.Objects.DataClasses.StructuralObject.VerifyComplexObjectIsNotNull(characterSet, "CharacterSet"); typeSpecification.IsMultiSet = isMultiSet; return typeSpecification; } /// /// There are no comments for Property TypeName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string TypeName { get { return this._TypeName; } set { this.OnTypeNameChanging(value); this.ReportPropertyChanging("TypeName"); this._TypeName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("TypeName"); this.OnTypeNameChanged(); } } private string _TypeName; partial void OnTypeNameChanging(string value); partial void OnTypeNameChanged(); /// /// There are no comments for Property MaxLength in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable MaxLength { get { return this._MaxLength; } set { this.OnMaxLengthChanging(value); this.ReportPropertyChanging("MaxLength"); this._MaxLength = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("MaxLength"); this.OnMaxLengthChanged(); } } private global::System.Nullable _MaxLength; partial void OnMaxLengthChanging(global::System.Nullable value); partial void OnMaxLengthChanged(); /// /// There are no comments for Property Precision in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable Precision { get { return this._Precision; } set { this.OnPrecisionChanging(value); this.ReportPropertyChanging("Precision"); this._Precision = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Precision"); this.OnPrecisionChanged(); } } private global::System.Nullable _Precision; partial void OnPrecisionChanging(global::System.Nullable value); partial void OnPrecisionChanged(); /// /// There are no comments for Property DateTimePrecision in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable DateTimePrecision { get { return this._DateTimePrecision; } set { this.OnDateTimePrecisionChanging(value); this.ReportPropertyChanging("DateTimePrecision"); this._DateTimePrecision = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("DateTimePrecision"); this.OnDateTimePrecisionChanged(); } } private global::System.Nullable _DateTimePrecision; partial void OnDateTimePrecisionChanging(global::System.Nullable value); partial void OnDateTimePrecisionChanged(); /// /// There are no comments for Property Scale in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable Scale { get { return this._Scale; } set { this.OnScaleChanging(value); this.ReportPropertyChanging("Scale"); this._Scale = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Scale"); this.OnScaleChanged(); } } private global::System.Nullable _Scale; partial void OnScaleChanging(global::System.Nullable value); partial void OnScaleChanged(); /// /// There are no comments for Property Collation in the schema. /// [global::System.Data.Objects.DataClasses.EdmComplexPropertyAttribute()] [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] [global::System.Xml.Serialization.XmlElement(IsNullable=true)] [global::System.Xml.Serialization.SoapElement(IsNullable=true)] [global::System.Runtime.Serialization.DataMemberAttribute()] public Collation Collation { get { this._Collation = this.GetValidValue(this._Collation, "Collation", false, this._CollationInitialized); this._CollationInitialized = true; return this._Collation; } set { this.OnCollationChanging(value); this.ReportPropertyChanging("Collation"); this._Collation = this.SetValidValue(this._Collation, value, "Collation"); this._CollationInitialized = true; this.ReportPropertyChanged("Collation"); this.OnCollationChanged(); } } private Collation _Collation; private bool _CollationInitialized; partial void OnCollationChanging(Collation value); partial void OnCollationChanged(); /// /// There are no comments for Property CharacterSet in the schema. /// [global::System.Data.Objects.DataClasses.EdmComplexPropertyAttribute()] [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] [global::System.Xml.Serialization.XmlElement(IsNullable=true)] [global::System.Xml.Serialization.SoapElement(IsNullable=true)] [global::System.Runtime.Serialization.DataMemberAttribute()] public CharacterSet CharacterSet { get { this._CharacterSet = this.GetValidValue(this._CharacterSet, "CharacterSet", false, this._CharacterSetInitialized); this._CharacterSetInitialized = true; return this._CharacterSet; } set { this.OnCharacterSetChanging(value); this.ReportPropertyChanging("CharacterSet"); this._CharacterSet = this.SetValidValue(this._CharacterSet, value, "CharacterSet"); this._CharacterSetInitialized = true; this.ReportPropertyChanged("CharacterSet"); this.OnCharacterSetChanged(); } } private CharacterSet _CharacterSet; private bool _CharacterSetInitialized; partial void OnCharacterSetChanging(CharacterSet value); partial void OnCharacterSetChanged(); /// /// There are no comments for Property IsMultiSet in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public bool IsMultiSet { get { return this._IsMultiSet; } set { this.OnIsMultiSetChanging(value); this.ReportPropertyChanging("IsMultiSet"); this._IsMultiSet = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("IsMultiSet"); this.OnIsMultiSetChanged(); } } private bool _IsMultiSet; partial void OnIsMultiSetChanging(bool value); partial void OnIsMultiSetChanged(); } /// /// There are no comments for ComplexType Store.Collation in the schema. /// [global::System.Data.Objects.DataClasses.EdmComplexTypeAttribute(NamespaceName="Store", Name="Collation")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Collation : global::System.Data.Objects.DataClasses.ComplexObject { /// /// There are no comments for Property CatalogName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string CatalogName { get { return this._CatalogName; } set { this.OnCatalogNameChanging(value); this.ReportPropertyChanging("CatalogName"); this._CatalogName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("CatalogName"); this.OnCatalogNameChanged(); } } private string _CatalogName; partial void OnCatalogNameChanging(string value); partial void OnCatalogNameChanged(); /// /// There are no comments for Property SchemaName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string SchemaName { get { return this._SchemaName; } set { this.OnSchemaNameChanging(value); this.ReportPropertyChanging("SchemaName"); this._SchemaName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("SchemaName"); this.OnSchemaNameChanged(); } } private string _SchemaName; partial void OnSchemaNameChanging(string value); partial void OnSchemaNameChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); } /// /// There are no comments for ComplexType Store.CharacterSet in the schema. /// [global::System.Data.Objects.DataClasses.EdmComplexTypeAttribute(NamespaceName="Store", Name="CharacterSet")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class CharacterSet : global::System.Data.Objects.DataClasses.ComplexObject { /// /// There are no comments for Property CatalogName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string CatalogName { get { return this._CatalogName; } set { this.OnCatalogNameChanging(value); this.ReportPropertyChanging("CatalogName"); this._CatalogName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("CatalogName"); this.OnCatalogNameChanged(); } } private string _CatalogName; partial void OnCatalogNameChanging(string value); partial void OnCatalogNameChanged(); /// /// There are no comments for Property SchemaName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string SchemaName { get { return this._SchemaName; } set { this.OnSchemaNameChanging(value); this.ReportPropertyChanging("SchemaName"); this._SchemaName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("SchemaName"); this.OnSchemaNameChanged(); } } private string _SchemaName; partial void OnSchemaNameChanging(string value); partial void OnSchemaNameChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); } /// /// There are no comments for Store.TableOrView in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="TableOrView")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::Store.Table))] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::Store.View))] public abstract partial class TableOrView : global::System.Data.Objects.DataClasses.EntityObject { /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private string _Id; partial void OnIdChanging(string value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for Property CatalogName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string CatalogName { get { return this._CatalogName; } set { this.OnCatalogNameChanging(value); this.ReportPropertyChanging("CatalogName"); this._CatalogName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("CatalogName"); this.OnCatalogNameChanged(); } } private string _CatalogName; partial void OnCatalogNameChanging(string value); partial void OnCatalogNameChanged(); /// /// There are no comments for Property SchemaName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string SchemaName { get { return this._SchemaName; } set { this.OnSchemaNameChanging(value); this.ReportPropertyChanging("SchemaName"); this._SchemaName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("SchemaName"); this.OnSchemaNameChanged(); } } private string _SchemaName; partial void OnSchemaNameChanging(string value); partial void OnSchemaNameChanged(); /// /// There are no comments for Columns in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "TableOrViewColumn", "Column")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection Columns { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("Store.TableOrViewColumn", "Column"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("Store.TableOrViewColumn", "Column", value); } } } /// /// There are no comments for Constraints in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "TableOrViewConstraint", "Constraint")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection Constraints { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("Store.TableOrViewConstraint", "Constraint"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("Store.TableOrViewConstraint", "Constraint", value); } } } } /// /// There are no comments for Store.Table in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="Table")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Table : TableOrView { /// /// Create a new Table object. /// /// Initial value of Id. /// Initial value of Name. public static Table CreateTable(string id, string name) { Table table = new Table(); table.Id = id; table.Name = name; return table; } } /// /// There are no comments for Store.Column in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="Column")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Column : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Column object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of Ordinal. /// Initial value of IsNullable. /// Initial value of ColumnType. /// Initial value of IsIdentity. /// Initial value of IsStoreGenerated. public static Column CreateColumn(string id, string name, int ordinal, bool isNullable, TypeSpecification columnType, bool isIdentity, bool isStoreGenerated) { Column column = new Column(); column.Id = id; column.Name = name; column.Ordinal = ordinal; column.IsNullable = isNullable; column.ColumnType = global::System.Data.Objects.DataClasses.StructuralObject.VerifyComplexObjectIsNotNull(columnType, "ColumnType"); column.IsIdentity = isIdentity; column.IsStoreGenerated = isStoreGenerated; return column; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private string _Id; partial void OnIdChanging(string value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for Property Ordinal in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Ordinal { get { return this._Ordinal; } set { this.OnOrdinalChanging(value); this.ReportPropertyChanging("Ordinal"); this._Ordinal = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Ordinal"); this.OnOrdinalChanged(); } } private int _Ordinal; partial void OnOrdinalChanging(int value); partial void OnOrdinalChanged(); /// /// There are no comments for Property IsNullable in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public bool IsNullable { get { return this._IsNullable; } set { this.OnIsNullableChanging(value); this.ReportPropertyChanging("IsNullable"); this._IsNullable = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("IsNullable"); this.OnIsNullableChanged(); } } private bool _IsNullable; partial void OnIsNullableChanging(bool value); partial void OnIsNullableChanged(); /// /// There are no comments for Property ColumnType in the schema. /// [global::System.Data.Objects.DataClasses.EdmComplexPropertyAttribute()] [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] [global::System.Xml.Serialization.XmlElement(IsNullable=true)] [global::System.Xml.Serialization.SoapElement(IsNullable=true)] [global::System.Runtime.Serialization.DataMemberAttribute()] public TypeSpecification ColumnType { get { this._ColumnType = this.GetValidValue(this._ColumnType, "ColumnType", false, this._ColumnTypeInitialized); this._ColumnTypeInitialized = true; return this._ColumnType; } set { this.OnColumnTypeChanging(value); this.ReportPropertyChanging("ColumnType"); this._ColumnType = this.SetValidValue(this._ColumnType, value, "ColumnType"); this._ColumnTypeInitialized = true; this.ReportPropertyChanged("ColumnType"); this.OnColumnTypeChanged(); } } private TypeSpecification _ColumnType; private bool _ColumnTypeInitialized; partial void OnColumnTypeChanging(TypeSpecification value); partial void OnColumnTypeChanged(); /// /// There are no comments for Property IsIdentity in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public bool IsIdentity { get { return this._IsIdentity; } set { this.OnIsIdentityChanging(value); this.ReportPropertyChanging("IsIdentity"); this._IsIdentity = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("IsIdentity"); this.OnIsIdentityChanged(); } } private bool _IsIdentity; partial void OnIsIdentityChanging(bool value); partial void OnIsIdentityChanged(); /// /// There are no comments for Property IsStoreGenerated in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public bool IsStoreGenerated { get { return this._IsStoreGenerated; } set { this.OnIsStoreGeneratedChanging(value); this.ReportPropertyChanging("IsStoreGenerated"); this._IsStoreGenerated = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("IsStoreGenerated"); this.OnIsStoreGeneratedChanged(); } } private bool _IsStoreGenerated; partial void OnIsStoreGeneratedChanging(bool value); partial void OnIsStoreGeneratedChanged(); /// /// There are no comments for Property Default in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Default { get { return this._Default; } set { this.OnDefaultChanging(value); this.ReportPropertyChanging("Default"); this._Default = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("Default"); this.OnDefaultChanged(); } } private string _Default; partial void OnDefaultChanging(string value); partial void OnDefaultChanged(); /// /// There are no comments for Parent in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "TableOrViewColumn", "Parent")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public TableOrView Parent { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.TableOrViewColumn", "Parent").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.TableOrViewColumn", "Parent").Value = value; } } /// /// There are no comments for Parent in the schema. /// [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference ParentReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.TableOrViewColumn", "Parent"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("Store.TableOrViewColumn", "Parent", value); } } } /// /// There are no comments for Constraints in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "TableOrViewConstraintColumn", "Constraint")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection Constraints { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("Store.TableOrViewConstraintColumn", "Constraint"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("Store.TableOrViewConstraintColumn", "Constraint", value); } } } /// /// There are no comments for ToForeignKeys in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "ToForeignKeyColumn", "ForeignKey")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection ToForeignKeys { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("Store.ToForeignKeyColumn", "ForeignKey"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("Store.ToForeignKeyColumn", "ForeignKey", value); } } } /// /// There are no comments for FromForeignKeys in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "FromForeignKeyColumn", "ForeignKey")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection FromForeignKeys { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("Store.FromForeignKeyColumn", "ForeignKey"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("Store.FromForeignKeyColumn", "ForeignKey", value); } } } } /// /// There are no comments for Store.View in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="View")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class View : TableOrView { /// /// Create a new View object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of IsUpdatable. public static View CreateView(string id, string name, bool isUpdatable) { View view = new View(); view.Id = id; view.Name = name; view.IsUpdatable = isUpdatable; return view; } /// /// There are no comments for Property IsUpdatable in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public bool IsUpdatable { get { return this._IsUpdatable; } set { this.OnIsUpdatableChanging(value); this.ReportPropertyChanging("IsUpdatable"); this._IsUpdatable = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("IsUpdatable"); this.OnIsUpdatableChanged(); } } private bool _IsUpdatable; partial void OnIsUpdatableChanging(bool value); partial void OnIsUpdatableChanged(); /// /// There are no comments for Property ViewDefinition in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string ViewDefinition { get { return this._ViewDefinition; } set { this.OnViewDefinitionChanging(value); this.ReportPropertyChanging("ViewDefinition"); this._ViewDefinition = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("ViewDefinition"); this.OnViewDefinitionChanged(); } } private string _ViewDefinition; partial void OnViewDefinitionChanging(string value); partial void OnViewDefinitionChanged(); } /// /// There are no comments for Store.Routine in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="Routine")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::Store.Function))] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::Store.Procedure))] public abstract partial class Routine : global::System.Data.Objects.DataClasses.EntityObject { /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private string _Id; partial void OnIdChanging(string value); partial void OnIdChanged(); /// /// There are no comments for Property CatalogName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string CatalogName { get { return this._CatalogName; } set { this.OnCatalogNameChanging(value); this.ReportPropertyChanging("CatalogName"); this._CatalogName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("CatalogName"); this.OnCatalogNameChanged(); } } private string _CatalogName; partial void OnCatalogNameChanging(string value); partial void OnCatalogNameChanged(); /// /// There are no comments for Property SchemaName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string SchemaName { get { return this._SchemaName; } set { this.OnSchemaNameChanging(value); this.ReportPropertyChanging("SchemaName"); this._SchemaName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("SchemaName"); this.OnSchemaNameChanged(); } } private string _SchemaName; partial void OnSchemaNameChanging(string value); partial void OnSchemaNameChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for Parameters in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "RoutineParameter", "Parameter")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection Parameters { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("Store.RoutineParameter", "Parameter"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("Store.RoutineParameter", "Parameter", value); } } } } /// /// There are no comments for Store.Parameter in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="Parameter")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Parameter : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Parameter object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of Ordinal. /// Initial value of ParameterType. public static Parameter CreateParameter(string id, string name, int ordinal, TypeSpecification parameterType) { Parameter parameter = new Parameter(); parameter.Id = id; parameter.Name = name; parameter.Ordinal = ordinal; parameter.ParameterType = global::System.Data.Objects.DataClasses.StructuralObject.VerifyComplexObjectIsNotNull(parameterType, "ParameterType"); return parameter; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private string _Id; partial void OnIdChanging(string value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for Property Ordinal in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Ordinal { get { return this._Ordinal; } set { this.OnOrdinalChanging(value); this.ReportPropertyChanging("Ordinal"); this._Ordinal = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Ordinal"); this.OnOrdinalChanged(); } } private int _Ordinal; partial void OnOrdinalChanging(int value); partial void OnOrdinalChanged(); /// /// There are no comments for Property ParameterType in the schema. /// [global::System.Data.Objects.DataClasses.EdmComplexPropertyAttribute()] [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] [global::System.Xml.Serialization.XmlElement(IsNullable=true)] [global::System.Xml.Serialization.SoapElement(IsNullable=true)] [global::System.Runtime.Serialization.DataMemberAttribute()] public TypeSpecification ParameterType { get { this._ParameterType = this.GetValidValue(this._ParameterType, "ParameterType", false, this._ParameterTypeInitialized); this._ParameterTypeInitialized = true; return this._ParameterType; } set { this.OnParameterTypeChanging(value); this.ReportPropertyChanging("ParameterType"); this._ParameterType = this.SetValidValue(this._ParameterType, value, "ParameterType"); this._ParameterTypeInitialized = true; this.ReportPropertyChanged("ParameterType"); this.OnParameterTypeChanged(); } } private TypeSpecification _ParameterType; private bool _ParameterTypeInitialized; partial void OnParameterTypeChanging(TypeSpecification value); partial void OnParameterTypeChanged(); /// /// There are no comments for Property Mode in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Mode { get { return this._Mode; } set { this.OnModeChanging(value); this.ReportPropertyChanging("Mode"); this._Mode = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("Mode"); this.OnModeChanged(); } } private string _Mode; partial void OnModeChanging(string value); partial void OnModeChanged(); /// /// There are no comments for Property Default in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Default { get { return this._Default; } set { this.OnDefaultChanging(value); this.ReportPropertyChanging("Default"); this._Default = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("Default"); this.OnDefaultChanged(); } } private string _Default; partial void OnDefaultChanging(string value); partial void OnDefaultChanged(); /// /// There are no comments for Routine in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "RoutineParameter", "Routine")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public Routine Routine { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.RoutineParameter", "Routine").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.RoutineParameter", "Routine").Value = value; } } /// /// There are no comments for Routine in the schema. /// [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference RoutineReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.RoutineParameter", "Routine"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("Store.RoutineParameter", "Routine", value); } } } } /// /// There are no comments for Store.Function in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="Function")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::Store.ScalarFunction))] public abstract partial class Function : Routine { /// /// There are no comments for Property IsBuiltIn in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable IsBuiltIn { get { return this._IsBuiltIn; } set { this.OnIsBuiltInChanging(value); this.ReportPropertyChanging("IsBuiltIn"); this._IsBuiltIn = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("IsBuiltIn"); this.OnIsBuiltInChanged(); } } private global::System.Nullable _IsBuiltIn; partial void OnIsBuiltInChanging(global::System.Nullable value); partial void OnIsBuiltInChanged(); /// /// There are no comments for Property IsNiladic in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable IsNiladic { get { return this._IsNiladic; } set { this.OnIsNiladicChanging(value); this.ReportPropertyChanging("IsNiladic"); this._IsNiladic = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("IsNiladic"); this.OnIsNiladicChanged(); } } private global::System.Nullable _IsNiladic; partial void OnIsNiladicChanging(global::System.Nullable value); partial void OnIsNiladicChanged(); } /// /// There are no comments for Store.ScalarFunction in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="ScalarFunction")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class ScalarFunction : Function { /// /// Create a new ScalarFunction object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of ReturnType. public static ScalarFunction CreateScalarFunction(string id, string name, TypeSpecification returnType) { ScalarFunction scalarFunction = new ScalarFunction(); scalarFunction.Id = id; scalarFunction.Name = name; scalarFunction.ReturnType = global::System.Data.Objects.DataClasses.StructuralObject.VerifyComplexObjectIsNotNull(returnType, "ReturnType"); return scalarFunction; } /// /// There are no comments for Property ReturnType in the schema. /// [global::System.Data.Objects.DataClasses.EdmComplexPropertyAttribute()] [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] [global::System.Xml.Serialization.XmlElement(IsNullable=true)] [global::System.Xml.Serialization.SoapElement(IsNullable=true)] [global::System.Runtime.Serialization.DataMemberAttribute()] public TypeSpecification ReturnType { get { this._ReturnType = this.GetValidValue(this._ReturnType, "ReturnType", false, this._ReturnTypeInitialized); this._ReturnTypeInitialized = true; return this._ReturnType; } set { this.OnReturnTypeChanging(value); this.ReportPropertyChanging("ReturnType"); this._ReturnType = this.SetValidValue(this._ReturnType, value, "ReturnType"); this._ReturnTypeInitialized = true; this.ReportPropertyChanged("ReturnType"); this.OnReturnTypeChanged(); } } private TypeSpecification _ReturnType; private bool _ReturnTypeInitialized; partial void OnReturnTypeChanging(TypeSpecification value); partial void OnReturnTypeChanged(); /// /// There are no comments for Property IsAggregate in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable IsAggregate { get { return this._IsAggregate; } set { this.OnIsAggregateChanging(value); this.ReportPropertyChanging("IsAggregate"); this._IsAggregate = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("IsAggregate"); this.OnIsAggregateChanged(); } } private global::System.Nullable _IsAggregate; partial void OnIsAggregateChanging(global::System.Nullable value); partial void OnIsAggregateChanged(); } /// /// There are no comments for Store.Procedure in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="Procedure")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Procedure : Routine { /// /// Create a new Procedure object. /// /// Initial value of Id. /// Initial value of Name. public static Procedure CreateProcedure(string id, string name) { Procedure procedure = new Procedure(); procedure.Id = id; procedure.Name = name; return procedure; } } /// /// There are no comments for Store.Constraint in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="Constraint")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::Store.TableOrViewColumnConstraint))] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::Store.ForeignKeyConstraint))] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::Store.CheckConstraint))] public abstract partial class Constraint : global::System.Data.Objects.DataClasses.EntityObject { /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private string _Id; partial void OnIdChanging(string value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for Property IsDeferrable in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public bool IsDeferrable { get { return this._IsDeferrable; } set { this.OnIsDeferrableChanging(value); this.ReportPropertyChanging("IsDeferrable"); this._IsDeferrable = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("IsDeferrable"); this.OnIsDeferrableChanged(); } } private bool _IsDeferrable; partial void OnIsDeferrableChanging(bool value); partial void OnIsDeferrableChanged(); /// /// There are no comments for Property IsInitiallyDeferred in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public bool IsInitiallyDeferred { get { return this._IsInitiallyDeferred; } set { this.OnIsInitiallyDeferredChanging(value); this.ReportPropertyChanging("IsInitiallyDeferred"); this._IsInitiallyDeferred = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("IsInitiallyDeferred"); this.OnIsInitiallyDeferredChanged(); } } private bool _IsInitiallyDeferred; partial void OnIsInitiallyDeferredChanging(bool value); partial void OnIsInitiallyDeferredChanged(); /// /// There are no comments for Parent in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "TableOrViewConstraint", "Parent")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public TableOrView Parent { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.TableOrViewConstraint", "Parent").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.TableOrViewConstraint", "Parent").Value = value; } } /// /// There are no comments for Parent in the schema. /// [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference ParentReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.TableOrViewConstraint", "Parent"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("Store.TableOrViewConstraint", "Parent", value); } } } } /// /// There are no comments for Store.CheckConstraint in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="CheckConstraint")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class CheckConstraint : Constraint { /// /// Create a new CheckConstraint object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of IsDeferrable. /// Initial value of IsInitiallyDeferred. public static CheckConstraint CreateCheckConstraint(string id, string name, bool isDeferrable, bool isInitiallyDeferred) { CheckConstraint checkConstraint = new CheckConstraint(); checkConstraint.Id = id; checkConstraint.Name = name; checkConstraint.IsDeferrable = isDeferrable; checkConstraint.IsInitiallyDeferred = isInitiallyDeferred; return checkConstraint; } /// /// There are no comments for Property Expression in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Expression { get { return this._Expression; } set { this.OnExpressionChanging(value); this.ReportPropertyChanging("Expression"); this._Expression = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("Expression"); this.OnExpressionChanged(); } } private string _Expression; partial void OnExpressionChanging(string value); partial void OnExpressionChanged(); } /// /// There are no comments for Store.TableOrViewColumnConstraint in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="TableOrViewColumnConstraint")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::Store.PrimaryKeyConstraint))] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::Store.UniqueConstraint))] public abstract partial class TableOrViewColumnConstraint : Constraint { /// /// There are no comments for Columns in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "TableOrViewConstraintColumn", "Column")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection Columns { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("Store.TableOrViewConstraintColumn", "Column"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("Store.TableOrViewConstraintColumn", "Column", value); } } } } /// /// There are no comments for Store.PrimaryKeyConstraint in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="PrimaryKeyConstraint")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class PrimaryKeyConstraint : TableOrViewColumnConstraint { /// /// Create a new PrimaryKeyConstraint object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of IsDeferrable. /// Initial value of IsInitiallyDeferred. public static PrimaryKeyConstraint CreatePrimaryKeyConstraint(string id, string name, bool isDeferrable, bool isInitiallyDeferred) { PrimaryKeyConstraint primaryKeyConstraint = new PrimaryKeyConstraint(); primaryKeyConstraint.Id = id; primaryKeyConstraint.Name = name; primaryKeyConstraint.IsDeferrable = isDeferrable; primaryKeyConstraint.IsInitiallyDeferred = isInitiallyDeferred; return primaryKeyConstraint; } } /// /// There are no comments for Store.UniqueConstraint in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="UniqueConstraint")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class UniqueConstraint : TableOrViewColumnConstraint { /// /// Create a new UniqueConstraint object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of IsDeferrable. /// Initial value of IsInitiallyDeferred. public static UniqueConstraint CreateUniqueConstraint(string id, string name, bool isDeferrable, bool isInitiallyDeferred) { UniqueConstraint uniqueConstraint = new UniqueConstraint(); uniqueConstraint.Id = id; uniqueConstraint.Name = name; uniqueConstraint.IsDeferrable = isDeferrable; uniqueConstraint.IsInitiallyDeferred = isInitiallyDeferred; return uniqueConstraint; } } /// /// There are no comments for Store.ForeignKeyConstraint in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="ForeignKeyConstraint")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class ForeignKeyConstraint : Constraint { /// /// Create a new ForeignKeyConstraint object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of IsDeferrable. /// Initial value of IsInitiallyDeferred. /// Initial value of UpdateRule. /// Initial value of DeleteRule. public static ForeignKeyConstraint CreateForeignKeyConstraint(string id, string name, bool isDeferrable, bool isInitiallyDeferred, string updateRule, string deleteRule) { ForeignKeyConstraint foreignKeyConstraint = new ForeignKeyConstraint(); foreignKeyConstraint.Id = id; foreignKeyConstraint.Name = name; foreignKeyConstraint.IsDeferrable = isDeferrable; foreignKeyConstraint.IsInitiallyDeferred = isInitiallyDeferred; foreignKeyConstraint.UpdateRule = updateRule; foreignKeyConstraint.DeleteRule = deleteRule; return foreignKeyConstraint; } /// /// There are no comments for Property UpdateRule in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string UpdateRule { get { return this._UpdateRule; } set { this.OnUpdateRuleChanging(value); this.ReportPropertyChanging("UpdateRule"); this._UpdateRule = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("UpdateRule"); this.OnUpdateRuleChanged(); } } private string _UpdateRule; partial void OnUpdateRuleChanging(string value); partial void OnUpdateRuleChanged(); /// /// There are no comments for Property DeleteRule in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string DeleteRule { get { return this._DeleteRule; } set { this.OnDeleteRuleChanging(value); this.ReportPropertyChanging("DeleteRule"); this._DeleteRule = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("DeleteRule"); this.OnDeleteRuleChanged(); } } private string _DeleteRule; partial void OnDeleteRuleChanging(string value); partial void OnDeleteRuleChanged(); /// /// There are no comments for ForeignKeys in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "ConstraintForeignKey", "ForeignKey")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection ForeignKeys { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("Store.ConstraintForeignKey", "ForeignKey"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("Store.ConstraintForeignKey", "ForeignKey", value); } } } } /// /// There are no comments for Store.ForeignKey in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Store", Name="ForeignKey")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class ForeignKey : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new ForeignKey object. /// /// Initial value of Id. /// Initial value of Ordinal. public static ForeignKey CreateForeignKey(string id, int ordinal) { ForeignKey foreignKey = new ForeignKey(); foreignKey.Id = id; foreignKey.Ordinal = ordinal; return foreignKey; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private string _Id; partial void OnIdChanging(string value); partial void OnIdChanged(); /// /// There are no comments for Property Ordinal in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Ordinal { get { return this._Ordinal; } set { this.OnOrdinalChanging(value); this.ReportPropertyChanging("Ordinal"); this._Ordinal = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Ordinal"); this.OnOrdinalChanged(); } } private int _Ordinal; partial void OnOrdinalChanging(int value); partial void OnOrdinalChanged(); /// /// There are no comments for Constraint in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "ConstraintForeignKey", "Constraint")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public ForeignKeyConstraint Constraint { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.ConstraintForeignKey", "Constraint").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.ConstraintForeignKey", "Constraint").Value = value; } } /// /// There are no comments for Constraint in the schema. /// [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference ConstraintReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.ConstraintForeignKey", "Constraint"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("Store.ConstraintForeignKey", "Constraint", value); } } } /// /// There are no comments for FromColumn in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "FromForeignKeyColumn", "Column")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public Column FromColumn { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.FromForeignKeyColumn", "Column").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.FromForeignKeyColumn", "Column").Value = value; } } /// /// There are no comments for FromColumn in the schema. /// [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference FromColumnReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.FromForeignKeyColumn", "Column"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("Store.FromForeignKeyColumn", "Column", value); } } } /// /// There are no comments for ToColumn in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("Store", "ToForeignKeyColumn", "Column")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public Column ToColumn { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.ToForeignKeyColumn", "Column").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.ToForeignKeyColumn", "Column").Value = value; } } /// /// There are no comments for ToColumn in the schema. /// [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference ToColumnReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("Store.ToForeignKeyColumn", "Column"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("Store.ToForeignKeyColumn", "Column", value); } } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/ProceduresAndFunctions.cs0000644000175000017500000001314611127003600030531 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2010 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using NUnit.Framework; using System.Data.Objects; using System.Linq; namespace MySql.Data.Entity.Tests { [TestFixture] public class ProceduresAndFunctions : BaseEdmTest { public ProceduresAndFunctions() : base() { } [Test] public void Insert() { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Authors", conn); DataTable dt = new DataTable(); da.Fill(dt); int count = dt.Rows.Count; using (testEntities context = new testEntities()) { Author a = new Author(); a.Id = 23; a.Name = "Test name"; a.Age = 44; context.AddToAuthors(a); context.SaveChanges(); } dt.Clear(); da.Fill(dt); Assert.AreEqual(count + 1, dt.Rows.Count); Assert.AreEqual(23, dt.Rows[count]["id"]); } [Test] public void Update() { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Authors", conn); DataTable dt = new DataTable(); da.Fill(dt); int count = dt.Rows.Count; using (testEntities context = new testEntities()) { var q = from a in context.Authors where a.Name == "Don Box" select a; foreach (Author a in q) a.Name = "Dummy"; context.SaveChanges(); } da.SelectCommand.CommandText = "SELECT * FROM Authors WHERE name='Dummy'"; dt.Clear(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); } [Test] public void Delete() { using (testEntities context = new testEntities()) { foreach (Book b in context.Books) context.DeleteObject(b); context.SaveChanges(); } MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Books", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(0, dt.Rows.Count); } /// /// Bug #45277 Calling User Defined Function using eSql causes NullReferenceException /// [Test] public void UserDefinedFunction() { using (EntityConnection conn = new EntityConnection("name=testEntities")) { conn.Open(); string query = @"SELECT e.FirstName AS Name FROM testEntities.Employees AS e WHERE testModel.Store.spFunc(e.Id, '') = 6"; using (EntityCommand cmd = new EntityCommand(query, conn)) { EntityDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess); Assert.IsTrue(reader.Read()); Assert.AreEqual("Scooby", reader[0]); } } } /// /// Bug #56806 Default Command Timeout has no effect in connection string /// [Test] public void CommandTimeout() { string connectionString = String.Format( "metadata=res://*/TestModel.csdl|res://*/TestModel.ssdl|res://*/TestModel.msl;provider=MySql.Data.MySqlClient; provider connection string=\"{0};default command timeout=5\"", GetConnectionString(true)); EntityConnection connection = new EntityConnection(connectionString); using (testEntities context = new testEntities(connection)) { Author a = new Author(); a.Id = 66; // special value to indicate the routine should take 30 seconds a.Name = "Test name"; a.Age = 44; context.AddToAuthors(a); try { context.SaveChanges(); Assert.Fail("This should have timed out"); } catch (Exception ex) { string s = ex.Message; } } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/UpdateTests.cs0000644000175000017500000000404511127003600026345 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using NUnit.Framework; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using System.Data.Objects; namespace MySql.Data.Entity.Tests { [TestFixture] public class UpdateTests : BaseEdmTest { [Test] public void UpdateAllRows() { MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM toys", conn); object count = cmd.ExecuteScalar(); using (testEntities context = new testEntities()) { foreach (Toy t in context.Toys) t.Name = "Top"; context.SaveChanges(); } cmd.CommandText = "SELECT COUNT(*) FROM Toys WHERE name='Top'"; object newCount = cmd.ExecuteScalar(); Assert.AreEqual(count, newCount); } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Wizard.cs0000644000175000017500000001132411127003600025336 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Threading; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using NUnit.Framework; using System.Data.Objects; using System.Data.Entity.Design; using System.Linq; using Store; using System.Configuration; using System.Xml; namespace MySql.Data.Entity.Tests { // This test unit covers the tests that the wizard runs when generating a model // from an existing database [TestFixture] public class WizardTests : BaseEdmTest { private EntityConnection GetConnection() { return EntityStoreSchemaGenerator.CreateStoreSchemaConnection( "MySql.Data.MySqlClient", @"server=localhost;uid=root;database=test;pooling=false"); } [Test] public void SelectAllTables() { execSQL("CREATE TABLE test (id int)"); System.Data.DataTable dt = conn.GetSchema("Tables"); using (EntityConnection ec = GetConnection()) { using (SchemaInformation si = new SchemaInformation(ec)) { int i = 0; var q = si.Tables.Select("it.CatalogName, it.SchemaName, it.Name").OrderBy("it.Name, it.SchemaName"); foreach (DbDataRecord t in q) Assert.AreEqual(dt.Rows[i++]["TABLE_NAME"], t.GetString(2)); } } } [Test] public void SelectAllViews() { execSQL("CREATE TABLE test (id int)"); execSQL("CREATE VIEW view1 as SELECT * FROM test"); System.Data.DataTable dt = conn.GetSchema("Views"); using (EntityConnection ec = GetConnection()) { using (SchemaInformation si = new SchemaInformation(ec)) { int i = 0; var q = si.Views.Select("it.CatalogName, it.SchemaName, it.Name").OrderBy("it.Name, it.SchemaName"); foreach (DbDataRecord t in q) Assert.AreEqual(dt.Rows[i++]["TABLE_NAME"], t.GetString(2)); } } } [Test] public void GetDbProviderManifestTokenReturnsCorrectSchemaVersion() { if (Version < new Version(5, 0)) return; MySqlProviderServices services = new MySqlProviderServices(); string token = services.GetProviderManifestToken(conn); if (Version < new Version(5, 1)) Assert.AreEqual("5.0", token); else if (Version < new Version(5, 5)) Assert.AreEqual("5.1", token); else Assert.AreEqual("5.5", token); } [Test] public void GetStoreSchemaDescriptionDoesNotThrowForServer50OrGreater() { if (Version < new Version(5, 0)) return; MySqlProviderManifest manifest = new MySqlProviderManifest(Version.Major + "." + Version.Minor); using (XmlReader reader = manifest.GetInformation(DbProviderManifest.StoreSchemaDefinition)) { Assert.IsNotNull(reader); } } } public static class ExtensionMethods { public static string ToTraceString(this IQueryable t) { // try to cast to ObjectQuery ObjectQuery oqt = t as ObjectQuery; if (oqt != null) return oqt.ToTraceString(); return ""; } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/App.Config0000644000175000017500000000237511127003600025424 0ustar directhexdirecthex mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/ProviderServicesTests.cs0000644000175000017500000000630211127003600030417 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using NUnit.Framework; using System.Data.Objects; namespace MySql.Data.Entity.Tests { [TestFixture] public class ProviderServicesTests : BaseEdmTest { #if CLR4 [Test] public void CreateDatabase() { suExecSQL("GRANT ALL ON `modeldb`.* to 'test'@'localhost'"); suExecSQL("FLUSH PRIVILEGES"); using (Model1Container ctx = new Model1Container()) { Assert.IsFalse(ctx.DatabaseExists()); ctx.CreateDatabase(); Assert.IsTrue(ctx.DatabaseExists()); } } [Test] public void CreateDatabaseScript() { using (testEntities ctx = new testEntities()) { string s = ctx.CreateDatabaseScript(); } } [Test] public void DeleteDatabase() { suExecSQL("GRANT ALL ON `modeldb`.* to 'test'@'localhost'"); suExecSQL("FLUSH PRIVILEGES"); using (Model1Container ctx = new Model1Container()) { Assert.IsFalse(ctx.DatabaseExists()); ctx.CreateDatabase(); Assert.IsTrue(ctx.DatabaseExists()); ctx.DeleteDatabase(); Assert.IsFalse(ctx.DatabaseExists()); } } [Test] public void DatabaseExists() { suExecSQL("GRANT ALL ON `modeldb`.* to 'test'@'localhost'"); suExecSQL("FLUSH PRIVILEGES"); using (Model1Container ctx = new Model1Container()) { Assert.IsFalse(ctx.DatabaseExists()); ctx.CreateDatabase(); Assert.IsTrue(ctx.DatabaseExists()); ctx.DeleteDatabase(); Assert.IsFalse(ctx.DatabaseExists()); } } #endif } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Model2.edmx0000644000175000017500000001545511127003600025561 0ustar directhexdirecthex mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/OrderingAndGrouping.cs0000644000175000017500000001415711127003600030014 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using NUnit.Framework; using System.Data.Objects; using MySql.Data.Entity.Tests.Properties; using System.Linq; namespace MySql.Data.Entity.Tests { [TestFixture] public class OrderingAndGrouping : BaseEdmTest { [Test] public void OrderBySimple() { MySqlDataAdapter da = new MySqlDataAdapter( "SELECT id FROM Companies c ORDER BY c.Name", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE c FROM Companies AS c ORDER BY c.Name"; ObjectQuery query = context.CreateQuery(eSql); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.OrderBySimple); int i = 0; foreach (Company c in query) Assert.AreEqual(dt.Rows[i++][0], c.Id); } } [Test] public void OrderByWithPredicate() { using (testEntities context = new testEntities()) { using (EntityConnection ec = context.Connection as EntityConnection) { ec.Open(); MySqlDataAdapter da = new MySqlDataAdapter( "SELECT id FROM Companies c WHERE c.NumEmployees > 100 ORDER BY c.Name", conn); DataTable dt = new DataTable(); da.Fill(dt); string eSql = "SELECT VALUE c FROM Companies AS c WHERE c.NumEmployees > 100 ORDER BY c.Name"; ObjectQuery query = context.CreateQuery(eSql); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.OrderByWithPredicate); int i = 0; foreach (Company c in query) Assert.AreEqual(dt.Rows[i++][0], c.Id); } } } [Test] public void CanGroupBySingleColumn() { MySqlDataAdapter adapter = new MySqlDataAdapter( "SELECT Name, COUNT(Id) as Count FROM Companies GROUP BY Name", conn); DataTable table = new DataTable(); adapter.Fill(table); using (testEntities context = new testEntities()) { var companies = from c in context.Companies group c by c.Name into cgroup select new { Name = cgroup.Key, Count = cgroup.Count() }; string sql = companies.ToTraceString(); CheckSql(sql, SQLSyntax.CanGroupBySingleColumn); int i = 0; foreach (var company in companies) { Assert.AreEqual(table.Rows[i][0], company.Name); Assert.AreEqual(table.Rows[i][1], company.Count); i++; } } } [Test] public void CanGroupByMultipleColumns() { MySqlDataAdapter adapter = new MySqlDataAdapter( "SELECT Name, COUNT(Id) as Count FROM Companies GROUP BY Name, NumEmployees, DateBegan", conn); DataTable table = new DataTable(); adapter.Fill(table); using (testEntities context = new testEntities()) { var companies = from c in context.Companies group c by new { c.Name, c.NumEmployees, c.DateBegan } into cgroup select new { Name = cgroup.Key.Name, Count = cgroup.Count() }; string sql = companies.ToTraceString(); CheckSql(sql, SQLSyntax.CanGroupByMultipleColumns); int i = 0; foreach (var company in companies) { Assert.AreEqual(table.Rows[i][0], company.Name); Assert.AreEqual(table.Rows[i][1], company.Count); i++; } } } [Test] public void OrdersTableDoesNotProvokeSyntaxError() { using (model2Entities context = new model2Entities()) { var customers = from c in context.customer select c; Assert.DoesNotThrow(delegate { customers.ToList().ForEach(c => c.order.Load()); }); } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Properties/0000755000175000017500000000000011127003600025702 5ustar directhexdirecthexmysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Properties/SQLSyntax.resx0000644000175000017500000004515611127003600030466 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`Age` FROM `Authors` AS `Extent1` WHERE NOT EXISTS(SELECT 1 AS `C1` FROM `Books` AS `Extent2` WHERE `Extent1`.`Id` = `Extent2`.`Author_id`) SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT AVG(`Extent1`.`MinAge`) AS `A1` FROM `Toys` AS `Extent1`) AS `GroupBy1` SELECT 1 AS `C1`, `GroupBy1`.`A1` AS `C2` FROM (SELECT `Extent1`.`StoreId` AS `K1`, AVG(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` GROUP BY `Extent1`.`StoreId`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT AVG(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` WHERE `Extent1`.`StoreId` = 3) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT COUNT(`Extent1`.`Id`) AS `A1` FROM `Toys` AS `Extent1`) AS `GroupBy1` SELECT 1 AS `C1`, `GroupBy1`.`K1` AS `Name`, `GroupBy1`.`A1` AS `C2` FROM (SELECT `Extent1`.`Name` AS `K1`, `Extent1`.`DateBegan` AS `K2`, `Extent1`.`NumEmployees` AS `K3`, COUNT(1) AS `A1` FROM `Companies` AS `Extent1` GROUP BY `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`) AS `GroupBy1` SELECT 1 AS `C1`, `GroupBy1`.`K1` AS `Name`, `GroupBy1`.`A1` AS `C2` FROM (SELECT `Extent1`.`Name` AS `K1`, COUNT(1) AS `A1` FROM `Companies` AS `Extent1` GROUP BY `Extent1`.`Name`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT COUNT(`Extent1`.`Id`) AS `A1` FROM `Toys` AS `Extent1`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT COUNT(`Extent1`.`Id`) AS `A1` FROM `Toys` AS `Extent1` WHERE `Extent1`.`MinAge` > 3) AS `GroupBy1` SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode` FROM `Companies` AS `Extent1` WHERE EXISTS(SELECT 1 AS `C1` FROM `Toys` AS `Extent2` WHERE (`Extent1`.`Id` = `Extent2`.`SupplierId`) AND (`Extent2`.`MinAge` < 4)) SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Join1`.`Id` AS `C1`, `Join1`.`Name` AS `C2`, `Join1`.`Id1` AS `C3`, `Join1`.`Name1` AS `C4` FROM `Companies` AS `Extent1` INNER JOIN (SELECT `UnionAll1`.`Id`, `UnionAll1`.`Name`, `UnionAll2`.`Id` AS `Id1`, `UnionAll2`.`Name` AS `Name1` FROM (SELECT `Extent2`.`Id`, `Extent2`.`Name` FROM `Toys` AS `Extent2` UNION ALL SELECT `Extent3`.`Id`, `Extent3`.`Name` FROM `Stores` AS `Extent3`) AS `UnionAll1` INNER JOIN (SELECT `Extent4`.`Id`, `Extent4`.`Name` FROM `Authors` AS `Extent4` UNION ALL SELECT `Extent5`.`Id`, `Extent5`.`Name` FROM `Books` AS `Extent5`) AS `UnionAll2` ON `UnionAll1`.`Id` = `UnionAll2`.`Id`) AS `Join1` ON `Extent1`.`Id` = `Join1`.`Id` SELECT `Extent1`.`Id`, `Extent1`.`EmployeeID`, `Extent1`.`LastName`, `Extent1`.`FirstName`, `Extent1`.`BirthTime`, `Extent1`.`Weight`, `Extent1`.`LastModified` FROM `EmployeeChildren` AS `Extent1` INNER JOIN (SELECT `Extent2`.`Id`, `Extent2`.`LastName`, `Extent2`.`FirstName`, `Extent2`.`Age`, `Extent3`.`EmployeeId`, `Extent3`.`Salary` FROM `Employees` AS `Extent2` LEFT OUTER JOIN `SalariedEmployees` AS `Extent3` ON `Extent2`.`Id` = `Extent3`.`EmployeeId`) AS `Join1` ON `Extent1`.`EmployeeID` = `Join1`.`Id` WHERE `Extent1`.`Weight` > 7 SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Join1`.`Id` AS `Id1`, `Join1`.`Name` AS `Name1`, `Join1`.`Id1` AS `Id2`, `Join1`.`Name1` AS `Name2` FROM `Companies` AS `Extent1` INNER JOIN (SELECT `Extent2`.`Id`, `Extent2`.`Name`, `Extent2`.`Age`, `Extent3`.`Id` AS `Id1`, `Extent3`.`Name` AS `Name1`, `Extent3`.`Pages`, `Extent3`.`Author_id`, `Extent3`.`Publisher_id` FROM `Authors` AS `Extent2` INNER JOIN `Books` AS `Extent3` ON `Extent2`.`Id` = `Extent3`.`Id`) AS `Join1` ON `Extent1`.`Id` = `Join1`.`Id` SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode` FROM `Stores` AS `Extent1` INNER JOIN (SELECT MAX(`Extent2`.`StoreId`) AS `A1` FROM `Orders` AS `Extent2`) AS `GroupBy1` ON `Extent1`.`Id` = `GroupBy1`.`A1` SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode` FROM `Stores` AS `Extent1` INNER JOIN (SELECT MAX(`Extent2`.`StoreId`) AS `A1` FROM `Orders` AS `Extent2`) AS `GroupBy1` ON `Extent1`.`Id` = `GroupBy1`.`A1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT MAX(`Extent1`.`MinAge`) AS `A1` FROM `Toys` AS `Extent1`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT `Extent1`.`StoreId` AS `K1`, MAX(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` GROUP BY `Extent1`.`StoreId`) AS `GroupBy1` SELECT 1 AS `C1`, `GroupBy1`.`A1` AS `C2` FROM (SELECT MAX(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` WHERE `Extent1`.`StoreId` = 1) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT MIN(`Extent1`.`MinAge`) AS `A1` FROM `Toys` AS `Extent1`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT `Extent1`.`StoreId` AS `K1`, MIN(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` GROUP BY `Extent1`.`StoreId`) AS `GroupBy1` SELECT 1 AS `C1`, `GroupBy1`.`A1` AS `C2` FROM (SELECT MIN(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` WHERE `Extent1`.`StoreId` = 2) AS `GroupBy1` SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode` FROM `Companies` AS `Extent1` ORDER BY `Extent1`.`Name` ASC SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode` FROM `Companies` AS `Extent1` WHERE `Extent1`.`NumEmployees` > 100 ORDER BY `Extent1`.`Name` ASC SELECT `Extent1`.`Id`, `Extent1`.`LastName` FROM `Employees` AS `Extent1` LEFT OUTER JOIN `SalariedEmployees` AS `Extent2` ON `Extent1`.`Id` = `Extent2`.`EmployeeId` WHERE `Extent1`.`Age` > 20 SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent2`.`Name` AS `Name1` FROM `Books` AS `Extent1` INNER JOIN `Authors` AS `Extent2` ON `Extent1`.`Author_id` = `Extent2`.`Id` SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent2`.`Name` AS `Name1` FROM `Books` AS `Extent1` INNER JOIN `Authors` AS `Extent2` ON `Extent1`.`Author_id` = `Extent2`.`Id` WHERE `Extent1`.`Pages` > 300 SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`MinAge`, `Extent1`.`SupplierId` FROM `Toys` AS `Extent1` SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`MinAge`, `Extent1`.`SupplierId` FROM `Toys` AS `Extent1` WHERE `Extent1`.`MinAge` = 4 SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`MinAge`, `Extent1`.`SupplierId` FROM `Toys` AS `Extent1` WHERE `Extent1`.`MinAge` > @age SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode` FROM `Companies` AS `Extent1` ORDER BY `Extent1`.`Id` ASC LIMIT 3,18446744073709551615 SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode` FROM `Companies` AS `Extent1` ORDER BY `Extent1`.`Id` ASC LIMIT 2,2 SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode` FROM `Companies` AS `Extent1` ORDER BY `Extent1`.`Name` DESC LIMIT 2,2 SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT SUM(`Extent1`.`MinAge`) AS `A1` FROM `Toys` AS `Extent1`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT `Extent1`.`StoreId` AS `K1`, SUM(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` GROUP BY `Extent1`.`StoreId`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT SUM(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` WHERE `Extent1`.`StoreId` = 2) AS `GroupBy1` SELECT `Id`, `Name`, `DateBegan`, `NumEmployees`, `Address`, `City`, `State`, `ZipCode` FROM `Companies` LIMIT 2 SELECT `UnionAll1`.`Id` AS `C1`, `UnionAll1`.`Id1` AS `C2`, `UnionAll1`.`Name` AS `C3` FROM (SELECT `Extent1`.`Id`, `Extent1`.`Id` AS `Id1`, `Extent1`.`Name` FROM `Toys` AS `Extent1` UNION ALL SELECT `Extent2`.`Id`, `Extent2`.`Id` AS `Id1`, `Extent2`.`Name` FROM `Companies` AS `Extent2`) AS `UnionAll1` SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode` FROM `Companies` AS `Extent1` WHERE `Extent1`.`City` = @gp1 SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`MinAge`, `Extent1`.`SupplierId` FROM `Toys` AS `Extent1` INNER JOIN `Companies` AS `Extent2` ON `Extent1`.`SupplierId` = `Extent2`.`Id` WHERE `Extent2`.`State` = @gp1 SELECT `Filter1`.`Id`, `Filter1`.`Name`, `Filter1`.`MinAge`, `Filter1`.`SupplierId` FROM (SELECT `Extent1`.`Id`, `Extent1`.`SupplierId`, `Extent1`.`Name`, `Extent1`.`MinAge`, `Extent2`.`Id` AS `Id1`, `Extent2`.`Name` AS `Name1`, `Extent2`.`DateBegan`, `Extent2`.`NumEmployees`, `Extent2`.`Address`, `Extent2`.`City`, `Extent2`.`State`, `Extent2`.`ZipCode` FROM `Toys` AS `Extent1` INNER JOIN `Companies` AS `Extent2` ON `Extent1`.`SupplierId` = `Extent2`.`Id` WHERE `Extent2`.`State` != @gp1) AS `Filter1` LEFT OUTER JOIN `Companies` AS `Extent3` ON `Filter1`.`SupplierId` = `Extent3`.`Id` WHERE `Extent3`.`State` != @gp2 mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Properties/Resources.resx0000644000175000017500000001441311127003600030562 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 procs.sql;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 schema.sql;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Properties/schema.sql0000644000175000017500000002033611127003600027667 0ustar directhexdirecthexDROP TABLE IF EXISTS `Order`; DROP TABLE IF EXISTS Customer; DROP TABLE IF EXISTS Products; DROP TABLE IF EXISTS SalariedEmployees; DROP TABLE IF EXISTS Employees; DROP TABLE IF EXISTS EmployeeChildren; DROP TABLE IF EXISTS Toys; DROP TABLE IF EXISTS Companies; DROP TABLE IF EXISTS Orders; DROP TABLE IF EXISTS Stores; DROP TABLE IF EXISTS Books; DROP TABLE IF EXISTS Authors; DROP TABLE IF EXISTS Publishers; DROP TABLE IF EXISTS DataTypeTests; DROP TABLE IF EXISTS DesktopComputers; DROP TABLE IF EXISTS LaptopComputers; DROP TABLE IF EXISTS TabletComputers; DROP TABLE IF EXISTS Computers; CREATE TABLE Employees( Id INT NOT NULL PRIMARY KEY, LastName NVARCHAR(20) NOT NULL, FirstName NVARCHAR(10) NOT NULL, Age INT) ENGINE=InnoDB; INSERT INTO Employees VALUES (1, 'Flintstone', 'Fred', 43); INSERT INTO Employees VALUES (2, 'Flintstone', 'Wilma', 37); INSERT INTO Employees VALUES (3, 'Rubble', 'Barney', 41); INSERT INTO Employees VALUES (4, 'Rubble', 'Betty', 35); INSERT INTO Employees VALUES (5, 'Slate', 'S', 62); INSERT INTO Employees VALUES (6, 'Doo', 'Scooby', 7); INSERT INTO Employees VALUES (7, 'Underdog', 'J', 12); CREATE TABLE SalariedEmployees( EmployeeId INT NOT NULL PRIMARY KEY, Salary INT NOT NULL, CONSTRAINT FOREIGN KEY (EmployeeId) REFERENCES Employees (Id)) Engine=InnoDB; INSERT INTO salariedEmployees VALUES (5, 500); INSERT INTO salariedEmployees VALUES (7, 50); CREATE TABLE EmployeeChildren( Id INT UNSIGNED NOT NULL PRIMARY KEY, EmployeeId INT NOT NULL, LastName NVARCHAR(20) NOT NULL, FirstName NVARCHAR(10) NOT NULL, BirthTime TIME, Weight DOUBLE, LastModified TIMESTAMP NOT NULL); INSERT INTO EmployeeChildren VALUES (1, 1, 'Flintstone', 'Pebbles', NULL, NULL, NULL); CREATE TABLE Companies ( `Id` INT NOT NULL AUTO_INCREMENT, `Name` VARCHAR(100) NOT NULL, `DateBegan` DATETIME, `NumEmployees` INT, `Address` VARCHAR(50), `City` VARCHAR(50), `State` CHAR(2), `ZipCode` CHAR(9), CONSTRAINT PK_Companies PRIMARY KEY (Id)) ENGINE=InnoDB; INSERT INTO Companies VALUES (1, 'Hasbro', '1996-11-15 5:18:23', 200, '123 My Street', 'Nashville', 'TN', 12345); INSERT INTO Companies VALUES (2, 'Acme', NULL, 55, '45 The Lane', 'St. Louis', 'MO', 44332); INSERT INTO Companies VALUES (3, 'Bandai America', NULL, 376, '1 Infinite Loop', 'Cupertino', 'CA', 54321); INSERT INTO Companies VALUES (4, 'Lego Group', NULL, 700, '222 Park Circle', 'Lexington', 'KY', 32323); INSERT INTO Companies VALUES (5, 'Mattel', NULL, 888, '111 Parkwood Ave', 'San Jose', 'CA', 55676); INSERT INTO Companies VALUES (6, 'K''NEX', NULL, 382, '7812 N. 51st', 'Dallas', 'TX', 11239); INSERT INTO Companies VALUES (7, 'Playmobil', NULL, 541, '546 Main St.', 'Omaha', 'NE', 78439); CREATE TABLE Toys ( `Id` INT NOT NULL AUTO_INCREMENT, `SupplierId` INT NOT NULL, `Name` varchar(100) NOT NULL, `MinAge` int NOT NULL, CONSTRAINT PK_Toys PRIMARY KEY (Id), KEY `SupplierId` (`SupplierId`), FOREIGN KEY (SupplierId) REFERENCES Companies(Id) ) ENGINE=InnoDB; INSERT INTO Toys VALUES (1, 3, 'Slinky', 2); INSERT INTO Toys VALUES (2, 2, 'Rubiks Cube', 5); INSERT INTO Toys VALUES (3, 1, 'Lincoln Logs', 3); INSERT INTO Toys VALUES (4, 4, 'Legos', 4); CREATE TABLE Computers ( `Id` INT NOT NULL AUTO_INCREMENT, `Brand` varchar(100) NOT NULL, CONSTRAINT PK_Computers PRIMARY KEY (Id)) ENGINE=InnoDB; INSERT INTO Computers VALUES (1, 'Dell'); INSERT INTO Computers VALUES (2, 'Acer'); INSERT INTO Computers VALUES (3, 'Toshiba'); INSERT INTO Computers VALUES (4, 'Sony'); INSERT INTO Computers VALUES (5, 'Apple'); INSERT INTO Computers VALUES (6, 'HP'); CREATE TABLE DesktopComputers ( `IdDesktopComputer` INT NOT NULL , `Color` VARCHAR(15) NULL DEFAULT NULL , PRIMARY KEY (`IdDesktopComputer`) , CONSTRAINT FK_DesktopComputer_Computer FOREIGN KEY (IdDesktopComputer) REFERENCES Computers (Id)) ENGINE = InnoDB; INSERT INTO DesktopComputers VALUES (1, 'White'); INSERT INTO DesktopComputers VALUES (2, 'Black'); CREATE TABLE LaptopComputers ( `IdLaptopComputer` INT NOT NULL , `Size` VARCHAR(45) NULL DEFAULT NULL , `IsCertified` BIT(1) NULL DEFAULT NULL , PRIMARY KEY (IdLaptopComputer) , CONSTRAINT FK_LaptopComputer_Computer FOREIGN KEY (IdLaptopComputer) REFERENCES Computers(Id)) ENGINE = InnoDB; INSERT INTO LaptopComputers VALUES (3, '13.2 x 9.4', 1); INSERT INTO LaptopComputers VALUES (4, '19.5 x 13', 0); CREATE TABLE TabletComputers ( `IdTabletComputer` INT NOT NULL , `IsAvailable` BIT(1) NULL DEFAULT NULL , `ReleaseDate` DATETIME NULL DEFAULT NULL , PRIMARY KEY (IdTabletComputer) , CONSTRAINT FK_TabletComputer_Computer FOREIGN KEY (IdTabletComputer) REFERENCES Computers(Id)) ENGINE = InnoDB; INSERT INTO TabletComputers VALUES (5, 1, '2011-05-04'); INSERT INTO TabletComputers VALUES (6, 1, '2010-06-09'); CREATE TABLE Stores ( id INT PRIMARY KEY, `name` VARCHAR(50) NOT NULL, address VARCHAR(50), city VARCHAR(50), state CHAR(2), zipcode CHAR(9) ) ENGINE=InnoDB; INSERT INTO Stores VALUES (1, 'Target', '2417 N. Haskell Ave', 'Dallas', 'TX', '75204'); INSERT INTO Stores VALUES (2, 'K-Mart', '4225 W. Indian School Rd.', 'Phoenix', 'AZ', '85019'); INSERT INTO Stores VALUES (3, 'Wal-Mart', '1238 Putty Hill Ave', 'Towson', 'MD', '21286'); CREATE TABLE Orders ( id INT PRIMARY KEY, storeId INT NOT NULL, freight DOUBLE NOT NULL, FOREIGN KEY (storeId) REFERENCES Stores(id)) ENGINE=InnoDB; INSERT INTO Orders VALUES (1, 1, 65.3); INSERT INTO Orders VALUES (2, 2, 127.8); INSERT INTO Orders VALUES (3, 3, 254.78); INSERT INTO Orders VALUES (4, 1, 165.8); INSERT INTO Orders VALUES (5, 2, 85.2); INSERT INTO Orders VALUES (6, 3, 98.5); INSERT INTO Orders VALUES (7, 1, 222.3); INSERT INTO Orders VALUES (8, 2, 125); INSERT INTO Orders VALUES (9, 3, 126.4); INSERT INTO Orders VALUES (10, 3, 350.54721); CREATE TABLE Authors( id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` VARCHAR(20) NOT NULL, age INT) ENGINE=InnoDB; INSERT INTO Authors VALUES (1, 'Tom Clancy', 65); INSERT INTO Authors VALUES (2, 'Stephen King', 57); INSERT INTO Authors VALUES (3, 'John Grisham', 49); INSERT INTO Authors VALUES (4, 'Dean Koontz', 52); INSERT INTO Authors VALUES (5, 'Don Box', 44); CREATE TABLE Publishers( id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` VARCHAR(20) NOT NULL) ENGINE=InnoDB; INSERT INTO Publishers VALUES (1, 'Acme Publishing'); CREATE TABLE Books ( id INT AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` VARCHAR(20) NOT NULL, pages int, author_id int NOT NULL, publisher_id int NOT NULL, FOREIGN KEY (author_id) REFERENCES Authors(id), FOREIGN KEY (publisher_id) REFERENCES Publishers(id)) ENGINE=InnoDB; INSERT INTO Books VALUES (1, 'Debt of Honor', 200, 1, 1); INSERT INTO Books VALUES (2, 'Insomnia', 350, 2, 1); INSERT INTO Books VALUES (3, 'Rainmaker', 475, 3, 1); SET @guid=UUID(); CREATE TABLE DataTypeTests( id CHAR(36) CHARACTER SET utf8 NOT NULL PRIMARY KEY, id2 CHAR(36) BINARY NOT NULL, idAsChar VARCHAR(36)); INSERT INTO DataTypeTests VALUES (@guid, @guid, @guid); INSERT INTO DataTypeTests VALUES ('481A6506-03A3-4ef9-A05A-B247E75A2FB4', '481A6506-03A3-4ef9-A05A-B247E75A2FB4', '481A6506-03A3-4ef9-A05A-B247E75A2FB4'); CREATE TABLE Products ( Id INT NOT NULL AUTO_INCREMENT, Name VARCHAR(45) NOT NULL, CreatedDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (Id)); CREATE TABLE Customer ( Id int(11) NOT NULL auto_increment, Name varchar(255) default NULL, PRIMARY KEY (ID) ) ENGINE=InnoDB AUTO_INCREMENT=5; insert into Customer(Id,Name) values (1,'Fred'),(2,'Barney'),(3,'Wilma'),(4,'Betty'); CREATE TABLE `Order` ( Id int(11) NOT NULL auto_increment, Order_Date datetime NOT NULL, Customer_Id int(11) default NULL, PRIMARY KEY (ID), KEY ORDER_CUSTOMER_KEY (CUSTOMER_ID), CONSTRAINT FK_ORDER_CUSTOMER FOREIGN KEY (Customer_Id) REFERENCES Customer (Id) ) ENGINE=InnoDB AUTO_INCREMENT=7; insert into `Order`(Id,Order_Date,Customer_Id) values (1,'2011-06-24 00:00:00',1),(2,'2011-06-25 00:00:00',1),(3,'2011-06-26 00:00:00',1), (4,'2011-06-01 00:00:00',2),(5,'2011-06-02 00:00:00',2),(6,'2011-06-03 00:00:00',3); mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Properties/procs.sql0000644000175000017500000000124311127003600027551 0ustar directhexdirecthex DROP PROCEDURE IF EXISTS AddAuthor$$ DROP PROCEDURE IF EXISTS DeleteAuthor$$ DROP PROCEDURE IF EXISTS UpdateAuthor$$ CREATE PROCEDURE AddAuthor(theid INT, thename VARCHAR(20), theage INT) BEGIN IF theid = 66 THEN SELECT SLEEP(30); ELSE INSERT INTO authors VALUES (theid, thename, theage); END IF; END $$ CREATE PROCEDURE DeleteAuthor(theid int) BEGIN DELETE FROM authors WHERE id=theid; END $$ CREATE PROCEDURE UpdateAuthor(theid int, thename varchar(20), theage int) BEGIN UPDATE authors SET `name`=thename, age=theage WHERE id=theid; END $$ CREATE FUNCTION spFunc(id INT, name VARCHAR(20)) RETURNS INT BEGIN RETURN id; END $$ mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Properties/AssemblyInfo.cs0000644000175000017500000000434411127003600030631 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MySql.Data.Entity.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Oracle")] [assembly: AssemblyProduct("MySql.Data.Entity.Tests")] [assembly: AssemblyCopyright("Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a4c0a8f2-5e48-4227-a712-bf8ae7446101")] [assembly: AssemblyKeyName("ConnectorNet")]mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/Properties/SQLSyntax.Designer.cs0000644000175000017500000006671511127003600031655 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.235 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace MySql.Data.Entity.Tests.Properties { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SQLSyntax { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SQLSyntax() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MySql.Data.Entity.Tests.Properties.SQLSyntax", typeof(SQLSyntax).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`Age` ///FROM `Authors` AS `Extent1` /// WHERE NOT EXISTS(SELECT ///1 AS `C1` ///FROM `Books` AS `Extent2` /// WHERE `Extent1`.`Id` = `Extent2`.`Author_id`). /// internal static string Any { get { return ResourceManager.GetString("Any", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`GroupBy1`.`A1` AS `C1` ///FROM (SELECT ///AVG(`Extent1`.`MinAge`) AS `A1` ///FROM `Toys` AS `Extent1`) AS `GroupBy1`. /// internal static string AverageSimple { get { return ResourceManager.GetString("AverageSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS `C1`, ///`GroupBy1`.`A1` AS `C2` ///FROM (SELECT ///`Extent1`.`StoreId` AS `K1`, ///AVG(`Extent1`.`Freight`) AS `A1` ///FROM `Orders` AS `Extent1` /// GROUP BY ///`Extent1`.`StoreId`) AS `GroupBy1`. /// internal static string AverageWithGrouping { get { return ResourceManager.GetString("AverageWithGrouping", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`GroupBy1`.`A1` AS `C1` ///FROM (SELECT ///AVG(`Extent1`.`Freight`) AS `A1` ///FROM `Orders` AS `Extent1` /// WHERE `Extent1`.`StoreId` = 3) AS `GroupBy1`. /// internal static string AverageWithPredicate { get { return ResourceManager.GetString("AverageWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`GroupBy1`.`A1` AS `C1` ///FROM (SELECT ///COUNT(`Extent1`.`Id`) AS `A1` ///FROM `Toys` AS `Extent1`) AS `GroupBy1`. /// internal static string BigCountSimple { get { return ResourceManager.GetString("BigCountSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS `C1`, ///`GroupBy1`.`K1` AS `Name`, ///`GroupBy1`.`A1` AS `C2` ///FROM (SELECT ///`Extent1`.`Name` AS `K1`, ///`Extent1`.`DateBegan` AS `K2`, ///`Extent1`.`NumEmployees` AS `K3`, ///COUNT(1) AS `A1` ///FROM `Companies` AS `Extent1` /// GROUP BY ///`Extent1`.`Name`, ///`Extent1`.`DateBegan`, ///`Extent1`.`NumEmployees`) AS `GroupBy1`. /// internal static string CanGroupByMultipleColumns { get { return ResourceManager.GetString("CanGroupByMultipleColumns", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS `C1`, ///`GroupBy1`.`K1` AS `Name`, ///`GroupBy1`.`A1` AS `C2` ///FROM (SELECT ///`Extent1`.`Name` AS `K1`, ///COUNT(1) AS `A1` ///FROM `Companies` AS `Extent1` /// GROUP BY ///`Extent1`.`Name`) AS `GroupBy1`. /// internal static string CanGroupBySingleColumn { get { return ResourceManager.GetString("CanGroupBySingleColumn", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`GroupBy1`.`A1` AS `C1` ///FROM (SELECT ///COUNT(`Extent1`.`Id`) AS `A1` ///FROM `Toys` AS `Extent1`) AS `GroupBy1`. /// internal static string CountSimple { get { return ResourceManager.GetString("CountSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`GroupBy1`.`A1` AS `C1` ///FROM (SELECT ///COUNT(`Extent1`.`Id`) AS `A1` ///FROM `Toys` AS `Extent1` /// WHERE `Extent1`.`MinAge` > 3) AS `GroupBy1`. /// internal static string CountWithPredicate { get { return ResourceManager.GetString("CountWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`DateBegan`, ///`Extent1`.`NumEmployees`, ///`Extent1`.`Address`, ///`Extent1`.`City`, ///`Extent1`.`State`, ///`Extent1`.`ZipCode` ///FROM `Companies` AS `Extent1` /// WHERE EXISTS(SELECT ///1 AS `C1` ///FROM `Toys` AS `Extent2` /// WHERE (`Extent1`.`Id` = `Extent2`.`SupplierId`) AND (`Extent2`.`MinAge` < 4)). /// internal static string Exists { get { return ResourceManager.GetString("Exists", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Join1`.`Id` AS `C1`, ///`Join1`.`Name` AS `C2`, ///`Join1`.`Id1` AS `C3`, ///`Join1`.`Name1` AS `C4` ///FROM `Companies` AS `Extent1` INNER JOIN (SELECT ///`UnionAll1`.`Id`, ///`UnionAll1`.`Name`, ///`UnionAll2`.`Id` AS `Id1`, ///`UnionAll2`.`Name` AS `Name1` ///FROM (SELECT ///`Extent2`.`Id`, ///`Extent2`.`Name` ///FROM `Toys` AS `Extent2` UNION ALL SELECT ///`Extent3`.`Id`, ///`Extent3`.`Name` ///FROM `Stores` AS `Extent3`) AS `UnionAll1` INNER JOIN (SELECT ///`Extent4`.`Id`, ///`Ext [rest of string was truncated]";. /// internal static string JoinOfUnionsOnRightSideOfJoin { get { return ResourceManager.GetString("JoinOfUnionsOnRightSideOfJoin", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`EmployeeID`, ///`Extent1`.`LastName`, ///`Extent1`.`FirstName`, ///`Extent1`.`BirthTime`, ///`Extent1`.`Weight`, ///`Extent1`.`LastModified` ///FROM `EmployeeChildren` AS `Extent1` INNER JOIN (SELECT ///`Extent2`.`Id`, ///`Extent2`.`LastName`, ///`Extent2`.`FirstName`, ///`Extent2`.`Age`, ///`Extent3`.`EmployeeId`, ///`Extent3`.`Salary` ///FROM `Employees` AS `Extent2` LEFT OUTER JOIN `SalariedEmployees` AS `Extent3` ON `Extent2`.`Id` = `Extent3`.`EmployeeId`) AS `Join1` ON `Extent1`.`E [rest of string was truncated]";. /// internal static string JoinOnRightSideAsDerivedTable { get { return ResourceManager.GetString("JoinOnRightSideAsDerivedTable", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Join1`.`Id` AS `Id1`, ///`Join1`.`Name` AS `Name1`, ///`Join1`.`Id1` AS `Id2`, ///`Join1`.`Name1` AS `Name2` ///FROM `Companies` AS `Extent1` INNER JOIN (SELECT ///`Extent2`.`Id`, ///`Extent2`.`Name`, ///`Extent2`.`Age`, ///`Extent3`.`Id` AS `Id1`, ///`Extent3`.`Name` AS `Name1`, ///`Extent3`.`Pages`, ///`Extent3`.`Author_id`, ///`Extent3`.`Publisher_id` ///FROM `Authors` AS `Extent2` INNER JOIN `Books` AS `Extent3` ON `Extent2`.`Id` = `Extent3`.`Id`) AS `Join1` ON `Extent1`.` [rest of string was truncated]";. /// internal static string JoinOnRightSideNameClash { get { return ResourceManager.GetString("JoinOnRightSideNameClash", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`Address`, ///`Extent1`.`City`, ///`Extent1`.`State`, ///`Extent1`.`ZipCode` ///FROM `Stores` AS `Extent1` INNER JOIN (SELECT ///MAX(`Extent2`.`StoreId`) AS `A1` ///FROM `Orders` AS `Extent2`) AS `GroupBy1` ON `Extent1`.`Id` = `GroupBy1`.`A1`. /// internal static string MaxInSubQuery1 { get { return ResourceManager.GetString("MaxInSubQuery1", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`Address`, ///`Extent1`.`City`, ///`Extent1`.`State`, ///`Extent1`.`ZipCode` ///FROM `Stores` AS `Extent1` INNER JOIN (SELECT ///MAX(`Extent2`.`StoreId`) AS `A1` ///FROM `Orders` AS `Extent2`) AS `GroupBy1` ON `Extent1`.`Id` = `GroupBy1`.`A1`. /// internal static string MaxInSubQuery2 { get { return ResourceManager.GetString("MaxInSubQuery2", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`GroupBy1`.`A1` AS `C1` ///FROM (SELECT ///MAX(`Extent1`.`MinAge`) AS `A1` ///FROM `Toys` AS `Extent1`) AS `GroupBy1`. /// internal static string MaxSimple { get { return ResourceManager.GetString("MaxSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`GroupBy1`.`A1` AS `C1` ///FROM (SELECT ///`Extent1`.`StoreId` AS `K1`, ///MAX(`Extent1`.`Freight`) AS `A1` ///FROM `Orders` AS `Extent1` /// GROUP BY ///`Extent1`.`StoreId`) AS `GroupBy1`. /// internal static string MaxWithGrouping { get { return ResourceManager.GetString("MaxWithGrouping", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS `C1`, ///`GroupBy1`.`A1` AS `C2` ///FROM (SELECT ///MAX(`Extent1`.`Freight`) AS `A1` ///FROM `Orders` AS `Extent1` /// WHERE `Extent1`.`StoreId` = 1) AS `GroupBy1`. /// internal static string MaxWithPredicate { get { return ResourceManager.GetString("MaxWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`GroupBy1`.`A1` AS `C1` ///FROM (SELECT ///MIN(`Extent1`.`MinAge`) AS `A1` ///FROM `Toys` AS `Extent1`) AS `GroupBy1`. /// internal static string MinSimple { get { return ResourceManager.GetString("MinSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`GroupBy1`.`A1` AS `C1` ///FROM (SELECT ///`Extent1`.`StoreId` AS `K1`, ///MIN(`Extent1`.`Freight`) AS `A1` ///FROM `Orders` AS `Extent1` /// GROUP BY ///`Extent1`.`StoreId`) AS `GroupBy1`. /// internal static string MinWithGrouping { get { return ResourceManager.GetString("MinWithGrouping", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS `C1`, ///`GroupBy1`.`A1` AS `C2` ///FROM (SELECT ///MIN(`Extent1`.`Freight`) AS `A1` ///FROM `Orders` AS `Extent1` /// WHERE `Extent1`.`StoreId` = 2) AS `GroupBy1`. /// internal static string MinWithPredicate { get { return ResourceManager.GetString("MinWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`DateBegan`, ///`Extent1`.`NumEmployees`, ///`Extent1`.`Address`, ///`Extent1`.`City`, ///`Extent1`.`State`, ///`Extent1`.`ZipCode` ///FROM `Companies` AS `Extent1` /// ORDER BY ///`Extent1`.`Name` ASC. /// internal static string OrderBySimple { get { return ResourceManager.GetString("OrderBySimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`DateBegan`, ///`Extent1`.`NumEmployees`, ///`Extent1`.`Address`, ///`Extent1`.`City`, ///`Extent1`.`State`, ///`Extent1`.`ZipCode` ///FROM `Companies` AS `Extent1` /// WHERE `Extent1`.`NumEmployees` > 100 /// ORDER BY ///`Extent1`.`Name` ASC. /// internal static string OrderByWithPredicate { get { return ResourceManager.GetString("OrderByWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`LastName` ///FROM `Employees` AS `Extent1` LEFT OUTER JOIN `SalariedEmployees` AS `Extent2` ON `Extent1`.`Id` = `Extent2`.`EmployeeId` /// WHERE `Extent1`.`Age` > 20. /// internal static string SelectWithComplexType { get { return ResourceManager.GetString("SelectWithComplexType", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent2`.`Name` AS `Name1` ///FROM `Books` AS `Extent1` INNER JOIN `Authors` AS `Extent2` ON `Extent1`.`Author_id` = `Extent2`.`Id`. /// internal static string SimpleJoin { get { return ResourceManager.GetString("SimpleJoin", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent2`.`Name` AS `Name1` ///FROM `Books` AS `Extent1` INNER JOIN `Authors` AS `Extent2` ON `Extent1`.`Author_id` = `Extent2`.`Id` /// WHERE `Extent1`.`Pages` > 300. /// internal static string SimpleJoinWithPredicate { get { return ResourceManager.GetString("SimpleJoinWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`MinAge`, ///`Extent1`.`SupplierId` ///FROM `Toys` AS `Extent1`. /// internal static string SimpleSelect { get { return ResourceManager.GetString("SimpleSelect", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`MinAge`, ///`Extent1`.`SupplierId` ///FROM `Toys` AS `Extent1` /// WHERE `Extent1`.`MinAge` = 4. /// internal static string SimpleSelectWithFilter { get { return ResourceManager.GetString("SimpleSelectWithFilter", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`MinAge`, ///`Extent1`.`SupplierId` ///FROM `Toys` AS `Extent1` /// WHERE `Extent1`.`MinAge` > @age. /// internal static string SimpleSelectWithParam { get { return ResourceManager.GetString("SimpleSelectWithParam", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`DateBegan`, ///`Extent1`.`NumEmployees`, ///`Extent1`.`Address`, ///`Extent1`.`City`, ///`Extent1`.`State`, ///`Extent1`.`ZipCode` ///FROM `Companies` AS `Extent1` /// ORDER BY ///`Extent1`.`Id` ASC LIMIT 3,18446744073709551615. /// internal static string Skip { get { return ResourceManager.GetString("Skip", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`DateBegan`, ///`Extent1`.`NumEmployees`, ///`Extent1`.`Address`, ///`Extent1`.`City`, ///`Extent1`.`State`, ///`Extent1`.`ZipCode` ///FROM `Companies` AS `Extent1` /// ORDER BY ///`Extent1`.`Id` ASC LIMIT 2,2. /// internal static string SkipAndTakeSimple { get { return ResourceManager.GetString("SkipAndTakeSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`DateBegan`, ///`Extent1`.`NumEmployees`, ///`Extent1`.`Address`, ///`Extent1`.`City`, ///`Extent1`.`State`, ///`Extent1`.`ZipCode` ///FROM `Companies` AS `Extent1` /// ORDER BY ///`Extent1`.`Name` DESC LIMIT 2,2. /// internal static string SkipAndTakeWithOrdering { get { return ResourceManager.GetString("SkipAndTakeWithOrdering", resourceCulture); } } /// /// Looks up a localized string similar to . /// internal static string String1 { get { return ResourceManager.GetString("String1", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`GroupBy1`.`A1` AS `C1` ///FROM (SELECT ///SUM(`Extent1`.`MinAge`) AS `A1` ///FROM `Toys` AS `Extent1`) AS `GroupBy1`. /// internal static string SumSimple { get { return ResourceManager.GetString("SumSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`GroupBy1`.`A1` AS `C1` ///FROM (SELECT ///`Extent1`.`StoreId` AS `K1`, ///SUM(`Extent1`.`Freight`) AS `A1` ///FROM `Orders` AS `Extent1` /// GROUP BY ///`Extent1`.`StoreId`) AS `GroupBy1`. /// internal static string SumWithGrouping { get { return ResourceManager.GetString("SumWithGrouping", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`GroupBy1`.`A1` AS `C1` ///FROM (SELECT ///SUM(`Extent1`.`Freight`) AS `A1` ///FROM `Orders` AS `Extent1` /// WHERE `Extent1`.`StoreId` = 2) AS `GroupBy1`. /// internal static string SumWithPredicate { get { return ResourceManager.GetString("SumWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Id`, ///`Name`, ///`DateBegan`, ///`NumEmployees`, ///`Address`, ///`City`, ///`State`, ///`ZipCode` ///FROM `Companies` LIMIT 2. /// internal static string Top { get { return ResourceManager.GetString("Top", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`UnionAll1`.`Id` AS `C1`, ///`UnionAll1`.`Id1` AS `C2`, ///`UnionAll1`.`Name` AS `C3` ///FROM (SELECT ///`Extent1`.`Id`, ///`Extent1`.`Id` AS `Id1`, ///`Extent1`.`Name` ///FROM `Toys` AS `Extent1` UNION ALL SELECT ///`Extent2`.`Id`, ///`Extent2`.`Id` AS `Id1`, ///`Extent2`.`Name` ///FROM `Companies` AS `Extent2`) AS `UnionAll1`. /// internal static string UnionAll { get { return ResourceManager.GetString("UnionAll", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`DateBegan`, ///`Extent1`.`NumEmployees`, ///`Extent1`.`Address`, ///`Extent1`.`City`, ///`Extent1`.`State`, ///`Extent1`.`ZipCode` ///FROM `Companies` AS `Extent1` /// WHERE `Extent1`.`City` = @gp1. /// internal static string WhereLiteralOnRelation { get { return ResourceManager.GetString("WhereLiteralOnRelation", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Extent1`.`Id`, ///`Extent1`.`Name`, ///`Extent1`.`MinAge`, ///`Extent1`.`SupplierId` ///FROM `Toys` AS `Extent1` INNER JOIN `Companies` AS `Extent2` ON `Extent1`.`SupplierId` = `Extent2`.`Id` /// WHERE `Extent2`.`State` = @gp1. /// internal static string WhereWithRelatedEntities1 { get { return ResourceManager.GetString("WhereWithRelatedEntities1", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///`Filter1`.`Id`, ///`Filter1`.`Name`, ///`Filter1`.`MinAge`, ///`Filter1`.`SupplierId` ///FROM (SELECT ///`Extent1`.`Id`, ///`Extent1`.`SupplierId`, ///`Extent1`.`Name`, ///`Extent1`.`MinAge`, ///`Extent2`.`Id` AS `Id1`, ///`Extent2`.`Name` AS `Name1`, ///`Extent2`.`DateBegan`, ///`Extent2`.`NumEmployees`, ///`Extent2`.`Address`, ///`Extent2`.`City`, ///`Extent2`.`State`, ///`Extent2`.`ZipCode` ///FROM `Toys` AS `Extent1` INNER JOIN `Companies` AS `Extent2` ON `Extent1`.`SupplierId` = `Extent2`.`Id` /// WHERE `Extent2`.`S [rest of string was truncated]";. /// internal static string WhereWithRelatedEntities2 { get { return ResourceManager.GetString("WhereWithRelatedEntities2", resourceCulture); } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/AggregateOperators.cs0000644000175000017500000003443111127003600027667 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using NUnit.Framework; using System.Data.Objects; using MySql.Data.Entity.Tests.Properties; namespace MySql.Data.Entity.Tests { [TestFixture] public class AggregateOperators : BaseEdmTest { [Test] public void CountSimple() { MySqlCommand trueCmd = new MySqlCommand("SELECT COUNT(*) FROM Toys", conn); object trueCount = trueCmd.ExecuteScalar(); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE Count(t.Id) FROM Toys AS t"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.CountSimple); foreach (int count in q) Assert.AreEqual(trueCount, count); } } [Test] public void BigCountSimple() { MySqlCommand trueCmd = new MySqlCommand("SELECT COUNT(*) FROM Toys", conn); object trueCount = trueCmd.ExecuteScalar(); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE BigCount(t.Id) FROM Toys AS t"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.BigCountSimple); foreach (int count in q) Assert.AreEqual(trueCount, count); } } [Test] public void CountWithPredicate() { MySqlCommand trueCmd = new MySqlCommand("SELECT COUNT(*) FROM Toys AS t WHERE t.MinAge > 3", conn); object trueCount = trueCmd.ExecuteScalar(); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE Count(t.Id) FROM Toys AS t WHERE t.MinAge > 3"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.CountWithPredicate); foreach (int count in q) Assert.AreEqual(trueCount, count); } } [Test] public void MinSimple() { MySqlCommand trueCmd = new MySqlCommand("SELECT MIN(minage) FROM Toys", conn); int trueMin = (int)trueCmd.ExecuteScalar(); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE MIN(t.MinAge) FROM Toys AS t"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.MinSimple); foreach (int age in q) Assert.AreEqual(trueMin, age); } } [Test] public void MinWithPredicate() { MySqlCommand trueCmd = new MySqlCommand("SELECT MIN(Freight) FROM Orders WHERE storeId=2", conn); object freight = trueCmd.ExecuteScalar(); using (testEntities context = new testEntities()) { string eSql = "SELECT Min(o.Freight) FROM Orders AS o WHERE o.Store.Id = 2"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.MinWithPredicate); foreach (DbDataRecord r in q) { Assert.AreEqual(freight, r.GetDouble(0)); } } } [Test] public void MinWithGrouping() { MySqlDataAdapter da = new MySqlDataAdapter( "SELECT MIN(Freight) FROM Orders GROUP BY storeId", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE Min(o.Freight) FROM Orders AS o GROUP BY o.Store.Id"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.MinWithGrouping); int i = 0; foreach (double freight in q) Assert.AreEqual(Convert.ToInt32(dt.Rows[i++][0]), Convert.ToInt32(freight)); } } [Test] public void MaxSimple() { MySqlCommand trueCmd = new MySqlCommand("SELECT MAX(minage) FROM Toys", conn); int trueMax = (int)trueCmd.ExecuteScalar(); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE MAX(t.MinAge) FROM Toys AS t"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.MaxSimple); foreach (int max in q) Assert.AreEqual(trueMax, max); } } [Test] public void MaxWithPredicate() { MySqlCommand trueCmd = new MySqlCommand("SELECT MAX(Freight) FROM Orders WHERE storeId=1", conn); object freight = trueCmd.ExecuteScalar(); using (testEntities context = new testEntities()) { string eSql = "SELECT MAX(o.Freight) FROM Orders AS o WHERE o.Store.Id = 1"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.MaxWithPredicate); foreach (DbDataRecord r in q) Assert.AreEqual(freight, r.GetDouble(0)); } } [Test] public void MaxWithGrouping() { MySqlDataAdapter da = new MySqlDataAdapter( "SELECT MAX(Freight) FROM Orders GROUP BY StoreId", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE MAX(o.Freight) FROM Orders AS o GROUP BY o.Store.Id"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.MaxWithGrouping); int i = 0; foreach (double freight in q) Assert.AreEqual(Convert.ToInt32(dt.Rows[i++][0]), Convert.ToInt32(freight)); } } [Test] public void AverageSimple() { MySqlCommand trueCmd = new MySqlCommand("SELECT AVG(minAge) FROM Toys", conn); object avgAge = trueCmd.ExecuteScalar(); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE Avg(t.MinAge) FROM Toys AS t"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.AverageSimple); foreach (Decimal r in q) Assert.AreEqual(avgAge, r); } } [Test] public void AverageWithPredicate() { MySqlCommand trueCmd = new MySqlCommand("SELECT AVG(Freight) FROM Orders WHERE storeId=3", conn); Double freight = (Double)trueCmd.ExecuteScalar(); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE AVG(o.Freight) FROM Orders AS o WHERE o.Store.Id = 3"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.AverageWithPredicate); foreach (Double r in q) Assert.AreEqual(Convert.ToInt32(freight), Convert.ToInt32(r)); } } [Test] public void AverageWithGrouping() { MySqlDataAdapter da = new MySqlDataAdapter( "SELECT AVG(Freight) FROM Orders GROUP BY StoreId", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { string eSql = "SELECT AVG(o.Freight) FROM Orders AS o GROUP BY o.Store.Id"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.AverageWithGrouping); foreach (object x in q) { string s = x.GetType().ToString(); } int i = 0; foreach (var freight in q) { // Assert.AreEqual(Convert.ToInt32(dt.Rows[i++][0]), Convert.ToInt32(freight)); } } } [Test] public void SumSimple() { MySqlCommand trueCmd = new MySqlCommand("SELECT SUM(minage) FROM Toys", conn); object sumAge = trueCmd.ExecuteScalar(); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE Sum(t.MinAge) FROM Toys AS t"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.SumSimple); foreach (int r in q) Assert.AreEqual(sumAge, r); } } [Test] public void SumWithPredicate() { MySqlCommand trueCmd = new MySqlCommand("SELECT SUM(Freight) FROM Orders WHERE storeId=2", conn); object freight = trueCmd.ExecuteScalar(); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE SUM(o.Freight) FROM Orders AS o WHERE o.Store.Id = 2"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.SumWithPredicate); foreach (Double r in q) Assert.AreEqual(freight, r); } } [Test] public void SumWithGrouping() { MySqlDataAdapter da = new MySqlDataAdapter( "SELECT SUM(Freight) FROM Orders GROUP BY StoreId", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { string eSql = "SELECT VALUE SUM(o.Freight) FROM Orders AS o GROUP BY o.Store.Id"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.SumWithGrouping); int i = 0; foreach (double freight in q) Assert.AreEqual(Convert.ToInt32(dt.Rows[i++][0]), Convert.ToInt32(freight)); } } [Test] public void MaxInSubQuery1() { MySqlDataAdapter da= new MySqlDataAdapter( "SELECT s.* FROM Stores AS s WHERE s.id=(SELECT MAX(o.storeId) FROM Orders AS o)", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { string eSql = @"SELECT VALUE s FROM Stores AS s WHERE s.Id = MAX(SELECT VALUE o.Store.Id FROM Orders As o)"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.MaxInSubQuery1); int i = 0; foreach (Store s in q) Assert.AreEqual(dt.Rows[i++]["id"], s.Id); } } [Test] public void MaxInSubQuery2() { MySqlDataAdapter da = new MySqlDataAdapter( "SELECT s.* FROM Stores AS s WHERE s.id=(SELECT MAX(o.storeId) FROM Orders AS o)", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { string eSql = @"SELECT VALUE s FROM Stores AS s WHERE s.Id = ANYELEMENT(SELECT VALUE MAX(o.Store.Id) FROM Orders As o)"; ObjectQuery q = context.CreateQuery(eSql); string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.MaxInSubQuery2); int i = 0; foreach (Store s in q) Assert.AreEqual(dt.Rows[i++]["id"], s.Id); } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/TestModel.Designer.cs0000644000175000017500000024233511127003600027545 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // //------------------------------------------------------------------------------ using System; using System.Data.Objects; using System.Data.Objects.DataClasses; using System.Data.EntityClient; using System.ComponentModel; using System.Xml.Serialization; using System.Runtime.Serialization; [assembly: EdmSchemaAttribute()] #region EDM Relationship Metadata [assembly: EdmRelationshipAttribute("testModel", "FK_Toys_Supplier", "Supplier", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(MySql.Data.Entity.Tests.Company), "Toys", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(MySql.Data.Entity.Tests.Toy))] [assembly: EdmRelationshipAttribute("testModel", "FK_Orders_Store", "Store", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(MySql.Data.Entity.Tests.Store), "Orders", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(MySql.Data.Entity.Tests.Order))] [assembly: EdmRelationshipAttribute("testModel", "FK_Books_Authors", "Authors", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(MySql.Data.Entity.Tests.Author), "Books", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(MySql.Data.Entity.Tests.Book))] [assembly: EdmRelationshipAttribute("testModel", "FK_Books_Publishers", "Publishers", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(MySql.Data.Entity.Tests.Publisher), "Books", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(MySql.Data.Entity.Tests.Book))] #endregion namespace MySql.Data.Entity.Tests { #region Contexts /// /// No Metadata Documentation available. /// public partial class testEntities : ObjectContext { #region Constructors /// /// Initializes a new testEntities object using the connection string found in the 'testEntities' section of the application configuration file. /// public testEntities() : base("name=testEntities", "testEntities") { OnContextCreated(); } /// /// Initialize a new testEntities object. /// public testEntities(string connectionString) : base(connectionString, "testEntities") { OnContextCreated(); } /// /// Initialize a new testEntities object. /// public testEntities(EntityConnection connection) : base(connection, "testEntities") { OnContextCreated(); } #endregion #region Partial Methods partial void OnContextCreated(); #endregion #region ObjectSet Properties /// /// No Metadata Documentation available. /// public ObjectSet Employees { get { if ((_Employees == null)) { _Employees = base.CreateObjectSet("Employees"); } return _Employees; } } private ObjectSet _Employees; /// /// No Metadata Documentation available. /// public ObjectSet Children { get { if ((_Children == null)) { _Children = base.CreateObjectSet("Children"); } return _Children; } } private ObjectSet _Children; /// /// No Metadata Documentation available. /// public ObjectSet Companies { get { if ((_Companies == null)) { _Companies = base.CreateObjectSet("Companies"); } return _Companies; } } private ObjectSet _Companies; /// /// No Metadata Documentation available. /// public ObjectSet Toys { get { if ((_Toys == null)) { _Toys = base.CreateObjectSet("Toys"); } return _Toys; } } private ObjectSet _Toys; /// /// No Metadata Documentation available. /// public ObjectSet Stores { get { if ((_Stores == null)) { _Stores = base.CreateObjectSet("Stores"); } return _Stores; } } private ObjectSet _Stores; /// /// No Metadata Documentation available. /// public ObjectSet Orders { get { if ((_Orders == null)) { _Orders = base.CreateObjectSet("Orders"); } return _Orders; } } private ObjectSet _Orders; /// /// No Metadata Documentation available. /// public ObjectSet Books { get { if ((_Books == null)) { _Books = base.CreateObjectSet("Books"); } return _Books; } } private ObjectSet _Books; /// /// No Metadata Documentation available. /// public ObjectSet Authors { get { if ((_Authors == null)) { _Authors = base.CreateObjectSet("Authors"); } return _Authors; } } private ObjectSet _Authors; /// /// No Metadata Documentation available. /// public ObjectSet Publishers { get { if ((_Publishers == null)) { _Publishers = base.CreateObjectSet("Publishers"); } return _Publishers; } } private ObjectSet _Publishers; /// /// No Metadata Documentation available. /// public ObjectSet DataTypeTests { get { if ((_DataTypeTests == null)) { _DataTypeTests = base.CreateObjectSet("DataTypeTests"); } return _DataTypeTests; } } private ObjectSet _DataTypeTests; /// /// No Metadata Documentation available. /// public ObjectSet Computers { get { if ((_Computers == null)) { _Computers = base.CreateObjectSet("Computers"); } return _Computers; } } private ObjectSet _Computers; /// /// No Metadata Documentation available. /// public ObjectSet Products { get { if ((_Products == null)) { _Products = base.CreateObjectSet("Products"); } return _Products; } } private ObjectSet _Products; #endregion #region AddTo Methods /// /// Deprecated Method for adding a new object to the Employees EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToEmployees(Employee employee) { base.AddObject("Employees", employee); } /// /// Deprecated Method for adding a new object to the Children EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToChildren(Child child) { base.AddObject("Children", child); } /// /// Deprecated Method for adding a new object to the Companies EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToCompanies(Company company) { base.AddObject("Companies", company); } /// /// Deprecated Method for adding a new object to the Toys EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToToys(Toy toy) { base.AddObject("Toys", toy); } /// /// Deprecated Method for adding a new object to the Stores EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToStores(Store store) { base.AddObject("Stores", store); } /// /// Deprecated Method for adding a new object to the Orders EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToOrders(Order order) { base.AddObject("Orders", order); } /// /// Deprecated Method for adding a new object to the Books EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToBooks(Book book) { base.AddObject("Books", book); } /// /// Deprecated Method for adding a new object to the Authors EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToAuthors(Author author) { base.AddObject("Authors", author); } /// /// Deprecated Method for adding a new object to the Publishers EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToPublishers(Publisher publisher) { base.AddObject("Publishers", publisher); } /// /// Deprecated Method for adding a new object to the DataTypeTests EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToDataTypeTests(DataTypeTest dataTypeTest) { base.AddObject("DataTypeTests", dataTypeTest); } /// /// Deprecated Method for adding a new object to the Computers EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToComputers(Computer computer) { base.AddObject("Computers", computer); } /// /// Deprecated Method for adding a new object to the Products EntitySet. Consider using the .Add method of the associated ObjectSet<T> property instead. /// public void AddToProducts(Product product) { base.AddObject("Products", product); } #endregion } #endregion #region Entities /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="Author")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Author : EntityObject { #region Factory Method /// /// Create a new Author object. /// /// Initial value of the Id property. /// Initial value of the Name property. public static Author CreateAuthor(global::System.Int32 id, global::System.String name) { Author author = new Author(); author.Id = id; author.Name = name; return author; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Name { get { return _Name; } set { OnNameChanging(value); ReportPropertyChanging("Name"); _Name = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Name"); OnNameChanged(); } } private global::System.String _Name; partial void OnNameChanging(global::System.String value); partial void OnNameChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public Nullable Age { get { return _Age; } set { OnAgeChanging(value); ReportPropertyChanging("Age"); _Age = StructuralObject.SetValidValue(value); ReportPropertyChanged("Age"); OnAgeChanged(); } } private Nullable _Age; partial void OnAgeChanging(Nullable value); partial void OnAgeChanged(); #endregion #region Navigation Properties /// /// No Metadata Documentation available. /// [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Books_Authors", "Books")] public EntityCollection Books { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection("testModel.FK_Books_Authors", "Books"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection("testModel.FK_Books_Authors", "Books", value); } } } #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="Book")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Book : EntityObject { #region Factory Method /// /// Create a new Book object. /// /// Initial value of the Id property. /// Initial value of the Name property. /// Initial value of the Pages property. public static Book CreateBook(global::System.Int32 id, global::System.String name, global::System.Int32 pages) { Book book = new Book(); book.Id = id; book.Name = name; book.Pages = pages; return book; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Name { get { return _Name; } set { OnNameChanging(value); ReportPropertyChanging("Name"); _Name = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Name"); OnNameChanged(); } } private global::System.String _Name; partial void OnNameChanging(global::System.String value); partial void OnNameChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Pages { get { return _Pages; } set { OnPagesChanging(value); ReportPropertyChanging("Pages"); _Pages = StructuralObject.SetValidValue(value); ReportPropertyChanged("Pages"); OnPagesChanged(); } } private global::System.Int32 _Pages; partial void OnPagesChanging(global::System.Int32 value); partial void OnPagesChanged(); #endregion #region Navigation Properties /// /// No Metadata Documentation available. /// [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Books_Authors", "Authors")] public Author Author { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("testModel.FK_Books_Authors", "Authors").Value; } set { ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("testModel.FK_Books_Authors", "Authors").Value = value; } } /// /// No Metadata Documentation available. /// [BrowsableAttribute(false)] [DataMemberAttribute()] public EntityReference AuthorReference { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("testModel.FK_Books_Authors", "Authors"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference("testModel.FK_Books_Authors", "Authors", value); } } } /// /// No Metadata Documentation available. /// [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Books_Publishers", "Publishers")] public Publisher Publisher { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("testModel.FK_Books_Publishers", "Publishers").Value; } set { ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("testModel.FK_Books_Publishers", "Publishers").Value = value; } } /// /// No Metadata Documentation available. /// [BrowsableAttribute(false)] [DataMemberAttribute()] public EntityReference PublisherReference { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("testModel.FK_Books_Publishers", "Publishers"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference("testModel.FK_Books_Publishers", "Publishers", value); } } } #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="Child")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Child : EntityObject { #region Factory Method /// /// Create a new Child object. /// /// Initial value of the Id property. /// Initial value of the EmployeeID property. /// Initial value of the LastName property. /// Initial value of the FirstName property. /// Initial value of the Modified property. public static Child CreateChild(global::System.Int64 id, global::System.Int32 employeeID, global::System.String lastName, global::System.String firstName, global::System.DateTime modified) { Child child = new Child(); child.Id = id; child.EmployeeID = employeeID; child.LastName = lastName; child.FirstName = firstName; child.Modified = modified; return child; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int64 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int64 _Id; partial void OnIdChanging(global::System.Int64 value); partial void OnIdChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 EmployeeID { get { return _EmployeeID; } set { OnEmployeeIDChanging(value); ReportPropertyChanging("EmployeeID"); _EmployeeID = StructuralObject.SetValidValue(value); ReportPropertyChanged("EmployeeID"); OnEmployeeIDChanged(); } } private global::System.Int32 _EmployeeID; partial void OnEmployeeIDChanging(global::System.Int32 value); partial void OnEmployeeIDChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String LastName { get { return _LastName; } set { OnLastNameChanging(value); ReportPropertyChanging("LastName"); _LastName = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("LastName"); OnLastNameChanged(); } } private global::System.String _LastName; partial void OnLastNameChanging(global::System.String value); partial void OnLastNameChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String FirstName { get { return _FirstName; } set { OnFirstNameChanging(value); ReportPropertyChanging("FirstName"); _FirstName = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("FirstName"); OnFirstNameChanged(); } } private global::System.String _FirstName; partial void OnFirstNameChanging(global::System.String value); partial void OnFirstNameChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public Nullable BirthTime { get { return _BirthTime; } set { OnBirthTimeChanging(value); ReportPropertyChanging("BirthTime"); _BirthTime = StructuralObject.SetValidValue(value); ReportPropertyChanged("BirthTime"); OnBirthTimeChanged(); } } private Nullable _BirthTime; partial void OnBirthTimeChanging(Nullable value); partial void OnBirthTimeChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public Nullable BirthWeight { get { return _BirthWeight; } set { OnBirthWeightChanging(value); ReportPropertyChanging("BirthWeight"); _BirthWeight = StructuralObject.SetValidValue(value); ReportPropertyChanged("BirthWeight"); OnBirthWeightChanged(); } } private Nullable _BirthWeight; partial void OnBirthWeightChanging(Nullable value); partial void OnBirthWeightChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.DateTime Modified { get { return _Modified; } set { OnModifiedChanging(value); ReportPropertyChanging("Modified"); _Modified = StructuralObject.SetValidValue(value); ReportPropertyChanged("Modified"); OnModifiedChanged(); } } private global::System.DateTime _Modified; partial void OnModifiedChanging(global::System.DateTime value); partial void OnModifiedChanged(); #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="Company")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Company : EntityObject { #region Factory Method /// /// Create a new Company object. /// /// Initial value of the Id property. /// Initial value of the Name property. /// Initial value of the Address property. public static Company CreateCompany(global::System.Int32 id, global::System.String name, CommonAddress address) { Company company = new Company(); company.Id = id; company.Name = name; company.Address = StructuralObject.VerifyComplexObjectIsNotNull(address, "Address"); return company; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Name { get { return _Name; } set { OnNameChanging(value); ReportPropertyChanging("Name"); _Name = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Name"); OnNameChanged(); } } private global::System.String _Name; partial void OnNameChanging(global::System.String value); partial void OnNameChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public Nullable DateBegan { get { return _DateBegan; } set { OnDateBeganChanging(value); ReportPropertyChanging("DateBegan"); _DateBegan = StructuralObject.SetValidValue(value); ReportPropertyChanged("DateBegan"); OnDateBeganChanged(); } } private Nullable _DateBegan; partial void OnDateBeganChanging(Nullable value); partial void OnDateBeganChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public Nullable NumEmployees { get { return _NumEmployees; } set { OnNumEmployeesChanging(value); ReportPropertyChanging("NumEmployees"); _NumEmployees = StructuralObject.SetValidValue(value); ReportPropertyChanged("NumEmployees"); OnNumEmployeesChanged(); } } private Nullable _NumEmployees; partial void OnNumEmployeesChanging(Nullable value); partial void OnNumEmployeesChanged(); #endregion #region Complex Properties /// /// No Metadata Documentation available. /// [EdmComplexPropertyAttribute()] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [XmlElement(IsNullable=true)] [SoapElement(IsNullable=true)] [DataMemberAttribute()] public CommonAddress Address { get { _Address = GetValidValue(_Address, "Address", false, _AddressInitialized); _AddressInitialized = true; return _Address; } set { OnAddressChanging(value); ReportPropertyChanging("Address"); _Address = SetValidValue(_Address, value, "Address"); _AddressInitialized = true; ReportPropertyChanged("Address"); OnAddressChanged(); } } private CommonAddress _Address; private bool _AddressInitialized; partial void OnAddressChanging(CommonAddress value); partial void OnAddressChanged(); #endregion #region Navigation Properties /// /// No Metadata Documentation available. /// [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Toys_Supplier", "Toys")] public EntityCollection Toys { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection("testModel.FK_Toys_Supplier", "Toys"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection("testModel.FK_Toys_Supplier", "Toys", value); } } } #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="Computer")] [Serializable()] [DataContractAttribute(IsReference=true)] [KnownTypeAttribute(typeof(DesktopComputer))] [KnownTypeAttribute(typeof(LaptopComputer))] [KnownTypeAttribute(typeof(TabletComputer))] public abstract partial class Computer : EntityObject { #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Brand { get { return _Brand; } set { OnBrandChanging(value); ReportPropertyChanging("Brand"); _Brand = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Brand"); OnBrandChanged(); } } private global::System.String _Brand; partial void OnBrandChanging(global::System.String value); partial void OnBrandChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="DataTypeTest")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class DataTypeTest : EntityObject { #region Factory Method /// /// Create a new DataTypeTest object. /// /// Initial value of the id property. /// Initial value of the id2 property. public static DataTypeTest CreateDataTypeTest(global::System.Guid id, global::System.Guid id2) { DataTypeTest dataTypeTest = new DataTypeTest(); dataTypeTest.id = id; dataTypeTest.id2 = id2; return dataTypeTest; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Guid id { get { return _id; } set { if (_id != value) { OnidChanging(value); ReportPropertyChanging("id"); _id = StructuralObject.SetValidValue(value); ReportPropertyChanged("id"); OnidChanged(); } } } private global::System.Guid _id; partial void OnidChanging(global::System.Guid value); partial void OnidChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Guid id2 { get { return _id2; } set { Onid2Changing(value); ReportPropertyChanging("id2"); _id2 = StructuralObject.SetValidValue(value); ReportPropertyChanged("id2"); Onid2Changed(); } } private global::System.Guid _id2; partial void Onid2Changing(global::System.Guid value); partial void Onid2Changed(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String idAsChar { get { return _idAsChar; } set { OnidAsCharChanging(value); ReportPropertyChanging("idAsChar"); _idAsChar = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("idAsChar"); OnidAsCharChanged(); } } private global::System.String _idAsChar; partial void OnidAsCharChanging(global::System.String value); partial void OnidAsCharChanged(); #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="DesktopComputer")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class DesktopComputer : Computer { #region Factory Method /// /// Create a new DesktopComputer object. /// /// Initial value of the Brand property. /// Initial value of the Id property. public static DesktopComputer CreateDesktopComputer(global::System.String brand, global::System.Int32 id) { DesktopComputer desktopComputer = new DesktopComputer(); desktopComputer.Brand = brand; desktopComputer.Id = id; return desktopComputer; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String Color { get { return _Color; } set { OnColorChanging(value); ReportPropertyChanging("Color"); _Color = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("Color"); OnColorChanged(); } } private global::System.String _Color; partial void OnColorChanging(global::System.String value); partial void OnColorChanged(); #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="Employee")] [Serializable()] [DataContractAttribute(IsReference=true)] [KnownTypeAttribute(typeof(SalariedEmployee))] public partial class Employee : EntityObject { #region Factory Method /// /// Create a new Employee object. /// /// Initial value of the Id property. /// Initial value of the LastName property. /// Initial value of the FirstName property. public static Employee CreateEmployee(global::System.Int32 id, global::System.String lastName, global::System.String firstName) { Employee employee = new Employee(); employee.Id = id; employee.LastName = lastName; employee.FirstName = firstName; return employee; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String LastName { get { return _LastName; } set { OnLastNameChanging(value); ReportPropertyChanging("LastName"); _LastName = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("LastName"); OnLastNameChanged(); } } private global::System.String _LastName; partial void OnLastNameChanging(global::System.String value); partial void OnLastNameChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String FirstName { get { return _FirstName; } set { OnFirstNameChanging(value); ReportPropertyChanging("FirstName"); _FirstName = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("FirstName"); OnFirstNameChanged(); } } private global::System.String _FirstName; partial void OnFirstNameChanging(global::System.String value); partial void OnFirstNameChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public Nullable Age { get { return _Age; } set { OnAgeChanging(value); ReportPropertyChanging("Age"); _Age = StructuralObject.SetValidValue(value); ReportPropertyChanged("Age"); OnAgeChanged(); } } private Nullable _Age; partial void OnAgeChanging(Nullable value); partial void OnAgeChanged(); #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="LaptopComputer")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class LaptopComputer : Computer { #region Factory Method /// /// Create a new LaptopComputer object. /// /// Initial value of the Brand property. /// Initial value of the Id property. public static LaptopComputer CreateLaptopComputer(global::System.String brand, global::System.Int32 id) { LaptopComputer laptopComputer = new LaptopComputer(); laptopComputer.Brand = brand; laptopComputer.Id = id; return laptopComputer; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public Nullable IsCertified { get { return _IsCertified; } set { OnIsCertifiedChanging(value); ReportPropertyChanging("IsCertified"); _IsCertified = StructuralObject.SetValidValue(value); ReportPropertyChanged("IsCertified"); OnIsCertifiedChanged(); } } private Nullable _IsCertified; partial void OnIsCertifiedChanging(Nullable value); partial void OnIsCertifiedChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String Size { get { return _Size; } set { OnSizeChanging(value); ReportPropertyChanging("Size"); _Size = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("Size"); OnSizeChanged(); } } private global::System.String _Size; partial void OnSizeChanging(global::System.String value); partial void OnSizeChanged(); #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="Order")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Order : EntityObject { #region Factory Method /// /// Create a new Order object. /// /// Initial value of the Id property. /// Initial value of the Freight property. public static Order CreateOrder(global::System.Int32 id, global::System.Double freight) { Order order = new Order(); order.Id = id; order.Freight = freight; return order; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Double Freight { get { return _Freight; } set { OnFreightChanging(value); ReportPropertyChanging("Freight"); _Freight = StructuralObject.SetValidValue(value); ReportPropertyChanged("Freight"); OnFreightChanged(); } } private global::System.Double _Freight; partial void OnFreightChanging(global::System.Double value); partial void OnFreightChanged(); #endregion #region Navigation Properties /// /// No Metadata Documentation available. /// [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Orders_Store", "Store")] public Store Store { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("testModel.FK_Orders_Store", "Store").Value; } set { ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("testModel.FK_Orders_Store", "Store").Value = value; } } /// /// No Metadata Documentation available. /// [BrowsableAttribute(false)] [DataMemberAttribute()] public EntityReference StoreReference { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("testModel.FK_Orders_Store", "Store"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference("testModel.FK_Orders_Store", "Store", value); } } } #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="Product")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Product : EntityObject { #region Factory Method /// /// Create a new Product object. /// /// Initial value of the Id property. /// Initial value of the Name property. /// Initial value of the CreatedDate property. public static Product CreateProduct(global::System.Int32 id, global::System.String name, global::System.DateTime createdDate) { Product product = new Product(); product.Id = id; product.Name = name; product.CreatedDate = createdDate; return product; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Name { get { return _Name; } set { OnNameChanging(value); ReportPropertyChanging("Name"); _Name = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Name"); OnNameChanged(); } } private global::System.String _Name; partial void OnNameChanging(global::System.String value); partial void OnNameChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.DateTime CreatedDate { get { return _CreatedDate; } set { OnCreatedDateChanging(value); ReportPropertyChanging("CreatedDate"); _CreatedDate = StructuralObject.SetValidValue(value); ReportPropertyChanged("CreatedDate"); OnCreatedDateChanged(); } } private global::System.DateTime _CreatedDate; partial void OnCreatedDateChanging(global::System.DateTime value); partial void OnCreatedDateChanged(); #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="Publisher")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Publisher : EntityObject { #region Factory Method /// /// Create a new Publisher object. /// /// Initial value of the id property. /// Initial value of the name property. public static Publisher CreatePublisher(global::System.Int32 id, global::System.String name) { Publisher publisher = new Publisher(); publisher.id = id; publisher.name = name; return publisher; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 id { get { return _id; } set { if (_id != value) { OnidChanging(value); ReportPropertyChanging("id"); _id = StructuralObject.SetValidValue(value); ReportPropertyChanged("id"); OnidChanged(); } } } private global::System.Int32 _id; partial void OnidChanging(global::System.Int32 value); partial void OnidChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String name { get { return _name; } set { OnnameChanging(value); ReportPropertyChanging("name"); _name = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("name"); OnnameChanged(); } } private global::System.String _name; partial void OnnameChanging(global::System.String value); partial void OnnameChanged(); #endregion #region Navigation Properties /// /// No Metadata Documentation available. /// [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Books_Publishers", "Books")] public EntityCollection Books { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection("testModel.FK_Books_Publishers", "Books"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection("testModel.FK_Books_Publishers", "Books", value); } } } #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="SalariedEmployee")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class SalariedEmployee : Employee { #region Factory Method /// /// Create a new SalariedEmployee object. /// /// Initial value of the Id property. /// Initial value of the LastName property. /// Initial value of the FirstName property. /// Initial value of the Salary property. public static SalariedEmployee CreateSalariedEmployee(global::System.Int32 id, global::System.String lastName, global::System.String firstName, global::System.Int32 salary) { SalariedEmployee salariedEmployee = new SalariedEmployee(); salariedEmployee.Id = id; salariedEmployee.LastName = lastName; salariedEmployee.FirstName = firstName; salariedEmployee.Salary = salary; return salariedEmployee; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Salary { get { return _Salary; } set { OnSalaryChanging(value); ReportPropertyChanging("Salary"); _Salary = StructuralObject.SetValidValue(value); ReportPropertyChanged("Salary"); OnSalaryChanged(); } } private global::System.Int32 _Salary; partial void OnSalaryChanging(global::System.Int32 value); partial void OnSalaryChanged(); #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="Store")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Store : EntityObject { #region Factory Method /// /// Create a new Store object. /// /// Initial value of the Id property. /// Initial value of the Name property. public static Store CreateStore(global::System.Int32 id, global::System.String name) { Store store = new Store(); store.Id = id; store.Name = name; return store; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Name { get { return _Name; } set { OnNameChanging(value); ReportPropertyChanging("Name"); _Name = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Name"); OnNameChanged(); } } private global::System.String _Name; partial void OnNameChanging(global::System.String value); partial void OnNameChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String Address { get { return _Address; } set { OnAddressChanging(value); ReportPropertyChanging("Address"); _Address = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("Address"); OnAddressChanged(); } } private global::System.String _Address; partial void OnAddressChanging(global::System.String value); partial void OnAddressChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String City { get { return _City; } set { OnCityChanging(value); ReportPropertyChanging("City"); _City = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("City"); OnCityChanged(); } } private global::System.String _City; partial void OnCityChanging(global::System.String value); partial void OnCityChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String State { get { return _State; } set { OnStateChanging(value); ReportPropertyChanging("State"); _State = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("State"); OnStateChanged(); } } private global::System.String _State; partial void OnStateChanging(global::System.String value); partial void OnStateChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String ZipCode { get { return _ZipCode; } set { OnZipCodeChanging(value); ReportPropertyChanging("ZipCode"); _ZipCode = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("ZipCode"); OnZipCodeChanged(); } } private global::System.String _ZipCode; partial void OnZipCodeChanging(global::System.String value); partial void OnZipCodeChanged(); #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="TabletComputer")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class TabletComputer : Computer { #region Factory Method /// /// Create a new TabletComputer object. /// /// Initial value of the Brand property. /// Initial value of the Id property. public static TabletComputer CreateTabletComputer(global::System.String brand, global::System.Int32 id) { TabletComputer tabletComputer = new TabletComputer(); tabletComputer.Brand = brand; tabletComputer.Id = id; return tabletComputer; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public Nullable IsAvailable { get { return _IsAvailable; } set { OnIsAvailableChanging(value); ReportPropertyChanging("IsAvailable"); _IsAvailable = StructuralObject.SetValidValue(value); ReportPropertyChanged("IsAvailable"); OnIsAvailableChanged(); } } private Nullable _IsAvailable; partial void OnIsAvailableChanging(Nullable value); partial void OnIsAvailableChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public Nullable ReleaseDate { get { return _ReleaseDate; } set { OnReleaseDateChanging(value); ReportPropertyChanging("ReleaseDate"); _ReleaseDate = StructuralObject.SetValidValue(value); ReportPropertyChanged("ReleaseDate"); OnReleaseDateChanged(); } } private Nullable _ReleaseDate; partial void OnReleaseDateChanging(Nullable value); partial void OnReleaseDateChanged(); #endregion } /// /// No Metadata Documentation available. /// [EdmEntityTypeAttribute(NamespaceName="testModel", Name="Toy")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class Toy : EntityObject { #region Factory Method /// /// Create a new Toy object. /// /// Initial value of the Id property. /// Initial value of the Name property. /// Initial value of the MinAge property. public static Toy CreateToy(global::System.Int32 id, global::System.String name, global::System.Int32 minAge) { Toy toy = new Toy(); toy.Id = id; toy.Name = name; toy.MinAge = minAge; return toy; } #endregion #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 Id { get { return _Id; } set { if (_Id != value) { OnIdChanging(value); ReportPropertyChanging("Id"); _Id = StructuralObject.SetValidValue(value); ReportPropertyChanged("Id"); OnIdChanged(); } } } private global::System.Int32 _Id; partial void OnIdChanging(global::System.Int32 value); partial void OnIdChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Name { get { return _Name; } set { OnNameChanging(value); ReportPropertyChanging("Name"); _Name = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Name"); OnNameChanged(); } } private global::System.String _Name; partial void OnNameChanging(global::System.String value); partial void OnNameChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 MinAge { get { return _MinAge; } set { OnMinAgeChanging(value); ReportPropertyChanging("MinAge"); _MinAge = StructuralObject.SetValidValue(value); ReportPropertyChanged("MinAge"); OnMinAgeChanged(); } } private global::System.Int32 _MinAge; partial void OnMinAgeChanging(global::System.Int32 value); partial void OnMinAgeChanged(); #endregion #region Navigation Properties /// /// No Metadata Documentation available. /// [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Toys_Supplier", "Supplier")] public Company Supplier { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("testModel.FK_Toys_Supplier", "Supplier").Value; } set { ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("testModel.FK_Toys_Supplier", "Supplier").Value = value; } } /// /// No Metadata Documentation available. /// [BrowsableAttribute(false)] [DataMemberAttribute()] public EntityReference SupplierReference { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference("testModel.FK_Toys_Supplier", "Supplier"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference("testModel.FK_Toys_Supplier", "Supplier", value); } } } #endregion } #endregion #region ComplexTypes /// /// No Metadata Documentation available. /// [EdmComplexTypeAttribute(NamespaceName="testModel", Name="CommonAddress")] [DataContractAttribute(IsReference=true)] [Serializable()] public partial class CommonAddress : ComplexObject { #region Primitive Properties /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String Address { get { return _Address; } set { OnAddressChanging(value); ReportPropertyChanging("Address"); _Address = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("Address"); OnAddressChanged(); } } private global::System.String _Address; partial void OnAddressChanging(global::System.String value); partial void OnAddressChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String City { get { return _City; } set { OnCityChanging(value); ReportPropertyChanging("City"); _City = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("City"); OnCityChanged(); } } private global::System.String _City; partial void OnCityChanging(global::System.String value); partial void OnCityChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String State { get { return _State; } set { OnStateChanging(value); ReportPropertyChanging("State"); _State = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("State"); OnStateChanged(); } } private global::System.String _State; partial void OnStateChanging(global::System.String value); partial void OnStateChanged(); /// /// No Metadata Documentation available. /// [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)] [DataMemberAttribute()] public global::System.String ZipCode { get { return _ZipCode; } set { OnZipCodeChanging(value); ReportPropertyChanging("ZipCode"); _ZipCode = StructuralObject.SetValidValue(value, true); ReportPropertyChanged("ZipCode"); OnZipCodeChanged(); } } private global::System.String _ZipCode; partial void OnZipCodeChanging(global::System.String value); partial void OnZipCodeChanged(); #endregion } #endregion } mysql-connector-net-6.4.3/Tests/MySql.Data.Entity.Tests/JoinTests.cs0000644000175000017500000001501611127003600026022 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using NUnit.Framework; using MySql.Data.MySqlClient.Tests; using System.Data.EntityClient; using System.Data.Common; using System.Data.Objects; using System.Linq; using MySql.Data.Entity.Tests.Properties; namespace MySql.Data.Entity.Tests { [TestFixture] public class JoinTests : BaseEdmTest { [Test] public void SimpleJoin() { MySqlDataAdapter da = new MySqlDataAdapter( @"SELECT b.id,b.name,a.name as author_name from books b JOIN authors a ON b.author_id=a.id", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { var q = from b in context.Books join a in context.Authors on b.Author.Id equals a.Id select new { bookId = b.Id, bookName = b.Name, authorName = a.Name }; string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.SimpleJoin); int i = 0; foreach (var o in q) Assert.AreEqual(dt.Rows[i++][0], o.bookId); Assert.AreEqual(dt.Rows.Count, i); } } [Test] public void SimpleJoinWithPredicate() { MySqlDataAdapter da = new MySqlDataAdapter( @"SELECT b.id,b.name,a.name as author_name from books b JOIN authors a ON b.author_id=a.id WHERE b.pages > 300", conn); DataTable dt = new DataTable(); da.Fill(dt); using (testEntities context = new testEntities()) { var q = from b in context.Books join a in context.Authors on b.Author.Id equals a.Id where b.Pages > 300 select new { bookId = b.Id, bookName = b.Name, authorName = a.Name }; string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.SimpleJoinWithPredicate); int i = 0; foreach (var o in q) Assert.AreEqual(dt.Rows[i++][0], o.bookId); Assert.AreEqual(dt.Rows.Count, i); } } [Test] public void JoinOnRightSideAsDerivedTable() { using (testEntities context = new testEntities()) { var q = from child in context.Children join emp in context.Employees on child.EmployeeID equals emp.Id where child.BirthWeight > 7 select child; string sql = q.ToTraceString(); CheckSql(sql, SQLSyntax.JoinOnRightSideAsDerivedTable); foreach (Child c in q) { } } } [Test] public void JoinOfUnionsOnRightSideofJoin() { using (testEntities context = new testEntities()) { string eSql = @"SELECT c.Id, c.Name, Union1.Id, Union1.Name, Union2.Id, Union2.Name FROM testEntities.Companies AS c JOIN ( ((SELECT t.Id, t.Name FROM testEntities.Toys as t) UNION ALL (SELECT s.Id, s.Name FROM testEntities.Stores as s)) AS Union1 JOIN ((SELECT a.Id, a.Name FROM testEntities.Authors AS a) UNION ALL (SELECT b.Id, b.Name FROM testEntities.Books AS b)) AS Union2 ON Union1.Id = Union2.Id) ON c.Id = Union1.Id"; ObjectQuery query = context.CreateQuery(eSql); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.JoinOfUnionsOnRightSideOfJoin); foreach (DbDataRecord record in query) { Assert.AreEqual(6, record.FieldCount); } } } [Test] public void JoinOnRightSideNameClash() { using (testEntities context = new testEntities()) { string eSql = @"SELECT c.Id, c.Name, a.Id, a.Name, b.Id, b.Name FROM testEntities.Companies AS c JOIN (testEntities.Authors AS a JOIN testEntities.Books AS b ON a.Id = b.Id) ON c.Id = a.Id"; ObjectQuery query = context.CreateQuery(eSql); string sql = query.ToTraceString(); CheckSql(sql, SQLSyntax.JoinOnRightSideNameClash); foreach (DbDataRecord record in query) { Assert.AreEqual(6, record.FieldCount); } } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/0000755000175000017500000000000011127003600022273 5ustar directhexdirecthexmysql-connector-net-6.4.3/Tests/MySql.Data.Tests/SqlTokenizer.cs0000644000175000017500000000362111127003600025256 0ustar directhexdirecthexusing System.Reflection; using System.Collections.Generic; namespace MySql.Data.MySqlClient.Tests { class SqlTokenizer { object tokenizer; public SqlTokenizer(string sql) { tokenizer = typeof(MySqlConnection).Assembly.CreateInstance("MySql.Data.MySqlClient.MySqlTokenizer", false, System.Reflection.BindingFlags.CreateInstance, null, new object[] { sql }, null, null); } public bool ReturnComments { set { PropertyInfo pi = tokenizer.GetType().GetProperty("ReturnComments"); pi.SetValue(tokenizer, value, null); } } public bool AnsiQuotes { set { PropertyInfo pi = tokenizer.GetType().GetProperty("AnsiQuotes"); pi.SetValue(tokenizer, value, null); } } public bool SqlServerMode { set { PropertyInfo pi = tokenizer.GetType().GetProperty("SqlServerMode"); pi.SetValue(tokenizer, value, null); } } public bool Quoted { get { PropertyInfo pi = tokenizer.GetType().GetProperty("Quoted"); return (bool)pi.GetValue(tokenizer, null); } } public string NextToken() { return (string)tokenizer.GetType().InvokeMember("NextToken", System.Reflection.BindingFlags.InvokeMethod, null, tokenizer, null); } public string NextParameter() { return (string)tokenizer.GetType().InvokeMember("NextParameter", System.Reflection.BindingFlags.InvokeMethod, null, tokenizer, null); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/Utils.cs0000644000175000017500000000267011127003600023727 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for Utils. /// public class Utils { public static byte[] CreateBlob( int size ) { byte[] buf = new byte[size]; Random r = new Random(); r.NextBytes( buf ); return buf; } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/CursorTests.cs0000644000175000017500000001211211127003600025117 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for BlobTests. /// [TestFixture] public class CursorTests : BaseTest { protected override void FixtureSetup() { Open(); execSQL("DROP TABLE IF EXISTS Test"); execSQL("DROP TABLE IF EXISTS Test2"); execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(100), PRIMARY KEY(id))"); execSQL("CREATE TABLE Test2 (id INT NOT NULL, parent INT, PRIMARY KEY(id))"); } protected override void TestFixtureTearDown() { execSQL("DROP TABLE IF EXISTS Test2"); Close(); } /* [Test] public void NestedCursors() { execSQL("INSERT INTO Test VALUES (1, 'Test1')"); execSQL("INSERT INTO Test VALUES (2, 'Test2')"); execSQL("INSERT INTO Test VALUES (3, 'Test3')"); execSQL("INSERT INTO Test2 VALUES (66, 1)"); execSQL("INSERT INTO Test2 VALUES (77, 2)"); execSQL("INSERT INTO Test2 VALUES (88, 3)"); MySqlCommand cmdOuter = new MySqlCommand("SELECT * FROM Test", conn); MySqlDataReader reader = null; MySqlDataReader reader2 = null; try { cmdOuter.Prepare(1); reader = cmdOuter.ExecuteReader(); Assert.IsTrue( reader.Read() ); Assert.AreEqual( 1, reader.GetInt32(0) ); Assert.AreEqual( "Test1", reader.GetString(1) ); MySqlCommand cmd = new MySqlCommand( "SELECT * FROM Test2 WHERE parent=" + reader.GetInt32(0), conn ); cmd.Prepare(1); reader2 = cmd.ExecuteReader(); Assert.IsTrue( reader2.Read() ); Assert.AreEqual( 66, reader2.GetInt32(0) ); reader2.Close(); Assert.IsTrue( reader.Read() ); Assert.AreEqual( 2, reader.GetInt32(0) ); Assert.AreEqual( "Test2", reader.GetString(1) ); cmd.CommandText = "SELECT * FROM Test2 WHERE parent=" + reader.GetInt32(0); cmd.Prepare(1); reader2 = cmd.ExecuteReader(); Assert.IsTrue( reader2.Read() ); Assert.AreEqual( 77, reader2.GetInt32(0) ); reader2.Close(); Assert.IsTrue( reader.Read() ); Assert.AreEqual( 3, reader.GetInt32(0) ); Assert.AreEqual( "Test3", reader.GetString(1) ); cmd.CommandText = "SELECT * FROM Test2 WHERE parent=" + reader.GetInt32(0); cmd.Prepare(1); reader2 = cmd.ExecuteReader(); Assert.IsTrue( reader2.Read() ); Assert.AreEqual( 88, reader2.GetInt32(0) ); reader2.Close(); Assert.IsFalse( reader.NextResult() ); } catch (Exception ex) { Assert.Fail( ex.Message ); } finally { if (reader != null) reader.Close(); } } */ /* [Test] public void SimpleCursors() { execSQL("INSERT INTO Test VALUES (1, 'Test1')"); execSQL("INSERT INTO Test VALUES (2, 'Test2')"); execSQL("INSERT INTO Test VALUES (3, 'Test3')"); execSQL("INSERT INTO Test VALUES (4, 'Test4')"); execSQL("INSERT INTO Test VALUES (5, 'Test5')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); MySqlDataReader reader =null; try { cmd.Prepare(1); reader = cmd.ExecuteReader(); Assert.IsTrue( reader.Read() ); Assert.AreEqual( 1, reader.GetInt32(0) ); Assert.AreEqual( "Test1", reader.GetString(1) ); Assert.IsTrue( reader.Read() ); Assert.AreEqual( 2, reader.GetInt32(0) ); Assert.AreEqual( "Test2", reader.GetString(1) ); Assert.IsTrue( reader.Read() ); Assert.AreEqual( 3, reader.GetInt32(0) ); Assert.AreEqual( "Test3", reader.GetString(1) ); Assert.IsTrue( reader.Read() ); Assert.AreEqual( 4, reader.GetInt32(0) ); Assert.AreEqual( "Test4", reader.GetString(1) ); Assert.IsTrue( reader.Read() ); Assert.AreEqual( 5, reader.GetInt32(0) ); Assert.AreEqual( "Test5", reader.GetString(1) ); Assert.IsFalse( reader.NextResult() ); } catch (Exception ex) { Assert.Fail( ex.Message ); } finally { if (reader != null) reader.Close(); } }*/ } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/ScriptExecution.cs0000644000175000017500000002214411127003600025755 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Text; using System.Data; using System.IO; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class ScriptExecution : BaseTest { [SetUp] public override void Setup() { base.Setup (); execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); } private int statementCount; private string statementTemplate1 = @"CREATE PROCEDURE `spTest{0}`() NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER COMMENT '' BEGIN SELECT 1,2,3; END{1}"; [Test] public void ExecuteScriptWithProcedures() { if (Version < new Version(5, 0)) return; statementCount = 0; string scriptText = String.Empty; for (int i=0; i < 10; i++) { scriptText += String.Format(statementTemplate1, i, "$$"); } MySqlScript script = new MySqlScript(scriptText); script.StatementExecuted += new MySqlStatementExecutedEventHandler(ExecuteScriptWithProcedures_QueryExecuted); script.Connection = conn; script.Delimiter = "$$"; int count = script.Execute(); Assert.AreEqual(10, count); MySqlCommand cmd = new MySqlCommand( String.Format(@"SELECT COUNT(*) FROM information_schema.routines WHERE routine_schema = '{0}' AND routine_name LIKE 'spTest%'", database0), conn); Assert.AreEqual(10, cmd.ExecuteScalar()); } void ExecuteScriptWithProcedures_QueryExecuted(object sender, MySqlScriptEventArgs e) { string stmt = String.Format(statementTemplate1, statementCount++, null); Assert.AreEqual(stmt, e.StatementText); } private string statementTemplate2 = @"INSERT INTO Test (id, name) VALUES ({0}, 'a "" na;me'){1}"; [Test] public void ExecuteScriptWithInserts() { statementCount = 0; string scriptText = String.Empty; for (int i = 0; i < 10; i++) { scriptText += String.Format(statementTemplate2, i, ";"); } MySqlScript script = new MySqlScript(scriptText); script.Connection = conn; script.StatementExecuted += new MySqlStatementExecutedEventHandler(ExecuteScriptWithInserts_StatementExecuted); int count = script.Execute(); Assert.AreEqual(10, count); MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM Test", conn); Assert.AreEqual(10, cmd.ExecuteScalar()); } void ExecuteScriptWithInserts_StatementExecuted(object sender, MySqlScriptEventArgs e) { string stmt = String.Format(statementTemplate2, statementCount++, null); Assert.AreEqual(stmt, e.StatementText); } [Test] public void ExecuteScriptContinueOnError() { statementCount = 0; string scriptText = String.Empty; for (int i = 0; i < 5; i++) scriptText += String.Format(statementTemplate2, i, ";"); scriptText += "bogus statement;"; for (int i = 5; i < 10; i++) scriptText += String.Format(statementTemplate2, i, ";"); MySqlScript script = new MySqlScript(scriptText); script.Connection = conn; script.Error += new MySqlScriptErrorEventHandler(ExecuteScript_ContinueOnError); int count = script.Execute(); Assert.AreEqual(10, count); Assert.AreEqual(1, statementCount); MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM Test", conn); Assert.AreEqual(10, cmd.ExecuteScalar()); } void ExecuteScript_ContinueOnError(object sender, MySqlScriptErrorEventArgs args) { args.Ignore = true; statementCount++; } [Test] public void ExecuteScriptNotContinueOnError() { statementCount = 0; string scriptText = String.Empty; for (int i = 0; i < 5; i++) scriptText += String.Format(statementTemplate2, i, ";"); scriptText += "bogus statement;"; for (int i = 5; i < 10; i++) scriptText += String.Format(statementTemplate2, i, ";"); MySqlScript script = new MySqlScript(scriptText); script.Connection = conn; script.Error += new MySqlScriptErrorEventHandler(ExecuteScript_NotContinueOnError); int count = script.Execute(); Assert.AreEqual(5, count); Assert.AreEqual(1, statementCount); MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM Test", conn); Assert.AreEqual(5, cmd.ExecuteScalar()); } void ExecuteScript_NotContinueOnError(object sender, MySqlScriptErrorEventArgs args) { args.Ignore = false; statementCount++; } [Test] public void ExecuteScriptWithUserVariables() { string connStr = conn.ConnectionString.ToLowerInvariant(); connStr = connStr.Replace("allow user variables=true", "allow user variables=false"); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); string scriptText = "SET @myvar = 1"; MySqlScript script = new MySqlScript(scriptText); script.Connection = c; int count = script.Execute(); Assert.AreEqual(1, count); } } /// /// Bug #46429 use DELIMITER command in MySql.Data.MySqlClient.MySqlScript /// [Test] public void ScriptWithDelimiterStatements() { if (Version < new Version(5, 0)) return; StringBuilder sql = new StringBuilder(); sql.AppendFormat("{0}DELIMITER $${0}", Environment.NewLine); sql.AppendFormat(statementTemplate1, 1, "$$"); sql.AppendFormat("{0}DELIMITER //{0}", Environment.NewLine); sql.AppendFormat(statementTemplate1, 2, "//"); MySqlScript s = new MySqlScript(); s.Query = sql.ToString(); s.Delimiter = "XX"; s.Connection = conn; int count = s.Execute(); } /// /// Bug #46429 use DELIMITER command in MySql.Data.MySqlClient.MySqlScript /// [Test] public void DelimiterInScriptV2() { StringBuilder sql = new StringBuilder(); sql.AppendLine("DELIMITER MySuperDelimiter"); sql.AppendLine("CREATE PROCEDURE TestProcedure1()"); sql.AppendLine("BEGIN"); sql.AppendLine(" SELECT * FROM mysql.proc;"); sql.AppendLine("END MySuperDelimiter"); sql.AppendLine("CREATE PROCEDURE TestProcedure2()"); sql.AppendLine("BEGIN"); sql.AppendLine(" SELECT * FROM mysql.proc;"); sql.AppendLine("END mysuperdelimiter"); sql.AppendLine("DELIMITER ;"); MySqlScript script = new MySqlScript(conn, sql.ToString()); script.Execute(); } /// /// Bug #50344 MySqlScript.Execute() throws InvalidOperationException /// [Test] public void EmptyLastLineWithScriptExecute() { StringBuilder sb = new StringBuilder(); sb.AppendLine("DROP FUNCTION IF EXISTS `BlaBla`;"); sb.AppendLine("DELIMITER ;;"); MySqlScript script = new MySqlScript(conn, sb.ToString()); // InvalidOperationException : The CommandText property has not been properly initialized. script.Execute(); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/DataTypeTests.cs0000644000175000017500000012217311127003600025366 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using MySql.Data.MySqlClient; using MySql.Data.Types; using System.Data; using NUnit.Framework; using System.Data.Common; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for ConnectionTests. /// [TestFixture] public class DataTypeTests : BaseTest { [Test] public void BytesAndBooleans() { InternalBytesAndBooleans(false); } [Test] public void BytesAndBooleansPrepared() { if (Version < new Version(4, 1)) return; InternalBytesAndBooleans(true); } private void InternalBytesAndBooleans(bool prepare) { execSQL("CREATE TABLE Test (id TINYINT, idu TINYINT UNSIGNED, i INT UNSIGNED)"); execSQL("INSERT INTO Test VALUES (-98, 140, 20)"); execSQL("INSERT INTO Test VALUES (0, 0, 0)"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); if (prepare) cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(-98, (sbyte)reader.GetByte(0)); Assert.AreEqual(140, reader.GetByte(1)); Assert.IsTrue(reader.GetBoolean(1)); Assert.AreEqual(20, reader.GetUInt32(2)); Assert.AreEqual(20, reader.GetInt32(2)); Assert.IsTrue(reader.Read()); Assert.AreEqual(0, reader.GetByte(0)); Assert.AreEqual(0, reader.GetByte(1)); Assert.IsFalse(reader.GetBoolean(1)); Assert.IsFalse(reader.Read()); } } /// /// Bug#46205 - tinyint as boolean does not work for utf8 default database character set. /// /// /// Original bug occured only with mysqld started with --default-character-set=utf8. /// It does not seem possible to reproduce the original buggy behaviorotherwise /// Neither "set global character_set_server = utf8" , nor "create table /database with character set " /// were sufficient. /// [Test] public void TreatTinyAsBool() { if (version < new Version(4, 1)) return; execSQL("CREATE TABLE Test2(i TINYINT(1))"); execSQL("INSERT INTO Test2 VALUES(1)"); execSQL("INSERT INTO Test2 VALUES(0)"); execSQL("INSERT INTO Test2 VALUES(2)"); MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(conn.ConnectionString); Assert.IsTrue(builder.TreatTinyAsBoolean); MySqlCommand cmd = new MySqlCommand("SELECT * from Test2", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { bool b; Assert.IsTrue(reader.Read()); b = (bool)reader.GetValue(0); Assert.IsTrue(b); Assert.IsTrue(reader.Read()); b = (bool)reader.GetValue(0); Assert.IsFalse(b); Assert.IsTrue(reader.Read()); b = (bool)reader.GetValue(0); Assert.IsTrue(b); } } [Test] public void TestFloat() { InternalTestFloats(false); } [Test] public void TestFloatPrepared() { if (Version < new Version(4, 1)) return; InternalTestFloats(true); } private void InternalTestFloats(bool prepared) { execSQL("CREATE TABLE Test (fl FLOAT, db DOUBLE, dec1 DECIMAL(5,2))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?fl, ?db, ?dec)", conn); cmd.Parameters.Add("?fl", MySqlDbType.Float); cmd.Parameters.Add("?db", MySqlDbType.Double); cmd.Parameters.Add("?dec", MySqlDbType.Decimal); cmd.Parameters[0].Value = 2.3; cmd.Parameters[1].Value = 4.6; cmd.Parameters[2].Value = 23.82; if (prepared) cmd.Prepare(); int count = cmd.ExecuteNonQuery(); Assert.AreEqual(1, count); cmd.Parameters[0].Value = 1.5; cmd.Parameters[1].Value = 47.85; cmd.Parameters[2].Value = 123.85; count = cmd.ExecuteNonQuery(); Assert.AreEqual(1, count); cmd.CommandText = "SELECT * FROM Test"; if (prepared) cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(2.3, (decimal)reader.GetFloat(0)); Assert.AreEqual(4.6, reader.GetDouble(1)); Assert.AreEqual(23.82, reader.GetDecimal(2)); Assert.IsTrue(reader.Read()); Assert.AreEqual(1.5, (decimal)reader.GetFloat(0)); Assert.AreEqual(47.85, reader.GetDouble(1)); Assert.AreEqual(123.85, reader.GetDecimal(2)); } } [Test] public void TestTime() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(100), d DATE, dt DATETIME, tm TIME, PRIMARY KEY(id))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, tm) VALUES (1, '00:00')", conn); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO Test (id, tm) VALUES (2, '512:45:17')"; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); object value = reader["tm"]; Assert.AreEqual(value.GetType(), typeof(TimeSpan)); TimeSpan ts = (TimeSpan)reader["tm"]; Assert.AreEqual(0, ts.Hours); Assert.AreEqual(0, ts.Minutes); Assert.AreEqual(0, ts.Seconds); reader.Read(); value = reader["tm"]; Assert.AreEqual(value.GetType(), typeof(TimeSpan)); ts = (TimeSpan)reader["tm"]; Assert.AreEqual(21, ts.Days); Assert.AreEqual(8, ts.Hours); Assert.AreEqual(45, ts.Minutes); Assert.AreEqual(17, ts.Seconds); } } [Test] public void YearType() { execSQL("CREATE TABLE Test (yr YEAR)"); execSQL("INSERT INTO Test VALUES (98)"); execSQL("INSERT INTO Test VALUES (1990)"); execSQL("INSERT INTO Test VALUES (2004)"); execSQL("SET SQL_MODE=''"); execSQL("INSERT INTO Test VALUES (111111111111111111111)"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual(1998, reader.GetUInt32(0)); reader.Read(); Assert.AreEqual(1990, reader.GetUInt32(0)); reader.Read(); Assert.AreEqual(2004, reader.GetUInt32(0)); reader.Read(); Assert.AreEqual(0, reader.GetUInt32(0)); } } [Test] public void TypeCoercion() { MySqlParameter p = new MySqlParameter("?test", 1); Assert.AreEqual( DbType.Int32, p.DbType ); Assert.AreEqual( MySqlDbType.Int32, p.MySqlDbType ); p.DbType = DbType.Int64; Assert.AreEqual( DbType.Int64, p.DbType ); Assert.AreEqual( MySqlDbType.Int64, p.MySqlDbType ); p.MySqlDbType = MySqlDbType.Int16; Assert.AreEqual( DbType.Int16, p.DbType ); Assert.AreEqual( MySqlDbType.Int16, p.MySqlDbType ); } /// /// Bug #7951 - Error reading timestamp column /// [Test] public void Timestamp() { // don't run this test on 6 and higher if (Version.Major >= 5 && Version.Minor >= 5) return; execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (id int, dt DATETIME, ts2 TIMESTAMP(2), ts4 TIMESTAMP(4), " + "ts6 TIMESTAMP(6), ts8 TIMESTAMP(8), ts10 TIMESTAMP(10), ts12 TIMESTAMP(12), " + "ts14 TIMESTAMP(14))"); execSQL("INSERT INTO Test (id, dt, ts2, ts4, ts6, ts8, ts10, ts12, ts14) " + "VALUES (1, Now(), Now(), Now(), Now(), Now(), Now(), Now(), Now())"); MySqlDataAdapter da = new MySqlDataAdapter( "SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); DateTime now = (DateTime)dt.Rows[0]["dt"]; Assert.AreEqual( 1, dt.Rows[0]["id"] ); DateTime ts2 = (DateTime)dt.Rows[0]["ts2"]; Assert.AreEqual( now.Year, ts2.Year ); DateTime ts4 = (DateTime)dt.Rows[0]["ts4"]; Assert.AreEqual( now.Year, ts4.Year ); Assert.AreEqual( now.Month, ts4.Month ); DateTime ts6 = (DateTime)dt.Rows[0]["ts6"]; Assert.AreEqual( now.Year, ts6.Year ); Assert.AreEqual( now.Month, ts6.Month ); Assert.AreEqual( now.Day, ts6.Day ); DateTime ts8 = (DateTime)dt.Rows[0]["ts8"]; Assert.AreEqual( now.Year, ts8.Year ); Assert.AreEqual( now.Month, ts8.Month ); Assert.AreEqual( now.Day, ts8.Day ); DateTime ts10 = (DateTime)dt.Rows[0]["ts10"]; Assert.AreEqual( now.Year, ts10.Year ); Assert.AreEqual( now.Month, ts10.Month ); Assert.AreEqual( now.Day, ts10.Day ); Assert.AreEqual( now.Hour, ts10.Hour ); Assert.AreEqual( now.Minute, ts10.Minute ); DateTime ts12 = (DateTime)dt.Rows[0]["ts12"]; Assert.AreEqual( now.Year, ts12.Year ); Assert.AreEqual( now.Month, ts12.Month ); Assert.AreEqual( now.Day, ts12.Day ); Assert.AreEqual( now.Hour, ts12.Hour ); Assert.AreEqual( now.Minute, ts12.Minute ); Assert.AreEqual( now.Second, ts12.Second ); DateTime ts14 = (DateTime)dt.Rows[0]["ts14"]; Assert.AreEqual( now.Year, ts14.Year ); Assert.AreEqual( now.Month, ts14.Month ); Assert.AreEqual( now.Day, ts14.Day ); Assert.AreEqual( now.Hour, ts14.Hour ); Assert.AreEqual( now.Minute, ts14.Minute ); Assert.AreEqual( now.Second, ts14.Second ); } [Test] public void AggregateTypesTest() { execSQL("CREATE TABLE foo (abigint bigint, aint int)"); execSQL("INSERT INTO foo VALUES (1, 2)"); execSQL("INSERT INTO foo VALUES (2, 3)"); execSQL("INSERT INTO foo VALUES (3, 4)"); execSQL("INSERT INTO foo VALUES (3, 5)"); // Try a normal query string NORMAL_QRY = "SELECT abigint, aint FROM foo WHERE abigint = {0}"; string qry = String.Format(NORMAL_QRY, 3); MySqlCommand cmd = new MySqlCommand(qry, conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { reader.GetInt64(0); reader.GetInt32(1); // <--- aint... this succeeds } } cmd.CommandText = "SELECT abigint, max(aint) FROM foo GROUP BY abigint"; using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { reader.GetInt64(0); reader.GetInt64(1); // <--- max(aint)... this fails } } } /* [Test] public void TypeBoundaries() { execSQL("CREATE TABLE Test ( MaxDouble DOUBLE, MinDouble DOUBLE, MaxFloat FLOAT, MinFloat FLOAT )"); MySqlCommand cmd = new MySqlCommand( "INSERT Test (MaxDouble, MinDouble, MaxFloat, MinFloat) VALUES " + "(?maxDouble, ?minDouble, ?maxFloat, ?minFloat)", conn); cmd.Parameters.Add("?maxDouble", MySqlDouble.MaxValue); cmd.Parameters.Add("?minDouble", MySqlDouble.MinValue); cmd.Parameters.Add("?maxFloat", MySqlFloat.MaxValue); cmd.Parameters.Add("?minFloat", MySqlFloat.MinValue); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual(MySqlDouble.MaxValue, reader.GetDouble(0)); Assert.AreEqual(MySqlDouble.MinValue, reader.GetDouble(1)); Assert.AreEqual(MySqlFloat.MaxValue, reader.GetFloat(2)); Assert.AreEqual(MySqlFloat.MinValue, reader.GetFloat(3)); } }*/ [Test] public void BitAndDecimal() { execSQL("CREATE TABLE Test (bt1 BIT(2), bt4 BIT(4), bt11 BIT(11), bt23 BIT(23), bt32 BIT(32)) engine=myisam"); execSQL("INSERT INTO Test VALUES (2, 3, 120, 240, 1000)"); execSQL("INSERT INTO Test VALUES (NULL, NULL, 100, NULL, NULL)"); string connStr = GetConnectionString(true) + ";treat tiny as boolean=false"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", c); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(2, reader.GetInt32(0)); Assert.AreEqual(3, reader.GetInt32(1)); Assert.AreEqual(120, reader.GetInt32(2)); if (Version >= new Version(5, 0)) { Assert.AreEqual(240, reader.GetInt32(3)); Assert.AreEqual(1000, reader.GetInt32(4)); } else { Assert.AreEqual(127, reader.GetInt32(3)); Assert.AreEqual(127, reader.GetInt32(4)); } Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.IsDBNull(0)); Assert.IsTrue(reader.IsDBNull(1)); Assert.AreEqual(100, reader.GetInt32(2)); Assert.IsTrue(reader.IsDBNull(3)); Assert.IsTrue(reader.IsDBNull(4)); } } } /// /// Bug #10486 MySqlDataAdapter.Update error for decimal column /// [Test] public void UpdateDecimalColumns() { execSQL("CREATE TABLE Test (id int not null auto_increment primary key, " + "dec1 decimal(10,1))"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataTable dt = new DataTable(); da.Fill(dt); DataRow row = dt.NewRow(); row["id"] = DBNull.Value; row["dec1"] = 23.4; dt.Rows.Add(row); da.Update(dt); dt.Clear(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(1, dt.Rows[0]["id"]); Assert.AreEqual(23.4, dt.Rows[0]["dec1"]); cb.Dispose(); } [Test] public void DecimalTests() { execSQL("CREATE TABLE Test (val decimal(10,1))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(?dec)", conn); cmd.Parameters.AddWithValue("?dec", (decimal)2.4); Assert.AreEqual(1, cmd.ExecuteNonQuery()); cmd.Prepare(); Assert.AreEqual(1, cmd.ExecuteNonQuery()); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.IsTrue(reader[0] is Decimal); Assert.AreEqual(2.4, reader[0]); Assert.IsTrue(reader.Read()); Assert.IsTrue(reader[0] is Decimal); Assert.AreEqual(2.4, reader[0]); Assert.IsFalse(reader.Read()); Assert.IsFalse(reader.NextResult()); } } [Test] public void DecimalTests2() { execSQL("CREATE TABLE Test (val decimal(10,1))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(?dec)", conn); cmd.Parameters.AddWithValue("?dec", (decimal)2.4); Assert.AreEqual(1, cmd.ExecuteNonQuery()); cmd.Prepare(); Assert.AreEqual(1, cmd.ExecuteNonQuery()); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.IsTrue(reader[0] is Decimal); Assert.AreEqual(2.4, reader[0]); Assert.IsTrue(reader.Read()); Assert.IsTrue(reader[0] is Decimal); Assert.AreEqual(2.4, reader[0]); Assert.IsFalse(reader.Read()); Assert.IsFalse(reader.NextResult()); } } [Test] public void Bit() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE Test (bit1 BIT, bit2 BIT(5), bit3 BIT(10))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?b1, ?b2, ?b3)", conn); cmd.Parameters.Add(new MySqlParameter("?b1", MySqlDbType.Bit)); cmd.Parameters.Add(new MySqlParameter("?b2", MySqlDbType.Bit)); cmd.Parameters.Add(new MySqlParameter("?b3", MySqlDbType.Bit)); cmd.Prepare(); cmd.Parameters[0].Value = 1; cmd.Parameters[1].Value = 2; cmd.Parameters[2].Value = 3; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(1, reader[0]); Assert.AreEqual(2, reader[1]); Assert.AreEqual(3, reader[2]); } } /// /// Bug #17375 CommandBuilder ignores Unsigned flag at Parameter creation /// Bug #15274 Use MySqlDbType.UInt32, throwed exception 'Only byte arrays can be serialize' /// [Test] public void UnsignedTypes() { execSQL("CREATE TABLE Test (b TINYINT UNSIGNED PRIMARY KEY)"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataTable dt = new DataTable(); da.Fill(dt); DataView dv = new DataView(dt); DataRowView row; row = dv.AddNew(); row["b"] = 120; row.EndEdit(); da.Update(dv.Table); row = dv.AddNew(); row["b"] = 135; row.EndEdit(); da.Update(dv.Table); cb.Dispose(); execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (b MEDIUMINT UNSIGNED PRIMARY KEY)"); execSQL("INSERT INTO Test VALUES(20)"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test WHERE (b > ?id)", conn); cmd.Parameters.Add("?id", MySqlDbType.UInt16).Value = 10; using (MySqlDataReader dr = cmd.ExecuteReader()) { dr.Read(); Assert.AreEqual(20, dr.GetUInt16(0)); } } /// /// Bug #25912 selecting negative time values gets wrong results /// [Test] public void TestNegativeTime() { execSQL("CREATE TABLE Test (t time)"); execSQL("INSERT INTO Test SET T='-07:24:00'"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); TimeSpan ts = (TimeSpan)dt.Rows[0]["t"]; Assert.AreEqual(-7, ts.Hours); Assert.AreEqual(-24, ts.Minutes); Assert.AreEqual(0, ts.Seconds); } /// /// Bug #25605 BINARY and VARBINARY is returned as a string /// [Test] public void BinaryAndVarBinary() { MySqlCommand cmd = new MySqlCommand("SELECT BINARY 'something' AS BinaryData", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); byte[] buffer = new byte[2]; long read = reader.GetBytes(0, 0, buffer, 0, 2); Assert.AreEqual('s', buffer[0]); Assert.AreEqual('o', buffer[1]); Assert.AreEqual(2, read); string s = reader.GetString(0); Assert.AreEqual("something", s); } } [Test] public void NumericAsBinary() { MySqlCommand cmd = new MySqlCommand("SELECT IFNULL(NULL,0) AS MyServerID", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("BIGINT", reader.GetDataTypeName(0)); Assert.AreEqual(typeof(Int64), reader.GetFieldType(0)); Assert.AreEqual("System.Int64", reader.GetValue(0).GetType().FullName); Assert.AreEqual(0, reader.GetValue(0)); } } [Test] public void BinaryTypes() { execSQL(@"CREATE TABLE Test (c1 VARCHAR(20), c2 VARBINARY(20), c3 TEXT, c4 BLOB, c6 VARCHAR(20) CHARACTER SET BINARY)"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(typeof(String), dt.Columns[0].DataType); Assert.AreEqual(typeof(byte[]), dt.Columns[1].DataType); Assert.AreEqual(typeof(String), dt.Columns[2].DataType); Assert.AreEqual(typeof(byte[]), dt.Columns[3].DataType); Assert.AreEqual(typeof(byte[]), dt.Columns[4].DataType); } [Test] public void ShowColumns() { if (Version < new Version(5, 0)) return; MySqlDataAdapter da = new MySqlDataAdapter( @"SELECT TRIM(TRAILING ' unsigned' FROM TRIM(TRAILING ' zerofill' FROM COLUMN_TYPE)) AS MYSQL_TYPE, IF(COLUMN_DEFAULT IS NULL, NULL, IF(ASCII(COLUMN_DEFAULT) = 1 OR COLUMN_DEFAULT = '1', 1, 0)) AS TRUE_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='test' AND TABLE_NAME='test'", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(typeof(string), dt.Columns[0].DataType); Assert.AreEqual(typeof(Int64), dt.Columns[1].DataType); } [Test] public void RespectBinaryFlag() { execSQL("CREATE TABLE Test (col1 VARBINARY(20), col2 BLOB)"); string connStr = GetConnectionString(true) + ";respect binary flags=false"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", c); DataTable dt = new DataTable(); da.Fill(dt); Assert.IsTrue(dt.Columns[0].DataType == typeof(System.String)); Assert.IsTrue(dt.Columns[1].DataType == typeof(System.Byte[])); } } /// /// Bug #27959 Bool datatype is not returned as System.Boolean by MySqlDataAdapter /// [Test] public void Boolean() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE Test (id INT, `on` BOOLEAN, v TINYINT(2))"); execSQL("INSERT INTO Test VALUES (1,1,1), (2,0,0)"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(typeof(Boolean), dt.Columns[1].DataType); Assert.AreEqual(typeof(SByte), dt.Columns[2].DataType); Assert.AreEqual(true, dt.Rows[0][1]); Assert.AreEqual(false, dt.Rows[1][1]); Assert.AreEqual(1, dt.Rows[0][2]); Assert.AreEqual(0, dt.Rows[1][2]); } [Test] public void Binary16AsGuid() { if (Version < new Version(5, 0)) return; execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (id INT, g BINARY(16), c VARBINARY(16), c1 BINARY(255))"); string connStr = GetConnectionString(true) + ";old guids=true"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); Guid g = Guid.NewGuid(); byte[] bytes = g.ToByteArray(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (1, @g, @c, @c1)", c); cmd.Parameters.AddWithValue("@g", bytes); cmd.Parameters.AddWithValue("@c", bytes); cmd.Parameters.AddWithValue("@c1", g.ToString()); cmd.ExecuteNonQuery(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", c); DataTable dt = new DataTable(); da.Fill(dt); Assert.IsTrue(dt.Rows[0][1] is Guid); Assert.IsTrue(dt.Rows[0][2] is byte[]); Assert.IsTrue(dt.Rows[0][3] is byte[]); Assert.AreEqual(g, dt.Rows[0][1]); string s = BitConverter.ToString(bytes); s = s.Replace("-", ""); string sql = String.Format("TRUNCATE TABLE Test;INSERT INTO Test VALUES(1,0x{0},NULL,NULL)", s); execSQL(sql); cmd.CommandText = "SELECT * FROM Test"; cmd.Parameters.Clear(); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Guid g1 = reader.GetGuid(1); Assert.AreEqual(g, g1); } } } /// /// Bug #35041 'Binary(16) as GUID' - columns lose IsGuid value after a NULL value found /// [Test] public void Binary16AsGuidWithNull() { execSQL(@"CREATE TABLE Test (id int(10) NOT NULL AUTO_INCREMENT, AGUID binary(16), PRIMARY KEY (id))"); Guid g = new Guid(); byte[] guid = g.ToByteArray(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (NULL, @g)", conn); cmd.Parameters.AddWithValue("@g", guid); cmd.ExecuteNonQuery(); execSQL("insert into Test (AGUID) values (NULL)"); cmd.ExecuteNonQuery(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); } /// /// Bug #36313 BIT result is lost in the left outer join /// [Test] public void BitInLeftOuterJoin() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE TABLE Main (Id int(10) unsigned NOT NULL AUTO_INCREMENT, Descr varchar(45) NOT NULL, PRIMARY KEY (`Id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1"); execSQL(@"INSERT INTO Main (Id,Descr) VALUES (1,'AAA'), (2,'BBB'), (3, 'CCC')"); execSQL(@"CREATE TABLE Child (Id int(10) unsigned NOT NULL AUTO_INCREMENT, MainId int(10) unsigned NOT NULL, Value int(10) unsigned NOT NULL, Enabled bit(1) NOT NULL, PRIMARY KEY (`Id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1"); execSQL(@"INSERT INTO Child (Id, MainId, Value, Enabled) VALUES (1,2,12345,0x01)"); MySqlDataAdapter da = new MySqlDataAdapter( @"SELECT m.Descr, c.Value, c.Enabled FROM Main m LEFT OUTER JOIN Child c ON m.Id=c.MainId ORDER BY m.Descr", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(3, dt.Rows.Count); Assert.AreEqual("AAA", dt.Rows[0][0]); Assert.AreEqual("BBB", dt.Rows[1][0]); Assert.AreEqual("CCC", dt.Rows[2][0]); Assert.AreEqual(DBNull.Value, dt.Rows[0][1]); Assert.AreEqual(12345, dt.Rows[1][1]); Assert.AreEqual(DBNull.Value, dt.Rows[2][1]); Assert.AreEqual(DBNull.Value, dt.Rows[0][2]); Assert.AreEqual(1, dt.Rows[1][2]); Assert.AreEqual(DBNull.Value, dt.Rows[2][2]); } /// /// Bug #36081 Get Unknown Datatype in C# .Net /// [Test] public void GeometryType() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE TABLE Test (ID int(11) NOT NULL, ogc_geom geometry NOT NULL, PRIMARY KEY (`ID`))"); execSQL(@"INSERT INTO Test VALUES (1, GeomFromText('GeometryCollection(Point(1 1), LineString(2 2, 3 3))'))"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); } } /// /// Bug #33322 Incorrect Double/Single value saved to MySQL database using MySQL Connector for /// [Test] public void StoringAndRetrievingDouble() { if (version.Major < 5) return; execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (v DOUBLE(25,20) NOT NULL)"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?v)", conn); cmd.Parameters.Add("?v", MySqlDbType.Double); cmd.Parameters[0].Value = Math.PI; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); double d = reader.GetDouble(0); Assert.AreEqual(Math.PI, d); } } /// /// Bug #40571 Add GetSByte to the list of public methods supported by MySqlDataReader /// [Test] public void SByteFromReader() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (c1 TINYINT, c2 TINYINT UNSIGNED)"); execSQL("INSERT INTO Test VALUES (99, 217)"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual(99, reader.GetSByte(0)); Assert.AreEqual(217, reader.GetByte(1)); Assert.AreEqual(99, reader.GetByte(0)); } } [Test] public void NewGuidDataType() { execSQL("CREATE TABLE Test(id INT, g BINARY(16))"); string connStr = GetConnectionString(true) + ";old guids=true"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); Guid guid = Guid.NewGuid(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(1, @g)", c); cmd.Parameters.Add(new MySqlParameter("@g", MySqlDbType.Guid)); cmd.Parameters[0].Value = guid; cmd.ExecuteNonQuery(); DataTable dt = new DataTable(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", c); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(1, dt.Rows[0]["id"]); Assert.AreEqual(guid, dt.Rows[0]["g"]); } } /// /// Bug #44507 Binary(16) considered as Guid /// [Test] public void ReadBinary16AsBinary() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (id INT, guid BINARY(16))"); string connStr = GetConnectionString(true) + ";old guids=true"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); Guid g = new Guid("32A48AC5-285A-46c6-A0D4-158E6E39729C"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (1, ?guid)", c); //MySqlParameter p = new MySqlParameter(); //p.ParameterName = "guid"; //p.Value = Guid.NewGuid(); cmd.Parameters.AddWithValue("guid", Guid.NewGuid()); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; cmd.Parameters.Clear(); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); object o = reader.GetValue(1); Assert.IsTrue(o is Guid); byte[] bytes = new byte[16]; long size = reader.GetBytes(1, 0, bytes, 0, 16); Assert.AreEqual(16, size); } } } [Test] public void ReadingUUIDAsGuid() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (id INT, guid CHAR(36))"); execSQL("INSERT INTO Test VALUES (1, UUID())"); MySqlCommand cmd = new MySqlCommand("SELECT CONCAT('A', guid) FROM Test", conn); string serverGuidStr = cmd.ExecuteScalar().ToString().Substring(1); Guid serverGuid = new Guid(serverGuidStr); cmd.CommandText = "SELECT guid FROM Test"; Guid g = (Guid)cmd.ExecuteScalar(); Assert.AreEqual(serverGuid, g); } [Test] public void NewGuidType() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (id INT, guid CHAR(36))"); Guid g = Guid.NewGuid(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(1, @g)", conn); cmd.Parameters.AddWithValue("@g", g); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT guid FROM Test"; Guid readG = (Guid)cmd.ExecuteScalar(); Assert.AreEqual(g, readG); } /// /// Bug #47928 Old Guids=true setting is lost after null value is /// encountered in a Binary(16) /// [Test] public void OldGuidsWithNull() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (id INT, guid BINARY(16))"); string connStr = GetConnectionString(true) + ";old guids=true"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (1, ?guid)", c); cmd.Parameters.AddWithValue("guid", Guid.NewGuid()); cmd.ExecuteNonQuery(); cmd.Parameters["guid"].Value = null; cmd.ExecuteNonQuery(); cmd.Parameters["guid"].Value = Guid.NewGuid(); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT guid FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { //In Bug #47928, following loop will crash after encountering // null value. while (reader.Read()) { object o = reader.GetValue(0); } } } } /// /// Bug #47985 UTF-8 String Length Issue (guids etc) /// [Test] public void UTF8Char12AsGuid() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (id INT, name CHAR(12) CHARSET utf8)"); execSQL("INSERT INTO Test VALUES (1, 'Name')"); string connStr = GetConnectionString(true) + ";charset=utf8"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", c); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string s = reader.GetString(1); Assert.AreEqual("Name", s); } } } /// /// Bug #48100 Impossible to retrieve decimal value if it doesn't fit into .Net System.Decimal /// [Test] public void MySqlDecimal() { if (Version < new Version(5, 0)) return; execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test (id INT, dec1 DECIMAL(36,2))"); execSQL("INSERT INTO Test VALUES (1, 9999999999999999999999999999999999.99)"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); MySqlDecimal dec = reader.GetMySqlDecimal(1); string s = dec.ToString(); Assert.AreEqual(9999999999999999999999999999999999.99, dec.ToDouble()); Assert.AreEqual("9999999999999999999999999999999999.99", dec.ToString()); try { decimal d = dec.Value; Assert.Fail("this should have failed"); } catch (Exception) { } } } /// /// Bug #48171 MySqlDataReader.GetSchemaTable() returns 0 in "NumericPrecision" for newdecimal /// [Test] public void DecimalPrecision() { execSQL("DROP TABLE IF EXISTS test"); execSQL("CREATE TABLE test(a decimal(35,2), b decimal(36,2), c decimal(36,2) unsigned)"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { DataTable dt = reader.GetSchemaTable(); DataRow columnDefinition = dt.Rows[0]; Assert.AreEqual(35, columnDefinition[SchemaTableColumn.NumericPrecision]); columnDefinition = dt.Rows[1]; Assert.AreEqual(36, columnDefinition[SchemaTableColumn.NumericPrecision]); columnDefinition = dt.Rows[2]; Assert.AreEqual(36, columnDefinition[SchemaTableColumn.NumericPrecision]); } } /// /// Bug #55644 Value was either too large or too small for a Double /// [Test] public void DoubleMinValue() { execSQL("DROP TABLE IF EXISTS test"); execSQL("CREATE TABLE test(dbl double)"); MySqlCommand cmd = new MySqlCommand("insert into test values(?param1)"); cmd.Connection = conn; cmd.Parameters.Add(new MySqlParameter("?param1", MySqlDbType.Double)); cmd.Parameters["?param1"].Value = Double.MinValue; cmd.ExecuteNonQuery(); cmd.Parameters["?param1"].Value = Double.MaxValue; cmd.ExecuteNonQuery(); cmd = new MySqlCommand("SELECT * FROM test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); double d = reader.GetDouble(0); Assert.AreEqual(d, double.MinValue); reader.Read(); d = reader.GetDouble(0); Assert.AreEqual(d, double.MaxValue); } } /// /// Bug #58373 ReadInteger problem /// [Test] public void BigIntAutoInc() { execSQL("DROP TABLE IF EXISTS test"); execSQL("CREATE TABLE test(ID bigint unsigned AUTO_INCREMENT NOT NULL PRIMARY KEY, name VARCHAR(20))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO test VALUES (@id, 'boo')", conn); ulong val = UInt64.MaxValue; val -= 100; cmd.Parameters.AddWithValue("@id", val); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO test (name) VALUES ('boo2')"; cmd.ExecuteNonQuery(); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/Syntax.cs0000644000175000017500000005207711127003600024123 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using NUnit.Framework; using System.Collections; using System.Collections.Generic; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class Syntax : BaseTest { [Test] public void ShowCreateTable() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); MySqlDataAdapter da = new MySqlDataAdapter("SHOW CREATE TABLE Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(2, dt.Columns.Count); } [Test] public void ProblemCharsInSQLUTF8() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), mt MEDIUMTEXT, " + "PRIMARY KEY(id)) CHAR SET utf8"); using (MySqlConnection c = new MySqlConnection(GetConnectionString(true) + ";charset=utf8")) { c.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?text, ?mt)", c); cmd.Parameters.AddWithValue("?id", 1); cmd.Parameters.AddWithValue("?text", "This is my;test ? string"); cmd.Parameters.AddWithValue("?mt", "My MT string: ?"); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(1, reader.GetInt32(0)); Assert.AreEqual("This is my;test ? string", reader.GetString(1)); Assert.AreEqual("My MT string: ?", reader.GetString(2)); } } } [Test] public void ProblemCharsInSQL() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), mt MEDIUMTEXT, " + "PRIMARY KEY(id))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?text, ?mt)", conn); cmd.Parameters.AddWithValue("?id", 1); cmd.Parameters.AddWithValue("?text", "This is my;test ? string-'''\"\"."); cmd.Parameters.AddWithValue("?mt", "My MT string: ?"); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(1, reader.GetInt32(0)); Assert.AreEqual("This is my;test ? string-'''\"\".", reader.GetString(1)); Assert.AreEqual("My MT string: ?", reader.GetString(2)); } } [Test] public void LoadDataLocalInfile() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); string connString = conn.ConnectionString + ";pooling=false"; MySqlConnection c = new MySqlConnection(connString); c.Open(); string path = Path.GetTempFileName(); StreamWriter sw = new StreamWriter(path); for (int i = 0; i < 2000000; i++) sw.WriteLine(i + ",'Test'"); sw.Flush(); sw.Close(); path = path.Replace(@"\", @"\\"); MySqlCommand cmd = new MySqlCommand( "LOAD DATA LOCAL INFILE '" + path + "' INTO TABLE Test FIELDS TERMINATED BY ','", conn); cmd.CommandTimeout = 0; object cnt = 0; cnt = cmd.ExecuteNonQuery(); Assert.AreEqual(2000000, cnt); cmd.CommandText = "SELECT COUNT(*) FROM Test"; cnt = cmd.ExecuteScalar(); Assert.AreEqual(2000000, cnt); c.Close(); } [Test] public void ShowTablesInNonExistentDb() { MySqlCommand cmd = new MySqlCommand("SHOW TABLES FROM dummy", conn); try { using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.Fail("ExecuteReader should not succeed"); } } catch (MySqlException) { Assert.AreEqual(ConnectionState.Open, conn.State); } } [Test] public void Bug6135() { string sql = @"CREATE TABLE `KLANT` (`KlantNummer` int(11) NOT NULL auto_increment, `Username` varchar(50) NOT NULL default '', `Password` varchar(100) NOT NULL default '', `Naam` varchar(100) NOT NULL default '', `Voornaam` varchar(100) NOT NULL default '', `Straat` varchar(100) NOT NULL default '', `StraatNr` varchar(10) NOT NULL default '', `Gemeente` varchar(100) NOT NULL default '', `Postcode` varchar(10) NOT NULL default '', `DefaultMail` varchar(255) default '', `BtwNr` varchar(50) default '', `ReceiveMail` tinyint(1) NOT NULL default '0', `Online` tinyint(1) NOT NULL default '0', `LastVisit` timestamp NOT NULL, `Categorie` int(11) NOT NULL default '0', PRIMARY KEY (`KlantNummer`), UNIQUE KEY `UniqueUsername` (`Username`), UNIQUE KEY `UniqueDefaultMail` (`DefaultMail`) )"; createTable(sql, "MyISAM"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM KLANT", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { } } } [Test] public void Sum() { execSQL("CREATE TABLE Test (field1 mediumint(9) default '0', field2 float(9,3) " + "default '0.000', field3 double(15,3) default '0.000') engine=innodb "); execSQL("INSERT INTO Test values (1,1,1)"); MySqlCommand cmd2 = new MySqlCommand("SELECT sum(field2) FROM Test", conn); using (MySqlDataReader reader = cmd2.ExecuteReader()) { reader.Read(); object o = reader[0]; Assert.AreEqual(1, o); } } [Test] public void Sum2() { execSQL("CREATE TABLE Test (id int, count int)"); execSQL("INSERT INTO Test VALUES (1, 21)"); execSQL("INSERT INTO Test VALUES (1, 33)"); execSQL("INSERT INTO Test VALUES (1, 16)"); execSQL("INSERT INTO Test VALUES (1, 40)"); MySqlCommand cmd = new MySqlCommand("SELECT id, SUM(count) FROM Test GROUP BY id", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual( 1, reader.GetInt32(0) ); Assert.AreEqual( 110, reader.GetDouble(1) ); } } [Test] public void ForceWarnings() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); MySqlCommand cmd = new MySqlCommand( "SELECT * FROM Test; DROP TABLE IF EXISTS test2; SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.NextResult()) { } } } [Test] public void SettingAutoIncrementColumns() { execSQL("CREATE TABLE Test (id int auto_increment, name varchar(100), primary key(id))"); execSQL("INSERT INTO Test VALUES (1, 'One')"); execSQL("INSERT INTO Test VALUES (3, 'Two')"); MySqlCommand cmd = new MySqlCommand("SELECT name FROM Test WHERE id=1", conn); object name = cmd.ExecuteScalar(); Assert.AreEqual( "One", name ); cmd.CommandText = "SELECT name FROM Test WHERE id=3"; name = cmd.ExecuteScalar(); Assert.AreEqual( "Two", name ); try { execSQL("INSERT INTO Test (id, name2) values (5, 'Three')"); Assert.Fail( "This should have failed" ); } catch (MySqlException) { } } /// /// Bug #16645 FOUND_ROWS() Bug /// [Test] public void FoundRows() { execSQL("CREATE TABLE Test (testID int(11) NOT NULL auto_increment, testName varchar(100) default '', " + "PRIMARY KEY (testID)) ENGINE=InnoDB DEFAULT CHARSET=latin1"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (NULL, 'test')", conn); for (int i=0; i < 1000; i++) cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT SQL_CALC_FOUND_ROWS * FROM Test LIMIT 0, 10"; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT FOUND_ROWS()"; object cnt = cmd.ExecuteScalar(); Assert.AreEqual(1000, cnt); } [Test] public void AutoIncrement() { execSQL("CREATE TABLE Test (testID int(11) NOT NULL auto_increment, testName varchar(100) default '', " + "PRIMARY KEY (testID)) ENGINE=InnoDB DEFAULT CHARSET=latin1"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (NULL, 'test')", conn); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT @@IDENTITY as 'Identity'"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); int ident = Int32.Parse(reader.GetValue(0).ToString()); Assert.AreEqual(1, ident); } } /// /// Bug #21521 # Symbols not allowed in column/table names. /// [Test] public void CommentSymbolInTableName() { execSQL("CREATE TABLE Test (`PO#` int(11) NOT NULL auto_increment, " + "`PODate` date default NULL, PRIMARY KEY (`PO#`))"); execSQL("INSERT INTO Test ( `PO#`, `PODate` ) " + "VALUES ( NULL, '2006-01-01' )"); string sql = "SELECT `PO#` AS PurchaseOrderNumber, " + "`PODate` AS OrderDate FROM Test"; MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataAdapter da = new MySqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); } /// /// Bug #25178 Addition message in error /// [Test] public void ErrorMessage() { MySqlCommand cmd = new MySqlCommand("SELEKT NOW() as theTime", conn); try { cmd.ExecuteScalar(); } catch (MySqlException ex) { string s = ex.Message; Assert.IsFalse(s.StartsWith("#")); } } /// /// Bug #27221 describe SQL command returns all byte array on MySQL versions older than 4.1.15 /// [Test] public void Describe() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); MySqlDataAdapter da = new MySqlDataAdapter("DESCRIBE Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.IsTrue(dt.Columns[0].DataType == typeof(string)); Assert.IsTrue(dt.Columns[1].DataType == typeof(string)); Assert.IsTrue(dt.Columns[2].DataType == typeof(string)); Assert.IsTrue(dt.Columns[3].DataType == typeof(string)); Assert.IsTrue(dt.Columns[4].DataType == typeof(string)); Assert.IsTrue(dt.Columns[5].DataType == typeof(string)); } [Test] public void ShowTableStatus() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); MySqlDataAdapter da = new MySqlDataAdapter( String.Format("SHOW TABLE STATUS FROM `{0}` LIKE 'Test'", database0), conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.IsTrue(dt.Rows[0][0].GetType() == typeof(string)); } /// /// Bug #26960 Connector .NET 5.0.5 / Visual Studio Plugin 1.1.2 /// [Test] public void NullAsAType() { MySqlDataAdapter da = new MySqlDataAdapter( @"SELECT 'localhost' as SERVER_NAME, null as CATALOG_NAME, database() as SCHEMA_NAME", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.IsTrue(dt.Rows[0][0].GetType() == typeof(string)); Assert.AreEqual(DBNull.Value, dt.Rows[0][1]); Assert.IsTrue(dt.Rows[0][2].GetType() == typeof(string)); } [Test] public void SpaceInDatabaseName() { string dbName = System.IO.Path.GetFileNameWithoutExtension( System.IO.Path.GetTempFileName()) + " x"; try { suExecSQL(String.Format("CREATE DATABASE `{0}`", dbName)); suExecSQL(String.Format("GRANT ALL ON `{0}`.* to 'test'@'localhost' identified by 'test'", dbName)); suExecSQL(String.Format("GRANT ALL ON `{0}`.* to 'test'@'%' identified by 'test'", dbName)); suExecSQL("FLUSH PRIVILEGES"); string connStr = GetConnectionString(false) + ";database=" + dbName; MySqlConnection c = new MySqlConnection(connStr); c.Open(); c.Close(); } finally { suExecSQL(String.Format("DROP DATABASE `{0}`", dbName)); } } /// /// Bug #28448 show processlist; returns byte arrays in the resulting data table /// [Test] public void ShowProcessList() { string connStr = GetConnectionString(true) + ";respect binary flags=false;"; MySqlConnection c = new MySqlConnection(connStr); using (c) { c.Open(); MySqlCommand cmd = new MySqlCommand("show processlist", c); DataTable dt = new DataTable(); using (MySqlDataReader rdr = cmd.ExecuteReader()) { dt.Load(rdr); } DataRow row = dt.Rows[0]; Assert.IsTrue(row["User"].GetType().Name == "String"); Assert.IsTrue(row["Host"].GetType().Name == "String"); Assert.IsTrue(row["Command"].GetType().Name == "String"); } } [Test] public void SemisAtStartAndEnd() { using (MySqlCommand cmd = new MySqlCommand(";;SELECT 1;;;", conn)) { Assert.AreEqual(1, cmd.ExecuteScalar()); } } /// /// Bug #51610 Exception thrown inside Connector.NET /// [Test] public void Bug51610() { MySqlCommand cmd = new MySqlCommand("SELECT 'ABC', (0/`QOH`) from (SELECT 1 as `QOH`) `d1`", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("ABC", reader.GetString(0)); Assert.AreEqual(0, reader.GetInt32(1)); } cmd.CommandText = "SELECT 'ABC', (0-`QOH`) from (SELECT 1 as `QOH`) `d1`"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("ABC", reader.GetString(0)); Assert.AreEqual(-1, reader.GetInt32(1)); } cmd.CommandText = "SELECT 'test 2010-03-04 @ 10:14'"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("test 2010-03-04 @ 10:14", reader.GetString(0)); } } /// /// Bug #54386 : expression with parentheses in INSERT leads to invalid /// query when using batching /// [Test] public void TokenizerBatching() { execSQL("CREATE TABLE Test (id INT, expr INT,name VARCHAR(20), PRIMARY KEY(id))"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommand ins = new MySqlCommand( "INSERT INTO test (id, expr, name) VALUES(?p1, (?p2 * 2) + 3, ?p3)", conn); da.InsertCommand = ins; ins.UpdatedRowSource = UpdateRowSource.None; ins.Parameters.Add("?p1", MySqlDbType.Int32).SourceColumn = "id"; ins.Parameters.Add("?p2", MySqlDbType.Int32).SourceColumn = "expr"; ins.Parameters.Add("?p3", MySqlDbType.VarChar, 20).SourceColumn = "name"; DataTable dt = new DataTable(); da.Fill(dt); for (int i = 1; i <= 100; i++) { DataRow row = dt.NewRow(); row["id"] = i; row["expr"] = i; row["name"] = "name " + i; dt.Rows.Add(row); } da.UpdateBatchSize = 10; da.Update(dt); } /// /// Bug #51788 Error in SQL syntax not reported. A CLR exception was thrown instead, /// [Test] public void NonTerminatedString() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test(id INT, name1 VARCHAR(20), name2 VARCHAR(20))"); try { MySqlCommand cmd = new MySqlCommand( "INSERT INTO test VALUES (1, 'test 2010-03-04 @ 10:14, name2=' joe')", conn); cmd.ExecuteNonQuery(); } catch (MySqlException) { } } /// /// Bug #53865 : crash in QueryNormalizer, "IN" clause incomplete /// [Test] public void QueryNormalizerCrash1() { execSQL( "CREATE TABLE extable_1 (x_coord int, y_coord int, z_coord int,"+ "edge_id int, life_id int)") ; execSQL("CREATE TABLE extable_2 (daset_id int, sect_id int, "+ "xyz_id int, edge_id int, life_id int, another_id int, yetanother_id int)"); string connStr = GetConnectionString(true) + ";logging=true"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand( "SELECT tblb.x_coord, tblb.y_coord, tblb.z_coord, " + "tbl_c.x_coord, tbl_c.y_coord, tbl_c.z_coord, tbl_a.edge_id, " + "tbl_a.life_id, tbl_a.daset_id, tbl_a.sect_id, tbl_a.yetanother_id," + " IFNULL(tbl_a.xyz_id,0) FROM extable_2 tbl_a, extable_1 tblb, " + "extable_1 tbl_c WHERE tbl_a.daset_id=208 AND tbl_a.sect_id IN "+ "(1,2,3,4,5,6,7)", c); Console.WriteLine(cmd.ExecuteScalar()); } } /// /// Bug #54152 : Crash in QueryNormalizer, VALUES incomplete /// [Test] public void QueryNormalizerCrash2() { execSQL("CREATE TABLE bug54152 (id INT, expr INT,name VARCHAR(20),"+ "fld4 VARCHAR(10), fld5 VARCHAR(10), fld6 VARCHAR(10),"+ "fld7 VARCHAR(10), fld8 VARCHAR(10), fld9 VARCHAR(10),"+ "fld10 VARCHAR(10), PRIMARY KEY(id))"); string connStr = GetConnectionString(true) + ";logging=true"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); string query = "INSERT INTO bug54152 VALUES "+ "(1,1, 'name 1',1,1,1,1,1,1,1)," + "(2,2,'name 2',2,2,2,2,2,2,2)," + "(3,3,'name 3',3,3,3,3,3,3,3)," + "(4,4,'name 4',4,4,4,4,4,4,4)," + "(5,5,'name 5',5,5,5,5,5,5,5)," + "(6,6,'name 6',6,6,6,6,6,6,6)," + "(7,7,'name 7',7,7,7,7,7,7,7)," + "(8,8,'name 8',8,8,8,8,8,8,8)," + "(9,9,'name 9',9,9,9,9,9,9,9)," + "(10,10,'name 10',10,10,10,10,10,10,10)"; MySqlCommand cmd = new MySqlCommand(query, c); cmd.ExecuteNonQuery(); } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/ParameterTests.cs0000644000175000017500000004534111127003600025574 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using NUnit.Framework; using System.Diagnostics; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for ConnectionTests. /// [TestFixture] public class ParameterTests : BaseTest { [SetUp] public override void Setup() { base.Setup(); execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(100), dt DATETIME, tm TIME, ts TIMESTAMP, PRIMARY KEY(id))"); } [Test] public void TestQuoting() { MySqlCommand cmd = new MySqlCommand("", conn); cmd.CommandText = "INSERT INTO Test VALUES (?id, ?name, NULL,NULL,NULL)"; cmd.Parameters.Add( new MySqlParameter("?id", 1)); cmd.Parameters.Add( new MySqlParameter("?name", "my ' value")); cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = 2; cmd.Parameters[1].Value = @"my "" value"; cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = 3; cmd.Parameters[1].Value = @"my ` value"; cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = 4; cmd.Parameters[1].Value = @"my value"; cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = 5; cmd.Parameters[1].Value = @"my \ value"; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; MySqlDataReader reader = null; try { reader = cmd.ExecuteReader(); reader.Read(); Assert.AreEqual( "my ' value", reader.GetString(1)); reader.Read(); Assert.AreEqual( @"my "" value", reader.GetString(1)); reader.Read(); Assert.AreEqual( "my ` value", reader.GetString(1)); reader.Read(); Assert.AreEqual( "my value", reader.GetString(1)); reader.Read(); Assert.AreEqual( @"my \ value", reader.GetString(1)); } catch (Exception ex) { Assert.Fail( ex.Message ); } finally { if (reader != null) reader.Close(); } } [Test] public void TestDateTimeParameter() { MySqlCommand cmd = new MySqlCommand("", conn); TimeSpan time = new TimeSpan(0, 1, 2, 3); DateTime dt = new DateTime( 2003, 11, 11, 1, 2, 3 ); cmd.CommandText = "INSERT INTO Test VALUES (1, 'test', ?dt, ?time, NULL)"; cmd.Parameters.Add( new MySqlParameter("?time", time)); cmd.Parameters.Add( new MySqlParameter("?dt", dt)); int cnt = cmd.ExecuteNonQuery(); Assert.AreEqual( 1, cnt, "Insert count" ); cmd = new MySqlCommand("SELECT tm, dt, ts FROM Test WHERE id=1", conn); MySqlDataReader reader = cmd.ExecuteReader(); reader.Read(); TimeSpan time2 = (TimeSpan)reader.GetValue(0); Assert.AreEqual( time, time2 ); DateTime dt2 = reader.GetDateTime(1); Assert.AreEqual( dt, dt2 ); DateTime ts2 = reader.GetDateTime(2); reader.Close(); // now check the timestamp column. We won't check the minute or second for obvious reasons DateTime now = DateTime.Now; Assert.AreEqual( now.Year, ts2.Year ); Assert.AreEqual( now.Month, ts2.Month ); Assert.AreEqual( now.Day, ts2.Day ); Assert.AreEqual( now.Hour, ts2.Hour ); // now we'll set some nulls and see how they are handled cmd = new MySqlCommand("UPDATE Test SET tm=?ts, dt=?dt WHERE id=1", conn); cmd.Parameters.Add( new MySqlParameter("?ts", DBNull.Value )); cmd.Parameters.Add( new MySqlParameter("?dt", DBNull.Value)); cnt = cmd.ExecuteNonQuery(); Assert.AreEqual( 1, cnt, "Update null count" ); cmd = new MySqlCommand("SELECT tm, dt FROM Test WHERE id=1", conn); reader = cmd.ExecuteReader(); reader.Read(); object tso = reader.GetValue(0); object dto = reader.GetValue(1); Assert.AreEqual( DBNull.Value, tso, "Time column" ); Assert.AreEqual( DBNull.Value, dto, "DateTime column" ); reader.Close(); cmd.CommandText = "DELETE FROM Test WHERE id=1"; cmd.ExecuteNonQuery(); } [Test] public void NestedQuoting() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, name) " + "VALUES(1, 'this is ?\"my value\"')", conn); int count = cmd.ExecuteNonQuery(); Assert.AreEqual(1, count); } [Test] public void SetDbType() { IDbCommand cmd = conn.CreateCommand(); IDbDataParameter prm = cmd.CreateParameter(); prm.DbType = DbType.Int64; Assert.AreEqual(DbType.Int64, prm.DbType); prm.Value = 3; Assert.AreEqual(DbType.Int64, prm.DbType); MySqlParameter p = new MySqlParameter("name", MySqlDbType.Int64); Assert.AreEqual(DbType.Int64, p.DbType); Assert.AreEqual(MySqlDbType.Int64, p.MySqlDbType); p.Value = 3; Assert.AreEqual(DbType.Int64, p.DbType); Assert.AreEqual(MySqlDbType.Int64, p.MySqlDbType); } #if !CF [Test] public void UseOldSyntaxGivesWarning() { Trace.Listeners.Clear(); GenericListener listener = new GenericListener(); Trace.Listeners.Add(listener); string connStr = conn.ConnectionString + ";old syntax=yes;pooling=false"; MySqlConnection conn2 = new MySqlConnection(connStr); conn2.Open(); Assert.IsTrue(listener.Find("Use Old Syntax is now obsolete") != 0); conn2.Close(); Trace.Listeners.Clear(); } #endif [Test] public void NullParameterObject() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, name) VALUES (1, ?name)", conn); try { cmd.Parameters.Add(null); } catch (ArgumentException) { } } /// /// Bug #7398 MySqlParameterCollection doesn't allow parameters without filled in names /// [Test] public void AllowUnnamedParameters() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id,name) VALUES (?id, ?name)", conn); MySqlParameter p = new MySqlParameter(); p.ParameterName = "?id"; p.Value = 1; cmd.Parameters.Add(p); p = new MySqlParameter(); p.ParameterName = "?name"; p.Value = "test"; cmd.Parameters.Add(p); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT id FROM Test"; Assert.AreEqual(1, cmd.ExecuteScalar()); cmd.CommandText = "SELECT name FROM Test"; Assert.AreEqual( "test", cmd.ExecuteScalar()); } [Test] public void NullParameterValue() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, name) VALUES (1, ?name)", conn); cmd.Parameters.Add( new MySqlParameter("?name", null)); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT name FROM Test WHERE id=1"; object name = cmd.ExecuteScalar(); Assert.AreEqual( DBNull.Value, name ); } /// /// Bug #12646 Parameters are defaulted to Decimal /// [Test] public void DefaultType() { IDbCommand cmd = conn.CreateCommand(); IDbDataParameter p = cmd.CreateParameter(); p.ParameterName = "?boo"; p.Value = "test"; MySqlParameter mp = (MySqlParameter)p; Assert.AreEqual(MySqlDbType.VarChar, mp.MySqlDbType); } [Test] public void OddCharsInParameterNames() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, name) VALUES (1, ?nam$es)", conn); cmd.Parameters.Add( new MySqlParameter("?nam$es", "Test")); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO Test (id, name) VALUES (2, ?nam_es)"; cmd.Parameters.Clear(); cmd.Parameters.Add( new MySqlParameter("?nam_es", "Test2")); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO Test (id, name) VALUES (3, ?nam.es)"; cmd.Parameters.Clear(); cmd.Parameters.Add( new MySqlParameter("?nam.es", "Test3")); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT name FROM Test WHERE id=1"; object name = cmd.ExecuteScalar(); Assert.AreEqual( "Test", name ); cmd.CommandText = "SELECT name FROM Test WHERE id=2"; name = cmd.ExecuteScalar(); Assert.AreEqual( "Test2", name ); cmd.CommandText = "SELECT name FROM Test WHERE id=3"; name = cmd.ExecuteScalar(); Assert.AreEqual( "Test3", name ); } /// /// Bug #13276 Exception on serialize after inserting null value /// [Test] public void InsertValueAfterNull() { execSQL("DROP TABLE Test"); execSQL("CREATE TABLE Test (id int auto_increment primary key, foo int)"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommand c = new MySqlCommand("INSERT INTO Test (foo) values (?foo)", conn); c.Parameters.Add("?foo", MySqlDbType.Int32, 0, "foo"); da.InsertCommand = c; DataTable dt = new DataTable(); da.Fill(dt); DataRow row = dt.NewRow(); dt.Rows.Add(row); row = dt.NewRow(); row["foo"] = 2; dt.Rows.Add(row); da.Update(dt); dt.Clear(); da.Fill(dt); Assert.AreEqual(2, dt.Rows.Count); Assert.AreEqual(2, dt.Rows[1]["foo"]); } /// /// Bug #24565 Inferring DbType fails when reusing commands and the first time the value is nul /// [Test] public void UnTypedParameterBeingReused() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, dt) VALUES (?id, ?dt)", conn); cmd.Parameters.AddWithValue("?id", 1); MySqlParameter p = cmd.CreateParameter(); p.ParameterName = "?dt"; p.Value = DBNull.Value; cmd.Parameters.Add(p); cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = 2; p.Value = DateTime.Now; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; cmd.Parameters.Clear(); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.IsTrue(reader.IsDBNull(2)); reader.Read(); Assert.IsFalse(reader.IsDBNull(2)); Assert.IsFalse(reader.Read()); } } [Test] public void ParameterCacheNotClearing() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, name) VALUES (?id, ?name)", conn); cmd.Parameters.AddWithValue("?id", 1); cmd.Parameters.AddWithValue("?name", "test"); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO Test (id, name, dt) VALUES (?id1, ?name1, ?id)"; cmd.Parameters[0].ParameterName = "?id1"; cmd.Parameters[0].Value = 2; cmd.Parameters[1].ParameterName = "?name1"; cmd.Parameters.AddWithValue("?id", DateTime.Now); cmd.ExecuteNonQuery(); } [Test] public void WithAndWithoutMarker() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, name) VALUES (?id, ?name)", conn); cmd.Parameters.AddWithValue("id", 1); Assert.AreEqual(-1, cmd.Parameters.IndexOf("?id")); cmd.Parameters.AddWithValue("name", "test"); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("?id", 2); Assert.AreEqual(-1, cmd.Parameters.IndexOf("id")); cmd.Parameters.AddWithValue("?name", "test2"); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT COUNT(*) FROM Test"; object count = cmd.ExecuteScalar(); Assert.AreEqual(2, count); } [Test] public void DoubleAddingParameters() { try { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, name) VALUES (?id, ?name)", conn); cmd.Parameters.AddWithValue("id", 1); Assert.AreEqual(-1, cmd.Parameters.IndexOf("?id")); Assert.AreEqual(-1, cmd.Parameters.IndexOf("@id")); cmd.Parameters.AddWithValue("name", "test"); cmd.Parameters.AddWithValue("?id", 2); Assert.Fail("Should not get here"); } catch (Exception) { } } /// /// Bug #26904 MySqlParameterCollection fails to add MySqlParameter that previously removed /// [Test] public void AddingParameterPreviouslyRemoved() { MySqlCommand cmd = new MySqlCommand("Insert into sometable(s1, s2) values(?p1, ?p2)"); MySqlParameter param1 = cmd.CreateParameter(); param1.ParameterName = "?p1"; param1.DbType = DbType.String; param1.Value = "Ali Gel"; cmd.Parameters.Add(param1); cmd.Parameters.RemoveAt(0); cmd.Parameters.Add(param1); } /// /// Bug #27135 MySqlParameterCollection and parameters added with Insert Method /// [Test] public void AddingParametersUsingInsert() { MySqlCommand cmd = new MySqlCommand(); cmd.Parameters.Insert(0, new MySqlParameter("?id", MySqlDbType.Int32)); MySqlParameter p = cmd.Parameters["?id"]; Assert.AreEqual("?id", p.ParameterName); } /// /// Bug #27187 cmd.Parameters.RemoveAt("Id") will cause an error if the last item is requested /// [Test] public void FindParameterAfterRemoval() { MySqlCommand cmd = new MySqlCommand(); cmd.Parameters.Add("?id1", MySqlDbType.Int32); cmd.Parameters.Add("?id2", MySqlDbType.Int32); cmd.Parameters.Add("?id3", MySqlDbType.Int32); cmd.Parameters.Add("?id4", MySqlDbType.Int32); cmd.Parameters.Add("?id5", MySqlDbType.Int32); cmd.Parameters.Add("?id6", MySqlDbType.Int32); cmd.Parameters.RemoveAt("?id1"); MySqlParameter p = cmd.Parameters["?id6"]; Assert.AreEqual("?id6", p.ParameterName); } /// /// Bug #29312 System.FormatException if parameter not found /// [Test] public void MissingParameter() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test(id) VALUES (?id)", conn); try { cmd.ExecuteNonQuery(); } catch (MySqlException) { } } /// /// Bug #32094 Size property on string parameter throws an exception /// [Test] public void StringParameterSizeSetAfterValue() { execSQL("DROP TABLE Test"); execSQL("CREATE TABLE Test (v VARCHAR(10))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?p1)", conn); cmd.Parameters.Add("?p1", MySqlDbType.VarChar); cmd.Parameters[0].Value = "123"; cmd.Parameters[0].Size = 10; cmd.ExecuteNonQuery(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual("123", dt.Rows[0][0]); cmd.Parameters.Clear(); cmd.Parameters.Add("?p1", MySqlDbType.VarChar); cmd.Parameters[0].Value = "123456789012345"; cmd.Parameters[0].Size = 10; cmd.ExecuteNonQuery(); dt.Clear(); da.Fill(dt); Assert.AreEqual("1234567890", dt.Rows[1][0]); } /// /// Bug #32093 MySqlParameter Constructor does not allow Direction of anything other than Input /// [Test] public void NonInputParametersToCtor() { MySqlParameter p = new MySqlParameter("?p1", MySqlDbType.VarChar, 20, ParameterDirection.InputOutput, true, 0, 0, "id", DataRowVersion.Current, 0); Assert.AreEqual(ParameterDirection.InputOutput, p.Direction); MySqlParameter p1 = new MySqlParameter("?p1", MySqlDbType.VarChar, 20, ParameterDirection.Output, true, 0, 0, "id", DataRowVersion.Current, 0); Assert.AreEqual(ParameterDirection.Output, p1.Direction); } /// /// Bug #13991 oldsyntax configuration and ParameterMarker value bug /// [Test] public void SetOldSyntaxAfterCommandCreation() { string connStr = this.GetConnectionString(true); MySqlConnection c = new MySqlConnection(connStr); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id) VALUES (@id)", c); c.ConnectionString = connStr += ";old syntax=yes"; cmd.Parameters.AddWithValue("@id", 2); c.Open(); cmd.ExecuteNonQuery(); c.Close(); } [Test] public void UseAtSignForParameters() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, name) VALUES (@id, @name)", conn); cmd.Parameters.AddWithValue("@id", 33); cmd.Parameters.AddWithValue("@name", "Test"); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual(33, reader.GetInt32(0)); Assert.AreEqual("Test", reader.GetString(1)); } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/ConnectionTests.cs0000644000175000017500000007024411127003600025753 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Properties; using NUnit.Framework; using System.Configuration; using System.Security; using System.Security.Permissions; using System.Net; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for ConnectionTests. /// [TestFixture] public class ConnectionTests : BaseTest { [Test] public void TestConnectionStrings() { MySqlConnection c = new MySqlConnection(); // public properties Assert.AreEqual(15, c.ConnectionTimeout, "ConnectionTimeout"); Assert.AreEqual("", c.Database, "Database"); Assert.AreEqual(String.Empty, c.DataSource, "DataSource"); Assert.AreEqual(false, c.UseCompression, "Use Compression"); Assert.AreEqual(System.Data.ConnectionState.Closed, c.State, "State"); c = new MySqlConnection("connection timeout=25; user id=myuser; " + "password=mypass; database=Test;server=myserver; use compression=true; " + "pooling=false;min pool size=5; max pool size=101"); // public properties Assert.AreEqual(25, c.ConnectionTimeout, "ConnectionTimeout"); Assert.AreEqual("Test", c.Database, "Database"); Assert.AreEqual("myserver", c.DataSource, "DataSource"); Assert.AreEqual(true, c.UseCompression, "Use Compression"); Assert.AreEqual(System.Data.ConnectionState.Closed, c.State, "State"); c.ConnectionString = "connection timeout=15; user id=newuser; " + "password=newpass; port=3308; database=mydb; data source=myserver2; " + "use compression=true; pooling=true; min pool size=3; max pool size=76"; // public properties Assert.AreEqual(15, c.ConnectionTimeout, "ConnectionTimeout"); Assert.AreEqual("mydb", c.Database, "Database"); Assert.AreEqual("myserver2", c.DataSource, "DataSource"); Assert.AreEqual(true, c.UseCompression, "Use Compression"); Assert.AreEqual(System.Data.ConnectionState.Closed, c.State, "State"); } #if !CF //No Security.Principal on CF [Test] public void TestIntegratedSecurityNoPooling() { TestIntegratedSecurity(false); } [Test] public void TestIntegratedSecurityPooling() { TestIntegratedSecurity(true); } public void TestIntegratedSecurity(bool pooling) { if (version.Major < 5 && version.Minor < 5) return; const string PluginName = "authentication_windows"; // Check if server has windows authentication plugin is installed MySqlCommand cmd = new MySqlCommand("show plugins", rootConn); bool haveWindowsAuthentication = false; using (MySqlDataReader r = cmd.ExecuteReader()) { while (r.Read()) { string name = (string)r["Name"]; if (name == PluginName) { haveWindowsAuthentication = true; break; } } } if(!haveWindowsAuthentication) return; bool haveAuthWindowsUser = false; string pluginName = null; string authenticationString = ""; // Check if predefined proxy user exists cmd.CommandText = "select plugin,authentication_string from mysql.user where user='auth_windows'"; using (MySqlDataReader r = cmd.ExecuteReader()) { if (r.Read()) { haveAuthWindowsUser = true; pluginName = (string) r["plugin"]; authenticationString = (string) r["authentication_string"]; } } // Create mapping for current Windows user=>foo_user String windowsUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name; windowsUser = windowsUser.Replace("\\", "\\\\"); string userMapping = windowsUser+"=foo_user"; try { if (!haveAuthWindowsUser) { suExecSQL( "CREATE USER auth_windows IDENTIFIED WITH " + PluginName +" as '" + userMapping + "'"); } else { // extend mapping string for current user suExecSQL( "UPDATE mysql.user SET authentication_string='" + userMapping + "," + authenticationString + "'"); } suExecSQL("create user foo_user identified by 'pass'"); suExecSQL("grant all privileges on *.* to 'foo_user'@'%'"); suExecSQL("grant proxy on foo_user to auth_windows"); // Finally, use IntegratedSecurity=true for the newly created user string connStr = GetConnectionString(true) + ";Integrated Security=SSPI"; /* If pooling is requested, we'll run test twice, with connection reset in between */ if (pooling) { connStr += ";Connection Reset=true;Pooling=true"; } int testIterations = pooling ? 2 : 1; int threadId = -1; for (int i = 0; i < testIterations ;i++ ) { using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); threadId = c.ServerThread; MySqlCommand command = new MySqlCommand("SELECT 1", c); long ret = (long)command.ExecuteScalar(); Assert.AreEqual(ret, 1); command.CommandText = "select user()"; string user = (string)command.ExecuteScalar(); // Check if proxy user is correct Assert.IsTrue(user.StartsWith("auth_windows@")); // check if mysql user is correct // (foo_user is mapped to current OS user) command.CommandText = "select current_user()"; string currentUser = (string)command.ExecuteScalar(); Assert.IsTrue(currentUser.StartsWith("foo_user@")); } } if (pooling) { suExecSQL("KILL " + threadId); } } finally { // Cleanup // Drop test user suExecSQL("drop user foo_user"); if (!haveAuthWindowsUser) { // drop proxy user if we created it suExecSQL("drop user auth_windows"); } else { // revert changes in the mapping string suExecSQL("UPDATE mysql.user SET authentication_string='" + authenticationString + "'"); } } } #endif [Test] public void TestConnectingSocketBadUserName() { suExecSQL("DELETE FROM mysql.user WHERE length(user) = 0"); suExecSQL("FLUSH PRIVILEGES"); string connStr = "server={0};user id=dummy;password=;database=Test;pooling=false"; MySqlConnection c = new MySqlConnection( String.Format(connStr, host)); try { c.Open(); c.Close(); throw new Exception("Open should not have worked"); } catch (MySqlException) { } } [Test] public void TestConnectingSocketBadDbName() { string connStr = "server={0};user id={1};password={2};database=dummy; " + "pooling=false"; MySqlConnection c = new MySqlConnection( String.Format(connStr, host, user, password)); try { c.Open(); c.Close(); throw new Exception("Open should not have worked"); } catch (MySqlException) { } } [Test] public void TestPersistSecurityInfoCachingPasswords() { string connStr = GetConnectionString(true); MySqlConnection c = new MySqlConnection(connStr); c.Open(); c.Close(); // this shouldn't work connStr = GetConnectionString(user, "bad_password", true); c = new MySqlConnection(connStr); try { c.Open(); Assert.Fail("Thn is should not work"); c.Close(); return; } catch (MySqlException) { } // this should work connStr = GetConnectionString(true); c = new MySqlConnection(connStr); c.Open(); c.Close(); } [Test] public void ChangeDatabase() { string connStr = GetConnectionString(true); MySqlConnection c = new MySqlConnection(connStr + ";pooling=false"); c.Open(); Assert.IsTrue(c.State == ConnectionState.Open); Assert.AreEqual(database0.ToLower(), c.Database.ToLower()); c.ChangeDatabase(database1); Assert.AreEqual(database1.ToLower(), c.Database.ToLower()); c.Close(); } [Test] public void ConnectionTimeout() { MySqlConnection c = new MySqlConnection( "server=1.1.1.1;user id=bogus;pwd=bogus;Connection timeout=5;" + "pooling=false"); DateTime start = DateTime.Now; try { c.Open(); } catch (Exception) { TimeSpan diff = DateTime.Now.Subtract(start); Assert.IsTrue(diff.TotalSeconds < 15, "Timeout exceeded"); } } /* [Test] public void AnonymousLogin() { suExecSQL(String.Format("GRANT ALL ON *.* to ''@'{0}' IDENTIFIED BY 'set_to_blank'", host)); suExecSQL("UPDATE mysql.user SET password='' WHERE password='set_to_blank'"); MySqlConnection c = new MySqlConnection(String.Empty); c.Open(); c.Close(); } */ [Test] public void ConnectInVariousWays() { // connect with no db string connStr2 = GetConnectionString(false); MySqlConnection c = new MySqlConnection(connStr2); c.Open(); c.Close(); suExecSQL("GRANT ALL ON *.* to 'nopass'@'%'"); suExecSQL("GRANT ALL ON *.* to 'nopass'@'localhost'"); suExecSQL("FLUSH PRIVILEGES"); // connect with no password connStr2 = GetConnectionString("nopass", null, false); c = new MySqlConnection(connStr2); c.Open(); c.Close(); connStr2 = GetConnectionString("nopass", "", false); c = new MySqlConnection(connStr2); c.Open(); c.Close(); } [Test] public void ConnectingAsUTF8() { if (Version < new Version(4, 1)) return; string connStr = GetConnectionString(true) + ";charset=utf8"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand( "CREATE TABLE test (id varbinary(16), active bit) CHARACTER SET utf8", conn); cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO test (id, active) VALUES (CAST(0x1234567890 AS Binary), true)"; cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO test (id, active) VALUES (CAST(0x123456789a AS Binary), true)"; cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO test (id, active) VALUES (CAST(0x123456789b AS Binary), true)"; cmd.ExecuteNonQuery(); } using (MySqlConnection d = new MySqlConnection(connStr)) { d.Open(); MySqlCommand cmd2 = new MySqlCommand("SELECT id, active FROM test", d); using (MySqlDataReader reader = cmd2.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.IsTrue(reader.GetBoolean(1)); } } } /// /// Bug #10281 Clone issue with MySqlConnection /// Bug #27269 MySqlConnection.Clone does not mimic SqlConnection.Clone behaviour /// [Test] public void TestConnectionClone() { MySqlConnection c = new MySqlConnection(); MySqlConnection clone = (MySqlConnection)((ICloneable)c).Clone(); clone.ToString(); string connStr = GetConnectionString(true); connStr = connStr.Replace("persist security info=true", "persist security info=false"); c = new MySqlConnection(connStr); c.Open(); c.Close(); MySqlConnection c2 = (MySqlConnection)((ICloneable)c).Clone(); c2.Open(); c2.Close(); } /// /// Bug #13321 Persist security info does not woek /// [Test] public void PersistSecurityInfo() { string s = GetConnectionString(true).ToLower(); int start = s.IndexOf("persist security info"); int end = s.IndexOf(";", start); string connStr = s.Substring(0, start); connStr += s.Substring(end, s.Length - (end)); string p = "password"; if (connStr.IndexOf("pwd") != -1) p = "pwd"; else if (connStr.IndexOf("passwd") != -1) p = "passwd"; string newConnStr = connStr + ";persist security info=true"; MySqlConnection conn2 = new MySqlConnection(newConnStr); Assert.IsTrue(conn2.ConnectionString.IndexOf(p) != -1); conn2.Open(); conn2.Close(); Assert.IsTrue(conn2.ConnectionString.IndexOf(p) != -1); newConnStr = connStr + ";persist security info=false"; conn2 = new MySqlConnection(newConnStr); Assert.IsTrue(conn2.ConnectionString.IndexOf(p) != -1); conn2.Open(); conn2.Close(); Assert.IsTrue(conn2.ConnectionString.IndexOf(p) == -1); } /// /// Bug #13658 connection.state does not update on Ping() /// [Test] public void PingUpdatesState() { MySqlConnection conn2 = new MySqlConnection(GetConnectionString(true)); conn2.Open(); KillConnection(conn2); Assert.IsFalse(conn2.Ping()); Assert.IsTrue(conn2.State == ConnectionState.Closed); conn2.Open(); conn2.Close(); } /// /// Bug #16659 Can't use double quotation marks(") as password access server by Connector/NET /// [Test] public void ConnectWithQuotePassword() { suExecSQL("GRANT ALL ON *.* to 'quotedUser'@'%' IDENTIFIED BY '\"'"); suExecSQL("GRANT ALL ON *.* to 'quotedUser'@'localhost' IDENTIFIED BY '\"'"); string connStr = GetConnectionString("quotedUser", null, false); connStr += ";pwd='\"'"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); } } /// /// Bug #24802 Error Handling /// [Test] public void TestConnectingSocketBadHostName() { string connStr = "server=foobar;user id=foouser;password=;database=Test;" + "pooling=false"; try { using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); } } catch (MySqlException ex) { Assert.AreEqual((int)MySqlErrorCode.UnableToConnectToHost, ex.Number); } } /// /// Bug #29123 Connection String grows with each use resulting in OutOfMemoryException /// [Test] public void ConnectionStringNotAffectedByChangeDatabase() { for (int i = 0; i < 10; i++) { string connStr = GetConnectionString(true) + ";pooling=false"; connStr = connStr.Replace("database", "Initial Catalog"); connStr = connStr.Replace("persist security info=true", "persist security info=false"); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); string str = c.ConnectionString; int index = str.IndexOf("Database="); Assert.AreEqual(-1, index); } } } class ConnectionClosedCheck { public bool closed = false; public void stateChangeHandler(object sender, StateChangeEventArgs e) { if (e.CurrentState == ConnectionState.Closed) closed = true; } } [Test] public void ConnectionCloseByGC() { int threadId; ConnectionClosedCheck check = new ConnectionClosedCheck(); string connStr = GetConnectionString(true) + ";pooling=true"; MySqlConnection c = new MySqlConnection(connStr); c.StateChange += new StateChangeEventHandler(check.stateChangeHandler); c.Open(); threadId = c.ServerThread; c = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.IsTrue(check.closed); MySqlCommand cmd = new MySqlCommand("KILL " + threadId, conn); cmd.ExecuteNonQuery(); } /// /// Bug #30964 StateChange imperfection /// MySqlConnection rqConnection; [Test] public void RunningAQueryFromStateChangeHandler() { string connStr = GetConnectionString(true); using (rqConnection = new MySqlConnection(connStr)) { rqConnection.StateChange += new StateChangeEventHandler(RunningQueryStateChangeHandler); rqConnection.Open(); } } void RunningQueryStateChangeHandler(object sender, StateChangeEventArgs e) { if (e.CurrentState == ConnectionState.Open) { MySqlCommand cmd = new MySqlCommand("SELECT 1", rqConnection); object o = cmd.ExecuteScalar(); Assert.AreEqual(1, o); } } /// /// Bug #31262 NullReferenceException in MySql.Data.MySqlClient.NativeDriver.ExecuteCommand /// [Test] public void ConnectionNotOpenThrowningBadException() { MySqlConnection c2 = new MySqlConnection(); c2.ConnectionString = GetConnectionString(true); // "DataSource=localhost;Database=test;UserID=root;Password=********;PORT=3306;Allow Zero Datetime=True;logging=True;"; //conn.Open(); << REM MySqlCommand command = new MySqlCommand(); command.Connection = c2; MySqlCommand cmdCreateTable = new MySqlCommand("DROP TABLE IF EXISTS `test`.`contents_catalog`", c2); cmdCreateTable.CommandType = CommandType.Text; cmdCreateTable.CommandTimeout = 0; try { cmdCreateTable.ExecuteNonQuery(); } catch (InvalidOperationException) { } } /// /// Bug #31433 Username incorrectly cached for logon where case sensitive /// [Test] public void CaseSensitiveUserId() { string connStr = GetConnectionString("Test", "test", true); using (MySqlConnection c = new MySqlConnection(connStr)) { try { c.Open(); } catch (MySqlException) { } } connStr = GetConnectionString("test", "test", true); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); } } /// /// Bug #35619 creating a MySql connection from toolbox generates an error /// [Test] public void NullConnectionString() { MySqlConnection c = new MySqlConnection(); c.ConnectionString = null; } /// /// Bug #53097 Connection.Ping() closes connection if executed on a connection with datareader /// [Test] public void PingWhileReading() { MySqlCommand command = new MySqlCommand("SELECT 1", conn); using (MySqlDataReader reader = command.ExecuteReader()) { reader.Read(); try { conn.Ping(); Assert.Fail("Test Failed."); } catch (MySqlException ex) { Assert.AreEqual(Resources.DataReaderOpen, ex.Message); } } } /// /// Test if keepalive parameters work. /// [Test] public void Keepalive() { string connstr = GetConnectionString("test", "test", true); connstr += ";keepalive=1;"; using (MySqlConnection c = new MySqlConnection(connstr)) { c.Open(); } } #if !CF [Test] public void CanOpenConnectionInMediumTrust() { AppDomain appDomain = PartialTrustSandbox.CreatePartialTrustDomain(); PartialTrustSandbox sandbox = (PartialTrustSandbox)appDomain.CreateInstanceAndUnwrap( typeof(PartialTrustSandbox).Assembly.FullName, typeof(PartialTrustSandbox).FullName); try { MySqlConnection connection = sandbox.TryOpenConnection(GetConnectionString(true)); Assert.IsNotNull(connection); Assert.IsTrue(connection.State == ConnectionState.Open); connection.Close(); //Now try with logging enabled connection = sandbox.TryOpenConnection(GetConnectionString(true) + ";logging=true"); Assert.IsNotNull(connection); Assert.IsTrue(connection.State == ConnectionState.Open); connection.Close(); //Now try with Usage Advisor enabled connection = sandbox.TryOpenConnection(GetConnectionString(true) + ";Use Usage Advisor=true"); Assert.IsNotNull(connection); Assert.IsTrue(connection.State == ConnectionState.Open); connection.Close(); } finally { AppDomain.Unload(appDomain); } } /// /// A client can connect to MySQL server using SSL and a pfx file. /// /// This test requires starting the server with SSL support. /// For instance, the following command line enables SSL in the server: /// mysqld --no-defaults --standalone --console --ssl-ca='MySQLServerDir'\mysql-test\std_data\cacert.pem --ssl-cert='MySQLServerDir'\mysql-test\std_data\server-cert.pem --ssl-key='MySQLServerDir'\mysql-test\std_data\server-key.pem /// /// [Test] public void CanConnectUsingFileBasedCertificate() { if (Version < new Version(5, 1)) return; string connstr = GetConnectionString(true); connstr += ";CertificateFile=client.pfx;CertificatePassword=pass;SSL Mode=Required;"; using (MySqlConnection c = new MySqlConnection(connstr)) { c.Open(); Assert.AreEqual(ConnectionState.Open, c.State); } } #endif #if CF /// /// A client running in .NET Compact Framework can't connect to MySQL server using SSL and a pfx file. /// /// This test requires starting the server with SSL support. /// For instance, the following command line enables SSL in the server: /// mysqld --no-defaults --standalone --console --ssl-ca='MySQLServerDir'\mysql-test\std_data\cacert.pem --ssl-cert='MySQLServerDir'\mysql-test\std_data\server-cert.pem --ssl-key='MySQLServerDir'\mysql-test\std_data\server-key.pem /// /// [Test] [ExpectedException(typeof(ArgumentException))] public void CannotConnectUsingFileBasedCertificateInCF() { string connstr = GetConnectionString(true); connstr += ";CertificateFile=client.pfx;CertificatePassword=pass;SSL Mode=Required;"; MySqlConnection c = new MySqlConnection(connstr); } #endif [Test] public void CanOpenConnectionAfterAborting() { MySqlConnection connection = new MySqlConnection(GetConnectionString(true)); connection.Open(); Assert.AreEqual(ConnectionState.Open, connection.State); connection.Abort(); Assert.AreEqual(ConnectionState.Closed, connection.State); connection.Open(); Assert.AreEqual(ConnectionState.Open, connection.State); connection.Close(); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/GetSchemaTests.cs0000644000175000017500000005635411127003600025522 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using NUnit.Framework; using System.Globalization; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class GetSchemaTests : BaseTest { [Test] public void Collections() { DataTable dt = conn.GetSchema(); int row = 0; Assert.AreEqual("MetaDataCollections", dt.Rows[row++][0]); Assert.AreEqual("DataSourceInformation", dt.Rows[row++][0]); Assert.AreEqual("DataTypes", dt.Rows[row++][0]); Assert.AreEqual("Restrictions", dt.Rows[row++][0]); Assert.AreEqual("ReservedWords", dt.Rows[row++][0]); Assert.AreEqual("Databases", dt.Rows[row++][0]); Assert.AreEqual("Tables", dt.Rows[row++][0]); Assert.AreEqual("Columns", dt.Rows[row++][0]); Assert.AreEqual("Users", dt.Rows[row++][0]); Assert.AreEqual("Foreign Keys", dt.Rows[row++][0]); Assert.AreEqual("IndexColumns", dt.Rows[row++][0]); Assert.AreEqual("Indexes", dt.Rows[row++][0]); Assert.AreEqual("Foreign Key Columns", dt.Rows[row++][0]); Assert.AreEqual("UDF", dt.Rows[row++][0]); Assert.AreEqual("Views", dt.Rows[row++][0]); Assert.AreEqual("ViewColumns", dt.Rows[row++][0]); Assert.AreEqual("Procedure Parameters", dt.Rows[row++][0]); Assert.AreEqual("Procedures", dt.Rows[row++][0]); Assert.AreEqual("Triggers", dt.Rows[row++][0]); } /// /// Bug #25907 DataType Column of DataTypes collection does'nt contain the correct CLR Datatype /// Bug #25947 CreateFormat/CreateParameters Column of DataTypes collection incorrect for CHAR /// [Test] public void DataTypes() { DataTable dt = conn.GetSchema("DataTypes", new string[] { }); foreach (DataRow row in dt.Rows) { string type = row["TYPENAME"].ToString(); Type systemType = Type.GetType(row["DATATYPE"].ToString()); if (type == "BIT") Assert.AreEqual(typeof(System.UInt64), systemType); else if (type == "DATE" || type == "DATETIME" || type == "TIMESTAMP") Assert.AreEqual(typeof(System.DateTime), systemType); else if (type == "BLOB" || type == "TINYBLOB" || type == "MEDIUMBLOB" || type == "LONGBLOB") Assert.AreEqual(typeof(System.Byte[]), systemType); else if (type == "TIME") Assert.AreEqual(typeof(System.TimeSpan), systemType); else if (type == "CHAR" || type == "VARCHAR") { Assert.AreEqual(typeof(System.String), systemType); Assert.IsFalse(Convert.ToBoolean(row["IsFixedLength"])); string format = type + "({0})"; Assert.AreEqual(format, row["CreateFormat"].ToString()); } else if (type == "SET" || type == "ENUM") Assert.AreEqual(typeof(System.String), systemType); else if (type == "DOUBLE") Assert.AreEqual(typeof(System.Double), systemType); else if (type == "SINGLE") Assert.AreEqual(typeof(System.Single), systemType); else if (type == "TINYINT") { if (row["CREATEFORMAT"].ToString().EndsWith("UNSIGNED")) Assert.AreEqual(typeof(System.Byte), systemType); else Assert.AreEqual(typeof(System.SByte), systemType); } else if (type == "SMALLINT") { if (row["CREATEFORMAT"].ToString().EndsWith("UNSIGNED")) Assert.AreEqual(typeof(System.UInt16), systemType); else Assert.AreEqual(typeof(System.Int16), systemType); } else if (type == "MEDIUMINT" || type == "INT") { if (row["CREATEFORMAT"].ToString().EndsWith("UNSIGNED")) Assert.AreEqual(typeof(System.UInt32), systemType); else Assert.AreEqual(typeof(System.Int32), systemType); } else if (type == "BIGINT") { if (row["CREATEFORMAT"].ToString().EndsWith("UNSIGNED")) Assert.AreEqual(typeof(System.UInt64), systemType); else Assert.AreEqual(typeof(System.Int64), systemType); } else if (type == "DECIMAL") { Assert.AreEqual(typeof(System.Decimal), systemType); Assert.AreEqual("DECIMAL({0},{1})", row["CreateFormat"].ToString()); } else if (type == "TINYINT") Assert.AreEqual(typeof(System.Byte), systemType); } } [Test] public void Databases() { DataTable dt = conn.GetSchema("Databases"); Assert.AreEqual("Databases", dt.TableName); bool foundZero = false; bool foundOne = false; foreach (DataRow row in dt.Rows) { string dbName = row[1].ToString().ToLower(); if (dbName == database0.ToLower()) foundZero = true; else if (dbName == database1.ToLower()) foundOne = true; } Assert.IsTrue(foundZero); Assert.IsTrue(foundOne); dt = conn.GetSchema("Databases", new string[1] { database0 }); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(database0.ToLower(), dt.Rows[0][1].ToString().ToLower()); } [Test] public void Tables() { execSQL("CREATE TABLE test1 (id int)"); string[] restrictions = new string[4]; restrictions[1] = database0; restrictions[2] = "test1"; DataTable dt = conn.GetSchema("Tables", restrictions); if (Version.Major >= 5 && Version.Minor >= 1) { Assert.IsTrue(dt.Columns["VERSION"].DataType == typeof(UInt64)); Assert.IsTrue(dt.Columns["TABLE_ROWS"].DataType == typeof(UInt64)); Assert.IsTrue(dt.Columns["AVG_ROW_LENGTH"].DataType == typeof(UInt64)); Assert.IsTrue(dt.Columns["DATA_LENGTH"].DataType == typeof(UInt64)); Assert.IsTrue(dt.Columns["MAX_DATA_LENGTH"].DataType == typeof(UInt64)); Assert.IsTrue(dt.Columns["INDEX_LENGTH"].DataType == typeof(UInt64)); Assert.IsTrue(dt.Columns["DATA_FREE"].DataType == typeof(UInt64)); Assert.IsTrue(dt.Columns["AUTO_INCREMENT"].DataType == typeof(UInt64)); Assert.IsTrue(dt.Columns["CHECKSUM"].DataType == typeof(UInt64)); } Assert.IsTrue(dt.Rows.Count == 1); Assert.AreEqual("Tables", dt.TableName); Assert.AreEqual("test1", dt.Rows[0][2]); } [Test] public void Columns() { execSQL(@"CREATE TABLE test (col1 int, col2 decimal(20,5), col3 varchar(50) character set utf8, col4 tinyint unsigned, col5 varchar(20) default 'boo')"); string[] restrictions = new string[4]; restrictions[1] = database0; restrictions[2] = "test"; DataTable dt = conn.GetSchema("Columns", restrictions); Assert.AreEqual(5, dt.Rows.Count); Assert.AreEqual("Columns", dt.TableName); if (Version.Major >= 5 && Version.Minor >= 1) { Assert.IsTrue(dt.Columns["ORDINAL_POSITION"].DataType == typeof(UInt64)); Assert.IsTrue(dt.Columns["CHARACTER_MAXIMUM_LENGTH"].DataType == typeof(UInt64)); Assert.IsTrue(dt.Columns["NUMERIC_PRECISION"].DataType == typeof(UInt64)); Assert.IsTrue(dt.Columns["NUMERIC_SCALE"].DataType == typeof(UInt64)); } // first column Assert.AreEqual(database0.ToUpper(), dt.Rows[0]["TABLE_SCHEMA"].ToString().ToUpper()); Assert.AreEqual("COL1", dt.Rows[0]["COLUMN_NAME"].ToString().ToUpper()); Assert.AreEqual(1, dt.Rows[0]["ORDINAL_POSITION"]); Assert.AreEqual("YES", dt.Rows[0]["IS_NULLABLE"]); Assert.AreEqual("INT", dt.Rows[0]["DATA_TYPE"].ToString().ToUpper()); // second column Assert.AreEqual(database0.ToUpper(), dt.Rows[1]["TABLE_SCHEMA"].ToString().ToUpper()); Assert.AreEqual("COL2", dt.Rows[1]["COLUMN_NAME"].ToString().ToUpper()); Assert.AreEqual(2, dt.Rows[1]["ORDINAL_POSITION"]); Assert.AreEqual("YES", dt.Rows[1]["IS_NULLABLE"]); Assert.AreEqual("DECIMAL", dt.Rows[1]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual("DECIMAL(20,5)", dt.Rows[1]["COLUMN_TYPE"].ToString().ToUpper()); Assert.AreEqual(20, dt.Rows[1]["NUMERIC_PRECISION"]); Assert.AreEqual(5, dt.Rows[1]["NUMERIC_SCALE"]); // third column Assert.AreEqual(database0.ToUpper(), dt.Rows[2]["TABLE_SCHEMA"].ToString().ToUpper()); Assert.AreEqual("COL3", dt.Rows[2]["COLUMN_NAME"].ToString().ToUpper()); Assert.AreEqual(3, dt.Rows[2]["ORDINAL_POSITION"]); Assert.AreEqual("YES", dt.Rows[2]["IS_NULLABLE"]); Assert.AreEqual("VARCHAR", dt.Rows[2]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual("VARCHAR(50)", dt.Rows[2]["COLUMN_TYPE"].ToString().ToUpper()); // fourth column Assert.AreEqual(database0.ToUpper(), dt.Rows[3]["TABLE_SCHEMA"].ToString().ToUpper()); Assert.AreEqual("COL4", dt.Rows[3]["COLUMN_NAME"].ToString().ToUpper()); Assert.AreEqual(4, dt.Rows[3]["ORDINAL_POSITION"]); Assert.AreEqual("YES", dt.Rows[3]["IS_NULLABLE"]); Assert.AreEqual("TINYINT", dt.Rows[3]["DATA_TYPE"].ToString().ToUpper()); // fifth column Assert.AreEqual(database0.ToUpper(), dt.Rows[4]["TABLE_SCHEMA"].ToString().ToUpper()); Assert.AreEqual("COL5", dt.Rows[4]["COLUMN_NAME"].ToString().ToUpper()); Assert.AreEqual(5, dt.Rows[4]["ORDINAL_POSITION"]); Assert.AreEqual("YES", dt.Rows[4]["IS_NULLABLE"]); Assert.AreEqual("VARCHAR", dt.Rows[4]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual("VARCHAR(20)", dt.Rows[4]["COLUMN_TYPE"].ToString().ToUpper()); Assert.AreEqual("'BOO'", dt.Rows[4]["COLUMN_DEFAULT"].ToString().ToUpper()); } /// /// Bug #46270 connection.GetSchema("Columns") fails on MySQL 4.1 /// [Test] public void EnumAndSetColumns() { execSQL("DROP TABLE IF EXISTS test"); execSQL("CREATE TABLE test (col1 set('A','B','C'), col2 enum('A','B','C'))"); DataTable dt = conn.GetSchema("Columns", new string[] { null, null, "test", null }); Assert.AreEqual(2, dt.Rows.Count); Assert.AreEqual("set", dt.Rows[0]["DATA_TYPE"]); Assert.AreEqual("enum", dt.Rows[1]["DATA_TYPE"]); Assert.AreEqual("set('A','B','C')", dt.Rows[0]["COLUMN_TYPE"]); Assert.AreEqual("enum('A','B','C')", dt.Rows[1]["COLUMN_TYPE"]); } [Test] public void Procedures() { if (Version < new Version(5, 0)) return; execSQL("DROP PROCEDURE IF EXISTS spTest"); execSQL("CREATE PROCEDURE spTest (id int) BEGIN SELECT 1; END"); string[] restrictions = new string[4]; restrictions[1] = database0; restrictions[2] = "spTest"; DataTable dt = conn.GetSchema("Procedures", restrictions); Assert.IsTrue(dt.Rows.Count == 1); Assert.AreEqual("Procedures", dt.TableName); Assert.AreEqual("spTest", dt.Rows[0][3]); } [Test] public void Functions() { if (Version < new Version(5, 0)) return; execSQL("DROP FUNCTION IF EXISTS spFunc"); execSQL("CREATE FUNCTION spFunc (id int) RETURNS INT BEGIN RETURN 1; END"); string[] restrictions = new string[4]; restrictions[1] = database0; restrictions[2] = "spFunc"; DataTable dt = conn.GetSchema("Procedures", restrictions); Assert.IsTrue(dt.Rows.Count == 1); Assert.AreEqual("Procedures", dt.TableName); Assert.AreEqual("spFunc", dt.Rows[0][3]); } [Test] public void Indexes() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE test (id int, PRIMARY KEY(id))"); string[] restrictions = new string[4]; restrictions[2] = "test"; restrictions[1] = database0; DataTable dt = conn.GetSchema("Indexes", restrictions); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("test", dt.Rows[0]["TABLE_NAME"]); Assert.AreEqual(true, dt.Rows[0]["PRIMARY"]); Assert.AreEqual(true, dt.Rows[0]["UNIQUE"]); execSQL("DROP TABLE IF EXISTS test"); execSQL("CREATE TABLE test (id int, name varchar(50), " + "UNIQUE KEY key2 (name))"); dt = conn.GetSchema("Indexes", restrictions); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("test", dt.Rows[0]["TABLE_NAME"]); Assert.AreEqual("key2", dt.Rows[0]["INDEX_NAME"]); Assert.AreEqual(false, dt.Rows[0]["PRIMARY"]); Assert.AreEqual(true, dt.Rows[0]["UNIQUE"]); restrictions[3] = "key2"; dt = conn.GetSchema("Indexes", restrictions); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("test", dt.Rows[0]["TABLE_NAME"]); Assert.AreEqual("key2", dt.Rows[0]["INDEX_NAME"]); Assert.AreEqual(false, dt.Rows[0]["PRIMARY"]); Assert.AreEqual(true, dt.Rows[0]["UNIQUE"]); /// /// Bug #48101 MySqlConnection.GetSchema on "Indexes" throws when there's a table named "b`a`d" /// execSQL("DROP TABLE IF EXISTS test"); execSQL(@"CREATE TABLE `te``s``t` (id int, name varchar(50), " + "KEY key2 (name))"); restrictions[2] = "te`s`t"; dt = conn.GetSchema("Indexes", restrictions); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("te`s`t", dt.Rows[0]["TABLE_NAME"]); Assert.AreEqual("key2", dt.Rows[0]["INDEX_NAME"]); Assert.AreEqual(false, dt.Rows[0]["PRIMARY"]); Assert.AreEqual(false, dt.Rows[0]["UNIQUE"]); } [Test] public void IndexColumns() { execSQL("CREATE TABLE test (id int, PRIMARY KEY(id))"); string[] restrictions = new string[5]; restrictions[2] = "test"; restrictions[1] = database0; DataTable dt = conn.GetSchema("IndexColumns", restrictions); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("test", dt.Rows[0]["TABLE_NAME"]); Assert.AreEqual("id", dt.Rows[0]["COLUMN_NAME"]); execSQL("DROP TABLE IF EXISTS test"); execSQL("CREATE TABLE test (id int, id1 int, id2 int, " + "INDEX key1 (id1, id2))"); restrictions[2] = "test"; restrictions[1] = database0; restrictions[4] = "id2"; dt = conn.GetSchema("IndexColumns", restrictions); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("test", dt.Rows[0]["TABLE_NAME"]); Assert.AreEqual("id2", dt.Rows[0]["COLUMN_NAME"]); Assert.AreEqual(2, dt.Rows[0]["ORDINAL_POSITION"]); restrictions[3] = "key1"; dt = conn.GetSchema("IndexColumns", restrictions); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("test", dt.Rows[0]["TABLE_NAME"]); Assert.AreEqual("id2", dt.Rows[0]["COLUMN_NAME"]); Assert.AreEqual(2, dt.Rows[0]["ORDINAL_POSITION"]); restrictions = new string[3]; restrictions[1] = database0; restrictions[2] = "test"; dt = conn.GetSchema("IndexColumns", restrictions); Assert.AreEqual(2, dt.Rows.Count); Assert.AreEqual("test", dt.Rows[0]["TABLE_NAME"]); Assert.AreEqual("id1", dt.Rows[0]["COLUMN_NAME"]); Assert.AreEqual(1, dt.Rows[0]["ORDINAL_POSITION"]); Assert.AreEqual("test", dt.Rows[1]["TABLE_NAME"]); Assert.AreEqual("id2", dt.Rows[1]["COLUMN_NAME"]); Assert.AreEqual(2, dt.Rows[1]["ORDINAL_POSITION"]); restrictions = new string[4]; execSQL("DROP TABLE IF EXISTS test"); execSQL("CREATE TABLE test (id int primary key, id1 int, KEY key1 (id1))"); restrictions[2] = "test"; restrictions[1] = database0; restrictions[3] = "PRIMARY"; dt = conn.GetSchema("IndexColumns", restrictions); } [Test] public void Views() { if (Version < new Version(5, 0)) return; execSQL("DROP VIEW IF EXISTS vw"); execSQL("CREATE VIEW vw AS SELECT Now() as theTime"); string[] restrictions = new string[4]; restrictions[1] = database0; restrictions[2] = "vw"; DataTable dt = conn.GetSchema("Views", restrictions); Assert.IsTrue(dt.Rows.Count == 1); Assert.AreEqual("Views", dt.TableName); Assert.AreEqual("vw", dt.Rows[0]["TABLE_NAME"]); } [Test] public void ViewColumns() { if (Version < new Version(5, 0)) return; execSQL("DROP VIEW IF EXISTS vw"); execSQL("CREATE VIEW vw AS SELECT Now() as theTime"); string[] restrictions = new string[4]; restrictions[1] = database0; restrictions[2] = "vw"; DataTable dt = conn.GetSchema("ViewColumns", restrictions); Assert.IsTrue(dt.Rows.Count == 1); Assert.AreEqual("ViewColumns", dt.TableName); Assert.AreEqual(database0.ToLower(), dt.Rows[0]["VIEW_SCHEMA"].ToString().ToLower()); Assert.AreEqual("vw", dt.Rows[0]["VIEW_NAME"]); Assert.AreEqual("theTime", dt.Rows[0]["COLUMN_NAME"]); } [Test] public void SingleForeignKey() { execSQL("CREATE TABLE parent (id INT NOT NULL, PRIMARY KEY (id)) ENGINE=INNODB"); execSQL("CREATE TABLE child (id INT, parent_id INT, INDEX par_ind (parent_id), " + "CONSTRAINT c1 FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE) ENGINE=INNODB"); string[] restrictions = new string[4]; restrictions[0] = null; restrictions[1] = database0; restrictions[2] = "child"; DataTable dt = conn.GetSchema("Foreign Keys", restrictions); Assert.AreEqual(1, dt.Rows.Count); DataRow row = dt.Rows[0]; Assert.AreEqual(database0.ToLower(), row["CONSTRAINT_SCHEMA"].ToString().ToLower()); Assert.AreEqual("c1", row["CONSTRAINT_NAME"]); Assert.AreEqual(database0.ToLower(), row["TABLE_SCHEMA"].ToString().ToLower()); Assert.AreEqual("child", row["TABLE_NAME"]); Assert.AreEqual(database0.ToLower(), row["REFERENCED_TABLE_SCHEMA"].ToString().ToLower()); Assert.AreEqual("parent", row["REFERENCED_TABLE_NAME"]); } /// /// Bug #26660 MySqlConnection.GetSchema fails with NullReferenceException for Foreign Keys /// [Test] public void ForeignKeys() { execSQL("CREATE TABLE product (category INT NOT NULL, id INT NOT NULL, " + "price DECIMAL, PRIMARY KEY(category, id)) ENGINE=INNODB"); execSQL("CREATE TABLE customer (id INT NOT NULL, PRIMARY KEY (id)) ENGINE=INNODB"); execSQL("CREATE TABLE product_order (no INT NOT NULL AUTO_INCREMENT, " + "product_category INT NOT NULL, product_id INT NOT NULL, customer_id INT NOT NULL, " + "PRIMARY KEY(no), INDEX (product_category, product_id), " + "FOREIGN KEY (product_category, product_id) REFERENCES product(category, id) " + "ON UPDATE CASCADE ON DELETE RESTRICT, INDEX (customer_id), " + "FOREIGN KEY (customer_id) REFERENCES customer(id)) ENGINE=INNODB"); DataTable dt = conn.GetSchema("Foreign Keys"); Assert.IsTrue(dt.Columns.Contains("REFERENCED_TABLE_CATALOG")); } [Test] public void MultiSingleForeignKey() { execSQL("CREATE TABLE product (category INT NOT NULL, id INT NOT NULL, " + "price DECIMAL, PRIMARY KEY(category, id)) ENGINE=INNODB"); execSQL("CREATE TABLE customer (id INT NOT NULL, PRIMARY KEY (id)) ENGINE=INNODB"); execSQL("CREATE TABLE product_order (no INT NOT NULL AUTO_INCREMENT, " + "product_category INT NOT NULL, product_id INT NOT NULL, customer_id INT NOT NULL, " + "PRIMARY KEY(no), INDEX (product_category, product_id), " + "FOREIGN KEY (product_category, product_id) REFERENCES product(category, id) " + "ON UPDATE CASCADE ON DELETE RESTRICT, INDEX (customer_id), " + "FOREIGN KEY (customer_id) REFERENCES customer(id)) ENGINE=INNODB"); string[] restrictions = new string[4]; restrictions[0] = null; restrictions[1] = database0; restrictions[2] = "product_order"; DataTable dt = conn.GetSchema("Foreign Keys", restrictions); Assert.AreEqual(2, dt.Rows.Count); DataRow row = dt.Rows[0]; Assert.AreEqual(database0.ToLower(), row["CONSTRAINT_SCHEMA"].ToString().ToLower()); Assert.AreEqual("product_order_ibfk_1", row["CONSTRAINT_NAME"]); Assert.AreEqual(database0.ToLower(), row["TABLE_SCHEMA"].ToString().ToLower()); Assert.AreEqual("product_order", row["TABLE_NAME"]); Assert.AreEqual(database0.ToLower(), row["REFERENCED_TABLE_SCHEMA"].ToString().ToLower()); Assert.AreEqual("product", row["REFERENCED_TABLE_NAME"]); row = dt.Rows[1]; Assert.AreEqual(database0.ToLower(), row["CONSTRAINT_SCHEMA"].ToString().ToLower()); Assert.AreEqual("product_order_ibfk_2", row["CONSTRAINT_NAME"]); Assert.AreEqual(database0.ToLower(), row["TABLE_SCHEMA"].ToString().ToLower()); Assert.AreEqual("product_order", row["TABLE_NAME"]); Assert.AreEqual(database0.ToLower(), row["REFERENCED_TABLE_SCHEMA"].ToString().ToLower()); Assert.AreEqual("customer", row["REFERENCED_TABLE_NAME"]); } [Test] public void Triggers() { if (Version < new Version(5, 1, 6)) return; execSQL("CREATE TABLE test1 (id int)"); execSQL("CREATE TABLE test2 (count int)"); execSQL("INSERT INTO test2 VALUES (0)"); string sql = String.Format("CREATE TRIGGER `{0}`.trigger1 AFTER INSERT ON test1 FOR EACH ROW BEGIN " + "UPDATE test2 SET count = count+1; END", database0); suExecSQL(sql); string[] restrictions = new string[4]; restrictions[1] = database0; restrictions[2] = "test1"; DataTable dt = rootConn.GetSchema("Triggers", restrictions); Assert.IsTrue(dt.Rows.Count == 1); Assert.AreEqual("Triggers", dt.TableName); Assert.AreEqual("trigger1", dt.Rows[0]["TRIGGER_NAME"]); Assert.AreEqual("INSERT", dt.Rows[0]["EVENT_MANIPULATION"]); Assert.AreEqual("test1", dt.Rows[0]["EVENT_OBJECT_TABLE"]); Assert.AreEqual("ROW", dt.Rows[0]["ACTION_ORIENTATION"]); Assert.AreEqual("AFTER", dt.Rows[0]["ACTION_TIMING"]); } [Test] public void UsingQuotedRestrictions() { execSQL("CREATE TABLE test1 (id int)"); string[] restrictions = new string[4]; restrictions[1] = database0; restrictions[2] = "`test1`"; DataTable dt = conn.GetSchema("Tables", restrictions); Assert.IsTrue(dt.Rows.Count == 1); Assert.AreEqual("Tables", dt.TableName); Assert.AreEqual("test1", dt.Rows[0][2]); Assert.AreEqual("`test1`", restrictions[2]); } [Test] public void ReservedWords() { DataTable dt = conn.GetSchema("ReservedWords"); foreach (DataRow row in dt.Rows) Assert.IsFalse(String.IsNullOrEmpty(row[0] as string)); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/EventTests.cs0000644000175000017500000000500011127003600024721 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using System.Globalization; using System.Threading; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class EventTests : BaseTest { [Test] public void Warnings() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (name VARCHAR(10))"); string connStr = GetConnectionString(true); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("SET SQL_MODE=''", c); cmd.ExecuteNonQuery(); c.InfoMessage += new MySqlInfoMessageEventHandler(WarningsInfoMessage); cmd.CommandText = "INSERT INTO Test VALUES ('12345678901')"; using (MySqlDataReader reader = cmd.ExecuteReader()) { } } } private void WarningsInfoMessage(object sender, MySqlInfoMessageEventArgs args) { Assert.AreEqual(1, args.errors.Length); } [Test] public void StateChange() { MySqlConnection c = new MySqlConnection(GetConnectionString(true)); c.StateChange += new StateChangeEventHandler(StateChangeHandler); c.Open(); c.Close(); } private void StateChangeHandler(object sender, StateChangeEventArgs e) { } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/Syntax2.cs0000644000175000017500000001774011127003600024203 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class Syntax2 : BaseTest { public Syntax2() { csAdditions += ";logging=true;"; } [Test] public void CommentsInSQL() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); string sql = "INSERT INTO Test /* my table */ VALUES (1 /* this is the id */, 'Test' );" + "/* These next inserts are just for testing \r\n" + " comments */\r\n" + "INSERT INTO \r\n" + " # This table is bogus\r\n" + "Test VALUES (2, 'Test2')"; MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.ExecuteNonQuery(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable table = new DataTable(); da.Fill(table); Assert.AreEqual(1, table.Rows[0]["id"]); Assert.AreEqual("Test", table.Rows[0]["name"]); Assert.AreEqual(2, table.Rows.Count); Assert.AreEqual(2, table.Rows[1]["id"]); Assert.AreEqual("Test2", table.Rows[1]["name"]); } [Test] public void LastInsertid() { execSQL("CREATE TABLE Test(id int auto_increment, name varchar(20), primary key(id))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(NULL, 'test')", conn); cmd.ExecuteNonQuery(); Assert.AreEqual(1, cmd.LastInsertedId); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); } Assert.AreEqual(2, cmd.LastInsertedId); cmd.CommandText = "SELECT id FROM Test"; cmd.ExecuteScalar(); Assert.AreEqual(-1, cmd.LastInsertedId); } [Test] public void ParsingBugTest() { if (Version.Major < 5) return; execSQL("DROP FUNCTION IF EXISTS `TestFunction`"); execSQL(@"CREATE FUNCTION `TestFunction`(A INTEGER (11), B INTEGER (11), C VARCHAR (20)) RETURNS int(11) RETURN 1"); MySqlCommand command = new MySqlCommand("TestFunction", conn); command.CommandType = CommandType.StoredProcedure; command.CommandText = "TestFunction"; command.Parameters.AddWithValue("@A", 1); command.Parameters.AddWithValue("@B", 2); command.Parameters.AddWithValue("@C", "test"); command.Parameters.Add("@return", MySqlDbType.Int32).Direction = ParameterDirection.ReturnValue; command.ExecuteNonQuery(); } /// /// Bug #44960 backslash in string - connector return exeption /// [Test] public void EscapedBackslash() { execSQL("CREATE TABLE Test(id INT, name VARCHAR(20))"); MySqlCommand cmd = new MySqlCommand(@"INSERT INTO Test VALUES (1, '\\=\\')", conn); cmd.ExecuteNonQuery(); } /* [Category("NotWorking")] [Test] public void TestCase() { string importQuery = "SET FOREIGN_KEY_CHECKS = 1;DELETE FROM Category " + "WHERE id=\'0205342903\';SET FOREIGN_KEY_CHECKS = 0;INSERT INTO Category " + "VALUES(\'d0450f050a0dfd8e00e6da7bda3bb07e\',\'0205342903\',\'000000000000000 " + "00000000000000000\',\'\',\'0\');INSERT INTO Attribute " + "VALUES(\'d0450f050a0dfd8e00e6da7b00dfa3c5\',\'d0450f050a0dfd8e00e6da7bda3bb0 " + "7e\',\'eType\',\'machine\',null);SET FOREIGN_KEY_CHECKS = 1;"; string deleteQuery = "SET FOREIGN_KEY_CHECKS=1;DELETE FROM Attribute " + "WHERE foreignuuid=\'d0450f050a0dfd8e00e6da7bda3bb07e\' AND " + "name=\'eType\'"; string insertQuery = "SET FOREIGN_KEY_CHECKS = 0;INSERT INTO Attribute " + "VALUES(\'d0563ba70a0dfd8e01df43e22395b352\',\'d0450f050a0dfd8e00e6da7bda3bb0 " + "7e\',\'eType\',\'machine\',null);SET FOREIGN_KEY_CHECKS = 1"; string updateQuery = "SET FOREIGN_KEY_CHECKS = 1;DELETE FROM Attribute " + "WHERE foreignuuid=\'d0450f050a0dfd8e00e6da7bda3bb07e\' AND " + "name=\'eType\';SET FOREIGN_KEY_CHECKS = 0;INSERT INTO Attribute " + "VALUES(\'d0563ba70a0dfd8e01df43e22395b352\',\'d0450f050a0dfd8e00e6da7bda3bb0 " + "7e\',\'eType\',\'machine\',null);SET FOREIGN_KEY_CHECKS = 1;"; string bugQuery = "SELECT name,value FROM Attribute WHERE " + "foreignuuid=\'d0450f050a0dfd8e00e6da7bda3bb07e\'"; execSQL("SET FOREIGN_KEY_CHECKS=0"); execSQL("DROP TABLE IF EXISTS Attribute"); execSQL("CREATE TABLE IF NOT EXISTS Attribute (uuid char(32) NOT NULL," + "foreignuuid char(32), name character varying(254), value character varying(254)," + "fid integer, PRIMARY KEY (uuid), INDEX foreignuuid (foreignuuid), " + "INDEX name (name(16)), INDEX value (value(8)), CONSTRAINT `attribute_fk_1` " + "FOREIGN KEY (`foreignuuid`) REFERENCES `Category` (`uuid`) ON DELETE CASCADE" + ") CHARACTER SET utf8 ENGINE=InnoDB;"); execSQL("DROP TABLE IF EXISTS Category"); execSQL("CREATE TABLE IF NOT EXISTS Category (uuid char(32) NOT NULL," + "id character varying(254), parentuuid char(32), name character varying(254)," + "sort integer, PRIMARY KEY (uuid), INDEX parentuuid (parentuuid), INDEX id (id)," + "CONSTRAINT `parent_fk_1` FOREIGN KEY (`parentuuid`) REFERENCES `Category` " + "(`uuid`) ON DELETE CASCADE) CHARACTER SET utf8 ENGINE=InnoDB;"); execSQL("SET FOREIGN_KEY_CHECKS=1"); conn.InfoMessage += new MySqlInfoMessageEventHandler(conn_InfoMessage); MySqlCommand cmd = new MySqlCommand(importQuery, conn); cmd.ExecuteNonQuery(); for (int i = 0; i <= 5000; i++) { cmd.CommandText = deleteQuery; cmd.ExecuteNonQuery(); cmd.CommandText = insertQuery; cmd.ExecuteNonQuery(); cmd.CommandText = bugQuery; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Close(); } } } void conn_InfoMessage(object sender, MySqlInfoMessageEventArgs args) { throw new Exception("The method or operation is not implemented."); } */ } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/CommandBuilderTests.cs0000644000175000017500000003610011127003600026532 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class CommandBuilderTests : BaseTest { public CommandBuilderTests() { } [Test] public void MultiWord() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(100), dt DATETIME, tm TIME, `multi word` int, PRIMARY KEY(id))"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataTable dt = new DataTable(); da.Fill(dt); DataRow row = dt.NewRow(); row["id"] = 1; row["name"] = "Name"; row["dt"] = DBNull.Value; row["tm"] = DBNull.Value; row["multi word"] = 2; dt.Rows.Add(row); da.Update(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(2, dt.Rows[0]["multi word"]); dt.Rows[0]["multi word"] = 3; da.Update(dt); cb.Dispose(); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(3, dt.Rows[0]["multi word"]); } [Test] public void LastOneWins() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(100), dt DATETIME, tm TIME, `multi word` int, PRIMARY KEY(id))"); execSQL("INSERT INTO Test (id, name) VALUES (1, 'Test')"); MySqlCommandBuilder cb = new MySqlCommandBuilder( new MySqlDataAdapter("SELECT * FROM Test", conn)); MySqlDataAdapter da = cb.DataAdapter; cb.ConflictOption = ConflictOption.OverwriteChanges; DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); execSQL("UPDATE Test SET name='Test2' WHERE id=1"); dt.Rows[0]["name"] = "Test3"; Assert.AreEqual(1, da.Update(dt)); dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("Test3", dt.Rows[0]["name"]); } [Test] public void NotLastOneWins() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(100), dt DATETIME, tm TIME, `multi word` int, PRIMARY KEY(id))"); execSQL("INSERT INTO Test (id, name) VALUES (1, 'Test')"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); cb.ConflictOption = ConflictOption.CompareAllSearchableValues; DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); execSQL("UPDATE Test SET name='Test2' WHERE id=1"); try { dt.Rows[0]["name"] = "Test3"; da.Update(dt); Assert.Fail("This should not work"); } catch (DBConcurrencyException) { } dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("Test2", dt.Rows[0]["name"]); } /// /// Bug #8574 - MySqlCommandBuilder unable to support sub-queries /// Bug #11947 - MySQLCommandBuilder mishandling CONCAT() aliased column /// [Test] public void UsingFunctions() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(100), dt DATETIME, tm TIME, `multi word` int, PRIMARY KEY(id))"); execSQL("INSERT INTO Test (id, name) VALUES (1,'test1')"); execSQL("INSERT INTO Test (id, name) VALUES (2,'test2')"); execSQL("INSERT INTO Test (id, name) VALUES (3,'test3')"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT id, name, now() as ServerTime FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataTable dt = new DataTable(); da.Fill(dt); dt.Rows[0]["id"] = 4; da.Update(dt); da.SelectCommand.CommandText = "SELECT id, name, CONCAT(name, ' boo') as newname from Test where id=4"; dt.Clear(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("test1", dt.Rows[0]["name"]); Assert.AreEqual("test1 boo", dt.Rows[0]["newname"]); dt.Rows[0]["id"] = 5; da.Update(dt); dt.Clear(); da.SelectCommand.CommandText = "SELECT * FROM Test WHERE id=5"; da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("test1", dt.Rows[0]["name"]); da.SelectCommand.CommandText = "SELECT *, now() as stime FROM Test WHERE id<4"; cb = new MySqlCommandBuilder(da); cb.ConflictOption = ConflictOption.OverwriteChanges; da.InsertCommand = cb.GetInsertCommand(); } /// /// Bug #8382 Commandbuilder does not handle queries to other databases than the default one- /// [Test] public void DifferentDatabase() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(100), dt DATETIME, tm TIME, `multi word` int, PRIMARY KEY(id))"); execSQL("INSERT INTO Test (id, name) VALUES (1,'test1')"); execSQL("INSERT INTO Test (id, name) VALUES (2,'test2')"); execSQL("INSERT INTO Test (id, name) VALUES (3,'test3')"); conn.ChangeDatabase(database1); MySqlDataAdapter da = new MySqlDataAdapter( String.Format("SELECT id, name FROM `{0}`.Test", database0), conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataSet ds = new DataSet(); da.Fill(ds); ds.Tables[0].Rows[0]["id"] = 4; DataSet changes = ds.GetChanges(); da.Update(changes); ds.Merge(changes); ds.AcceptChanges(); cb.Dispose(); conn.ChangeDatabase(database0); } /// /// Bug #13036 Returns error when field names contain any of the following chars %<>()/ etc /// [Test] public void SpecialCharactersInFieldNames() { execSQL("CREATE TABLE Test (`col%1` int PRIMARY KEY, `col()2` int, `col<>3` int, `col/4` int)"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); cb.ToString(); // keep the compiler happy DataTable dt = new DataTable(); da.Fill(dt); DataRow row = dt.NewRow(); row[0] = 1; row[1] = 2; row[2] = 3; row[3] = 4; dt.Rows.Add(row); da.Update(dt); } /// /// Bug #14631 "#42000Query was empty" /// [Test] public void SemicolonAtEndOfSQL() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(100), PRIMARY KEY(id))"); execSQL("INSERT INTO Test VALUES(1, 'Data')"); DataSet ds = new DataSet(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM `Test`;", conn); da.FillSchema(ds, SchemaType.Source, "Test"); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataTable dt = new DataTable(); da.Fill(dt); dt.Rows[0]["id"] = 2; da.Update(dt); dt.Clear(); da.Fill(dt); cb.Dispose(); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(2, dt.Rows[0]["id"]); } /// /// Bug #23862 Problem with CommandBuilder 'GetInsertCommand' method /// [Test] public void AutoIncrementColumnsOnInsert() { execSQL("CREATE TABLE Test (id INT UNSIGNED NOT NULL AUTO_INCREMENT, " + "name VARCHAR(100), PRIMARY KEY(id))"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); da.InsertCommand = cb.GetInsertCommand(); da.InsertCommand.CommandText += "; SELECT last_insert_id()"; da.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord; DataTable dt = new DataTable(); da.Fill(dt); dt.Columns[0].AutoIncrement = true; Assert.IsTrue(dt.Columns[0].AutoIncrement); dt.Columns[0].AutoIncrementSeed = -1; dt.Columns[0].AutoIncrementStep = -1; DataRow row = dt.NewRow(); row["name"] = "Test"; dt.Rows.Add(row); da.Update(dt); dt.Clear(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(1, dt.Rows[0]["id"]); Assert.AreEqual("Test", dt.Rows[0]["name"]); cb.Dispose(); } /// /// Bug #25569 UpdateRowSource.FirstReturnedRecord does not work /// [Test] public void AutoIncrementColumnsOnInsert2() { execSQL("CREATE TABLE Test (id INT UNSIGNED NOT NULL " + "AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20))"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); MySqlCommand cmd = (MySqlCommand)(cb.GetInsertCommand() as ICloneable).Clone(); cmd.CommandText += "; SELECT last_insert_id() as id"; cmd.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord; da.InsertCommand = cmd; DataTable dt = new DataTable(); da.Fill(dt); dt.Rows.Clear(); DataRow row = dt.NewRow(); row["name"] = "Test"; dt.Rows.Add(row); da.Update(dt); Assert.AreEqual(1, dt.Rows[0]["id"]); Assert.AreEqual("Test", dt.Rows[0]["name"]); row = dt.NewRow(); row["name"] = "Test2"; dt.Rows.Add(row); da.Update(dt); Assert.AreEqual(2, dt.Rows[1]["id"]); Assert.AreEqual("Test2", dt.Rows[1]["name"]); Assert.AreEqual(1, dt.Rows[0]["id"]); } [Test] public void MultiUpdate() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(100), dt DATETIME, tm TIME, `multi word` int, PRIMARY KEY(id))"); execSQL("INSERT INTO Test (id, name) VALUES (1, 'test1')"); execSQL("INSERT INTO Test (id, name) VALUES (2, 'test2')"); execSQL("INSERT INTO Test (id, name) VALUES (3, 'test3')"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataTable dt = new DataTable(); da.Fill(dt); dt.Rows[0]["id"] = 4; dt.Rows[0]["name"] = "test4"; dt.Rows[1]["id"] = 5; dt.Rows[1]["name"] = "test5"; dt.Rows[2]["id"] = 6; dt.Rows[2]["name"] = "test6"; DataTable changes = dt.GetChanges(); da.Update(changes); dt.AcceptChanges(); dt.Rows[0]["id"] = 7; dt.Rows[0]["name"] = "test7"; dt.Rows[1]["id"] = 8; dt.Rows[1]["name"] = "test8"; dt.Rows[2]["id"] = 9; dt.Rows[2]["name"] = "test9"; changes = dt.GetChanges(); da.Update(changes); dt.AcceptChanges(); cb.Dispose(); } /// /// Bug #30077 MySqlDataAdapter.Update() exception due to date field format /// [Test] public void UpdatingWithDateInKey() { execSQL("CREATE TABLE Test (cod INT, dt DATE, PRIMARY KEY(cod, dt))"); execSQL("INSERT INTO Test (cod, dt) VALUES (1, '2006-1-1')"); execSQL("INSERT INTO Test (cod, dt) VALUES (2, '2006-1-2')"); execSQL("INSERT INTO Test (cod, dt) VALUES (3, '2006-1-3')"); execSQL("INSERT INTO Test (cod, dt) VALUES (4, '2006-1-4')"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test ORDER BY cod", conn); MySqlCommandBuilder bld = new MySqlCommandBuilder(da); bld.ConflictOption = ConflictOption.OverwriteChanges; DataTable dt = new DataTable(); da.Fill(dt); dt.Rows[0]["cod"] = 6; da.Update(dt); dt.Clear(); da.SelectCommand.CommandText = "SELECT * FROM Test WHERE cod=6"; da.Fill(dt); Assert.AreEqual(6, dt.Rows[0]["cod"]); } /// /// Bug #35492 Please implement DbCommandBuilder.QuoteIdentifier /// [Test] public void QuoteAndUnquoteIdentifiers() { MySqlCommandBuilder cb = new MySqlCommandBuilder(); Assert.AreEqual("`boo`", cb.QuoteIdentifier("boo")); Assert.AreEqual("`bo``o`", cb.QuoteIdentifier("bo`o")); Assert.AreEqual("`boo`", cb.QuoteIdentifier("`boo`")); // now do the unquoting Assert.AreEqual("boo", cb.UnquoteIdentifier("`boo`")); Assert.AreEqual("`boo", cb.UnquoteIdentifier("`boo")); Assert.AreEqual("bo`o", cb.UnquoteIdentifier("`bo``o`")); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/BaseTest.cs0000644000175000017500000002757211127003600024351 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using NUnit.Framework; using System.Configuration; using System.Data; using MySql.Data.MySqlClient; using System.Reflection; using System.Diagnostics; using System.Resources; using System.IO; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for BaseTest. /// public class BaseTest { //statics protected static int maxPacketSize; protected static MySqlConnection rootConn; protected static string host; protected static string user; protected static string password; protected static int port; protected static string pipeName; protected static string memoryName; protected static string rootUser; protected static string rootPassword; protected static string database0; protected static string database1; protected static Version version; protected string table; protected string csAdditions = String.Empty; protected MySqlConnection conn; protected bool accessToMySqlDb; private int numProcessesRunning; public BaseTest() { if (host == null) LoadStaticConfiguration(); } protected virtual void LoadStaticConfiguration() { Debug.Assert(host == null); user = "test"; password = "test"; port = 3306; rootUser = "root"; rootPassword = ""; string strPort = null; #if !CF host = ConfigurationManager.AppSettings["host"]; strPort = ConfigurationManager.AppSettings["port"]; pipeName = ConfigurationManager.AppSettings["pipename"]; memoryName = ConfigurationManager.AppSettings["memory_name"]; #endif if (strPort != null) port = Int32.Parse(strPort); if (host == null) host = "localhost"; if (pipeName == null) pipeName = "MYSQL"; if (memoryName == null) memoryName = "MYSQL"; // we don't use FileVersion because it's not available // on the compact framework if (database0 == null) { string fullname = Assembly.GetExecutingAssembly().FullName; string[] parts = fullname.Split(new char[] { '=' }); string[] versionParts = parts[1].Split(new char[] { '.' }); database0 = String.Format("db{0}{1}{2}-a", versionParts[0], versionParts[1], port - 3300); database1 = String.Format("db{0}{1}{2}-b", versionParts[0], versionParts[1], port - 3300); } string connStr = GetConnectionString(rootUser, rootPassword, false); rootConn = new MySqlConnection(connStr + ";database=mysql"); rootConn.Open(); if (rootConn.ServerVersion.StartsWith("5")) { // run all tests in strict mode MySqlCommand cmd = new MySqlCommand("SET GLOBAL SQL_MODE=STRICT_ALL_TABLES", rootConn); cmd.ExecuteNonQuery(); } } #region Properties protected Version Version { get { if (version == null) { string versionString = rootConn.ServerVersion; int i = 0; while (i < versionString.Length && (Char.IsDigit(versionString[i]) || versionString[i] == '.')) i++; version = new Version(versionString.Substring(0, i)); } return version; } } #endregion protected virtual string GetConnectionInfo() { return String.Format("protocol=sockets;port={0};", port); } protected string GetConnectionString(string userId, string pw, bool includedb) { Debug.Assert(userId != null); string connStr = String.Format("server={0};user id={1};pooling=false;" + "persist security info=true;connection reset=true;allow user variables=true;", host, userId); if (pw != null) connStr += String.Format(";password={0};", pw); if (includedb) connStr += String.Format("database={0};", database0); connStr += GetConnectionInfo(); connStr += csAdditions; return connStr; } protected string GetConnectionString(bool includedb) { return GetConnectionString(user, password, includedb); } protected string GetPoolingConnectionString() { string s = GetConnectionString(true); s = s.Replace("pooling=false", "pooling=true"); return s; } protected void Open() { string connString = GetConnectionString(true); conn = new MySqlConnection(connString); conn.Open(); } protected void SetAccountPerms(bool includeProc) { // now allow our user to access them suExecSQL(String.Format(@"GRANT ALL ON `{0}`.* to 'test'@'localhost' identified by 'test'", database0)); suExecSQL(String.Format(@"GRANT SELECT ON `{0}`.* to 'test'@'localhost' identified by 'test'", database1)); if (Version.Major >= 5) suExecSQL(String.Format(@"GRANT EXECUTE ON `{0}`.* to 'test'@'localhost' identified by 'test'", database1)); if (includeProc) { // now allow our user to access them suExecSQL(@"GRANT ALL ON mysql.proc to 'test'@'localhost' identified by 'test'"); } suExecSQL("FLUSH PRIVILEGES"); } [SetUp] public virtual void Setup() { Assembly executingAssembly = Assembly.GetExecutingAssembly(); #if !CF Stream stream = executingAssembly.GetManifestResourceStream("MySql.Data.MySqlClient.Tests.Properties.Setup.sql"); #else Stream stream = executingAssembly.GetManifestResourceStream("MySql.Data.CF.Tests.Properties.Setup.sql"); #endif StreamReader sr = new StreamReader(stream); string sql = sr.ReadToEnd(); sr.Close(); SetAccountPerms(accessToMySqlDb); sql = sql.Replace("[database0]", database0); sql = sql.Replace("[database1]", database1); ExecuteSQLAsRoot(sql); Open(); numProcessesRunning = CountProcesses(); } protected void ExecuteSQLAsRoot(string sql) { MySqlScript s = new MySqlScript(rootConn, sql); s.Execute(); } [TearDown] public virtual void Teardown() { // wait up to 5 seconds for our connection to close int procs = CountProcesses(); for (int x = 0; x < 50; x++) { if (procs == numProcessesRunning) break; System.Threading.Thread.Sleep(100); procs = CountProcesses(); } Assert.AreEqual(numProcessesRunning, procs, "Too many processes still running"); conn.Close(); if (Version.Major < 5) suExecSQL("REVOKE ALL PRIVILEGES, GRANT OPTION FROM 'test'"); else suExecSQL("DROP USER 'test'@'localhost'"); DropDatabase(database0); DropDatabase(database1); } private void DropDatabase(string name) { for (int i = 0; i < 5; i++) { try { suExecSQL(String.Format("DROP DATABASE IF EXISTS `{0}`", name)); return; } catch (Exception) { System.Threading.Thread.Sleep(1000); } } Assert.Fail("Unable to drop database " + name); } protected void KillConnection(MySqlConnection c) { int threadId = c.ServerThread; MySqlCommand cmd = new MySqlCommand("KILL " + threadId, conn); cmd.ExecuteNonQuery(); // the kill flag might need a little prodding to do its thing try { cmd.CommandText = "SELECT 1"; cmd.Connection = c; cmd.ExecuteNonQuery(); } catch (Exception) { } // now wait till the process dies bool processStillAlive = false; while (true) { MySqlDataAdapter da = new MySqlDataAdapter("SHOW PROCESSLIST", conn); DataTable dt = new DataTable(); da.Fill(dt); foreach (DataRow row in dt.Rows) if (row["Id"].Equals(threadId)) processStillAlive = true; if (!processStillAlive) break; System.Threading.Thread.Sleep(500); } } protected void KillPooledConnection(string connStr) { MySqlConnection c = new MySqlConnection(connStr); c.Open(); KillConnection(c); } protected void createTable(string sql, string engine) { if (Version >= new Version(4,1)) sql += " ENGINE=" + engine; else sql += " TYPE=" + engine; execSQL(sql); } protected void suExecSQL(string sql) { Debug.Assert(rootConn != null); MySqlCommand cmd = new MySqlCommand(sql, rootConn); cmd.ExecuteNonQuery(); } protected void execSQL(string sql) { MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.ExecuteNonQuery(); } protected IDataReader execReader(string sql) { MySqlCommand cmd = new MySqlCommand(sql, conn); return cmd.ExecuteReader(); } protected int CountProcesses() { MySqlDataAdapter da = new MySqlDataAdapter("SHOW PROCESSLIST", rootConn); DataTable dt = new DataTable(); da.Fill(dt); return dt.Rows.Count; } protected bool TableExists(string tableName) { string[] restrictions = new string[4]; restrictions[2] = tableName; DataTable dt = conn.GetSchema("Tables", restrictions); return dt.Rows.Count > 0; } protected DataTable FillTable(string sql) { MySqlDataAdapter da = new MySqlDataAdapter(sql, conn); DataTable dt = new DataTable(); da.Fill(dt); return dt; } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/SqlServerMode.cs0000644000175000017500000000403711127003600025361 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for BlobTests. /// [TestFixture] public class SqlServerMode : BaseTest { public SqlServerMode() { csAdditions += ";sqlservermode=yes;"; } [Test] public void Simple() { execSQL("CREATE TABLE Test (id INT, name VARCHAR(20))"); execSQL("INSERT INTO Test VALUES (1, 'A')"); MySqlCommand cmd = new MySqlCommand("SELECT [id], [name] FROM [Test]", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual(1, reader.GetInt32(0)); Assert.AreEqual("A", reader.GetString(1)); } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/Logging.cs0000644000175000017500000001374011127003600024215 0ustar directhexdirecthex// Copyright (c) 2009-2010 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Diagnostics; using NUnit.Framework; using System.Text; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class LoggingTests : BaseTest { public LoggingTests() { csAdditions = ";logging=true;"; } public override void Setup() { base.Setup(); createTable("CREATE TABLE Test (id int, name VARCHAR(200))", "INNODB"); } [Test] public void SimpleLogging() { execSQL("INSERT INTO Test VALUES (1, 'Test1')"); execSQL("INSERT INTO Test VALUES (2, 'Test2')"); execSQL("INSERT INTO Test VALUES (3, 'Test3')"); execSQL("INSERT INTO Test VALUES (4, 'Test4')"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { } Assert.AreEqual(4, listener.Strings.Count); Assert.IsTrue(listener.Strings[0].Contains("Query Opened: SELECT * FROM Test")); Assert.IsTrue(listener.Strings[1].Contains("Resultset Opened: field(s) = 2, affected rows = -1, inserted id = -1")); Assert.IsTrue(listener.Strings[2].Contains("Resultset Closed. Total rows=4, skipped rows=4, size (bytes)=32")); Assert.IsTrue(listener.Strings[3].Contains("Query Closed")); } [Test] public void Warnings() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test(id INT, name VARCHAR(5))"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); MySqlCommand cmd = new MySqlCommand("INSERT IGNORE INTO Test VALUES (1, 'abcdef')", conn); cmd.ExecuteNonQuery(); Assert.AreEqual(9, listener.Strings.Count); Assert.IsTrue(listener.Strings[0].Contains("Query Opened: INSERT IGNORE INTO Test VALUES (1, 'abcdef')")); Assert.IsTrue(listener.Strings[1].Contains("Resultset Opened: field(s) = 0, affected rows = 1, inserted id = 0")); Assert.IsTrue(listener.Strings[2].Contains("Resultset Closed. Total rows=0, skipped rows=0, size (bytes)=0")); Assert.IsTrue(listener.Strings[3].Contains("Query Opened: SHOW WARNINGS")); Assert.IsTrue(listener.Strings[4].Contains("Resultset Opened: field(s) = 3, affected rows = -1, inserted id = -1")); Assert.IsTrue(listener.Strings[5].Contains("Resultset Closed. Total rows=1, skipped rows=0, size (bytes)=55")); Assert.IsTrue(listener.Strings[6].Contains("Query Closed")); Assert.IsTrue(listener.Strings[7].Contains("MySql Warning: Level=Warning, Code=1265, Message=Data truncated for column 'name' at row 1")); Assert.IsTrue(listener.Strings[8].Contains("Query Closed")); } [Test] public void ProviderNormalizingQuery() { MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); StringBuilder sql = new StringBuilder("SELECT '"); for (int i=0; i < 400; i++) sql.Append("a"); sql.Append("'"); MySqlCommand cmd = new MySqlCommand(sql.ToString(), conn); cmd.ExecuteNonQuery(); Assert.AreEqual(5, listener.Strings.Count); Assert.IsTrue(listener.Strings[1].EndsWith("SELECT ?")); } /// /// Bug #57641 Substring out of range exception in ConsumeQuotedToken /// [Test] public void QuotedTokenAt300() { MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); string sql = @"SELECT 1 AS `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA1`, 2 AS `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2`, 3 AS `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3`, 4 AS `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA4`, 5 AS `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA5`, 6 AS `AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA6`;"; MySqlCommand cmd = new MySqlCommand(sql, conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/ProcedureParameters.cs0000644000175000017500000005004711127003600026604 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class ProcedureParameterTests : BaseTest { [Test] public void ProcedureParameters() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest (id int, name varchar(50)) BEGIN SELECT 1; END"); string[] restrictions = new string[5]; restrictions[1] = database0; restrictions[2] = "spTest"; DataTable dt = conn.GetSchema("Procedure Parameters", restrictions); Assert.IsTrue(dt.Rows.Count == 2); Assert.AreEqual("Procedure Parameters", dt.TableName); Assert.AreEqual(database0.ToLower(), dt.Rows[0]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[0]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("id", dt.Rows[0]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(1, dt.Rows[0]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[0]["PARAMETER_MODE"]); restrictions[4] = "name"; dt.Clear(); dt = conn.GetSchema("Procedure Parameters", restrictions); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(database0.ToLower(), dt.Rows[0]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[0]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("name", dt.Rows[0]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(2, dt.Rows[0]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[0]["PARAMETER_MODE"]); execSQL("DROP FUNCTION IF EXISTS spFunc"); execSQL("CREATE FUNCTION spFunc (id int) RETURNS INT BEGIN RETURN 1; END"); restrictions[4] = null; restrictions[1] = database0; restrictions[2] = "spFunc"; dt = conn.GetSchema("Procedure Parameters", restrictions); Assert.IsTrue(dt.Rows.Count == 2); Assert.AreEqual("Procedure Parameters", dt.TableName); Assert.AreEqual(database0.ToLower(), dt.Rows[0]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("spfunc", dt.Rows[0]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual(0, dt.Rows[0]["ORDINAL_POSITION"]); Assert.AreEqual(database0.ToLower(), dt.Rows[1]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("spfunc", dt.Rows[1]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("id", dt.Rows[1]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(1, dt.Rows[1]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[1]["PARAMETER_MODE"]); } /// /// Bug #6902 Errors in parsing stored procedure parameters /// [Test] public void ProcedureParameters2() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE PROCEDURE spTest(`/*id*/` /* before type 1 */ varchar(20), /* after type 1 */ OUT result2 DECIMAL(/*size1*/10,/*size2*/2) /* p2 */) BEGIN SELECT action, result; END"); string[] restrictions = new string[5]; restrictions[1] = database0; restrictions[2] = "spTest"; DataTable dt = conn.GetSchema("Procedure Parameters", restrictions); Assert.IsTrue(dt.Rows.Count == 2); Assert.AreEqual(database0.ToLower(), dt.Rows[0]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[0]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("/*id*/", dt.Rows[0]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(1, dt.Rows[0]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[0]["PARAMETER_MODE"]); Assert.AreEqual("VARCHAR", dt.Rows[0]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(20, dt.Rows[0]["CHARACTER_MAXIMUM_LENGTH"]); Assert.AreEqual(20, dt.Rows[0]["CHARACTER_OCTET_LENGTH"]); Assert.AreEqual(database0.ToLower(), dt.Rows[1]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[1]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("result2", dt.Rows[1]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(2, dt.Rows[1]["ORDINAL_POSITION"]); Assert.AreEqual("OUT", dt.Rows[1]["PARAMETER_MODE"]); Assert.AreEqual("DECIMAL", dt.Rows[1]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(10, dt.Rows[1]["NUMERIC_PRECISION"]); Assert.AreEqual(2, dt.Rows[1]["NUMERIC_SCALE"]); } [Test] public void ProcedureParameters3() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE PROCEDURE spTest (_ACTION varchar(20), `/*dumb-identifier-1*/` int, `#dumb-identifier-2` int, `--dumb-identifier-3` int, _CLIENT_ID int, -- ABC _LOGIN_ID int, # DEF _WHERE varchar(2000), _SORT varchar(2000), out _SQL varchar(/* inline right here - oh my gosh! */ 8000), _SONG_ID int, _NOTES varchar(2000), out _RESULT varchar(10) /* , -- Generic result parameter out _PERIOD_ID int, -- Returns the period_id. Useful when using @PREDEFLINK to return which is the last period _SONGS_LIST varchar(8000), _COMPOSERID int, _PUBLISHERID int, _PREDEFLINK int -- If the user is accessing through a predefined link: 0=none 1=last period */) BEGIN SELECT 1; END"); string[] restrictions = new string[5]; restrictions[1] = database0; restrictions[2] = "spTest"; DataTable dt = conn.GetSchema("Procedure Parameters", restrictions); Assert.IsTrue(dt.Rows.Count == 12); Assert.AreEqual(database0.ToLower(), dt.Rows[0]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[0]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("_action", dt.Rows[0]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(1, dt.Rows[0]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[0]["PARAMETER_MODE"]); Assert.AreEqual("VARCHAR", dt.Rows[0]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(20, dt.Rows[0]["CHARACTER_OCTET_LENGTH"]); Assert.AreEqual(database0.ToLower(), dt.Rows[1]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[1]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("/*dumb-identifier-1*/", dt.Rows[1]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(2, dt.Rows[1]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[1]["PARAMETER_MODE"]); Assert.AreEqual("INT", dt.Rows[1]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(database0.ToLower(), dt.Rows[2]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[2]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("#dumb-identifier-2", dt.Rows[2]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(3, dt.Rows[2]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[2]["PARAMETER_MODE"]); Assert.AreEqual("INT", dt.Rows[2]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(database0.ToLower(), dt.Rows[3]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[3]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("--dumb-identifier-3", dt.Rows[3]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(4, dt.Rows[3]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[3]["PARAMETER_MODE"]); Assert.AreEqual("INT", dt.Rows[3]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(database0.ToLower(), dt.Rows[4]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[4]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("_client_id", dt.Rows[4]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(5, dt.Rows[4]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[4]["PARAMETER_MODE"]); Assert.AreEqual("INT", dt.Rows[4]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(database0.ToLower(), dt.Rows[5]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[5]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("_login_id", dt.Rows[5]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(6, dt.Rows[5]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[5]["PARAMETER_MODE"]); Assert.AreEqual("INT", dt.Rows[5]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(database0.ToLower(), dt.Rows[6]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[6]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("_where", dt.Rows[6]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(7, dt.Rows[6]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[6]["PARAMETER_MODE"]); Assert.AreEqual("VARCHAR", dt.Rows[6]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(2000, dt.Rows[6]["CHARACTER_OCTET_LENGTH"]); Assert.AreEqual(database0.ToLower(), dt.Rows[7]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[7]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("_sort", dt.Rows[7]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(8, dt.Rows[7]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[7]["PARAMETER_MODE"]); Assert.AreEqual("VARCHAR", dt.Rows[7]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(2000, dt.Rows[7]["CHARACTER_OCTET_LENGTH"]); Assert.AreEqual(database0.ToLower(), dt.Rows[8]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[8]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("_sql", dt.Rows[8]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(9, dt.Rows[8]["ORDINAL_POSITION"]); Assert.AreEqual("OUT", dt.Rows[8]["PARAMETER_MODE"]); Assert.AreEqual("VARCHAR", dt.Rows[8]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(8000, dt.Rows[8]["CHARACTER_OCTET_LENGTH"]); Assert.AreEqual(database0.ToLower(), dt.Rows[9]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[9]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("_song_id", dt.Rows[9]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(10, dt.Rows[9]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[9]["PARAMETER_MODE"]); Assert.AreEqual("INT", dt.Rows[9]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(database0.ToLower(), dt.Rows[10]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[10]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("_notes", dt.Rows[10]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(11, dt.Rows[10]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[10]["PARAMETER_MODE"]); Assert.AreEqual("VARCHAR", dt.Rows[10]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(2000, dt.Rows[10]["CHARACTER_OCTET_LENGTH"]); Assert.AreEqual(database0.ToLower(), dt.Rows[11]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[11]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("_result", dt.Rows[11]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(12, dt.Rows[11]["ORDINAL_POSITION"]); Assert.AreEqual("OUT", dt.Rows[11]["PARAMETER_MODE"]); Assert.AreEqual("VARCHAR", dt.Rows[11]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(10, dt.Rows[11]["CHARACTER_OCTET_LENGTH"]); } [Test] public void ProcedureParameters4() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE PROCEDURE spTest (name VARCHAR(1200) CHARACTER /* hello*/ SET utf8) BEGIN SELECT name; END"); string[] restrictions = new string[5]; restrictions[1] = database0; restrictions[2] = "spTest"; DataTable dt = conn.GetSchema("Procedure Parameters", restrictions); Assert.IsTrue(dt.Rows.Count == 1); Assert.AreEqual(database0.ToLower(), dt.Rows[0]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[0]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("name", dt.Rows[0]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(1, dt.Rows[0]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[0]["PARAMETER_MODE"]); Assert.AreEqual("VARCHAR", dt.Rows[0]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual(1200, dt.Rows[0]["CHARACTER_MAXIMUM_LENGTH"]); if (Version.Major >= 6) Assert.AreEqual(4800, dt.Rows[0]["CHARACTER_OCTET_LENGTH"]); else Assert.AreEqual(3600, dt.Rows[0]["CHARACTER_OCTET_LENGTH"]); Assert.AreEqual("utf8", dt.Rows[0]["CHARACTER_SET_NAME"]); Assert.AreEqual("utf8_general_ci", dt.Rows[0]["COLLATION_NAME"]); } [Test] public void ProcedureParameters5() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE PROCEDURE spTest (name VARCHAR(1200) ASCII BINARY, name2 TEXT UNICODE) BEGIN SELECT name; END"); string[] restrictions = new string[5]; restrictions[1] = database0; restrictions[2] = "spTest"; DataTable dt = conn.GetSchema("Procedure Parameters", restrictions); Assert.IsTrue(dt.Rows.Count == 2); Assert.AreEqual(database0.ToLower(), dt.Rows[0]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[0]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("name", dt.Rows[0]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(1, dt.Rows[0]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[0]["PARAMETER_MODE"]); Assert.AreEqual("VARCHAR", dt.Rows[0]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual("latin1", dt.Rows[0]["CHARACTER_SET_NAME"]); Assert.AreEqual(1200, dt.Rows[0]["CHARACTER_OCTET_LENGTH"]); Assert.AreEqual(database0.ToLower(), dt.Rows[1]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[1]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("name2", dt.Rows[1]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(2, dt.Rows[1]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[1]["PARAMETER_MODE"]); Assert.AreEqual("TEXT", dt.Rows[1]["DATA_TYPE"].ToString().ToUpper()); Assert.AreEqual("ucs2", dt.Rows[1]["CHARACTER_SET_NAME"]); } [Test] public void DTD_Identifier() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE PROCEDURE spTest (id INT UNSIGNED ZEROFILL, dec1 DECIMAL(10,2), name VARCHAR(20) /* this is a comment */ CHARACTER SET ascii, t1 TINYTEXT BINARY, t2 ENUM('a','b','c'), t3 /* comment */ SET(/* comment */'1','2','3')) BEGIN SELECT name; END"); string[] restrictions = new string[5]; restrictions[1] = database0; restrictions[2] = "spTest"; DataTable dt = conn.GetSchema("Procedure Parameters", restrictions); Assert.IsTrue(dt.Rows.Count == 6); Assert.AreEqual("INT(10) UNSIGNED ZEROFILL", dt.Rows[0]["DTD_IDENTIFIER"].ToString().ToUpper()); Assert.AreEqual("DECIMAL(10,2)", dt.Rows[1]["DTD_IDENTIFIER"].ToString().ToUpper()); Assert.AreEqual("VARCHAR(20)", dt.Rows[2]["DTD_IDENTIFIER"].ToString().ToUpper()); Assert.AreEqual("TINYTEXT", dt.Rows[3]["DTD_IDENTIFIER"].ToString().ToUpper()); Assert.AreEqual("ENUM('A','B','C')", dt.Rows[4]["DTD_IDENTIFIER"].ToString().ToUpper()); Assert.AreEqual("SET('1','2','3')", dt.Rows[5]["DTD_IDENTIFIER"].ToString().ToUpper()); } /// /// Bug #48586 Expose defined possible enum values /// [Test] public void PossibleValues() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE PROCEDURE spTest (id INT UNSIGNED ZEROFILL, dec1 DECIMAL(10,2), name VARCHAR(20) /* this is a comment */ CHARACTER SET ascii, t1 TINYTEXT BINARY, t2 ENUM('a','b','c'), t3 /* comment */ SET(/* comment */'1','2','3')) BEGIN SELECT name; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; MySqlCommandBuilder.DeriveParameters(cmd); Assert.IsNull(cmd.Parameters["@id"].PossibleValues); Assert.IsNull(cmd.Parameters["@dec1"].PossibleValues); Assert.IsNull(cmd.Parameters["@name"].PossibleValues); Assert.IsNull(cmd.Parameters["@t1"].PossibleValues); MySqlParameter t2 = cmd.Parameters["@t2"]; Assert.IsNotNull(t2.PossibleValues); Assert.AreEqual("a", t2.PossibleValues[0]); Assert.AreEqual("b", t2.PossibleValues[1]); Assert.AreEqual("c", t2.PossibleValues[2]); MySqlParameter t3 = cmd.Parameters["@t3"]; Assert.IsNotNull(t3.PossibleValues); Assert.AreEqual("1", t3.PossibleValues[0]); Assert.AreEqual("2", t3.PossibleValues[1]); Assert.AreEqual("3", t3.PossibleValues[2]); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/PreparedStatements.cs0000644000175000017500000007743511127003600026454 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class PreparedStatements : BaseTest { public PreparedStatements() { csAdditions += ";ignore prepare=false;"; } [Test] public void Simple() { execSQL("CREATE TABLE Test (id INT, dec1 DECIMAL(5,2), name VARCHAR(100))"); execSQL("INSERT INTO Test VALUES (1, 345.12, 'abcd')"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(1,345.12,'abcd')", conn); cmd.Prepare(); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(1, reader.GetInt32(0)); Assert.AreEqual(345.12, reader.GetDecimal(1)); Assert.AreEqual("abcd", reader.GetString(2)); } } [Test] public void SimplePrepareBeforeParms() { execSQL("CREATE TABLE Test (one INTEGER, two INTEGER)"); execSQL("INSERT INTO Test VALUES (1, 2)"); // create the command and prepare the statement IDbCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * FROM Test WHERE one = ?p1"; // create the parameter IDbDataParameter p1 = cmd.CreateParameter(); p1.ParameterName = "?p1"; p1.DbType = DbType.Int32; p1.Precision = (byte)10; p1.Scale = (byte)0; p1.Size = 4; cmd.Parameters.Add(p1); p1.Value = 1; cmd.Prepare(); // Execute the reader using (IDataReader reader = cmd.ExecuteReader()) { // Fetch the first record reader.Read(); Assert.AreEqual(1, reader.GetInt32(0)); Assert.AreEqual(2, reader.GetInt32(1)); } } [Test] public void DateAndTimes() { execSQL("CREATE TABLE Test (id INT NOT NULL, d DATE, dt DATETIME, tm TIME, ts TIMESTAMP, PRIMARY KEY(id))"); string sql = "INSERT INTO Test VALUES(?id, ?d, ?dt, ?tm, NULL)"; MySqlCommand cmd = new MySqlCommand(sql, conn); DateTime dt = DateTime.Now; dt = dt.AddMilliseconds( dt.Millisecond * -1 ); TimeSpan ts = new TimeSpan( 8, 11, 44, 56, 501 ); cmd.Parameters.AddWithValue("?id", 1); cmd.Parameters.AddWithValue("?d", dt); cmd.Parameters.AddWithValue("?dt", dt); cmd.Parameters.AddWithValue("?tm", ts); cmd.Prepare(); int count = cmd.ExecuteNonQuery(); Assert.AreEqual(1, count, "Records affected by insert"); cmd.CommandText = "SELECT * FROM Test"; cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual(1, reader.GetInt32(0), "Id column"); Assert.AreEqual(dt.Date, reader.GetDateTime(1).Date, "Date column"); DateTime dt2 = reader.GetDateTime(2); Assert.AreEqual(dt.Date, dt2.Date); Assert.AreEqual(dt.Hour, dt2.Hour); Assert.AreEqual(dt.Minute, dt2.Minute); Assert.AreEqual(dt.Second, dt2.Second); TimeSpan ts2 = reader.GetTimeSpan(3); Assert.AreEqual(ts.Days, ts2.Days); Assert.AreEqual(ts.Hours, ts2.Hours); Assert.AreEqual(ts.Minutes, ts2.Minutes); Assert.AreEqual(ts.Seconds, ts2.Seconds); Assert.AreEqual(dt.Date, reader.GetDateTime(4).Date, "Timestamp column"); } } [Test] public void ResetCommandText() { execSQL("CREATE TABLE Test (id int, name varchar(100))"); execSQL("INSERT INTO Test VALUES (1, 'Test')"); MySqlCommand cmd = new MySqlCommand("SELECT id FROM Test", conn); cmd.Prepare(); object o = cmd.ExecuteScalar(); Assert.AreEqual( 1, o ); cmd.CommandText = "SELECT name FROM Test"; cmd.Prepare(); o = cmd.ExecuteScalar(); Assert.AreEqual( "Test", o ); } [Test] public void DifferentParameterOrder() { execSQL("CREATE TABLE Test (id int NOT NULL AUTO_INCREMENT, " + "id2 int NOT NULL, name varchar(50) DEFAULT NULL, " + "id3 int DEFAULT NULL, PRIMARY KEY (id))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, id2, name, id3) " + "VALUES(?id, ?id2, ?name,?id3)", conn); MySqlParameter id = new MySqlParameter(); id.ParameterName = "?id"; id.DbType = DbType.Int32; id.Value = DBNull.Value; MySqlParameter id2 = new MySqlParameter(); id2.ParameterName = "?id2"; id2.DbType = DbType.Int32; id2.Value = 2; MySqlParameter name = new MySqlParameter(); name.ParameterName = "?name"; name.DbType = DbType.String; name.Value = "Test"; MySqlParameter id3 = new MySqlParameter(); id3.ParameterName = "?id3"; id3.DbType = DbType.Int32; id3.Value = 3; cmd.Parameters.Add(id); cmd.Parameters.Add(id2); cmd.Parameters.Add(name); cmd.Parameters.Add(id3); cmd.Prepare(); Assert.AreEqual(1, cmd.ExecuteNonQuery()); cmd.Parameters.Clear(); id3.Value = DBNull.Value; name.Value = DBNull.Value; cmd.Parameters.Add(id); cmd.Parameters.Add(id2); cmd.Parameters.Add(id3); cmd.Parameters.Add(name); cmd.Prepare(); Assert.AreEqual(1, cmd.ExecuteNonQuery()); cmd.CommandText = "SELECT id3 FROM Test WHERE id=1"; Assert.AreEqual(3, cmd.ExecuteScalar()); cmd.CommandText = "SELECT name FROM Test WHERE id=2"; Assert.AreEqual(DBNull.Value, cmd.ExecuteScalar()); } [Test] public void Blobs() { execSQL("CREATE TABLE Test (id INT, blob1 LONGBLOB, text1 LONGTEXT)"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?blob1, ?text1)", conn); byte[] bytes = Utils.CreateBlob( 400000 ); string inStr = "This is my text"; cmd.Parameters.AddWithValue("?id", 1); cmd.Parameters.AddWithValue("?blob1", bytes); cmd.Parameters.AddWithValue("?text1", inStr); cmd.Prepare(); int count = cmd.ExecuteNonQuery(); Assert.AreEqual( 1, count ); cmd.CommandText = "SELECT * FROM Test"; cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue( reader.Read() ); Assert.AreEqual( 1, reader.GetInt32(0) ); Assert.AreEqual( bytes.Length, reader.GetBytes( 1, 0, null, 0, 0 )); byte[] outBytes = new byte[ bytes.Length ]; reader.GetBytes( 1, 0, outBytes, 0, bytes.Length ); for (int x=0; x < bytes.Length; x++) Assert.AreEqual( bytes[x], outBytes[x] ); Assert.AreEqual( inStr, reader.GetString( 2 ) ); } } [Test] public void SimpleTest2() { execSQL("CREATE TABLE Test (one integer, two integer, three integer, four integer, five integer, six integer, seven integer)"); execSQL("INSERT INTO Test VALUES (1, 2, 3, 4, 5, 6, 7)"); // create the command and prepare the statement IDbCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT one, two, three, four, five, six, seven FROM Test"; cmd.Prepare(); // Execute the reader using (IDataReader reader = cmd.ExecuteReader()) { // Fetch the first record reader.Read(); Assert.AreEqual( 1, reader.GetInt32(0) ); Assert.AreEqual( 2, reader.GetInt32(1) ); Assert.AreEqual( 3, reader.GetInt32(2) ); Assert.AreEqual( 4, reader.GetInt32(3) ); Assert.AreEqual( 5, reader.GetInt32(4) ); Assert.AreEqual( 6, reader.GetInt32(5) ); Assert.AreEqual( 7, reader.GetInt32(6) ); } } [Test] public void Bug6271() { if (Version < new Version(4, 1)) return; // Create the table again execSQL("CREATE TABLE `Test2` (id INT unsigned NOT NULL auto_increment, " + "`xpDOSG_Name` text,`xpDOSG_Desc` text, `Avatar` MEDIUMBLOB, `dtAdded` DATETIME, `dtTime` TIMESTAMP, " + "PRIMARY KEY(id)) ENGINE=InnoDB DEFAULT CHARSET=latin1" ); string sql = "INSERT INTO `Test2` (`xpDOSG_Name`,`dtAdded`, `xpDOSG_Desc`,`Avatar`, `dtTime`) " + "VALUES(?name, ?dt, ?desc, ?Avatar, NULL)"; MySqlCommand cmd = new MySqlCommand(sql, conn); DateTime dt = DateTime.Now; dt = dt.AddMilliseconds(dt.Millisecond * -1); byte[] xpDOSG_Avatar = Utils.CreateBlob(13000); cmd.Parameters.AddWithValue("?name", "Ceci est un nom"); cmd.Parameters.AddWithValue("?desc", "Ceci est une description facile plantouiller"); cmd.Parameters.AddWithValue("?avatar",xpDOSG_Avatar); cmd.Parameters.AddWithValue("?dt", dt); cmd.Prepare(); int count = cmd.ExecuteNonQuery(); Assert.AreEqual(1, count); cmd.CommandText = "SELECT * FROM Test2"; using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual("Ceci est un nom", reader.GetString(1)); Assert.AreEqual(dt.ToString("G"), reader.GetDateTime(4).ToString("G")); Assert.AreEqual("Ceci est une description facile plantouiller", reader.GetString(2)); long len = reader.GetBytes(3, 0, null, 0, 0); Assert.AreEqual(xpDOSG_Avatar.Length, len); byte[] outBytes = new byte[len]; reader.GetBytes(3, 0, outBytes, 0, (int)len); for (int x=0; x < xpDOSG_Avatar.Length; x++) Assert.AreEqual(xpDOSG_Avatar[x], outBytes[x]); } } [Test] public void SimpleTest() { execSQL("CREATE TABLE Test (one integer, two integer )"); execSQL("INSERT INTO Test VALUES( 1, 2)"); // create the command and prepare the statement IDbCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT * FROM Test where one = ?p1"; // create the parameter IDbDataParameter p1 = cmd.CreateParameter(); p1.ParameterName = "?p1"; p1.DbType = DbType.Int32; p1.Precision = (byte)10; p1.Scale = (byte)0; p1.Size = 4; cmd.Parameters.Add(p1); // prepare the command cmd.Prepare(); // set the parameter value p1.Value = 1; // Execute the reader IDataReader reader = null; try { reader = cmd.ExecuteReader(); // Fetch the first record reader.Read(); } catch (Exception ex) { Assert.Fail( ex.Message ); } finally { if (reader != null) reader.Close(); } } /// /// Bug #13662 Prepare() truncates accented character input /// [Test] public void InsertAccentedCharacters() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (id INT UNSIGNED NOT NULL PRIMARY KEY " + "AUTO_INCREMENT, input TEXT NOT NULL) CHARACTER SET UTF8"); // COLLATE " + //"utf8_bin"); using (MySqlConnection conn2 = new MySqlConnection(GetConnectionString(true) + ";charset=utf8")) { conn2.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test(input) " + "VALUES (?input) ON DUPLICATE KEY UPDATE " + "id=LAST_INSERT_ID(id)", conn2); cmd.Parameters.Add(new MySqlParameter("?input", "")); cmd.Prepare(); cmd.Parameters[0].Value = "irache martnez@yahoo.es aol.com"; cmd.ExecuteNonQuery(); MySqlCommand cmd2 = new MySqlCommand("SELECT input FROM Test", conn2); Assert.AreEqual("irache martnez@yahoo.es aol.com", cmd2.ExecuteScalar()); } } /// /// Bug #13541 Prepare breaks if a parameter is used more than once /// [Test] public void UsingParametersTwice() { if (Version < new Version(4, 1)) return; execSQL(@"CREATE TABLE IF NOT EXISTS Test (input TEXT NOT NULL, UNIQUE (input(100)), state INT NOT NULL, score INT NOT NULL)"); MySqlCommand cmd = new MySqlCommand(@"Insert into Test (input, state, score) VALUES (?input, ?st, ?sc) ON DUPLICATE KEY UPDATE state=state|?st;", conn); cmd.Parameters.Add (new MySqlParameter("?input", "")); cmd.Parameters.Add (new MySqlParameter("?st", Convert.ToInt32(0))); cmd.Parameters.Add (new MySqlParameter("?sc", Convert.ToInt32(0))); cmd.Prepare(); cmd.Parameters["?input"].Value = "test"; cmd.Parameters["?st"].Value = 1; cmd.Parameters["?sc"].Value = 42; int result = cmd.ExecuteNonQuery(); Assert.AreEqual(1, result); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("test", dt.Rows[0]["input"]); Assert.AreEqual(1, dt.Rows[0]["state"]); Assert.AreEqual(42, dt.Rows[0]["score"]); } /// /// Bug #19261 Supplying Input Parameters /// [Test] public void MoreParametersOutOfOrder() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE `Test` (`BlackListID` int(11) NOT NULL auto_increment, " + "`SubscriberID` int(11) NOT NULL, `Phone` varchar(50) default NULL, " + "`ContactID` int(11) default NULL, " + "`AdminJunk` tinyint(1) NOT NULL default '0', " + "PRIMARY KEY (`BlackListID`), KEY `SubscriberID` (`SubscriberID`))"); IDbCommand cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO `Test`(`SubscriberID`,`Phone`,`ContactID`, " + "`AdminJunk`) VALUES (?SubscriberID,?Phone,?ContactID, ?AdminJunk);"; MySqlParameter oParameterSubscriberID = new MySqlParameter(); oParameterSubscriberID.ParameterName = "?SubscriberID"; oParameterSubscriberID.DbType = DbType.Int32; oParameterSubscriberID.Value = 1; MySqlParameter oParameterPhone = new MySqlParameter(); oParameterPhone.ParameterName = "?Phone"; oParameterPhone.DbType = DbType.String; oParameterPhone.Value = DBNull.Value; MySqlParameter oParameterContactID = new MySqlParameter(); oParameterContactID.ParameterName = "?ContactID"; oParameterContactID.DbType = DbType.Int32; oParameterContactID.Value = DBNull.Value; MySqlParameter oParameterAdminJunk = new MySqlParameter(); oParameterAdminJunk.ParameterName = "?AdminJunk"; oParameterAdminJunk.DbType = DbType.Boolean; oParameterAdminJunk.Value = true; cmd.Parameters.Add(oParameterSubscriberID); cmd.Parameters.Add(oParameterPhone); cmd.Parameters.Add(oParameterAdminJunk); cmd.Parameters.Add(oParameterContactID); cmd.Prepare(); int cnt = cmd.ExecuteNonQuery(); Assert.AreEqual(1, cnt); } /// /// Bug #16627 Index and length must refer to a location within the string." when executing c /// [Test] public void ParameterLengths() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (id int, name VARCHAR(255))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?name)", conn); cmd.Parameters.Add("?id", MySqlDbType.Int32); cmd.Parameters.Add("?name", MySqlDbType.VarChar); cmd.Parameters[1].Size = 255; cmd.Prepare(); cmd.Parameters[0].Value = 1; cmd.Parameters[1].Value = "short string"; cmd.ExecuteNonQuery(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(1, dt.Rows[0]["id"]); Assert.AreEqual("short string", dt.Rows[0]["name"]); } /// /// Bug #18570 Unsigned tinyint (NET byte) incorrectly determined param type from param val /// [Test] public void UnsignedTinyInt() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test(ID TINYINT UNSIGNED NOT NULL, " + "Name VARCHAR(50) NOT NULL, PRIMARY KEY (ID), UNIQUE (ID), " + "UNIQUE (Name))"); execSQL("INSERT INTO Test VALUES ('127', 'name1')"); execSQL("INSERT INTO Test VALUES ('128', 'name2')"); execSQL("INSERT INTO Test VALUES ('255', 'name3')"); string sql = " SELECT count(*) FROM Test WHERE ID = ?id"; MySqlCommand command = new MySqlCommand(); command.CommandText = sql; command.CommandType = CommandType.Text; command.Connection = (MySqlConnection)conn; command.Parameters.AddWithValue("?id", (byte)127); command.Prepare(); object count = command.ExecuteScalar(); Assert.AreEqual(1, count); command.Parameters.Clear(); command.Parameters.AddWithValue("?id", (byte)128); count = command.ExecuteScalar(); Assert.AreEqual(1, count); command.Parameters.Clear(); command.Parameters.AddWithValue("?id", (byte)255); count = command.ExecuteScalar(); Assert.AreEqual(1, count); command.Parameters.Clear(); command.Parameters.AddWithValue("?id", "255"); count = command.ExecuteScalar(); Assert.AreEqual(1, count); } /// /// Bug #16934 Unsigned values > 2^63 (UInt64) cannot be used in prepared statements /// [Test] public void UnsignedValues() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (ulVal BIGINT UNSIGNED, lVal INT UNSIGNED, " + "mVal MEDIUMINT UNSIGNED, sVal SMALLINT UNSIGNED)"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?ulVal, " + "?lVal, ?mVal, ?sVal)", conn); cmd.Parameters.Add("?ulVal", MySqlDbType.UInt64); cmd.Parameters.Add("?lVal", MySqlDbType.UInt32); cmd.Parameters.Add("?mVal", MySqlDbType.UInt24); cmd.Parameters.Add("?sVal", MySqlDbType.UInt16); cmd.Prepare(); cmd.Parameters[0].Value = UInt64.MaxValue; cmd.Parameters[1].Value = UInt32.MaxValue; cmd.Parameters[2].Value = 16777215; cmd.Parameters[3].Value = UInt16.MaxValue; Assert.AreEqual(1, cmd.ExecuteNonQuery()); cmd.CommandText = "SELECT * FROM Test"; cmd.CommandType = CommandType.Text; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual(UInt64.MaxValue, reader.GetUInt64(0)); Assert.AreEqual(UInt32.MaxValue, reader.GetUInt32(1)); Assert.AreEqual(16777215, reader.GetUInt32(2)); Assert.AreEqual(UInt16.MaxValue, reader.GetUInt16(3)); } } /// /// Bug #18391 Better error handling for the .NET class "MySqlCommand" needed. /// [Test] public void PrepareEmptyString() { try { MySqlCommand cmd = new MySqlCommand("", conn); cmd.Prepare(); cmd.ExecuteNonQuery(); Assert.Fail("Should not get here"); } catch (InvalidOperationException) { } } /// /// Bug #14115 Prepare() with compound statements breaks /// [Test] public void CompoundStatements() { execSQL("CREATE TABLE IF NOT EXISTS Test ("+ "id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT," + "test1 INT UNSIGNED, test2 INT UNSIGNED)"); try { MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO Test VALUES (NULL, ?t1, ?t2);" + "SELECT last_insert_id()"; cmd.Parameters.Add("?t1", MySqlDbType.Int32); cmd.Parameters.Add("?t2", MySqlDbType.Int32); cmd.Prepare(); Assert.Fail("Should not reach here"); } catch (Exception) { } } [Test] public void SchemaOnly() { execSQL("CREATE TABLE Test (id INT, name VARCHAR(50))"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly)) { reader.Read(); } } private int GetPreparedStatementCount() { MySqlCommand cmd = new MySqlCommand("SHOW GLOBAL STATUS LIKE 'Prepared%'", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string s = reader.GetString(1); return Int32.Parse(s); } } [Test] public void ClosingCommandsProperly() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE Test (id INT, name VARCHAR(50))"); string connStr = GetConnectionString(true) + ";ignore prepare=false"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); int initialCount = GetPreparedStatementCount(); for (int i = 0; i < 10; i++) { using (MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?name)", c)) { cmd.Parameters.Add("?id", MySqlDbType.Int32); cmd.Parameters.Add("?name", MySqlDbType.VarChar); cmd.Prepare(); cmd.Parameters[0].Value = i; cmd.Parameters[1].Value = "foobar"; cmd.ExecuteNonQuery(); } } c.Ping(); Assert.AreEqual(initialCount, GetPreparedStatementCount()); } } /// /// Bug #37968 Prepared statements byte/tinyint causes data corruption. /// [Test] public void InsertingUnsignedTinyInt() { execSQL("DROP TABLE IF EXISTS Test"); execSQL(@"CREATE TABLE Test(id TINYINT UNSIGNED NOT NULL, id2 INT UNSIGNED, id3 TINYINT UNSIGNED, id4 INT UNSIGNED NOT NULL)"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?id2, ?id3, ?id4)", conn); cmd.Parameters.Add("?id", MySqlDbType.UByte); cmd.Parameters.Add("?id2", MySqlDbType.UByte); cmd.Parameters.Add("?id3", MySqlDbType.UByte); cmd.Parameters.Add("?id4", MySqlDbType.UByte); cmd.Prepare(); cmd.Parameters[0].Value = 127; cmd.Parameters[1].Value = 1; cmd.Parameters[2].Value = 2; cmd.Parameters[3].Value = 3; cmd.ExecuteNonQuery(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(127, dt.Rows[0][0]); Assert.AreEqual(1, dt.Rows[0][1]); Assert.AreEqual(2, dt.Rows[0][2]); Assert.AreEqual(3, dt.Rows[0][3]); } /// /// Bug #39275 Inserting negative time value through the use of MySqlParameter throws exception /// Bug #39294 Reading negative time value greater than -01:00:00 return positive value /// [Test] public void NegativeTimePrepared() { NegativeTime(true); ReadNegativeTime(true); } /// /// Bug #39275 Inserting negative time value through the use of MySqlParameter throws exception /// Bug #39294 Reading negative time value greater than -01:00:00 return positive value /// [Test] public void NegativeTimeNonPrepared() { NegativeTime(false); ReadNegativeTime(false); } public void NegativeTime(bool prepared) { execSQL("DROP TABLE IF EXISTS Test"); execSQL(@"CREATE TABLE Test(id int, t time)"); MySqlCommand cmd = new MySqlCommand(@"INSERT INTO Test VALUES (1, @t)", conn); cmd.Parameters.Add("@t", MySqlDbType.Time); TimeSpan[] times = new TimeSpan[8] { new TimeSpan(-10, 0, 0), new TimeSpan(2, -5, 10, 20), new TimeSpan(20, -10, 10), new TimeSpan(0, -15, 25), new TimeSpan(-4, -10, 20, -10), new TimeSpan(3, 17, 23, 6), new TimeSpan(-1,-2,-3,-4), new TimeSpan(0,0,0,-15) }; if (prepared) cmd.Prepare(); foreach (TimeSpan ts in times) { cmd.Parameters[0].Value = ts; cmd.ExecuteNonQuery(); } cmd.CommandText = "SELECT * FROM Test"; cmd.Parameters.Clear(); using (MySqlDataReader reader = cmd.ExecuteReader()) { foreach (TimeSpan ts in times) { reader.Read(); TimeSpan t = reader.GetTimeSpan(1); Assert.AreEqual(ts, t); } } } private void ReadNegativeTime(bool prepared) { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test(id int, t time)"); execSQL("INSERT INTO Test VALUES (1, '-00:10:00')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); if (prepared) cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); TimeSpan ts = reader.GetTimeSpan(1); Assert.AreEqual(0, ts.Hours); Assert.AreEqual(-10, ts.Minutes); Assert.AreEqual(0, ts.Seconds); } } [Test] public void SprocOutputParams() { if (Version < new Version(6, 0, 8)) return; execSQL("CREATE PROCEDURE spTest(id INT, OUT age INT) BEGIN SET age=id; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.Parameters.Add("@id", MySqlDbType.Int32); cmd.Parameters.Add("@age", MySqlDbType.Int32).Direction = ParameterDirection.Output; cmd.CommandType = CommandType.StoredProcedure; cmd.Prepare(); cmd.Parameters[0].Value = 20; Assert.AreEqual(0, cmd.ExecuteNonQuery()); Assert.AreEqual(20, cmd.Parameters[1].Value); execSQL("DROP PROCEDURE IF EXISTS spTest"); execSQL("CREATE PROCEDURE spTest(id INT, OUT age INT) BEGIN SET age=age*2; END"); cmd.Parameters[0].Value = 1; cmd.Parameters[1].Value = 20; Assert.AreEqual(0, cmd.ExecuteNonQuery()); Assert.AreEqual(20, cmd.Parameters[1].Value); } [Test] public void SprocInputOutputParams() { if (Version < new Version(6, 0, 8)) return; execSQL("CREATE PROCEDURE spTest(id INT, INOUT age INT) BEGIN SET age=age*2; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.Parameters.Add("@id", MySqlDbType.Int32); cmd.Parameters.Add("@age", MySqlDbType.Int32).Direction = ParameterDirection.InputOutput; cmd.CommandType = CommandType.StoredProcedure; cmd.Prepare(); cmd.Parameters[0].Value = 1; cmd.Parameters[1].Value = 20; Assert.AreEqual(0, cmd.ExecuteNonQuery()); Assert.AreEqual(40, cmd.Parameters[1].Value); } /// /// Bug #49794 MySqlDataReader.GetUInt64 doesn't work for large BIGINT UNSIGNED /// [Test] public void BigIntUnsigned() { execSQL("DROP TABLE IF EXISTS test"); execSQL(@"CREATE TABLE test(id int(10) unsigned NOT NULL, testValue bigint(20) unsigned NOT NULL, PRIMARY KEY USING BTREE (Id)) ENGINE=InnoDB DEFAULT CHARSET=latin1"); execSQL("INSERT INTO test(Id,TestValue) VALUES(1, 3000000000)"); MySqlCommand cmd = new MySqlCommand("SELECT testValue FROM test WHERE id=@Id", conn); cmd.Parameters.Add("@id", MySqlDbType.UInt32); cmd.Prepare(); cmd.Parameters["@id"].Value = 1; using (MySqlDataReader rdr = cmd.ExecuteReader()) { rdr.Read(); UInt64 v = rdr.GetUInt64(0); Assert.AreEqual(3000000000, v); } } } #region Configs #if !CF [Category("Compressed")] public class PreparedStatementsSocketCompressed : PreparedStatements { protected override string GetConnectionInfo() { return String.Format("port={0};compress=true", port); } } [Category("Pipe")] public class PreparedStatementsPipe : PreparedStatements { protected override string GetConnectionInfo() { return String.Format("protocol=pipe;pipe name={0}", pipeName); } } [Category("Compressed")] [Category("Pipe")] public class PreparedStatementsPipeCompressed : PreparedStatements { protected override string GetConnectionInfo() { return String.Format("protocol=pipe;pipe name={0};compress=true", pipeName); } } [Category("SharedMemory")] public class PreparedStatementsSharedMemory : PreparedStatements { protected override string GetConnectionInfo() { return String.Format("protocol=memory; shared memory name={0}", memoryName); } } [Category("Compressed")] [Category("SharedMemory")] public class PreparedStatementsSharedMemoryCompressed : PreparedStatements { protected override string GetConnectionInfo() { return String.Format("protocol=memory; shared memory name={0};compress=true", memoryName); } } #endif #endregion } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/UsageAdvisor.cs0000644000175000017500000002563411127003600025230 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Diagnostics; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class UsageAdvisorTests : BaseTest { public UsageAdvisorTests() { csAdditions = ";Usage Advisor=true;"; } public override void Setup() { base.Setup(); createTable("CREATE TABLE Test (id int, name VARCHAR(200))", "INNODB"); } [Test] public void NotReadingEveryField() { execSQL("INSERT INTO Test VALUES (1, 'Test1')"); execSQL("INSERT INTO Test VALUES (2, 'Test2')"); execSQL("INSERT INTO Test VALUES (3, 'Test3')"); execSQL("INSERT INTO Test VALUES (4, 'Test4')"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); string sql = "SELECT * FROM Test; SELECT * FROM Test WHERE id > 2"; MySqlCommand cmd = new MySqlCommand(sql, conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); reader.GetInt32(0); // access the first field reader.Read(); Assert.IsTrue(reader.NextResult()); reader.Read(); Assert.AreEqual("Test3", reader.GetString(1)); Assert.IsFalse(reader.NextResult()); } Assert.AreEqual(12, listener.Strings.Count); Assert.IsTrue(listener.Strings[0].Contains("Query Opened: SELECT * FROM Test; SELECT * FROM Test WHERE id > 2")); Assert.IsTrue(listener.Strings[1].Contains("Resultset Opened: field(s) = 2, affected rows = -1, inserted id = -1")); Assert.IsTrue(listener.Strings[2].Contains("Usage Advisor Warning: Query does not use an index")); Assert.IsTrue(listener.Strings[3].Contains("Usage Advisor Warning: Skipped 2 rows. Consider a more focused query.")); Assert.IsTrue(listener.Strings[4].Contains("Usage Advisor Warning: The following columns were not accessed: name")); Assert.IsTrue(listener.Strings[5].Contains("Resultset Closed. Total rows=4, skipped rows=2, size (bytes)=32")); Assert.IsTrue(listener.Strings[6].Contains("Resultset Opened: field(s) = 2, affected rows = -1, inserted id = -1")); Assert.IsTrue(listener.Strings[7].Contains("Usage Advisor Warning: Query does not use an index")); Assert.IsTrue(listener.Strings[8].Contains("Usage Advisor Warning: Skipped 1 rows. Consider a more focused query.")); Assert.IsTrue(listener.Strings[9].Contains("Usage Advisor Warning: The following columns were not accessed: id")); Assert.IsTrue(listener.Strings[10].Contains("Resultset Closed. Total rows=2, skipped rows=1, size (bytes)=16")); Assert.IsTrue(listener.Strings[11].Contains("Query Closed")); } [Test] public void NotReadingEveryRow() { execSQL("INSERT INTO Test VALUES (1, 'Test1')"); execSQL("INSERT INTO Test VALUES (2, 'Test2')"); execSQL("INSERT INTO Test VALUES (3, 'Test3')"); execSQL("INSERT INTO Test VALUES (4, 'Test4')"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test; SELECT * FROM Test WHERE id > 2", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); reader.Read(); Assert.IsTrue(reader.NextResult()); reader.Read(); reader.Read(); Assert.IsFalse(reader.NextResult()); } Assert.AreEqual(11, listener.Strings.Count); Assert.IsTrue(listener.Strings[0].Contains("Query Opened: SELECT * FROM Test; SELECT * FROM Test WHERE id > 2")); Assert.IsTrue(listener.Strings[1].Contains("Resultset Opened: field(s) = 2, affected rows = -1, inserted id = -1")); Assert.IsTrue(listener.Strings[2].Contains("Usage Advisor Warning: Query does not use an index")); Assert.IsTrue(listener.Strings[3].Contains("Usage Advisor Warning: Skipped 2 rows. Consider a more focused query.")); Assert.IsTrue(listener.Strings[4].Contains("Usage Advisor Warning: The following columns were not accessed: id,name")); Assert.IsTrue(listener.Strings[5].Contains("Resultset Closed. Total rows=4, skipped rows=2, size (bytes)=32")); Assert.IsTrue(listener.Strings[6].Contains("Resultset Opened: field(s) = 2, affected rows = -1, inserted id = -1")); Assert.IsTrue(listener.Strings[7].Contains("Usage Advisor Warning: Query does not use an index")); Assert.IsTrue(listener.Strings[8].Contains("Usage Advisor Warning: The following columns were not accessed: id,name")); Assert.IsTrue(listener.Strings[9].Contains("Resultset Closed. Total rows=2, skipped rows=0, size (bytes)=16")); Assert.IsTrue(listener.Strings[10].Contains("Query Closed")); } [Test] public void FieldConversion() { execSQL("INSERT INTO Test VALUES (1, 'Test1')"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); short s = reader.GetInt16(0); long l = reader.GetInt64(0); string str = reader.GetString(1); } Assert.AreEqual(6, listener.Strings.Count); Assert.IsTrue(listener.Strings[0].Contains("Query Opened: SELECT * FROM Test")); Assert.IsTrue(listener.Strings[1].Contains("Resultset Opened: field(s) = 2, affected rows = -1, inserted id = -1")); Assert.IsTrue(listener.Strings[2].Contains("Usage Advisor Warning: Query does not use an index")); Assert.IsTrue(listener.Strings[3].Contains("Usage Advisor Warning: The field 'id' was converted to the following types: Int16,Int64")); Assert.IsTrue(listener.Strings[4].Contains("Resultset Closed. Total rows=1, skipped rows=0, size (bytes)=8")); Assert.IsTrue(listener.Strings[5].Contains("Query Closed")); } [Test] public void NoIndexUsed() { execSQL("INSERT INTO Test VALUES (1, 'Test1')"); execSQL("INSERT INTO Test VALUES (2, 'Test1')"); execSQL("INSERT INTO Test VALUES (3, 'Test1')"); execSQL("INSERT INTO Test VALUES (4, 'Test1')"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); MySqlCommand cmd = new MySqlCommand("SELECT name FROM Test WHERE id=3", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); } Assert.AreEqual(6, listener.Strings.Count); Assert.IsTrue(listener.Strings[0].Contains("Query Opened: SELECT name FROM Test WHERE id=3")); Assert.IsTrue(listener.Strings[1].Contains("Resultset Opened: field(s) = 1, affected rows = -1, inserted id = -1")); Assert.IsTrue(listener.Strings[2].Contains("Usage Advisor Warning: Query does not use an index")); Assert.IsTrue(listener.Strings[3].Contains("Usage Advisor Warning: The following columns were not accessed: name")); Assert.IsTrue(listener.Strings[4].Contains("Resultset Closed. Total rows=1, skipped rows=0, size (bytes)=6")); Assert.IsTrue(listener.Strings[5].Contains("Query Closed")); } [Test] public void BadIndexUsed() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test(id INT, name VARCHAR(20) PRIMARY KEY)"); execSQL("INSERT INTO Test VALUES (1, 'Test1')"); execSQL("INSERT INTO Test VALUES (2, 'Test2')"); execSQL("INSERT INTO Test VALUES (3, 'Test3')"); execSQL("INSERT INTO Test VALUES (4, 'Test4')"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); MySqlCommand cmd = new MySqlCommand("SELECT name FROM Test WHERE id=3", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); } Assert.AreEqual(6, listener.Strings.Count); Assert.IsTrue(listener.Strings[0].Contains("Query Opened: SELECT name FROM Test WHERE id=3")); Assert.IsTrue(listener.Strings[1].Contains("Resultset Opened: field(s) = 1, affected rows = -1, inserted id = -1")); Assert.IsTrue(listener.Strings[2].Contains("Usage Advisor Warning: Query does not use an index")); Assert.IsTrue(listener.Strings[3].Contains("Usage Advisor Warning: The following columns were not accessed: name")); Assert.IsTrue(listener.Strings[4].Contains("Resultset Closed. Total rows=1, skipped rows=0, size (bytes)=6")); Assert.IsTrue(listener.Strings[5].Contains("Query Closed")); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/TableCaching.cs0000644000175000017500000001362511127003600025135 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using NUnit.Framework; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class TableCaching : BaseTest { [Test] public void SimpleTableCaching() { execSQL("CREATE TABLE test (id INT, name VARCHAR(20), name2 VARCHAR(20))"); execSQL("INSERT INTO test VALUES (1, 'boo', 'hoo'), (2, 'first', 'last'), (3, 'fred', 'flintstone')"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); string connStr = GetConnectionString(true) + ";logging=true;table cache=true"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("test", c); cmd.CommandType = CommandType.TableDirect; ConsumeReader(cmd); // now run the query again but this time it shouldn't generate a call to the database ConsumeReader(cmd); } Assert.AreEqual(1, listener.Find("Resultset Opened: field(s) = 3")); } [Test] public void ConnectionStringExpiry() { execSQL("CREATE TABLE test3 (id INT, name VARCHAR(20), name2 VARCHAR(20))"); execSQL("INSERT INTO test3 VALUES (1, 'boo', 'hoo'), (2, 'first', 'last'), (3, 'fred', 'flintstone')"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); string connStr = GetConnectionString(true) + ";logging=true;table cache=true;default table cache age=1"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("test3", c); cmd.CommandType = CommandType.TableDirect; ConsumeReader(cmd); Thread.Sleep(1500); // now run the query again but this time it should generate a call to the database // since our next query is past the cache age of 1 second ConsumeReader(cmd); } Assert.AreEqual(2, listener.Find("Resultset Opened: field(s) = 3")); } [Test] public void SettingAgeOnCommand() { execSQL("CREATE TABLE test2 (id INT, name VARCHAR(20), name2 VARCHAR(20))"); execSQL("INSERT INTO test2 VALUES (1, 'boo', 'hoo'), (2, 'first', 'last'), (3, 'fred', 'flintstone')"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); string connStr = GetConnectionString(true) + ";logging=true;table cache=true;default table cache age=1"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("test2", c); cmd.CommandType = CommandType.TableDirect; cmd.CacheAge = 20; ConsumeReader(cmd); Thread.Sleep(1000); // now run the query again but this time it shouldn't generate a call to the database // since we have overriden the connection string cache age of 1 second and set it // to 20 seconds on our command ConsumeReader(cmd); } Assert.AreEqual(1, listener.Find("Resultset Opened: field(s) = 3")); } private void ConsumeReader(MySqlCommand cmd) { using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual(1, reader.GetInt32(0)); Assert.AreEqual("boo", reader.GetString(1)); Assert.AreEqual("hoo", reader.GetString(2)); reader.Read(); Assert.AreEqual(2, reader.GetInt32(0)); Assert.AreEqual("first", reader.GetString(1)); Assert.AreEqual("last", reader.GetString(2)); reader.Read(); Assert.AreEqual(3, reader.GetInt32(0)); Assert.AreEqual("fred", reader.GetString(1)); Assert.AreEqual("flintstone", reader.GetString(2)); Assert.IsFalse(reader.Read()); } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/DataReaderTests.cs0000644000175000017500000007057111127003600025653 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Diagnostics; using MySql.Data.MySqlClient; using MySql.Data.Types; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for ConnectionTests. /// [TestFixture] public class DataReaderTests : BaseTest { private void CreateDefaultTable() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(100), d DATE, dt DATETIME, b1 LONGBLOB, PRIMARY KEY(id))"); } [Test] public void TestMultipleResultsets() { CreateDefaultTable(); MySqlCommand cmd = new MySqlCommand("", conn); // insert 100 records cmd.CommandText = "INSERT INTO Test (id,name) VALUES (?id, 'test')"; cmd.Parameters.Add( new MySqlParameter("?id", 1)); for (int i=1; i <= 100; i++) { cmd.Parameters[0].Value = i; cmd.ExecuteNonQuery(); } // execute it one time cmd = new MySqlCommand("SELECT id FROM Test WHERE id<50; SELECT * FROM Test WHERE id >= 50;", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsNotNull(reader); Assert.AreEqual(true, reader.HasRows); Assert.IsTrue(reader.Read()); Assert.AreEqual(1, reader.FieldCount); Assert.IsTrue(reader.NextResult()); Assert.AreEqual(true, reader.HasRows); Assert.AreEqual(5, reader.FieldCount); } // now do it again using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsNotNull(reader); Assert.AreEqual(true, reader.HasRows); Assert.IsTrue(reader.Read()); Assert.AreEqual(1, reader.FieldCount); Assert.IsTrue(reader.NextResult()); Assert.AreEqual(true, reader.HasRows); Assert.AreEqual(5, reader.FieldCount); } } [Test] public void GetBytes() { CreateDefaultTable(); int len = 50000; byte[] bytes = Utils.CreateBlob(len); MySqlCommand cmd = new MySqlCommand( "INSERT INTO Test (id, name, b1) VALUES(1, 'Test', ?b1)", conn); cmd.Parameters.AddWithValue("?b1", bytes); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); long sizeBytes = reader.GetBytes(4, 0, null, 0, 0); Assert.AreEqual(len, sizeBytes); byte[] buff1 = new byte[len / 2]; byte[] buff2 = new byte[len - (len / 2)]; long buff1cnt = reader.GetBytes(4, 0, buff1, 0, len / 2); long buff2cnt = reader.GetBytes(4, buff1cnt, buff2, 0, buff2.Length); Assert.AreEqual(buff1.Length, buff1cnt); Assert.AreEqual(buff2.Length, buff2cnt); for (int i = 0; i < buff1.Length; i++) Assert.AreEqual(bytes[i], buff1[i]); for (int i = 0; i < buff2.Length; i++) Assert.AreEqual(bytes[buff1.Length + i], buff2[i]); } // now check with sequential access using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { Assert.IsTrue(reader.Read()); int mylen = len; byte[] buff = new byte[8192]; int startIndex = 0; while (mylen > 0) { int readLen = Math.Min(mylen, buff.Length); int retVal = (int)reader.GetBytes(4, startIndex, buff, 0, readLen); Assert.AreEqual(readLen, retVal); for (int i = 0; i < readLen; i++) Assert.AreEqual(bytes[startIndex + i], buff[i]); startIndex += readLen; mylen -= readLen; } } } [Test] public void TestSingleResultSetBehavior() { CreateDefaultTable(); execSQL("INSERT INTO Test (id, name, b1) VALUES (1, 'Test1', NULL)"); execSQL("INSERT INTO Test (id, name, b1) VALUES (2, 'Test1', NULL)"); MySqlCommand cmd = new MySqlCommand( "SELECT * FROM Test WHERE id=1; SELECT * FROM Test WHERE id=2", conn); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleResult)) { bool result = reader.Read(); Assert.AreEqual(true, result); result = reader.NextResult(); Assert.AreEqual(false, result); } } /// /// Bug #59989 MysqlDataReader.GetSchemaTable returns incorrect Values an types /// [Test] public void GetSchema() { string sql = @"CREATE TABLE test2(id INT UNSIGNED AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, name2 VARCHAR(40), fl FLOAT, dt DATETIME, `udec` DECIMAL(20,6) unsigned, `dec` DECIMAL(44,3), bt boolean, PRIMARY KEY(id))"; execSQL(sql); execSQL("INSERT INTO test2 VALUES(1,'Test', 'Test', 1.0, now(), 20.0, 12.324, True)"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM test2", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { DataTable dt = reader.GetSchemaTable(); Assert.AreEqual(true, dt.Rows[0]["IsAutoIncrement"], "Checking auto increment"); Assert.IsFalse((bool)dt.Rows[0]["IsUnique"], "Checking IsUnique"); Assert.IsTrue((bool)dt.Rows[0]["IsKey"]); Assert.AreEqual(false, dt.Rows[0]["AllowDBNull"], "Checking AllowDBNull"); Assert.AreEqual(false, dt.Rows[1]["AllowDBNull"], "Checking AllowDBNull"); Assert.AreEqual(255, dt.Rows[1]["ColumnSize"]); Assert.AreEqual(40, dt.Rows[2]["ColumnSize"]); // udec column Assert.AreEqual(21, dt.Rows[5]["ColumnSize"]); Assert.AreEqual(20, dt.Rows[5]["NumericPrecision"]); Assert.AreEqual(6, dt.Rows[5]["NumericScale"]); // dec column Assert.AreEqual(46, dt.Rows[6]["ColumnSize"]); Assert.AreEqual(44, dt.Rows[6]["NumericPrecision"]); Assert.AreEqual(3, dt.Rows[6]["NumericScale"]); } } [Test] public void CloseConnectionBehavior() { CreateDefaultTable(); execSQL("INSERT INTO Test(id,name) VALUES(1,'test')"); using (MySqlConnection c2 = new MySqlConnection(conn.ConnectionString)) { c2.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", c2); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { Assert.IsTrue(reader.Read()); reader.Close(); Assert.IsTrue(c2.State == ConnectionState.Closed); } } } [Test] public void SingleRowBehavior() { CreateDefaultTable(); execSQL("INSERT INTO Test(id,name) VALUES(1,'test1')"); execSQL("INSERT INTO Test(id,name) VALUES(2,'test2')"); execSQL("INSERT INTO Test(id,name) VALUES(3,'test3')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { Assert.IsTrue(reader.Read(), "First read"); Assert.IsFalse(reader.Read(), "Second read"); Assert.IsFalse(reader.NextResult(), "Trying NextResult"); } cmd.CommandText = "SELECT * FROM Test where id=1"; using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { Assert.IsTrue(reader.Read()); Assert.AreEqual("test1", reader.GetString(1)); Assert.IsFalse(reader.Read()); Assert.IsFalse(reader.NextResult()); } } [Test] public void SingleRowBehaviorWithLimit() { CreateDefaultTable(); execSQL("INSERT INTO Test(id,name) VALUES(1,'test1')"); execSQL("INSERT INTO Test(id,name) VALUES(2,'test2')"); execSQL("INSERT INTO Test(id,name) VALUES(3,'test3')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test LIMIT 2", conn); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { Assert.IsTrue(reader.Read(), "First read"); Assert.IsFalse(reader.Read(), "Second read"); Assert.IsFalse(reader.NextResult(), "Trying NextResult"); } using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { Assert.IsTrue(reader.Read(), "First read"); Assert.IsFalse(reader.Read(), "Second read"); Assert.IsFalse(reader.NextResult(), "Trying NextResult"); } using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { Assert.IsTrue(reader.Read(), "First read"); Assert.IsFalse(reader.Read(), "Second read"); Assert.IsFalse(reader.NextResult(), "Trying NextResult"); } } [Test] public void SimpleSingleRow() { CreateDefaultTable(); execSQL("INSERT INTO Test(id,name) VALUES(1,'test1')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read(), "First read"); Assert.AreEqual(1, reader.GetInt32(0)); Assert.AreEqual("test1", reader.GetString(1)); Assert.IsFalse(reader.Read(), "Second read"); Assert.IsFalse(reader.NextResult(), "Trying NextResult"); } } [Test] public void ConsecutiveNulls() { CreateDefaultTable(); execSQL("INSERT INTO Test (id, name, dt) VALUES (1, 'Test', NULL)"); execSQL("INSERT INTO Test (id, name, dt) VALUES (2, NULL, now())"); execSQL("INSERT INTO Test (id, name, dt) VALUES (3, 'Test2', NULL)"); MySqlCommand cmd = new MySqlCommand("SELECT id, name, dt FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual(1, reader.GetValue(0)); Assert.AreEqual("Test", reader.GetValue(1)); Assert.AreEqual("Test", reader.GetString(1)); Assert.AreEqual(DBNull.Value, reader.GetValue(2)); reader.Read(); Assert.AreEqual(2, reader.GetValue(0)); Assert.AreEqual(DBNull.Value, reader.GetValue(1)); try { reader.GetString(1); Assert.Fail("Should not get here"); } catch (Exception) { } Assert.IsFalse(reader.IsDBNull(2)); reader.Read(); Assert.AreEqual(3, reader.GetValue(0)); Assert.AreEqual("Test2", reader.GetValue(1)); Assert.AreEqual("Test2", reader.GetString(1)); Assert.AreEqual(DBNull.Value, reader.GetValue(2)); try { reader.GetMySqlDateTime(2); Assert.Fail("Should not get here"); } catch (Exception) { } Assert.IsFalse(reader.Read()); Assert.IsFalse(reader.NextResult()); } } [Test] public void HungDataReader() { MySqlCommand cmd = new MySqlCommand("USE `" + database0 + "`; SHOW TABLES", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { reader.GetString(0); } } } /// /// Added test for IsDBNull from bug# 7399 /// [Test] public void SequentialAccessBehavior() { CreateDefaultTable(); execSQL("INSERT INTO Test(id,name) VALUES(1,'test1')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { Assert.IsTrue(reader.Read()); Assert.IsFalse(reader.IsDBNull(0)); int i = reader.GetInt32(0); string s = reader.GetString(1); Assert.AreEqual(1, i); Assert.AreEqual("test1", s); // this next line should throw an exception try { i = reader.GetInt32(0); Assert.Fail("This line should not execute"); } catch (MySqlException) { } } } [Test] public void ReadingTextFields() { execSQL("CREATE TABLE Test (id int, t1 TEXT)"); execSQL("INSERT INTO Test VALUES (1, 'Text value')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string s = reader["t1"].ToString(); Assert.AreEqual( "Text value", s ); } } [Test] public void ReadingFieldsBeforeRead() { CreateDefaultTable(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { try { reader.GetInt32(0); } catch (MySqlException) { } } } [Test] public void GetChar() { CreateDefaultTable(); execSQL("INSERT INTO Test (id, name) VALUES (1, 'a')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); char achar = reader.GetChar( 1 ); Assert.AreEqual( 'a', achar ); } } [Test] public void ReaderOnNonQuery() { CreateDefaultTable(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id,name) VALUES (1,'Test')", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsFalse( reader.Read() ); reader.Close(); cmd.CommandText = "SELECT name FROM Test"; object v = cmd.ExecuteScalar(); Assert.AreEqual( "Test", v ); } } [Test] public void TestManyDifferentResultsets() { CreateDefaultTable(); MySqlCommand cmd = new MySqlCommand("", conn); // insert 100 records cmd.CommandText = "INSERT INTO Test (id,name,dt,b1) VALUES (?id, 'test','2004-12-05 12:57:00','long blob data')"; cmd.Parameters.Add( new MySqlParameter("?id", 1)); for (int i=1; i <= 100; i++) { cmd.Parameters[0].Value = i; cmd.ExecuteNonQuery(); } cmd = new MySqlCommand("SELECT id FROM Test WHERE id= ?param1; "+ "SELECT id, dt, b1 FROM Test WHERE id = -50; "+ "SELECT b1 FROM Test WHERE id = -50; "+ "SELECT id, dt, b1 FROM Test WHERE id < ?param1; "+ "SELECT b1 FROM Test WHERE id >= ?param1;", conn); cmd.Parameters.AddWithValue("?param1",50); using (MySqlDataReader reader = cmd.ExecuteReader()) { //First ResultSet, should have 49 rows. //SELECT id FROM Test WHERE id= ?param1; Assert.IsTrue(reader.NextResult()); Assert.AreEqual(true, reader.HasRows); Assert.AreEqual(5, reader.FieldCount); for (int i = 0; i < 51; i++) { Assert.IsTrue(reader.Read()); } Assert.AreEqual(false, reader.Read()); //Fourth ResultSet, should have no rows. //SELECT id, dt, b1 FROM Test WHERE id = -50; Assert.IsTrue(reader.NextResult()); Assert.AreEqual(false, reader.HasRows); Assert.AreEqual(3, reader.FieldCount); //Will Fail if uncommented expected 3 returned 5 Assert.AreEqual(false, reader.Read()); //Fifth ResultSet, should have no rows. //SELECT b1 FROM Test WHERE id = -50; Assert.IsTrue(reader.NextResult()); Assert.AreEqual(false, reader.HasRows); Assert.AreEqual(1, reader.FieldCount); //Will Fail if uncommented expected 1 returned 5 Assert.AreEqual(false, reader.Read()); //Sixth ResultSet, should have 49 rows. //SELECT id, dt, b1 FROM Test WHERE id < ?param1; Assert.IsTrue(reader.NextResult()); Assert.AreEqual(true, reader.HasRows); Assert.AreEqual(3, reader.FieldCount); //Will Fail if uncommented expected 3 returned 5 for (int i = 0; i < 49; i++) { Assert.IsTrue(reader.Read()); } Assert.AreEqual(false, reader.Read()); //Seventh ResultSet, should have 51 rows. //SELECT b1 FROM Test WHERE id >= ?param1; Assert.IsTrue(reader.NextResult()); Assert.AreEqual(true, reader.HasRows); Assert.AreEqual(1, reader.FieldCount); //Will Fail if uncommented expected 1 returned 5 for (int i = 0; i < 51; i++) { Assert.IsTrue(reader.Read()); } Assert.AreEqual(false, reader.Read()); } } [Test] public void TestMultipleResultsWithQueryCacheOn() { CreateDefaultTable(); execSQL("SET SESSION query_cache_type = ON"); execSQL("INSERT INTO Test (id,name) VALUES (1, 'Test')"); execSQL("INSERT INTO Test (id,name) VALUES (51, 'Test')"); // execute it one time MySqlCommand cmd = new MySqlCommand("SELECT id FROM Test WHERE id<50; SELECT * FROM Test WHERE id >= 50;", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsNotNull(reader); Assert.AreEqual(true, reader.HasRows); Assert.IsTrue(reader.Read()); Assert.AreEqual(1, reader.FieldCount); Assert.IsTrue(reader.NextResult()); Assert.AreEqual(true, reader.HasRows); Assert.AreEqual(5, reader.FieldCount); } // now do it again using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsNotNull(reader); Assert.AreEqual(true, reader.HasRows); Assert.IsTrue(reader.Read()); Assert.AreEqual(1, reader.FieldCount); Assert.IsTrue(reader.NextResult()); Assert.AreEqual(true, reader.HasRows); Assert.AreEqual(5, reader.FieldCount); } } /// /// Bug #8630 Executing a query with the SchemaOnly option reads the entire resultset /// [Test] public void SchemaOnly() { CreateDefaultTable(); execSQL("INSERT INTO Test (id,name) VALUES(1,'test1')"); execSQL("INSERT INTO Test (id,name) VALUES(2,'test2')"); execSQL("INSERT INTO Test (id,name) VALUES(3,'test3')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly)) { DataTable table = reader.GetSchemaTable(); Assert.AreEqual(5, table.Rows.Count); Assert.AreEqual(22, table.Columns.Count); Assert.IsFalse(reader.Read()); } } /// /// Bug #9237 MySqlDataReader.AffectedRecords not set to -1 /// [Test] public void AffectedRows() { MySqlCommand cmd = new MySqlCommand("SHOW TABLES", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); reader.Close(); Assert.AreEqual(-1, reader.RecordsAffected); } } /// /// Bug #11873 Invalid timestamp in query produces incorrect reader exception /// [Test] public void InvalidTimestamp() { execSQL("CREATE TABLE Test (tm TIMESTAMP)"); execSQL("INSERT INTO Test VALUES (NULL)"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test WHERE tm = '7/1/2005 12:00:00 AM'", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { } } /// /// Bug #19294 IDataRecord.GetString method should return null for null values /// [Test] public void GetStringOnNull() { execSQL("CREATE TABLE Test (id int, PRIMARY KEY(id))"); MySqlCommand cmd = new MySqlCommand( String.Format("SHOW INDEX FROM Test FROM `{0}`", database0), conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); try { reader.GetString(reader.GetOrdinal("Sub_part")); Assert.Fail("We should not get here"); } catch (System.Data.SqlTypes.SqlNullValueException) { } } } /// /// Bug #23538 Exception thrown when GetSchemaTable is called and "fields" is null. /// [Test] public void GetSchemaTableOnEmptyResultset() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest() BEGIN END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; using (MySqlDataReader reader = cmd.ExecuteReader()) { DataTable dt = reader.GetSchemaTable(); Assert.IsNull(dt); } } /// /// Bug #24765 Retrieving empty fields results in check for isDBNull /// [Test] public void IsDbNullOnNonNullFields() { CreateDefaultTable(); execSQL("INSERT INTO Test (id, name) VALUES (1, '')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.IsFalse(reader.IsDBNull(1)); } } /// /// Bug #30204 Incorrect ConstraintException /// [Test] public void ConstraintWithLoadingReader() { execSQL(@"CREATE TABLE Test (ID_A int(11) NOT NULL, ID_B int(11) NOT NULL, PRIMARY KEY (ID_A,ID_B) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); DataTable dt = new DataTable(); using (MySqlDataReader reader = cmd.ExecuteReader()) { dt.Load(reader); } DataRow row = dt.NewRow(); row["ID_A"] = 2; row["ID_B"] = 3; dt.Rows.Add(row); row = dt.NewRow(); row["ID_A"] = 2; row["ID_B"] = 4; dt.Rows.Add(row); } [Test] public void CloseConnectionBehavior2() { CreateDefaultTable(); execSQL("INSERT INTO Test(id,name) VALUES(1,'test')"); using (MySqlConnection c2 = new MySqlConnection(conn.ConnectionString)) { c2.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", c2); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { Assert.IsTrue(reader.Read()); } } } /// /// Test that using command behavior SchemaOnly does not hose the connection /// by leaving SQL_SELECT_LIMIT set to 0 after the error (and in normal /// case too) /// /// Bug#30518 /// [Test] public void CommandBehaviorSchemaOnly() { MySqlCommand cmd = new MySqlCommand("select * from doesnotexist", conn); MySqlDataReader reader; try { reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly); Assert.Fail("should have failed"); } catch (MySqlException) { } // Check that failed ExecuteReader did not leave SQL_SELECT_LIMIT // set to 0. cmd.CommandText = "select now()"; reader = cmd.ExecuteReader(); Assert.IsTrue(reader.Read()); reader.Close(); // Check that CommandBehavior.SchemaOnly does not return rows reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly); Assert.IsFalse(reader.Read()); reader.Close(); reader = cmd.ExecuteReader(); // Check that prior setting of CommandBehavior did not // leave SQL_SELECT_LIMIT set to 0 Assert.IsTrue(reader.Read()); reader.Close(); } /// /// Bug #37239 MySqlReader GetOrdinal performance changes break existing functionality /// [Test] public void ColumnsWithSameName() { CreateDefaultTable(); execSQL("INSERT INTO Test (id, name) VALUES (1, 'test')"); MySqlCommand cmd = new MySqlCommand("SELECT a.name, a.name FROM Test a", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string name1 = reader.GetString(0); string name2 = reader.GetString(1); Assert.AreEqual(name1, name2); Assert.AreEqual(name1, "test"); } cmd.CommandText = "SELECT 'a' AS XYZ, 'b' as Xyz"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string name1 = reader.GetString(0); string name2 = reader.GetString(1); } } /// /// Bug #47467 Two simple changes for DataReader /// [Test] public void Bug47467() { MySqlCommand cmd = new MySqlCommand("SELECT 1 as c1", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Type t = reader.GetFieldType("c1"); try { reader.GetOrdinal("nocol"); Assert.Fail("This should have failed"); } catch (IndexOutOfRangeException ex) { Assert.IsTrue(ex.Message.IndexOf("nocol") != -1); } } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/MySql.Data.Tests.csproj0000644000175000017500000001334711127003600026543 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4} Library Properties MySql.Data.MySqlClient.Tests MySql.Data.Tests 3.5 v4.0 false publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false true true full false bin\Debug\ TRACE;DEBUG;NUNIT prompt 4 false AllRules.ruleset pdbonly true bin\Release\ TRACE prompt 4 AllRules.ruleset Properties\VersionInfo.cs PreserveNewest {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} MySql.Data mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/TimeoutAndCancel.cs0000644000175000017500000003245311127003600026010 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using System.Threading; using NUnit.Framework; using System.Globalization; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class TimeoutAndCancel : BaseTest { private delegate void CommandInvokerDelegate(MySqlCommand cmdToRun); private void CommandRunner(MySqlCommand cmdToRun) { object o = cmdToRun.ExecuteScalar(); Assert.IsNull(o); } [Test] public void CancelSingleQuery() { if (Version < new Version(5, 0)) return; // first we need a routine that will run for a bit execSQL(@"CREATE PROCEDURE spTest(duration INT) BEGIN SELECT SLEEP(duration); END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("duration", 10); // now we start execution of the command CommandInvokerDelegate d = new CommandInvokerDelegate(CommandRunner); d.BeginInvoke(cmd, null, null); // sleep 1 seconds Thread.Sleep(1000); // now cancel the command cmd.Cancel(); } int stateChangeCount; [Test] public void WaitTimeoutExpiring() { string connStr = GetConnectionString(true); MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder(connStr); if (sb.ConnectionProtocol == MySqlConnectionProtocol.NamedPipe) // wait timeout does not work for named pipe connections return; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); c.StateChange += new StateChangeEventHandler(c_StateChange); // set the session wait timeout on this new connection MySqlCommand cmd = new MySqlCommand("SET SESSION interactive_timeout=3", c); cmd.ExecuteNonQuery(); cmd.CommandText = "SET SESSION wait_timeout=2"; cmd.ExecuteNonQuery(); stateChangeCount = 0; // now wait 4 seconds Thread.Sleep(4000); try { cmd.CommandText = "SELECT now()"; cmd.ExecuteScalar(); } catch (Exception ex) { Assert.IsTrue(ex.Message.StartsWith("Fatal")); } Assert.AreEqual(1, stateChangeCount); Assert.AreEqual(ConnectionState.Closed, c.State); } using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("SELECT now() as thetime, database() as db", c); using (MySqlDataReader r = cmd.ExecuteReader()) { Assert.IsTrue(r.Read()); } } } void c_StateChange(object sender, StateChangeEventArgs e) { stateChangeCount++; } [Test] public void TimeoutExpiring() { if (version < new Version(5, 0)) return; DateTime start = DateTime.Now; try { MySqlCommand cmd = new MySqlCommand("SELECT SLEEP(200)", conn); cmd.CommandTimeout = 1; cmd.ExecuteReader(CommandBehavior.SingleRow); Assert.Fail("Should not get to this point"); } catch (MySqlException ex) { TimeSpan ts = DateTime.Now.Subtract(start); Assert.IsTrue(ts.TotalSeconds <= 3); Assert.IsTrue(ex.Message.StartsWith("Timeout expired"), "Message is wrong " +ex.Message); } long x = (long)(new MySqlCommand("select 10", conn).ExecuteScalar()); Assert.AreEqual(10, x); } [Test] public void TimeoutNotExpiring() { if (Version < new Version(5, 0)) return; MySqlCommand cmd = new MySqlCommand("SELECT SLEEP(1)", conn); cmd.CommandTimeout = 2; cmd.ExecuteNonQuery(); } [Test] public void TimeoutNotExpiring2() { if (Version < new Version(5, 0)) return; MySqlCommand cmd = new MySqlCommand("SELECT SLEEP(1)", conn); cmd.CommandTimeout = 0; // infinite timeout cmd.ExecuteNonQuery(); } [Test] public void TimeoutDuringBatch() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE PROCEDURE spTest(duration INT) BEGIN SELECT SLEEP(duration); END"); execSQL("CREATE TABLE test (id INT)"); MySqlCommand cmd = new MySqlCommand( "call spTest(5);INSERT INTO test VALUES(4)", conn); cmd.CommandTimeout = 2; try { cmd.ExecuteNonQuery(); Assert.Fail("This should have timed out"); } catch (MySqlException ex) { Assert.IsTrue(ex.Message.StartsWith("Timeout expired"), "Message is wrong" +ex); } // Check that connection is still usable MySqlCommand cmd2 = new MySqlCommand("select 10", conn); long res = (long)cmd2.ExecuteScalar(); Assert.AreEqual(10, res); } [Test] public void CancelSelect() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE Test (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20))"); for (int i=0; i < 1000; i++) execSQL("INSERT INTO Test VALUES (NULL, 'my string')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); cmd.CommandTimeout = 0; int rows = 0; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); cmd.Cancel(); while (true) { try { if (!reader.Read()) break; rows++; } catch (MySqlException ex) { Assert.IsTrue(ex.Number == (int)MySqlErrorCode.QueryInterrupted); if (rows < 1000) { bool readOK = reader.Read(); Assert.IsFalse(readOK); } } } } Assert.IsTrue(rows < 1000); } /// /// Bug #40091 mysql driver 5.2.3.0 connection pooling issue /// [Test] public void ConnectionStringModifiedAfterCancel() { if (Version.Major < 5) return; string connStr = GetPoolingConnectionString(); MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder(connStr); if (sb.ConnectionProtocol == MySqlConnectionProtocol.NamedPipe) // idle named pipe connections cannot be KILLed (server bug#47571) return; connStr = connStr.Replace("persist security info=true", "persist security info=false"); int threadId; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); threadId = c.ServerThread; string connStr1 = c.ConnectionString; MySqlCommand cmd = new MySqlCommand("SELECT SLEEP(2)", c); cmd.CommandTimeout = 1; try { using (MySqlDataReader reader = cmd.ExecuteReader()) { } } catch (MySqlException ex) { Assert.IsTrue(ex.InnerException is TimeoutException); Assert.IsTrue(c.State == ConnectionState.Open); } string connStr2 = c.ConnectionString.ToLower(CultureInfo.InvariantCulture); Assert.AreEqual(connStr1.ToLower(CultureInfo.InvariantCulture), connStr2); } execSQL("kill " + threadId); } /// /// Bug #45978 Silent problem when net_write_timeout is exceeded /// [Test] public void NetWriteTimeoutExpiring() { execSQL("CREATE TABLE Test(id int, blob1 longblob)"); int rows = 1000; byte[] b1 = Utils.CreateBlob(5000); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (@id, @b1)", conn); cmd.Parameters.Add("@id", MySqlDbType.Int32); cmd.Parameters.AddWithValue("@name", b1); for (int i = 0; i < rows; i++) { cmd.Parameters[0].Value = i; cmd.ExecuteNonQuery(); } string connStr = GetConnectionString(true); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); cmd.Connection = c; cmd.Parameters.Clear(); cmd.CommandText = "SET net_write_timeout = 1"; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test LIMIT " + rows; int i=0; try { using (MySqlDataReader reader = cmd.ExecuteReader()) { // after this several cycles of DataReader.Read() are executed // normally and then the problem, described above, occurs for (; i < rows; i++) { if (!reader.Read()) Assert.Fail("unexpected 'false' from reader.Read"); if(i%10 == 0) Thread.Sleep(1); object v = reader.GetValue(1); } } } catch (Exception e) { bool seenEndOfStreamException = false; for (Exception nextException = e; e != null; e = e.InnerException) { if (e is System.IO.EndOfStreamException) seenEndOfStreamException = true; } if (!seenEndOfStreamException) throw; Assert.IsTrue(seenEndOfStreamException); return; } // IT is relatively hard to predict where Console.WriteLine("Warning: all reads completed!"); Assert.IsTrue(i == rows); } } } #region Configs public class TimeoutAndCancelSocketCompressed : TimeoutAndCancel { protected override string GetConnectionInfo() { return String.Format("port={0};compress=true", port); } } #if !CF [Category("Pipe")] public class TimeoutAndCancelPipe : TimeoutAndCancel { protected override string GetConnectionInfo() { return String.Format("protocol=namedpipe;pipe name={0}", pipeName); } } [Category("SharedMemory")] public class TimeoutAndCancelSharedMemory : TimeoutAndCancel { protected override string GetConnectionInfo() { return String.Format("protocol=sharedmemory; shared memory name={0}", memoryName); } } #endif #endregion } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/ConnectionStringBuilder.cs0000644000175000017500000001454311127003600027426 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class ConnectionStringBuilder : BaseTest { [Test] public void Simple() { MySqlConnectionStringBuilder sb = null; sb = new MySqlConnectionStringBuilder(); sb.ConnectionString = "server=localhost;uid=reggie;pwd=pass;port=1111;" + "connection timeout=23; pooling=true; min pool size=33; " + "max pool size=66;keepalive=1"; Assert.AreEqual("localhost", sb.Server); Assert.AreEqual("reggie", sb.UserID); Assert.AreEqual("pass", sb.Password); Assert.AreEqual(1111, sb.Port); Assert.AreEqual(23, sb.ConnectionTimeout); Assert.IsTrue(sb.Pooling); Assert.AreEqual(33, sb.MinimumPoolSize); Assert.AreEqual(66, sb.MaximumPoolSize); Assert.AreEqual(sb.Keepalive, 1); try { sb.ConnectionString = "server=localhost;badkey=badvalue"; Assert.Fail("This should not work"); } catch (ArgumentException) { } sb.Clear(); Assert.AreEqual(15, sb.ConnectionTimeout); Assert.AreEqual(true, sb.Pooling); Assert.AreEqual(3306, sb.Port); Assert.AreEqual(String.Empty, sb.Server); Assert.AreEqual(false, sb.PersistSecurityInfo); Assert.AreEqual(0, sb.ConnectionLifeTime); Assert.IsFalse(sb.ConnectionReset); Assert.AreEqual(0, sb.MinimumPoolSize); Assert.AreEqual(100, sb.MaximumPoolSize); Assert.AreEqual(String.Empty, sb.UserID); Assert.AreEqual(String.Empty, sb.Password); Assert.AreEqual(false, sb.UseUsageAdvisor); Assert.AreEqual(String.Empty, sb.CharacterSet); Assert.AreEqual(false, sb.UseCompression); Assert.AreEqual("MYSQL", sb.PipeName); Assert.IsFalse(sb.Logging); Assert.IsFalse(sb.UseOldSyntax); Assert.IsTrue(sb.AllowBatch); Assert.IsFalse(sb.ConvertZeroDateTime); Assert.AreEqual("MYSQL", sb.SharedMemoryName); Assert.AreEqual(String.Empty, sb.Database); Assert.AreEqual(MySqlConnectionProtocol.Sockets, sb.ConnectionProtocol); Assert.IsFalse(sb.AllowZeroDateTime); Assert.IsFalse(sb.UsePerformanceMonitor); Assert.AreEqual(25, sb.ProcedureCacheSize); Assert.AreEqual(0, sb.Keepalive); } /// /// Bug #37955 Connector/NET keeps adding the same option to the connection string /// [Test] public void SettingValueMultipeTimes() { MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder(); s["database"] = "test"; s["database"] = "test2"; Assert.AreEqual("database=test2", s.ConnectionString); } #if !CF [Test] public void EncryptKeyword() { string connStr = "database=test;uid=root;server=localhost;encrypt=yes"; MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder(connStr); } #endif /// /// Bug #51209 error on parameter without value on connectionstring /// [Test] public void NoValueGivenForConnectionStringOption() { MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder(); s.ConnectionString = "compress=;pooling="; Assert.IsFalse(s.UseCompression); Assert.IsTrue(s.Pooling); } #if !CF /// /// Bug #59835 .Net Connector MySqlConnectionStringBuilder wrong result ContainsKey function /// [Test] public void ContainsKey() { MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder(); s["database"] = "test"; Assert.IsTrue(s.ContainsKey("initial catalog")); s["server"] = "myserver"; Assert.IsTrue(s.ContainsKey("server")); Assert.IsTrue(s.ContainsKey("host")); Assert.IsFalse(s.ContainsKey("badkey")); } #endif [Test] public void UseProcedureBodiesSettingCheckParameters() { MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder("server=localhost;use procedure bodies=false"); Assert.IsFalse(s.CheckParameters); } #if !CF [Test] public void EncrpytSslmode() { MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder("server=localhost;encrypt=true"); Assert.AreEqual(s.SslMode, MySqlSslMode.Preferred); } #endif [Test] [ExpectedException(typeof(ArgumentException))] public void SettingInvalidKeyThrowsArgumentException() { MySqlConnectionStringBuilder s = new MySqlConnectionStringBuilder(); s["foo keyword"] = "foo"; } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/AsyncTests.cs0000644000175000017500000000706111127003600024726 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class AsyncTests : BaseTest { [Test] public void ExecuteNonQuery() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE test (id int)"); execSQL("CREATE PROCEDURE spTest() BEGIN SET @x=0; REPEAT INSERT INTO test VALUES(@x); " + "SET @x=@x+1; UNTIL @x = 300 END REPEAT; END"); MySqlCommand proc = new MySqlCommand("spTest", conn); proc.CommandType = CommandType.StoredProcedure; IAsyncResult iar = proc.BeginExecuteNonQuery(); int count = 0; while (!iar.IsCompleted) { count++; System.Threading.Thread.Sleep(20); } proc.EndExecuteNonQuery(iar); Assert.IsTrue(count > 0); proc.CommandType = CommandType.Text; proc.CommandText = "SELECT COUNT(*) FROM test"; object cnt = proc.ExecuteScalar(); Assert.AreEqual(300, cnt); } [Test] public void ExecuteReader() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE test (id int)"); execSQL("CREATE PROCEDURE spTest() BEGIN INSERT INTO test VALUES(1); " + "SELECT SLEEP(2); SELECT 'done'; END"); MySqlCommand proc = new MySqlCommand("spTest", conn); proc.CommandType = CommandType.StoredProcedure; IAsyncResult iar = proc.BeginExecuteReader(); int count = 0; while (!iar.IsCompleted) { count++; System.Threading.Thread.Sleep(20); } using (MySqlDataReader reader = proc.EndExecuteReader(iar)) { Assert.IsNotNull(reader); Assert.IsTrue(count > 0, "count > 0"); Assert.IsTrue(reader.Read(), "can read"); Assert.IsTrue(reader.NextResult()); Assert.IsTrue(reader.Read()); Assert.AreEqual("done", reader.GetString(0)); reader.Close(); proc.CommandType = CommandType.Text; proc.CommandText = "SELECT COUNT(*) FROM test"; object cnt = proc.ExecuteScalar(); Assert.AreEqual(1, cnt); } } [Test] public void ThrowingExceptions() { MySqlCommand cmd = new MySqlCommand("SELECT xxx", conn); IAsyncResult r = cmd.BeginExecuteReader(); try { using (MySqlDataReader reader = cmd.EndExecuteReader(r)) { Assert.Fail("EndExecuteReader should have thrown an exception"); } } catch (MySqlException) { } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/Threading.cs0000644000175000017500000001231611127003600024532 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using MySql.Data.MySqlClient; using System.Data; using NUnit.Framework; using System.Threading; using System.Collections; using System.Diagnostics; using System.Text; using System.Collections.Specialized; namespace MySql.Data.MySqlClient.Tests { class GenericListener : TraceListener { StringCollection strings; StringBuilder partial; public GenericListener() { strings = new StringCollection(); partial = new StringBuilder(); } public StringCollection Strings { get { return strings; } } public int Find(string sToFind) { int count = 0; foreach (string s in strings) if (s.IndexOf(sToFind) != -1) count++; return count; } public void Clear() { partial.Remove(0, partial.Length); strings.Clear(); } public override void Write(string message) { partial.Append(message); } public override void WriteLine(string message) { Write(message); strings.Add(partial.ToString()); partial.Remove(0, partial.Length); } public int CountLinesContaining(string text) { int count = 0; foreach (string s in strings) if (s.Contains(text)) count++; return count; } } /// /// Summary description for ConnectionTests. /// [TestFixture] public class ThreadingTests : BaseTest { private void MultipleThreadsWorker(object ev) { (ev as ManualResetEvent).WaitOne(); using (MySqlConnection c = new MySqlConnection(GetConnectionString(true))) { c.Open(); } } /// /// Bug #17106 MySql.Data.MySqlClient.CharSetMap.GetEncoding thread synchronization issue /// [Test] public void MultipleThreads() { GenericListener myListener = new GenericListener(); ManualResetEvent ev = new ManualResetEvent(false); ArrayList threads = new ArrayList(); System.Diagnostics.Trace.Listeners.Add(myListener); for (int i = 0; i < 20; i++) { ParameterizedThreadStart ts = new ParameterizedThreadStart(MultipleThreadsWorker); Thread t = new Thread(ts); threads.Add(t); t.Start(ev); } // now let the threads go ev.Set(); // wait for the threads to end int x = 0; while (x < threads.Count) { while ((threads[x] as Thread).IsAlive) Thread.Sleep(50); x++; } } /// /// Bug #54012 MySql Connector/NET is not hardened to deal with /// ThreadAbortException /// private void HardenedThreadAbortExceptionWorker() { try { using (MySqlConnection c = new MySqlConnection(GetConnectionString(true))) { c.Open(); MySqlCommand cmd = new MySqlCommand( "SELECT BENCHMARK(10000000000,ENCODE('hello','goodbye'))", c); // ThreadAbortException is not delivered, when thread is // stuck in system call. To shorten test time, set command // timeout to a small value. Note .shortening command timeout // means we could actually have timeout exception here too, // but it seems like CLR delivers ThreadAbortException, if // the thread was aborted. cmd.CommandTimeout = 2; cmd.ExecuteNonQuery(); } } catch (ThreadAbortException) { Thread.ResetAbort(); return; } Assert.Fail("expected ThreadAbortException"); } [Test] public void HardenedThreadAbortException() { Thread t = new Thread(new ThreadStart(HardenedThreadAbortExceptionWorker)); t.Name = "Execute Query"; t.Start(); Thread.Sleep(500); t.Abort(); t.Join(); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/BulkLoading.cs0000644000175000017500000003330611127003600025022 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using NUnit.Framework; using System.IO; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class BulkLoading : BaseTest { [Test] public void BulkLoadSimple() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); // first create the external file string path = Path.GetTempFileName(); StreamWriter sw = new StreamWriter(path); for (int i = 0; i < 200; i++) sw.WriteLine(i + "\t'Test'"); sw.Flush(); sw.Close(); MySqlBulkLoader loader = new MySqlBulkLoader(conn); loader.TableName = "Test"; loader.FileName = path; loader.Timeout = 0; int count = loader.Load(); Assert.AreEqual(200, count); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(200, dt.Rows.Count); Assert.AreEqual("'Test'", dt.Rows[0][1].ToString().Trim()); } [Test] public void BulkLoadReadOnlyFile() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); // first create the external file string path = Path.GetTempFileName(); StreamWriter sw = new StreamWriter(path); for (int i = 0; i < 200; i++) sw.WriteLine(i + "\t'Test'"); sw.Flush(); sw.Close(); FileInfo fi = new FileInfo(path); FileAttributes oldAttr = fi.Attributes; fi.Attributes = fi.Attributes | FileAttributes.ReadOnly; try { MySqlBulkLoader loader = new MySqlBulkLoader(conn); loader.TableName = "Test"; loader.FileName = path; loader.Timeout = 0; int count = loader.Load(); Assert.AreEqual(200, count); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(200, dt.Rows.Count); Assert.AreEqual("'Test'", dt.Rows[0][1].ToString().Trim()); } finally { fi.Attributes = oldAttr; fi.Delete(); } } [Test] public void BulkLoadSimple2() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); // first create the external file string path = Path.GetTempFileName(); StreamWriter sw = new StreamWriter(path); for (int i = 0; i < 200; i++) sw.Write(i + ",'Test' xxx"); sw.Flush(); sw.Close(); MySqlBulkLoader loader = new MySqlBulkLoader(conn); loader.TableName = "Test"; loader.FileName = path; loader.Timeout = 0; loader.FieldTerminator = ","; loader.LineTerminator = "xxx"; int count = loader.Load(); Assert.AreEqual(200, count); MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM Test", conn); Assert.AreEqual(200, cmd.ExecuteScalar()); } [Test] public void BulkLoadSimple3() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); // first create the external file string path = Path.GetTempFileName(); StreamWriter sw = new StreamWriter(path); for (int i = 0; i < 200; i++) sw.Write(i + ",'Test' xxx"); sw.Flush(); sw.Close(); MySqlBulkLoader loader = new MySqlBulkLoader(conn); loader.TableName = "Test"; loader.FileName = path; loader.Timeout = 0; loader.FieldTerminator = ","; loader.LineTerminator = "xxx"; loader.NumberOfLinesToSkip = 50; int count = loader.Load(); Assert.AreEqual(150, count); MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM Test", conn); Assert.AreEqual(150, cmd.ExecuteScalar()); } [Test] public void BulkLoadSimple4() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); // first create the external file string path = Path.GetTempFileName(); StreamWriter sw = new StreamWriter(path); for (int i = 0; i < 100; i++) sw.Write("aaa" + i + ",'Test' xxx"); for (int i = 100; i < 200; i++) sw.Write("bbb" + i + ",'Test' xxx"); for (int i = 200; i < 300; i++) sw.Write("aaa" + i + ",'Test' xxx"); for (int i = 300; i < 400; i++) sw.Write("bbb" + i + ",'Test' xxx"); sw.Flush(); sw.Close(); MySqlBulkLoader loader = new MySqlBulkLoader(conn); loader.TableName = "Test"; loader.FileName = path; loader.Timeout = 0; loader.FieldTerminator = ","; loader.LineTerminator = "xxx"; loader.LinePrefix = "bbb"; int count = loader.Load(); Assert.AreEqual(200, count); MySqlCommand cmd = new MySqlCommand("SELECT COUNT(*) FROM Test", conn); Assert.AreEqual(200, cmd.ExecuteScalar()); } [Test] public void BulkLoadFieldQuoting() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), name2 VARCHAR(250), PRIMARY KEY(id))"); // first create the external file string path = Path.GetTempFileName(); StreamWriter sw = new StreamWriter(path); for (int i = 0; i < 200; i++) sw.WriteLine(i + "\t`col1`\tcol2"); sw.Flush(); sw.Close(); MySqlBulkLoader loader = new MySqlBulkLoader(conn); loader.TableName = "Test"; loader.FileName = path; loader.Timeout = 0; loader.FieldQuotationCharacter = '`'; loader.FieldQuotationOptional = true; int count = loader.Load(); Assert.AreEqual(200, count); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(200, dt.Rows.Count); Assert.AreEqual("col1", dt.Rows[0][1]); Assert.AreEqual("col2", dt.Rows[0][2].ToString().Trim()); } [Test] public void BulkLoadEscaping() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), name2 VARCHAR(250), PRIMARY KEY(id))"); // first create the external file string path = Path.GetTempFileName(); StreamWriter sw = new StreamWriter(path); for (int i = 0; i < 200; i++) sw.WriteLine(i + ",col1\tstill col1,col2"); sw.Flush(); sw.Close(); MySqlBulkLoader loader = new MySqlBulkLoader(conn); loader.TableName = "Test"; loader.FileName = path; loader.Timeout = 0; loader.EscapeCharacter = '\t'; loader.FieldTerminator = ","; int count = loader.Load(); Assert.AreEqual(200, count); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(200, dt.Rows.Count); Assert.AreEqual("col1still col1", dt.Rows[0][1]); Assert.AreEqual("col2", dt.Rows[0][2].ToString().Trim()); } [Test] public void BulkLoadConflictOptionReplace() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); // first create the external file string path = Path.GetTempFileName(); StreamWriter sw = new StreamWriter(path); for (int i = 0; i < 20; i++) sw.WriteLine(i + ",col1"); sw.Flush(); sw.Close(); MySqlBulkLoader loader = new MySqlBulkLoader(conn); loader.TableName = "Test"; loader.FileName = path; loader.Timeout = 0; loader.FieldTerminator = ","; int count = loader.Load(); Assert.AreEqual(20, count); path = Path.GetTempFileName(); sw = new StreamWriter(path); for (int i = 0; i < 20; i++) sw.WriteLine(i + ",col2"); sw.Flush(); sw.Close(); loader = new MySqlBulkLoader(conn); loader.TableName = "Test"; loader.FileName = path; loader.Timeout = 0; loader.FieldTerminator = ","; loader.ConflictOption = MySqlBulkLoaderConflictOption.Replace; loader.Load(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(20, dt.Rows.Count); Assert.AreEqual("col2", dt.Rows[0][1].ToString().Trim()); } [Test] public void BulkLoadConflictOptionIgnore() { execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(250), PRIMARY KEY(id))"); // first create the external file string path = Path.GetTempFileName(); StreamWriter sw = new StreamWriter(path); for (int i = 0; i < 20; i++) sw.WriteLine(i + ",col1"); sw.Flush(); sw.Close(); MySqlBulkLoader loader = new MySqlBulkLoader(conn); loader.TableName = "Test"; loader.FileName = path; loader.Timeout = 0; loader.FieldTerminator = ","; int count = loader.Load(); Assert.AreEqual(20, count); path = Path.GetTempFileName(); sw = new StreamWriter(path); for (int i = 0; i < 20; i++) sw.WriteLine(i + ",col2"); sw.Flush(); sw.Close(); loader = new MySqlBulkLoader(conn); loader.TableName = "Test"; loader.FileName = path; loader.Timeout = 0; loader.FieldTerminator = ","; loader.ConflictOption = MySqlBulkLoaderConflictOption.Ignore; loader.Load(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(20, dt.Rows.Count); Assert.AreEqual("col1", dt.Rows[0][1].ToString().Trim()); } [Test] public void BulkLoadColumnOrder() { execSQL(@"CREATE TABLE Test (id INT NOT NULL, n1 VARCHAR(250), n2 VARCHAR(250), n3 VARCHAR(250), PRIMARY KEY(id))"); // first create the external file string path = Path.GetTempFileName(); StreamWriter sw = new StreamWriter(path); for (int i = 0; i < 20; i++) sw.WriteLine(i + ",col3,col2,col1"); sw.Flush(); sw.Close(); MySqlBulkLoader loader = new MySqlBulkLoader(conn); loader.TableName = "Test"; loader.FileName = path; loader.Timeout = 0; loader.FieldTerminator = ","; loader.LineTerminator = Environment.NewLine; loader.Columns.Add("id"); loader.Columns.Add("n3"); loader.Columns.Add("n2"); loader.Columns.Add("n1"); int count = loader.Load(); Assert.AreEqual(20, count); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(20, dt.Rows.Count); Assert.AreEqual("col1", dt.Rows[0][1]); Assert.AreEqual("col2", dt.Rows[0][2]); Assert.AreEqual("col3", dt.Rows[0][3].ToString().Trim()); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/OutputParameters.cs0000644000175000017500000005711611127003600026160 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using NUnit.Framework; using System.Globalization; using System.Threading; using MySql.Data.Types; using System.Data.Common; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for StoredProcedure. /// [TestFixture] public class OutputParametersBatch : BaseTest { protected bool prepare; protected override string GetConnectionInfo() { return "allow batch=true; ignore prepare = false"; } /// /// Bug #17814 Stored procedure fails unless DbType set explicitly /// Bug #23749 VarChar field size over 255 causes a System.OverflowException /// [Test] public void OutputParameters() { if (Version < new Version(5, 0)) return; // we don't want to run this test under no access string connInfo = GetConnectionInfo(); if (connInfo.IndexOf("use procedure bodies=false") != -1) return; // create our procedure execSQL("CREATE PROCEDURE spTest(out value VARCHAR(350), OUT intVal INT, " + "OUT dateVal TIMESTAMP, OUT floatVal FLOAT, OUT noTypeVarChar VARCHAR(20), " + "OUT noTypeInt INT) " + "BEGIN SET value='42'; SET intVal=33; SET dateVal='2004-06-05 07:58:09'; " + "SET floatVal = 1.2; SET noTypeVarChar='test'; SET noTypeInt=66; END"); // we use rootConn here since we are using parameters MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new MySqlParameter("?value", MySqlDbType.VarChar)); cmd.Parameters.Add(new MySqlParameter("?intVal", MySqlDbType.Int32)); cmd.Parameters.Add(new MySqlParameter("?dateVal", MySqlDbType.DateTime)); cmd.Parameters.Add(new MySqlParameter("?floatVal", MySqlDbType.Float)); MySqlParameter vcP = new MySqlParameter(); vcP.ParameterName = "?noTypeVarChar"; vcP.Direction = ParameterDirection.Output; cmd.Parameters.Add(vcP); MySqlParameter vcI = new MySqlParameter(); vcI.ParameterName = "?noTypeInt"; vcI.Direction = ParameterDirection.Output; cmd.Parameters.Add(vcI); cmd.Parameters[0].Direction = ParameterDirection.Output; cmd.Parameters[1].Direction = ParameterDirection.Output; cmd.Parameters[2].Direction = ParameterDirection.Output; cmd.Parameters[3].Direction = ParameterDirection.Output; if (prepare) cmd.Prepare(); int rowsAffected = cmd.ExecuteNonQuery(); //TODO fix this //Assert.AreEqual(0, rowsAffected); Assert.AreEqual("42", cmd.Parameters[0].Value); Assert.AreEqual(33, cmd.Parameters[1].Value); Assert.AreEqual(new DateTime(2004, 6, 5, 7, 58, 9), Convert.ToDateTime(cmd.Parameters[2].Value)); Assert.AreEqual(1.2, (decimal)(float)cmd.Parameters[3].Value); Assert.AreEqual("test", cmd.Parameters[4].Value); Assert.AreEqual(66, cmd.Parameters[5].Value); } [Test] public void InputOutputParameters() { if (Version < new Version(5, 0)) return; // create our procedure execSQL("CREATE PROCEDURE spTest( INOUT strVal VARCHAR(50), INOUT numVal INT, OUT outVal INT UNSIGNED ) " + "BEGIN SET strVal = CONCAT(strVal,'ending'); SET numVal=numVal * 2; SET outVal=99; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?strVal", "beginning"); cmd.Parameters.AddWithValue("?numVal", 33); cmd.Parameters.AddWithValue("?outVal", MySqlDbType.Int32); cmd.Parameters[0].Direction = ParameterDirection.InputOutput; cmd.Parameters[1].Direction = ParameterDirection.InputOutput; cmd.Parameters[2].Direction = ParameterDirection.Output; if (prepare) cmd.Prepare(); int rowsAffected = cmd.ExecuteNonQuery(); Assert.AreEqual(0, rowsAffected); Assert.AreEqual("beginningending", cmd.Parameters[0].Value); Assert.AreEqual(66, cmd.Parameters[1].Value); Assert.AreEqual(99, cmd.Parameters[2].Value); } [Test] public void ExecuteScalar() { if (Version < new Version(5, 0)) return; // create our procedure execSQL("CREATE PROCEDURE spTest( IN valin VARCHAR(50), OUT valout VARCHAR(50) ) " + "BEGIN SET valout=valin; SELECT 'Test'; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?valin", "valuein"); cmd.Parameters.Add(new MySqlParameter("?valout", MySqlDbType.VarChar)); cmd.Parameters[1].Direction = ParameterDirection.Output; if (prepare) cmd.Prepare(); object result = cmd.ExecuteScalar(); Assert.AreEqual("Test", result); Assert.AreEqual("valuein", cmd.Parameters[1].Value); } [Test] public void ExecuteReader() { if (Version < new Version(5, 0)) return; // create our procedure execSQL("CREATE PROCEDURE spTest(OUT p INT) " + "BEGIN SELECT 1; SET p=2; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.Parameters.Add("?p", MySqlDbType.Int32); cmd.Parameters[0].Direction = ParameterDirection.Output; cmd.CommandType = CommandType.StoredProcedure; if (prepare) cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.AreEqual(true, reader.Read()); Assert.AreEqual(false, reader.NextResult()); Assert.AreEqual(false, reader.Read()); } Assert.AreEqual(2, cmd.Parameters[0].Value); } [Test] public void FunctionNoParams() { if (Version < new Version(5, 0)) return; execSQL("CREATE FUNCTION fnTest() RETURNS CHAR(50)" + " LANGUAGE SQL DETERMINISTIC BEGIN RETURN \"Test\"; END"); MySqlCommand cmd = new MySqlCommand("SELECT fnTest()", conn); cmd.CommandType = CommandType.Text; if (prepare) cmd.Prepare(); object result = cmd.ExecuteScalar(); Assert.AreEqual("Test", result); } [Test] public void FunctionParams() { if (Version < new Version(5, 0)) return; execSQL("CREATE FUNCTION fnTest( val1 INT, val2 CHAR(40) ) RETURNS INT " + " LANGUAGE SQL DETERMINISTIC BEGIN RETURN val1 + LENGTH(val2); END"); MySqlCommand cmd = new MySqlCommand("SELECT fnTest(22, 'Test')", conn); cmd.CommandType = CommandType.Text; if (prepare) cmd.Prepare(); object result = cmd.ExecuteScalar(); Assert.AreEqual(26, result); } /// /// Bug #10644 Cannot call a stored function directly from Connector/Net /// Bug #25013 Return Value parameter not found /// [Test] public void CallingStoredFunctionasProcedure() { if (Version < new Version(5, 0)) return; execSQL("CREATE FUNCTION fnTest(valin int) RETURNS INT " + " LANGUAGE SQL DETERMINISTIC BEGIN return valin * 2; END"); MySqlCommand cmd = new MySqlCommand("fnTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?valin", 22); MySqlParameter retVal = cmd.CreateParameter(); retVal.ParameterName = "?retval"; retVal.MySqlDbType = MySqlDbType.Int32; retVal.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(retVal); if (prepare) cmd.Prepare(); cmd.ExecuteNonQuery(); Assert.AreEqual(44, cmd.Parameters[1].Value); } [Test] public void ReturningEmptyResultSet() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE test1 (id int AUTO_INCREMENT NOT NULL, " + "Name VARCHAR(100) NOT NULL, PRIMARY KEY(id))"); execSQL("CREATE TABLE test2 (id int AUTO_INCREMENT NOT NULL, " + "id1 INT NOT NULL, id2 INT NOT NULL, PRIMARY KEY(id))"); execSQL("INSERT INTO test1 (Id, Name) VALUES (1, 'Item1')"); execSQL("INSERT INTO test1 (Id, Name) VALUES (2, 'Item2')"); execSQL("INSERT INTO test2 (Id, Id1, Id2) VALUES (1, 1, 1)"); execSQL("INSERT INTO test2 (Id, Id1, Id2) VALUES (2, 2, 1)"); execSQL("CREATE PROCEDURE spTest(Name VARCHAR(100), OUT Table1Id INT) " + "BEGIN SELECT t1.Id INTO Table1Id FROM test1 t1 WHERE t1.Name LIKE Name; " + "SELECT t3.Id2 FROM test2 t3 WHERE t3.Id1 = Table1Id; END"); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "spTest"; cmd.Parameters.AddWithValue("?Name", "Item3"); cmd.Parameters.Add("?Table1Id", MySqlDbType.Int32); cmd.Parameters["?Table1Id"].Direction = ParameterDirection.Output; DataSet ds = new DataSet(); if (prepare) cmd.Prepare(); MySqlDataAdapter da = new MySqlDataAdapter(cmd); try { da.Fill(ds); } catch (MySqlException) { // on 5.1 this throws an exception that no rows were returned. } } [Test] public void UnsignedOutputParameters() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE Test (id INT(10) UNSIGNED AUTO_INCREMENT, PRIMARY KEY (id)) "); execSQL("CREATE PROCEDURE spTest (OUT id BIGINT UNSIGNED) " + "BEGIN INSERT INTO Test VALUES (NULL); SET id=LAST_INSERT_ID(); END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("?id", MySqlDbType.UInt64); cmd.Parameters[0].Direction = ParameterDirection.Output; if (prepare) cmd.Prepare(); cmd.ExecuteNonQuery(); object o = cmd.Parameters[0].Value; Assert.IsTrue(o is ulong); Assert.AreEqual(1, o); } /// /// Bug #25625 Crashes when calling with CommandType set to StoredProcedure /// [Test] public void RunWithoutSelectPrivsThrowException() { if (Version < new Version(5, 0)) return; // we don't want this test to run in our all access fixture string connInfo = GetConnectionInfo(); if (connInfo.IndexOf("use procedure bodies=false") == -1) return; suExecSQL(String.Format( "GRANT ALL ON `{0}`.* to 'testuser'@'%' identified by 'testuser'", database0)); suExecSQL(String.Format( "GRANT ALL ON `{0}`.* to 'testuser'@'localhost' identified by 'testuser'", database0)); execSQL("DROP PROCEDURE IF EXISTS spTest"); execSQL("CREATE PROCEDURE spTest(id int, OUT outid int, INOUT inoutid int) " + "BEGIN SET outid=id+inoutid; SET inoutid=inoutid+id; END"); string s = GetConnectionString("testuser", "testuser", true); MySqlConnection c = new MySqlConnection(s); c.Open(); try { MySqlCommand cmd = new MySqlCommand("spTest", c); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?id", 2); cmd.Parameters.AddWithValue("?outid", MySqlDbType.Int32); cmd.Parameters[1].Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("?inoutid", 4); cmd.Parameters[2].Direction = ParameterDirection.InputOutput; if (prepare) cmd.Prepare(); cmd.ExecuteNonQuery(); Assert.AreEqual(6, cmd.Parameters[1].Value); Assert.AreEqual(6, cmd.Parameters[2].Value); } catch (InvalidOperationException iex) { Assert.IsTrue(iex.Message.StartsWith("Unable to retrieve")); } finally { if (c != null) c.Close(); suExecSQL("DELETE FROM mysql.user WHERE user = 'testuser'"); } } [Test] public void CallingFunctionWithoutReturnParameter() { if (Version < new Version(5, 0)) return; execSQL("CREATE FUNCTION fnTest (p_kiosk bigint(20), " + "p_user bigint(20)) returns double begin declare v_return double; " + "set v_return = 3.6; return v_return; end"); MySqlCommand cmd = new MySqlCommand("fnTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?p_kiosk", 2); cmd.Parameters.AddWithValue("?p_user", 4); try { if (prepare) cmd.Prepare(); cmd.ExecuteNonQuery(); Assert.Fail("This should fail"); } catch (InvalidOperationException) { } } /// /// Bug #27668 FillSchema and Stored Proc with an out parameter /// [Test] public void GetSchema2() { if (Version.Major < 5) return; execSQL(@"CREATE TABLE Test(id INT AUTO_INCREMENT, PRIMARY KEY (id)) "); execSQL(@"CREATE PROCEDURE spTest (OUT id INT) BEGIN INSERT INTO Test VALUES (NULL); SET id=520; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("?id", MySqlDbType.Int32); cmd.Parameters[0].Direction = ParameterDirection.Output; MySqlDataAdapter da = new MySqlDataAdapter(cmd); DataTable dt = new DataTable(); if (prepare) cmd.Prepare(); cmd.ExecuteNonQuery(); da.Fill(dt); da.FillSchema(dt, SchemaType.Mapped); } [Test] public void NoAccessToProcedureBodies() { if (Version < new Version(5, 0)) return; string sql = String.Format("CREATE PROCEDURE `{0}`.`spTest`(in1 INT, INOUT inout1 INT, OUT out1 INT ) " + "BEGIN SET inout1 = inout1+2; SET out1=inout1-3; SELECT in1; END", database0); execSQL(sql); string connStr = GetConnectionString(true) + "; use procedure bodies=false"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("spTest", c); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?in1", 2); cmd.Parameters.AddWithValue("?inout1", 4); cmd.Parameters.Add("?out1", MySqlDbType.Int32); cmd.Parameters[1].Direction = ParameterDirection.InputOutput; cmd.Parameters[2].Direction = ParameterDirection.Output; if (prepare) cmd.Prepare(); cmd.ExecuteNonQuery(); Assert.AreEqual(6, cmd.Parameters[1].Value); Assert.AreEqual(3, cmd.Parameters[2].Value); } } [Test] public void BinaryAndVarBinaryParameters() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest(OUT out1 BINARY(20), OUT out2 VARBINARY(20)) " + "BEGIN SET out1 = 'out1'; SET out2='out2'; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("out1", MySqlDbType.Binary); cmd.Parameters[0].Direction = ParameterDirection.Output; cmd.Parameters.Add("out2", MySqlDbType.VarBinary); cmd.Parameters[1].Direction = ParameterDirection.Output; if (prepare) cmd.Prepare(); cmd.ExecuteNonQuery(); byte[] out1 = (byte[])cmd.Parameters[0].Value; Assert.AreEqual('o', out1[0]); Assert.AreEqual('u', out1[1]); Assert.AreEqual('t', out1[2]); Assert.AreEqual('1', out1[3]); out1 = (byte[])cmd.Parameters[1].Value; Assert.AreEqual('o', out1[0]); Assert.AreEqual('u', out1[1]); Assert.AreEqual('t', out1[2]); Assert.AreEqual('2', out1[3]); } /// /// Bug #31930 Stored procedures with "ambiguous column name" error cause lock-ups /// [Test] public void CallingFunction() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE FUNCTION `GetSupplierBalance`(SupplierID_ INTEGER(11)) RETURNS double NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER COMMENT '' BEGIN RETURN 1.0; END"); MySqlCommand command = new MySqlCommand("GetSupplierBalance", conn); command.CommandType = CommandType.StoredProcedure; command.Parameters.Add("?SupplierID_", MySqlDbType.Int32).Value = 1; command.Parameters.Add("?Balance", MySqlDbType.Double).Direction = ParameterDirection.ReturnValue; if (prepare) command.Prepare(); command.ExecuteNonQuery(); double balance = Convert.ToDouble(command.Parameters["?Balance"].Value); Assert.AreEqual(1.0, balance); } /// /// [Test] public void OutputParametersWithNewParamHandling() { if (Version < new Version(5, 0)) return; // create our procedure execSQL("CREATE PROCEDURE spTest(out val1 VARCHAR(350)) " + "BEGIN SET val1 = '42'; END"); string connStr = GetConnectionString(true); connStr = connStr.Replace("allow user variables=true", "allow user variables=false"); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("spTest", c); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new MySqlParameter("@val1", MySqlDbType.VarChar)).Direction = ParameterDirection.Output; if (prepare) cmd.Prepare(); int rowsAffected = cmd.ExecuteNonQuery(); Assert.AreEqual(0, rowsAffected); Assert.AreEqual("42", cmd.Parameters[0].Value); } } /// /// [Test] public void FunctionWithNewParamHandling() { if (Version < new Version(5, 0)) return; // create our procedure execSQL("CREATE FUNCTION spTest(`value` INT) RETURNS INT " + "BEGIN RETURN value; END"); string connStr = GetConnectionString(true); connStr = connStr.Replace("allow user variables=true", "allow user variables=false"); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("spTest", c); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new MySqlParameter("@value", MySqlDbType.Int32)).Value = 22; cmd.Parameters.Add(new MySqlParameter("@returnvalue", MySqlDbType.Int32)).Direction = ParameterDirection.ReturnValue; if (prepare) cmd.Prepare(); int rowsAffected = cmd.ExecuteNonQuery(); Assert.AreEqual(0, rowsAffected); Assert.AreEqual(22, cmd.Parameters[1].Value); } } /// /// Bug #56756 Output Parameter MySqlDbType.Bit get a wrong Value (48/49 for false or true) /// [Test] public void BitTypeAsOutParameter() { execSQL(@"CREATE PROCEDURE `spTest`(out x bit(1)) BEGIN Set x = 1; -- Outparameter value is 49 Set x = 0; -- Outparameter value is 48 END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("x", MySqlDbType.Bit).Direction = ParameterDirection.Output; if (prepare) cmd.Prepare(); cmd.ExecuteNonQuery(); Assert.AreEqual(0, cmd.Parameters[0].Value); } } #region Configs public class OutputParametersNoBatch : OutputParametersBatch { protected override string GetConnectionInfo() { return "allow batch=false"; } } public class OutputParametersBatchPrepared : OutputParametersBatch { protected override string GetConnectionInfo() { prepare = true; return "allow batch=true; ignore prepare=false"; } } public class OutputParametersNoBatchPrepared : OutputParametersBatch { protected override string GetConnectionInfo() { prepare = true; return "allow batch=false; ignore prepare=false"; } } #endregion } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/PoolingTests.cs0000644000175000017500000004620211127003600025260 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using NUnit.Framework; using System.Reflection; using System.Collections; using System.Collections.Generic; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for PoolingTests. /// [TestFixture] public class PoolingTests : BaseTest { [Test] public void Connection() { string connStr = GetPoolingConnectionString(); MySqlConnection c = new MySqlConnection(connStr); c.Open(); int serverThread = c.ServerThread; c.Close(); // first test that only a single connection get's used for (int i = 0; i < 10; i++) { c = new MySqlConnection(connStr); c.Open(); Assert.AreEqual(serverThread, c.ServerThread); c.Close(); } c.Open(); KillConnection(c); c.Close(); connStr += ";Min Pool Size=10"; MySqlConnection[] connArray = new MySqlConnection[10]; for (int i = 0; i < connArray.Length; i++) { connArray[i] = new MySqlConnection(connStr); connArray[i].Open(); } // now make sure all the server ids are different for (int i = 0; i < connArray.Length; i++) { for (int j = 0; j < connArray.Length; j++) { if (i != j) Assert.IsTrue(connArray[i].ServerThread != connArray[j].ServerThread); } } for (int i = 0; i < connArray.Length; i++) { KillConnection(connArray[i]); connArray[i].Close(); } } [Test] public void OpenKilled() { string connStr = GetPoolingConnectionString() + ";min pool size=1; max pool size=1"; MySqlConnection c = new MySqlConnection(connStr); c.Open(); int threadId = c.ServerThread; // thread gets killed right here KillConnection(c); c.Close(); c.Dispose(); c = new MySqlConnection(connStr); c.Open(); int secondThreadId = c.ServerThread; KillConnection(c); c.Close(); Assert.IsFalse(threadId == secondThreadId); } [Test] public void ReclaimBrokenConnection() { // now create a new connection string only allowing 1 connection in the pool string connStr = GetPoolingConnectionString() + ";connect timeout=2;max pool size=1"; // now use up that connection MySqlConnection c = new MySqlConnection(connStr); c.Open(); // now attempting to open a connection should fail try { MySqlConnection c2 = new MySqlConnection(connStr); c2.Open(); Assert.Fail("Open after using up pool should fail"); } catch (Exception) { } // we now kill the first connection to simulate a server stoppage base.KillConnection(c); // now we do something on the first connection try { c.ChangeDatabase("mysql"); Assert.Fail("This change database should not work"); } catch (Exception) { } // Opening a connection now should work MySqlConnection connection = new MySqlConnection(connStr); connection.Open(); KillConnection(connection); connection.Close(); } [Test] public void TestUserReset() { string connStr = GetPoolingConnectionString(); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("SET @testvar='5'", c); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT @testvar"; object var = cmd.ExecuteScalar(); Assert.AreEqual("5", var); c.Close(); c.Open(); object var2 = cmd.ExecuteScalar(); Assert.AreEqual(DBNull.Value, var2); KillConnection(c); } } #if !CF // Test that thread does not come to pool after abort [Test] public void TestAbort() { string connStr = GetPoolingConnectionString(); int threadId; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); threadId = c.ServerThread; MethodInfo abort = c.GetType().GetMethod("Abort", BindingFlags.NonPublic | BindingFlags.Instance); abort.Invoke(c, null); } using (MySqlConnection c1 = new MySqlConnection(connStr)) { c1.Open(); Assert.IsTrue(c1.ServerThread != threadId); KillConnection(c1); } } #endif /// /// Bug #25614 After connection is closed, and opened again UTF-8 characters are not read well /// [Test] public void UTF8AfterClosing() { string originalValue = "??????????"; execSQL("CREATE TABLE test (id int(11) NOT NULL, " + "value varchar(100) NOT NULL, PRIMARY KEY (`id`) " + ") ENGINE=MyISAM DEFAULT CHARSET=utf8"); string connStr = GetPoolingConnectionString() + ";charset=utf8"; using (MySqlConnection con = new MySqlConnection(connStr)) { con.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO test VALUES (1, '??????????')", con); cmd.ExecuteNonQuery(); cmd = new MySqlCommand("SELECT value FROM test WHERE id = 1", con); string firstS = cmd.ExecuteScalar().ToString(); Assert.AreEqual(originalValue, firstS); con.Close(); con.Open(); //Does not work: cmd = new MySqlCommand("SELECT value FROM test WHERE id = 1", con); string secondS = cmd.ExecuteScalar().ToString(); KillConnection(con); con.Close(); Assert.AreEqual(firstS, secondS); } } #if !CF private void PoolingWorker(object cn) { MySqlConnection conn = (cn as MySqlConnection); Thread.Sleep(5000); conn.Close(); } /// /// Bug #24373 High CPU utilization when no idle connection /// [Test] public void MultipleThreads() { string connStr = GetPoolingConnectionString() + ";max pool size=1"; MySqlConnection c = new MySqlConnection(connStr); c.Open(); ParameterizedThreadStart ts = new ParameterizedThreadStart(PoolingWorker); Thread t = new Thread(ts); t.Start(c); using (MySqlConnection c2 = new MySqlConnection(connStr)) { c2.Open(); KillConnection(c2); } c.Close(); } #endif [Test] public void NewTest() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE Test (id INT, name VARCHAR(50))"); execSQL("CREATE PROCEDURE spTest(theid INT) BEGIN SELECT * FROM test WHERE id=theid; END"); execSQL("INSERT INTO test VALUES (1, 'First')"); execSQL("INSERT INTO test VALUES (2, 'Second')"); execSQL("INSERT INTO test VALUES (3, 'Third')"); execSQL("INSERT INTO test VALUES (4, 'Fourth')"); string connStr = GetPoolingConnectionString(); for (int i = 1; i < 5; i++) { using (MySqlConnection con = new MySqlConnection(connStr)) { con.Open(); MySqlCommand reccmd = new MySqlCommand("spTest", con); reccmd.CommandTimeout = 0; reccmd.CommandType = CommandType.StoredProcedure; MySqlParameter par = new MySqlParameter("@theid", MySqlDbType.String); par.Value = i; reccmd.Parameters.Add(par); using (MySqlDataReader recdr = reccmd.ExecuteReader()) { if (recdr.Read()) { int x = recdr.GetOrdinal("name"); Assert.AreEqual(1, x); } } } } MySqlConnection c = new MySqlConnection(connStr); c.Open(); KillConnection(c); } /// /// Bug #29409 Bug on Open Connection with pooling=true to a MYSQL Server that is shutdown /// [Test] public void ConnectAfterMaxPoolSizeTimeouts() { //TODO: refactor test suite to support starting/stopping services /* string connStr = "server=localhost;uid=root;database=test;pooling=true;connect timeout=6; max pool size = 6"; MySqlConnection c = new MySqlConnection(connStr); for (int i = 0; i < 6; i++) { try { c.Open(); } catch (Exception ex) { } } c.Open(); c.Close();*/ } bool IsConnectionAlive(int serverThread) { MySqlDataAdapter da = new MySqlDataAdapter("SHOW PROCESSLIST", conn); DataTable dt = new DataTable(); da.Fill(dt); foreach (DataRow row in dt.Rows) if ((long)row["Id"] == serverThread) return true; return false; } [Test] public void CleanIdleConnections() { string assemblyName = typeof(MySqlConnection).Assembly.FullName; string pmName = String.Format("MySql.Data.MySqlClient.MySqlPoolManager, {0}", assemblyName); Type poolManager = Type.GetType(pmName, false); FieldInfo poolManagerTimerField = poolManager.GetField("timer", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); FieldInfo poolManagerMaxConnectionIdleTime = poolManager.GetField ("maxConnectionIdleTime", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); Timer poolManagerTimer = (Timer)poolManagerTimerField.GetValue(null); int origMaxConnectionIdleTime = (int) poolManagerMaxConnectionIdleTime.GetValue(null); try { // Normally, idle connection would expire after 3 minutes and would // be cleaned up by timer that also runs every 3 minutes. // Since we do not want to wait that long during a unit tests, // we use tricks. // - temporarily reduce max.idle time for connections down to 1 // second // - temporarily change cleanup timer to run each second. int threadId = -1; string connStr = GetPoolingConnectionString(); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); threadId = c.ServerThread; } // Pooled connection should be still alive Assert.IsTrue(IsConnectionAlive(threadId)); poolManagerMaxConnectionIdleTime.SetValue(null, 1); poolManagerTimer.Change(1000, 1000); // Let the idle connection expire and let cleanup timer run. Thread.Sleep(2500); // The connection that was pooled must be dead now Assert.IsFalse(IsConnectionAlive(threadId)); } finally { // restore values for connection idle time and timer interval poolManagerMaxConnectionIdleTime.SetValue(null, origMaxConnectionIdleTime); poolManagerTimer.Change(origMaxConnectionIdleTime*1000, origMaxConnectionIdleTime*1000); } } [Test] public void ClearPool() { string connStr = GetPoolingConnectionString() + ";min pool size=10"; MySqlConnectionStringBuilder settings = new MySqlConnectionStringBuilder(connStr); MySqlConnection[] connections = new MySqlConnection[10]; connections[0] = new MySqlConnection(connStr); connections[0].Open(); string assemblyName = typeof(MySqlConnection).Assembly.FullName; string pmName = String.Format("MySql.Data.MySqlClient.MySqlPoolManager, {0}", assemblyName); Type poolManager = Type.GetType(pmName, false); FieldInfo poolManagerHashTable = poolManager.GetField("pools", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); Hashtable poolHash = (Hashtable)poolManagerHashTable.GetValue(null); FieldInfo clearingPoolsFI = poolManager.GetField("clearingPools", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); ICollection clearingPools = (ICollection)clearingPoolsFI.GetValue(null); // now we need to investigate string poolName = String.Format("MySql.Data.MySqlClient.MySqlPool, {0}", assemblyName); Type poolType = Type.GetType(poolName, false); FieldInfo inUsePool = poolType.GetField("inUsePool", BindingFlags.NonPublic | BindingFlags.Instance); ICollection inUseList = (ICollection)inUsePool.GetValue(poolHash[settings.ConnectionString]); Assert.AreEqual(1, inUseList.Count); FieldInfo idlePool = poolType.GetField("idlePool", BindingFlags.NonPublic | BindingFlags.Instance); ICollection idleList = (ICollection)idlePool.GetValue(poolHash[settings.ConnectionString]); Assert.AreEqual(9, idleList.Count); // now open 4 more of these. Now we shoudl have 5 open and five // still in the pool for (int i = 1; i < 5; i++) { connections[i] = new MySqlConnection(connStr); connections[i].Open(); } Assert.AreEqual(5, inUseList.Count); Assert.AreEqual(5, idleList.Count); Assert.AreEqual(0, clearingPools.Count); // now tell this connection to clear its pool MySqlConnection.ClearPool(connections[0]); Assert.AreEqual(1, clearingPools.Count); Assert.AreEqual(0, idleList.Count); for (int i = 0; i < 5; i++) connections[i].Close(); Assert.AreEqual(0, clearingPools.Count); } [Test] public void TestBadConnections() { MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(); builder.Pooling = true; builder.Server = "xxxxxxxx"; // one that definitely does not exist. builder.UserID = "whoever"; builder.Password = "whatever"; int numberOfConnections = 1; for (int i = 0; i < numberOfConnections; ++i) { using (MySqlConnection connection = new MySqlConnection(builder.ConnectionString)) { try { connection.Open(); Assert.Fail("Connection should throw an exception."); } catch (Exception) { } } Thread.Sleep(50); } MySqlConnection.ClearAllPools(); } /// /// Bug #42801 ClearPool .Net connector : NullReferenceException /// [Test] public void DoubleClearingConnectionPool() { MySqlConnection c1 = new MySqlConnection(GetConnectionString(true)); MySqlConnection c2 = new MySqlConnection(GetConnectionString(true)); c1.Open(); c2.Open(); c1.Close(); c2.Close(); MySqlConnection.ClearPool(c1); MySqlConnection.ClearPool(c2); } /// /// Bug #49563 Mysql Client wrongly communications with server when using pooled connections /// [Test] public void OpenSecondPooledConnectionWithoutDatabase() { string connectionString = GetConnectionString(false); connectionString = connectionString.Replace("pooling=false", "pooling=true"); MySqlConnection c1 = new MySqlConnection(connectionString); using (c1) { c1.Open(); c1.Close(); } MySqlConnection c2 = new MySqlConnection(connectionString); using (c2) { c2.Open(); c2.Close(); } MySqlConnection.ClearAllPools(); } /// /// Bug #47153 Connector/NET fails to reset connection when encoding has changed /// [Test] public void ConnectionResetAfterUnicode() { execSQL("CREATE TABLE test (id INT, name VARCHAR(20) CHARSET UCS2)"); execSQL("INSERT INTO test VALUES (1, 'test')"); string connStr = GetPoolingConnectionString() + ";connection reset=true;min pool size=1; max pool size=1"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM test", c); using (MySqlDataReader r = cmd.ExecuteReader()) { r.Read(); } c.Close(); try { c.Open(); } finally { KillConnection(c); } } } #if !CF private void CacheServerPropertiesInternal(bool cache) { string connStr = GetPoolingConnectionString() + String.Format(";logging=true;cache server properties={0}", cache); GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); MySqlTrace.Switch.Level = System.Diagnostics.SourceLevels.All; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); using (MySqlConnection c2 = new MySqlConnection(connStr)) { c2.Open(); KillConnection(c2); } KillConnection(c); } int count = listener.CountLinesContaining("SHOW VARIABLES"); Assert.AreEqual(cache ? 1 : 2, count); } [Test] public void CacheServerProperties() { CacheServerPropertiesInternal(true); CacheServerPropertiesInternal(false); } #endif } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/Tokenizer.cs0000644000175000017500000003137711127003600024607 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using NUnit.Framework; using System.Collections; using System.Collections.Generic; using System.Reflection; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class Tokenizer : BaseTest { #if !CF [Test] public void Simple() { SqlTokenizer tokenizer = new SqlTokenizer("SELECT * FROM Test"); Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual("*", tokenizer.NextToken()); Assert.AreEqual("FROM", tokenizer.NextToken()); Assert.AreEqual("Test", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); } [Test] public void DashSingleLineComment() { string comment = "-- this is my comment\r\n"; string sql = String.Format("SELECT {0} * FROM Test", comment); SqlTokenizer tokenizer = new SqlTokenizer(sql); tokenizer.ReturnComments = true; Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual(comment, tokenizer.NextToken()); Assert.AreEqual("*", tokenizer.NextToken()); Assert.AreEqual("FROM", tokenizer.NextToken()); Assert.AreEqual("Test", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); tokenizer = new SqlTokenizer(sql); tokenizer.ReturnComments = false; Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual("*", tokenizer.NextToken()); Assert.AreEqual("FROM", tokenizer.NextToken()); Assert.AreEqual("Test", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); } [Test] public void HashSingleLineComment() { string comment = "#this is my comment\r\n"; string sql = String.Format("SELECT {0} * FROM Test", comment); SqlTokenizer tokenizer = new SqlTokenizer(sql); tokenizer.ReturnComments = true; Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual(comment, tokenizer.NextToken()); Assert.AreEqual("*", tokenizer.NextToken()); Assert.AreEqual("FROM", tokenizer.NextToken()); Assert.AreEqual("Test", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); tokenizer = new SqlTokenizer(sql); tokenizer.ReturnComments = false; Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual("*", tokenizer.NextToken()); Assert.AreEqual("FROM", tokenizer.NextToken()); Assert.AreEqual("Test", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); } [Test] public void MultiLineComment() { string comment = "/* this is my comment \r\n lines 2 \r\n line 3*/"; string sql = String.Format("SELECT{0} * FROM Test", comment); SqlTokenizer tokenizer = new SqlTokenizer(sql); tokenizer.ReturnComments = true; Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual(comment.Trim(), tokenizer.NextToken()); Assert.AreEqual("*", tokenizer.NextToken()); Assert.AreEqual("FROM", tokenizer.NextToken()); Assert.AreEqual("Test", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); tokenizer = new SqlTokenizer(sql); tokenizer.ReturnComments = false; Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual("*", tokenizer.NextToken()); Assert.AreEqual("FROM", tokenizer.NextToken()); Assert.AreEqual("Test", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); } [Test] public void Parameter() { string sql = "SELECT * FROM Test WHERE id=@id AND id2=?id2"; SqlTokenizer tokenizer = new SqlTokenizer(sql); tokenizer.ReturnComments = true; Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual("*", tokenizer.NextToken()); Assert.AreEqual("FROM", tokenizer.NextToken()); Assert.AreEqual("Test", tokenizer.NextToken()); Assert.AreEqual("WHERE", tokenizer.NextToken()); Assert.AreEqual("id", tokenizer.NextToken()); Assert.AreEqual("=", tokenizer.NextToken()); Assert.AreEqual("@id", tokenizer.NextToken()); Assert.AreEqual("AND", tokenizer.NextToken()); Assert.AreEqual("id2", tokenizer.NextToken()); Assert.AreEqual("=", tokenizer.NextToken()); Assert.AreEqual("?id2", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); } [Test] public void NextParameter() { string sql = "SELECT * FROM Test WHERE id=@id AND id2=?id2"; SqlTokenizer tokenizer = new SqlTokenizer(sql); tokenizer.ReturnComments = true; Assert.AreEqual("@id", tokenizer.NextParameter()); Assert.AreEqual("?id2", tokenizer.NextParameter()); Assert.IsNull(tokenizer.NextParameter()); } [Test] public void ParameterWithSpecialCharacters() { string sql = "SELECT * FROM Test WHERE id=@id_$123"; SqlTokenizer tokenizer = new SqlTokenizer(sql); tokenizer.ReturnComments = true; Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual("*", tokenizer.NextToken()); Assert.AreEqual("FROM", tokenizer.NextToken()); Assert.AreEqual("Test", tokenizer.NextToken()); Assert.AreEqual("WHERE", tokenizer.NextToken()); Assert.AreEqual("id", tokenizer.NextToken()); Assert.AreEqual("=", tokenizer.NextToken()); Assert.AreEqual("@id_$123", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); } [Test] public void StringLiteral() { string sql = "SELECT 'a', 1, 'b'"; SqlTokenizer tokenizer = new SqlTokenizer(sql); tokenizer.ReturnComments = false; Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual("'a'", tokenizer.NextToken()); Assert.AreEqual(",", tokenizer.NextToken()); Assert.AreEqual("1", tokenizer.NextToken()); Assert.AreEqual(",", tokenizer.NextToken()); Assert.AreEqual("'b'", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); } [Test] public void UserVariable() { string sql = "SELECT 'a', 1, @@myVar"; SqlTokenizer tokenizer = new SqlTokenizer(sql); tokenizer.ReturnComments = false; Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual("'a'", tokenizer.NextToken()); Assert.AreEqual(",", tokenizer.NextToken()); Assert.AreEqual("1", tokenizer.NextToken()); Assert.AreEqual(",", tokenizer.NextToken()); Assert.AreEqual("@@myVar", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); } [Test] public void AnsiQuotes() { string sql = "SELECT 'a', \"a\", `a`"; SqlTokenizer tokenizer = new SqlTokenizer(sql); tokenizer.AnsiQuotes = false; Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual("'a'", tokenizer.NextToken()); Assert.IsTrue(tokenizer.Quoted); Assert.AreEqual(",", tokenizer.NextToken()); Assert.AreEqual("\"a\"", tokenizer.NextToken()); Assert.IsTrue(tokenizer.Quoted); Assert.AreEqual(",", tokenizer.NextToken()); Assert.AreEqual("`a`", tokenizer.NextToken()); Assert.IsTrue(tokenizer.Quoted); Assert.IsNull(tokenizer.NextToken()); } [Test] public void ParseProcBody() { string sql = "CREATE PROCEDURE spTest(testid INT, testname VARCHAR(20)) BEGIN SELECT 1; END"; SqlTokenizer tokenizer = new SqlTokenizer(sql); tokenizer.AnsiQuotes = false; Assert.AreEqual("CREATE", tokenizer.NextToken()); Assert.AreEqual("PROCEDURE", tokenizer.NextToken()); Assert.AreEqual("spTest", tokenizer.NextToken()); Assert.AreEqual("(", tokenizer.NextToken()); Assert.AreEqual("testid", tokenizer.NextToken()); Assert.AreEqual("INT", tokenizer.NextToken()); Assert.AreEqual(",", tokenizer.NextToken()); Assert.AreEqual("testname", tokenizer.NextToken()); Assert.AreEqual("VARCHAR", tokenizer.NextToken()); Assert.AreEqual("(", tokenizer.NextToken()); Assert.AreEqual("20", tokenizer.NextToken()); Assert.AreEqual(")", tokenizer.NextToken()); Assert.AreEqual(")", tokenizer.NextToken()); Assert.AreEqual("BEGIN", tokenizer.NextToken()); Assert.AreEqual("SELECT", tokenizer.NextToken()); Assert.AreEqual("1", tokenizer.NextToken()); Assert.AreEqual(";", tokenizer.NextToken()); Assert.AreEqual("END", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); } #endif /// /// Bug #44318 Tokenizer /// [Test] public void NoSpaceAroundEquals() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test(name VARCHAR(40))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test SET name='test -- test';", conn); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT name FROM Test"; object o = cmd.ExecuteScalar(); Assert.AreEqual("test -- test", o); cmd.CommandText = "UPDATE Test SET name='Can you explain this ?';"; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT name FROM Test"; o = cmd.ExecuteScalar(); Assert.AreEqual("Can you explain this ?", o); } [Test] public void Slash() { string sql = "AND // OR"; SqlTokenizer tokenizer = new SqlTokenizer(sql); tokenizer.AnsiQuotes = false; Assert.AreEqual("AND", tokenizer.NextToken()); Assert.AreEqual("/", tokenizer.NextToken()); Assert.AreEqual("/", tokenizer.NextToken()); Assert.AreEqual("OR", tokenizer.NextToken()); Assert.IsNull(tokenizer.NextToken()); } [Test] public void SqlServerMode() { string sql = "SELECT `a`, [id], [name] FROM [test]"; SqlTokenizer tokenizer = new SqlTokenizer(sql); tokenizer.SqlServerMode = true; tokenizer.NextToken(); Assert.AreEqual("`a`", tokenizer.NextToken()); Assert.IsTrue(tokenizer.Quoted); tokenizer.NextToken(); // read , Assert.AreEqual("[id]", tokenizer.NextToken()); Assert.IsTrue(tokenizer.Quoted); tokenizer.NextToken(); // read , Assert.AreEqual("[name]", tokenizer.NextToken()); Assert.IsTrue(tokenizer.Quoted); tokenizer.NextToken(); // read FROM Assert.AreEqual("[test]", tokenizer.NextToken()); Assert.IsTrue(tokenizer.Quoted); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/InterfaceTests.cs0000644000175000017500000000420211127003600025543 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using NUnit.Framework; using System.Data.Common; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class InterfaceTests : BaseTest { #if !CF [Test] public void ClientFactory() { DbProviderFactory f = new MySqlClientFactory(); using (DbConnection c = f.CreateConnection()) { DbConnectionStringBuilder cb = f.CreateConnectionStringBuilder(); cb.ConnectionString = GetConnectionString(true); c.ConnectionString = cb.ConnectionString; c.Open(); DbCommand cmd = f.CreateCommand(); cmd.Connection = c; cmd.CommandText = "SELECT 1"; cmd.CommandType = CommandType.Text; using (DbDataReader reader = cmd.ExecuteReader()) { reader.Read(); } } } #endif } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/SimpleTransactions.cs0000644000175000017500000001270411127003600026450 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using NUnit.Framework; using System.Data.Common; using System.Reflection; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class SimpleTransactions : BaseTest { public override void Setup() { base.Setup(); createTable("CREATE TABLE Test (key2 VARCHAR(1), name VARCHAR(100), name2 VARCHAR(100))", "INNODB"); } [Test] public void TestReader() { execSQL("INSERT INTO Test VALUES('P', 'Test1', 'Test2')"); MySqlTransaction txn = conn.BeginTransaction(); MySqlConnection c = txn.Connection; Assert.AreEqual( conn, c ); MySqlCommand cmd = new MySqlCommand("SELECT name, name2 FROM Test WHERE key2='P'", conn, txn); MySqlTransaction t2 = cmd.Transaction; Assert.AreEqual( txn, t2 ); MySqlDataReader reader = null; try { reader = cmd.ExecuteReader(); reader.Close(); txn.Commit(); } catch (Exception ex) { Assert.Fail( ex.Message ); txn.Rollback(); } finally { if (reader != null) reader.Close(); } } /// /// Bug #22400 Nested transactions /// [Test] public void NestedTransactions() { MySqlTransaction t1 = conn.BeginTransaction(); try { MySqlTransaction t2 = conn.BeginTransaction(); Assert.Fail("Exception should have been thrown"); t2.Rollback(); } catch (InvalidOperationException) { } finally { t1.Rollback(); } } [Test] public void BeginTransactionOnPreviouslyOpenConnection() { string connStr = GetConnectionString(true); MySqlConnection c = new MySqlConnection(connStr); c.Open(); c.Close(); try { c.BeginTransaction(); } catch (Exception ex) { Assert.AreEqual("The connection is not open.", ex.Message); } } /// /// Bug #37991 Connection fails when trying to close after a commit while network to db is bad /// This test is not a perfect test of this bug as the kill connection is not quite the /// same as unplugging the network but it's the best I've figured out so far /// [Test] public void CommitAfterConnectionDead() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test(id INT, name VARCHAR(20))"); string connStr = GetConnectionString(true) + ";pooling=false"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlTransaction trans = c.BeginTransaction(); using (MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (1, 'boo')", c)) { cmd.ExecuteNonQuery(); } KillConnection(c); try { trans.Commit(); Assert.Fail("Should have thrown an exception"); } catch (Exception) { } Assert.AreEqual(ConnectionState.Closed, c.State); c.Close(); // this should work even though we are closed } } /// /// Bug #39817 Transaction Dispose does not roll back /// [Test] public void DisposingCallsRollback() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES ('a', 'b', 'c')", conn); MySqlTransaction txn = conn.BeginTransaction(); using (txn) { cmd.ExecuteNonQuery(); } // the txn should be closed now as a rollback should have happened. Type t = txn.GetType(); FieldInfo fi = t.GetField("open", BindingFlags.Instance | BindingFlags.NonPublic); bool isOpen = (bool)fi.GetValue(txn); Assert.IsFalse(isOpen); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/LanguageTests.cs0000644000175000017500000002737211127003600025403 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using System.Globalization; using System.Threading; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class LanguageTests : BaseTest { [Test] public void Unicode() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (u2 varchar(255) CHARACTER SET ucs2)"); using (MySqlConnection c = new MySqlConnection(conn.ConnectionString + ";charset=utf8")) { c.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES ( CONVERT('困巫忘否役' using ucs2))", c); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string s1 = reader.GetString(0); Assert.AreEqual("困巫忘否役", s1); } } } /// /// Bug #13806 Does not support Code Page 932 /// [Test] public void CP932() { using (MySqlConnection c = new MySqlConnection(GetConnectionString(true) + ";charset=cp932")) { c.Open(); MySqlCommand cmd = new MySqlCommand("SELECT '涯割晦叶角'", c); string s = (string)cmd.ExecuteScalar(); Assert.AreEqual("涯割晦叶角", s); } } [Test] public void UTF8() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (id int, name VARCHAR(200) CHAR SET utf8)"); using (MySqlConnection c = new MySqlConnection(conn.ConnectionString + ";charset=utf8")) { c.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(1, 'ЁЄЉҖҚ')", c); //russian cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO Test VALUES(2, '兣冘凥凷冋')"; // simplified Chinese cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO Test VALUES(3, '困巫忘否役')"; // traditional Chinese cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO Test VALUES(4, '涯割晦叶角')"; // Japanese cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO Test VALUES(5, 'ברחפע')"; // Hebrew cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO Test VALUES(6, 'ψόβΩΞ')"; // Greek cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO Test VALUES(7, 'þðüçöÝÞÐÜÇÖ')"; // Turkish cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO Test VALUES(8, 'ฅๆษ')"; // Thai cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("ЁЄЉҖҚ", reader.GetString(1)); reader.Read(); Assert.AreEqual("兣冘凥凷冋", reader.GetString(1)); reader.Read(); Assert.AreEqual("困巫忘否役", reader.GetString(1)); reader.Read(); Assert.AreEqual("涯割晦叶角", reader.GetString(1)); reader.Read(); Assert.AreEqual("ברחפע", reader.GetString(1)); reader.Read(); Assert.AreEqual("ψόβΩΞ", reader.GetString(1)); reader.Read(); Assert.AreEqual("þðüçöÝÞÐÜÇÖ", reader.GetString(1)); reader.Read(); Assert.AreEqual("ฅๆษ", reader.GetString(1)); } } } [Test] public void UTF8PreparedAndUsingParameters() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (name VARCHAR(200) CHAR SET utf8)"); using (MySqlConnection c = new MySqlConnection(conn.ConnectionString + ";charset=utf8")) { c.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(?val)", c); cmd.Parameters.Add("?val", MySqlDbType.VarChar); cmd.Prepare(); cmd.Parameters[0].Value = "ЁЄЉҖҚ"; // Russian cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = "兣冘凥凷冋"; // simplified Chinese cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = "困巫忘否役"; // traditional Chinese cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = "涯割晦叶角"; // Japanese cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = "ברחפע"; // Hebrew cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = "ψόβΩΞ"; // Greek cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = "þðüçöÝÞÐÜÇÖ"; // Turkish cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = "ฅๆษ"; // Thai cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("ЁЄЉҖҚ", reader.GetString(0)); reader.Read(); Assert.AreEqual("兣冘凥凷冋", reader.GetString(0)); reader.Read(); Assert.AreEqual("困巫忘否役", reader.GetString(0)); reader.Read(); Assert.AreEqual("涯割晦叶角", reader.GetString(0)); reader.Read(); Assert.AreEqual("ברחפע", reader.GetString(0)); reader.Read(); Assert.AreEqual("ψόβΩΞ", reader.GetString(0)); reader.Read(); Assert.AreEqual("þðüçöÝÞÐÜÇÖ", reader.GetString(0)); reader.Read(); Assert.AreEqual("ฅๆษ", reader.GetString(0)); } } } [Test] public void Chinese() { if (Version < new Version(4, 1)) return; using (MySqlConnection c = new MySqlConnection(conn.ConnectionString + ";charset=utf8")) { c.Open(); execSQL("CREATE TABLE Test (id int, name VARCHAR(200) CHAR SET big5, name2 VARCHAR(200) CHAR SET gb2312)"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(1, '困巫忘否役', '涝搞谷侪魍' )", c); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("困巫忘否役", reader.GetString(1)); Assert.AreEqual("涝搞谷侪魍", reader.GetString(2)); } } } [Test] public void Turkish() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (id int, name VARCHAR(200) CHAR SET latin5 )"); using (MySqlConnection c = new MySqlConnection(conn.ConnectionString + ";charset=utf8")) { c.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(1, 'ĞËÇÄŞ')", c); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("ĞËÇÄŞ", reader.GetString(1)); } } } [Test] public void Russian() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (id int, name VARCHAR(200) CHAR SET cp1251)"); using (MySqlConnection c = new MySqlConnection(conn.ConnectionString + ";charset=utf8")) { c.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(1, 'щьеи')", c); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("щьеи", reader.GetString(1)); } } } [Test] public void VariousCollations() { if (Version < new Version(4, 1)) return; createTable(@"CREATE TABLE `test_tbl`(`test` VARCHAR(255) NOT NULL) CHARACTER SET utf8 COLLATE utf8_swedish_ci", "MYISAM"); execSQL("INSERT INTO test_tbl VALUES ('myval')"); MySqlCommand cmd = new MySqlCommand("SELECT test FROM test_tbl", conn); cmd.ExecuteScalar(); } /// /// Bug #25651 SELECT does not work properly when WHERE contains UTF-8 characters /// [Test] public void UTF8Parameters() { execSQL("CREATE TABLE test (id int(11) NOT NULL, " + "value varchar(100) NOT NULL, PRIMARY KEY (id)) " + "ENGINE=MyISAM DEFAULT CHARSET=utf8"); string conString = GetConnectionString(true) + ";charset=utf8"; using (MySqlConnection con = new MySqlConnection(conString)) { con.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO test VALUES (1, 'šđč枊ĐČĆŽ')", con); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT id FROM test WHERE value = ?parameter"; cmd.Parameters.Add("?parameter", MySqlDbType.VarString); cmd.Parameters[0].Value = "šđč枊ĐČĆŽ"; object o = cmd.ExecuteScalar(); Assert.AreEqual(1, o); } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/ExceptionTests.cs0000644000175000017500000000544711127003600025615 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using System.Threading; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class ExceptionTests : BaseTest { public override void Setup() { base.Setup(); execSQL("CREATE TABLE Test (id INT NOT NULL, name VARCHAR(100))"); } [Test] public void Timeout() { for (int i=1; i < 10; i++) execSQL("INSERT INTO Test VALUES (" + i + ", 'This is a long text string that I am inserting')"); // we create a new connection so our base one is not closed MySqlConnection c2 = new MySqlConnection(conn.ConnectionString); c2.Open(); KillConnection(c2); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", c2); MySqlDataReader reader = null; try { reader = cmd.ExecuteReader(); reader.Read(); reader.Read(); reader.Close(); Assert.Fail("We should not reach this code"); } catch (Exception) { Assert.AreEqual(ConnectionState.Closed, c2.State); } finally { if (reader != null) reader.Close(); c2.Close(); } } #if !CF /// /// Bug #27436 Add the MySqlException.Number property value to the Exception.Data Dictionary /// [Test] public void ErrorData() { MySqlCommand cmd = new MySqlCommand("SELEDT 1", conn); try { cmd.ExecuteNonQuery(); } catch (Exception ex) { Assert.AreEqual(1064, ex.Data["Server Error Code"]); } } #endif } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/client.pfx0000644000175000017500000000430511127003600024272 0ustar directhexdirecthex00 *H xt0p0o *H `0\0U *H 0 *H  0 ^v({]q¶Oɩ'V.,*r» M~ӀW}:2&_u[ gG9 mq>m<9q .Jf'O$wGi yowM'']H ZZЋ uxu[ߥ>ɉ_Y4\G5jf``kIW S=.H`N]W&8<%`Mpζ|X5gi^K0lة2IeT8;E:ظ@i%h)l>p7%|Q0.l5N1D070Tf/U zޗܴ %isWh] .Y3Nt*Y͛9gNl\57ʵl@KE9` >%c&CsM2 E 9lΐRJU3 ?7 >{VXbsAr*&Mo= Ŏ֟G3q`ȖG8='kc~π +v6=(Ys<]Pξ3wNyxCӶYRCl?$jxXgӵW/]8$,Z1Dߢo(@\>\;goO*2s';(J<'yf6<f g}hb绣I߬6=P3=W}9{aQܷS} 8jf$MqKK݅I 3nF>ԩ|#EKh!|+5mE__=2CJ gT"R7c,*GYL7?5U߅~=.w,\3ZPY(/BgP0)BXJxg^ҁX'bغꦯmPv@;] @=Ⱦ$<* .;N+J N?J{DUFb41ܡ+ї3{e:št¹\Td^x+M_i_*.k$ӑ;K;h7n47 ̷eN!@34_bė-G:_Q).=S0}:fjȤIprDG11}vX*Y+l굃x>4COmԅ4BiAeß8qs6Ai(k73S.4oqZCR%ZIM.k_> ͔kɠ{'&OG ɷCrȐꋣcklꑳ/tk\@Y0ymJ3SLTVGN̬x͉bJ}N6]{d]Wʿ=C_`E!l/@s&f8TJ:ϜQ1)jQe|nh!Pr^{я7o+-/6kS3t"r>E3K{2FA[POCr7T OoJ/ߖs Y\g6BiP1f1%0# *H  1Z#W$TxSmW010!0 +PT;7 /g8~ͭ{a)h;mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/ReplicationTests.cs0000644000175000017500000000345111127003600026121 0ustar directhexdirecthex// Copyright (c) 2011 Oracle, Inc. All Rights Reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class ReplicationTests : BaseTest { public ReplicationTests() { csAdditions += ";replication=yes"; } [Test] public void Simple() { MySqlCommand cmd = new MySqlCommand("SET @v=1", conn); try { cmd.ExecuteNonQuery(); } catch (MySqlException ex) { Assert.IsTrue(ex.Message.Contains("Replicated")); } } } }mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/Transactions.cs0000644000175000017500000010643611127003600025304 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using NUnit.Framework; using System.Transactions; using System.Data.Common; using System.Threading; using System.Diagnostics; using System.Text; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class Transactions : BaseTest { void TransactionScopeInternal(bool commit) { createTable("CREATE TABLE Test (key2 VARCHAR(1), name VARCHAR(100), name2 VARCHAR(100))", "INNODB"); using (MySqlConnection c = new MySqlConnection(GetConnectionString(true))) { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES ('a', 'name', 'name2')", c); using (TransactionScope ts = new TransactionScope()) { c.Open(); cmd.ExecuteNonQuery(); if (commit) ts.Complete(); } cmd.CommandText = "SELECT COUNT(*) FROM Test"; object count = cmd.ExecuteScalar(); Assert.AreEqual(commit ? 1 : 0, count); } } [Test] public void TransactionScopeRollback() { TransactionScopeInternal(false); } [Test] public void TransactionScopeCommit() { TransactionScopeInternal(true); } // The following block is not currently supported /* void TransactionScopeMultipleInternal(bool commit) { MySqlConnection c1 = new MySqlConnection(GetConnectionString(true)); MySqlConnection c2 = new MySqlConnection(GetConnectionString(true)); MySqlCommand cmd1 = new MySqlCommand("INSERT INTO Test VALUES ('a', 'name', 'name2')", c1); MySqlCommand cmd2 = new MySqlCommand("INSERT INTO Test VALUES ('b', 'name', 'name2')", c1); try { using (TransactionScope ts = new TransactionScope()) { c1.Open(); cmd1.ExecuteNonQuery(); c2.Open(); cmd2.ExecuteNonQuery(); if (commit) ts.Complete(); } cmd1.CommandText = "SELECT COUNT(*) FROM Test"; object count = cmd1.ExecuteScalar(); Assert.AreEqual(commit ? 2 : 0, count); } catch (Exception ex) { Assert.Fail(ex.Message); } finally { if (c1 != null) c1.Close(); if (c2 != null) c2.Close(); } } [Test] public void TransactionScopeMultipleRollback() { TransactionScopeMultipleInternal(false); } [Test] public void TransactionScopeMultipleCommit() { TransactionScopeMultipleInternal(true); } */ /// /// Bug #34448 Connector .Net 5.2.0 with Transactionscope doesnt use specified IsolationLevel /// [Test] public void TransactionScopeWithIsolationLevel() { TransactionOptions opts = new TransactionOptions(); opts.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, opts)) { string connStr = GetConnectionString(true); using (MySqlConnection myconn = new MySqlConnection(connStr)) { myconn.Open(); MySqlCommand cmd = new MySqlCommand("SHOW VARIABLES LIKE 'tx_isolation'", myconn); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string level = reader.GetString(1); Assert.AreEqual("READ-COMMITTED", level); } } } } /// /// Bug #27289 Transaction is not rolledback when connection close /// [Test] public void RollingBackOnClose() { execSQL("CREATE TABLE Test (id INT) ENGINE=InnoDB"); string connStr = GetPoolingConnectionString(); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (1)", c); c.BeginTransaction(); cmd.ExecuteNonQuery(); } using (MySqlConnection c2 = new MySqlConnection(connStr)) { c2.Open(); MySqlCommand cmd2 = new MySqlCommand("SELECT COUNT(*) from Test", c2); c2.BeginTransaction(); object count = cmd2.ExecuteScalar(); Assert.AreEqual(0, count); } MySqlConnection connection = new MySqlConnection(connStr); connection.Open(); KillConnection(connection); } /// /// NullReferenceException thrown on TransactionScope dispose /// [Test] public void LockedTable() { string connStr = GetConnectionString(true); connStr = String.Format(@"Use Affected Rows=true;allow user variables=yes;Server=localhost;Port=3306; Database={0};Uid=root;Connect Timeout=35;default command timeout=90;charset=utf8", database0); execSQL(@"CREATE TABLE `t1` ( `Key` int(10) unsigned NOT NULL auto_increment, `Val` varchar(100) NOT NULL, `Val2` varchar(100) NOT NULL default '', PRIMARY KEY (`Key`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1"); execSQL(@"CREATE TABLE `t2` ( `Key` int(10) unsigned NOT NULL auto_increment, `Val` varchar(100) NOT NULL, PRIMARY KEY (`Key`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1"); execSQL("lock tables t2 read"); using (TransactionScope scope = new TransactionScope()) { using (MySqlConnection conn = new MySqlConnection(connStr)) using (MySqlCommand cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = @"insert into t1 (Val,Val2) values (?value1, ?value2)"; ; cmd.CommandTimeout = 5; cmd.Parameters.AddWithValue("?value1", new Random().Next()); cmd.Parameters.AddWithValue("?value2", new Random().Next()); cmd.ExecuteNonQuery(); } using (MySqlConnection conn = new MySqlConnection(connStr)) using (MySqlCommand cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = @"insert into t2 (Val) values (?value)"; cmd.CommandTimeout = 5; cmd.Parameters.AddWithValue("?value", new Random().Next()); try { cmd.ExecuteNonQuery(); } catch (MySqlException ex) { Assert.IsTrue(ex.InnerException is TimeoutException); } } scope.Complete(); } MySqlPoolManager.ClearAllPools(); } /// /// Bug #22042 mysql-connector-net-5.0.0-alpha BeginTransaction /// [Test] public void Bug22042() { DbProviderFactory factory = new MySql.Data.MySqlClient.MySqlClientFactory(); using (DbConnection conexion = factory.CreateConnection()) { conexion.ConnectionString = GetConnectionString(true); conexion.Open(); DbTransaction trans = conexion.BeginTransaction(); trans.Rollback(); } } /// /// Bug #26754 EnlistTransaction throws false MySqlExeption "Already enlisted" /// [Test] public void EnlistTransactionNullTest() { try { MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; cmd.Connection.EnlistTransaction(null); } catch { } using (TransactionScope ts = new TransactionScope()) { MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; cmd.Connection.EnlistTransaction(Transaction.Current); } } /// /// Bug #26754 EnlistTransaction throws false MySqlExeption "Already enlisted" /// [Test] public void EnlistTransactionWNestedTrxTest() { MySqlTransaction t = conn.BeginTransaction(); using (TransactionScope ts = new TransactionScope()) { MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; try { cmd.Connection.EnlistTransaction(Transaction.Current); } catch (InvalidOperationException) { /* caught NoNestedTransactions */ } } t.Rollback(); using (TransactionScope ts = new TransactionScope()) { MySqlCommand cmd = new MySqlCommand(); cmd.Connection = conn; cmd.Connection.EnlistTransaction(Transaction.Current); } } [Test] public void ManualEnlistment() { createTable("CREATE TABLE Test (key2 VARCHAR(1), name VARCHAR(100), name2 VARCHAR(100))", "INNODB"); string connStr = GetConnectionString(true) + ";auto enlist=false"; MySqlConnection c = null; using (TransactionScope ts = new TransactionScope()) { c = new MySqlConnection(connStr); c.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES ('a', 'name', 'name2')", c); cmd.ExecuteNonQuery(); } MySqlCommand cmd2 = new MySqlCommand("SELECT COUNT(*) FROM Test", conn); Assert.AreEqual(1, cmd2.ExecuteScalar()); c.Dispose(); KillPooledConnection(connStr); } private void ManuallyEnlistingInitialConnection(bool complete) { createTable("CREATE TABLE Test (key2 VARCHAR(1), name VARCHAR(100), name2 VARCHAR(100))", "INNODB"); string connStr = GetConnectionString(true) + ";auto enlist=false"; using (TransactionScope ts = new TransactionScope()) { using (MySqlConnection c1 = new MySqlConnection(connStr)) { c1.Open(); c1.EnlistTransaction(Transaction.Current); MySqlCommand cmd1 = new MySqlCommand("INSERT INTO Test (key2) VALUES ('a')", c1); cmd1.ExecuteNonQuery(); } using (MySqlConnection c2 = new MySqlConnection(connStr)) { c2.Open(); c2.EnlistTransaction(Transaction.Current); MySqlCommand cmd2 = new MySqlCommand("INSERT INTO Test (key2) VALUES ('b')", c2); cmd2.ExecuteNonQuery(); } if (complete) ts.Complete(); } KillPooledConnection(connStr); } [Test] public void ManuallyEnlistingInitialConnection() { ManuallyEnlistingInitialConnection(true); } [Test] public void ManuallyEnlistingInitialConnectionNoComplete() { ManuallyEnlistingInitialConnection(false); } [Test] public void ManualEnlistmentWithActiveConnection() { using (TransactionScope ts = new TransactionScope()) { string connStr = GetConnectionString(true); using (MySqlConnection c1 = new MySqlConnection(connStr)) { c1.Open(); connStr += "; auto enlist=false"; using (MySqlConnection c2 = new MySqlConnection(connStr)) { c2.Open(); try { c2.EnlistTransaction(Transaction.Current); } catch (NotSupportedException) { } } } } } [Test] public void AttemptToEnlistTwoConnections() { using (TransactionScope ts = new TransactionScope()) { string connStr = GetConnectionString(true); using (MySqlConnection c1 = new MySqlConnection(connStr)) { c1.Open(); using (MySqlConnection c2 = new MySqlConnection(connStr)) { try { c2.Open(); } catch (NotSupportedException) { } } } } } private void NestedScopeInternalTest( TransactionScopeOption nestedOption, bool innerComplete, bool outerComplete, bool expectInnerChangesVisible, bool expectOuterChangesVisible) { createTable("CREATE TABLE T(str varchar(10))", "INNODB"); try { using (TransactionScope outer = new TransactionScope()) { string connStr = GetConnectionString(true); using (MySqlConnection c1 = new MySqlConnection(connStr)) { c1.Open(); MySqlCommand cmd1 = new MySqlCommand("INSERT INTO T VALUES ('outer')", c1); cmd1.ExecuteNonQuery(); using (TransactionScope inner = new TransactionScope(nestedOption)) { MySqlConnection c2; if (nestedOption == TransactionScopeOption.Required) { // inner scope joins already running ambient // transaction, we cannot use new connection here c2 = c1; } else { // when TransactionScopeOption.RequiresNew or // new TransactionScopeOption.Suppress is used, // we have to use a new transaction. We create a // new connection for it. c2 = new MySqlConnection(connStr); c2.Open(); } MySqlCommand cmd2 = new MySqlCommand("INSERT INTO T VALUES ('inner')", c2); cmd2.ExecuteNonQuery(); if (innerComplete) inner.Complete(); // Dispose connection if it was created. if (c2 != c1) c2.Dispose(); } } if (outerComplete) outer.Complete(); } bool innerChangesVisible = ((long)MySqlHelper.ExecuteScalar(conn, "select count(*) from T where str = 'inner'") == 1); bool outerChangesVisible = ((long)MySqlHelper.ExecuteScalar(conn, "select count(*) from T where str = 'outer'") == 1); Assert.AreEqual(innerChangesVisible, expectInnerChangesVisible); Assert.AreEqual(outerChangesVisible, expectOuterChangesVisible); } finally { MySqlHelper.ExecuteNonQuery(conn, "DROP TABLE T"); } } /// /// Test inner/outer scope behavior, with different scope options, /// completing either inner or outer scope, or both. /// [Test] public void NestedScope() { // inner scope joins the ambient scope, neither inner not outer scope completes // Expect empty table. NestedScopeInternalTest(TransactionScopeOption.Required, false, false, false, false); // inner scope joins the ambient scope, inner does not complete, outer completes // Expect exception while disposing outer transaction try { NestedScopeInternalTest(TransactionScopeOption.Required, false, true, false, false); Assert.Fail("expected TransactionAborted exception"); } catch (TransactionAbortedException) { } // inner scope joins the ambient scope, inner completes, outer does not // Expect empty table. NestedScopeInternalTest(TransactionScopeOption.Required, true, false, false, false); // inner scope joins the ambient scope, both complete. // Expect table with entries for inner and outer scope NestedScopeInternalTest(TransactionScopeOption.Required, true, true, true, true); // inner scope creates new transaction, neither inner not outer scope completes // Expect empty table. NestedScopeInternalTest(TransactionScopeOption.RequiresNew, false, false, false, false); // inner scope creates new transaction, inner does not complete, outer completes // Expect changes by outer transaction visible ?? NestedScopeInternalTest(TransactionScopeOption.RequiresNew, false, true, false, true); // inner scope creates new transactiion, inner completes, outer does not // Expect changes by inner transaction visible NestedScopeInternalTest(TransactionScopeOption.RequiresNew, true, false, true, false); // inner scope creates new transaction, both complete NestedScopeInternalTest(TransactionScopeOption.RequiresNew, true, true, true, true); // inner scope suppresses transaction, neither inner not outer scope completes // Expect changes made by inner scope to be visible NestedScopeInternalTest(TransactionScopeOption.Suppress, false, false, true, false); // inner scope supresses transaction, inner does not complete, outer completes // Expect changes by inner scope to be visible ?? NestedScopeInternalTest(TransactionScopeOption.Suppress, true, false, true, false); // inner scope supresses transaction, inner completes, outer does not // Expect changes by inner transaction visible NestedScopeInternalTest(TransactionScopeOption.Suppress, true, false, true, false); // inner scope supresses transaction, both complete NestedScopeInternalTest(TransactionScopeOption.Suppress, true, true, true, true); } private void ReusingSameConnection(bool pooling, bool complete) { int c1Thread; execSQL("TRUNCATE TABLE Test"); using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.MaxValue)) { string connStr = GetConnectionString(true); if (!pooling) connStr += ";pooling=false"; using (MySqlConnection c1 = new MySqlConnection(connStr)) { c1.Open(); MySqlCommand cmd1 = new MySqlCommand("INSERT INTO Test (key2) VALUES ('a')", c1); cmd1.ExecuteNonQuery(); c1Thread = c1.ServerThread; } using (MySqlConnection c2 = new MySqlConnection(connStr)) { c2.Open(); MySqlCommand cmd2 = new MySqlCommand("INSERT INTO Test (key2) VALUES ('b')", c2); cmd2.ExecuteNonQuery(); Assert.AreEqual(c1Thread, c2.ServerThread); } if (complete) ts.Complete(); } MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); if (complete) { Assert.AreEqual(2, dt.Rows.Count); Assert.AreEqual("a", dt.Rows[0][0]); Assert.AreEqual("b", dt.Rows[1][0]); } else { Assert.AreEqual(0, dt.Rows.Count); } } [Test] public void ReusingSameConnection() { createTable("CREATE TABLE Test (key2 VARCHAR(1), name VARCHAR(100), name2 VARCHAR(100))", "INNODB"); ReusingSameConnection(true, true); // Assert.AreEqual(processes + 1, CountProcesses()); ReusingSameConnection(true, false); // Assert.AreEqual(processes + 1, CountProcesses()); ReusingSameConnection(false, true); // Assert.AreEqual(processes + 1, CountProcesses()); ReusingSameConnection(false, false); // Assert.AreEqual(processes + 1, CountProcesses()); } /// /// bug#35330 - even if transaction scope has expired, rows can be inserted into /// the table, due to race condition with the thread doing rollback /// [Test] public void ScopeTimeoutWithMySqlHelper() { execSQL("DROP TABLE IF EXISTS Test"); createTable("CREATE TABLE Test (id int)", "INNODB"); string connStr = GetConnectionString(true); using (new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.FromSeconds(1))) { try { for (int i = 0; ; i++) { MySqlHelper.ExecuteNonQuery(connStr, String.Format("INSERT INTO Test VALUES({0})", i)); ; } } catch (Exception) { } } long count = (long)MySqlHelper.ExecuteScalar(connStr, "select count(*) from test"); Assert.AreEqual(0, count); } /// /// Variation of previous test, with a single connection and maual enlistment. /// Checks that transaction rollback leaves the connection intact (does not close it) /// and checks that no command is possible after scope has expired and /// rollback by timer thread is finished. /// [Test] public void AttemptToUseConnectionAfterScopeTimeout() { execSQL("DROP TABLE IF EXISTS Test"); createTable("CREATE TABLE Test (id int)", "INNODB"); string connStr = GetConnectionString(true); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("select 1", c); using (new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.FromSeconds(1))) { c.EnlistTransaction(Transaction.Current); cmd = new MySqlCommand("select 1", c); try { for (int i = 0; ; i++) { cmd.CommandText = String.Format("INSERT INTO Test VALUES({0})", i); cmd.ExecuteNonQuery(); } } catch (Exception) { // Eat exception } // Here, scope is timed out and rollback is in progress. // Wait until timeout thread finishes rollback then try to // use an aborted connection. Thread.Sleep(500); try { cmd.ExecuteNonQuery(); Assert.Fail("Using aborted transaction"); } catch (TransactionAbortedException) { } } Assert.IsTrue(c.State == ConnectionState.Open); cmd.CommandText = "select count(*) from Test"; long count = (long)cmd.ExecuteScalar(); Assert.AreEqual(0, count); } } /// /// Bug#54681 : Null Reference exception when using transaction /// scope in more that one thread /// [Test] public void TransactionScopeWithThreads() { // use transaction scope in the current thread DoThreadWork(); //use transaction scope in another thread (used to crash with null // reference exception) Thread t = new Thread(new ThreadStart(DoThreadWork)); t.Start(); t.Join(); } /// /// Ensures that a commit after heavy ammount of inserts does not timeout. /// [Test] public void CommitDoesNotTimeout() { const int requiredNumberOfRuns = 1; const int binarySize = 5000000; const int requiredNumberOfRowsPerRun = 100; Debug.WriteLine("Required Number Of Runs :" + requiredNumberOfRuns); Debug.WriteLine("Required Number Of Rows Per Run :" + requiredNumberOfRowsPerRun); suExecSQL("SET GLOBAL max_allowed_packet=64000000"); MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(); using (MySqlConnection connection = new MySqlConnection(GetConnectionString(true))) { connection.Open(); using (MySqlCommand command = new MySqlCommand()) { command.Connection = connection; command.CommandType = CommandType.Text; command.CommandText = "DROP TABLE IF EXISTS test_timeout;"; command.ExecuteNonQuery(); StringBuilder sqlCommand = new StringBuilder(512); sqlCommand.Append("CREATE TABLE test_timeout ("); sqlCommand.Append("identity INT NOT NULL auto_increment, "); sqlCommand.Append("a INT NOT NULL, "); sqlCommand.Append("b INT NOT NULL, "); sqlCommand.Append("c INT NOT NULL, "); sqlCommand.Append("binary_data LONGBLOB NOT NULL, "); sqlCommand.Append("PRIMARY KEY(identity), "); sqlCommand.Append("KEY `abc` (`a`,`b`, `c`) "); sqlCommand.Append(") ENGINE = INNODB"); command.CommandText = sqlCommand.ToString(); command.ExecuteNonQuery(); } for (int numberOfRuns = 0; numberOfRuns < requiredNumberOfRuns; ++numberOfRuns) { using (MySqlTransaction transaction = connection.BeginTransaction()) { Stopwatch stopwatch = Stopwatch.StartNew(); using (MySqlCommand command = new MySqlCommand()) { command.Connection = connection; command.CommandText = "INSERT INTO test_timeout VALUES (?f1, ?f2, ?f3, ?f4, ?f5)"; command.Parameters.Add("?f1", MySqlDbType.Int32); command.Parameters.Add("?f2", MySqlDbType.Int32); command.Parameters.Add("?f3", MySqlDbType.Int32); command.Parameters.Add("?f4", MySqlDbType.Int32); command.Parameters.Add("?f5", MySqlDbType.LongBlob); command.CommandTimeout = 0; command.Prepare(); byte[] buffer; using (MemoryStream stream = new MemoryStream()) { using (BinaryWriter binary = new BinaryWriter(stream)) { int count = 0; while (stream.Position < binarySize) { binary.Write(++count); } } buffer = stream.ToArray(); } for (int i = 0; i < requiredNumberOfRowsPerRun; ++i) { command.Parameters[1].Value = i; command.Parameters[2].Value = i; command.Parameters[3].Value = i; command.Parameters[4].Value = buffer; command.ExecuteNonQuery(); } } transaction.Commit(); Assert.IsNotNull(transaction); stopwatch.Stop(); double seconds = stopwatch.Elapsed.TotalSeconds; double recordsPerSecond = requiredNumberOfRowsPerRun / seconds; StringBuilder sb = new StringBuilder(); sb.AppendFormat("Truncate Result : Insert {0} Took {1:F4}; Per Second {2:F1} ", requiredNumberOfRowsPerRun, seconds, recordsPerSecond); Debug.WriteLine(sb.ToString()); } using (MySqlCommand command = new MySqlCommand()) { command.Connection = connection; command.CommandText = "SELECT * FROM test_timeout"; Stopwatch stopwatch = Stopwatch.StartNew(); int count = 0; using (MySqlDataReader reader = command.ExecuteReader()) { int previous = -1; while (reader.Read()) { int current = reader.GetInt32(0); Assert.Greater(current, previous); previous = current; ++count; } } stopwatch.Stop(); double seconds = stopwatch.Elapsed.TotalSeconds; double recordsPerSecond = count / seconds; StringBuilder sb = new StringBuilder(); sb.AppendFormat("Test Result : Select {0} Took {1:F4}; Per Second {2:F1} ", count, seconds, recordsPerSecond); Debug.WriteLine(sb.ToString()); } using (MySqlCommand command = new MySqlCommand()) { command.Connection = connection; command.CommandText = "TRUNCATE TABLE test_timeout"; command.ExecuteNonQuery(); } } MySqlConnection.ClearPool(connection); } } [Test] [ExpectedException(typeof(NotSupportedException))] public void SnapshotIsolationLevelThrowsNotSupportedException() { using (MySqlConnection connection = new MySqlConnection(GetConnectionString(true))) { connection.Open(); MySqlTransaction transaction = connection.BeginTransaction(System.Data.IsolationLevel.Snapshot); transaction.Commit(); } } private void DoThreadWork() { using (TransactionScope ts = new TransactionScope()) { string connStr = GetConnectionString(true); using (MySqlConnection c1 = new MySqlConnection(connStr)) { c1.Open(); } } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/StoredProcedure.cs0000644000175000017500000010157311127003600025742 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using NUnit.Framework; using System.Globalization; using System.Threading; using MySql.Data.Types; using System.Data.Common; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for StoredProcedure. /// [TestFixture] public class StoredProcedure : BaseTest { private static string fillError = null; public StoredProcedure() { csAdditions = ";procedure cache size=0;"; } /// /// Bug #7623 Adding MySqlParameter causes error if MySqlDbType is Decimal /// [Test] public void ReturningResultset() { if (Version < new Version(5, 0)) return; // create our procedure execSQL("CREATE PROCEDURE spTest(val decimal(10,3)) begin select val; end"); using (MySqlCommand cmd = new MySqlCommand("spTest", conn)) { cmd.CommandType = CommandType.StoredProcedure; MySqlParameter p = cmd.Parameters.Add("?val", MySqlDbType.Decimal); p.Precision = 10; p.Scale = 3; p.Value = 21; decimal id = (decimal)cmd.ExecuteScalar(); Assert.AreEqual(21, id); } } [Test] public void NonQuery() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE Test(id INT, name VARCHAR(20))"); execSQL(@"CREATE PROCEDURE spTest(IN value INT) BEGIN INSERT INTO Test VALUES(value, 'Test'); END"); //setup testing data MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?value", 2); int rowsAffected = cmd.ExecuteNonQuery(); Assert.AreEqual(1, rowsAffected); cmd.CommandText = "SELECT * FROM Test"; cmd.CommandType = CommandType.Text; using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(2, reader.GetInt32(0)); Assert.AreEqual("Test", reader.GetString(1)); Assert.IsFalse(reader.Read()); Assert.IsFalse(reader.NextResult()); } } [Test] public void NoBatch() { if (Version < new Version(5, 0)) return; try { MySqlCommand cmd = new MySqlCommand("spTest;select * from Test", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); Assert.Fail("Should have thrown an exception"); } catch (Exception) { } } [Test] public void WrongParameters() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest(p1 INT) BEGIN SELECT 1; END"); try { MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?p2", 1); cmd.ExecuteNonQuery(); Assert.Fail("Should have thrown an exception"); } catch (Exception) { } } [Test] public void NoInOutMarker() { if (Version < new Version(5, 0)) return; // create our procedure execSQL("CREATE PROCEDURE spTest( valin varchar(50) ) BEGIN SELECT valin; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?valin", "myvalue"); object val = cmd.ExecuteScalar(); Assert.AreEqual("myvalue", val); } [Test] public void NoSPOnPre50() { if (Version < new Version(5, 0)) return; try { MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); Assert.Fail("This should not have worked"); } catch (Exception) { } } /// /// Bug #13590 ExecuteScalar returns only Int64 regardless of actual SQL type /// [Test] public void ExecuteScalar2() { if (Version < new Version(5, 0)) return; // create our procedure execSQL("CREATE PROCEDURE spTest() " + "BEGIN DECLARE myVar1 INT; SET myVar1 := 1; SELECT myVar1; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; object result = cmd.ExecuteScalar(); Assert.AreEqual(1, result); Assert.IsTrue(result is Int32); } [Test] public void MultipleResultsets() { if (Version < new Version(5, 0)) return; MultipleResultsetsImpl(false); } [Test] public void MultipleResultsetsPrepared() { if (Version < new Version(5, 0)) return; MultipleResultsetsImpl(true); } private void MultipleResultsetsImpl(bool prepare) { if (Version < new Version(5, 0)) return; // create our procedure execSQL("CREATE PROCEDURE spTest() " + "BEGIN SELECT 1; SELECT 2; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); if (prepare) cmd.Prepare(); cmd.CommandType = CommandType.StoredProcedure; MySqlDataReader reader = cmd.ExecuteReader(); Assert.AreEqual(true, reader.Read()); Assert.AreEqual(true, reader.NextResult()); Assert.AreEqual(true, reader.Read()); Assert.AreEqual(false, reader.NextResult()); Assert.AreEqual(false, reader.Read()); reader.Close(); DataSet ds = new DataSet(); MySqlCommand cmd2 = new MySqlCommand("spTest", conn); cmd2.CommandType = CommandType.StoredProcedure; MySqlDataAdapter da = new MySqlDataAdapter(cmd2); da.FillError += new FillErrorEventHandler(da_FillError); fillError = null; da.Fill(ds); Assert.AreEqual(2, ds.Tables.Count); Assert.AreEqual(1, ds.Tables[0].Rows.Count); Assert.AreEqual(1, ds.Tables[1].Rows.Count); Assert.AreEqual(1, ds.Tables[0].Rows[0][0]); Assert.AreEqual(2, ds.Tables[1].Rows[0][0]); Assert.IsNull(fillError); } private static void da_FillError(object sender, FillErrorEventArgs e) { fillError = e.Errors.Message; e.Continue = true; } [Test] public void ExecuteWithCreate() { if (Version < new Version(5, 0)) return; // create our procedure string sql = "CREATE PROCEDURE spTest(IN var INT) BEGIN SELECT var; END; call spTest(?v)"; MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.Parameters.Add(new MySqlParameter("?v", 33)); object val = cmd.ExecuteScalar(); Assert.AreEqual(33, val); } /// /// Bug #9722 Connector does not recognize parameters separated by a linefeed /// [Test] public void OtherProcSigs() { if (Version < new Version(5, 0)) return; // create our procedure execSQL("CREATE PROCEDURE spTest(IN \r\nvalin DECIMAL(10,2),\nIN val2 INT) " + "SQL SECURITY INVOKER BEGIN SELECT valin; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?valin", 20.4); cmd.Parameters.AddWithValue("?val2", 4); decimal val = (decimal)cmd.ExecuteScalar(); Decimal d = new Decimal(20.4); Assert.AreEqual(d, val); // create our second procedure execSQL("DROP PROCEDURE IF EXISTS spTest"); execSQL("CREATE PROCEDURE spTest( \r\n) BEGIN SELECT 4; END"); cmd.Parameters.Clear(); object val1 = cmd.ExecuteScalar(); Assert.AreEqual(4, val1); } /// /// Bug #11450 Connector/Net, current database and stored procedures /// [Test] public void NoDefaultDatabase() { if (Version < new Version(5, 0)) return; // create our procedure execSQL("CREATE PROCEDURE spTest() BEGIN SELECT 4; END"); string newConnStr = GetConnectionString(false); using (MySqlConnection c = new MySqlConnection(newConnStr)) { c.Open(); MySqlCommand cmd2 = new MySqlCommand(String.Format("use `{0}`", database0), c); cmd2.ExecuteNonQuery(); MySqlCommand cmd = new MySqlCommand("spTest", c); cmd.CommandType = CommandType.StoredProcedure; object val = cmd.ExecuteScalar(); Assert.AreEqual(4, val); cmd2.CommandText = String.Format("use `{0}`", database1); cmd2.ExecuteNonQuery(); cmd.CommandText = String.Format("`{0}`.spTest", database0); val = cmd.ExecuteScalar(); Assert.AreEqual(4, val); } } /// /// Bug #13590 ExecuteScalar returns only Int64 regardless of actual SQL type /// /* [Test] public void TestSelectingInts() { execSQL("CREATE PROCEDURE spTest() BEGIN DECLARE myVar INT; " + "SET MyVar := 1; SELECT CAST(myVar as SIGNED); END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; object val = cmd.ExecuteScalar(); Assert.AreEqual(1, val, "Checking value"); Assert.IsTrue(val is Int32, "Checking type"); } */ /// /// Bug #11386 Numeric parameters with Precision and Scale not taken into account by Connector /// [Test] public void DecimalAsParameter() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest(IN d DECIMAL(19,4)) BEGIN SELECT d; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?d", 21); decimal d = (decimal)cmd.ExecuteScalar(); Assert.AreEqual(21, d); } /// /// Bug #6902 Errors in parsing stored procedure parameters /// [Test] public void ParmWithCharacterSet() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest(P longtext character set utf8) " + "BEGIN SELECT P; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?P", "This is my value"); string p = (string)cmd.ExecuteScalar(); Assert.AreEqual("This is my value", p); } /// /// Bug #13753 Exception calling stored procedure with special characters in parameters /// [Test] public void SpecialCharacters() { if (Version < new Version(5, 0)) return; execSQL("SET sql_mode=ANSI_QUOTES"); try { execSQL("CREATE PROCEDURE spTest(\"@Param1\" text) BEGIN SELECT \"@Param1\"; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.Parameters.AddWithValue("@Param1", "This is my value"); cmd.CommandType = CommandType.StoredProcedure; string val = (string)cmd.ExecuteScalar(); Assert.AreEqual("This is my value", val); } finally { execSQL("SET sql_mode=\"\""); } } [Test] public void CallingSPWithPrepare() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest(P int) BEGIN SELECT P; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?P", 33); cmd.Prepare(); int p = (int)cmd.ExecuteScalar(); Assert.AreEqual(33, p); } /// /// Bug #13927 Multiple Records to same Table in Transaction Problem /// [Test] public void MultipleRecords() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE Test (id INT, name VARCHAR(20))"); execSQL("CREATE PROCEDURE spTest(id int, str VARCHAR(45)) " + "BEGIN INSERT INTO Test VALUES(id, str); END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?id", 1); cmd.Parameters.AddWithValue("?str", "First record"); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("?id", 2); cmd.Parameters.AddWithValue("?str", "Second record"); cmd.ExecuteNonQuery(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(1, dt.Rows[0]["id"]); Assert.AreEqual(2, dt.Rows[1]["id"]); Assert.AreEqual("First record", dt.Rows[0]["name"]); Assert.AreEqual("Second record", dt.Rows[1]["name"]); } /// /// Bug #16788 Only byte arrays and strings can be serialized by MySqlBinary /// [Test] public void Bug16788() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE Test (id integer(9), state varchar(2))"); execSQL("CREATE PROCEDURE spTest(IN p1 integer(9), IN p2 varchar(2)) " + "BEGIN " + "INSERT INTO Test (id, state) VALUES (p1, p2); " + "END"); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "spTest"; cmd.Parameters.Add("?p1", MySqlDbType.UInt16, 9); cmd.Parameters["?p1"].Value = 44; cmd.Parameters.Add("?p2", MySqlDbType.VarChar, 2); cmd.Parameters["?p2"].Value = "ss"; cmd.ExecuteNonQuery(); } #if !CF [Explicit] [Test] public void ProcedureCache() { if (Version < new Version(5, 0)) return; // open a new connection using a procedure cache string connStr = GetConnectionString(true); connStr += ";procedure cache size=25;logging=true"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); // install our custom trace listener GenericListener myListener = new GenericListener(); System.Diagnostics.Trace.Listeners.Add(myListener); for (int x = 0; x < 10; x++) { execSQL("CREATE PROCEDURE spTest" + x + "() BEGIN SELECT 1; END"); MySqlCommand cmd = new MySqlCommand("spTest" + x, c); cmd.CommandType = CommandType.StoredProcedure; for (int y = 0; y < 20; y++) { cmd.ExecuteNonQuery(); } } // remove our custom trace listener System.Diagnostics.Trace.Listeners.Remove(myListener); // now see how many times our listener recorded a cache hit Assert.AreEqual(190, myListener.Find("from procedure cache")); Assert.AreEqual(10, myListener.Find("from server")); } } #endif /// /// Bug #20581 Null Reference Exception when closing reader after stored procedure. /// [Test] public void Bug20581() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest(p int) BEGIN SELECT p; END"); MySqlParameter param1; MySqlCommand command = new MySqlCommand("spTest", conn); command.CommandType = CommandType.StoredProcedure; param1 = command.Parameters.Add("?p", MySqlDbType.Int32); param1.Value = 3; command.Prepare(); using (MySqlDataReader reader = command.ExecuteReader()) { reader.Read(); } } /// /// Bug #17046 Null pointer access when stored procedure is used /// [Test] public void PreparedReader() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE Test (id int(10) unsigned NOT NULL default '0', " + "val int(10) unsigned default NULL, PRIMARY KEY (id)) " + "ENGINE=InnoDB DEFAULT CHARSET=utf8"); execSQL("CREATE PROCEDURE spTest (IN pp INTEGER) " + "select * from Test where id > pp "); MySqlCommand c = new MySqlCommand("spTest", conn); c.CommandType = CommandType.StoredProcedure; IDataParameter p = c.CreateParameter(); p.ParameterName = "?pp"; p.Value = 10; c.Parameters.Add(p); c.Prepare(); using (MySqlDataReader reader = c.ExecuteReader()) { while (reader.Read()) { } } } #if !CF /// /// Bug #22452 MySql.Data.MySqlClient.MySqlException: /// [Test] public void TurkishStoredProcs() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest(IN p_paramname INT) BEGIN SELECT p_paramname; END"); CultureInfo uiCulture = Thread.CurrentThread.CurrentUICulture; CultureInfo culture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("tr-TR"); try { MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.Parameters.AddWithValue("?p_paramname", 2); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteScalar(); } finally { Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = uiCulture; } } #endif /// /// Bug #23268 System.FormatException when invoking procedure with ENUM input parameter /// [Test] public void ProcEnumParamTest() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE Test(str VARCHAR(50), e ENUM ('P','R','F','E'), i INT(6))"); execSQL("CREATE PROCEDURE spTest(IN p_enum ENUM('P','R','F','E')) BEGIN " + "INSERT INTO Test (str, e, i) VALUES (null, p_enum, 55); END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?p_enum", "P"); cmd.Parameters["?p_enum"].Direction = ParameterDirection.Input; using (MySqlDataReader reader = cmd.ExecuteReader()) { } cmd.CommandText = "SELECT e FROM Test"; cmd.CommandType = CommandType.Text; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("P", reader.GetString(0)); } } /// /// Bug #25609 MySqlDataAdapter.FillSchema /// [Test] public void GetSchema() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest() BEGIN SELECT * FROM Test; END"); execSQL(@"CREATE TABLE Test(id INT AUTO_INCREMENT, name VARCHAR(20), PRIMARY KEY (id)) "); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly); reader.Read(); reader.Close(); MySqlDataAdapter da = new MySqlDataAdapter(cmd); DataTable schema = new DataTable(); da.FillSchema(schema, SchemaType.Source); Assert.AreEqual(2, schema.Columns.Count); } /// /// Bug #26139 MySqlCommand.LastInsertedId doesn't work for stored procedures /// Currently this is borked on the server so we are marking this as notworking /// until the server has this fixed. /// /* [Test] public void LastInsertId() { execSQL("CREATE TABLE Test (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(200))"); execSQL("INSERT INTO Test VALUES (NULL, 'Test1')"); execSQL("CREATE PROCEDURE spTest() BEGIN " + "INSERT INTO Test VALUES (NULL, 'test'); END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); Assert.AreEqual(2, cmd.LastInsertedId); } */ /// /// Bug #27093 Exception when using large values in IN UInt64 parameters /// [Test] public void UsingUInt64AsParam() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE TABLE Test(f1 bigint(20) unsigned NOT NULL, PRIMARY KEY(f1)) ENGINE=InnoDB DEFAULT CHARSET=utf8"); execSQL(@"CREATE PROCEDURE spTest(in _val bigint unsigned) BEGIN insert into Test set f1=_val; END"); DbCommand cmd = new MySqlCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "spTest"; DbParameter param = cmd.CreateParameter(); param.DbType = DbType.UInt64; param.Direction = ParameterDirection.Input; param.ParameterName = "?_val"; ulong bigval = long.MaxValue; bigval += 1000; param.Value = bigval; cmd.Parameters.Add(param); cmd.ExecuteNonQuery(); } /// /// Bug #29526 syntax error: "show create procedure" with catalog names containing hyphens /// [Test] public void CatalogWithHyphens() { if (Version < new Version(5, 0)) return; // make sure this test is valid Assert.IsTrue(database0.IndexOf('-') != -1); MySqlCommand cmd = new MySqlCommand("CREATE PROCEDURE spTest() BEGIN SELECT 1; END", conn); cmd.ExecuteNonQuery(); cmd.CommandText = "spTest"; cmd.CommandType = CommandType.StoredProcedure; Assert.AreEqual(1, cmd.ExecuteScalar()); } [Test] public void ComplexDefinition() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE PROCEDURE `spTest`() NOT DETERMINISTIC CONTAINS SQL SQL SECURITY DEFINER COMMENT '' BEGIN SELECT 1,2,3; END"); MySqlCommand command = new MySqlCommand("spTest", conn); command.CommandType = CommandType.StoredProcedure; using (MySqlDataReader reader = command.ExecuteReader()) { } } [Test] public void AmbiguousColumns() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE t1 (id INT)"); execSQL("CREATE TABLE t2 (id1 INT, id INT)"); execSQL(@"CREATE PROCEDURE spTest() BEGIN SELECT * FROM t1; SELECT id FROM t1 JOIN t2 on t1.id=t2.id; SELECT * FROM t2; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = 0; MySqlDataAdapter da = new MySqlDataAdapter(cmd); DataSet ds = new DataSet(); try { da.Fill(ds); Assert.Fail("The above should have thrown an exception"); } catch (Exception) { } } /// /// Bug #41034 .net parameter not found in the collection /// [Test] public void SPWithSpaceInParameterType() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest(myparam decimal (8,2)) BEGIN SELECT 1; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.Parameters.Add("@myparam", MySqlDbType.Decimal).Value = 20; cmd.CommandType = CommandType.StoredProcedure; object o = cmd.ExecuteScalar(); Assert.AreEqual(1, o); } private void ParametersInReverseOrderInternal(bool isOwner) { if (Version.Major < 5) return; execSQL(@"CREATE PROCEDURE spTest(IN p_1 VARCHAR(5), IN p_2 VARCHAR(5)) BEGIN SELECT p_1 AS P1, p_2 AS P2; END"); string spName = "spTest"; string connStr = GetConnectionString(true); if (!isOwner) connStr += ";use procedure bodies=false"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand(spName, c); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?p_2", ("World")); cmd.Parameters[0].DbType = DbType.AnsiString; cmd.Parameters[0].Direction = ParameterDirection.Input; cmd.Parameters.AddWithValue("?p_1", ("Hello")); cmd.Parameters[1].DbType = DbType.AnsiString; cmd.Parameters[1].Direction = ParameterDirection.Input; MySqlDataAdapter da = new MySqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (!isOwner) { Assert.AreEqual("World", dt.Rows[0][0]); Assert.AreEqual("Hello", dt.Rows[0][1]); } else { Assert.AreEqual("Hello", dt.Rows[0]["P1"]); Assert.AreEqual("World", dt.Rows[0]["P2"]); } } } [Test] public void ParametersInReverseOrderNotOwner() { ParametersInReverseOrderInternal(false); } [Test] public void ParametersInReverseOrderOwner() { ParametersInReverseOrderInternal(true); } [Test] public void DeriveParameters() { if (Version < new Version(5, 0)) return; if (Version > new Version(6, 0, 6)) return; execSQL(@"CREATE PROCEDURE spTest (id INT, name VARCHAR(20)) BEGIN SELECT name; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; MySqlCommandBuilder.DeriveParameters(cmd); Assert.AreEqual(2, cmd.Parameters.Count); } /// /// Bug #52562 Sometimes we need to reload cached function parameters /// [Test] public void ProcedureCacheMiss() { execSQL("CREATE PROCEDURE spTest(id INT) BEGIN SELECT 1; END"); string connStr = GetConnectionString(true) + ";procedure cache size=25"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("spTest", c); cmd.Parameters.AddWithValue("@id", 1); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteScalar(); execSQL("DROP PROCEDURE spTest"); execSQL("CREATE PROCEDURE spTest(id INT, id2 INT, id3 INT) BEGIN SELECT 1; END"); cmd.Parameters.AddWithValue("@id2", 2); cmd.Parameters.AddWithValue("@id3", 3); cmd.ExecuteScalar(); } } /// /// Verifies that GetProcedureParameters does not require SELECT permission on mysql.proc table. /// [Test] public void GetProcedureParametersDoesNotRequireSelectFromMySqlProceduresTable() { if (Version < new Version(5, 5, 3)) return; suExecSQL(String.Format("GRANT ALL ON `{0}`.* to 'simpleuser' identified by 'simpleuser'", database0)); execSQL("DROP PROCEDURE IF EXISTS spTest"); execSQL(@"CREATE PROCEDURE spTest(id INT, name VARCHAR(20)) BEGIN SELECT name; END"); string connStr = GetConnectionString("simpleuser", "simpleuser", true) + ";use procedure bodies=false"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); string[] restrictions = new string[4]; restrictions[1] = c.Database; restrictions[2] = "spTest"; DataTable procTable = c.GetSchema("procedures", restrictions); ISSchemaProvider isp = new ISSchemaProvider(c); string[] rest = isp.CleanRestrictions(restrictions); DataTable parametersTable = isp.GetProcedureParameters(rest, procTable); Assert.IsNotNull(parametersTable); } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/BlobTests.cs0000644000175000017500000003011211127003600024520 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Threading; using MySql.Data.MySqlClient; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for BlobTests. /// [TestFixture] public class BlobTests : BaseTest { [Test] public void InsertBinary() { int lenIn = 400000; byte[] dataIn = Utils.CreateBlob(lenIn); execSQL("CREATE TABLE Test (id INT NOT NULL, blob1 LONGBLOB, PRIMARY KEY(id))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?b1)", conn); cmd.Parameters.Add(new MySqlParameter("?id", 1)); cmd.Parameters.Add(new MySqlParameter("?b1", dataIn)); int rows = cmd.ExecuteNonQuery(); byte[] dataIn2 = Utils.CreateBlob(lenIn); cmd.Parameters[0].Value = 2; cmd.Parameters[1].Value = dataIn2; rows += cmd.ExecuteNonQuery(); Assert.AreEqual(2, rows, "Checking insert rowcount"); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.AreEqual(true, reader.HasRows, "Checking HasRows"); reader.Read(); byte[] dataOut = new byte[lenIn]; long lenOut = reader.GetBytes(1, 0, dataOut, 0, lenIn); Assert.AreEqual(lenIn, lenOut, "Checking length of binary data (row 1)"); // now see if the buffer is intact for (int x = 0; x < dataIn.Length; x++) Assert.AreEqual(dataIn[x], dataOut[x], "Checking first binary array at " + x); // now we test chunking int pos = 0; int lenToRead = dataIn.Length; while (lenToRead > 0) { int size = Math.Min(lenToRead, 1024); int read = (int)reader.GetBytes(1, pos, dataOut, pos, size); lenToRead -= read; pos += read; } // now see if the buffer is intact for (int x = 0; x < dataIn.Length; x++) Assert.AreEqual(dataIn[x], dataOut[x], "Checking first binary array at " + x); reader.Read(); lenOut = reader.GetBytes(1, 0, dataOut, 0, lenIn); Assert.AreEqual(lenIn, lenOut, "Checking length of binary data (row 2)"); // now see if the buffer is intact for (int x = 0; x < dataIn2.Length; x++) Assert.AreEqual(dataIn2[x], dataOut[x], "Checking second binary array at " + x); } } [Test] public void GetChars() { InternalGetChars(false); } [Test] public void GetCharsPrepared() { if (Version < new Version(4, 1)) return; InternalGetChars(true); } private void InternalGetChars(bool prepare) { execSQL("CREATE TABLE Test (id INT NOT NULL, text1 LONGTEXT, PRIMARY KEY(id))"); char[] data = new char[20000]; for (int x = 0; x < data.Length; x++) data[x] = (char)(65 + (x % 20)); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (1, ?text1)", conn); cmd.Parameters.AddWithValue("?text1", data); if (prepare) cmd.Prepare(); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; cmd.Parameters.Clear(); if (prepare) cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); // now we test chunking char[] dataOut = new char[data.Length]; int pos = 0; int lenToRead = data.Length; while (lenToRead > 0) { int size = Math.Min(lenToRead, 1024); int read = (int)reader.GetChars(1, pos, dataOut, pos, size); lenToRead -= read; pos += read; } // now see if the buffer is intact for (int x = 0; x < data.Length; x++) Assert.AreEqual(data[x], dataOut[x], "Checking first text array at " + x); } } [Test] public void InsertText() { InternalInsertText(false); } [Test] public void InsertTextPrepared() { if (Version < new Version(4, 1)) return; InternalInsertText(true); } private void InternalInsertText(bool prepare) { execSQL("CREATE TABLE Test (id INT NOT NULL, blob1 LONGBLOB, text1 LONGTEXT, PRIMARY KEY(id))"); byte[] data = new byte[1024]; for (int x = 0; x < 1024; x++) data[x] = (byte)(65 + (x % 20)); // Create sample table MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (1, ?b1, ?t1)", conn); cmd.Parameters.Add(new MySqlParameter("?t1", data)); cmd.Parameters.Add(new MySqlParameter("?b1", "This is my blob data")); if (prepare) cmd.Prepare(); int rows = cmd.ExecuteNonQuery(); Assert.AreEqual(1, rows, "Checking insert rowcount"); cmd.CommandText = "INSERT INTO Test VALUES(2, ?b1, ?t1)"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("?t1", DBNull.Value); string str = "This is my text value"; cmd.Parameters.Add(new MySqlParameter("?b1", MySqlDbType.LongBlob, str.Length, ParameterDirection.Input, true, 0, 0, "b1", DataRowVersion.Current, str)); rows = cmd.ExecuteNonQuery(); Assert.AreEqual(1, rows, "Checking insert rowcount"); cmd.CommandText = "SELECT * FROM Test"; if (prepare) cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.AreEqual(true, reader.HasRows, "Checking HasRows"); Assert.IsTrue(reader.Read()); Assert.AreEqual("This is my blob data", reader.GetString(1)); string s = reader.GetString(2); Assert.AreEqual(1024, s.Length, "Checking length returned "); Assert.AreEqual("ABCDEFGHI", s.Substring(0, 9), "Checking first few chars of string"); Assert.IsTrue(reader.Read()); Assert.AreEqual(DBNull.Value, reader.GetValue(2)); Assert.AreEqual("This is my text value", reader.GetString(1)); } } [Test] public void UpdateDataSet() { execSQL("CREATE TABLE Test (id INT NOT NULL, blob1 LONGBLOB, text1 LONGTEXT, PRIMARY KEY(id))"); execSQL("INSERT INTO Test VALUES( 1, NULL, 'Text field' )"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataTable dt = new DataTable(); da.Fill(dt); string s = (string)dt.Rows[0][2]; Assert.AreEqual("Text field", s); byte[] inBuf = Utils.CreateBlob(512); dt.Rows[0].BeginEdit(); dt.Rows[0]["blob1"] = inBuf; dt.Rows[0].EndEdit(); DataTable changes = dt.GetChanges(); da.Update(changes); dt.AcceptChanges(); dt.Clear(); da.Fill(dt); cb.Dispose(); byte[] outBuf = (byte[])dt.Rows[0]["blob1"]; Assert.AreEqual(inBuf.Length, outBuf.Length, "checking length of updated buffer"); for (int y = 0; y < inBuf.Length; y++) Assert.AreEqual(inBuf[y], outBuf[y], "checking array data"); } [Test] public void GetCharsOnLongTextColumn() { execSQL("CREATE TABLE Test (id INT NOT NULL, blob1 LONGBLOB, text1 LONGTEXT, PRIMARY KEY(id))"); execSQL("INSERT INTO Test (id, text1) VALUES(1, 'Test')"); MySqlCommand cmd = new MySqlCommand("SELECT id, text1 FROM Test", conn); char[] buf = new char[2]; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); reader.GetChars(1, 0, buf, 0, 2); Assert.AreEqual('T', buf[0]); Assert.AreEqual('e', buf[1]); } } [Test] public void MediumIntBlobSize() { execSQL("CREATE TABLE test (id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, " + "image MEDIUMBLOB NOT NULL, imageSize MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT 0, " + "PRIMARY KEY (id))"); byte[] image = new byte[2048]; for (int x = 0; x < image.Length; x++) image[x] = (byte)(x % 47); MySqlCommand cmd = new MySqlCommand("INSERT INTO test VALUES(NULL, ?image, ?size)", conn); cmd.Parameters.AddWithValue("?image", image); cmd.Parameters.AddWithValue("?size", image.Length); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT imageSize, length(image), image FROM test WHERE id=?id"; cmd.Parameters.AddWithValue("?id", 1); cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); uint actualsize = reader.GetUInt32(1); Assert.AreEqual(image.Length, actualsize); uint size = reader.GetUInt32(0); byte[] outImage = new byte[size]; long len = reader.GetBytes(reader.GetOrdinal("image"), 0, outImage, 0, (int)size); Assert.AreEqual(image.Length, size); Assert.AreEqual(image.Length, len); } } [Test] public void BlobBiggerThanMaxPacket() { suExecSQL("SET GLOBAL max_allowed_packet=" + 500*1024); execSQL("CREATE TABLE test (id INT(10), image BLOB)"); using (MySqlConnection c = new MySqlConnection(GetConnectionString(true))) { c.Open(); byte[] image = Utils.CreateBlob(1000000); MySqlCommand cmd = new MySqlCommand("INSERT INTO test VALUES(NULL, ?image)", c); cmd.Parameters.AddWithValue("?image", image); try { cmd.ExecuteNonQuery(); Assert.Fail("This should have thrown an exception"); } catch (MySqlException) { } } } } #region Configs #if !CF [Category("Compressed")] public class BlobTestsSocketCompressed : BlobTests { protected override string GetConnectionInfo() { return String.Format("port={0};compress=true", port); } } [Category("Pipe")] public class BlobTestsPipe : BlobTests { protected override string GetConnectionInfo() { return String.Format("protocol=pipe;pipe name={0}", pipeName); } } [Category("Compressed")] [Category("Pipe")] public class BlobTestsPipeCompressed : BlobTests { protected override string GetConnectionInfo() { return String.Format("protocol=pipe;pipe name={0};compress=true", pipeName); } } [Category("SharedMemory")] public class BlobTestsSharedMemory : BlobTests { protected override string GetConnectionInfo() { return String.Format("protocol=memory; shared memory name={0}", memoryName); } } [Category("Compressed")] [Category("SharedMemory")] public class BlobTestsSharedMemoryCompressed : BlobTests { protected override string GetConnectionInfo() { return String.Format("protocol=memory; shared memory name={0};compress=true", memoryName); } } #endif #endregion }mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/CultureTests.cs0000644000175000017500000001512711127003600025276 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using System.Globalization; using System.Threading; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class CultureTests : BaseTest { #if !CF [Test] public void TestFloats() { InternalTestFloats(false); } [Test] public void TestFloatsPrepared() { if (Version < new Version(4, 1)) return; InternalTestFloats(true); } private void InternalTestFloats(bool prepared) { CultureInfo curCulture = Thread.CurrentThread.CurrentCulture; CultureInfo curUICulture = Thread.CurrentThread.CurrentUICulture; CultureInfo c = new CultureInfo("de-DE"); Thread.CurrentThread.CurrentCulture = c; Thread.CurrentThread.CurrentUICulture = c; execSQL("CREATE TABLE Test (fl FLOAT, db DOUBLE, dec1 DECIMAL(5,2))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?fl, ?db, ?dec)", conn); cmd.Parameters.Add("?fl", MySqlDbType.Float); cmd.Parameters.Add("?db", MySqlDbType.Double); cmd.Parameters.Add("?dec", MySqlDbType.Decimal); cmd.Parameters[0].Value = 2.3; cmd.Parameters[1].Value = 4.6; cmd.Parameters[2].Value = 23.82; if (prepared) cmd.Prepare(); int count = cmd.ExecuteNonQuery(); Assert.AreEqual(1, count); try { cmd.CommandText = "SELECT * FROM Test"; if (prepared) cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual(2.3, (decimal)reader.GetFloat(0)); Assert.AreEqual(4.6, reader.GetDouble(1)); Assert.AreEqual(23.82, reader.GetDecimal(2)); } } finally { Thread.CurrentThread.CurrentCulture = curCulture; Thread.CurrentThread.CurrentUICulture = curUICulture; } } /// /// Bug #8228 turkish character set causing the error /// [Test] public void Turkish() { CultureInfo curCulture = Thread.CurrentThread.CurrentCulture; CultureInfo curUICulture = Thread.CurrentThread.CurrentUICulture; CultureInfo c = new CultureInfo("tr-TR"); Thread.CurrentThread.CurrentCulture = c; Thread.CurrentThread.CurrentUICulture = c; using (MySqlConnection newConn = new MySqlConnection(GetConnectionString(true))) { newConn.Open(); } Thread.CurrentThread.CurrentCulture = curCulture; Thread.CurrentThread.CurrentUICulture = curUICulture; } /// /// Bug #29931 Connector/NET does not handle Saudi Hijri calendar correctly /// [Test] public void ArabicCalendars() { execSQL("CREATE TABLE test(dt DATETIME)"); execSQL("INSERT INTO test VALUES ('2007-01-01 12:30:45')"); CultureInfo curCulture = Thread.CurrentThread.CurrentCulture; CultureInfo curUICulture = Thread.CurrentThread.CurrentUICulture; CultureInfo c = new CultureInfo("ar-SA"); Thread.CurrentThread.CurrentCulture = c; Thread.CurrentThread.CurrentUICulture = c; MySqlCommand cmd = new MySqlCommand("SELECT dt FROM test", conn); DateTime dt = (DateTime)cmd.ExecuteScalar(); Assert.AreEqual(2007, dt.Year); Assert.AreEqual(1, dt.Month); Assert.AreEqual(1, dt.Day); Assert.AreEqual(12, dt.Hour); Assert.AreEqual(30, dt.Minute); Assert.AreEqual(45, dt.Second); Thread.CurrentThread.CurrentCulture = curCulture; Thread.CurrentThread.CurrentUICulture = curUICulture; } /// /// Bug #52187 FunctionsReturnString=true messes up decimal separator /// [Test] public void FunctionsReturnStringAndDecimal() { execSQL("CREATE TABLE bug52187a (a decimal(5,2) not null)"); execSQL("CREATE TABLE bug52187b (b decimal(5,2) not null)"); execSQL("insert into bug52187a values (1.25)"); execSQL("insert into bug52187b values (5.99)"); CultureInfo curCulture = Thread.CurrentThread.CurrentCulture; CultureInfo curUICulture = Thread.CurrentThread.CurrentUICulture; CultureInfo c = new CultureInfo("pt-PT"); Thread.CurrentThread.CurrentCulture = c; Thread.CurrentThread.CurrentUICulture = c; string connStr = GetConnectionString(true) + ";functions return string=true"; try { using (MySqlConnection con = new MySqlConnection(connStr)) { con.Open(); MySqlDataAdapter da = new MySqlDataAdapter( "select *,(select b from bug52187b) as field_b from bug52187a", con); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(1.25, dt.Rows[0][0]); Assert.AreEqual(5.99, dt.Rows[0][1]); } } finally { Thread.CurrentThread.CurrentCulture = curCulture; Thread.CurrentThread.CurrentUICulture = curUICulture; } } #endif } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/Properties/0000755000175000017500000000000011127003600024427 5ustar directhexdirecthexmysql-connector-net-6.4.3/Tests/MySql.Data.Tests/Properties/AssemblyInfo.cs0000644000175000017500000000644711127003600027364 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Reflection; using System.Runtime.CompilerServices; using System.Security; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("MySqlClientTests")] [assembly: AssemblyDescription("Test fixtures for MySQL Connector/Net")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Oracle")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Copyright 2004-2010, Oracle")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("ConnectorNet")] #if !CF [assembly: AllowPartiallyTrustedCallers] #endifmysql-connector-net-6.4.3/Tests/MySql.Data.Tests/Properties/Setup.sql0000644000175000017500000000122111127003600026244 0ustar directhexdirecthexDROP DATABASE IF EXISTS `[database0]`; CREATE DATABASE `[database0]`; GRANT ALL ON `[database0]`.* to 'test'@'localhost' IDENTIFIED BY 'test'; GRANT ALL ON `[database0]`.* to 'test'@'%' IDENTIFIED BY 'test'; DROP DATABASE IF EXISTS `[database1]`; CREATE DATABASE `[database1]`; GRANT ALL ON `[database1]`.* to 'test'@'localhost' IDENTIFIED BY 'test'; GRANT ALL ON `[database1]`.* to 'test'@'%' IDENTIFIED BY 'test'; FLUSH PRIVILEGES; SET GLOBAL max_allowed_packet = 1048576; DELETE FROM mysql.user WHERE length(user) = 0; DELETE FROM mysql.user WHERE user='nopass'; DELETE FROM mysql.user WHERE user='quotedUser'; FLUSH PRIVILEGES; mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/CharacterSetTests.cs0000644000175000017500000006225611127003600026230 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // <http://www.mysql.com/about/legal/licensing/foss-exception.html>. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using System.Globalization; using System.Threading; using NUnit.Framework; using System.Text; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class CharacterSetTests : BaseTest { [Test] public void UseFunctions() { execSQL("CREATE TABLE Test (valid char, UserCode varchar(100), password varchar(100)) CHARSET latin1"); MySqlConnection c = new MySqlConnection(conn.ConnectionString + ";charset=latin1"); c.Open(); MySqlCommand cmd = new MySqlCommand("SELECT valid FROM Test WHERE Valid = 'Y' AND " + "UserCode = 'username' AND Password = AES_ENCRYPT('Password','abc')", c); cmd.ExecuteScalar(); c.Close(); } [Test] public void VarBinary() { if (Version < new Version(4, 1)) return; createTable("CREATE TABLE test (id int, name varchar(200) collate utf8_bin) charset utf8", "InnoDB"); execSQL("INSERT INTO test VALUES (1, 'Test1')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); object o = reader.GetValue(1); Assert.IsTrue(o is string); } } [Test] public void Latin1Connection() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (id INT, name VARCHAR(200)) CHARSET latin1"); execSQL("INSERT INTO Test VALUES( 1, _latin1 'Test')"); MySqlConnection c = new MySqlConnection(conn.ConnectionString + ";charset=latin1"); c.Open(); MySqlCommand cmd = new MySqlCommand("SELECT id FROM Test WHERE name LIKE 'Test'", c); object id = cmd.ExecuteScalar(); Assert.AreEqual(1, id); c.Close(); } /// <summary> /// Bug #11621 connector does not support charset cp1250 /// </summary> /* [Test] public void CP1250Connection() { execSQL("CREATE TABLE Test (name VARCHAR(200)) CHARSET cp1250"); MySqlConnection c = new MySqlConnection(conn.ConnectionString + ";charset=cp1250"); c.Open(); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(' d}a')", c); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT name FROM Test"; object name = cmd.ExecuteScalar(); Assert.AreEqual(" d}a", name); c.Close(); } */ /// <summary> /// Bug #14592 Wrong column length returned for VARCHAR UTF8 columns /// </summary> [Test] public void GetSchemaOnUTF8() { if (Version.Major >= 6) return; execSQL("CREATE TABLE Test(name VARCHAR(40) NOT NULL, name2 VARCHAR(20)) " + "CHARACTER SET utf8"); execSQL("INSERT INTO Test VALUES('Test', 'Test')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { DataTable dt = reader.GetSchemaTable(); Assert.AreEqual(40, dt.Rows[0]["ColumnSize"]); Assert.AreEqual(20, dt.Rows[1]["ColumnSize"]); } } [Test] public void UTF8BlogsTruncating() { execSQL("CREATE TABLE test (name LONGTEXT) CHARSET utf8"); string szParam = "test:"; string szSQL = "INSERT INTO test Values (?monParametre)"; string connStr = GetConnectionString(true) + ";charset=utf8"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand(szSQL, c); cmd.Parameters.Add(new MySqlParameter("?monParametre", MySqlDbType.VarChar)); cmd.Parameters[0].Value = szParam; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string s = reader.GetString(0); Assert.AreEqual(szParam, s); } } } [Test] public void BlobAsUtf8() { execSQL(@"CREATE TABLE Test(include_blob BLOB, include_tinyblob TINYBLOB, include_longblob LONGBLOB, exclude_tinyblob TINYBLOB, exclude_blob BLOB, exclude_longblob LONGBLOB)"); byte[] utf8_bytes = new byte[4] { 0xf0, 0x90, 0x80, 0x80 }; Encoding utf8 = Encoding.GetEncoding("UTF-8"); string utf8_string = utf8.GetString(utf8_bytes, 0, utf8_bytes.Length); // insert our UTF-8 bytes into the table MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?p1, ?p2, ?p3, ?p4, ?p5, ?p5)", conn); cmd.Parameters.AddWithValue("?p1", utf8_bytes); cmd.Parameters.AddWithValue("?p2", utf8_bytes); cmd.Parameters.AddWithValue("?p3", utf8_bytes); cmd.Parameters.AddWithValue("?p4", utf8_bytes); cmd.Parameters.AddWithValue("?p5", utf8_bytes); cmd.Parameters.AddWithValue("?p6", utf8_bytes); cmd.ExecuteNonQuery(); // now check that the on/off is working string connStr = GetConnectionString(true) + ";Treat Blobs As UTF8=yes;BlobAsUTF8IncludePattern=.*"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", c); DataTable dt = new DataTable(); da.Fill(dt); foreach (DataColumn col in dt.Columns) { Assert.AreEqual(typeof(string), col.DataType); string s = (string)dt.Rows[0][0]; byte[] b = utf8.GetBytes(s); Assert.AreEqual(utf8_string, dt.Rows[0][col.Ordinal].ToString()); } } // now check that exclusion works connStr = GetConnectionString(true) + ";Treat Blobs As UTF8=yes;BlobAsUTF8ExcludePattern=exclude.*"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", c); DataTable dt = new DataTable(); da.Fill(dt); foreach (DataColumn col in dt.Columns) { if (col.ColumnName.StartsWith("exclude")) Assert.AreEqual(typeof(byte[]), col.DataType); else { Assert.AreEqual(typeof(string), col.DataType); Assert.AreEqual(utf8_string, dt.Rows[0][col.Ordinal].ToString()); } } } // now check that inclusion works connStr = GetConnectionString(true) + ";Treat Blobs As UTF8=yes;BlobAsUTF8IncludePattern=include.*"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", c); DataTable dt = new DataTable(); da.Fill(dt); foreach (DataColumn col in dt.Columns) { if (col.ColumnName.StartsWith("include")) { Assert.AreEqual(typeof(string), col.DataType); Assert.AreEqual(utf8_string, dt.Rows[0][col.Ordinal].ToString()); } else Assert.AreEqual(typeof(byte[]), col.DataType); } } } /// <summary> /// Bug #31185 columns names are incorrect when using the 'AS' clause and name with accents /// Bug #38721 GetOrdinal doesn't accept column names accepted by MySQL 5.0 /// </summary> [Test] public void UTF8AsColumnNames() { string connStr = GetConnectionString(true) + ";charset=utf8;pooling=false"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlDataAdapter da = new MySqlDataAdapter("select now() as 'Numro'", c); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual("Numro", dt.Columns[0].ColumnName); MySqlCommand cmd = new MySqlCommand("SELECT NOW() AS 'Numro'", c); using (MySqlDataReader reader = cmd.ExecuteReader()) { int ord = reader.GetOrdinal("Numro"); Assert.AreEqual(0, ord); } } } /// <summary> /// Bug #31117 Connector/Net exceptions do not support server charset /// </summary> [Test] public void NonLatin1Exception() { string connStr = GetConnectionString(true) + ";charset=utf8"; execSQL("CREATE TABLE Test (id int)"); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); try { MySqlCommand cmd = new MySqlCommand("select `Numro` from Test", c); cmd.ExecuteScalar(); } catch (Exception ex) { Assert.AreEqual("Unknown column 'Numro' in 'field list'", ex.Message); } } } /// <summary> /// Bug #40076 "Functions Return String" option does not set the proper encoding for the string /// </summary> [Test] public void FunctionReturnsStringWithCharSet() { string connStr = GetConnectionString(true) + ";functions return string=true"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand( "SELECT CONCAT('Trdgrdsvgen', 1)", c); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual("Trdgrdsvgen1", reader.GetString(0)); } } } [Test] public void RespectBinaryFlags() { if (Version.Major >= 5 && Version.Minor >= 5) return; string connStr = GetConnectionString(true) + ";respect binary flags=true"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlDataAdapter da = new MySqlDataAdapter( "SELECT CONCAT('Trdgrdsvgen', 1)", c); DataTable dt = new DataTable(); da.Fill(dt); Assert.IsTrue(dt.Rows[0][0] is byte[]); } connStr = GetConnectionString(true) + ";respect binary flags=false"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlDataAdapter da = new MySqlDataAdapter( "SELECT CONCAT('Trdgrdsvgen', 1)", c); DataTable dt = new DataTable(); da.Fill(dt); Assert.IsTrue(dt.Rows[0][0] is string); Assert.AreEqual("Trdgrdsvgen1", dt.Rows[0][0]); } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/PerfMonTests.cs0000644000175000017500000000572511127003600025224 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #if !MONO using System; using System.Data; using MySql.Data.MySqlClient; using NUnit.Framework; using System.Diagnostics; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for StoredProcedure. /// [TestFixture] public class PerfMonTests : BaseTest { public PerfMonTests() { csAdditions = ";use performance monitor=true;"; } public override void Setup() { base.Setup(); execSQL("CREATE TABLE Test (id INT, name VARCHAR(100))"); } /// /// This test doesn't work from the CI setup currently /// [Test] public void ProcedureFromCache() { return; if (Version < new Version(5, 0)) return; execSQL("DROP PROCEDURE IF EXISTS spTest"); execSQL("CREATE PROCEDURE spTest(id int) BEGIN END"); PerformanceCounter hardQuery = new PerformanceCounter( ".NET Data Provider for MySQL", "HardProcedureQueries", true); PerformanceCounter softQuery = new PerformanceCounter( ".NET Data Provider for MySQL", "SoftProcedureQueries", true); long hardCount = hardQuery.RawValue; long softCount = softQuery.RawValue; MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("?id", 1); cmd.ExecuteScalar(); Assert.AreEqual(hardCount + 1, hardQuery.RawValue); Assert.AreEqual(softCount, softQuery.RawValue); hardCount = hardQuery.RawValue; MySqlCommand cmd2 = new MySqlCommand("spTest", conn); cmd2.CommandType = CommandType.StoredProcedure; cmd2.Parameters.AddWithValue("?id", 1); cmd2.ExecuteScalar(); Assert.AreEqual(hardCount, hardQuery.RawValue); Assert.AreEqual(softCount + 1, softQuery.RawValue); } } } #endif mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/DateTimeTests.cs0000644000175000017500000004103311127003600025342 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Data.Common; using System.Threading; using MySql.Data.MySqlClient; using MySql.Data.Types; using System.Globalization; using NUnit.Framework; using System.Text; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class DateTimeTests : BaseTest { [SetUp] public override void Setup() { base.Setup(); execSQL("CREATE TABLE Test (id INT NOT NULL, dt DATETIME, d DATE, " + "t TIME, ts TIMESTAMP, PRIMARY KEY(id))"); } [Test] public void ConvertZeroDateTime() { execSQL("INSERT INTO Test VALUES(1, '0000-00-00', '0000-00-00', " + "'00:00:00', NULL)"); string connStr = this.GetConnectionString(true); connStr += ";convert zero datetime=yes"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", c); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(DateTime.MinValue.Date, reader.GetDateTime(1).Date); Assert.AreEqual(DateTime.MinValue.Date, reader.GetDateTime(2).Date); } } } [Test] public void TestNotAllowZerDateAndTime() { execSQL("SET SQL_MODE=''"); execSQL("INSERT INTO Test VALUES(1, 'Test', '0000-00-00', '0000-00-00', '00:00:00')"); execSQL("INSERT INTO Test VALUES(2, 'Test', '2004-11-11', '2004-11-11', '06:06:06')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); MySqlDateTime testDate = reader.GetMySqlDateTime(2); Assert.IsFalse(testDate.IsValidDateTime, "IsZero is false"); try { reader.GetValue(2); Assert.Fail("This should not work"); } catch (MySqlConversionException) { } Assert.IsTrue(reader.Read()); DateTime dt2 = (DateTime)reader.GetValue(2); Assert.AreEqual(new DateTime(2004, 11, 11).Date, dt2.Date); } } [Test] public void DateAdd() { MySqlCommand cmd = new MySqlCommand("select date_add(?someday, interval 1 hour)", conn); DateTime now = DateTime.Now; DateTime later = now.AddHours(1); later = later.AddMilliseconds(later.Millisecond * -1); cmd.Parameters.AddWithValue("?someday", now); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); DateTime dt = reader.GetDateTime(0); Assert.AreEqual(later.Date, dt.Date); Assert.AreEqual(later.Hour, dt.Hour); Assert.AreEqual(later.Minute, dt.Minute); Assert.AreEqual(later.Second, dt.Second); } } /// /// Bug #9619 Cannot update row using DbDataAdapter when row contains an invalid date /// Bug #15112 MySqlDateTime Constructor /// [Test] public void TestAllowZeroDateTime() { execSQL("TRUNCATE TABLE Test"); execSQL("INSERT INTO Test (id, d, dt) VALUES (1, '0000-00-00', '0000-00-00 00:00:00')"); using (MySqlConnection c = new MySqlConnection( conn.ConnectionString + ";pooling=false;AllowZeroDatetime=true")) { c.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", c); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.IsTrue(reader.GetValue(1) is MySqlDateTime); Assert.IsTrue(reader.GetValue(2) is MySqlDateTime); Assert.IsFalse(reader.GetMySqlDateTime(1).IsValidDateTime); Assert.IsFalse(reader.GetMySqlDateTime(2).IsValidDateTime); try { reader.GetDateTime(1); Assert.Fail("This should not succeed"); } catch (MySqlConversionException) { } } DataTable dt = new DataTable(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", c); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); da.Fill(dt); dt.Rows[0]["id"] = 2; DataRow row = dt.NewRow(); row["id"] = 3; row["d"] = new MySqlDateTime("2003-9-24"); row["dt"] = new MySqlDateTime("0000/0/00 00:00:00"); dt.Rows.Add(row); da.Update(dt); dt.Clear(); da.Fill(dt); Assert.AreEqual(2, dt.Rows.Count); MySqlDateTime date = (MySqlDateTime)dt.Rows[1]["d"]; Assert.AreEqual(2003, date.Year); Assert.AreEqual(9, date.Month); Assert.AreEqual(24, date.Day); cb.Dispose(); } } [Test] public void InsertDateTimeValue() { using (MySqlConnection c = new MySqlConnection(conn.ConnectionString + ";allow zero datetime=yes")) { c.Open(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT id, dt FROM Test", c); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataTable dt = new DataTable(); dt.Columns.Add(new DataColumn("id", typeof(int))); dt.Columns.Add(new DataColumn("dt", typeof(DateTime))); da.Fill(dt); DateTime now = DateTime.Now; DataRow row = dt.NewRow(); row["id"] = 1; row["dt"] = now; dt.Rows.Add(row); da.Update(dt); dt.Clear(); da.Fill(dt); cb.Dispose(); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(now.Date, ((DateTime)dt.Rows[0]["dt"]).Date); } } #if !CF [Test] public void SortingMySqlDateTimes() { execSQL("INSERT INTO Test (id, dt) VALUES (1, '2004-10-01')"); execSQL("INSERT INTO Test (id, dt) VALUES (2, '2004-10-02')"); execSQL("INSERT INTO Test (id, dt) VALUES (3, '2004-11-01')"); execSQL("INSERT INTO Test (id, dt) VALUES (4, '2004-11-02')"); CultureInfo curCulture = Thread.CurrentThread.CurrentCulture; CultureInfo curUICulture = Thread.CurrentThread.CurrentUICulture; CultureInfo cul = new CultureInfo("en-GB"); Thread.CurrentThread.CurrentCulture = cul; Thread.CurrentThread.CurrentUICulture = cul; using( MySqlConnection c = new MySqlConnection( conn.ConnectionString + ";allow zero datetime=yes" )) { MySqlDataAdapter da = new MySqlDataAdapter("SELECT dt FROM Test", c); DataTable dt = new DataTable(); da.Fill(dt); DataView dv = dt.DefaultView; dv.Sort = "dt ASC"; Assert.AreEqual(new DateTime(2004, 10, 1).Date, Convert.ToDateTime(dv[0]["dt"]).Date); Assert.AreEqual(new DateTime(2004, 10, 2).Date, Convert.ToDateTime(dv[1]["dt"]).Date); Assert.AreEqual(new DateTime(2004, 11, 1).Date, Convert.ToDateTime(dv[2]["dt"]).Date); Assert.AreEqual(new DateTime(2004, 11, 2).Date, Convert.ToDateTime(dv[3]["dt"]).Date); Thread.CurrentThread.CurrentCulture = curCulture; Thread.CurrentThread.CurrentUICulture = curUICulture; } } #endif [Test] public void TestZeroDateTimeException() { execSQL("INSERT INTO Test (id, d, dt) VALUES (1, '0000-00-00', '0000-00-00 00:00:00')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { try { reader.Read(); reader.GetDateTime(2); Assert.Fail("Should throw an exception"); } catch (MySqlConversionException) { } } } /// /// Bug #8929 Timestamp values with a date > 10/29/9997 cause problems /// [Test] public void LargeDateTime() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, dt) VALUES(?id,?dt)", conn); cmd.Parameters.Add(new MySqlParameter("?id", 1)); cmd.Parameters.Add(new MySqlParameter("?dt", DateTime.Parse("9997-10-29"))); cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = 2; cmd.Parameters[1].Value = DateTime.Parse("9997-10-30"); cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = 3; cmd.Parameters[1].Value = DateTime.Parse("9999-12-31"); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT id,dt FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(DateTime.Parse("9997-10-29").Date, reader.GetDateTime(1).Date); Assert.IsTrue(reader.Read()); Assert.AreEqual(DateTime.Parse("9997-10-30").Date, reader.GetDateTime(1).Date); Assert.IsTrue(reader.Read()); Assert.AreEqual(DateTime.Parse("9999-12-31").Date, reader.GetDateTime(1).Date); } } [Test] public void UsingDatesAsStrings() { MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id, dt) VALUES (1, ?dt)", conn); cmd.Parameters.Add("?dt", MySqlDbType.Date); cmd.Parameters[0].Value = "2005-03-04"; cmd.ExecuteNonQuery(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); DateTime date = (DateTime)dt.Rows[0]["dt"]; Assert.AreEqual(2005, date.Year); Assert.AreEqual(3, date.Month); Assert.AreEqual(4, date.Day); } /// /// Bug #19481 Where clause with datetime throws exception [any warning causes the exception] /// [Test] public void Bug19481() { execSQL("DROP TABLE Test"); execSQL("CREATE TABLE Test(ID INT NOT NULL AUTO_INCREMENT, " + "SATELLITEID VARCHAR(3) NOT NULL, ANTENNAID INT, AOS_TIMESTAMP DATETIME NOT NULL, " + "TEL_TIMESTAMP DATETIME, LOS_TIMESTAMP DATETIME, PRIMARY KEY (ID))"); execSQL("INSERT INTO Test VALUES (NULL,'224','0','2005-07-24 00:00:00'," + "'2005-07-24 00:02:00','2005-07-24 00:22:00')"); execSQL("INSERT INTO Test VALUES (NULL,'155','24','2005-07-24 03:00:00'," + "'2005-07-24 03:02:30','2005-07-24 03:20:00')"); execSQL("INSERT INTO Test VALUES (NULL,'094','34','2005-07-24 09:00:00'," + "'2005-07-24 09:00:30','2005-07-24 09:15:00')"); execSQL("INSERT INTO Test VALUES (NULL,'224','54','2005-07-24 12:00:00'," + "'2005-07-24 12:01:00','2005-07-24 12:33:00')"); execSQL("INSERT INTO Test VALUES (NULL,'155','25','2005-07-24 15:00:00'," + "'2005-07-24 15:02:00','2005-07-24 15:22:00')"); execSQL("INSERT INTO Test VALUES (NULL,'094','0','2005-07-24 17:00:00'," + "'2005-07-24 17:02:12','2005-07-24 17:20:00')"); execSQL("INSERT INTO Test VALUES (NULL,'224','24','2005-07-24 19:00:00'," + "'2005-07-24 19:02:00','2005-07-24 19:27:00')"); execSQL("INSERT INTO Test VALUES (NULL,'155','34','2005-07-24 21:00:00'," + "'2005-07-24 21:02:33','2005-07-24 21:22:55')"); execSQL("INSERT INTO Test VALUES (NULL,'094','55','2005-07-24 23:00:00'," + "'2005-07-24 23:00:45','2005-07-24 23:22:23')"); DateTime date = DateTime.Parse("7/24/2005"); StringBuilder sql = new StringBuilder(); sql.AppendFormat(CultureInfo.InvariantCulture, @"SELECT ID, ANTENNAID, TEL_TIMESTAMP, LOS_TIMESTAMP FROM Test WHERE TEL_TIMESTAMP >= '{0}'", date.ToString("u")); MySqlDataAdapter da = new MySqlDataAdapter(sql.ToString(), conn); DataSet dataSet = new DataSet(); da.Fill(dataSet); } /// /// Bug #17736 Selecting a row with with empty date '0000-00-00' results in Read() hanging. /// [Test] public void PreparedZeroDateTime() { if (Version < new Version(4, 1)) return; execSQL("INSERT INTO Test VALUES(1, Now(), '0000-00-00', NULL, NULL)"); MySqlCommand cmd = new MySqlCommand("SELECT d FROM Test WHERE id=?id", conn); cmd.Parameters.AddWithValue("?id", 1); cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); } } [Test] public void DateTimeInDataTable() { execSQL("INSERT INTO Test VALUES(1, Now(), '0000-00-00', NULL, NULL)"); using (MySqlConnection c = new MySqlConnection( conn.ConnectionString + ";pooling=false;AllowZeroDatetime=true")) { c.Open(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", c); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataTable dt = new DataTable(); da.Fill(dt); DataRow row = dt.NewRow(); row["id"] = 2; row["dt"] = new MySqlDateTime(DateTime.Now); row["d"] = new MySqlDateTime(DateTime.Now); row["t"] = new TimeSpan(1, 1, 1); row["ts"] = DBNull.Value; dt.Rows.Add(row); da.Update(dt); dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual(2, dt.Rows.Count); cb.Dispose(); } } /// /// Bug #32010 Connector return incorrect value when pulling 0 datetime /// [Test] public void MySqlDateTimeFormatting() { DateTime dt = DateTime.Now; MySqlDateTime mdt = new MySqlDateTime(dt); Assert.AreEqual(dt.ToString(), mdt.ToString()); } /// /// Bug #41021 DateTime format incorrect /// [Test] public void DateFormat() { DateTime dt = DateTime.Now; MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(1, ?dt, NULL, NULL, NULL)", conn); cmd.Parameters.AddWithValue("?dt", dt); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT dt FROM Test WHERE DATE_FORMAT(DATE(dt), GET_FORMAT(DATETIME, 'ISO'))=?datefilter"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("?datefilter", dt.Date); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); } } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/PartialTrustSandbox.cs0000644000175000017500000000234011127003600026576 0ustar directhexdirecthexusing System; using System.Collections.Generic; using System.Text; using System.Security; using System.Security.Permissions; using System.Net; namespace MySql.Data.MySqlClient.Tests { public class PartialTrustSandbox : MarshalByRefObject { public static AppDomain CreatePartialTrustDomain() { AppDomainSetup setup = new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory, PrivateBinPath = AppDomain.CurrentDomain.RelativeSearchPath }; PermissionSet permissions = new PermissionSet(null); permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); permissions.AddPermission(new DnsPermission(PermissionState.Unrestricted)); permissions.AddPermission(new SocketPermission(PermissionState.Unrestricted)); return AppDomain.CreateDomain("Partial Trust Sandbox", AppDomain.CurrentDomain.Evidence, setup, permissions); } public MySqlConnection TryOpenConnection(string connectionString) { MySqlConnection connection = new MySqlConnection(connectionString); connection.Open(); return connection; } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/DataAdapterTests.cs0000644000175000017500000011106711127003600026025 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using MySql.Data.MySqlClient; using MySql.Data.Types; using System.Data; using NUnit.Framework; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for ConnectionTests. /// [TestFixture] public class DataAdapterTests : BaseTest { private void CreateDefaultTable() { execSQL("CREATE TABLE Test (id INT NOT NULL AUTO_INCREMENT, " + "id2 INT NOT NULL, name VARCHAR(100), dt DATETIME, tm TIME, " + "ts TIMESTAMP, OriginalId INT, PRIMARY KEY(id, id2))"); } [Test] public void TestFill() { FillImpl(false); } [Test] public void TestFillPrepared() { FillImpl(true); } private void FillImpl(bool prepare) { CreateDefaultTable(); execSQL("INSERT INTO Test (id, id2, name, dt) VALUES (NULL, 1, 'Name 1', Now())"); execSQL("INSERT INTO Test (id, id2, name, dt) VALUES (NULL, 2, NULL, Now())"); execSQL("INSERT INTO Test (id, id2, name, dt) VALUES (NULL, 3, '', Now())"); MySqlDataAdapter da = new MySqlDataAdapter("select * from Test", conn); if (prepare) da.SelectCommand.Prepare(); DataSet ds = new DataSet(); da.Fill(ds, "Test"); Assert.AreEqual(1, ds.Tables.Count); Assert.AreEqual(3, ds.Tables[0].Rows.Count); Assert.AreEqual(1, ds.Tables[0].Rows[0]["id2"]); Assert.AreEqual(2, ds.Tables[0].Rows[1]["id2"]); Assert.AreEqual(3, ds.Tables[0].Rows[2]["id2"]); Assert.AreEqual("Name 1", ds.Tables[0].Rows[0]["name"]); Assert.AreEqual(DBNull.Value, ds.Tables[0].Rows[1]["name"]); Assert.AreEqual(String.Empty, ds.Tables[0].Rows[2]["name"]); } [Test] public void TestUpdate() { CreateDefaultTable(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataTable dt = new DataTable(); da.Fill(dt); DataRow dr = dt.NewRow(); dr["id2"] = 2; dr["name"] = "TestName1"; dt.Rows.Add(dr); int count = da.Update(dt); // make sure our refresh of auto increment values worked Assert.AreEqual(1, count, "checking insert count"); Assert.IsNotNull(dt.Rows[ dt.Rows.Count-1 ]["id"], "Checking auto increment column"); dt.Rows.Clear(); da.Fill(dt); dt.Rows[0]["id2"] = 3; dt.Rows[0]["name"] = "TestName2"; dt.Rows[0]["ts"] = DBNull.Value; DateTime day1 = new DateTime(2003, 1, 16, 12, 24, 0); dt.Rows[0]["dt"] = day1; dt.Rows[0]["tm"] = day1.TimeOfDay; count = da.Update(dt); Assert.IsNotNull(dt.Rows[0]["ts"], "checking refresh of record"); Assert.AreEqual(3, dt.Rows[0]["id2"], "checking refresh of primary column"); dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual(1, count, "checking update count"); DateTime dateTime = (DateTime)dt.Rows[0]["dt"]; Assert.AreEqual(day1.Date, dateTime.Date, "checking date"); Assert.AreEqual(day1.TimeOfDay, dt.Rows[0]["tm"], "checking time"); dt.Rows[0].Delete(); count = da.Update(dt); Assert.AreEqual(1, count, "checking insert count"); dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual(0, dt.Rows.Count, "checking row count"); cb.Dispose(); } [Test] public void OriginalInName() { CreateDefaultTable(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); cb.ToString(); // keep the compiler happy DataTable dt = new DataTable(); da.Fill(dt); DataRow row = dt.NewRow(); row["id"] = DBNull.Value; row["id2"] = 1; row["name"] = "Test"; row["dt"] = DBNull.Value; row["tm"] = DBNull.Value; row["ts"] = DBNull.Value; row["OriginalId"] = 2; dt.Rows.Add( row ); da.Update(dt); Assert.AreEqual( 1, dt.Rows.Count ); Assert.AreEqual( 2, dt.Rows[0]["OriginalId"] ); } [Test] public void UseAdapterPropertyOfCommandBuilder() { CreateDefaultTable(); execSQL("INSERT INTO Test (id, id2, name) VALUES (NULL, 1, 'Test')"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(); cb.DataAdapter = da; DataTable dt = new DataTable(); da.Fill(dt); dt.Rows[0]["name"] = "Test Update"; int updateCnt = da.Update(dt); Assert.AreEqual( 1, updateCnt ); dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual( 1, dt.Rows.Count ); Assert.AreEqual( "Test Update", dt.Rows[0]["name"] ); } [Test] public void UpdateNullTextFieldToEmptyString() { CreateDefaultTable(); execSQL("INSERT INTO Test (id, id2, name) VALUES (1, 1, NULL)"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); cb.ToString(); // keep the compiler happy DataTable dt = new DataTable(); da.Fill(dt); dt.Rows[0]["name"] = ""; int updateCnt = da.Update(dt); Assert.AreEqual( 1, updateCnt ); dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual( 1, dt.Rows.Count ); Assert.AreEqual( "", dt.Rows[0]["name"] ); } [Test] public void UpdateExtendedTextFields() { execSQL("CREATE TABLE Test (id int, notes MEDIUMTEXT, PRIMARY KEY(id))"); execSQL("INSERT INTO Test VALUES(1, 'This is my note')"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); cb.ToString(); // keep the compiler happy DataTable dt = new DataTable(); da.Fill(dt); dt.Rows[0]["notes"] = "This is my new note"; da.Update( dt ); dt.Clear(); da.Fill(dt); Assert.AreEqual( "This is my new note", dt.Rows[0]["notes"]); } [Test] public void SelectMoreThan252Rows() { CreateDefaultTable(); for (int i = 0; i < 500; i++) execSQL("INSERT INTO Test(id, id2) VALUES(NULL, " + i + ")"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual( 500, dt.Rows.Count ); } /* [Test] [Explicit] public void UpdateManyRows() { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataTable dt = new DataTable(); da.Fill(dt); for (int i=0; i < 100000; i++) { DataRow dr = dt.NewRow(); dr["id"] = DBNull.Value; dr["id2"] = i; dt.Rows.Add( dr ); DataTable changes = dt.GetChanges(); da.Update( changes ); dt.AcceptChanges(); } dt.Clear(); da.Fill(dt); Assert.AreEqual(100000, dt.Rows.Count); } */ [Test] public void DiscreteValues() { execSQL("CREATE TABLE Test (id int, name varchar(200), dt DATETIME, b1 TEXT)"); execSQL("INSERT INTO Test VALUES (1, 'Test', '2004-08-01', 'Text 1')"); execSQL("INSERT INTO Test VALUES (2, 'Test 1', '2004-07-02', 'Text 2')"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual("Test", dt.Rows[0]["name"]); Assert.AreEqual("Test 1", dt.Rows[1]["name"]); Assert.AreEqual("Text 1", dt.Rows[0]["b1"]); Assert.AreEqual("Text 2", dt.Rows[1]["b1"]); Assert.AreEqual(new DateTime(2004, 8, 1, 0, 0, 0).ToString(), dt.Rows[0]["dt"].ToString()); Assert.AreEqual(new DateTime(2004, 7, 2, 0, 0, 0).ToString(), dt.Rows[1]["dt"].ToString()); } [Test] public void Bug5798() { CreateDefaultTable(); execSQL("INSERT INTO Test (id, id2, name) VALUES (1, 1, '')"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); cb.ToString(); // keep the compiler happy DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(String.Empty, dt.Rows[0]["name"]); dt.Rows[0]["name"] = "Test"; da.Update(dt); dt.Clear(); da.Fill(dt); Assert.AreEqual("Test", dt.Rows[0]["name"]); } [Test] public void ColumnMapping() { execSQL("CREATE TABLE Test (id int, dcname varchar(100), primary key(id))"); execSQL("INSERT INTO Test VALUES (1, 'Test1')"); execSQL("INSERT INTO Test VALUES (2, 'Test2')"); execSQL("INSERT INTO Test VALUES (3, 'Test3')"); execSQL("INSERT INTO Test VALUES (4, 'Test4')"); // MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); // MySqlCommandBuilder cb = new MySqlCommandBuilder(da); // DataTable dt = new DataTable(); } [Test] public void TestFillWithHelper() { execSQL("CREATE TABLE table1 (`key` INT, PRIMARY KEY(`key`))"); execSQL("CREATE TABLE table2 (`key` INT, PRIMARY KEY(`key`))"); execSQL("INSERT INTO table1 VALUES (1)"); execSQL("INSERT INTO table2 VALUES (1)"); string sql = "SELECT table1.key FROM table1 WHERE table1.key=1; " + "SELECT table2.key FROM table2 WHERE table2.key=1"; DataSet ds = MySqlHelper.ExecuteDataset( conn, sql, null ); Assert.AreEqual( 2, ds.Tables.Count ); Assert.AreEqual( 1, ds.Tables[0].Rows.Count ); Assert.AreEqual( 1, ds.Tables[1].Rows.Count ); Assert.AreEqual( 1, ds.Tables[0].Rows[0]["key"] ); Assert.AreEqual( 1, ds.Tables[1].Rows[0]["key"] ); } /// /// Bug #8509 - MySqlDataAdapter.FillSchema does not interpret unsigned integer /// [Test] public void AutoIncrementColumns() { execSQL("CREATE TABLE Test (id int(10) unsigned NOT NULL auto_increment primary key)"); execSQL("INSERT INTO Test VALUES(NULL)"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataSet ds = new DataSet(); da.Fill(ds); Assert.AreEqual(1, ds.Tables[0].Rows[0]["id"]); DataRow row = ds.Tables[0].NewRow(); ds.Tables[0].Rows.Add(row); da.Update(ds); ds.Clear(); da.Fill(ds); Assert.AreEqual(1, ds.Tables[0].Rows[0]["id"]); Assert.AreEqual(2, ds.Tables[0].Rows[1]["id"]); cb.Dispose(); } /// /// Bug #8292 GROUP BY / WITH ROLLUP with DataSet causes System.Data.ConstraintException /// [Test] public void Rollup() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test ( id INT NOT NULL, amount INT )"); execSQL("INSERT INTO Test VALUES (1, 44)"); execSQL("INSERT INTO Test VALUES (2, 88)"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test GROUP BY id WITH ROLLUP", conn); DataSet ds = new DataSet(); da.Fill(ds); Assert.AreEqual(1, ds.Tables.Count); Assert.AreEqual(3, ds.Tables[0].Rows.Count); Assert.AreEqual(88, ds.Tables[0].Rows[2]["amount"]); Assert.AreEqual(DBNull.Value, ds.Tables[0].Rows[2]["id"]); } /// /// Bug #8514 CURRENT_TIMESTAMP default not respected /// /* [Test] public void DefaultValues() { execSQL("CREATE TABLE Test (id int, name VARCHAR(20) NOT NULL DEFAULT 'abc', dt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommand insCmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?name, ?dt)", conn); insCmd.Parameters.Add("?id", MySqlDbType.Int32, 0, "id"); insCmd.Parameters.Add("?name", MySqlDbType.VarChar, 20, "name"); insCmd.Parameters.Add("?dt", MySqlDbType.Datetime, 0, "dt"); da.InsertCommand = insCmd; DataTable dt = new DataTable(); //da.FillSchema(ds, SchemaType.Source);//, "Test"); da.MissingSchemaAction = MissingSchemaAction.AddWithKey; try { da.Fill(dt); } catch (Exception ex) { Console.WriteLine(ex.Message); } DataRow row = dt.NewRow(); row["id"] = 1; row["name"] = "xyz"; dt.Rows.Add(row); DataRow row2 = dt.NewRow(); row2["id"] = 2; row2["name"] = DBNull.Value; dt.Rows.Add(row2); da.Update(dt); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(1, reader["id"]); Assert.AreEqual("xyz", reader["name"]); Assert.AreEqual(DateTime.Now.Year, reader.GetDateTime(2).Year); Assert.IsTrue(reader.Read()); Assert.AreEqual(2, reader["id"]); Assert.AreEqual("abc", reader["name"]); Assert.AreEqual(DateTime.Now.Year, reader.GetDateTime(2).Year); Assert.IsFalse(reader.Read()); } } */ /// /// Bug #16307 @@Identity returning incorrect value /// [Test] public void Bug16307() { execSQL("CREATE TABLE Test (OrgNum int auto_increment, CallReportNum int, Stamp varchar(50), " + "WasRealCall varchar(50), WasHangup varchar(50), primary key(orgnum))"); string strSQL = "INSERT INTO Test(OrgNum, CallReportNum, Stamp, WasRealCall, WasHangup) " + "VALUES (?OrgNum, ?CallReportNum, ?Stamp, ?WasRealCall, ?WasHangup)"; MySqlCommand cmd = new MySqlCommand(strSQL, conn); MySqlParameterCollection pc = cmd.Parameters; pc.Add("?OrgNum", MySqlDbType.Int32, 0, "OrgNum"); pc.Add("?CallReportNum", MySqlDbType.Int32, 0, "CallReportNum"); pc.Add("?Stamp", MySqlDbType.VarChar, 0, "Stamp"); pc.Add("?WasRealCall", MySqlDbType.VarChar, 0, "WasRealCall"); pc.Add("?WasHangup", MySqlDbType.VarChar, 0, "WasHangup"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); da.InsertCommand = cmd; DataSet ds = new DataSet(); da.Fill(ds); DataRow row = ds.Tables[0].NewRow(); row["CallReportNum"] = 1; row["Stamp"] = "stamp"; row["WasRealCall"] = "yes"; row["WasHangup"] = "no"; ds.Tables[0].Rows.Add(row); da.Update(ds.Tables[0]); strSQL = "SELECT @@IDENTITY AS 'Identity';"; MySqlCommand cmd2 = new MySqlCommand(strSQL, conn); using (MySqlDataReader reader = cmd2.ExecuteReader()) { reader.Read(); int intCallNum = Int32.Parse(reader.GetValue(0).ToString()); Assert.AreEqual(1, intCallNum); } } /// /// Bug #8131 Data Adapter doesn't close connection /// [Test] public void QuietOpenAndClose() { execSQL("CREATE TABLE Test (id INT, PRIMARY KEY(id))"); execSQL("INSERT INTO Test VALUES(1)"); using (MySqlConnection c = new MySqlConnection(GetConnectionString(true))) { MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", c); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); Assert.IsTrue(c.State == ConnectionState.Closed); DataTable dt = new DataTable(); da.Fill(dt); Assert.IsTrue(c.State == ConnectionState.Closed); Assert.AreEqual(1, dt.Rows.Count); dt.Rows[0][0] = 2; DataRow[] rows = new DataRow[1]; rows[0] = dt.Rows[0]; da.Update(dt); Assert.IsTrue(c.State == ConnectionState.Closed); dt.Clear(); c.Open(); Assert.IsTrue(c.State == ConnectionState.Open); da.Fill(dt); Assert.IsTrue(c.State == ConnectionState.Open); Assert.AreEqual(1, dt.Rows.Count); cb.Dispose(); } } [Test] public void RangeFill() { execSQL("CREATE TABLE Test (id INT)"); execSQL("INSERT INTO Test VALUES (1)"); execSQL("INSERT INTO Test VALUES (2)"); execSQL("INSERT INTO Test VALUES (3)"); execSQL("INSERT INTO Test VALUES (4)"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataSet ds = new DataSet(); da.Fill(ds, 1, 2, "Test"); } [Test] public void FillWithNulls() { execSQL(@"CREATE TABLE Test (id INT UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(100), PRIMARY KEY(id))"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); DataTable dt = new DataTable(); da.Fill(dt); dt.Columns[0].AutoIncrement = true; dt.Columns[0].AutoIncrementSeed = -1; dt.Columns[0].AutoIncrementStep = -1; DataRow row = dt.NewRow(); row["name"] = "Test1"; dt.Rows.Add(row); da.Update(dt); dt.Clear(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(1, dt.Rows[0]["id"]); Assert.AreEqual("Test1", dt.Rows[0]["name"]); row = dt.NewRow(); row["name"] = System.DBNull.Value; dt.Rows.Add(row); da.Update(dt); dt.Clear(); da.Fill(dt); Assert.AreEqual(2, dt.Rows.Count); Assert.AreEqual(2, dt.Rows[1]["id"]); Assert.AreEqual(DBNull.Value, dt.Rows[1]["name"]); row = dt.NewRow(); row["name"] = "Test3"; dt.Rows.Add(row); da.Update(dt); dt.Clear(); da.Fill(dt); Assert.AreEqual(3, dt.Rows.Count); Assert.AreEqual(3, dt.Rows[2]["id"]); Assert.AreEqual("Test3", dt.Rows[2]["name"]); cb.Dispose(); } [Test] public void PagingFill() { CreateDefaultTable(); execSQL("INSERT INTO Test (id, id2, name) VALUES (NULL, 1, 'Name 1')"); execSQL("INSERT INTO Test (id, id2, name) VALUES (NULL, 2, 'Name 2')"); execSQL("INSERT INTO Test (id, id2, name) VALUES (NULL, 3, 'Name 3')"); execSQL("INSERT INTO Test (id, id2, name) VALUES (NULL, 4, 'Name 4')"); execSQL("INSERT INTO Test (id, id2, name) VALUES (NULL, 5, 'Name 5')"); execSQL("INSERT INTO Test (id, id2, name) VALUES (NULL, 6, 'Name 6')"); execSQL("INSERT INTO Test (id, id2, name) VALUES (NULL, 7, 'Name 7')"); execSQL("INSERT INTO Test (id, id2, name) VALUES (NULL, 8, 'Name 8')"); execSQL("INSERT INTO Test (id, id2, name) VALUES (NULL, 9, 'Name 9')"); execSQL("INSERT INTO Test (id, id2, name) VALUES (NULL, 10, 'Name 10')"); execSQL("INSERT INTO Test (id, id2, name) VALUES (NULL, 11, 'Name 11')"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(0, 10, new DataTable[] { dt }); Assert.AreEqual(10, dt.Rows.Count); } private string MakeLargeString(int len) { System.Text.StringBuilder sb = new System.Text.StringBuilder(len); while (len-- > 0) sb.Append('a'); return sb.ToString(); } [Test] public void SkippingRowsLargerThan1024() { execSQL("CREATE TABLE Test (id INT, name TEXT)"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, ?name)", conn); cmd.Parameters.Add("?id", MySqlDbType.Int32); cmd.Parameters.Add("?name", MySqlDbType.Text); for (int i = 0; i < 5; i++) { cmd.Parameters[0].Value = i; cmd.Parameters[1].Value = MakeLargeString(2000); cmd.ExecuteNonQuery(); } MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); DataTable dt = new DataTable(); da.Fill(0, 2, new DataTable[] { dt }); } [Test] public void TestBatchingInserts() { execSQL("CREATE TABLE Test (id INT, name VARCHAR(20), PRIMARY KEY(id))"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommand ins = new MySqlCommand("INSERT INTO test (id, name) VALUES (?p1, ?p2)", conn); da.InsertCommand = ins; ins.UpdatedRowSource = UpdateRowSource.None; ins.Parameters.Add("?p1", MySqlDbType.Int32).SourceColumn = "id"; ins.Parameters.Add("?p2", MySqlDbType.VarChar, 20).SourceColumn = "name"; DataTable dt = new DataTable(); da.Fill(dt); for (int i = 1; i <= 100; i++) { DataRow row = dt.NewRow(); row["id"] = i; row["name"] = "name " + i; dt.Rows.Add(row); } da.UpdateBatchSize = 10; da.Update(dt); dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual(100, dt.Rows.Count); for (int i = 0; i < 100; i++) { Assert.AreEqual(i+1, dt.Rows[i]["id"]); Assert.AreEqual("name " + (i+1), dt.Rows[i]["name"]); } } [Test] public void TestBatchingUpdates() { execSQL("CREATE TABLE Test (id INT, name VARCHAR(20), PRIMARY KEY(id))"); execSQL("INSERT INTO Test VALUES (1, 'Test 1')"); execSQL("INSERT INTO Test VALUES (2, 'Test 2')"); execSQL("INSERT INTO Test VALUES (3, 'Test 3')"); MySqlDataAdapter dummyDA = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(dummyDA); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test ORDER BY id ASC", conn); da.UpdateCommand = cb.GetUpdateCommand(); da.UpdateCommand.UpdatedRowSource = UpdateRowSource.None; DataTable dt = new DataTable(); da.Fill(dt); dt.Rows[0]["id"] = 4; dt.Rows[1]["name"] = "new test value"; dt.Rows[2]["id"] = 6; dt.Rows[2]["name"] = "new test value #2"; da.UpdateBatchSize = 0; da.Update(dt); dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual(3, dt.Rows.Count); Assert.AreEqual(2, dt.Rows[0]["id"]); Assert.AreEqual(4, dt.Rows[1]["id"]); Assert.AreEqual(6, dt.Rows[2]["id"]); Assert.AreEqual("new test value", dt.Rows[0]["name"]); Assert.AreEqual("Test 1", dt.Rows[1]["name"]); Assert.AreEqual("new test value #2", dt.Rows[2]["name"]); } [Test] public void TestBatchingMixed() { execSQL("CREATE TABLE Test (id INT, name VARCHAR(20), PRIMARY KEY(id))"); execSQL("INSERT INTO Test VALUES (1, 'Test 1')"); execSQL("INSERT INTO Test VALUES (2, 'Test 2')"); execSQL("INSERT INTO Test VALUES (3, 'Test 3')"); MySqlDataAdapter dummyDA = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommandBuilder cb = new MySqlCommandBuilder(dummyDA); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test ORDER BY id", conn); da.UpdateCommand = cb.GetUpdateCommand(); da.InsertCommand = cb.GetInsertCommand(); da.DeleteCommand = cb.GetDeleteCommand(); da.UpdateCommand.UpdatedRowSource = UpdateRowSource.None; da.InsertCommand.UpdatedRowSource = UpdateRowSource.None; da.DeleteCommand.UpdatedRowSource = UpdateRowSource.None; DataTable dt = new DataTable(); da.Fill(dt); dt.Rows[0]["id"] = 4; dt.Rows[1]["name"] = "new test value"; dt.Rows[2]["id"] = 6; dt.Rows[2]["name"] = "new test value #2"; DataRow row = dt.NewRow(); row["id"] = 7; row["name"] = "foobar"; dt.Rows.Add(row); dt.Rows[1].Delete(); da.UpdateBatchSize = 0; da.Update(dt); dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual(3, dt.Rows.Count); Assert.AreEqual(4, dt.Rows[0]["id"]); Assert.AreEqual(6, dt.Rows[1]["id"]); Assert.AreEqual(7, dt.Rows[2]["id"]); Assert.AreEqual("Test 1", dt.Rows[0]["name"]); Assert.AreEqual("new test value #2", dt.Rows[1]["name"]); Assert.AreEqual("foobar", dt.Rows[2]["name"]); } [Test] public void TestBatchingInsertsMoreThanMaxPacket() { int blobSize = 64000; execSQL("CREATE TABLE Test (id INT, img BLOB, PRIMARY KEY(id))"); int numRows = (maxPacketSize / blobSize) * 2; MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", conn); MySqlCommand ins = new MySqlCommand("INSERT INTO test (id, img) VALUES (@p1, @p2)", conn); da.InsertCommand = ins; ins.UpdatedRowSource = UpdateRowSource.None; ins.Parameters.Add("@p1", MySqlDbType.Int32).SourceColumn = "id"; ins.Parameters.Add("@p2", MySqlDbType.Blob).SourceColumn = "img"; DataTable dt = new DataTable(); da.Fill(dt); for (int i = 0; i < numRows; i++) { DataRow row = dt.NewRow(); row["id"] = i; row["img"] = Utils.CreateBlob(blobSize); dt.Rows.Add(row); } da.UpdateBatchSize = 0; da.Update(dt); dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual(numRows, dt.Rows.Count); for (int i=0; i < numRows; i++) Assert.AreEqual(i, dt.Rows[i]["id"]); } [Test] public void FunctionsReturnString() { string connStr = GetConnectionString(true) + ";functions return string=yes"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT CONCAT(1,2)", c); DataTable dt = new DataTable(); da.Fill(dt); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual("12", dt.Rows[0][0]); Assert.IsTrue(dt.Rows[0][0] is string); } } /// /// Bug #34657 MySqlDataAdapter.Update(DataRow[] rows) fails with MySqlCommandBuilder /// [Test] public void ConnectionNotOpenForInsert() { execSQL("DROP TABLE IF EXISTS Test"); execSQL(@"CREATE TABLE Test (id int(11) NOT NULL default '0', txt varchar(100) default NULL, val decimal(11,2) default NULL, PRIMARY KEY(id)) ENGINE=InnoDB DEFAULT CHARSET=latin1"); execSQL("INSERT INTO Test VALUES (1, 'name', 23.2)"); string connStr = GetConnectionString(true); using (MySqlConnection c = new MySqlConnection(connStr)) { string sql = "SELECT * FROM Test"; MySqlDataAdapter da = new MySqlDataAdapter(sql, c); MySqlCommandBuilder bld = new MySqlCommandBuilder(da); DataSet ds = new DataSet(); da.Fill(ds); ds.Tables[0].Rows[0]["val"] = 99.9M; da.Update(new DataRow[] { ds.Tables[0].Rows[0] }); DataRow r = ds.Tables[0].NewRow(); r["id"] = 4; r["txt"] = "sds"; r["val"] = 113.2M; ds.Tables[0].Rows.Add(r); da.Update(new DataRow[] { r }); } } /// /// Bug#54863 : several datadapter.Update()s with DataTable changes in /// between can result into ConcurrencyException /// [Test] public void AdapterConcurrentException() { execSQL( "CREATE TABLE T (" + "id_auto int(11) NOT NULL AUTO_INCREMENT," + "field varchar(50) DEFAULT NULL," + "PRIMARY KEY (id_auto))"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM T", conn); da.InsertCommand = conn.CreateCommand(); da.InsertCommand.CommandText = @"INSERT INTO T(field) VALUES (@p_field); SELECT * FROM T WHERE id_auto=@@IDENTITY"; da.InsertCommand.Parameters.Add("@p_field", MySqlDbType.VarChar, 50, "field"); da.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord; da.DeleteCommand = conn.CreateCommand(); da.DeleteCommand.CommandText = "DELETE FROM T WHERE id_auto=@id_auto"; da.DeleteCommand.Parameters.Add("@id_auto", MySqlDbType.Int32, 4, "id_auto"); DataSet ds = new DataSet(); da.Fill(ds, "T"); DataTable table = ds.Tables["T"]; DataRow r = table.NewRow(); r["field"] = "row"; table.Rows.Add(r); da.Update(table); Assert.AreEqual(r.RowState, DataRowState.Unchanged); table.Rows[0].Delete(); r = table.NewRow(); r["field"] = "row2"; table.Rows.Add(r); da.Update(table); // here was concurrencyviolation da.Fill(ds); Assert.AreEqual(ds.Tables["T"].Rows.Count, 1); Assert.AreEqual(ds.Tables["T"].Rows[0]["field"], "row2"); } /// /// Bug #38411, using closed connection with data adapter. /// [Test] public void BatchingConnectionClosed() { execSQL("CREATE TABLE Test (id INT, name VARCHAR(20), PRIMARY KEY(id))"); MySqlConnection c = new MySqlConnection(GetConnectionString(true)); MySqlConnection c2 = new MySqlConnection(GetConnectionString(true)); MySqlConnection c3 = new MySqlConnection(GetConnectionString(true)); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test", c); MySqlCommand ins = new MySqlCommand("INSERT INTO test (id, name) VALUES (?p1, ?p2)", c); da.InsertCommand = ins; ins.UpdatedRowSource = UpdateRowSource.None; ins.Parameters.Add("?p1", MySqlDbType.Int32).SourceColumn = "id"; ins.Parameters.Add("?p2", MySqlDbType.VarChar, 20).SourceColumn = "name"; MySqlCommand del = new MySqlCommand("delete from test where id=?p1", c2); da.DeleteCommand = del; del.UpdatedRowSource = UpdateRowSource.None; del.Parameters.Add("?p1", MySqlDbType.Int32).SourceColumn = "id"; MySqlCommand upd = new MySqlCommand("update test set id=?p1, name=?p2 where id=?p1", c3); da.UpdateCommand = upd; upd.UpdatedRowSource = UpdateRowSource.None; upd.Parameters.Add("?p1", MySqlDbType.Int32).SourceColumn = "id"; upd.Parameters.Add("?p2", MySqlDbType.VarChar, 20).SourceColumn = "name"; DataTable dt = new DataTable(); da.Fill(dt); for (int i = 1; i <= 100; i++) { DataRow row = dt.NewRow(); row["id"] = i; row["name"] = "name " + i; dt.Rows.Add(row); } da.UpdateBatchSize = 10; da.Update(dt); dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual(100, dt.Rows.Count); for (int i = 0; i < 100; i++) { Assert.AreEqual(i + 1, dt.Rows[i]["id"]); Assert.AreEqual("name " + (i + 1), dt.Rows[i]["name"]); } foreach (DataRow row in dt.Rows) { row["name"] = row["name"] + "_xxx"; } da.Update(dt); for (int i = 0; i < 100; i++) { dt.Rows[i].Delete(); } da.Update(dt); dt.Rows.Clear(); da.Fill(dt); Assert.AreEqual(dt.Rows.Count, 0); } /// /// Bug#54895 /// ConcurrencyException when trying to use UpdateRowSource.FirstReturnedRecord /// with UpdateCommand and stored procedure. /// [Test] public void UpdateReturnFirstRecord() { string createTable = "CREATE TABLE `bugtable` ( " + "`id_auto` int(11) NOT NULL AUTO_INCREMENT," + "`field` varchar(50) DEFAULT NULL," + "counter int NOT NULL DEFAULT 0," + "PRIMARY KEY (`id_auto`)" + ")"; string procGetAll = "CREATE PROCEDURE sp_getall_bugtable()" + " BEGIN " + "select * from bugtable;" + " END "; string procUpdate = "CREATE PROCEDURE sp_updatebugtable(" + "in p_id_auto int, " + "in p_field varchar(50)) " + "BEGIN " + "update bugtable set field = p_field, counter = counter+1 where id_auto=p_id_auto; " + "select * from bugtable where id_auto=p_id_auto; " + /*retrieve updated row*/ "END "; execSQL(createTable); execSQL(procGetAll); execSQL(procUpdate); /* Add one row to the table */ MySqlCommand cmd = new MySqlCommand( "insert into bugtable(field) values('x')", conn); cmd.ExecuteNonQuery(); DataSet ds = new DataSet(); MySqlDataAdapter da = new MySqlDataAdapter(); da.SelectCommand = conn.CreateCommand(); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.CommandText = "sp_getall_bugtable"; da.UpdateCommand = conn.CreateCommand(); da.UpdateCommand.CommandType = CommandType.StoredProcedure; da.UpdateCommand.CommandText = "sp_updatebugtable"; da.UpdateCommand.Parameters.Add("p_id_auto", MySqlDbType.Int32, 4, "id_auto"); da.UpdateCommand.Parameters.Add("p_field", MySqlDbType.VarChar, 4, "field"); da.UpdateCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord; da.Fill(ds, "bugtable"); DataTable table = ds.Tables["bugtable"]; DataRow row = table.Rows[0]; row["field"] = "newvalue"; Assert.AreEqual(row.RowState, DataRowState.Modified); Assert.AreEqual((int)row["counter"], 0); da.Update(table); // Verify that "counter" field was changed by updating stored procedure. Assert.AreEqual((int)row["counter"], 1); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/StoredProcedureWithAccess.cs0000644000175000017500000004451011127003600027715 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using NUnit.Framework; using System.Globalization; using System.Threading; using MySql.Data.Types; using System.Data.Common; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class StoredProcedureAccess : StoredProcedure { public override void Setup() { accessToMySqlDb = true; base.Setup(); } /// /// Bug #40139 ExecuteNonQuery hangs /// [Test] public void CallingStoredProcWithOnlyExecPrivs() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest() BEGIN SELECT 1; END"); execSQL("CREATE PROCEDURE spTest2() BEGIN SELECT 1; END"); suExecSQL("CREATE USER abc IDENTIFIED BY 'abc'"); try { suExecSQL(String.Format("GRANT SELECT ON `{0}`.* TO 'abc'@'%'", database0)); suExecSQL(String.Format("GRANT EXECUTE ON PROCEDURE `{0}`.spTest TO abc", database0)); string connStr = GetConnectionString("abc", "abc", true) + ";check parameters=false"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("spTest", c); cmd.CommandType = CommandType.StoredProcedure; object o = cmd.ExecuteScalar(); try { cmd.CommandText = "spTest2"; cmd.ExecuteScalar(); } catch (MySqlException ex) { string s = ex.Message; } } } finally { suExecSQL("DROP USER abc"); } } [Test] public void ProcedureParameters() { if (Version < new Version(5, 0)) return; execSQL("DROP PROCEDURE IF EXISTS spTest"); execSQL("CREATE PROCEDURE spTest (id int, name varchar(50)) BEGIN SELECT 1; END"); string[] restrictions = new string[5]; restrictions[1] = database0; restrictions[2] = "spTest"; DataTable dt = conn.GetSchema("Procedure Parameters", restrictions); Assert.IsTrue(dt.Rows.Count == 2); Assert.AreEqual("Procedure Parameters", dt.TableName); Assert.AreEqual(database0.ToLower(), dt.Rows[0]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[0]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("id", dt.Rows[0]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(1, dt.Rows[0]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[0]["PARAMETER_MODE"]); restrictions[4] = "name"; dt.Clear(); dt = conn.GetSchema("Procedure Parameters", restrictions); Assert.AreEqual(1, dt.Rows.Count); Assert.AreEqual(database0.ToLower(), dt.Rows[0]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("sptest", dt.Rows[0]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("name", dt.Rows[0]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(2, dt.Rows[0]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[0]["PARAMETER_MODE"]); execSQL("DROP FUNCTION IF EXISTS spFunc"); execSQL("CREATE FUNCTION spFunc (id int) RETURNS INT BEGIN RETURN 1; END"); restrictions[4] = null; restrictions[1] = database0; restrictions[2] = "spFunc"; dt = conn.GetSchema("Procedure Parameters", restrictions); Assert.IsTrue(dt.Rows.Count == 2); Assert.AreEqual("Procedure Parameters", dt.TableName); Assert.AreEqual(database0.ToLower(), dt.Rows[0]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("spfunc", dt.Rows[0]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual(0, dt.Rows[0]["ORDINAL_POSITION"]); Assert.AreEqual(database0.ToLower(), dt.Rows[1]["SPECIFIC_SCHEMA"].ToString().ToLower()); Assert.AreEqual("spfunc", dt.Rows[1]["SPECIFIC_NAME"].ToString().ToLower()); Assert.AreEqual("id", dt.Rows[1]["PARAMETER_NAME"].ToString().ToLower()); Assert.AreEqual(1, dt.Rows[1]["ORDINAL_POSITION"]); Assert.AreEqual("IN", dt.Rows[1]["PARAMETER_MODE"]); } [Test] public void SingleProcedureParameters() { if (Version < new Version(5, 0)) return; execSQL("DROP PROCEDURE IF EXISTS spTest"); execSQL("CREATE PROCEDURE spTest(id int, IN id2 INT(11), " + "INOUT io1 VARCHAR(20), OUT out1 FLOAT) BEGIN END"); string[] restrictions = new string[4]; restrictions[1] = database0; restrictions[2] = "spTest"; DataTable procs = conn.GetSchema("PROCEDURES", restrictions); Assert.AreEqual(1, procs.Rows.Count); Assert.AreEqual("spTest", procs.Rows[0][0]); Assert.AreEqual(database0.ToLower(), procs.Rows[0][2].ToString().ToLower(CultureInfo.InvariantCulture)); Assert.AreEqual("spTest", procs.Rows[0][3]); DataTable parameters = conn.GetSchema("PROCEDURE PARAMETERS", restrictions); Assert.AreEqual(4, parameters.Rows.Count); DataRow row = parameters.Rows[0]; Assert.AreEqual(database0.ToLower(CultureInfo.InvariantCulture), row["SPECIFIC_SCHEMA"].ToString().ToLower(CultureInfo.InvariantCulture)); Assert.AreEqual("spTest", row["SPECIFIC_NAME"]); Assert.AreEqual(1, row["ORDINAL_POSITION"]); Assert.AreEqual("IN", row["PARAMETER_MODE"]); Assert.AreEqual("id", row["PARAMETER_NAME"]); Assert.AreEqual("INT", row["DATA_TYPE"].ToString().ToUpper(CultureInfo.InvariantCulture)); row = parameters.Rows[1]; Assert.AreEqual(database0.ToLower(CultureInfo.InvariantCulture), row["SPECIFIC_SCHEMA"].ToString().ToLower(CultureInfo.InvariantCulture)); Assert.AreEqual("spTest", row["SPECIFIC_NAME"]); Assert.AreEqual(2, row["ORDINAL_POSITION"]); Assert.AreEqual("IN", row["PARAMETER_MODE"]); Assert.AreEqual("id2", row["PARAMETER_NAME"]); Assert.AreEqual("INT", row["DATA_TYPE"].ToString().ToUpper(CultureInfo.InvariantCulture)); row = parameters.Rows[2]; Assert.AreEqual(database0.ToLower(CultureInfo.InvariantCulture), row["SPECIFIC_SCHEMA"].ToString().ToLower(CultureInfo.InvariantCulture)); Assert.AreEqual("spTest", row["SPECIFIC_NAME"]); Assert.AreEqual(3, row["ORDINAL_POSITION"]); Assert.AreEqual("INOUT", row["PARAMETER_MODE"]); Assert.AreEqual("io1", row["PARAMETER_NAME"]); Assert.AreEqual("VARCHAR", row["DATA_TYPE"].ToString().ToUpper(CultureInfo.InvariantCulture)); row = parameters.Rows[3]; Assert.AreEqual(database0.ToLower(CultureInfo.InvariantCulture), row["SPECIFIC_SCHEMA"].ToString().ToLower(CultureInfo.InvariantCulture)); Assert.AreEqual("spTest", row["SPECIFIC_NAME"]); Assert.AreEqual(4, row["ORDINAL_POSITION"]); Assert.AreEqual("OUT", row["PARAMETER_MODE"]); Assert.AreEqual("out1", row["PARAMETER_NAME"]); Assert.AreEqual("FLOAT", row["DATA_TYPE"].ToString().ToUpper(CultureInfo.InvariantCulture)); } /// /// Bug #27679 MySqlCommandBuilder.DeriveParameters ignores UNSIGNED flag /// [Test] public void UnsignedParametersInSP() { if (Version < new Version(5, 0)) return; execSQL("CREATE PROCEDURE spTest(testid TINYINT UNSIGNED) BEGIN SELECT testid; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; MySqlCommandBuilder.DeriveParameters(cmd); Assert.AreEqual(MySqlDbType.UByte, cmd.Parameters[0].MySqlDbType); Assert.AreEqual(DbType.Byte, cmd.Parameters[0].DbType); } [Test] public void CheckNameOfReturnParameter() { if (Version < new Version(5, 0)) return; execSQL("CREATE FUNCTION fnTest() RETURNS CHAR(50)" + " LANGUAGE SQL DETERMINISTIC BEGIN RETURN \"Test\"; END"); MySqlCommand cmd = new MySqlCommand("fnTest", conn); cmd.CommandType = CommandType.StoredProcedure; MySqlCommandBuilder.DeriveParameters(cmd); Assert.AreEqual(1, cmd.Parameters.Count); Assert.AreEqual("@RETURN_VALUE", cmd.Parameters[0].ParameterName); } /// /// Bug #13632 the MySQLCommandBuilder.deriveparameters has not been updated for MySQL 5 /// Bug #15077 Error MySqlCommandBuilder.DeriveParameters for sp without parameters. /// Bug #19515 DiscoverParameters fails on numeric datatype /// [Test] public void DeriveParameters() { if (Version < new Version(5, 0)) return; execSQL("CREATE TABLE test2 (c CHAR(20))"); execSQL("INSERT INTO test2 values ( 'xxxx')"); MySqlCommand cmd2 = new MySqlCommand("SELECT * FROM test2", conn); using (MySqlDataReader reader = cmd2.ExecuteReader()) { } execSQL("CREATE PROCEDURE spTest(IN \r\nvalin DECIMAL(10,2), " + "\nIN val2 INT, INOUT val3 FLOAT, OUT val4 DOUBLE, INOUT val5 BIT, " + "val6 VARCHAR(155), val7 SET('a','b'), val8 CHAR, val9 NUMERIC(10,2)) " + "BEGIN SELECT 1; END"); MySqlCommand cmd = new MySqlCommand("spTest", conn); cmd.CommandType = CommandType.StoredProcedure; MySqlCommandBuilder.DeriveParameters(cmd); Assert.AreEqual(9, cmd.Parameters.Count); Assert.AreEqual("@valin", cmd.Parameters[0].ParameterName); Assert.AreEqual(ParameterDirection.Input, cmd.Parameters[0].Direction); Assert.AreEqual(MySqlDbType.NewDecimal, cmd.Parameters[0].MySqlDbType); Assert.AreEqual("@val2", cmd.Parameters[1].ParameterName); Assert.AreEqual(ParameterDirection.Input, cmd.Parameters[1].Direction); Assert.AreEqual(MySqlDbType.Int32, cmd.Parameters[1].MySqlDbType); Assert.AreEqual("@val3", cmd.Parameters[2].ParameterName); Assert.AreEqual(ParameterDirection.InputOutput, cmd.Parameters[2].Direction); Assert.AreEqual(MySqlDbType.Float, cmd.Parameters[2].MySqlDbType); Assert.AreEqual("@val4", cmd.Parameters[3].ParameterName); Assert.AreEqual(ParameterDirection.Output, cmd.Parameters[3].Direction); Assert.AreEqual(MySqlDbType.Double, cmd.Parameters[3].MySqlDbType); Assert.AreEqual("@val5", cmd.Parameters[4].ParameterName); Assert.AreEqual(ParameterDirection.InputOutput, cmd.Parameters[4].Direction); Assert.AreEqual(MySqlDbType.Bit, cmd.Parameters[4].MySqlDbType); Assert.AreEqual("@val6", cmd.Parameters[5].ParameterName); Assert.AreEqual(ParameterDirection.Input, cmd.Parameters[5].Direction); Assert.AreEqual(MySqlDbType.VarChar, cmd.Parameters[5].MySqlDbType); Assert.AreEqual("@val7", cmd.Parameters[6].ParameterName); Assert.AreEqual(ParameterDirection.Input, cmd.Parameters[6].Direction); Assert.AreEqual(MySqlDbType.Set, cmd.Parameters[6].MySqlDbType); Assert.AreEqual("@val8", cmd.Parameters[7].ParameterName); Assert.AreEqual(ParameterDirection.Input, cmd.Parameters[7].Direction); Assert.AreEqual(MySqlDbType.String, cmd.Parameters[7].MySqlDbType); Assert.AreEqual("@val9", cmd.Parameters[8].ParameterName); Assert.AreEqual(ParameterDirection.Input, cmd.Parameters[8].Direction); Assert.AreEqual(MySqlDbType.NewDecimal, cmd.Parameters[8].MySqlDbType); execSQL("DROP PROCEDURE spTest"); execSQL("CREATE PROCEDURE spTest() BEGIN END"); cmd.CommandText = "spTest"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Clear(); MySqlCommandBuilder.DeriveParameters(cmd); Assert.AreEqual(0, cmd.Parameters.Count); } /// /// Bug #13632 the MySQLCommandBuilder.deriveparameters has not been updated for MySQL 5 /// [Test] public void DeriveParametersForFunction() { if (Version < new Version(5, 0)) return; execSQL("CREATE FUNCTION fnTest(v1 DATETIME) RETURNS INT " + " LANGUAGE SQL DETERMINISTIC BEGIN RETURN 1; END"); MySqlCommand cmd = new MySqlCommand("fnTest", conn); cmd.CommandType = CommandType.StoredProcedure; MySqlCommandBuilder.DeriveParameters(cmd); Assert.AreEqual(2, cmd.Parameters.Count); Assert.AreEqual("@v1", cmd.Parameters[1].ParameterName); Assert.AreEqual(ParameterDirection.Input, cmd.Parameters[1].Direction); Assert.AreEqual(MySqlDbType.DateTime, cmd.Parameters[1].MySqlDbType); Assert.AreEqual(ParameterDirection.ReturnValue, cmd.Parameters[0].Direction); Assert.AreEqual(MySqlDbType.Int32, cmd.Parameters[0].MySqlDbType); } /// /// Bug #49642 FormatException when returning empty string from a stored function /// [Test] public void NotSpecifyingDataTypeOfReturnValue() { if (Version < new Version(5, 0)) return; execSQL(@"CREATE FUNCTION `TestFunction`() RETURNS varchar(20) RETURN ''"); MySqlCommand cmd = new MySqlCommand("TestFunction", conn); cmd.CommandType = CommandType.StoredProcedure; MySqlParameter returnParam = new MySqlParameter(); returnParam.ParameterName = "?RetVal_"; returnParam.Direction = ParameterDirection.ReturnValue; cmd.Parameters.Add(returnParam); cmd.ExecuteNonQuery(); } /// /// Bug #50123 Batch updates bug when UpdateBatchSize > 1 /// Bug #50444 Parameters.Clear() not working /// [Test] public void UpdateBatchSizeMoreThanOne() { execSQL("DROP TABLE IF EXISTS test"); execSQL(@"CREATE TABLE test(fldID INT NOT NULL, fldValue VARCHAR(50) NOT NULL, PRIMARY KEY(fldID))"); MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT * FROM test", conn); DataTable data = new DataTable(); adapter.Fill(data); MySqlCommand ins = new MySqlCommand( "INSERT INTO test(fldID, fldValue) VALUES (?p1, ?p2)", conn); ins.Parameters.Add("p1", MySqlDbType.Int32).SourceColumn = "fldID"; ins.Parameters.Add("p2", MySqlDbType.String).SourceColumn = "fldValue"; ins.UpdatedRowSource = UpdateRowSource.None; adapter.InsertCommand = ins; adapter.UpdateBatchSize = 10; int numToInsert = 20; for (int i = 0; i < numToInsert; i++) { DataRow row = data.NewRow(); row["fldID"] = i + 1; row["fldValue"] = "ID = " + (i + 1); data.Rows.Add(row); } Assert.AreEqual(numToInsert, adapter.Update(data)); //UPDATE VIA SP MySqlCommand comm = new MySqlCommand("DROP PROCEDURE IF EXISTS pbug50123", conn); comm.ExecuteNonQuery(); comm.CommandText = "CREATE PROCEDURE pbug50123(" + "IN pfldID INT, IN pfldValue VARCHAR(50)) " + "BEGIN INSERT INTO test(fldID, fldValue) " + "VALUES(pfldID, pfldValue); END"; comm.ExecuteNonQuery(); // Set the Insert Command ins.Parameters.Clear(); ins.CommandText = "pbug50123"; ins.CommandType = CommandType.StoredProcedure; ins.Parameters.Add("pfldID", MySqlDbType.Int32).SourceColumn = "fldID"; ins.Parameters.Add("pfldValue", MySqlDbType.String).SourceColumn = "fldValue"; ins.UpdatedRowSource = UpdateRowSource.None; for (int i = 21; i < 41; i++) { DataRow row = data.NewRow(); row["fldID"] = i + 1; row["fldValue"] = "ID = " + (i + 1); data.Rows.Add(row); } // Do the update Assert.AreEqual(numToInsert, adapter.Update(data)); } } } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/CommandTests.cs0000644000175000017500000005750511127003600025237 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using NUnit.Framework; using System.Threading; using System.Diagnostics; namespace MySql.Data.MySqlClient.Tests { [TestFixture] public class CommandTests : BaseTest { [Test] public void InsertTest() { execSQL("CREATE TABLE Test (id int NOT NULL, name VARCHAR(100))"); // do the insert MySqlCommand cmd = new MySqlCommand("INSERT INTO Test (id,name) VALUES(10,'Test')", conn); int cnt = cmd.ExecuteNonQuery(); Assert.AreEqual( 1, cnt, "Insert Count" ); // make sure we get the right value back out cmd.CommandText = "SELECT name FROM Test WHERE id=10"; string name = (string)cmd.ExecuteScalar(); Assert.AreEqual( "Test", name, "Insert result" ); // now do the insert with parameters cmd.CommandText = "INSERT INTO Test (id,name) VALUES(?id, ?name)"; cmd.Parameters.Add( new MySqlParameter("?id", 11)); cmd.Parameters.Add( new MySqlParameter("?name", "Test2")); cnt = cmd.ExecuteNonQuery(); Assert.AreEqual( 1, cnt, "Insert with Parameters Count" ); // make sure we get the right value back out cmd.Parameters.Clear(); cmd.CommandText = "SELECT name FROM Test WHERE id=11"; name = (string)cmd.ExecuteScalar(); Assert.AreEqual( "Test2", name, "Insert with parameters result" ); } [Test] public void UpdateTest() { execSQL("CREATE TABLE Test (id int NOT NULL, name VARCHAR(100))"); execSQL("INSERT INTO Test (id,name) VALUES(10, 'Test')"); execSQL("INSERT INTO Test (id,name) VALUES(11, 'Test2')"); // do the update MySqlCommand cmd = new MySqlCommand("UPDATE Test SET name='Test3' WHERE id=10 OR id=11", conn); MySqlConnection c = cmd.Connection; Assert.AreEqual(conn, c); int cnt = cmd.ExecuteNonQuery(); Assert.AreEqual(2, cnt); // make sure we get the right value back out cmd.CommandText = "SELECT name FROM Test WHERE id=10"; string name = (string)cmd.ExecuteScalar(); Assert.AreEqual("Test3", name); cmd.CommandText = "SELECT name FROM Test WHERE id=11"; name = (string)cmd.ExecuteScalar(); Assert.AreEqual("Test3", name); // now do the update with parameters cmd.CommandText = "UPDATE Test SET name=?name WHERE id=?id"; cmd.Parameters.Add( new MySqlParameter("?id", 11)); cmd.Parameters.Add( new MySqlParameter("?name", "Test5")); cnt = cmd.ExecuteNonQuery(); Assert.AreEqual(1, cnt, "Update with Parameters Count"); // make sure we get the right value back out cmd.Parameters.Clear(); cmd.CommandText = "SELECT name FROM Test WHERE id=11"; name = (string)cmd.ExecuteScalar(); Assert.AreEqual("Test5", name); } [Test] public void DeleteTest() { execSQL("CREATE TABLE Test (id int NOT NULL, name VARCHAR(100))"); execSQL("INSERT INTO Test (id, name) VALUES(1, 'Test')"); execSQL("INSERT INTO Test (id, name) VALUES(2, 'Test2')"); // make sure we get the right value back out MySqlCommand cmd = new MySqlCommand("DELETE FROM Test WHERE id=1 or id=2", conn); int delcnt = cmd.ExecuteNonQuery(); Assert.AreEqual(2, delcnt); // find out how many rows we have now cmd.CommandText = "SELECT COUNT(*) FROM Test"; object after_cnt = cmd.ExecuteScalar(); Assert.AreEqual(0, after_cnt); } [Test] public void CtorTest() { execSQL("CREATE TABLE Test (id int NOT NULL, name VARCHAR(100))"); MySqlTransaction txn = conn.BeginTransaction(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); MySqlCommand clone = new MySqlCommand(cmd.CommandText, (MySqlConnection)cmd.Connection, (MySqlTransaction)cmd.Transaction); clone.Parameters.AddWithValue("?test", 1); txn.Rollback(); } [Test] public void CloneCommand() { MySqlCommand cmd = new MySqlCommand(); MySqlCommand newCommand = cmd.Clone(); IDbCommand newCommand2 = (IDbCommand)(cmd as ICloneable).Clone(); } [Test] public void TableWithOVer100Columns() { string sql = "create table IF NOT EXISTS zvan (id int(8) primary key " + "unique auto_increment, name varchar(250)) ENGINE=INNODB; "; /* "create table IF NOT EXISTS ljudyna (id int(8) primary key " + "unique auto_increment, name varchar(250), data_narod date, " + "id_in_zvan int(8), kandidat varchar(250), tel_rob_vn varchar(250), " + "tel_rob_mis varchar(250), n_kabin varchar(250), n_nak_zvan varchar(250), " + "d_nak_zvan date, sex tinyint(1), n_nak_pos varchar(250), " + "d_nak_pos date, posad_data varchar(250), visl1 varchar(250), visl2 " + "varchar(250), visl3 varchar(250), cpidr_f int(8), cposad_f int(8), sumis " + "tinyint(1), zs_s date, zs_po date, ovs_z date, ovs_po date, naiavn_zviln " + "tinyint(1), ovs_z1 date, ovs_po1 date, ovs_z2 date, ovs_po2 date, ovs_z3 date, " + "ovs_po3 date, ovs_prakt varchar(250), data_atest date, data_sp date, v_akad_z " + "date, z_akad_zvln tinyint(1), v_akad_period varchar(250), nauk_stup " + "varchar(250), vch_zvan varchar(250), n_sprav varchar(250), n_posv varchar(250), " + "nacional varchar(250), osvita varchar(250), osvita_zakin_sho varchar(250), " + "osvita_zakin_koli date, osvita_special varchar(250), osvita_kvalifikac " + "varchar(250), de_navchaet varchar(250), data_vstupu date, termin_navch " + "varchar(250), adresa varchar(250), tel_dom varchar(250), marka_avto " + "varchar(250), n_avto varchar(250), color_avto varchar(250), vikor_avto " + "varchar(250), posv_avto varchar(250), marka_zbr varchar(250), nomer_calibr_zbr " + "varchar(250), vid_zbr varchar(250), nomer_data_razreshen varchar(250), pasport " + "varchar(250), oklad1 varchar(250), prem07_2003 varchar(250), nadb07_2003 " + "varchar(250), osob_nom varchar(250), nadbavka_stag_max varchar(250), " + "nadbavka_stag_08_2003 varchar(250), nadbavka_stag_10_2003 varchar(250), " + "nadbavka_stag_11_2003 varchar(250), nadbavka_stag_02_2004 varchar(250), " + "vidp_vikoristav varchar(250), vidp_plan varchar(250), vidp_vidgil varchar(250), " + "vidp_nevidgil_dniv varchar(250), nadb111 varchar(250), prem_3_1 varchar(250), " + "nadb_4_1 varchar(250), prem_3_2 varchar(250), nadb_3_2 varchar(250), nedolos " + "varchar(250), sposl int(8), cposl int(8), czaoh int(8), 07_2003_oklad " + "varchar(250), 05_2003_oklad varchar(250), deti_jeni varchar(250), nadb_volny " + "varchar(250), prem_volny varchar(250), dispanser tinyint(1), posl_spisok " + "tinyint(1), anketa_avtobiogr tinyint(1), photokartka tinyint(1), sp1 tinyint(1), " + "inshe varchar(250), oklad2 varchar(250), slugbova tinyint(1), atestuvan " + "varchar(250), 09_2004_oklad_vstan varchar(250), golosuvannia varchar(250), " + "stag_kalendar varchar(250), data_stag_kalendar varchar(250), medali " + "varchar(250), medali_mae varchar(250), visluga_cal_ovs_and_zs varchar(250), " + "FOREIGN KEY (id_in_zvan) REFERENCES zvan(id) ON DELETE CASCADE ON UPDATE " + "CASCADE) TYPE=INNODB DEFAULT CHARACTER SET cp1251 COLLATE cp1251_ukrainian_ci"; */ MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.ExecuteNonQuery(); } /// /// Bug #12245 using Prepare() on an insert command causes null parameters to convert to "0" /// [Test] public void InsertingPreparedNulls() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (id int NOT NULL, name VARCHAR(100))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(1, ?str)", conn); cmd.Parameters.Add("?str", MySqlDbType.VarChar); cmd.Prepare(); cmd.Parameters[0].Value = null; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.AreEqual(DBNull.Value, reader[1]); } } /// /// MySQL Bugs: #12163: Insert using prepared statement causes double insert /// [Test] public void PreparedInsertUsingReader() { if (Version < new Version(4, 1)) return; execSQL("CREATE TABLE Test (id int NOT NULL, name VARCHAR(100))"); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES(1, 'Test')", conn); cmd.Prepare(); using (MySqlDataReader reader = cmd.ExecuteReader()) { } cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { Assert.IsTrue(reader.Read()); Assert.IsFalse(reader.Read()); Assert.IsFalse(reader.NextResult()); } } /// /// Bug# 8119. Unable to reproduce but left in anyway /// /* [Test] public void ReallyBigCommandString() { System.Text.StringBuilder sql = new System.Text.StringBuilder(); for (int i = 0; i < 10; i++) sql.Append("DROP TABLE IF EXISTS idx" + i + ";CREATE TABLE idx" + i + "(aa int not null auto_increment primary key, a int, b varchar(50), c int);"); int c = 0; for (int z = 0; z < 100; z++) for (int x = 0; x < 10; x++, c++) { string s = String.Format("INSERT INTO idx{0} (a, b, c) values ({1}, 'field{1}', {2});", x, z, c); sql.Append(s); } MySqlCommand cmd = new MySqlCommand(sql.ToString(), conn); cmd.ExecuteNonQuery(); for (int i = 0; i < 10; i++) { cmd.CommandText = "SELECT COUNT(*) FROM idx" + i; object count = cmd.ExecuteScalar(); Assert.AreEqual(100, count); execSQL("DROP TABLE IF EXISTS idx" + i); } } */ /// /// Bug #7248 There is already an open DataReader associated with this Connection which must /// [Test] public void GenWarnings() { execSQL("CREATE TABLE Test (id INT, dt DATETIME)"); execSQL("INSERT INTO Test VALUES (1, NOW())"); execSQL("INSERT INTO Test VALUES (2, NOW())"); execSQL("INSERT INTO Test VALUES (3, NOW())"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM Test WHERE dt = '" + DateTime.Now + "'", conn); DataSet ds = new DataSet(); da.Fill(ds); } /// /// Bug #11991 ExecuteScalar /// [Test] public void CloseReaderAfterFailedConvert() { execSQL("CREATE TABLE Test (dt DATETIME)"); execSQL("INSERT INTO Test VALUES ('00-00-0000 00:00:00')"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM Test", conn); try { cmd.ExecuteScalar(); } catch (Exception) { } conn.BeginTransaction(); } /// /// Bug #25443 ExecuteScalar() hangs when more than one bad result /// [Test] public void ExecuteWithOneBadQuery() { MySqlCommand command = new MySqlCommand("SELECT 1; SELECT * FROM foo", conn); try { command.ExecuteScalar(); } catch (MySqlException) { } // now try using ExecuteNonQuery try { command.ExecuteNonQuery(); } catch (MySqlException) { } } /// /// Bug #27958 Cannot use Data Source Configuration Wizard on large databases /// [Test] public void DefaultCommandTimeout() { MySqlConnection c = new MySqlConnection("server=localhost"); MySqlCommand cmd = new MySqlCommand("", c); Assert.AreEqual(30, cmd.CommandTimeout); c = new MySqlConnection("server=localhost;default command timeout=47"); cmd = new MySqlCommand("", c); Assert.AreEqual(47, cmd.CommandTimeout); cmd = new MySqlCommand(""); Assert.AreEqual(30, cmd.CommandTimeout); cmd.CommandTimeout = 66; cmd.Connection = c; Assert.AreEqual(66, cmd.CommandTimeout); cmd.CommandTimeout = 0; Assert.AreEqual(0, cmd.CommandTimeout); c = new MySqlConnection("server=localhost;default command timeout=0"); cmd = new MySqlCommand("", c); Assert.AreEqual(0, cmd.CommandTimeout); } /// /// Bug #38276 Short circuit evaluation error in MySqlCommand.CheckState() /// [Test] public void SetNullConnection() { MySqlCommand command = new MySqlCommand(); command.CommandText = "SELECT 1"; command.Connection = null; try { object o = command.ExecuteScalar(); } catch (InvalidOperationException) { } } /// /// Bug #45941 SQL-Injection attack /// [Test] public void SqlInjection1() { execSQL("DROP TABLE IF EXISTS Test"); execSQL("CREATE TABLE Test(name VARCHAR(100)) ENGINE=MyISAM DEFAULT CHARSET=utf8"); execSQL("INSERT INTO Test VALUES ('name1'), ('name2'), ('name3')"); MySqlCommand cnt = new MySqlCommand("SELECT COUNT(*) FROM Test", conn); Int64 count = (Int64)cnt.ExecuteScalar(); MySqlCommand cmd = new MySqlCommand("DELETE FROM Test WHERE name=?name", conn); cmd.Parameters.Add("?name", MySqlDbType.VarChar); cmd.Parameters[0].Value = "\u2032 OR 1=1;-- --"; cmd.ExecuteNonQuery(); Assert.AreEqual(count, (Int64)cnt.ExecuteScalar()); } /// /// Bug #44194 ExecuteNonQuery for update commands does not match actual rows updated /// [Test] public void UseAffectedRows() { execSQL("CREATE TABLE Test (id INT, name VARCHAR(20))"); execSQL("INSERT INTO Test VALUES (1, 'A')"); execSQL("INSERT INTO Test VALUES (2, 'B')"); execSQL("INSERT INTO Test VALUES (3, 'C')"); MySqlCommand cmd = new MySqlCommand("UPDATE Test SET name='C' WHERE id=3", conn); Assert.AreEqual(1, cmd.ExecuteNonQuery()); string conn_str = GetConnectionString(true) + ";use affected rows=true"; using (MySqlConnection c = new MySqlConnection(conn_str)) { c.Open(); cmd.Connection = c; Assert.AreEqual(0, cmd.ExecuteNonQuery()); } } /// /// Bug #45502 error if "Allow Batch=False" /// [Test] public void DontAllowBatching() { string connStr = GetConnectionString(true) + ";allow batch=false;character set=utf8"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("SELECT 1", c); cmd.ExecuteScalar(); } } [Test] public void TableCommandType() { execSQL("CREATE TABLE Test (id INT, name VARCHAR(20))"); execSQL("INSERT INTO Test VALUES (1, 'A')"); execSQL("CREATE TABLE Test1 (id INT, name VARCHAR(20))"); execSQL("INSERT INTO Test1 VALUES (2, 'B')"); MySqlCommand cmd = new MySqlCommand("Test,Test1", conn); cmd.CommandType = CommandType.TableDirect; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); Assert.AreEqual(1, reader.GetInt32(0)); Assert.AreEqual("A", reader.GetString(1)); Assert.AreEqual(2, reader.GetInt32(2)); Assert.AreEqual("B", reader.GetString(3)); } } /// /// Bug #57501 MySql Connector/NET 6.3.5.0 fails to read from DataReader /// [Test] public void HelperTest() { string connStr = GetConnectionString(true); using (MySqlDataReader reader = MySqlHelper.ExecuteReader(connStr, "SHOW TABLES")) { while (reader.Read()) { } } } /// /// Bug #58652 ExecuteReader throws NullReferenceException when using CommandBehavior.Close /// [Test] public void SyntaxErrorWithCloseConnection() { string connStr = GetConnectionString(true); using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlCommand cmd = new MySqlCommand("SELE 1", c); try { cmd.ExecuteReader(CommandBehavior.CloseConnection); Assert.Fail("This should have failed"); } catch (MySqlException) { } Assert.IsTrue(c.State == ConnectionState.Closed); } } /// /// Bug #59537 Different behavior from console and /// [Test] public void EmptyOrJustSemiCommand() { MySqlCommand cmd = new MySqlCommand("", conn); try { cmd.ExecuteNonQuery(); Assert.Fail("Should not get here"); } catch (InvalidOperationException) { } cmd.CommandText = ";"; try { cmd.ExecuteNonQuery(); } catch (MySqlException) { } } #if !CF /// /// Bug #59616 Only INSERTs are batched /// [Test] public void BatchUpdatesAndDeletes() { execSQL("CREATE TABLE test (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20))"); execSQL("INSERT INTO test VALUES (1, 'boo'), (2, 'boo'), (3, 'boo')"); MySqlTrace.Listeners.Clear(); MySqlTrace.Switch.Level = SourceLevels.All; GenericListener listener = new GenericListener(); MySqlTrace.Listeners.Add(listener); string connStr = GetConnectionString(true) + ";logging=true;allow batch=true"; using (MySqlConnection c = new MySqlConnection(connStr)) { c.Open(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM test", c); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); da.UpdateCommand = cb.GetUpdateCommand(); da.UpdateCommand.UpdatedRowSource = UpdateRowSource.None; da.UpdateBatchSize = 100; DataTable dt = new DataTable(); da.Fill(dt); dt.Rows[0]["name"] = "boo2"; dt.Rows[1]["name"] = "boo2"; dt.Rows[2]["name"] = "boo2"; da.Update(dt); } Assert.AreEqual(1, listener.Find("Query Opened: UPDATE")); } #endif [Test] public void ExecuteReaderReturnsReaderAfterCancel() { execSQL("DROP TABLE IF EXISTS TableWithDateAsPrimaryKey"); execSQL("DROP TABLE IF EXISTS TableWithStringAsPrimaryKey"); createTable("CREATE TABLE TableWithDateAsPrimaryKey(PrimaryKey date NOT NULL, PRIMARY KEY (PrimaryKey))", "InnoDB"); createTable("CREATE TABLE TableWithStringAsPrimaryKey(PrimaryKey nvarchar(50) NOT NULL, PRIMARY KEY (PrimaryKey))", "InnoDB"); string connStr = GetConnectionString(true); using (MySqlConnection connection = new MySqlConnection(connStr)) { connection.Open(); MySqlCommand command = new MySqlCommand("SELECT PrimaryKey FROM TableWithDateAsPrimaryKey", connection); IDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); DataTable dataTableSchema = reader.GetSchemaTable(); command.Cancel(); reader.Close(); command = new MySqlCommand("SELECT PrimaryKey FROM TableWithStringAsPrimaryKey", connection); reader = command.ExecuteReader(CommandBehavior.KeyInfo); Assert.IsNotNull(reader); dataTableSchema = reader.GetSchemaTable(); Assert.AreEqual("PrimaryKey", dataTableSchema.Rows[0][dataTableSchema.Columns[0]]); reader.Close(); } } } #region Configs public class CommandTestsSocketCompressed : CommandTests { protected override string GetConnectionInfo() { return String.Format("port={0};compress=true", port); } } #if !CF [Category("Pipe")] public class CommandTestsPipe : CommandTests { protected override string GetConnectionInfo() { return String.Format("protocol=namedpipe;pipe name={0}", pipeName); } } [Category("Compressed")] [Category("Pipe")] public class CommandTestsPipeCompressed : CommandTests { protected override string GetConnectionInfo() { return String.Format("protocol=namedpipe;pipe name={0};compress=true", pipeName); } } [Category("SharedMemory")] public class CommandTestsSharedMemory : CommandTests { protected override string GetConnectionInfo() { return String.Format("protocol=sharedmemory; shared memory name={0}", memoryName); } } [Category("Compressed")] [Category("SharedMemory")] public class CommandTestsSharedMemoryCompressed : CommandTests { protected override string GetConnectionInfo() { return String.Format("protocol=sharedmemory; shared memory name={0};compress=true", memoryName); } } #endif #endregion } mysql-connector-net-6.4.3/Tests/MySql.Data.Tests/StressTests.cs0000644000175000017500000001342111127003600025131 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using MySql.Data.MySqlClient; using System.Data; using NUnit.Framework; using System.Threading; using System.Collections; namespace MySql.Data.MySqlClient.Tests { /// /// Summary description for ConnectionTests. /// [TestFixture] public class StressTests : BaseTest { public override void Setup() { base.Setup(); execSQL("CREATE TABLE Test (id INT NOT NULL, name varchar(100), blob1 LONGBLOB, text1 TEXT, " + "PRIMARY KEY(id))"); } #if !CF [Test] public void TestMultiPacket() { int len = 20000000; suExecSQL("SET GLOBAL max_allowed_packet=64000000"); // currently do not test this with compression if (conn.UseCompression) return; using (MySqlConnection c = new MySqlConnection(GetConnectionString(true))) { c.Open(); byte[] dataIn = Utils.CreateBlob(len); byte[] dataIn2 = Utils.CreateBlob(len); MySqlCommand cmd = new MySqlCommand("INSERT INTO Test VALUES (?id, NULL, ?blob, NULL )", c); cmd.CommandTimeout = 0; cmd.Parameters.Add(new MySqlParameter("?id", 1)); cmd.Parameters.Add(new MySqlParameter("?blob", dataIn)); cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = 2; cmd.Parameters[1].Value = dataIn2; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT * FROM Test"; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); byte[] dataOut = new byte[len]; long count = reader.GetBytes(2, 0, dataOut, 0, len); Assert.AreEqual(len, count); int i = 0; try { for (; i < len; i++) Assert.AreEqual(dataIn[i], dataOut[i]); } catch (Exception) { int z = i; } reader.Read(); count = reader.GetBytes(2, 0, dataOut, 0, len); Assert.AreEqual(len, count); for (int x=0; x < len; x++) Assert.AreEqual(dataIn2[x], dataOut[x]); } } } #endif [Test] public void TestSequence() { MySqlCommand cmd = new MySqlCommand("insert into Test (id, name) values (?id, 'test')", conn); cmd.Parameters.Add( new MySqlParameter("?id", 1)); for (int i=1; i <= 8000; i++) { cmd.Parameters[0].Value = i; cmd.ExecuteNonQuery(); } int i2 = 0; cmd = new MySqlCommand("select * from Test", conn); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { Assert.AreEqual( i2+1, reader.GetInt32(0), "Sequence out of order" ); i2++; } reader.Close(); Assert.AreEqual( 8000, i2 ); cmd = new MySqlCommand("delete from Test where id >= 100", conn); cmd.ExecuteNonQuery(); } } } #region Configs #if !CF [Category("Compressed")] public class StressTestsSocketCompressed : StressTests { protected override string GetConnectionInfo() { return String.Format("port={0};compress=true", port); } } [Category("Pipe")] public class StressTestsPipe : StressTests { protected override string GetConnectionInfo() { return String.Format("protocol=pipe;pipe name={0}", pipeName); } } [Category("Compressed")] [Category("Pipe")] public class StressTestsPipeCompressed : StressTests { protected override string GetConnectionInfo() { return String.Format("protocol=pipe;pipe name={0};compress=true", pipeName); } } [Category("SharedMemory")] public class StressTestsSharedMemory : StressTests { protected override string GetConnectionInfo() { return String.Format("protocol=memory; shared memory name={0}", memoryName); } } [Category("Compressed")] [Category("SharedMemory")] public class StressTestsSharedMemoryCompressed : StressTests { protected override string GetConnectionInfo() { return String.Format("protocol=memory; shared memory name={0};compress=true", memoryName); } } #endif #endregion } mysql-connector-net-6.4.3/COPYING0000644000175000017500000004377311127003600017224 0ustar directhexdirecthex GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is free software, and you are welcome to redistribute it under certain conditions; type 'show c' for details. The hypothetical commands 'show w' and 'show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than 'show w' and 'show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program 'Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.mysql-connector-net-6.4.3/VS2008/0000755000175000017500000000000011127003600017015 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/MySQLClient.sln0000644000175000017500000001161111127003600021637 0ustar directhexdirecthex Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data", "Source\MySql.Data\MySql.Data.csproj", "{E9DF5ED1-4CBD-4226-B931-9A51610AC14D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data.Tests", "Tests\MySql.Data.Tests\MySql.Data.Tests.csproj", "{F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Web", "Source\MySql.Web\MySql.Web.csproj", "{C28B1166-1380-445D-AEC1-8A18B990DD18}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Web.Tests", "Tests\MySql.Web.Tests\MySql.Web.Tests.csproj", "{83462D15-E576-4079-BBC9-9EE1CF0B24DD}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data.Entity", "Source\MySql.Data.Entity\MySql.Data.Entity.csproj", "{EDED3135-95D2-4BCE-A810-F3F2AD7935B7}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data.Entity.Tests", "Tests\MySql.Data.Entity.Tests\MySql.Data.Entity.Tests.csproj", "{D37B3572-767F-4622-A835-844B0EBEFD5B}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.VisualStudio", "Source\MySql.VisualStudio\MySql.VisualStudio.csproj", "{DC3517FF-AC26-4755-9B7A-EF658FF69593}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data.CF", "Source\MySql.Data.CF\MySql.Data.CF.csproj", "{587A47FB-C1CC-459D-93B6-179D95E41EFB}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data.CF.Tests", "Tests\MySql.Data.CF.Tests\MySql.Data.CF.Tests.csproj", "{710D9251-17A3-4429-9A91-63F03267F310}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|Any CPU.Build.0 = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|Any CPU.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|Any CPU.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|Any CPU.Build.0 = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|Any CPU.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|Any CPU.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|Any CPU.Build.0 = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|Any CPU.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|Any CPU.Build.0 = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Debug|Any CPU.Build.0 = Debug|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Release|Any CPU.ActiveCfg = Release|Any CPU {83462D15-E576-4079-BBC9-9EE1CF0B24DD}.Release|Any CPU.Build.0 = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Debug|Any CPU.Build.0 = Debug|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Release|Any CPU.ActiveCfg = Release|Any CPU {EDED3135-95D2-4BCE-A810-F3F2AD7935B7}.Release|Any CPU.Build.0 = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Debug|Any CPU.Build.0 = Debug|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Release|Any CPU.ActiveCfg = Release|Any CPU {D37B3572-767F-4622-A835-844B0EBEFD5B}.Release|Any CPU.Build.0 = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|Any CPU.Build.0 = Debug|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|Any CPU.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|Any CPU.Build.0 = Release|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Debug|Any CPU.Build.0 = Debug|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Release|Any CPU.ActiveCfg = Release|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Release|Any CPU.Build.0 = Release|Any CPU {710D9251-17A3-4429-9A91-63F03267F310}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {710D9251-17A3-4429-9A91-63F03267F310}.Debug|Any CPU.Build.0 = Debug|Any CPU {710D9251-17A3-4429-9A91-63F03267F310}.Release|Any CPU.ActiveCfg = Release|Any CPU {710D9251-17A3-4429-9A91-63F03267F310}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal mysql-connector-net-6.4.3/VS2008/Tests/0000755000175000017500000000000011127003600020117 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Tests/MySql.Web.Tests/0000755000175000017500000000000011127003600023001 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Tests/MySql.Web.Tests/MySql.Web.Tests.csproj0000644000175000017500000001075011127003600027110 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {83462D15-E576-4079-BBC9-9EE1CF0B24DD} Library Properties MySql.Web.Tests MySql.Web.Tests 3.5 v2.0 false publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false true true full false bin\Debug\ DEBUG;TRACE prompt 4 AllRules.ruleset pdbonly true bin\Release\ TRACE prompt 4 AllRules.ruleset Properties\VersionInfo.cs Properties\AssemblyInfo.cs {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} MySql.Data {C28B1166-1380-445D-AEC1-8A18B990DD18} MySql.Web {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4} MySql.Data.Tests mysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Entity.Tests/0000755000175000017500000000000011127003600024410 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Entity.Tests/Model1.Designer.cs0000644000175000017500000002111711127003600027621 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.5446 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ [assembly: global::System.Data.Objects.DataClasses.EdmSchemaAttribute()] // Original file name: // Generation date: 6/23/2011 7:22:59 AM namespace MySql.Data.Entity.Tests { /// /// There are no comments for Model1Container in the schema. /// public partial class Model1Container : global::System.Data.Objects.ObjectContext { /// /// Initializes a new Model1Container object using the connection string found in the 'Model1Container' section of the application configuration file. /// public Model1Container() : base("name=Model1Container", "Model1Container") { this.OnContextCreated(); } /// /// Initialize a new Model1Container object. /// public Model1Container(string connectionString) : base(connectionString, "Model1Container") { this.OnContextCreated(); } /// /// Initialize a new Model1Container object. /// public Model1Container(global::System.Data.EntityClient.EntityConnection connection) : base(connection, "Model1Container") { this.OnContextCreated(); } partial void OnContextCreated(); /// /// There are no comments for Animals in the schema. /// public global::System.Data.Objects.ObjectQuery Animals { get { if ((this._Animals == null)) { this._Animals = base.CreateQuery("[Animals]"); } return this._Animals; } } private global::System.Data.Objects.ObjectQuery _Animals; /// /// There are no comments for Shelters in the schema. /// public global::System.Data.Objects.ObjectQuery Shelters { get { if ((this._Shelters == null)) { this._Shelters = base.CreateQuery("[Shelters]"); } return this._Shelters; } } private global::System.Data.Objects.ObjectQuery _Shelters; /// /// There are no comments for Animals in the schema. /// public void AddToAnimals(Animal animal) { base.AddObject("Animals", animal); } /// /// There are no comments for Shelters in the schema. /// public void AddToShelters(Shelter shelter) { base.AddObject("Shelters", shelter); } } /// /// There are no comments for Model1.Animal in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Model1", Name="Animal")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Animal : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Animal object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of ShelterId. public static Animal CreateAnimal(int id, string name, int shelterId) { Animal animal = new Animal(); animal.Id = id; animal.Name = name; animal.ShelterId = shelterId; return animal; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for Property ShelterId in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int ShelterId { get { return this._ShelterId; } set { this.OnShelterIdChanging(value); this.ReportPropertyChanging("ShelterId"); this._ShelterId = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("ShelterId"); this.OnShelterIdChanged(); } } private int _ShelterId; partial void OnShelterIdChanging(int value); partial void OnShelterIdChanged(); } /// /// There are no comments for Model1.Shelter in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="Model1", Name="Shelter")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Shelter : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Shelter object. /// /// Initial value of Id. public static Shelter CreateShelter(int id) { Shelter shelter = new Shelter(); shelter.Id = id; return shelter; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); } } mysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Entity.Tests/TestModel.edmx0000644000175000017500000011166211127003600027176 0ustar directhexdirecthex mysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Entity.Tests/Model1.edmx0000644000175000017500000001016111127003600026407 0ustar directhexdirecthex mysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Entity.Tests/Model2.Designer.cs0000644000175000017500000002765211127003600027634 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.5446 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ [assembly: global::System.Data.Objects.DataClasses.EdmSchemaAttribute()] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("juliotestsModel", "FK_ORDER_CUSTOMER", "customer", global::System.Data.Metadata.Edm.RelationshipMultiplicity.ZeroOrOne, typeof(MySql.Data.Entity.Tests.customer), "order", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(MySql.Data.Entity.Tests.order))] // Original file name: // Generation date: 6/30/2011 4:19:17 PM namespace MySql.Data.Entity.Tests { /// /// There are no comments for model2Entities in the schema. /// public partial class model2Entities : global::System.Data.Objects.ObjectContext { /// /// Initializes a new model2Entities object using the connection string found in the 'model2Entities' section of the application configuration file. /// public model2Entities() : base("name=model2Entities", "model2Entities") { this.OnContextCreated(); } /// /// Initialize a new model2Entities object. /// public model2Entities(string connectionString) : base(connectionString, "model2Entities") { this.OnContextCreated(); } /// /// Initialize a new model2Entities object. /// public model2Entities(global::System.Data.EntityClient.EntityConnection connection) : base(connection, "model2Entities") { this.OnContextCreated(); } partial void OnContextCreated(); /// /// There are no comments for customer in the schema. /// public global::System.Data.Objects.ObjectQuery customer { get { if ((this._customer == null)) { this._customer = base.CreateQuery("[customer]"); } return this._customer; } } private global::System.Data.Objects.ObjectQuery _customer; /// /// There are no comments for order in the schema. /// public global::System.Data.Objects.ObjectQuery order { get { if ((this._order == null)) { this._order = base.CreateQuery("[order]"); } return this._order; } } private global::System.Data.Objects.ObjectQuery _order; /// /// There are no comments for customer in the schema. /// public void AddTocustomer(customer customer) { base.AddObject("customer", customer); } /// /// There are no comments for order in the schema. /// public void AddToorder(order order) { base.AddObject("order", order); } } /// /// There are no comments for juliotestsModel.customer in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="juliotestsModel", Name="customer")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class customer : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new customer object. /// /// Initial value of Id. public static customer Createcustomer(int id) { customer customer = new customer(); customer.Id = id; return customer; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for order in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("juliotestsModel", "FK_ORDER_CUSTOMER", "order")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection order { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("juliotestsModel.FK_ORDER_CUSTOMER", "order"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("juliotestsModel.FK_ORDER_CUSTOMER", "order", value); } } } } /// /// There are no comments for juliotestsModel.order in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="juliotestsModel", Name="order")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class order : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new order object. /// /// Initial value of Id. /// Initial value of Order_Date. public static order Createorder(int id, global::System.DateTime order_Date) { order order = new order(); order.Id = id; order.Order_Date = order_Date; return order; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property Order_Date in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.DateTime Order_Date { get { return this._Order_Date; } set { this.OnOrder_DateChanging(value); this.ReportPropertyChanging("Order_Date"); this._Order_Date = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Order_Date"); this.OnOrder_DateChanged(); } } private global::System.DateTime _Order_Date; partial void OnOrder_DateChanging(global::System.DateTime value); partial void OnOrder_DateChanged(); /// /// There are no comments for customer in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("juliotestsModel", "FK_ORDER_CUSTOMER", "customer")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public customer customer { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("juliotestsModel.FK_ORDER_CUSTOMER", "customer").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("juliotestsModel.FK_ORDER_CUSTOMER", "customer").Value = value; } } /// /// There are no comments for customer in the schema. /// [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference customerReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("juliotestsModel.FK_ORDER_CUSTOMER", "customer"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("juliotestsModel.FK_ORDER_CUSTOMER", "customer", value); } } } } } mysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Entity.Tests/MySql.Data.Entity.Tests.csproj0000644000175000017500000001757111127003600032136 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {D37B3572-767F-4622-A835-844B0EBEFD5B} Library Properties MySql.Data.Entity.Tests MySql.Data.Entity.Tests v3.5 512 3.5 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false bin\Debug\ DEBUG;TRACE prompt 4 AllRules.ruleset pdbonly true bin\Release\ TRACE prompt 4 AllRules.ruleset 3.5 3.5 3.5 3.5 3.0 Properties\VersionInfo.cs Properties\AssemblyInfo.cs True True Model1.edmx True True Model2.edmx True True TestModel.edmx EntityModelCodeGenerator Model2.Designer.cs EntityModelCodeGenerator Model1.Designer.cs EntityModelCodeGenerator TestModel.Designer.cs Properties\procs.sql Properties\schema.sql Designer Properties\Resources.resx {EDED3135-95D2-4BCE-A810-F3F2AD7935B7} MySql.Data.Entity {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} MySql.Data {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4} MySql.Data.Tests mysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Entity.Tests/Model2.edmx0000644000175000017500000001545511127003600026423 0ustar directhexdirecthex mysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Entity.Tests/Properties/0000755000175000017500000000000011127003600026544 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Entity.Tests/Properties/SQLSyntax.resx0000644000175000017500000005241011127003600031317 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`Age` FROM `Authors` AS `Extent1` WHERE NOT EXISTS(SELECT 1 AS `C1` FROM `Books` AS `Extent2` WHERE `Extent1`.`Id` = `Extent2`.`Author_id`) SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT AVG(`Extent1`.`MinAge`) AS `A1` FROM `Toys` AS `Extent1`) AS `GroupBy1` SELECT 1 AS `C1`, `GroupBy1`.`A1` AS `C2` FROM (SELECT `Extent2`.`Id` AS `K1`, AVG(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` LEFT OUTER JOIN `Stores` AS `Extent2` ON `Extent1`.`StoreId` = `Extent2`.`Id` GROUP BY `Extent2`.`Id`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT AVG(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` INNER JOIN `Stores` AS `Extent2` ON `Extent1`.`StoreId` = `Extent2`.`Id` WHERE `Extent2`.`Id` = 3) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT COUNT(`Extent1`.`Id`) AS `A1` FROM `Toys` AS `Extent1`) AS `GroupBy1` SELECT 1 AS `C1`, `GroupBy1`.`K1` AS `Name`, `GroupBy1`.`A1` AS `C2` FROM (SELECT `Extent1`.`Name` AS `K1`, `Extent1`.`DateBegan` AS `K2`, `Extent1`.`NumEmployees` AS `K3`, COUNT(1) AS `A1` FROM `Companies` AS `Extent1` GROUP BY `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`) AS `GroupBy1` SELECT 1 AS `C1`, `GroupBy1`.`K1` AS `Name`, `GroupBy1`.`A1` AS `C2` FROM (SELECT `Extent1`.`Name` AS `K1`, COUNT(1) AS `A1` FROM `Companies` AS `Extent1` GROUP BY `Extent1`.`Name`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT COUNT(`Extent1`.`Id`) AS `A1` FROM `Toys` AS `Extent1`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT COUNT(`Extent1`.`Id`) AS `A1` FROM `Toys` AS `Extent1` WHERE `Extent1`.`MinAge` > 3) AS `GroupBy1` SELECT `Project1`.`Id`, `Project1`.`Name`, `Project1`.`DateBegan`, `Project1`.`NumEmployees`, `Project1`.`C1`, `Project1`.`Address`, `Project1`.`City`, `Project1`.`State`, `Project1`.`ZipCode` FROM (SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode`, 1 AS `C1` FROM `Companies` AS `Extent1`) AS `Project1` WHERE EXISTS(SELECT 1 AS `C1` FROM `Toys` AS `Extent2` WHERE (`Project1`.`Id` = `Extent2`.`SupplierId`) AND (`Extent2`.`MinAge` < 4)) SELECT 1 AS `C1`, `Extent1`.`Id`, `Extent1`.`Name`, `Join1`.`Id` AS `C2`, `Join1`.`Name` AS `C3`, `Join1`.`Id1` AS `C4`, `Join1`.`Name1` AS `C5` FROM `Companies` AS `Extent1` INNER JOIN (SELECT `UnionAll1`.`Id`, `UnionAll1`.`Name`, `UnionAll2`.`Id` AS `Id1`, `UnionAll2`.`Name` AS `Name1` FROM (SELECT `Extent2`.`Id`, `Extent2`.`Name` FROM `Toys` AS `Extent2` UNION ALL SELECT `Extent3`.`Id`, `Extent3`.`Name` FROM `Stores` AS `Extent3`) AS `UnionAll1` INNER JOIN (SELECT `Extent4`.`Id`, `Extent4`.`Name` FROM `Authors` AS `Extent4` UNION ALL SELECT `Extent5`.`Id`, `Extent5`.`Name` FROM `Books` AS `Extent5`) AS `UnionAll2` ON `UnionAll1`.`Id` = `UnionAll2`.`Id`) AS `Join1` ON `Extent1`.`Id` = `Join1`.`Id` SELECT `Extent1`.`Id`, `Extent1`.`EmployeeID`, `Extent1`.`LastName`, `Extent1`.`FirstName`, `Extent1`.`BirthTime`, `Extent1`.`Weight`, `Extent1`.`LastModified` FROM `EmployeeChildren` AS `Extent1` INNER JOIN (SELECT `Extent2`.`Id`, `Extent2`.`LastName`, `Extent2`.`FirstName`, `Extent2`.`Age`, `Extent3`.`EmployeeId`, `Extent3`.`Salary` FROM `Employees` AS `Extent2` LEFT OUTER JOIN `SalariedEmployees` AS `Extent3` ON `Extent2`.`Id` = `Extent3`.`EmployeeId`) AS `Join1` ON (`Extent1`.`EmployeeID` = `Join1`.`Id`) OR ((`Extent1`.`EmployeeID` IS NULL) AND (`Join1`.`Id` IS NULL)) WHERE `Extent1`.`Weight` > 7 SELECT 1 AS `C1`, `Extent1`.`Id`, `Extent1`.`Name`, `Join1`.`Id` AS `Id1`, `Join1`.`Name` AS `Name1`, `Join1`.`Id1` AS `Id2`, `Join1`.`Name1` AS `Name2` FROM `Companies` AS `Extent1` INNER JOIN (SELECT `Extent2`.`Id`, `Extent2`.`Name`, `Extent2`.`Age`, `Extent3`.`Id` AS `Id1`, `Extent3`.`Name` AS `Name1`, `Extent3`.`Pages`, `Extent3`.`Author_id`, `Extent3`.`Publisher_id` FROM `Authors` AS `Extent2` INNER JOIN `Books` AS `Extent3` ON `Extent2`.`Id` = `Extent3`.`Id`) AS `Join1` ON `Extent1`.`Id` = `Join1`.`Id` SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode` FROM `Stores` AS `Extent1` INNER JOIN (SELECT MAX(`Extent3`.`Id`) AS `A1` FROM `Orders` AS `Extent2` LEFT OUTER JOIN `Stores` AS `Extent3` ON `Extent2`.`StoreId` = `Extent3`.`Id`) AS `GroupBy1` ON `Extent1`.`Id` = `GroupBy1`.`A1` SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode` FROM `Stores` AS `Extent1` INNER JOIN (SELECT MAX(`Extent3`.`Id`) AS `A1` FROM `Orders` AS `Extent2` LEFT OUTER JOIN `Stores` AS `Extent3` ON `Extent2`.`StoreId` = `Extent3`.`Id`) AS `GroupBy1` ON `Extent1`.`Id` = `GroupBy1`.`A1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT MAX(`Extent1`.`MinAge`) AS `A1` FROM `Toys` AS `Extent1`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT `Extent2`.`Id` AS `K1`, MAX(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` LEFT OUTER JOIN `Stores` AS `Extent2` ON `Extent1`.`StoreId` = `Extent2`.`Id` GROUP BY `Extent2`.`Id`) AS `GroupBy1` SELECT 1 AS `C1`, `GroupBy1`.`A1` AS `C2` FROM (SELECT MAX(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` INNER JOIN `Stores` AS `Extent2` ON `Extent1`.`StoreId` = `Extent2`.`Id` WHERE `Extent2`.`Id` = 1) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT MIN(`Extent1`.`MinAge`) AS `A1` FROM `Toys` AS `Extent1`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT `Extent2`.`Id` AS `K1`, MIN(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` LEFT OUTER JOIN `Stores` AS `Extent2` ON `Extent1`.`StoreId` = `Extent2`.`Id` GROUP BY `Extent2`.`Id`) AS `GroupBy1` SELECT 1 AS `C1`, `GroupBy1`.`A1` AS `C2` FROM (SELECT MIN(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` INNER JOIN `Stores` AS `Extent2` ON `Extent1`.`StoreId` = `Extent2`.`Id` WHERE `Extent2`.`Id` = 2) AS `GroupBy1` SELECT `Project1`.`Id`, `Project1`.`Name`, `Project1`.`DateBegan`, `Project1`.`NumEmployees`, `Project1`.`C1`, `Project1`.`Address`, `Project1`.`City`, `Project1`.`State`, `Project1`.`ZipCode` FROM (SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode`, 1 AS `C1` FROM `Companies` AS `Extent1`) AS `Project1` ORDER BY `Project1`.`Name` ASC SELECT `Project1`.`Id`, `Project1`.`Name`, `Project1`.`DateBegan`, `Project1`.`NumEmployees`, `Project1`.`C1`, `Project1`.`Address`, `Project1`.`City`, `Project1`.`State`, `Project1`.`ZipCode` FROM (SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode`, 1 AS `C1` FROM `Companies` AS `Extent1` WHERE `Extent1`.`NumEmployees` > 100) AS `Project1` ORDER BY `Project1`.`Name` ASC SELECT 1 AS `C1`, `Extent1`.`LastName` FROM `Employees` AS `Extent1` LEFT OUTER JOIN `SalariedEmployees` AS `Extent2` ON `Extent1`.`Id` = `Extent2`.`EmployeeId` WHERE `Extent1`.`Age` > 20 SELECT 1 AS `C1`, `Extent1`.`Id`, `Extent1`.`Name`, `Extent2`.`Name` AS `Name1` FROM `Books` AS `Extent1` INNER JOIN `Authors` AS `Extent2` ON (`Extent1`.`Author_id` = `Extent2`.`Id`) OR ((`Extent1`.`Author_id` IS NULL) AND (`Extent2`.`Id` IS NULL)) SELECT 1 AS `C1`, `Extent1`.`Id`, `Extent1`.`Name`, `Extent2`.`Name` AS `Name1` FROM `Books` AS `Extent1` INNER JOIN `Authors` AS `Extent2` ON (`Extent1`.`Author_id` = `Extent2`.`Id`) OR ((`Extent1`.`Author_id` IS NULL) AND (`Extent2`.`Id` IS NULL)) WHERE `Extent1`.`Pages` > 300 SELECT 1 AS `C1`, `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`MinAge`, `Extent1`.`SupplierId` FROM `Toys` AS `Extent1` SELECT 1 AS `C1`, `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`MinAge`, `Extent1`.`SupplierId` FROM `Toys` AS `Extent1` WHERE `Extent1`.`MinAge` = 4 SELECT 1 AS `C1`, `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`MinAge`, `Extent1`.`SupplierId` FROM `Toys` AS `Extent1` WHERE `Extent1`.`MinAge` > @age SELECT `Project1`.`Id`, `Project1`.`Name`, `Project1`.`DateBegan`, `Project1`.`NumEmployees`, `Project1`.`C1`, `Project1`.`Address`, `Project1`.`City`, `Project1`.`State`, `Project1`.`ZipCode` FROM (SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode`, 1 AS `C1` FROM `Companies` AS `Extent1`) AS `Project1` ORDER BY `Project1`.`Id` ASC LIMIT 3,18446744073709551615 SELECT `Project1`.`Id`, `Project1`.`Name`, `Project1`.`DateBegan`, `Project1`.`NumEmployees`, `Project1`.`C1`, `Project1`.`Address`, `Project1`.`City`, `Project1`.`State`, `Project1`.`ZipCode` FROM (SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode`, 1 AS `C1` FROM `Companies` AS `Extent1`) AS `Project1` ORDER BY `Project1`.`Id` ASC LIMIT 2,2 SELECT `Project1`.`Id`, `Project1`.`Name`, `Project1`.`DateBegan`, `Project1`.`NumEmployees`, `Project1`.`C1`, `Project1`.`Address`, `Project1`.`City`, `Project1`.`State`, `Project1`.`ZipCode` FROM (SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode`, 1 AS `C1` FROM `Companies` AS `Extent1`) AS `Project1` ORDER BY `Project1`.`Name` DESC LIMIT 2,2 SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT SUM(`Extent1`.`MinAge`) AS `A1` FROM `Toys` AS `Extent1`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT `Extent2`.`Id` AS `K1`, SUM(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` LEFT OUTER JOIN `Stores` AS `Extent2` ON `Extent1`.`StoreId` = `Extent2`.`Id` GROUP BY `Extent2`.`Id`) AS `GroupBy1` SELECT `GroupBy1`.`A1` AS `C1` FROM (SELECT SUM(`Extent1`.`Freight`) AS `A1` FROM `Orders` AS `Extent1` INNER JOIN `Stores` AS `Extent2` ON `Extent1`.`StoreId` = `Extent2`.`Id` WHERE `Extent2`.`Id` = 2) AS `GroupBy1` SELECT `Limit1`.`Id`, `Limit1`.`Name`, `Limit1`.`DateBegan`, `Limit1`.`NumEmployees`, `Limit1`.`C1`, `Limit1`.`Address`, `Limit1`.`City`, `Limit1`.`State`, `Limit1`.`ZipCode` FROM (SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode`, 1 AS `C1` FROM `Companies` AS `Extent1` LIMIT 2) AS `Limit1` SELECT `UnionAll1`.`C1`, `UnionAll1`.`Id` AS `C2`, `UnionAll1`.`Name` AS `C3` FROM (SELECT 1 AS `C1`, `Extent1`.`Id`, `Extent1`.`Name` FROM `Toys` AS `Extent1` UNION ALL SELECT 1 AS `C1`, `Extent2`.`Id`, `Extent2`.`Name` FROM `Companies` AS `Extent2`) AS `UnionAll1` SELECT `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`DateBegan`, `Extent1`.`NumEmployees`, 1 AS `C1`, `Extent1`.`Address`, `Extent1`.`City`, `Extent1`.`State`, `Extent1`.`ZipCode` FROM `Companies` AS `Extent1` WHERE `Extent1`.`City` = @gp1 SELECT 1 AS `C1`, `Extent1`.`Id`, `Extent1`.`Name`, `Extent1`.`MinAge`, `Extent1`.`SupplierId` FROM `Toys` AS `Extent1` INNER JOIN `Companies` AS `Extent2` ON `Extent1`.`SupplierId` = `Extent2`.`Id` WHERE `Extent2`.`State` = @gp1 SELECT 1 AS `C1`, `Filter1`.`Id`, `Filter1`.`Name`, `Filter1`.`MinAge`, `Filter1`.`SupplierId` FROM (SELECT `Extent1`.`Id`, `Extent1`.`SupplierId`, `Extent1`.`Name`, `Extent1`.`MinAge`, `Extent2`.`Id` AS `Id1`, `Extent2`.`Name` AS `Name1`, `Extent2`.`DateBegan`, `Extent2`.`NumEmployees`, `Extent2`.`Address`, `Extent2`.`City`, `Extent2`.`State`, `Extent2`.`ZipCode` FROM `Toys` AS `Extent1` LEFT OUTER JOIN `Companies` AS `Extent2` ON `Extent1`.`SupplierId` = `Extent2`.`Id` WHERE `Extent2`.`State` != @gp1) AS `Filter1` LEFT OUTER JOIN `Companies` AS `Extent3` ON `Filter1`.`SupplierId` = `Extent3`.`Id` WHERE `Extent3`.`State` != @gp2 mysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Entity.Tests/Properties/SQLSyntax.Designer.cs0000644000175000017500000007261611127003600032514 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.5444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace MySql.Data.Entity.Tests.Properties { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SQLSyntax { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SQLSyntax() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MySql.Data.Entity.Tests.Properties.SQLSyntax", typeof(SQLSyntax).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// /// Looks up a localized string similar to SELECT ///Extent1.Id, ///Extent1.Name, ///Extent1.Age ///FROM Authors AS Extent1 /// WHERE NOT EXISTS(SELECT ///1 AS C1 ///FROM Books AS Extent2 /// WHERE Extent1.Id = Extent2.Author_id). /// internal static string Any { get { return ResourceManager.GetString("Any", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Avg(Extent1.MinAge) AS A1 ///FROM Toys AS Extent1) AS GroupBy1. /// internal static string AverageSimple { get { return ResourceManager.GetString("AverageSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Extent2.Id AS K1, ///AVG(Extent1.Freight) AS A1 ///FROM Orders AS Extent1 LEFT OUTER JOIN Stores AS Extent2 ON Extent1.StoreId = Extent2.Id /// GROUP BY ///Extent2.Id) AS GroupBy1. /// internal static string AverageWithGrouping { get { return ResourceManager.GetString("AverageWithGrouping", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Avg(Extent1.Freight) AS A1 ///FROM Orders AS Extent1 INNER JOIN Stores AS Extent2 ON Extent1.StoreId = Extent2.Id /// WHERE Extent2.Id = 3) AS GroupBy1. /// internal static string AverageWithPredicate { get { return ResourceManager.GetString("AverageWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Count(Extent1.Id) AS A1 ///FROM Toys AS Extent1) AS GroupBy1. /// internal static string BigCountSimple { get { return ResourceManager.GetString("BigCountSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///GroupBy1.K1 AS Name, ///GroupBy1.A1 AS C2 ///FROM (SELECT ///Extent1.Name AS K1, ///Extent1.DateBegan AS K2, ///Extent1.NumEmployees AS K3, ///COUNT(1) AS A1 ///FROM Companies AS Extent1 /// GROUP BY ///Extent1.Name, ///Extent1.DateBegan, ///Extent1.NumEmployees) AS GroupBy1. /// internal static string CanGroupByMultipleColumns { get { return ResourceManager.GetString("CanGroupByMultipleColumns", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///GroupBy1.K1 AS Name, ///GroupBy1.A1 AS C2 ///FROM (SELECT ///Extent1.Name AS K1, ///COUNT(1) AS A1 ///FROM Companies AS Extent1 /// GROUP BY ///Extent1.Name) AS GroupBy1. /// internal static string CanGroupBySingleColumn { get { return ResourceManager.GetString("CanGroupBySingleColumn", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Count(Extent1.Id) AS A1 ///FROM Toys AS Extent1) AS GroupBy1. /// internal static string CountSimple { get { return ResourceManager.GetString("CountSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Count(Extent1.Id) AS A1 ///FROM Toys AS Extent1 /// WHERE Extent1.MinAge > 3) AS GroupBy1. /// internal static string CountWithPredicate { get { return ResourceManager.GetString("CountWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///Project1.Id, ///Project1.Name, ///Project1.DateBegan, ///Project1.NumEmployees, ///Project1.C1, ///Project1.Address, ///Project1.City, ///Project1.State, ///Project1.ZipCode ///FROM (SELECT ///Extent1.Id, ///Extent1.Name, ///Extent1.DateBegan, ///Extent1.NumEmployees, ///Extent1.Address, ///Extent1.City, ///Extent1.State, ///Extent1.ZipCode, ///1 AS C1 ///FROM Companies AS Extent1) AS Project1 /// WHERE EXISTS(SELECT ///1 AS C1 ///FROM Toys AS Extent2 /// WHERE (Project1.Id = Extent2.SupplierId) AND (Extent2.MinAge < 4)). /// internal static string Exists { get { return ResourceManager.GetString("Exists", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///Extent1.Id, ///Extent1.Name, ///Join1.Id AS C2, ///Join1.Name AS C3, ///Join1.Id1 AS C4, ///Join1.Name1 AS C5 ///FROM Companies AS Extent1 INNER JOIN (SELECT ///UnionAll1.Id, ///UnionAll1.Name, ///UnionAll2.Id AS Id1, ///UnionAll2.Name AS Name1 ///FROM (SELECT ///Extent2.Id, ///Extent2.Name ///FROM Toys AS Extent2 UNION ALL SELECT ///Extent3.Id, ///Extent3.Name ///FROM Stores AS Extent3) AS UnionAll1 INNER JOIN (SELECT ///Extent4.Id, ///Extent4.Name ///FROM Authors AS Extent4 UNION ALL SELECT ///Extent5.Id, ///Extent5.N [rest of string was truncated]";. /// internal static string JoinOfUnionsOnRightSideOfJoin { get { return ResourceManager.GetString("JoinOfUnionsOnRightSideOfJoin", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///Extent1.Id, ///Extent1.EmployeeID, ///Extent1.LastName, ///Extent1.FirstName, ///Extent1.BirthTime, ///Extent1.Weight, ///Extent1.LastModified ///FROM EmployeeChildren AS Extent1 INNER JOIN (SELECT ///Extent2.Id, ///Extent2.LastName, ///Extent2.FirstName, ///Extent2.Age, ///Extent3.EmployeeId, ///Extent3.Salary ///FROM Employees AS Extent2 LEFT OUTER JOIN SalariedEmployees AS Extent3 ON Extent2.Id = Extent3.EmployeeId) AS Join1 ON (Extent1.EmployeeID = Join1.Id) OR ((Extent1.EmployeeID IS NULL) AND (Join1.Id IS NU [rest of string was truncated]";. /// internal static string JoinOnRightSideAsDerivedTable { get { return ResourceManager.GetString("JoinOnRightSideAsDerivedTable", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///Extent1.Id, ///Extent1.Name, ///Join1.Id AS Id1, ///Join1.Name AS Name1, ///Join1.Id1 AS Id2, ///Join1.Name1 AS Name2 ///FROM Companies AS Extent1 INNER JOIN (SELECT ///Extent2.Id, ///Extent2.Name, ///Extent2.Age, ///Extent3.Id AS Id1, ///Extent3.Name AS Name1, ///Extent3.Pages, ///Extent3.Author_id, ///Extent3.Publisher_id ///FROM Authors AS Extent2 INNER JOIN Books AS Extent3 ON Extent2.Id = Extent3.Id) AS Join1 ON Extent1.Id = Join1.Id. /// internal static string JoinOnRightSideNameClash { get { return ResourceManager.GetString("JoinOnRightSideNameClash", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///Extent1.Id, ///Extent1.Name, ///Extent1.Address, ///Extent1.City, ///Extent1.State, ///Extent1.ZipCode ///FROM Stores AS Extent1 INNER JOIN (SELECT ///MAX(Extent3.Id) AS A1 ///FROM Orders AS Extent2 LEFT OUTER JOIN Stores AS Extent3 ON Extent2.StoreId = Extent3.Id) AS GroupBy1 ON Extent1.Id = GroupBy1.A1. /// internal static string MaxInSubQuery1 { get { return ResourceManager.GetString("MaxInSubQuery1", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///Extent1.Id, ///Extent1.Name, ///Extent1.Address, ///Extent1.City, ///Extent1.State, ///Extent1.ZipCode ///FROM Stores AS Extent1 INNER JOIN (SELECT ///MAX(Extent3.Id) AS A1 ///FROM Orders AS Extent2 LEFT OUTER JOIN Stores AS Extent3 ON Extent2.StoreId = Extent3.Id) AS GroupBy1 ON Extent1.Id = GroupBy1.A1. /// internal static string MaxInSubQuery2 { get { return ResourceManager.GetString("MaxInSubQuery2", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Max(Extent1.MinAge) AS A1 ///FROM Toys AS Extent1) AS GroupBy1. /// internal static string MaxSimple { get { return ResourceManager.GetString("MaxSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Extent2.Id AS K1, ///MAX(Extent1.Freight) AS A1 ///FROM Orders AS Extent1 LEFT OUTER JOIN Stores AS Extent2 ON Extent1.StoreId = Extent2.Id /// GROUP BY ///Extent2.Id) AS GroupBy1. /// internal static string MaxWithGrouping { get { return ResourceManager.GetString("MaxWithGrouping", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///GroupBy1.A1 AS C2 ///FROM (SELECT ///Max(Extent1.Freight) AS A1 ///FROM Orders AS Extent1 INNER JOIN Stores AS Extent2 ON Extent1.StoreId = Extent2.Id /// WHERE Extent2.Id = 1) AS GroupBy1. /// internal static string MaxWithPredicate { get { return ResourceManager.GetString("MaxWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Min(Extent1.MinAge) AS A1 ///FROM Toys AS Extent1) AS GroupBy1. /// internal static string MinSimple { get { return ResourceManager.GetString("MinSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Extent2.Id AS K1, ///MIN(Extent1.Freight) AS A1 ///FROM Orders AS Extent1 LEFT OUTER JOIN Stores AS Extent2 ON Extent1.StoreId = Extent2.Id /// GROUP BY ///Extent2.Id) AS GroupBy1. /// internal static string MinWithGrouping { get { return ResourceManager.GetString("MinWithGrouping", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///GroupBy1.A1 AS C2 ///FROM (SELECT ///Min(Extent1.Freight) AS A1 ///FROM Orders AS Extent1 INNER JOIN Stores AS Extent2 ON Extent1.StoreId = Extent2.Id /// WHERE Extent2.Id = 2) AS GroupBy1. /// internal static string MinWithPredicate { get { return ResourceManager.GetString("MinWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///Project1.Id, ///Project1.Name, ///Project1.DateBegan, ///Project1.NumEmployees, ///Project1.C1, ///Project1.Address, ///Project1.City, ///Project1.State, ///Project1.ZipCode ///FROM (SELECT ///Extent1.Id, ///Extent1.Name, ///Extent1.DateBegan, ///Extent1.NumEmployees, ///Extent1.Address, ///Extent1.City, ///Extent1.State, ///Extent1.ZipCode, ///1 AS C1 ///FROM Companies AS Extent1) AS Project1 /// ORDER BY ///Project1.Name ASC. /// internal static string OrderBySimple { get { return ResourceManager.GetString("OrderBySimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///Project1.Id, ///Project1.Name, ///Project1.DateBegan, ///Project1.NumEmployees, ///Project1.C1, ///Project1.Address, ///Project1.City, ///Project1.State, ///Project1.ZipCode ///FROM (SELECT ///Extent1.Id, ///Extent1.Name, ///Extent1.DateBegan, ///Extent1.NumEmployees, ///Extent1.Address, ///Extent1.City, ///Extent1.State, ///Extent1.ZipCode, ///1 AS C1 ///FROM Companies AS Extent1 /// WHERE Extent1.NumEmployees > 100) AS Project1 /// ORDER BY ///Project1.Name ASC. /// internal static string OrderByWithPredicate { get { return ResourceManager.GetString("OrderByWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///Extent1.LastName ///FROM Employees AS Extent1 LEFT OUTER JOIN SalariedEmployees AS Extent2 ON Extent1.Id = Extent2.EmployeeId /// WHERE Extent1.Age > 20. /// internal static string SelectWithComplexType { get { return ResourceManager.GetString("SelectWithComplexType", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///Extent1.Id, ///Extent1.Name, ///Extent2.Name AS Name1 ///FROM Books AS Extent1 INNER JOIN Authors AS Extent2 ON (Extent1.Author_id = Extent2.Id) OR ((Extent1.Author_id IS NULL) AND (Extent2.Id IS NULL)). /// internal static string SimpleJoin { get { return ResourceManager.GetString("SimpleJoin", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///Extent1.Id, ///Extent1.Name, ///Extent2.Name AS Name1 ///FROM Books AS Extent1 INNER JOIN Authors AS Extent2 ON (Extent1.Author_id = Extent2.Id) OR ((Extent1.Author_id IS NULL) AND (Extent2.Id IS NULL)) /// WHERE Extent1.Pages > 300. /// internal static string SimpleJoinWithPredicate { get { return ResourceManager.GetString("SimpleJoinWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///Extent1.Id, ///Extent1.Name, ///Extent1.MinAge, ///Extent1.SupplierId ///FROM Toys AS Extent1. /// internal static string SimpleSelect { get { return ResourceManager.GetString("SimpleSelect", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///Extent1.Id, ///Extent1.Name, ///Extent1.MinAge, ///Extent1.SupplierId ///FROM Toys AS Extent1 /// WHERE Extent1.MinAge = 4. /// internal static string SimpleSelectWithFilter { get { return ResourceManager.GetString("SimpleSelectWithFilter", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///Extent1.Id, ///Extent1.Name, ///Extent1.MinAge, ///Extent1.SupplierId ///FROM Toys AS Extent1 /// WHERE Extent1.MinAge > @age. /// internal static string SimpleSelectWithParam { get { return ResourceManager.GetString("SimpleSelectWithParam", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///Project1.Id, ///Project1.Name, ///Project1.DateBegan, ///Project1.NumEmployees, ///Project1.C1, ///Project1.Address, ///Project1.City, ///Project1.State, ///Project1.ZipCode ///FROM (SELECT ///Extent1.Id, ///Extent1.Name, ///Extent1.DateBegan, ///Extent1.NumEmployees, ///Extent1.Address, ///Extent1.City, ///Extent1.State, ///Extent1.ZipCode, ///1 AS C1 ///FROM Companies AS Extent1) AS Project1 /// ORDER BY ///Project1.Id ASC LIMIT 3,18446744073709551615. /// internal static string Skip { get { return ResourceManager.GetString("Skip", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///Project1.Id, ///Project1.Name, ///Project1.DateBegan, ///Project1.NumEmployees, ///Project1.C1, ///Project1.Address, ///Project1.City, ///Project1.State, ///Project1.ZipCode ///FROM (SELECT ///Extent1.Id, ///Extent1.Name, ///Extent1.DateBegan, ///Extent1.NumEmployees, ///Extent1.Address, ///Extent1.City, ///Extent1.State, ///Extent1.ZipCode, ///1 AS C1 ///FROM Companies AS Extent1) AS Project1 /// ORDER BY ///Project1.Id ASC LIMIT 2,2. /// internal static string SkipAndTakeSimple { get { return ResourceManager.GetString("SkipAndTakeSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///Project1.Id, ///Project1.Name, ///Project1.DateBegan, ///Project1.NumEmployees, ///Project1.C1, ///Project1.Address, ///Project1.City, ///Project1.State, ///Project1.ZipCode ///FROM (SELECT ///Extent1.Id, ///Extent1.Name, ///Extent1.DateBegan, ///Extent1.NumEmployees, ///Extent1.Address, ///Extent1.City, ///Extent1.State, ///Extent1.ZipCode, ///1 AS C1 ///FROM Companies AS Extent1) AS Project1 /// ORDER BY ///Project1.Name DESC LIMIT 2,2. /// internal static string SkipAndTakeWithOrdering { get { return ResourceManager.GetString("SkipAndTakeWithOrdering", resourceCulture); } } /// /// Looks up a localized string similar to . /// internal static string String1 { get { return ResourceManager.GetString("String1", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Sum(Extent1.MinAge) AS A1 ///FROM Toys AS Extent1) AS GroupBy1. /// internal static string SumSimple { get { return ResourceManager.GetString("SumSimple", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Extent2.Id AS K1, ///SUM(Extent1.Freight) AS A1 ///FROM Orders AS Extent1 LEFT OUTER JOIN Stores AS Extent2 ON Extent1.StoreId = Extent2.Id /// GROUP BY ///Extent2.Id) AS GroupBy1. /// internal static string SumWithGrouping { get { return ResourceManager.GetString("SumWithGrouping", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///GroupBy1.A1 AS C1 ///FROM (SELECT ///Sum(Extent1.Freight) AS A1 ///FROM Orders AS Extent1 INNER JOIN Stores AS Extent2 ON Extent1.StoreId = Extent2.Id /// WHERE Extent2.Id = 2) AS GroupBy1. /// internal static string SumWithPredicate { get { return ResourceManager.GetString("SumWithPredicate", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///Limit1.Id, ///Limit1.Name, ///Limit1.DateBegan, ///Limit1.NumEmployees, ///Limit1.C1, ///Limit1.Address, ///Limit1.City, ///Limit1.State, ///Limit1.ZipCode ///FROM (SELECT ///Extent1.Id, ///Extent1.Name, ///Extent1.DateBegan, ///Extent1.NumEmployees, ///Extent1.Address, ///Extent1.City, ///Extent1.State, ///Extent1.ZipCode, ///1 AS C1 ///FROM Companies AS Extent1 LIMIT 2) AS Limit1. /// internal static string Top { get { return ResourceManager.GetString("Top", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///UnionAll1.C1, ///UnionAll1.Id AS C2, ///UnionAll1.Name AS C3 ///FROM (SELECT ///1 AS C1, ///Extent1.Id, ///Extent1.Name ///FROM Toys AS Extent1 UNION ALL SELECT ///1 AS C1, ///Extent2.Id, ///Extent2.Name ///FROM Companies AS Extent2) AS UnionAll1. /// internal static string UnionAll { get { return ResourceManager.GetString("UnionAll", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///Extent1.Id, ///Extent1.Name, ///Extent1.DateBegan, ///Extent1.NumEmployees, ///1 AS C1, ///Extent1.Address, ///Extent1.City, ///Extent1.State, ///Extent1.ZipCode ///FROM Companies AS Extent1 /// WHERE Extent1.City = @gp1. /// internal static string WhereLiteralOnRelation { get { return ResourceManager.GetString("WhereLiteralOnRelation", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///Extent1.Id, ///Extent1.Name, ///Extent1.MinAge, ///Extent1.SupplierId ///FROM Toys AS Extent1 INNER JOIN Companies AS Extent2 ON Extent1.SupplierId = Extent2.Id /// WHERE Extent2.State = @gp1. /// internal static string WhereWithRelatedEntities1 { get { return ResourceManager.GetString("WhereWithRelatedEntities1", resourceCulture); } } /// /// Looks up a localized string similar to SELECT ///1 AS C1, ///Filter1.Id, ///Filter1.Name, ///Filter1.MinAge, ///Filter1.SupplierId ///FROM (SELECT ///Extent1.Id, ///Extent1.SupplierId, ///Extent1.Name, ///Extent1.MinAge, ///Extent2.Id AS Id1, ///Extent2.Name AS Name1, ///Extent2.DateBegan, ///Extent2.NumEmployees, ///Extent2.Address, ///Extent2.City, ///Extent2.State, ///Extent2.ZipCode ///FROM Toys AS Extent1 LEFT OUTER JOIN Companies AS Extent2 ON Extent1.SupplierId = Extent2.Id /// WHERE Extent2.State != @gp1) AS Filter1 LEFT OUTER JOIN Companies AS Extent3 ON Filter [rest of string was truncated]";. /// internal static string WhereWithRelatedEntities2 { get { return ResourceManager.GetString("WhereWithRelatedEntities2", resourceCulture); } } } } mysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Entity.Tests/TestModel.Designer.cs0000644000175000017500000025732011127003600030407 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.5446 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ [assembly: global::System.Data.Objects.DataClasses.EdmSchemaAttribute()] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("testModel", "FK_Toys_Supplier", "Supplier", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(MySql.Data.Entity.Tests.Company), "Toys", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(MySql.Data.Entity.Tests.Toy))] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("testModel", "FK_Orders_Store", "Store", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(MySql.Data.Entity.Tests.Store), "Orders", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(MySql.Data.Entity.Tests.Order))] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("testModel", "FK_Books_Authors", "Authors", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(MySql.Data.Entity.Tests.Author), "Books", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(MySql.Data.Entity.Tests.Book))] [assembly: global::System.Data.Objects.DataClasses.EdmRelationshipAttribute("testModel", "FK_Books_Publishers", "Publishers", global::System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(MySql.Data.Entity.Tests.Publisher), "Books", global::System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(MySql.Data.Entity.Tests.Book))] // Original file name: // Generation date: 6/23/2011 7:23:19 AM namespace MySql.Data.Entity.Tests { /// /// There are no comments for testEntities in the schema. /// public partial class testEntities : global::System.Data.Objects.ObjectContext { /// /// Initializes a new testEntities object using the connection string found in the 'testEntities' section of the application configuration file. /// public testEntities() : base("name=testEntities", "testEntities") { this.OnContextCreated(); } /// /// Initialize a new testEntities object. /// public testEntities(string connectionString) : base(connectionString, "testEntities") { this.OnContextCreated(); } /// /// Initialize a new testEntities object. /// public testEntities(global::System.Data.EntityClient.EntityConnection connection) : base(connection, "testEntities") { this.OnContextCreated(); } partial void OnContextCreated(); /// /// There are no comments for Employees in the schema. /// public global::System.Data.Objects.ObjectQuery Employees { get { if ((this._Employees == null)) { this._Employees = base.CreateQuery("[Employees]"); } return this._Employees; } } private global::System.Data.Objects.ObjectQuery _Employees; /// /// There are no comments for Children in the schema. /// public global::System.Data.Objects.ObjectQuery Children { get { if ((this._Children == null)) { this._Children = base.CreateQuery("[Children]"); } return this._Children; } } private global::System.Data.Objects.ObjectQuery _Children; /// /// There are no comments for Companies in the schema. /// public global::System.Data.Objects.ObjectQuery Companies { get { if ((this._Companies == null)) { this._Companies = base.CreateQuery("[Companies]"); } return this._Companies; } } private global::System.Data.Objects.ObjectQuery _Companies; /// /// There are no comments for Toys in the schema. /// public global::System.Data.Objects.ObjectQuery Toys { get { if ((this._Toys == null)) { this._Toys = base.CreateQuery("[Toys]"); } return this._Toys; } } private global::System.Data.Objects.ObjectQuery _Toys; /// /// There are no comments for Stores in the schema. /// public global::System.Data.Objects.ObjectQuery Stores { get { if ((this._Stores == null)) { this._Stores = base.CreateQuery("[Stores]"); } return this._Stores; } } private global::System.Data.Objects.ObjectQuery _Stores; /// /// There are no comments for Orders in the schema. /// public global::System.Data.Objects.ObjectQuery Orders { get { if ((this._Orders == null)) { this._Orders = base.CreateQuery("[Orders]"); } return this._Orders; } } private global::System.Data.Objects.ObjectQuery _Orders; /// /// There are no comments for Books in the schema. /// public global::System.Data.Objects.ObjectQuery Books { get { if ((this._Books == null)) { this._Books = base.CreateQuery("[Books]"); } return this._Books; } } private global::System.Data.Objects.ObjectQuery _Books; /// /// There are no comments for Authors in the schema. /// public global::System.Data.Objects.ObjectQuery Authors { get { if ((this._Authors == null)) { this._Authors = base.CreateQuery("[Authors]"); } return this._Authors; } } private global::System.Data.Objects.ObjectQuery _Authors; /// /// There are no comments for Publishers in the schema. /// public global::System.Data.Objects.ObjectQuery Publishers { get { if ((this._Publishers == null)) { this._Publishers = base.CreateQuery("[Publishers]"); } return this._Publishers; } } private global::System.Data.Objects.ObjectQuery _Publishers; /// /// There are no comments for DataTypeTests in the schema. /// public global::System.Data.Objects.ObjectQuery DataTypeTests { get { if ((this._DataTypeTests == null)) { this._DataTypeTests = base.CreateQuery("[DataTypeTests]"); } return this._DataTypeTests; } } private global::System.Data.Objects.ObjectQuery _DataTypeTests; /// /// There are no comments for Computers in the schema. /// public global::System.Data.Objects.ObjectQuery Computers { get { if ((this._Computers == null)) { this._Computers = base.CreateQuery("[Computers]"); } return this._Computers; } } private global::System.Data.Objects.ObjectQuery _Computers; /// /// There are no comments for Products in the schema. /// public global::System.Data.Objects.ObjectQuery Products { get { if ((this._Products == null)) { this._Products = base.CreateQuery("[Products]"); } return this._Products; } } private global::System.Data.Objects.ObjectQuery _Products; /// /// There are no comments for Employees in the schema. /// public void AddToEmployees(Employee employee) { base.AddObject("Employees", employee); } /// /// There are no comments for Children in the schema. /// public void AddToChildren(Child child) { base.AddObject("Children", child); } /// /// There are no comments for Companies in the schema. /// public void AddToCompanies(Company company) { base.AddObject("Companies", company); } /// /// There are no comments for Toys in the schema. /// public void AddToToys(Toy toy) { base.AddObject("Toys", toy); } /// /// There are no comments for Stores in the schema. /// public void AddToStores(Store store) { base.AddObject("Stores", store); } /// /// There are no comments for Orders in the schema. /// public void AddToOrders(Order order) { base.AddObject("Orders", order); } /// /// There are no comments for Books in the schema. /// public void AddToBooks(Book book) { base.AddObject("Books", book); } /// /// There are no comments for Authors in the schema. /// public void AddToAuthors(Author author) { base.AddObject("Authors", author); } /// /// There are no comments for Publishers in the schema. /// public void AddToPublishers(Publisher publisher) { base.AddObject("Publishers", publisher); } /// /// There are no comments for DataTypeTests in the schema. /// public void AddToDataTypeTests(DataTypeTest dataTypeTest) { base.AddObject("DataTypeTests", dataTypeTest); } /// /// There are no comments for Computers in the schema. /// public void AddToComputers(Computer computer) { base.AddObject("Computers", computer); } /// /// There are no comments for Products in the schema. /// public void AddToProducts(Product product) { base.AddObject("Products", product); } } /// /// There are no comments for testModel.Employee in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="Employee")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::MySql.Data.Entity.Tests.SalariedEmployee))] public partial class Employee : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Employee object. /// /// Initial value of Id. /// Initial value of LastName. /// Initial value of FirstName. public static Employee CreateEmployee(int id, string lastName, string firstName) { Employee employee = new Employee(); employee.Id = id; employee.LastName = lastName; employee.FirstName = firstName; return employee; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property LastName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string LastName { get { return this._LastName; } set { this.OnLastNameChanging(value); this.ReportPropertyChanging("LastName"); this._LastName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("LastName"); this.OnLastNameChanged(); } } private string _LastName; partial void OnLastNameChanging(string value); partial void OnLastNameChanged(); /// /// There are no comments for Property FirstName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string FirstName { get { return this._FirstName; } set { this.OnFirstNameChanging(value); this.ReportPropertyChanging("FirstName"); this._FirstName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("FirstName"); this.OnFirstNameChanged(); } } private string _FirstName; partial void OnFirstNameChanging(string value); partial void OnFirstNameChanged(); /// /// There are no comments for Property Age in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable Age { get { return this._Age; } set { this.OnAgeChanging(value); this.ReportPropertyChanging("Age"); this._Age = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Age"); this.OnAgeChanged(); } } private global::System.Nullable _Age; partial void OnAgeChanging(global::System.Nullable value); partial void OnAgeChanged(); } /// /// There are no comments for testModel.SalariedEmployee in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="SalariedEmployee")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class SalariedEmployee : Employee { /// /// Create a new SalariedEmployee object. /// /// Initial value of Id. /// Initial value of LastName. /// Initial value of FirstName. /// Initial value of Salary. public static SalariedEmployee CreateSalariedEmployee(int id, string lastName, string firstName, int salary) { SalariedEmployee salariedEmployee = new SalariedEmployee(); salariedEmployee.Id = id; salariedEmployee.LastName = lastName; salariedEmployee.FirstName = firstName; salariedEmployee.Salary = salary; return salariedEmployee; } /// /// There are no comments for Property Salary in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Salary { get { return this._Salary; } set { this.OnSalaryChanging(value); this.ReportPropertyChanging("Salary"); this._Salary = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Salary"); this.OnSalaryChanged(); } } private int _Salary; partial void OnSalaryChanging(int value); partial void OnSalaryChanged(); } /// /// There are no comments for testModel.Child in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="Child")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Child : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Child object. /// /// Initial value of Id. /// Initial value of EmployeeID. /// Initial value of LastName. /// Initial value of FirstName. /// Initial value of Modified. public static Child CreateChild(long id, int employeeID, string lastName, string firstName, global::System.DateTime modified) { Child child = new Child(); child.Id = id; child.EmployeeID = employeeID; child.LastName = lastName; child.FirstName = firstName; child.Modified = modified; return child; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public long Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private long _Id; partial void OnIdChanging(long value); partial void OnIdChanged(); /// /// There are no comments for Property EmployeeID in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int EmployeeID { get { return this._EmployeeID; } set { this.OnEmployeeIDChanging(value); this.ReportPropertyChanging("EmployeeID"); this._EmployeeID = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("EmployeeID"); this.OnEmployeeIDChanged(); } } private int _EmployeeID; partial void OnEmployeeIDChanging(int value); partial void OnEmployeeIDChanged(); /// /// There are no comments for Property LastName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string LastName { get { return this._LastName; } set { this.OnLastNameChanging(value); this.ReportPropertyChanging("LastName"); this._LastName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("LastName"); this.OnLastNameChanged(); } } private string _LastName; partial void OnLastNameChanging(string value); partial void OnLastNameChanged(); /// /// There are no comments for Property FirstName in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string FirstName { get { return this._FirstName; } set { this.OnFirstNameChanging(value); this.ReportPropertyChanging("FirstName"); this._FirstName = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("FirstName"); this.OnFirstNameChanged(); } } private string _FirstName; partial void OnFirstNameChanging(string value); partial void OnFirstNameChanged(); /// /// There are no comments for Property BirthTime in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable BirthTime { get { return this._BirthTime; } set { this.OnBirthTimeChanging(value); this.ReportPropertyChanging("BirthTime"); this._BirthTime = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("BirthTime"); this.OnBirthTimeChanged(); } } private global::System.Nullable _BirthTime; partial void OnBirthTimeChanging(global::System.Nullable value); partial void OnBirthTimeChanged(); /// /// There are no comments for Property BirthWeight in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable BirthWeight { get { return this._BirthWeight; } set { this.OnBirthWeightChanging(value); this.ReportPropertyChanging("BirthWeight"); this._BirthWeight = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("BirthWeight"); this.OnBirthWeightChanged(); } } private global::System.Nullable _BirthWeight; partial void OnBirthWeightChanging(global::System.Nullable value); partial void OnBirthWeightChanged(); /// /// There are no comments for Property Modified in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.DateTime Modified { get { return this._Modified; } set { this.OnModifiedChanging(value); this.ReportPropertyChanging("Modified"); this._Modified = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Modified"); this.OnModifiedChanged(); } } private global::System.DateTime _Modified; partial void OnModifiedChanging(global::System.DateTime value); partial void OnModifiedChanged(); } /// /// There are no comments for testModel.Company in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="Company")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Company : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Company object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of Address. public static Company CreateCompany(int id, string name, CommonAddress address) { Company company = new Company(); company.Id = id; company.Name = name; company.Address = global::System.Data.Objects.DataClasses.StructuralObject.VerifyComplexObjectIsNotNull(address, "Address"); return company; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for Property DateBegan in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable DateBegan { get { return this._DateBegan; } set { this.OnDateBeganChanging(value); this.ReportPropertyChanging("DateBegan"); this._DateBegan = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("DateBegan"); this.OnDateBeganChanged(); } } private global::System.Nullable _DateBegan; partial void OnDateBeganChanging(global::System.Nullable value); partial void OnDateBeganChanged(); /// /// There are no comments for Property NumEmployees in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable NumEmployees { get { return this._NumEmployees; } set { this.OnNumEmployeesChanging(value); this.ReportPropertyChanging("NumEmployees"); this._NumEmployees = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("NumEmployees"); this.OnNumEmployeesChanged(); } } private global::System.Nullable _NumEmployees; partial void OnNumEmployeesChanging(global::System.Nullable value); partial void OnNumEmployeesChanged(); /// /// There are no comments for Property Address in the schema. /// [global::System.Data.Objects.DataClasses.EdmComplexPropertyAttribute()] [global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)] [global::System.Xml.Serialization.XmlElement(IsNullable=true)] [global::System.Xml.Serialization.SoapElement(IsNullable=true)] [global::System.Runtime.Serialization.DataMemberAttribute()] public CommonAddress Address { get { this._Address = this.GetValidValue(this._Address, "Address", false, this._AddressInitialized); this._AddressInitialized = true; return this._Address; } set { this.OnAddressChanging(value); this.ReportPropertyChanging("Address"); this._Address = this.SetValidValue(this._Address, value, "Address"); this._AddressInitialized = true; this.ReportPropertyChanged("Address"); this.OnAddressChanged(); } } private CommonAddress _Address; private bool _AddressInitialized; partial void OnAddressChanging(CommonAddress value); partial void OnAddressChanged(); /// /// There are no comments for Toys in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Toys_Supplier", "Toys")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection Toys { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("testModel.FK_Toys_Supplier", "Toys"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("testModel.FK_Toys_Supplier", "Toys", value); } } } } /// /// There are no comments for testModel.Toy in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="Toy")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Toy : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Toy object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of MinAge. public static Toy CreateToy(int id, string name, int minAge) { Toy toy = new Toy(); toy.Id = id; toy.Name = name; toy.MinAge = minAge; return toy; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for Property MinAge in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int MinAge { get { return this._MinAge; } set { this.OnMinAgeChanging(value); this.ReportPropertyChanging("MinAge"); this._MinAge = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("MinAge"); this.OnMinAgeChanged(); } } private int _MinAge; partial void OnMinAgeChanging(int value); partial void OnMinAgeChanged(); /// /// There are no comments for Supplier in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Toys_Supplier", "Supplier")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public Company Supplier { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("testModel.FK_Toys_Supplier", "Supplier").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("testModel.FK_Toys_Supplier", "Supplier").Value = value; } } /// /// There are no comments for Supplier in the schema. /// [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference SupplierReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("testModel.FK_Toys_Supplier", "Supplier"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("testModel.FK_Toys_Supplier", "Supplier", value); } } } } /// /// There are no comments for ComplexType testModel.CommonAddress in the schema. /// [global::System.Data.Objects.DataClasses.EdmComplexTypeAttribute(NamespaceName="testModel", Name="CommonAddress")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class CommonAddress : global::System.Data.Objects.DataClasses.ComplexObject { /// /// There are no comments for Property Address in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Address { get { return this._Address; } set { this.OnAddressChanging(value); this.ReportPropertyChanging("Address"); this._Address = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("Address"); this.OnAddressChanged(); } } private string _Address; partial void OnAddressChanging(string value); partial void OnAddressChanged(); /// /// There are no comments for Property City in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string City { get { return this._City; } set { this.OnCityChanging(value); this.ReportPropertyChanging("City"); this._City = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("City"); this.OnCityChanged(); } } private string _City; partial void OnCityChanging(string value); partial void OnCityChanged(); /// /// There are no comments for Property State in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string State { get { return this._State; } set { this.OnStateChanging(value); this.ReportPropertyChanging("State"); this._State = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("State"); this.OnStateChanged(); } } private string _State; partial void OnStateChanging(string value); partial void OnStateChanged(); /// /// There are no comments for Property ZipCode in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string ZipCode { get { return this._ZipCode; } set { this.OnZipCodeChanging(value); this.ReportPropertyChanging("ZipCode"); this._ZipCode = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("ZipCode"); this.OnZipCodeChanged(); } } private string _ZipCode; partial void OnZipCodeChanging(string value); partial void OnZipCodeChanged(); } /// /// There are no comments for testModel.Store in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="Store")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Store : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Store object. /// /// Initial value of Id. /// Initial value of Name. public static Store CreateStore(int id, string name) { Store store = new Store(); store.Id = id; store.Name = name; return store; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for Property Address in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Address { get { return this._Address; } set { this.OnAddressChanging(value); this.ReportPropertyChanging("Address"); this._Address = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("Address"); this.OnAddressChanged(); } } private string _Address; partial void OnAddressChanging(string value); partial void OnAddressChanged(); /// /// There are no comments for Property City in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string City { get { return this._City; } set { this.OnCityChanging(value); this.ReportPropertyChanging("City"); this._City = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("City"); this.OnCityChanged(); } } private string _City; partial void OnCityChanging(string value); partial void OnCityChanged(); /// /// There are no comments for Property State in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string State { get { return this._State; } set { this.OnStateChanging(value); this.ReportPropertyChanging("State"); this._State = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("State"); this.OnStateChanged(); } } private string _State; partial void OnStateChanging(string value); partial void OnStateChanged(); /// /// There are no comments for Property ZipCode in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string ZipCode { get { return this._ZipCode; } set { this.OnZipCodeChanging(value); this.ReportPropertyChanging("ZipCode"); this._ZipCode = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("ZipCode"); this.OnZipCodeChanged(); } } private string _ZipCode; partial void OnZipCodeChanging(string value); partial void OnZipCodeChanged(); } /// /// There are no comments for testModel.Order in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="Order")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Order : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Order object. /// /// Initial value of Id. /// Initial value of Freight. public static Order CreateOrder(int id, double freight) { Order order = new Order(); order.Id = id; order.Freight = freight; return order; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property Freight in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public double Freight { get { return this._Freight; } set { this.OnFreightChanging(value); this.ReportPropertyChanging("Freight"); this._Freight = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Freight"); this.OnFreightChanged(); } } private double _Freight; partial void OnFreightChanging(double value); partial void OnFreightChanged(); /// /// There are no comments for Store in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Orders_Store", "Store")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public Store Store { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("testModel.FK_Orders_Store", "Store").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("testModel.FK_Orders_Store", "Store").Value = value; } } /// /// There are no comments for Store in the schema. /// [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference StoreReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("testModel.FK_Orders_Store", "Store"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("testModel.FK_Orders_Store", "Store", value); } } } } /// /// There are no comments for testModel.Book in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="Book")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Book : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Book object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of Pages. public static Book CreateBook(int id, string name, int pages) { Book book = new Book(); book.Id = id; book.Name = name; book.Pages = pages; return book; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for Property Pages in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Pages { get { return this._Pages; } set { this.OnPagesChanging(value); this.ReportPropertyChanging("Pages"); this._Pages = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Pages"); this.OnPagesChanged(); } } private int _Pages; partial void OnPagesChanging(int value); partial void OnPagesChanged(); /// /// There are no comments for Author in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Books_Authors", "Authors")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public Author Author { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("testModel.FK_Books_Authors", "Authors").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("testModel.FK_Books_Authors", "Authors").Value = value; } } /// /// There are no comments for Author in the schema. /// [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference AuthorReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("testModel.FK_Books_Authors", "Authors"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("testModel.FK_Books_Authors", "Authors", value); } } } /// /// There are no comments for Publisher in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Books_Publishers", "Publishers")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public Publisher Publisher { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("testModel.FK_Books_Publishers", "Publishers").Value; } set { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("testModel.FK_Books_Publishers", "Publishers").Value = value; } } /// /// There are no comments for Publisher in the schema. /// [global::System.ComponentModel.BrowsableAttribute(false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityReference PublisherReference { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedReference("testModel.FK_Books_Publishers", "Publishers"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedReference("testModel.FK_Books_Publishers", "Publishers", value); } } } } /// /// There are no comments for testModel.Author in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="Author")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Author : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Author object. /// /// Initial value of Id. /// Initial value of Name. public static Author CreateAuthor(int id, string name) { Author author = new Author(); author.Id = id; author.Name = name; return author; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for Property Age in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable Age { get { return this._Age; } set { this.OnAgeChanging(value); this.ReportPropertyChanging("Age"); this._Age = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Age"); this.OnAgeChanged(); } } private global::System.Nullable _Age; partial void OnAgeChanging(global::System.Nullable value); partial void OnAgeChanged(); /// /// There are no comments for Books in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Books_Authors", "Books")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection Books { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("testModel.FK_Books_Authors", "Books"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("testModel.FK_Books_Authors", "Books", value); } } } } /// /// There are no comments for testModel.Publisher in the schema. /// /// /// id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="Publisher")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Publisher : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Publisher object. /// /// Initial value of id. /// Initial value of name. public static Publisher CreatePublisher(int id, string name) { Publisher publisher = new Publisher(); publisher.id = id; publisher.name = name; return publisher; } /// /// There are no comments for Property id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int id { get { return this._id; } set { this.OnidChanging(value); this.ReportPropertyChanging("id"); this._id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("id"); this.OnidChanged(); } } private int _id; partial void OnidChanging(int value); partial void OnidChanged(); /// /// There are no comments for Property name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string name { get { return this._name; } set { this.OnnameChanging(value); this.ReportPropertyChanging("name"); this._name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("name"); this.OnnameChanged(); } } private string _name; partial void OnnameChanging(string value); partial void OnnameChanged(); /// /// There are no comments for Books in the schema. /// [global::System.Data.Objects.DataClasses.EdmRelationshipNavigationPropertyAttribute("testModel", "FK_Books_Publishers", "Books")] [global::System.Xml.Serialization.XmlIgnoreAttribute()] [global::System.Xml.Serialization.SoapIgnoreAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Data.Objects.DataClasses.EntityCollection Books { get { return ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.GetRelatedCollection("testModel.FK_Books_Publishers", "Books"); } set { if ((value != null)) { ((global::System.Data.Objects.DataClasses.IEntityWithRelationships)(this)).RelationshipManager.InitializeRelatedCollection("testModel.FK_Books_Publishers", "Books", value); } } } } /// /// There are no comments for testModel.DataTypeTest in the schema. /// /// /// id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="DataTypeTest")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class DataTypeTest : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new DataTypeTest object. /// /// Initial value of id. /// Initial value of id2. public static DataTypeTest CreateDataTypeTest(global::System.Guid id, global::System.Guid id2) { DataTypeTest dataTypeTest = new DataTypeTest(); dataTypeTest.id = id; dataTypeTest.id2 = id2; return dataTypeTest; } /// /// There are no comments for Property id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Guid id { get { return this._id; } set { this.OnidChanging(value); this.ReportPropertyChanging("id"); this._id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("id"); this.OnidChanged(); } } private global::System.Guid _id; partial void OnidChanging(global::System.Guid value); partial void OnidChanged(); /// /// There are no comments for Property id2 in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Guid id2 { get { return this._id2; } set { this.Onid2Changing(value); this.ReportPropertyChanging("id2"); this._id2 = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("id2"); this.Onid2Changed(); } } private global::System.Guid _id2; partial void Onid2Changing(global::System.Guid value); partial void Onid2Changed(); /// /// There are no comments for Property idAsChar in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string idAsChar { get { return this._idAsChar; } set { this.OnidAsCharChanging(value); this.ReportPropertyChanging("idAsChar"); this._idAsChar = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("idAsChar"); this.OnidAsCharChanged(); } } private string _idAsChar; partial void OnidAsCharChanging(string value); partial void OnidAsCharChanged(); } /// /// There are no comments for testModel.Computer in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="Computer")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::MySql.Data.Entity.Tests.DesktopComputer))] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::MySql.Data.Entity.Tests.LaptopComputer))] [global::System.Runtime.Serialization.KnownTypeAttribute(typeof(global::MySql.Data.Entity.Tests.TabletComputer))] public abstract partial class Computer : global::System.Data.Objects.DataClasses.EntityObject { /// /// There are no comments for Property Brand in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Brand { get { return this._Brand; } set { this.OnBrandChanging(value); this.ReportPropertyChanging("Brand"); this._Brand = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Brand"); this.OnBrandChanged(); } } private string _Brand; partial void OnBrandChanging(string value); partial void OnBrandChanged(); /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); } /// /// There are no comments for testModel.DesktopComputer in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="DesktopComputer")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class DesktopComputer : Computer { /// /// Create a new DesktopComputer object. /// /// Initial value of Brand. /// Initial value of Id. public static DesktopComputer CreateDesktopComputer(string brand, int id) { DesktopComputer desktopComputer = new DesktopComputer(); desktopComputer.Brand = brand; desktopComputer.Id = id; return desktopComputer; } /// /// There are no comments for Property Color in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Color { get { return this._Color; } set { this.OnColorChanging(value); this.ReportPropertyChanging("Color"); this._Color = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("Color"); this.OnColorChanged(); } } private string _Color; partial void OnColorChanging(string value); partial void OnColorChanged(); } /// /// There are no comments for testModel.LaptopComputer in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="LaptopComputer")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class LaptopComputer : Computer { /// /// Create a new LaptopComputer object. /// /// Initial value of Brand. /// Initial value of Id. public static LaptopComputer CreateLaptopComputer(string brand, int id) { LaptopComputer laptopComputer = new LaptopComputer(); laptopComputer.Brand = brand; laptopComputer.Id = id; return laptopComputer; } /// /// There are no comments for Property IsCertified in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable IsCertified { get { return this._IsCertified; } set { this.OnIsCertifiedChanging(value); this.ReportPropertyChanging("IsCertified"); this._IsCertified = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("IsCertified"); this.OnIsCertifiedChanged(); } } private global::System.Nullable _IsCertified; partial void OnIsCertifiedChanging(global::System.Nullable value); partial void OnIsCertifiedChanged(); /// /// There are no comments for Property Size in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Size { get { return this._Size; } set { this.OnSizeChanging(value); this.ReportPropertyChanging("Size"); this._Size = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, true); this.ReportPropertyChanged("Size"); this.OnSizeChanged(); } } private string _Size; partial void OnSizeChanging(string value); partial void OnSizeChanged(); } /// /// There are no comments for testModel.TabletComputer in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="TabletComputer")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class TabletComputer : Computer { /// /// Create a new TabletComputer object. /// /// Initial value of Brand. /// Initial value of Id. public static TabletComputer CreateTabletComputer(string brand, int id) { TabletComputer tabletComputer = new TabletComputer(); tabletComputer.Brand = brand; tabletComputer.Id = id; return tabletComputer; } /// /// There are no comments for Property IsAvailable in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable IsAvailable { get { return this._IsAvailable; } set { this.OnIsAvailableChanging(value); this.ReportPropertyChanging("IsAvailable"); this._IsAvailable = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("IsAvailable"); this.OnIsAvailableChanged(); } } private global::System.Nullable _IsAvailable; partial void OnIsAvailableChanging(global::System.Nullable value); partial void OnIsAvailableChanged(); /// /// There are no comments for Property ReleaseDate in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute()] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.Nullable ReleaseDate { get { return this._ReleaseDate; } set { this.OnReleaseDateChanging(value); this.ReportPropertyChanging("ReleaseDate"); this._ReleaseDate = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("ReleaseDate"); this.OnReleaseDateChanged(); } } private global::System.Nullable _ReleaseDate; partial void OnReleaseDateChanging(global::System.Nullable value); partial void OnReleaseDateChanged(); } /// /// There are no comments for testModel.Product in the schema. /// /// /// Id /// [global::System.Data.Objects.DataClasses.EdmEntityTypeAttribute(NamespaceName="testModel", Name="Product")] [global::System.Runtime.Serialization.DataContractAttribute(IsReference=true)] [global::System.Serializable()] public partial class Product : global::System.Data.Objects.DataClasses.EntityObject { /// /// Create a new Product object. /// /// Initial value of Id. /// Initial value of Name. /// Initial value of CreatedDate. public static Product CreateProduct(int id, string name, global::System.DateTime createdDate) { Product product = new Product(); product.Id = id; product.Name = name; product.CreatedDate = createdDate; return product; } /// /// There are no comments for Property Id in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this._Id; } set { this.OnIdChanging(value); this.ReportPropertyChanging("Id"); this._Id = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("Id"); this.OnIdChanged(); } } private int _Id; partial void OnIdChanging(int value); partial void OnIdChanged(); /// /// There are no comments for Property Name in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this._Name; } set { this.OnNameChanging(value); this.ReportPropertyChanging("Name"); this._Name = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value, false); this.ReportPropertyChanged("Name"); this.OnNameChanged(); } } private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// /// There are no comments for Property CreatedDate in the schema. /// [global::System.Data.Objects.DataClasses.EdmScalarPropertyAttribute(IsNullable=false)] [global::System.Runtime.Serialization.DataMemberAttribute()] public global::System.DateTime CreatedDate { get { return this._CreatedDate; } set { this.OnCreatedDateChanging(value); this.ReportPropertyChanging("CreatedDate"); this._CreatedDate = global::System.Data.Objects.DataClasses.StructuralObject.SetValidValue(value); this.ReportPropertyChanged("CreatedDate"); this.OnCreatedDateChanged(); } } private global::System.DateTime _CreatedDate; partial void OnCreatedDateChanging(global::System.DateTime value); partial void OnCreatedDateChanged(); } } mysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Tests/0000755000175000017500000000000011127003600023135 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.Tests/MySql.Data.Tests.csproj0000644000175000017500000001612511127003600027402 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4} Library Properties MySql.Data.MySqlClient.Tests MySql.Data.Tests 3.5 v2.0 false publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false true true full false bin\Debug\ TRACE;DEBUG;NUNIT prompt 4 false AllRules.ruleset pdbonly true bin\Release\ TRACE prompt 4 AllRules.ruleset Properties\VersionInfo.cs Properties\AssemblyInfo.cs PreserveNewest Properties\Setup.sql {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} MySql.Data mysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.CF.Tests/0000755000175000017500000000000011127003600023424 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Tests/MySql.Data.CF.Tests/MySql.Data.CF.Tests.csproj0000644000175000017500000001513111127003600030154 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {710D9251-17A3-4429-9A91-63F03267F310} Library Properties MySql.Data.CF.Tests MySql.Data.CF.Tests {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} WindowsCE E2BECB1F-8C8C-41ba-B736-9BE7D946A398 5.00 MySql.Data.Tests.CF v2.0 3.5 Windows CE true full false bin\Debug\ TRACE;DEBUG;CF true true prompt 512 4 Off pdbonly true bin\Release\ TRACE;CF true true prompt 512 4 Off False C:\Program Files (x86)\NUnit 2.5.10\bin\net-2.0\framework\nunit.framework.dll Properties\AssemblyInfo.cs Properties\Setup.sql {587A47FB-C1CC-459D-93B6-179D95E41EFB} MySql.Data.CF mysql-connector-net-6.4.3/VS2008/Source/0000755000175000017500000000000011127003600020255 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Source/MySql.Web/0000755000175000017500000000000011127003600022036 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Source/MySql.Web/MySql.Web.csproj0000644000175000017500000001352311127003600025045 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {C28B1166-1380-445D-AEC1-8A18B990DD18} Library Properties MySql.Web MySql.Web false 3.5 v2.0 false publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false true true full false bin\Debug\ DEBUG;TRACE prompt 4 1699 AllRules.ruleset pdbonly true bin\Release\ TRACE prompt 4 1699 bin\release\webdocs.xml AllRules.ruleset Properties\VersionInfo.cs Properties\AssemblyInfo.cs Resources.resx True True Properties\Resources.Designer.cs Component Designer PublicResXFileCodeGenerator Resources.Designer.cs Properties\Resources.resx Properties\schema6.sql Properties\schema1.sql Properties\schema4.sql Properties\schema2.sql Properties\schema3.sql Properties\schema5.sql {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} MySql.Data mysql-connector-net-6.4.3/VS2008/Source/MySql.Data/0000755000175000017500000000000011127003600022172 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Source/MySql.Data/MySql.Data.csproj0000644000175000017500000003523111127003600025335 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} Library Properties MySql.Data.MySqlClient MySql.Data 512 v2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false bin\Debug\ DEBUG;TRACE prompt 4 AllRules.ruleset pdbonly true bin\Release\ TRACE prompt 4 AllRules.ruleset Properties\AssemblyInfo.cs common\ContextString.cs common\NamedPipeStream.cs common\NativeMethods.cs common\Platform.cs common\SHA1.cs common\SharedMemoryStream.cs common\StreamCreator.cs common\Version.cs Component Component Types\MetaData.cs Types\MySqlBinary.cs Types\MySqlBit.cs Types\MySqlByte.cs Types\MySqlConversionException.cs Types\MySqlDateTime.cs Types\MySqlDecimal.cs Types\MySqlDouble.cs Types\MySqlInt16.cs Types\MySqlInt32.cs Types\MySqlInt64.cs Types\MySqlSingle.cs Types\MySqlString.cs Types\MySqlTime.cs Types\MySqlUByte.cs Types\MySqlUInt16.cs Types\MySqlUInt32.cs Types\MySqlUInt64.cs Types\MySqlValue.cs zlib\Adler32.cs zlib\Deflate.cs zlib\InfBlocks.cs zlib\InfCodes.cs zlib\Inflate.cs zlib\InfTree.cs zlib\StaticTree.cs zlib\SupportClass.cs zlib\Tree.cs zlib\ZInputStream.cs zlib\Zlib.cs zlib\ZOutputStream.cs zlib\ZStream.cs zlib\ZStreamException.cs Properties\VersionInfo.cs common\Cache.cs common\MySqlTokenizer.cs common\MyNetworkStream.cs Types\MySqlGuid.cs Properties\ReservedWords.txt Designer PublicResXFileCodeGenerator Resources.Designer.cs Properties\Resources.resx CHANGES Properties\keywords.txt docs\MySqlCommand.xml docs\MySqlCommandBuilder.xml docs\MySqlConnection.xml docs\MySqlConnectionStringBuilder.xml docs\MySqlDataAdapter.xml docs\MySqlDataReader.xml docs\MySqlException.xml docs\MySqlHelper.xml docs\MySqlParameter.xml docs\MySqlParameterCollection.xml docs\MySqlTransaction.xml True True Resources.resx Properties\Resources.Designer.cs common\LowResolutionStopwatch.cs common\QueryNormalizer.cs SSPI.cs TableCache.cs mysql-connector-net-6.4.3/VS2008/Source/MySql.VisualStudio/0000755000175000017500000000000011127003600023754 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Source/MySql.VisualStudio/MySql.VisualStudio.csproj0000644000175000017500000007500311127003600030702 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 Library Properties MySql.Data.VisualStudio MySql.VisualStudio false {DC3517FF-AC26-4755-9B7A-EF658FF69593} 3.5 v2.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false bin\Debug\ DEBUG;TRACE prompt 4 false AllRules.ruleset pdbonly true bin\Release\ TRACE prompt 4 AllRules.ruleset True c:\Program Files\Visual Studio 2005 SDK\2007.02\VisualStudioIntegration\Common\Assemblies\Microsoft.Data.ConnectionUI.dll True True c:\Program Files\Visual Studio 2005 SDK\2007.02\VisualStudioIntegration\Common\Assemblies\Microsoft.VisualStudio.Data.dll True c:\Program Files\Visual Studio 2005 SDK\2007.02\VisualStudioIntegration\Common\Assemblies\Microsoft.VisualStudio.OLE.Interop.dll True c:\Program Files\Visual Studio 2005 SDK\2007.02\VisualStudioIntegration\Common\Assemblies\Microsoft.VisualStudio.Package.LanguageService.dll True c:\Program Files\Visual Studio 2005 SDK\2007.02\VisualStudioIntegration\Common\Assemblies\Microsoft.VisualStudio.Shell.dll True c:\Program Files\Visual Studio 2005 SDK\2007.02\VisualStudioIntegration\Common\Assemblies\Microsoft.VisualStudio.Shell.Interop.dll True c:\Program Files\Visual Studio 2005 SDK\2007.02\VisualStudioIntegration\Common\Assemblies\Microsoft.VisualStudio.Shell.Interop.8.0.dll True c:\Program Files\Visual Studio 2005 SDK\2007.02\VisualStudioIntegration\Common\Assemblies\Microsoft.VisualStudio.TextManager.Interop.dll True c:\Program Files\Visual Studio 2005 SDK\2007.02\VisualStudioIntegration\Common\Assemblies\Microsoft.VisualStudio.TextManager.Interop.8.0.dll LanguageService\MySqlTokenizer.cs Properties\VersionInfo.cs UserControl Editors\BaseEditorControl.cs DbObjects\CollationTypeConverter.cs DbObjects\CharacterSetTypeConverter.cs DbObjects\DataRowHelpers.cs DbObjects\DataTypeConverter.cs DbObjects\ForeignKey.cs DbObjects\Index.cs DbObjects\IndexColumnTypeConverter.cs DbObjects\Metadata.cs DbObjects\NumericTypeConverter.cs DbObjects\ObjectComparer.cs DbObjects\TableEngineTypeConverters.cs DbObjects\Enums.cs DbObjects\Table.cs DbObjects\TablePartCollection.cs DDEX\MySqlConnectionProperties.cs DDEX\MySqlConnectionSupport.cs UserControl DDEX\MySqlConnectionUIControl.cs MySqlConnectionUIControl.cs DDEX\MySqlConnectionUIControl.designer.cs Form DDEX\MySqlDataConnectionPromptDialog.cs MySqlDataConnectionPromptDialog.cs DDEX\MySqlDataConnectionPromptDialog.Designer.cs DDEX\MySqlDataObjectEnumerator.cs DDEX\MySqlDataObjectIdentifierConverter.cs DDEX\MySqlDataObjectSupport.cs DDEX\MySqlDataSourceInformation.cs DDEX\MySqlDataSourceSpecializer.cs DDEX\MySqlDataViewCommandHandler.cs DDEX\MySqlDataViewSupport.cs DbObjects\ColumnWithTypeDescriptor.cs DDEX\StoredProcedureColumnEnumerator.cs UserControl Editors\VSCodeEditorUserControl.cs Form Editors\ConnectDialog.cs ConnectDialog.cs Editors\ConnectDialog.Designer.cs Editors\CustomPropertyDescriptor.cs Form Editors\ForeignKeyDialog.cs ForeignKeyDialog.cs Editors\ForeignKeyDialog.Designer.cs Form Editors\GenerateChangeScriptDialog.cs GenerateChangeScriptDialog.cs Editors\GenerateChangeScriptDialog.Designer.cs Editors\IEditor.cs Form Editors\IndexColumnEditorDialog.cs IndexColumnEditorDialog.cs Editors\IndexColumnEditorDialog.Designer.cs Component Editors\MyComboBox.cs Editors\MyDataGridViewRowHeaderCell.cs Editors\MyDescriptionAttribute.cs Component Editors\MySplitter.cs Editors\ServiceBroker.cs UserControl Editors\SqlEditor.cs SqlEditor.cs Editors\SqlEditor.Designer.cs Editors\SqlEditorFactory.cs Editors\SqlEditorPane.cs Editors\TableEditorPane.cs Form Editors\TableIndexDialog.cs TableIndexDialog.cs Editors\TableIndexDialog.Designer.cs Form Editors\TableNamePromptDialog.cs TableNamePromptDialog.cs Editors\TableNamePromptDialog.Designer.cs Form Editors\UDFEditor.cs UDFEditor.cs Editors\UDFEditor.Designer.cs Editors\VS2005ColorTable.cs Component Editors\VS2005PropertyGrid.cs Editors\VSCodeEditor.cs Editors\VSCodeEditorWindow.cs Editors\YesNoTypeConverter.cs LanguageService\MySqlLanguageService.cs UserControl Editors\TableEditor.cs LanguageService\MySqlScanner.cs LanguageService\Tokenizer.cs Component Nodes\BaseNode.cs DbObjects\Column.cs Nodes\TriggerNode.cs Nodes\UDFNode.cs Nodes\DocumentNode.cs Nodes\ViewNode.cs Nodes\StoredProcedureNode.cs Nodes\TableNode.cs True True Resources.resx Properties\Resources.Designer.cs Properties\AssemblyInfo.cs Form WebConfig\ConnectionStringEditorDlg.cs ConnectionStringEditorDlg.cs WebConfig\ConnectionStringEditorDlg.Designer.cs WebConfig\GenericConfig.cs WebConfig\MembershipConfig.cs Form WebConfig\MembershipOptionsDlg.cs MembershipOptionsDlg.cs WebConfig\MembershipOptionsDlg.Designer.cs WebConfig\ProfileConfig.cs WebConfig\RoleConfig.cs WebConfig\SessionStateConfig.cs WebConfig\WebConfig.cs Form WebConfig\WebConfigDlg.cs WebConfigDlg.cs WebConfig\WebConfigDlg.Designer.cs PublicResXFileCodeGenerator Resources.Designer.cs Designer true Properties\Resources.resx MySqlConnectionUIControl.cs Designer DDEX\MySqlConnectionUIControl.resx MySqlDataConnectionPromptDialog.cs DDEX\MySqlDataConnectionPromptDialog.resx DDEX\MySqlDataObjectSupport.xml DDEX\MySqlDataViewSupport.xml ConnectDialog.cs Editors\ConnectDialog.resx ForeignKeyDialog.cs Editors\ForeignKeyDialog.resx GenerateChangeScriptDialog.cs Designer Editors\GenerateChangeScriptDialog.resx IndexColumnEditorDialog.cs Editors\IndexColumnEditorDialog.resx SqlEditor.cs Editors\SqlEditor.resx Designer TableEditor.cs Editors\TableEditor.resx TableIndexDialog.cs Designer Editors\TableIndexDialog.resx TableNamePromptDialog.cs Editors\TableNamePromptDialog.resx UDFEditor.cs Designer Editors\UDFEditor.resx ConnectionStringEditorDlg.cs WebConfig\ConnectionStringEditorDlg.resx MembershipOptionsDlg.cs WebConfig\MembershipOptionsDlg.resx WebConfigDlg.cs WebConfig\WebConfigDlg.resx Resources\ArrowKey.bmp Resources\Key.bmp Resources\bannrbmp.bmp Resources\sql_editor_connect.bmp Resources\sql_editor_runsql.bmp Resources\sql_editor_validatesql.bmp Resources\sql_editor_executionplan.bmp Resources\sql_editor_banner.bmp Resources\sql_editor_disconnect.bmp Always Templates\MySQL Script.mysql Always Templates\MySqlDataProviderPackage.vsdir Resources\401.ico Resources\icon.bmp Resources\Package.ico 1000 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} MySql.Data false true true false mysql-connector-net-6.4.3/VS2008/Source/MySql.Data.CF/0000755000175000017500000000000011127003600022461 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Source/MySql.Data.CF/MySql.Data.CF.csproj0000644000175000017500000003204111127003600026107 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {587A47FB-C1CC-459D-93B6-179D95E41EFB} Library Properties MySql.Data.MySqlClient MySql.Data.CF {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} WindowsCE E2BECB1F-8C8C-41ba-B736-9BE7D946A398 5.00 MySql.Data.CF v2.0 3.5 Windows CE true full false bin\Debug\ TRACE;DEBUG;CF true true prompt 512 4 Off 1699 pdbonly true bin\Release\ TRACE;CF true true prompt 512 4 Off 1699 Properties\AssemblyInfo.cs Properties\Resources.Designer.cs Properties\VersionInfo.cs Component Component common\Cache.cs common\ContextString.cs common\LowResolutionStopwatch.cs common\MyNetworkStream.cs common\MySqlTokenizer.cs common\NativeMethods.cs common\Platform.cs common\SHA1.cs common\StreamCreator.cs common\Version.cs Component Component SSPI.cs TableCache.cs Types\MetaData.cs Types\MySqlBinary.cs Types\MySqlBit.cs Types\MySqlByte.cs Types\MySqlConversionException.cs Types\MySqlDateTime.cs Types\MySqlDecimal.cs Types\MySqlDouble.cs Types\MySqlGuid.cs Types\MySqlInt16.cs Types\MySqlInt32.cs Types\MySqlInt64.cs Types\MySqlSingle.cs Types\MySqlString.cs Types\MySqlTime.cs Types\MySqlUByte.cs Types\MySqlUInt16.cs Types\MySqlUInt32.cs Types\MySqlUInt64.cs Types\MySqlValue.cs zlib\Adler32.cs zlib\Deflate.cs zlib\InfBlocks.cs zlib\InfCodes.cs zlib\Inflate.cs zlib\InfTree.cs zlib\StaticTree.cs zlib\SupportClass.cs zlib\Tree.cs zlib\ZInputStream.cs zlib\Zlib.cs zlib\ZOutputStream.cs zlib\ZStream.cs zlib\ZStreamException.cs Designer Properties\Resources.resx Properties\ReservedWords.txt mysql-connector-net-6.4.3/VS2008/Source/MySql.Data.CF/base/0000755000175000017500000000000011127003600023373 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Source/MySql.Data.CF/base/DbException.cs0000644000175000017500000000362511127003600026134 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Runtime.InteropServices; namespace MySql.Data.MySqlClient { public abstract class DbException : ExternalException { private int errorCode; public DbException() : base() { } public DbException(string message) : base(message) { } public DbException(string message, Exception innerException) : base(message, innerException) { } public DbException(string message, int errorCode) : base(message) { this.errorCode = errorCode; } #region Properties // public int ErrorCode // { // get { return errorCode; } // } #endregion } } mysql-connector-net-6.4.3/VS2008/Source/MySql.Data.CF/base/DbConnectionStringBuilder.cs0000644000175000017500000002427611127003600031000 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.ComponentModel; using System.Text; using System.Globalization; namespace MySql.Data.MySqlClient { public class DbConnectionStringBuilder : IDictionary, ICollection, IEnumerable, ICustomTypeDescriptor { private Hashtable hash; private bool browsable; public DbConnectionStringBuilder() { hash = new Hashtable(StringComparer.InvariantCultureIgnoreCase); browsable = false; } #region Properties public bool BrowsableConnectionString { get { return browsable; } set { browsable = value; } } public string ConnectionString { get { return GetConnectionString(); } set { Clear(); ParseConnectionString(value); } } public virtual object this[string key] { get { return hash[key]; } set { Add(key, value); } } #endregion #region IDictionary Members public void Add(object key, object value) { hash[key] = value; } public virtual void Clear() { hash.Clear(); } public bool Contains(object key) { return hash.ContainsKey(key); } public IDictionaryEnumerator GetEnumerator() { return hash.GetEnumerator(); } public bool IsFixedSize { get { return false; } } public bool IsReadOnly { get { return false; } } public ICollection Keys { get { return hash.Keys; } } public void Remove(object key) { hash.Remove(key); } public ICollection Values { get { return hash.Values; } } public object this[object key] { get { return this[(string)key]; } set { this[(string)key] = value; } } #endregion #region ICollection Members public void CopyTo(Array array, int index) { hash.CopyTo(array, index); } public int Count { get { return hash.Count; } } public bool IsSynchronized { get { return hash.IsSynchronized; } } public object SyncRoot { get { return hash.SyncRoot; } } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return hash.GetEnumerator(); } #endregion #region ICustomTypeDescriptor Members public AttributeCollection GetAttributes() { throw new Exception("The method or operation is not implemented."); } public string GetClassName() { throw new Exception("The method or operation is not implemented."); } public string GetComponentName() { throw new Exception("The method or operation is not implemented."); } public TypeConverter GetConverter() { throw new Exception("The method or operation is not implemented."); } public EventDescriptor GetDefaultEvent() { throw new Exception("The method or operation is not implemented."); } public PropertyDescriptor GetDefaultProperty() { throw new Exception("The method or operation is not implemented."); } public object GetEditor(Type editorBaseType) { throw new Exception("The method or operation is not implemented."); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { throw new Exception("The method or operation is not implemented."); } public EventDescriptorCollection GetEvents() { throw new Exception("The method or operation is not implemented."); } public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { throw new Exception("The method or operation is not implemented."); } public PropertyDescriptorCollection GetProperties() { throw new Exception("The method or operation is not implemented."); } public object GetPropertyOwner(PropertyDescriptor pd) { throw new Exception("The method or operation is not implemented."); } #endregion public virtual object TryGetValue(string keyword, out object value) { if (!hash.ContainsKey(keyword)) { value = null; return false; } value = hash[keyword]; return true; } private void ParseConnectionString(string connectString) { if (connectString == null) return; StringBuilder key = new StringBuilder(); StringBuilder value = new StringBuilder(); bool keyDone = false; foreach (char c in connectString) { if (c == '=') keyDone = true; else if (c == ';') { string keyStr = key.ToString().Trim(); string valueStr = value.ToString().Trim(); valueStr = CleanValue(valueStr); if (keyStr.Length > 0) this[keyStr] = valueStr; keyDone = false; key.Remove(0, key.Length); value.Remove(0, value.Length); } else if (keyDone) value.Append(c); else key.Append(c); } if (key.Length == 0) return; this[key.ToString().Trim()] = CleanValue(value.ToString().Trim()); } private string CleanValue(string value) { if ((value.StartsWith("'") && value.EndsWith("'")) || (value.StartsWith("\"") && value.EndsWith("\""))) { value = value.Substring(1); value = value.Substring(0, value.Length - 1); } return value; } private string GetConnectionString() { StringBuilder builder = new StringBuilder(); string delimiter = ""; foreach (string key in this.Keys) { builder.AppendFormat(CultureInfo.CurrentCulture, "{0}{1}={2}", delimiter, key, this[key]); delimiter = ";"; } return builder.ToString(); } /* private void ParseConnectionString(string value) { String[] keyvalues = src.Split(';'); String[] newkeyvalues = new String[keyvalues.Length]; int x = 0; // first run through the array and check for any keys that // have ; in their value foreach (String keyvalue in keyvalues) { // check for trailing ; at the end of the connection string if (keyvalue.Length == 0) continue; // this value has an '=' sign so we are ok if (keyvalue.IndexOf('=') >= 0) { newkeyvalues[x++] = keyvalue; } else { newkeyvalues[x - 1] += ";"; newkeyvalues[x - 1] += keyvalue; } } Hashtable hash = new Hashtable(); // now we run through our normalized key-values, splitting on equals for (int y = 0; y < x; y++) { String[] parts = newkeyvalues[y].Split('='); // first trim off any space and lowercase the key parts[0] = parts[0].Trim().ToLower(); parts[1] = parts[1].Trim(); // we also want to clear off any quotes if (parts[1].Length >= 2) { if ((parts[1][0] == '"' && parts[1][parts[1].Length - 1] == '"') || (parts[1][0] == '\'' && parts[1][parts[1].Length - 1] == '\'')) { parts[1] = parts[1].Substring(1, parts[1].Length - 2); } } else { parts[1] = parts[1]; } parts[0] = parts[0].Trim('\'', '"'); hash[parts[0]] = parts[1]; } return hash; }*/ } } mysql-connector-net-6.4.3/VS2008/Source/MySql.Data.CF/cf/0000755000175000017500000000000011127003600023051 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Source/MySql.Data.CF/cf/MissingAttributes.cs0000644000175000017500000000405311127003600027062 0ustar directhexdirecthex// Copyright (c) 2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; namespace MySql.Data.MySqlClient { #if CF class CategoryAttribute : Attribute { public CategoryAttribute(string cat) { } } class DescriptionAttribute : Attribute { public DescriptionAttribute(string desc) { } } class DisplayNameAttribute : Attribute { private string displayName; public DisplayNameAttribute(string name) { displayName = name; } public string DisplayName { get { return displayName; } } } class RefreshPropertiesAttribute : Attribute { public RefreshPropertiesAttribute(RefreshProperties prop) { } } class PasswordPropertyTextAttribute : Attribute { public PasswordPropertyTextAttribute(bool v) { } } public enum RefreshProperties { None = 0, All = 1, Repaint = 2, } #endif } mysql-connector-net-6.4.3/VS2008/Source/MySql.Data.CF/cf/BufferedStream.cs0000644000175000017500000001540511127003600026303 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.IO; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.Common { internal class BufferedStream : Stream { private byte[] writeBuffer; private byte[] readBuffer; private int writePos; private int readLength; private int readPos; private int bufferSize; private Stream baseStream; public BufferedStream(Stream stream) { baseStream = stream; bufferSize = 4096; readBuffer = new byte[bufferSize]; writeBuffer = new byte[bufferSize]; } #region Stream Implementation public override bool CanRead { get { if (baseStream != null) return baseStream.CanRead; return false; } } public override bool CanSeek { get { if (baseStream != null) return baseStream.CanSeek; return false; } } public override bool CanWrite { get { if (baseStream != null) return baseStream.CanWrite; return false; } } public override void Flush() { if (baseStream == null) throw new InvalidOperationException(Resources.ObjectDisposed); if (writePos == 0) return; baseStream.Write(writeBuffer, 0, writePos); baseStream.Flush(); writePos = 0; } public override long Length { get { if (baseStream == null) throw new InvalidOperationException(Resources.ObjectDisposed); Flush(); return baseStream.Length; } } public override long Position { get { throw new Exception("The method or operation is not implemented."); } set { throw new Exception("The method or operation is not implemented."); } } public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer", Resources.ParameterCannotBeNull); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Resources.OffsetCannotBeNegative); if (count < 0) throw new ArgumentOutOfRangeException("count", Resources.CountCannotBeNegative); if ((buffer.Length - offset) < count) throw new ArgumentException(Resources.OffsetMustBeValid); if (baseStream == null) throw new InvalidOperationException(Resources.ObjectDisposed); if ((readLength - readPos) == 0) { TryToFillReadBuffer(); if (readLength == 0) return 0; } int inBuffer = readLength - readPos; int toRead = count; if (toRead > inBuffer) toRead = inBuffer; Buffer.BlockCopy(readBuffer, readPos, buffer, offset, toRead); readPos += toRead; count -= toRead; if (count > 0) { int read = baseStream.Read(buffer, offset + toRead, count); toRead += read; readPos = readLength = 0; } return toRead; } private void TryToFillReadBuffer() { int read = baseStream.Read(readBuffer, 0, bufferSize); readPos = 0; readLength = read; } public override long Seek(long offset, SeekOrigin origin) { throw new Exception("The method or operation is not implemented."); } public override void SetLength(long value) { throw new Exception("The method or operation is not implemented."); } public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer", Resources.ParameterCannotBeNull); if (offset < 0) throw new ArgumentOutOfRangeException("offset", Resources.OffsetCannotBeNegative); if (count < 0) throw new ArgumentOutOfRangeException("count", Resources.CountCannotBeNegative); if ((buffer.Length - offset) < count) throw new ArgumentException(Resources.OffsetMustBeValid); if (baseStream == null) throw new InvalidOperationException(Resources.ObjectDisposed); // if we don't have enough room in our current write buffer for the data // then flush the data int roomLeft = bufferSize - writePos; if (count > roomLeft) Flush(); // if the data will not fit into a entire buffer, then there is no need to buffer it. // We just send it down if (count > bufferSize) baseStream.Write(buffer, offset, count); else { // if we get here then there is room in our buffer for the data. We store it and // adjust our internal lengths. Buffer.BlockCopy(buffer, offset, writeBuffer, writePos, count); writePos += count; } } #endregion } } mysql-connector-net-6.4.3/VS2008/Source/MySql.Data.CF/cf/WinCE.cs0000644000175000017500000000267011127003600024352 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Runtime.InteropServices; namespace MySql.Data.Common { /// /// Summary description for Win32. /// internal class WinCE { [DllImport("coredll", SetLastError=true)] internal static extern Int32 WaitForSingleObject(IntPtr handle, Int32 milliseconds); } } mysql-connector-net-6.4.3/VS2008/Source/MySql.Data.Entity/0000755000175000017500000000000011127003600023445 5ustar directhexdirecthexmysql-connector-net-6.4.3/VS2008/Source/MySql.Data.Entity/MySql.Data.Entity.csproj0000644000175000017500000001764111127003600030070 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {EDED3135-95D2-4BCE-A810-F3F2AD7935B7} Library Properties MySql.Data.Entity MySql.Data.Entity v3.5 512 3.5 false publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false true true full false bin\Debug\ DEBUG;TRACE prompt 4 AllRules.ruleset pdbonly true bin\Release\ TRACE prompt 4 AllRules.ruleset Properties\SchemaMapping.msl Properties\VersionInfo.cs Component Fragments\TableFragment.cs Fragments\InputFragment.cs Fragments\JoinFragment.cs Fragments\SqlFragment.cs Generators\DeleteGenerator.cs Code Generators\FunctionGenerator.cs Generators\FunctionProcessor.cs Generators\InsertGenerator.cs Generators\Scope.cs Generators\SelectGenerator.cs Generators\SqlGenerator.cs Generators\UpdateGenerator.cs True True Resources.resx Properties\Resources.Designer.cs Statements\DeleteStatement.cs Statements\InsertStatement.cs Properties\AssemblyInfo.cs Statements\SelectStatement.cs Statements\UpdateStatement.cs Properties\ProviderManifest.xml Properties\SchemaDefinition-5.0.ssdl Properties\SchemaDefinition-5.5.ssdl Properties\SchemaDefinition-5.1.ssdl ResXFileCodeGenerator Resources.Designer.cs Properties\Resources.resx {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} MySql.Data mysql-connector-net-6.4.3/VS2008/MySQL-VS2005.sln0000644000175000017500000001521511127003600021341 0ustar directhexdirecthex Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Web", "MySql.Web\Providers\MySql.Web.csproj", "{C28B1166-1380-445D-AEC1-8A18B990DD18}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Web.Tests", "MySql.Web\Tests\MySql.Web.Tests.csproj", "{DC704374-EC50-4167-93AA-8D262136502E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data", "MySql.Data\Provider\MySql.Data.csproj", "{E9DF5ED1-4CBD-4226-B931-9A51610AC14D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data.CF", "MySql.Data\Provider\MySql.Data.CF.csproj", "{587A47FB-C1CC-459D-93B6-179D95E41EFB}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data.Tests", "MySql.Data\Tests\MySql.Data.Tests.csproj", "{F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.VisualStudio", "MySql.VisualStudio\MySql.VisualStudio.csproj", "{DC3517FF-AC26-4755-9B7A-EF658FF69593}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|.NET 2.0 = Debug|.NET 2.0 Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|.NET 2.0 = Release|.NET 2.0 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|.NET 2.0.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|Any CPU.Build.0 = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|x64.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|x86.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|.NET 2.0.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|Any CPU.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|Any CPU.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|x64.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|x86.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Debug|.NET 2.0.ActiveCfg = Debug|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Debug|Any CPU.Build.0 = Debug|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Debug|x64.ActiveCfg = Debug|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Debug|x86.ActiveCfg = Debug|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Release|.NET 2.0.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Release|Any CPU.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Release|Any CPU.Build.0 = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Release|x64.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Release|x86.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|.NET 2.0.ActiveCfg = Debug|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|Any CPU.Build.0 = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|x64.ActiveCfg = Debug|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|x86.ActiveCfg = Debug|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|x86.Build.0 = Debug|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|.NET 2.0.ActiveCfg = Release|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|Any CPU.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|Any CPU.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|x64.ActiveCfg = Release|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|x86.ActiveCfg = Release|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|x86.Build.0 = Release|x86 {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Debug|.NET 2.0.ActiveCfg = Debug|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Debug|Any CPU.Build.0 = Debug|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Debug|x64.ActiveCfg = Debug|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Debug|x86.ActiveCfg = Debug|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Release|.NET 2.0.ActiveCfg = Release|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Release|Any CPU.ActiveCfg = Release|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Release|Any CPU.Build.0 = Release|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Release|x64.ActiveCfg = Release|Any CPU {587A47FB-C1CC-459D-93B6-179D95E41EFB}.Release|x86.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|.NET 2.0.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|Any CPU.Build.0 = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|x64.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|x86.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|.NET 2.0.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|Any CPU.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|Any CPU.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|x64.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|x86.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|.NET 2.0.ActiveCfg = Debug|x64 {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|Any CPU.Build.0 = Debug|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|x64.ActiveCfg = Debug|x64 {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|x64.Build.0 = Debug|x64 {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Debug|x86.ActiveCfg = Debug|x64 {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|.NET 2.0.ActiveCfg = Release|x64 {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|Any CPU.ActiveCfg = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|Any CPU.Build.0 = Release|Any CPU {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|x64.ActiveCfg = Release|x64 {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|x64.Build.0 = Release|x64 {DC3517FF-AC26-4755-9B7A-EF658FF69593}.Release|x86.ActiveCfg = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal mysql-connector-net-6.4.3/Source/0000755000175000017500000000000011127003600017413 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Web/0000755000175000017500000000000011127003600021174 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Web/MySql.Web.csproj0000644000175000017500000001206211127003600024200 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {C28B1166-1380-445D-AEC1-8A18B990DD18} Library Properties MySql.Web MySql.Web false 3.5 v4.0 false publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false true true full false bin\Debug\ TRACE;DEBUG;CLR4 prompt 4 1699 AllRules.ruleset pdbonly true bin\Release\ TRACE;CLR4 prompt 4 1699 bin\release\webdocs.xml AllRules.ruleset Properties\VersionInfo.cs Component True True Resources.resx True True Designer PublicResXFileCodeGenerator Resources.Designer.cs {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} MySql.Data mysql-connector-net-6.4.3/Source/MySql.Web/Application.cs0000644000175000017500000000453711127003600023777 0ustar directhexdirecthexusing System; using System.Collections.Generic; using System.Text; using MySql.Data.MySqlClient; using System.Configuration.Provider; using MySql.Web.Properties; namespace MySql.Web.General { internal class Application { private int _id; private string _desc; public Application(string name, string desc) { Id = -1; Name = name; Description = desc; } public int Id { get { return _id; } private set { _id = value; } } public string Name; public string Description { get { return _desc; } private set { _desc = value; } } public int FetchId(MySqlConnection connection) { if (Id == -1) { MySqlCommand cmd = new MySqlCommand( @"SELECT id FROM my_aspnet_Applications WHERE name=@name", connection); cmd.Parameters.AddWithValue("@name", Name); object id = cmd.ExecuteScalar(); Id = id == null ? -1 : Convert.ToInt32(id); } return Id; } /// /// Creates the or fetch application id. /// /// Name of the application. /// The application id. /// The application desc. /// The connection. public int EnsureId(MySqlConnection connection) { // first try and retrieve the existing id if (FetchId(connection) <= 0) { MySqlCommand cmd = new MySqlCommand( "INSERT INTO my_aspnet_Applications VALUES (NULL, @appName, @appDesc)", connection); cmd.Parameters.AddWithValue("@appName", Name); cmd.Parameters.AddWithValue("@appDesc", Description); int recordsAffected = cmd.ExecuteNonQuery(); if (recordsAffected != 1) throw new ProviderException(Resources.UnableToCreateApplication); Id = Convert.ToInt32(cmd.LastInsertedId); } return Id; } } } mysql-connector-net-6.4.3/Source/MySql.Web/MembershipProvider.cs0000644000175000017500000021544411127003600025343 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12 // The copyright was assigned and transferred under the terms of // the MySQL Contributor License Agreement (CLA) using System; using System.Collections.Specialized; using System.Configuration; using System.Configuration.Provider; using System.Data; using System.Diagnostics; using System.Security.Cryptography; using System.Text; using System.Web.Configuration; using System.Web.Hosting; using System.Web.Security; using MySql.Data.MySqlClient; using MySql.Web.Properties; using MySql.Web.Profile; using MySql.Web.Common; using System.Text.RegularExpressions; using MySql.Web.General; namespace MySql.Web.Security { /// /// Manages storage of membership information for an ASP.NET application in a MySQL database. /// /// /// /// This class is used by the and classes /// to provide membership services for ASP.NET applications using a MySQL database. /// /// /// /// /// public sealed class MySQLMembershipProvider : MembershipProvider { private int newPasswordLength = 8; private string eventSource = "MySQLMembershipProvider"; private string eventLog = "Application"; private string exceptionMessage = "An exception occurred. Please check the Event Log."; private string connectionString; private int minRequiredPasswordLength; private bool writeExceptionsToEventLog; private bool enablePasswordReset; private bool enablePasswordRetrieval; private bool requiresQuestionAndAnswer; private bool requiresUniqueEmail; private int maxInvalidPasswordAttempts; private int passwordAttemptWindow; private MembershipPasswordFormat passwordFormat; private int minRequiredNonAlphanumericCharacters; private string passwordStrengthRegularExpression; private Application app; /// /// Initializes the MySQL membership provider with the property values specified in the /// ASP.NET application's configuration file. This method is not intended to be used directly /// from your code. /// /// The name of the instance to initialize. /// A collection of the name/value pairs representing the /// provider-specific attributes specified in the configuration for this provider. /// config is a null reference. /// An attempt is made to call on a provider after the provider has already been initialized. /// public override void Initialize(string name, NameValueCollection config) { if (config == null) { throw new ArgumentNullException("config"); } if (name == null || name.Length == 0) { name = "MySQLMembershipProvider"; } if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "MySQL default application"); } base.Initialize(name, config); string applicationName = GetConfigValue(config["applicationName"], HostingEnvironment.ApplicationVirtualPath); maxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5")); passwordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10")); minRequiredNonAlphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonalphanumericCharacters"], "1")); minRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "7")); passwordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], "")); enablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "True")); enablePasswordRetrieval = Convert.ToBoolean( GetConfigValue(config["enablePasswordRetrieval"], "False")); requiresQuestionAndAnswer = Convert.ToBoolean(GetConfigValue(config["requiresQuestionAndAnswer"], "False")); requiresUniqueEmail = Convert.ToBoolean(GetConfigValue(config["requiresUniqueEmail"], "True")); writeExceptionsToEventLog = Convert.ToBoolean(GetConfigValue(config["writeExceptionsToEventLog"], "True")); string temp_format = config["passwordFormat"]; if (temp_format == null) temp_format = "hashed"; else temp_format = temp_format.ToLowerInvariant(); if (temp_format == "hashed") passwordFormat = MembershipPasswordFormat.Hashed; else if (temp_format == "encrypted") passwordFormat = MembershipPasswordFormat.Encrypted; else if (temp_format == "clear") passwordFormat = MembershipPasswordFormat.Clear; else throw new ProviderException("Password format not supported."); // if the user is asking for the ability to retrieve hashed passwords, then let // them know we can't if (PasswordFormat == MembershipPasswordFormat.Hashed) { if (EnablePasswordRetrieval) throw new ProviderException(Resources.CannotRetrieveHashedPasswords); if (Runtime.IsMono) throw new ProviderException(Resources.MonoDoesNotSupportHash); } ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[ config["connectionStringName"]]; if (ConnectionStringSettings != null) connectionString = ConnectionStringSettings.ConnectionString.Trim(); else connectionString = ""; if (String.IsNullOrEmpty(connectionString)) return; // make sure we have the correct schema SchemaManager.CheckSchema(connectionString, config); app = new Application(applicationName, base.Description); } private static string GetConfigValue(string configValue, string defaultValue) { if (string.IsNullOrEmpty(configValue)) { return defaultValue; } return configValue; } #region Properties /// /// The name of the application using the MySQL membership provider. /// /// The name of the application using the MySQL membership provider. The default is the /// application virtual path. /// The ApplicationName is used by the MySqlMembershipProvider to separate /// membership information for multiple applications. Using different application names, /// applications can use the same membership database. /// Likewise, multiple applications can make use of the same membership data by simply using /// the same application name. /// Caution should be taken with multiple applications as the ApplicationName property is not /// thread safe during writes. /// /// /// The following example shows the membership element being used in an applications web.config file. /// The application name setting is being used. /// /// public override string ApplicationName { get { return app.Name; } set { lock (this) { if (value.ToLowerInvariant() == app.Name.ToLowerInvariant()) return; app = new Application(value, String.Empty); } } } /// /// Indicates whether the membership provider is configured to allow users to reset their passwords. /// /// true if the membership provider supports password reset; otherwise, false. The default is true. /// Allows the user to replace their password with a new, randomly generated password. /// This can be especially handy when using hashed passwords since hashed passwords cannot be /// retrieved. /// /// The following example shows the membership element being used in an applications web.config file. /// /// public override bool EnablePasswordReset { get { return enablePasswordReset; } } /// /// Indicates whether the membership provider is configured to allow users to retrieve /// their passwords. /// /// true if the membership provider is configured to support password retrieval; /// otherwise, false. The default is false. /// If the system is configured to use hashed passwords, then retrieval is not possible. /// If the user attempts to initialize the provider with hashed passwords and enable password retrieval /// set to true then a is thrown. /// /// The following example shows the membership element being used in an applications web.config file. /// /// public override bool EnablePasswordRetrieval { get { return enablePasswordRetrieval; } } /// /// Gets a value indicating whether the membership provider is /// configured to require the user to answer a password question /// for password reset and retrieval. /// /// true if a password answer is required for password /// reset and retrieval; otherwise, false. The default is false. /// /// The following example shows the membership element being used in an applications web.config file. /// /// public override bool RequiresQuestionAndAnswer { get { return requiresQuestionAndAnswer; } } /// /// Gets a value indicating whether the membership provider is configured /// to require a unique e-mail address for each user name. /// /// true if the membership provider requires a unique e-mail address; /// otherwise, false. The default is true. /// /// The following example shows the membership element being used in an applications web.config file. /// /// public override bool RequiresUniqueEmail { get { return requiresUniqueEmail; } } /// /// Gets the number of invalid password or password-answer attempts allowed /// before the membership user is locked out. /// /// The number of invalid password or password-answer attempts allowed /// before the membership user is locked out. /// /// The following example shows the membership element being used in an applications web.config file. /// /// public override int MaxInvalidPasswordAttempts { get { return maxInvalidPasswordAttempts; } } /// /// Gets the number of minutes in which a maximum number of invalid password or /// password-answer attempts are allowed before the membership user is locked out. /// /// The number of minutes in which a maximum number of invalid password or /// password-answer attempts are allowed before the membership user is locked out. /// /// The following example shows the membership element being used in an applications web.config file. /// /// public override int PasswordAttemptWindow { get { return passwordAttemptWindow; } } /// /// Gets a value indicating the format for storing passwords in the membership data store. /// /// One of the /// values indicating the format for storing passwords in the data store. /// /// The following example shows the membership element being used in an applications web.config file. /// /// public override MembershipPasswordFormat PasswordFormat { get { return passwordFormat; } } /// /// Gets the minimum number of special characters that must be present in a valid password. /// /// The minimum number of special characters that must be present /// in a valid password. /// /// The following example shows the membership element being used in an applications web.config file. /// /// public override int MinRequiredNonAlphanumericCharacters { get { return minRequiredNonAlphanumericCharacters; } } /// /// Gets the minimum length required for a password. /// /// The minimum length required for a password. /// /// The following example shows the membership element being used in an applications web.config file. /// /// public override int MinRequiredPasswordLength { get { return minRequiredPasswordLength; } } /// /// Gets the regular expression used to evaluate a password. /// /// A regular expression used to evaluate a password. /// /// The following example shows the membership element being used in an applications web.config file. /// In this example, the regular expression specifies that the password must meet the following /// criteria: ///
    /// Is at least seven characters. /// Contains at least one digit. /// Contains at least one special (non-alphanumeric) character. ///
/// ///
public override string PasswordStrengthRegularExpression { get { return passwordStrengthRegularExpression; } } /// /// Gets or sets a value indicating whether exceptions are written to the event log. /// /// /// true if exceptions should be written to the log; otherwise, false. /// public bool WriteExceptionsToEventLog { get { return writeExceptionsToEventLog; } set { writeExceptionsToEventLog = value; } } #endregion #region Public Methods /// /// Changes the password. /// /// The username. /// The old password. /// The new password. /// true if the password was updated successfully, false if the supplied old password /// is invalid, the user is locked out, or the user does not exist in the database. public override bool ChangePassword(string username, string oldPassword, string newPassword) { // this will return false if the username doesn't exist if (!(ValidateUser(username, oldPassword))) return false; ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true); OnValidatingPassword(args); if (args.Cancel) { if (!(args.FailureInformation == null)) throw args.FailureInformation; else throw new ProviderException(Resources.ChangePasswordCanceled); } // validate the password according to current guidelines if (!ValidatePassword(newPassword, "newPassword", true)) return false; try { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); // retrieve the existing key and format for this user string passwordKey; MembershipPasswordFormat passwordFormat; int userId = GetUserId(connection, username); GetPasswordInfo(connection, userId, out passwordKey, out passwordFormat); MySqlCommand cmd = new MySqlCommand( @"UPDATE my_aspnet_Membership SET Password = @pass, LastPasswordChangedDate = @lastPasswordChangedDate WHERE userId=@userId", connection); cmd.Parameters.AddWithValue("@pass", EncodePassword(newPassword, passwordKey, passwordFormat)); cmd.Parameters.AddWithValue("@lastPasswordChangedDate", DateTime.Now); cmd.Parameters.AddWithValue("@userId", userId); return cmd.ExecuteNonQuery() > 0; } } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "ChangePassword"); throw new ProviderException(exceptionMessage, e); } } /// /// Changes the password question and answer. /// /// The username. /// The password. /// The new password question. /// The new password answer. /// true if the update was successful; otherwise, false. A value of false is /// also returned if the password is incorrect, the user is locked out, or the user /// does not exist in the database. public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPwdQuestion, string newPwdAnswer) { // this handles the case where the username doesn't exist if (!(ValidateUser(username, password))) return false; try { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); string passwordKey; MembershipPasswordFormat passwordFormat; int userId = GetUserId(connection, username); GetPasswordInfo(connection, userId, out passwordKey, out passwordFormat); MySqlCommand cmd = new MySqlCommand( @"UPDATE my_aspnet_Membership SET PasswordQuestion = @passwordQuestion, PasswordAnswer = @passwordAnswer WHERE userId=@userId", connection); cmd.Parameters.AddWithValue("@passwordQuestion", newPwdQuestion); cmd.Parameters.AddWithValue("@passwordAnswer", EncodePassword(newPwdAnswer, passwordKey, passwordFormat)); cmd.Parameters.AddWithValue("@userId", userId); return cmd.ExecuteNonQuery() > 0; } } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "ChangePasswordQuestionAndAnswer"); throw new ProviderException(exceptionMessage, e); } } /// /// Adds a new membership user to the data source. /// /// The user name for the new user. /// The password for the new user. /// The e-mail address for the new user. /// The password question for the new user. /// The password answer for the new user /// Whether or not the new user is approved to be validated. /// The unique identifier from the membership data source for the user. /// A enumeration value indicating whether the user was created successfully. /// /// A object populated with the information for the newly created user. /// public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { ValidatePasswordEventArgs Args = new ValidatePasswordEventArgs(username, password, true); OnValidatingPassword(Args); if (Args.Cancel) { status = MembershipCreateStatus.InvalidPassword; return null; } if (RequiresUniqueEmail && !String.IsNullOrEmpty(GetUserNameByEmail(email))) { status = MembershipCreateStatus.DuplicateEmail; return null; } ValidateQA(passwordQuestion, passwordAnswer); // now try to validate the password if (!ValidatePassword(password, "password", false)) { status = MembershipCreateStatus.InvalidPassword; return null; } // now check to see if we already have a member by this name MembershipUser u = GetUser(username, false); if (u != null) { status = MembershipCreateStatus.DuplicateUserName; return null; } string passwordKey = GetPasswordKey(); DateTime createDate = DateTime.Now; MySqlTransaction transaction = null; using (MySqlConnection connection = new MySqlConnection(connectionString)) { try { connection.Open(); transaction = connection.BeginTransaction(); // either create a new user or fetch the existing user id int userId = SchemaManager.CreateOrFetchUserId(connection, username, app.EnsureId(connection), true); MySqlCommand cmd = new MySqlCommand( @"INSERT INTO my_aspnet_Membership VALUES(@userId, @email, @comment, @password, @passwordKey, @passwordFormat, @passwordQuestion, @passwordAnswer, @isApproved, @lastActivityDate, @lastLoginDate, @lastPasswordChangedDate, @creationDate, @isLockedOut, @lastLockedOutDate, @failedPasswordAttemptCount, @failedPasswordAttemptWindowStart, @failedPasswordAnswerAttemptCount, @failedPasswordAnswerAttemptWindowStart)", connection); cmd.Parameters.AddWithValue("@userId", userId); cmd.Parameters.AddWithValue("@email", email); cmd.Parameters.AddWithValue("@comment", ""); cmd.Parameters.AddWithValue("@password", EncodePassword(password, passwordKey, PasswordFormat)); cmd.Parameters.AddWithValue("@passwordKey", passwordKey); cmd.Parameters.AddWithValue("@passwordFormat", PasswordFormat); cmd.Parameters.AddWithValue("@passwordQuestion", passwordQuestion); cmd.Parameters.AddWithValue("@passwordAnswer", EncodePassword(passwordAnswer, passwordKey, PasswordFormat)); cmd.Parameters.AddWithValue("@isApproved", isApproved); cmd.Parameters.AddWithValue("@lastActivityDate", createDate); cmd.Parameters.AddWithValue("@lastLoginDate", createDate); cmd.Parameters.AddWithValue("@lastPasswordChangedDate", createDate); cmd.Parameters.AddWithValue("@creationDate", createDate); cmd.Parameters.AddWithValue("@isLockedOut", false); cmd.Parameters.AddWithValue("@lastLockedOutDate", createDate); cmd.Parameters.AddWithValue("@failedPasswordAttemptCount", 0); cmd.Parameters.AddWithValue("@failedPasswordAttemptWindowStart", createDate); cmd.Parameters.AddWithValue("@failedPasswordAnswerAttemptCount", 0); cmd.Parameters.AddWithValue("@failedPasswordAnswerAttemptWindowStart", createDate); int recAdded = cmd.ExecuteNonQuery(); if (recAdded > 0) status = MembershipCreateStatus.Success; else status = MembershipCreateStatus.UserRejected; transaction.Commit(); } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "CreateUser"); status = MembershipCreateStatus.ProviderError; if (transaction != null) transaction.Rollback(); return null; } } return GetUser(username, false); } /// /// Removes a user from the membership data source. /// /// The name of the user to delete. /// true to delete data related to the user from the database; false to leave data related to the user in the database. /// /// true if the user was successfully deleted; otherwise, false. /// public override bool DeleteUser(string username, bool deleteAllRelatedData) { try { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); int userId = GetUserId(conn, username); if (-1 == userId) return false; // if we are supposed to delete all related data, then delegate that to those providers if (deleteAllRelatedData) { MySQLRoleProvider.DeleteUserData(conn, userId); MySQLProfileProvider.DeleteUserData(conn, userId); } string sql = @"DELETE {0}m FROM my_aspnet_Users u, my_aspnet_Membership m WHERE u.id=m.userId AND u.id=@userId"; MySqlCommand cmd = new MySqlCommand( String.Format(sql, deleteAllRelatedData ? "u," : ""), conn); cmd.Parameters.AddWithValue("@appId", app.FetchId(conn)); cmd.Parameters.AddWithValue("@userId", userId); return cmd.ExecuteNonQuery() > 0; } } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "DeleteUser"); throw new ProviderException(exceptionMessage, e); } } /// /// Gets a collection of all the users in the data source in pages of data. /// /// The index of the page of results to return. is zero-based. /// The size of the page of results to return. /// The total number of matched users. /// /// A collection that contains a page of objects beginning at the page specified by . /// public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { return GetUsers(null, null, pageIndex, pageSize, out totalRecords); } /// /// Gets the number of users currently accessing the application. /// /// /// The number of users currently accessing the application. /// public override int GetNumberOfUsersOnline() { TimeSpan onlineSpan = new TimeSpan(0, Membership.UserIsOnlineTimeWindow, 0); DateTime compareTime = DateTime.Now.Subtract(onlineSpan); try { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); MySqlCommand cmd = new MySqlCommand( @"SELECT COUNT(*) FROM my_aspnet_Membership m JOIN my_aspnet_Users u ON m.userId=u.id WHERE m.LastActivityDate > @date AND u.applicationId=@appId", connection); cmd.Parameters.AddWithValue("@date", compareTime); cmd.Parameters.AddWithValue("@appId", app.FetchId(connection)); return Convert.ToInt32(cmd.ExecuteScalar()); } } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "GetNumberOfUsersOnline"); throw new ProviderException(exceptionMessage, e); } } /// /// Gets the password for the specified user name from the data source. /// /// The user to retrieve the password for. /// The password answer for the user. /// /// The password for the specified user name. /// public override string GetPassword(string username, string answer) { if (!EnablePasswordRetrieval) throw new ProviderException(Resources.PasswordRetrievalNotEnabled); try { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); int userId = GetUserId(connection, username); if (-1 == userId) throw new ProviderException("Username not found."); string sql = @"SELECT Password, PasswordAnswer, PasswordKey, PasswordFormat, IsLockedOut FROM my_aspnet_Membership WHERE userId=@userId"; MySqlCommand cmd = new MySqlCommand(sql, connection); cmd.Parameters.AddWithValue("@userId", userId); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { reader.Read(); if (reader.GetBoolean("IsLockedOut")) throw new MembershipPasswordException(Resources.UserIsLockedOut); string password = reader.GetString("Password"); string passwordAnswer = reader.GetValue(reader.GetOrdinal("PasswordAnswer")).ToString(); string passwordKey = reader.GetString("PasswordKey"); MembershipPasswordFormat format = (MembershipPasswordFormat)reader.GetInt32(3); reader.Close(); if (RequiresQuestionAndAnswer && !(CheckPassword(answer, passwordAnswer, passwordKey, format))) { UpdateFailureCount(userId, "PasswordAnswer", connection); throw new MembershipPasswordException(Resources.IncorrectPasswordAnswer); } if (PasswordFormat == MembershipPasswordFormat.Encrypted) { password = UnEncodePassword(password, format); } return password; } } } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "GetPassword"); throw new ProviderException(exceptionMessage, e); } } /// /// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user. /// /// The name of the user to get information for. /// true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user. /// /// A object populated with the specified user's information from the data source. /// public override MembershipUser GetUser(string username, bool userIsOnline) { try { int userId = -1; using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); userId = GetUserId(connection, username); if (-1 == userId) return null; } return GetUser(userId, userIsOnline); } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "GetUser(String, Boolean)"); throw new ProviderException(exceptionMessage, e); } } /// /// Gets user information from the data source based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user. /// /// The unique identifier for the membership user to get information for. /// true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user. /// /// A object populated with the specified user's information from the data source. /// public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { MySqlTransaction txn = null; try { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); txn = connection.BeginTransaction(); MySqlCommand cmd = new MySqlCommand("", connection); cmd.Parameters.AddWithValue("@userId", providerUserKey); if (userIsOnline) { cmd.CommandText = @"UPDATE my_aspnet_Users SET lastActivityDate = @date WHERE id=@userId"; cmd.Parameters.AddWithValue("@date", DateTime.Now); cmd.ExecuteNonQuery(); cmd.CommandText = "UPDATE my_aspnet_Membership SET LastActivityDate=@date WHERE userId=@userId"; cmd.ExecuteNonQuery(); } cmd.CommandText = @"SELECT m.*,u.name FROM my_aspnet_Membership m JOIN my_aspnet_Users u ON m.userId=u.id WHERE u.id=@userId"; MembershipUser user; using (MySqlDataReader reader = cmd.ExecuteReader()) { if (!reader.Read()) return null; user = GetUserFromReader(reader); } txn.Commit(); return user; } } catch (MySqlException e) { if (txn != null) txn.Rollback(); if (WriteExceptionsToEventLog) WriteToEventLog(e, "GetUser(Object, Boolean)"); throw new ProviderException(exceptionMessage); } } /// /// Unlocks the user. /// /// The username. /// true if the membership user was successfully unlocked; /// otherwise, false. A value of false is also returned if the user /// does not exist in the database. public override bool UnlockUser(string username) { try { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); int userId = GetUserId(conn, username); if (-1 == userId) return false; string sql = @"UPDATE my_aspnet_Membership SET IsLockedOut = false, LastLockedOutDate = @lastDate WHERE userId=@userId"; MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.Parameters.AddWithValue("@lastDate", DateTime.Now); cmd.Parameters.AddWithValue("@userId", userId); return cmd.ExecuteNonQuery() > 0; } } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "UnlockUser"); throw new ProviderException(exceptionMessage, e); } } /// /// Gets the user name associated with the specified e-mail address. /// /// The e-mail address to search for. /// /// The user name associated with the specified e-mail address. If no match is found, return null. /// public override string GetUserNameByEmail(string email) { try { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); string sql = @"SELECT u.name FROM my_aspnet_Users u JOIN my_aspnet_Membership m ON m.userid=u.id WHERE m.Email = @email AND u.applicationId=@appId"; MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.Parameters.AddWithValue("@email", email); cmd.Parameters.AddWithValue("@appId", app.FetchId(conn)); return (string)cmd.ExecuteScalar(); } } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "GetUserNameByEmail"); throw new ProviderException(exceptionMessage); } } /// /// Resets a user's password to a new, automatically generated password. /// /// The user to reset the password for. /// The password answer for the specified user. /// The new password for the specified user. public override string ResetPassword(string username, string answer) { if (!(EnablePasswordReset)) throw new NotSupportedException(Resources.PasswordResetNotEnabled); try { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); // fetch the userid first int userId = GetUserId(connection, username); if (-1 == userId) throw new ProviderException(Resources.UsernameNotFound); if (answer == null && RequiresQuestionAndAnswer) { UpdateFailureCount(userId, "PasswordAnswer", connection); throw new ProviderException(Resources.PasswordRequiredForReset); } string newPassword = Membership.GeneratePassword(newPasswordLength, MinRequiredNonAlphanumericCharacters); ValidatePasswordEventArgs Args = new ValidatePasswordEventArgs(username, newPassword, true); OnValidatingPassword(Args); if (Args.Cancel) { if (!(Args.FailureInformation == null)) throw Args.FailureInformation; else throw new MembershipPasswordException(Resources.PasswordResetCanceledNotValid); } MySqlCommand cmd = new MySqlCommand(@"SELECT PasswordAnswer, PasswordKey, PasswordFormat, IsLockedOut FROM my_aspnet_Membership WHERE userId=@userId", connection); cmd.Parameters.AddWithValue("@userId", userId); string passwordKey = String.Empty; MembershipPasswordFormat format; using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { reader.Read(); if (reader.GetBoolean("IsLockedOut")) throw new MembershipPasswordException(Resources.UserIsLockedOut); object passwordAnswer = reader.GetValue(reader.GetOrdinal("PasswordAnswer")); passwordKey = reader.GetString("PasswordKey"); format = (MembershipPasswordFormat)reader.GetByte("PasswordFormat"); reader.Close(); if (RequiresQuestionAndAnswer) { if (!CheckPassword(answer, (string)passwordAnswer, passwordKey, format)) { UpdateFailureCount(userId, "PasswordAnswer", connection); throw new MembershipPasswordException(Resources.IncorrectPasswordAnswer); } } } cmd.CommandText = @"UPDATE my_aspnet_Membership SET Password = @pass, LastPasswordChangedDate = @lastPassChange WHERE userId=@userId"; cmd.Parameters.AddWithValue("@pass", EncodePassword(newPassword, passwordKey, format)); cmd.Parameters.AddWithValue("@lastPassChange", DateTime.Now); int rowsAffected = cmd.ExecuteNonQuery(); if (rowsAffected != 1) throw new MembershipPasswordException(Resources.ErrorResettingPassword); return newPassword; } } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "ResetPassword"); throw new ProviderException(exceptionMessage, e); } } /// /// Updates information about a user in the data source. /// /// A object /// that represents the user to update and the updated information for the user. public override void UpdateUser(MembershipUser user) { try { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); int userId = GetUserId(conn, user.UserName); if (-1 == userId) throw new ProviderException(Resources.UsernameNotFound); string sql = @"UPDATE my_aspnet_Membership m, my_aspnet_Users u SET m.Email=@email, m.Comment=@comment, m.IsApproved=@isApproved, m.LastLoginDate=@lastLoginDate, u.lastActivityDate=@lastActivityDate, m.LastActivityDate=@lastActivityDate WHERE m.userId=u.id AND u.name LIKE @name AND u.applicationId=@appId"; MySqlCommand cmd = new MySqlCommand(sql, conn); cmd.Parameters.AddWithValue("@Email", user.Email); cmd.Parameters.AddWithValue("@Comment", user.Comment); cmd.Parameters.AddWithValue("@isApproved", user.IsApproved); cmd.Parameters.AddWithValue("@lastLoginDate", user.LastLoginDate); cmd.Parameters.AddWithValue("@lastActivityDate", user.LastActivityDate); cmd.Parameters.AddWithValue("@name", user.UserName); cmd.Parameters.AddWithValue("@appId", app.FetchId(conn)); cmd.ExecuteNonQuery(); } } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "UpdateUser"); throw new ProviderException(exceptionMessage); } } /// /// Verifies that the specified user name and password exist in the data source. /// /// The name of the user to validate. /// The password for the specified user. /// /// true if the specified username and password are valid; otherwise, false. /// public override bool ValidateUser(string username, string password) { bool isValid = false; try { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); // first get the user id. If that is -1, then the user doesn't exist // so we just return false since we can't bump any counters int userId = GetUserId(connection, username); if (-1 == userId) return false; string sql = @"SELECT Password, PasswordKey, PasswordFormat, IsApproved, Islockedout FROM my_aspnet_Membership WHERE userId=@userId"; MySqlCommand cmd = new MySqlCommand(sql, connection); cmd.Parameters.AddWithValue("@userId", userId); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (!reader.HasRows) return false; reader.Read(); if (reader.GetBoolean("IsLockedOut")) return false; string pwd = reader.GetString(0); string passwordKey = reader.GetString(1); MembershipPasswordFormat format = (MembershipPasswordFormat) reader.GetInt32(2); bool isApproved = reader.GetBoolean(3); reader.Close(); if (!CheckPassword(password, pwd, passwordKey, format)) UpdateFailureCount(userId, "Password", connection); else if (isApproved) { isValid = true; DateTime currentDate = DateTime.Now; MySqlCommand updateCmd = new MySqlCommand( @"UPDATE my_aspnet_Membership m, my_aspnet_Users u SET m.LastLoginDate = @lastLoginDate, u.lastActivityDate = @date, m.LastActivityDate=@date WHERE m.userId=@userid AND u.id=@userid", connection); updateCmd.Parameters.AddWithValue("@lastLoginDate", currentDate); updateCmd.Parameters.AddWithValue("@date", currentDate); updateCmd.Parameters.AddWithValue("@userid", userId); updateCmd.ExecuteNonQuery(); } } return isValid; } } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "ValidateUser"); throw new ProviderException(exceptionMessage, e); } } /// /// Gets a collection of membership users where the user name contains the specified user name to match. /// /// The user name to search for. /// The index of the page of results to return. is zero-based. /// The size of the page of results to return. /// The total number of matched users. /// /// A collection that contains a page of objects beginning at the page specified by . /// public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { return GetUsers(usernameToMatch, null, pageIndex, pageSize, out totalRecords); } /// /// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match. /// /// The e-mail address to search for. /// The index of the page of results to return. is zero-based. /// The size of the page of results to return. /// The total number of matched users. /// /// A collection that contains a page of objects beginning at the page specified by . /// public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { return GetUsers(null, emailToMatch, pageIndex, pageSize, out totalRecords); } #endregion #region Private Methods private int GetUserId(MySqlConnection connection, string username) { MySqlCommand cmd = new MySqlCommand( "SELECT id FROM my_aspnet_Users WHERE name = @name AND applicationId=@appId", connection); cmd.Parameters.AddWithValue("@name", username); cmd.Parameters.AddWithValue("@appId", app.FetchId(connection)); object id = cmd.ExecuteScalar(); if (id == null) return -1; return (int)id; } private void WriteToEventLog(Exception e, string action) { using (EventLog log = new EventLog()) { log.Source = eventSource; log.Log = eventLog; string message = "An exception occurred communicating with the data source." + Environment.NewLine + Environment.NewLine; message += "Action: " + action + Environment.NewLine + Environment.NewLine; message += "Exception: " + e; log.WriteEntry(message); } } private MembershipUser GetUserFromReader(MySqlDataReader reader) { object providerUserKey = reader.GetInt32("userId"); string username = reader.GetString("name"); string email = null; if (!reader.IsDBNull(reader.GetOrdinal("Email"))) email = reader.GetString("Email"); string passwordQuestion = ""; if (!(reader.GetValue(reader.GetOrdinal("PasswordQuestion")) == DBNull.Value)) passwordQuestion = reader.GetString("PasswordQuestion"); string comment = ""; if (!(reader.GetValue(reader.GetOrdinal("Comment")) == DBNull.Value)) comment = reader.GetString("Comment"); bool isApproved = reader.GetBoolean("IsApproved"); bool isLockedOut = reader.GetBoolean("IsLockedOut"); DateTime creationDate = reader.GetDateTime("CreationDate"); DateTime lastLoginDate = new DateTime(); if (!(reader.GetValue(reader.GetOrdinal("LastLoginDate")) == DBNull.Value)) lastLoginDate = reader.GetDateTime("LastLoginDate"); DateTime lastActivityDate = reader.GetDateTime("LastActivityDate"); DateTime lastPasswordChangedDate = reader.GetDateTime("LastPasswordChangedDate"); DateTime lastLockedOutDate = new DateTime(); if (!(reader.GetValue(reader.GetOrdinal("LastLockedoutDate")) == DBNull.Value)) lastLockedOutDate = reader.GetDateTime("LastLockedoutDate"); MembershipUser u = new MembershipUser(Name, username, providerUserKey, email, passwordQuestion, comment, isApproved, isLockedOut, creationDate, lastLoginDate, lastActivityDate, lastPasswordChangedDate, lastLockedOutDate); return u; } private string UnEncodePassword(string encodedPassword, MembershipPasswordFormat format) { string password = encodedPassword; if (format == MembershipPasswordFormat.Clear) return encodedPassword; else if (format == MembershipPasswordFormat.Encrypted) return Encoding.Unicode.GetString(DecryptPassword( Convert.FromBase64String(password))); else if (format == MembershipPasswordFormat.Hashed) throw new ProviderException(Resources.CannotUnencodeHashedPwd); else throw new ProviderException(Resources.UnsupportedPasswordFormat); } private string GetPasswordKey() { RNGCryptoServiceProvider cryptoProvider = new RNGCryptoServiceProvider(); byte[] key = new byte[16]; cryptoProvider.GetBytes(key); return Convert.ToBase64String(key); } /// /// this method is only necessary because early versions of Mono did not support /// the HashAlgorithmType property /// /// /// private string HashPasswordBytes(byte[] key, byte[] bytes) { HashAlgorithm hash = HashAlgorithm.Create(Membership.HashAlgorithmType); if (hash is KeyedHashAlgorithm) { KeyedHashAlgorithm keyedHash = hash as KeyedHashAlgorithm; keyedHash.Key = key; } return Convert.ToBase64String(hash.ComputeHash(bytes)); } private string EncodePassword(string password, string passwordKey, MembershipPasswordFormat format) { if (password == null) return null; if (format == MembershipPasswordFormat.Clear) return password; byte[] passwordBytes = Encoding.Unicode.GetBytes(password); byte[] keyBytes = Convert.FromBase64String(passwordKey); byte[] keyedBytes = new byte[passwordBytes.Length + keyBytes.Length]; Array.Copy(keyBytes, keyedBytes, keyBytes.Length); Array.Copy(passwordBytes, 0, keyedBytes, keyBytes.Length, passwordBytes.Length); if (format == MembershipPasswordFormat.Encrypted) { byte[] encryptedBytes = EncryptPassword(passwordBytes); return Convert.ToBase64String(encryptedBytes); } else if (format == MembershipPasswordFormat.Hashed) return HashPasswordBytes(keyBytes, keyedBytes); else throw new ProviderException(Resources.UnsupportedPasswordFormat); } private void UpdateFailureCount(int userId, string failureType, MySqlConnection connection) { MySqlCommand cmd = new MySqlCommand( @"SELECT FailedPasswordAttemptCount, FailedPasswordAttemptWindowStart, FailedPasswordAnswerAttemptCount, FailedPasswordAnswerAttemptWindowStart FROM my_aspnet_Membership WHERE userId=@userId", connection); cmd.Parameters.AddWithValue("@userId", userId); DateTime windowStart = new DateTime(); int failureCount = 0; try { using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (!reader.HasRows) throw new ProviderException(Resources.UnableToUpdateFailureCount); reader.Read(); if (failureType == "Password") { failureCount = reader.GetInt32(0); windowStart = reader.GetDateTime(1); } if (failureType == "PasswordAnswer") { failureCount = reader.GetInt32(2); windowStart = reader.GetDateTime(3); } } DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow); if (failureCount == 0 || DateTime.Now > windowEnd) { if (failureType == "Password") { cmd.CommandText = @"UPDATE my_aspnet_Membership SET FailedPasswordAttemptCount = @count, FailedPasswordAttemptWindowStart = @windowStart WHERE userId=@userId"; } if (failureType == "PasswordAnswer") { cmd.CommandText = @"UPDATE my_aspnet_Membership SET FailedPasswordAnswerAttemptCount = @count, FailedPasswordAnswerAttemptWindowStart = @windowStart WHERE userId = @userId"; } cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@count", 1); cmd.Parameters.AddWithValue("@windowStart", DateTime.Now); cmd.Parameters.AddWithValue("@userId", userId); if (cmd.ExecuteNonQuery() < 0) throw new ProviderException(Resources.UnableToUpdateFailureCount); } else { failureCount += 1; if (failureCount >= MaxInvalidPasswordAttempts) { cmd.CommandText = @"UPDATE my_aspnet_Membership SET IsLockedOut = @isLockedOut, LastLockedOutDate = @lastLockedOutDate WHERE userId=@userId"; cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@isLockedOut", true); cmd.Parameters.AddWithValue("@lastLockedOutDate", DateTime.Now); cmd.Parameters.AddWithValue("@userId", userId); if (cmd.ExecuteNonQuery() < 0) throw new ProviderException(Resources.UnableToLockOutUser); } else { if (failureType == "Password") { cmd.CommandText = @"UPDATE my_aspnet_Membership SET FailedPasswordAttemptCount = @count WHERE userId=@userId"; } if (failureType == "PasswordAnswer") { cmd.CommandText = @"UPDATE my_aspnet_Membership SET FailedPasswordAnswerAttemptCount = @count WHERE userId=@userId"; } cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@count", failureCount); cmd.Parameters.AddWithValue("@userId", userId); if (cmd.ExecuteNonQuery() < 0) throw new ProviderException("Unable to update failure count."); } } } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "UpdateFailureCount"); throw new ProviderException(exceptionMessage, e); } } private bool CheckPassword(string password, string dbpassword, string passwordKey, MembershipPasswordFormat format) { password = EncodePassword(password, passwordKey, format); return password == dbpassword; } private void GetPasswordInfo(MySqlConnection connection, int userId, out string passwordKey, out MembershipPasswordFormat passwordFormat) { MySqlCommand cmd = new MySqlCommand( @"SELECT PasswordKey, PasswordFormat FROM my_aspnet_Membership WHERE userId=@userId", connection); cmd.Parameters.AddWithValue("@userId", userId); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); passwordKey = reader.GetString(reader.GetOrdinal("PasswordKey")); passwordFormat = (MembershipPasswordFormat)reader.GetByte( reader.GetOrdinal("PasswordFormat")); } } private MembershipUserCollection GetUsers(string username, string email, int pageIndex, int pageSize, out int totalRecords) { MembershipUserCollection users = new MembershipUserCollection(); try { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); MySqlCommand cmd = new MySqlCommand(); cmd.Connection = connection; string sql = @"SELECT SQL_CALC_FOUND_ROWS u.name,m.* FROM my_aspnet_Users u JOIN my_aspnet_Membership m ON m.userId=u.id WHERE u.applicationId=@appId"; if (username != null) { sql += " AND u.name LIKE @name"; cmd.Parameters.AddWithValue("@name", username); } else if (email != null) { sql += " AND m.Email LIKE @email"; cmd.Parameters.AddWithValue("@email", email); } sql += " ORDER BY u.id ASC LIMIT {0},{1}"; cmd.CommandText = String.Format(sql, pageIndex * pageSize, pageSize); cmd.Parameters.AddWithValue("@appId", app.FetchId(connection)); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) users.Add(GetUserFromReader(reader)); } cmd.CommandText = "SELECT FOUND_ROWS()"; cmd.Parameters.Clear(); totalRecords = Convert.ToInt32(cmd.ExecuteScalar()); } return users; } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "GetUsers"); throw new ProviderException(exceptionMessage); } } private void ValidateQA(string question, string answer) { if (RequiresQuestionAndAnswer && String.IsNullOrEmpty(question)) throw new ArgumentException(Resources.PasswordQuestionInvalid); if (RequiresQuestionAndAnswer && String.IsNullOrEmpty(answer)) throw new ArgumentException(Resources.PasswordAnswerInvalid); } private bool ValidatePassword(string password, string argumentName, bool throwExceptions) { string exceptionString = null; object correctValue = MinRequiredPasswordLength; if (password.Length < MinRequiredPasswordLength) exceptionString = Resources.PasswordNotLongEnough; else { int count = 0; foreach (char c in password) if (!char.IsLetterOrDigit(c)) count++; if (count < MinRequiredNonAlphanumericCharacters) exceptionString = Resources.NotEnoughNonAlphaNumericInPwd; correctValue = MinRequiredNonAlphanumericCharacters; } if (exceptionString != null) { if (throwExceptions) throw new ArgumentException( string.Format(exceptionString, argumentName, correctValue), argumentName); else return false; } if (PasswordStrengthRegularExpression.Length > 0) if (!Regex.IsMatch(password, PasswordStrengthRegularExpression)) return false; return true; } #endregion } } mysql-connector-net-6.4.3/Source/MySql.Web/RoleProvider.cs0000644000175000017500000006362111127003600024147 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12 // The copyright was assigned and transferred under the terms of // the MySQL Contributor License Agreement (CLA) using System; using System.Collections.Specialized; using System.Configuration; using System.Configuration.Provider; using System.Diagnostics; using System.Web.Hosting; using System.Web.Security; using MySql.Data.MySqlClient; using System.Collections.Generic; using MySql.Web.Common; using MySql.Web.Properties; using System.Web; using MySql.Web.General; namespace MySql.Web.Security { /// /// Manages storage of role membership information for an ASP.NET application in a MySQL database. /// public sealed class MySQLRoleProvider : RoleProvider { private string eventSource = "MySQLRoleProvider"; private string eventLog = "Application"; private string exceptionMessage = "An exception occurred. Please check the Event Log."; private ConnectionStringSettings pConnectionStringSettings; private string connectionString; private bool pWriteExceptionsToEventLog = false; private Application app; /// /// Initializes the provider. /// /// The friendly name of the provider. /// A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider. /// The name of the provider is null. /// The name of the provider has a length of zero. /// An attempt is made to call on a provider after the provider has already been initialized. public override void Initialize(string name, NameValueCollection config) { if (config == null) { throw new ArgumentNullException("config"); } if (name == null || name.Length == 0) { name = "MySQLRoleProvider"; } if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "MySQL Role provider"); } base.Initialize(name, config); string applicationName = HostingEnvironment.ApplicationVirtualPath; if (!String.IsNullOrEmpty(config["applicationName"])) applicationName = config["applicationName"]; if (!(config["writeExceptionsToEventLog"] == null)) { if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE") { pWriteExceptionsToEventLog = true; } } pConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]]; if (pConnectionStringSettings != null) connectionString = pConnectionStringSettings.ConnectionString.Trim(); else connectionString = ""; if (String.IsNullOrEmpty(connectionString)) return; // make sure our schema is up to date SchemaManager.CheckSchema(connectionString, config); app = new Application(applicationName, Description); } #region Properties /// /// Gets or sets the name of the application to store and retrieve role information for. /// /// The name of the application to store and retrieve role information for. /// /// /// public override string ApplicationName { get { return app.Name; } set { app.Name = value; } } /// /// Gets or sets a value indicating whether [write exceptions to event log]. /// /// /// true if exceptions should be written to the event log; otherwise, false. /// /// /// /// public bool WriteExceptionsToEventLog { get { return pWriteExceptionsToEventLog; } set { pWriteExceptionsToEventLog = value; } } #endregion #region Public Methods /// /// Adds the users to roles. /// /// The usernames. /// The rolenames. public override void AddUsersToRoles(string[] usernames, string[] rolenames) { if (rolenames == null || rolenames.Length == 0) return; if (usernames == null || usernames.Length == 0) return; foreach (string rolename in rolenames) { if (String.IsNullOrEmpty(rolename)) throw new ArgumentException(Resources.IllegalRoleName, "rolenames"); if (!RoleExists(rolename)) throw new ProviderException(Resources.RoleNameNotFound); } foreach (string username in usernames) { if (String.IsNullOrEmpty(username)) throw new ArgumentException(Resources.IllegalUserName, "usernames"); if (username.IndexOf(',') != -1) throw new ArgumentException(Resources.InvalidCharactersInUserName); foreach (string rolename in rolenames) { if (IsUserInRole(username, rolename)) throw new ProviderException(Resources.UserIsAlreadyInRole); } } using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlTransaction txn = null; try { connection.Open(); txn = connection.BeginTransaction(); MySqlCommand cmd = new MySqlCommand( "INSERT INTO my_aspnet_UsersInRoles VALUES(@userId, @roleId)", connection); cmd.Parameters.Add("@userId", MySqlDbType.Int32); cmd.Parameters.Add("@roleId", MySqlDbType.Int32); foreach (string username in usernames) { // either create a new user or fetch the existing user id int userId = SchemaManager.CreateOrFetchUserId(connection, username, app.FetchId(connection), true); foreach (string rolename in rolenames) { int roleId = GetRoleId(connection, rolename); cmd.Parameters[0].Value = userId; cmd.Parameters[1].Value = roleId; cmd.ExecuteNonQuery(); } } txn.Commit(); } catch (Exception ex) { if (txn != null) txn.Rollback(); if (WriteExceptionsToEventLog) WriteToEventLog(ex, "AddUsersToRoles"); throw; } } } /// /// Creates the role. /// /// The rolename. public override void CreateRole(string rolename) { if (rolename.IndexOf(',') != -1) throw new ArgumentException(Resources.InvalidCharactersInUserName); if (RoleExists(rolename)) throw new ProviderException(Resources.RoleNameAlreadyExists); using (MySqlConnection connection = new MySqlConnection(connectionString)) { try { connection.Open(); MySqlCommand cmd = new MySqlCommand( @"INSERT INTO my_aspnet_Roles Values(NULL, @appId, @name)", connection); cmd.Parameters.AddWithValue("@appId", app.EnsureId(connection)); cmd.Parameters.AddWithValue("@name", rolename); cmd.ExecuteNonQuery(); } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "CreateRole"); throw; } } } /// /// Deletes the role. /// /// The rolename. /// if set to true [throw on populated role]. /// true if the role was successfully deleted; otherwise, false. public override bool DeleteRole(string rolename, bool throwOnPopulatedRole) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlTransaction txn = null; try { if (!(RoleExists(rolename))) throw new ProviderException(Resources.RoleNameNotFound); if (throwOnPopulatedRole && GetUsersInRole(rolename).Length > 0) throw new ProviderException(Resources.CannotDeleteAPopulatedRole); connection.Open(); txn = connection.BeginTransaction(); // first delete all the user/role mappings with that roleid MySqlCommand cmd = new MySqlCommand( @"DELETE uir FROM my_aspnet_UsersInRoles uir JOIN my_aspnet_Roles r ON uir.roleId=r.id WHERE r.name LIKE @rolename AND r.applicationId=@appId", connection); cmd.Parameters.AddWithValue("@rolename", rolename); cmd.Parameters.AddWithValue("@appId", app.FetchId(connection)); cmd.ExecuteNonQuery(); // now delete the role itself cmd.CommandText = @"DELETE FROM my_aspnet_Roles WHERE name=@rolename AND applicationId=@appId"; cmd.ExecuteNonQuery(); txn.Commit(); } catch (Exception ex) { if (txn != null) txn.Rollback(); if (WriteExceptionsToEventLog) WriteToEventLog(ex, "DeleteRole"); throw; } } return true; } /// /// Gets a list of all the roles for the configured applicationName. /// /// /// A string array containing the names of all the roles stored in the data source for the configured applicationName. /// public override string[] GetAllRoles() { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); return GetRolesByUserName(connection, null); } } /// /// Gets a list of the roles that a specified user is in for the configured applicationName. /// /// The user to return a list of roles for. /// /// A string array containing the names of all the roles that the specified user is in for the configured applicationName. /// public override string[] GetRolesForUser(string username) { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); return GetRolesByUserName(connection, username); } } /// /// Gets the users in role. /// /// The rolename. /// A string array containing the names of all the users /// who are members of the specified role. public override string[] GetUsersInRole(string rolename) { List users = new List(); try { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); int roleId = GetRoleId(connection, rolename); string sql = @"SELECT u.name FROM my_aspnet_Users u JOIN my_aspnet_UsersInRoles uir ON uir.userId=u.id AND uir.roleId=@roleId WHERE u.applicationId=@appId"; MySqlCommand cmd = new MySqlCommand(sql, connection); cmd.Parameters.AddWithValue("@roleId", roleId); cmd.Parameters.AddWithValue("@appId", app.FetchId(connection)); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) users.Add(reader.GetString(0)); } } return users.ToArray(); } catch (Exception ex) { if (WriteExceptionsToEventLog) WriteToEventLog(ex, "GetUsersInRole"); throw; } } /// /// Determines whether [is user in role] [the specified username]. /// /// The username. /// The rolename. /// /// true if [is user in role] [the specified username]; otherwise, false. /// public override bool IsUserInRole(string username, string rolename) { try { // this will refresh the app id if necessary if (!RoleExists(rolename)) return false; using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); string sql = @"SELECT COUNT(*) FROM my_aspnet_UsersInRoles uir JOIN my_aspnet_Users u ON uir.userId=u.id JOIN my_aspnet_Roles r ON uir.roleId=r.id WHERE u.applicationId=@appId AND u.name LIKE @userName AND r.name LIKE @roleName"; MySqlCommand cmd = new MySqlCommand(sql, connection); cmd.Parameters.AddWithValue("@appId", app.FetchId(connection)); cmd.Parameters.AddWithValue("@userName", username); cmd.Parameters.AddWithValue("@roleName", rolename); int count = Convert.ToInt32(cmd.ExecuteScalar()); return count > 0; } } catch (Exception ex) { if (WriteExceptionsToEventLog) WriteToEventLog(ex, "IsUserInRole"); throw; } } /// /// Removes the users from roles. /// /// The usernames. /// The rolenames. public override void RemoveUsersFromRoles(string[] usernames, string[] rolenames) { if (rolenames == null || rolenames.Length == 0) return; if (usernames == null || usernames.Length == 0) return; foreach (string rolename in rolenames) { if (!(RoleExists(rolename))) throw new ProviderException(Resources.RoleNameNotFound); } foreach (string username in usernames) { foreach (string rolename in rolenames) { if (!(IsUserInRole(username, rolename))) throw new ProviderException(Resources.UserNotInRole); } } using (MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlTransaction txn = null; try { connection.Open(); txn = connection.BeginTransaction(); string sql = @"DELETE uir FROM my_aspnet_UsersInRoles uir JOIN my_aspnet_Users u ON uir.userId=u.id JOIN my_aspnet_Roles r ON uir.roleId=r.id WHERE u.name LIKE @username AND r.name LIKE @rolename AND u.applicationId=@appId AND r.applicationId=@appId"; MySqlCommand cmd = new MySqlCommand(sql, connection); cmd.Parameters.Add("@username", MySqlDbType.VarChar, 255); cmd.Parameters.Add("@rolename", MySqlDbType.VarChar, 255); cmd.Parameters.AddWithValue("@appId", app.FetchId(connection)); foreach (string username in usernames) { foreach (string rolename in rolenames) { cmd.Parameters[0].Value = username; cmd.Parameters[1].Value = rolename; cmd.ExecuteNonQuery(); } } txn.Commit(); } catch (MySqlException e) { if (txn != null) txn.Rollback(); if (WriteExceptionsToEventLog) WriteToEventLog(e, "RemoveUsersFromRoles"); throw; } } } /// /// Roles the exists. /// /// The rolename. /// true if the role name already exists in the database; otherwise, false. public override bool RoleExists(string rolename) { try { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); MySqlCommand cmd = new MySqlCommand( @"SELECT COUNT(*) FROM my_aspnet_Roles WHERE applicationId=@appId AND name LIKE @name", connection); cmd.Parameters.AddWithValue("@appId", app.FetchId(connection)); cmd.Parameters.AddWithValue("@name", rolename); int count = Convert.ToInt32(cmd.ExecuteScalar()); return count != 0; } } catch (Exception ex) { if (WriteExceptionsToEventLog) WriteToEventLog(ex, "RoleExists"); throw; } } /// /// Finds the users in role. /// /// The rolename. /// The username to match. /// A string array containing the names of all the users where the /// user name matches usernameToMatch and the user is a member of the specified role. public override string[] FindUsersInRole(string rolename, string usernameToMatch) { if (!RoleExists(rolename)) throw new ProviderException(Resources.RoleNameNotFound); List users = new List(); try { using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); string sql = @"SELECT u.name FROM my_aspnet_UsersInRole uir JOIN my_aspnet_Users u ON uir.userId=u.id JOIN my_aspnet_Roles r ON uir.roleId=r.id WHERE r.name LIKE @rolename AND u.name LIKE @username AND u.applicationId=@appId"; MySqlCommand cmd = new MySqlCommand(sql, connection); cmd.Parameters.AddWithValue("@username", usernameToMatch); cmd.Parameters.AddWithValue("@rolename", rolename); cmd.Parameters.AddWithValue("@appId", app.FetchId(connection)); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) users.Add(reader.GetString(0)); } } return users.ToArray(); } catch (MySqlException e) { if (WriteExceptionsToEventLog) WriteToEventLog(e, "FindUsersInRole"); throw; } } #endregion internal static void DeleteUserData(MySqlConnection connection, int userId) { MySqlCommand cmd = new MySqlCommand( "DELETE FROM my_aspnet_UsersInRoles WHERE userId=@userId", connection); cmd.Parameters.AddWithValue("@userId", userId); cmd.ExecuteNonQuery(); } #region Private Methods private string[] GetRolesByUserName(MySqlConnection connection, string username) { List roleList = new List(); try { string sql = "SELECT r.name FROM my_aspnet_Roles r "; if (username != null) sql += "JOIN my_aspnet_UsersInRoles uir ON uir.roleId=r.id AND uir.userId=" + GetUserId(connection, username); sql += " WHERE r.applicationId=@appId"; MySqlCommand cmd = new MySqlCommand(sql, connection); cmd.Parameters.AddWithValue("@appId", app.FetchId(connection)); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) roleList.Add(reader.GetString(0)); } return (string[])roleList.ToArray(); } catch (Exception ex) { if (WriteExceptionsToEventLog) WriteToEventLog(ex, "GetRolesByUserName"); throw; } } private int GetUserId(MySqlConnection connection, string username) { MySqlCommand cmd = new MySqlCommand( "SELECT id FROM my_aspnet_Users WHERE name=@name AND applicationId=@appId", connection); cmd.Parameters.AddWithValue("@name", username); cmd.Parameters.AddWithValue("@appId", app.FetchId(connection)); object id = cmd.ExecuteScalar(); return Convert.ToInt32(id); } private int GetRoleId(MySqlConnection connection, string rolename) { MySqlCommand cmd = new MySqlCommand( "SELECT id FROM my_aspnet_Roles WHERE name=@name AND applicationId=@appId", connection); cmd.Parameters.AddWithValue("@name", rolename); cmd.Parameters.AddWithValue("@appId", app.FetchId(connection)); return (int)cmd.ExecuteScalar(); } private void WriteToEventLog(Exception e, string action) { using (EventLog log = new EventLog()) { log.Source = eventSource; log.Log = eventLog; string message = exceptionMessage + Environment.NewLine + Environment.NewLine; message += "Action: " + action + Environment.NewLine + Environment.NewLine; message += "Exception: " + e; log.WriteEntry(message); } } #endregion } }mysql-connector-net-6.4.3/Source/MySql.Web/SessionProvider.cs0000644000175000017500000010176511127003600024673 0ustar directhexdirecthex// Copyright (c) 2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Configuration; using System.Collections.Specialized; using System.Web.Hosting; using MySql.Data.MySqlClient; using System.Configuration.Provider; using System.IO; using MySql.Web.Common; using MySql.Web.General; using System.Web.SessionState; using System.Web.Configuration; using System.Web; using System.Diagnostics; using System.Threading; using System.Security; namespace MySql.Web.SessionState { /// /// This class allows ASP.NET applications to store and manage session state information in a /// MySQL database. /// Expired session data is periodically deleted from the database. /// public class MySqlSessionStateStore : SessionStateStoreProviderBase { string connectionString; ConnectionStringSettings connectionStringSettings; string eventSource = "MySQLSessionStateStore"; string eventLog = "Application"; string exceptionMessage = "An exception occurred. Please check the event log."; Application app; SessionStateSection sessionStateConfig; // cleanup old session Timer cleanupTimer; int cleanupInterval; bool cleanupRunning; bool writeExceptionsToEventLog = false; /// /// Indicates whether to write exceptions to event log /// public bool WriteExceptionsToEventLog { get { return writeExceptionsToEventLog; } set { writeExceptionsToEventLog = value; } } public string ApplicationName { get { return app.Name; } set { app.Name = value; } } private int ApplicationId { get { return app.Id; } } /// /// Handles MySql exception. /// If WriteExceptionsToEventLog is set, will write exception info /// to event log. /// It throws provider exception (original exception is stored as inner exception) /// /// exception /// name of the function that throwed the exception private void HandleMySqlException(MySqlException e, string action) { if (WriteExceptionsToEventLog) { using (EventLog log = new EventLog()) { log.Source = eventSource; log.Log = eventLog; string message = "An exception occurred communicating with the data source.\n\n"; message += "Action: " + action; message += "Exception: " + e.ToString(); log.WriteEntry(message); } } throw new ProviderException(exceptionMessage, e); } /// /// Initializes the provider with the property values specified in the ASP.NET application configuration file /// /// The name of the provider instance to initialize. /// Object that contains the names and values of configuration options for the provider. /// public override void Initialize(string name, NameValueCollection config) { //Initialize values from web.config. if (config == null) throw new ArgumentException("config"); if (name == null || name.Length == 0) throw new ArgumentException("name"); if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config["description"] = "MySQL Session State Store Provider"; } base.Initialize(name, config); string applicationName = HostingEnvironment.ApplicationVirtualPath; if (!String.IsNullOrEmpty(config["applicationName"])) applicationName = config["applicationName"]; // Get configuration element. Configuration webConfig = WebConfigurationManager.OpenWebConfiguration(HostingEnvironment.ApplicationVirtualPath); sessionStateConfig = (SessionStateSection)webConfig.SectionGroups["system.web"].Sections["sessionState"]; // Initialize connection. connectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]]; if (connectionStringSettings == null || connectionStringSettings.ConnectionString.Trim() == "") throw new HttpException("Connection string can not be blank"); connectionString = connectionStringSettings.ConnectionString; writeExceptionsToEventLog = false; if (config["writeExceptionsToEventLog"] != null) { writeExceptionsToEventLog = (config["writeExceptionsToEventLog"].ToUpper() == "TRUE"); } // Make sure we have the correct schema. SchemaManager.CheckSchema(connectionString, config); app = new Application(applicationName, base.Description); // Get the application id. try { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); app.EnsureId(conn); CheckStorageEngine(conn); cleanupInterval = GetCleanupInterval(conn); } } catch (MySqlException e) { HandleMySqlException(e, "Initialize"); } // Setup the cleanup timer if (cleanupInterval <= 0) cleanupInterval = 1; cleanupTimer = new Timer(new TimerCallback(CleanupOldSessions), null, 0, cleanupInterval * 1000 * 60); } /// /// This method creates a new SessionStateStoreData object for the current request. /// /// /// The HttpContext object for the current request. /// /// /// The timeout value (in minutes) for the SessionStateStoreData object that is created. /// public override SessionStateStoreData CreateNewStoreData(System.Web.HttpContext context, int timeout) { return new SessionStateStoreData(new SessionStateItemCollection(), SessionStateUtility.GetSessionStaticObjects(context), timeout); } /// /// This method adds a new session state item to the database. /// /// /// The HttpContext object for the current request. /// /// /// The session ID for the current request. /// /// /// The timeout value for the current request. /// public override void CreateUninitializedItem(System.Web.HttpContext context, string id, int timeout) { try { using (MySqlConnection conn = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand( "INSERT INTO my_aspnet_Sessions" + " (SessionId, ApplicationId, Created, Expires, LockDate," + " LockId, Timeout, Locked, SessionItems, Flags)" + " Values (@SessionId, @ApplicationId, NOW(), NOW() + INTERVAL @Timeout MINUTE, NOW()," + " @LockId , @Timeout, @Locked, @SessionItems, @Flags)", conn); cmd.Parameters.AddWithValue("@SessionId", id); cmd.Parameters.AddWithValue("@ApplicationId", ApplicationId); cmd.Parameters.AddWithValue("@LockId", 0); cmd.Parameters.AddWithValue("@Timeout", timeout); cmd.Parameters.AddWithValue("@Locked", 0); cmd.Parameters.AddWithValue("@SessionItems", null); cmd.Parameters.AddWithValue("@Flags", 1); conn.Open(); cmd.ExecuteNonQuery(); } } catch (MySqlException e) { HandleMySqlException(e, "CreateUninitializedItem"); } } /// /// This method releases all the resources for this instance. /// public override void Dispose() { if (cleanupTimer != null) cleanupTimer.Dispose(); } /// /// This method allows the MySqlSessionStateStore object to perform any cleanup that may be /// required for the current request. /// /// The HttpContext object for the current request public override void EndRequest(System.Web.HttpContext context) { } /// /// This method returns a read-only session item from the database. /// public override SessionStateStoreData GetItem(System.Web.HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions) { return GetSessionStoreItem(false, context, id, out locked, out lockAge, out lockId, out actions); } /// /// This method locks a session item and returns it from the database /// /// The HttpContext object for the current request /// The session ID for the current request /// /// true if the session item is locked in the database; otherwise, it is false. /// /// /// TimeSpan object that indicates the amount of time the session item has been locked in the database. /// /// /// A lock identifier object. /// /// /// A SessionStateActions enumeration value that indicates whether or /// not the session is uninitialized and cookieless. /// /// public override SessionStateStoreData GetItemExclusive(System.Web.HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions) { return GetSessionStoreItem(true, context, id, out locked, out lockAge, out lockId, out actions); } /// /// This method performs any per-request initializations that the MySqlSessionStateStore provider requires. /// public override void InitializeRequest(System.Web.HttpContext context) { } /// /// This method forcibly releases the lock on a session item in the database, if multiple attempts to /// retrieve the session item fail. /// /// The HttpContext object for the current request. /// The session ID for the current request. /// The lock identifier for the current request. public override void ReleaseItemExclusive(System.Web.HttpContext context, string id, object lockId) { try { using (MySqlConnection conn = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand( "UPDATE my_aspnet_Sessions SET Locked = 0, Expires = NOW() + INTERVAL @Timeout MINUTE " + "WHERE SessionId = @SessionId AND ApplicationId = @ApplicationId AND LockId = @LockId", conn); cmd.Parameters.AddWithValue("@Timeout", sessionStateConfig.Timeout.TotalMinutes); cmd.Parameters.AddWithValue("@SessionId", id); cmd.Parameters.AddWithValue("@ApplicationId", ApplicationId); cmd.Parameters.AddWithValue("@LockId", lockId); conn.Open(); cmd.ExecuteNonQuery(); } } catch (MySqlException e) { HandleMySqlException(e, "ReleaseItemExclusive"); } } /// /// This method removes the specified session item from the database /// /// The HttpContext object for the current request /// The session ID for the current request /// The lock identifier for the current request. /// The session item to remove from the database. public override void RemoveItem(System.Web.HttpContext context, string id, object lockId, SessionStateStoreData item) { try { using (MySqlConnection conn = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand("DELETE FROM my_aspnet_Sessions " + " WHERE SessionId = @SessionId AND ApplicationId = @ApplicationId AND LockId = @LockId", conn); cmd.Parameters.AddWithValue("@SessionId", id); cmd.Parameters.AddWithValue("@ApplicationId", ApplicationId); cmd.Parameters.AddWithValue("@LockId", lockId); conn.Open(); cmd.ExecuteNonQuery(); } } catch (MySqlException e) { HandleMySqlException(e, "RemoveItem"); } } /// /// This method resets the expiration date and timeout for a session item in the database. /// /// The HttpContext object for the current request /// The session ID for the current request public override void ResetItemTimeout(System.Web.HttpContext context, string id) { try { using (MySqlConnection conn = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand( "UPDATE my_aspnet_Sessions SET Expires = NOW() + INTERVAL @Timeout MINUTE" + " WHERE SessionId = @SessionId AND ApplicationId = @ApplicationId", conn); cmd.Parameters.AddWithValue("@Timeout", sessionStateConfig.Timeout.TotalMinutes); cmd.Parameters.AddWithValue("@SessionId", id); cmd.Parameters.AddWithValue("@ApplicationId", ApplicationId); conn.Open(); cmd.ExecuteNonQuery(); } } catch (MySqlException e) { HandleMySqlException(e, "ResetItemTimeout"); } } /// /// This method updates the session time information in the database with the specified session item, /// and releases the lock. /// /// The HttpContext object for the current request /// The session ID for the current request /// The session item containing new values to update the session item in the database with. /// /// The lock identifier for the current request. /// A Boolean value that indicates whether or not the session item is new in the database. /// A false value indicates an existing item. /// public override void SetAndReleaseItemExclusive(System.Web.HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem) { try { using (MySqlConnection conn = new MySqlConnection(connectionString)) { // Serialize the SessionStateItemCollection as a byte array byte[] sessItems = Serialize((SessionStateItemCollection)item.Items); MySqlCommand cmd; if (newItem) { //Insert the new session item . If there was expired session //with the same SessionId and Application id, it will be removed cmd = new MySqlCommand( "REPLACE INTO my_aspnet_Sessions (SessionId, ApplicationId, Created, Expires," + " LockDate, LockId, Timeout, Locked, SessionItems, Flags)" + " Values(@SessionId, @ApplicationId, NOW(), NOW() + INTERVAL @Timeout MINUTE, NOW()," + " @LockId , @Timeout, @Locked, @SessionItems, @Flags)", conn); cmd.Parameters.AddWithValue("@SessionId", id); cmd.Parameters.AddWithValue("@ApplicationId", ApplicationId); cmd.Parameters.AddWithValue("@Timeout", item.Timeout); cmd.Parameters.AddWithValue("@LockId", 0); cmd.Parameters.AddWithValue("@Locked", 0); cmd.Parameters.AddWithValue("@SessionItems", sessItems); cmd.Parameters.AddWithValue("@Flags", 0); } else { //Update the existing session item. cmd = new MySqlCommand( "UPDATE my_aspnet_Sessions SET Expires = NOW() + INTERVAL @Timeout MINUTE," + " SessionItems = @SessionItems, Locked = @Locked " + " WHERE SessionId = @SessionId AND ApplicationId = @ApplicationId AND LockId = @LockId", conn); cmd.Parameters.AddWithValue("@Timeout", item.Timeout); cmd.Parameters.AddWithValue("@SessionItems", sessItems); cmd.Parameters.AddWithValue("@Locked", 0); cmd.Parameters.AddWithValue("@SessionId", id); cmd.Parameters.AddWithValue("@ApplicationId", ApplicationId); cmd.Parameters.AddWithValue("@LockId", lockId); } conn.Open(); cmd.ExecuteNonQuery(); } } catch (MySqlException e) { HandleMySqlException(e, "SetAndReleaseItemExclusive"); } } /// /// GetSessionStoreItem is called by both the GetItem and GetItemExclusive methods. GetSessionStoreItem /// retrieves the session data from the data source. If the lockRecord parameter is true (in the case of /// GetItemExclusive), then GetSessionStoreItem locks the record and sets a New LockId and LockDate. /// private SessionStateStoreData GetSessionStoreItem(bool lockRecord, HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actionFlags) { // Initial values for return value and out parameters. SessionStateStoreData item = null; lockAge = TimeSpan.Zero; lockId = null; locked = false; actionFlags = SessionStateActions.None; // MySqlCommand for database commands. MySqlCommand cmd = null; // serialized SessionStateItemCollection. byte[] serializedItems = null; // True if a record is found in the database. bool foundRecord = false; // True if the returned session item is expired and needs to be deleted. bool deleteData = false; // Timeout value from the data store. int timeout = 0; try { using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); // lockRecord is True when called from GetItemExclusive and // False when called from GetItem. // Obtain a lock if possible. Ignore the record if it is expired. if (lockRecord) { cmd = new MySqlCommand( "UPDATE my_aspnet_Sessions SET " + " Locked = 1, LockDate = NOW()" + " WHERE SessionId = @SessionId AND ApplicationId = @ApplicationId AND" + " Locked = 0 AND Expires > NOW()", conn); cmd.Parameters.AddWithValue("@SessionId", id); cmd.Parameters.AddWithValue("@ApplicationId", ApplicationId); if (cmd.ExecuteNonQuery() == 0) { // No record was updated because the record was locked or not found. locked = true; } else { // The record was updated. locked = false; } } // Retrieve the current session item information. cmd = new MySqlCommand( "SELECT NOW(), Expires , SessionItems, LockId, Flags, Timeout, " + " LockDate " + " FROM my_aspnet_Sessions" + " WHERE SessionId = @SessionId AND ApplicationId = @ApplicationId", conn); cmd.Parameters.AddWithValue("@SessionId", id); cmd.Parameters.AddWithValue("@ApplicationId", ApplicationId); // Retrieve session item data from the data source. using (MySqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { DateTime now = reader.GetDateTime(0); DateTime expires = reader.GetDateTime(1); if (now.CompareTo(expires) > 0) { //The record was expired. Mark it as not locked. locked = false; // The session was expired. Mark the data for deletion. deleteData = true; } else { foundRecord = true; } object items = reader.GetValue(2); serializedItems = (items is DBNull) ? null : (byte[])items; lockId = reader.GetValue(3); if (lockId is DBNull) lockId = (int)0; actionFlags = (SessionStateActions)(reader.GetInt32(4)); timeout = reader.GetInt32(5); DateTime lockDate = reader.GetDateTime(6); lockAge = now.Subtract(lockDate); } } //If the returned session item is expired, // delete the record from the data source. if (deleteData) { cmd = new MySqlCommand("DELETE FROM my_aspnet_Sessions" + " WHERE SessionId = @SessionId AND ApplicationId = @ApplicationId", conn); cmd.Parameters.AddWithValue("@SessionId", id); cmd.Parameters.AddWithValue("@ApplicationId", ApplicationId); cmd.ExecuteNonQuery(); } // The record was not found. Ensure that locked is false. if (!foundRecord) locked = false; // If the record was found and you obtained a lock, then set // the lockId, clear the actionFlags, // and create the SessionStateStoreItem to return. if (foundRecord && !locked) { lockId = (int)(lockId) + 1; cmd = new MySqlCommand("UPDATE my_aspnet_Sessions SET" + " LockId = @LockId, Flags = 0 " + " WHERE SessionId = @SessionId AND ApplicationId = @ApplicationId", conn); cmd.Parameters.AddWithValue("@LockId", lockId); cmd.Parameters.AddWithValue("@SessionId", id); cmd.Parameters.AddWithValue("@ApplicationId", ApplicationId); cmd.ExecuteNonQuery(); // If the actionFlags parameter is not InitializeItem, // deserialize the stored SessionStateItemCollection. if (actionFlags == SessionStateActions.InitializeItem) { item = CreateNewStoreData(context, (int)sessionStateConfig.Timeout.TotalMinutes); } else { item = Deserialize(context, serializedItems, timeout); } } } } catch (MySqlException e) { HandleMySqlException(e, "GetSessionStoreItem"); } return item; } /// /// This method returns a false value to indicate that callbacks for expired sessions are not supported. /// /// /// false public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback) { return false; } /// /// Serialize is called by the SetAndReleaseItemExclusive method to /// convert the SessionStateItemCollection into a byte array to /// be stored in the blob field. /// private byte[] Serialize(SessionStateItemCollection items) { MemoryStream ms = new MemoryStream(); BinaryWriter writer = new BinaryWriter(ms); if (items != null) { items.Serialize(writer); } writer.Close(); return ms.ToArray(); } /// /// Deserialize is called by the GetSessionStoreItem method to /// convert the byte array stored in the blob field to a /// SessionStateItemCollection. /// private SessionStateStoreData Deserialize(HttpContext context, byte[] serializedItems, int timeout) { SessionStateItemCollection sessionItems = new SessionStateItemCollection(); if (serializedItems != null) { MemoryStream ms = new MemoryStream(serializedItems); if (ms.Length > 0) { BinaryReader reader = new BinaryReader(ms); sessionItems = SessionStateItemCollection.Deserialize(reader); } } return new SessionStateStoreData(sessionItems, SessionStateUtility.GetSessionStaticObjects(context), timeout); } private void CleanupOldSessions(object o) { if (cleanupRunning) return; cleanupRunning = true; try { using (MySqlConnection con = new MySqlConnection(connectionString)) { con.Open(); MySqlCommand cmd = new MySqlCommand( "UPDATE my_aspnet_SessionCleanup SET LastRun=NOW() where" + " LastRun + INTERVAL IntervalMinutes MINUTE < NOW()", con); if (cmd.ExecuteNonQuery() > 0) { cmd = new MySqlCommand( "DELETE FROM my_aspnet_Sessions WHERE Expires < NOW()", con); cmd.ExecuteNonQuery(); } } } catch (MySqlException e) { HandleMySqlException(e, "CleanupOldSessions"); } finally { cleanupRunning = false; } } int GetCleanupInterval(MySqlConnection con) { MySqlCommand cmd = new MySqlCommand("SELECT IntervalMinutes from my_aspnet_SessionCleanup", con); return (int)cmd.ExecuteScalar(); } /// /// Check storage engine used by my_aspnet_Sessions. /// Warn if MyISAM is used - it does not handle concurrent updates well /// which is important for session provider, as each access to session /// does an update to "expires" field. /// /// private void CheckStorageEngine(MySqlConnection con) { try { MySqlCommand cmd = new MySqlCommand( "SELECT ENGINE FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='my_aspnet_Sessions'", con); using (MySqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { string engine = reader.GetString(0); if (engine == "MyISAM") { string message = "Storage engine for table my_aspnet_Sessions is MyISAM." + "If possible, please change it to a transactional storage engine " + "to improve performance,e.g with 'alter table my_aspnet_Sessions engine innodb'\n"; try { using (EventLog log = new EventLog()) { log.Source = eventSource; log.Log = eventLog; log.WriteEntry(message); } } catch (SecurityException) { // Can't write to event log due to security restrictions Trace.WriteLine(message); } } } } } catch (MySqlException e) { Trace.Write("got exception while checking for engine" + e); } } } }mysql-connector-net-6.4.3/Source/MySql.Web/ProfileProvider.cs0000644000175000017500000007666211127003600024657 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12 // The copyright was assigned and transferred under the terms of // the MySQL Contributor License Agreement (CLA) using System; using System.Web.Profile; using System.Configuration; using System.Collections.Specialized; using System.Web.Hosting; using MySql.Data.MySqlClient; using System.Configuration.Provider; using System.Collections; using System.Collections.Generic; using System.Text; using System.Data; using System.IO; using System.Globalization; using System.Web.Security; using MySql.Web.Common; using MySql.Web.Properties; using MySql.Web.General; namespace MySql.Web.Profile { /// /// /// public class MySQLProfileProvider : ProfileProvider { private string connectionString; private Application app; #region Abstract Members /// /// Initializes the provider. /// /// The friendly name of the provider. /// A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider. /// The name of the provider is null. /// The name of the provider has a length of zero. /// An attempt is made to call on a provider after the provider has already been initialized. public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "MySQLProfileProvider"; if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "MySQL Profile provider"); } base.Initialize(name, config); try { string applicationName = GetConfigValue(config["applicationName"], HostingEnvironment.ApplicationVirtualPath); connectionString = ""; ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[ config["connectionStringName"]]; if (ConnectionStringSettings != null) connectionString = ConnectionStringSettings.ConnectionString.Trim(); if (String.IsNullOrEmpty(connectionString)) return; // make sure our schema is up to date SchemaManager.CheckSchema(connectionString, config); app = new Application(applicationName, base.Description); } catch (Exception ex) { throw new ProviderException(Resources.ErrorInitProfileProvider, ex); } } /// /// When overridden in a derived class, deletes all user-profile data /// for profiles in which the last activity date occurred before the /// specified date. /// /// One of the /// /// values, specifying whether anonymous, authenticated, or both /// types of profiles are deleted. /// A /// that identifies which user profiles are considered inactive. If the /// /// value of a user profile occurs on or before this date and time, the /// profile is considered inactive. /// /// The number of profiles deleted from the data source. /// public override int DeleteInactiveProfiles( ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { using (MySqlConnection c = new MySqlConnection(connectionString)) { c.Open(); MySqlCommand queryCmd = new MySqlCommand( @"SELECT * FROM my_aspnet_Users WHERE applicationId=@appId AND lastActivityDate < @lastActivityDate", c); queryCmd.Parameters.AddWithValue("@appId", app.FetchId(c)); queryCmd.Parameters.AddWithValue("@lastActivityDate", userInactiveSinceDate); if (authenticationOption == ProfileAuthenticationOption.Anonymous) queryCmd.CommandText += " AND isAnonymous = 1"; else if (authenticationOption == ProfileAuthenticationOption.Authenticated) queryCmd.CommandText += " AND isAnonymous = 0"; MySqlCommand deleteCmd = new MySqlCommand( "DELETE FROM my_aspnet_Profiles WHERE userId = @userId", c); deleteCmd.Parameters.Add("@userId", MySqlDbType.UInt64); List uidList = new List(); using (MySqlDataReader reader = queryCmd.ExecuteReader()) { while (reader.Read()) uidList.Add(reader.GetUInt64("userId")); } int count = 0; foreach (ulong uid in uidList) { deleteCmd.Parameters[0].Value = uid; count += deleteCmd.ExecuteNonQuery(); } return count; } } /// /// When overridden in a derived class, deletes profile properties /// and information for profiles that match the supplied list of user names. /// /// A string array of user names for /// profiles to be deleted. /// /// The number of profiles deleted from the data source. /// public override int DeleteProfiles(string[] usernames) { using (MySqlConnection c = new MySqlConnection(connectionString)) { c.Open(); MySqlCommand queryCmd = new MySqlCommand( @"SELECT * FROM my_aspnet_Users WHERE applicationId=@appId AND name = @name", c); queryCmd.Parameters.AddWithValue("@appId", app.FetchId(c)); queryCmd.Parameters.Add("@name", MySqlDbType.VarChar); MySqlCommand deleteCmd = new MySqlCommand( "DELETE FROM my_aspnet_Profiles WHERE userId = @userId", c); deleteCmd.Parameters.Add("@userId", MySqlDbType.UInt64); int count = 0; foreach (string name in usernames) { queryCmd.Parameters[1].Value = name; ulong uid = (ulong)queryCmd.ExecuteScalar(); deleteCmd.Parameters[0].Value = uid; count += deleteCmd.ExecuteNonQuery(); } return count; } } /// /// When overridden in a derived class, deletes profile properties /// and information for the supplied list of profiles. /// /// A /// of /// information about profiles that are to be deleted. /// /// The number of profiles deleted from the data source. /// public override int DeleteProfiles(ProfileInfoCollection profiles) { string[] s = new string[profiles.Count]; int i = 0; foreach (ProfileInfo p in profiles) s[i++] = p.UserName; return DeleteProfiles(s); } /// /// When overridden in a derived class, retrieves profile information /// for profiles in which the last activity date occurred on or before /// the specified date and the user name matches the specified user name. /// /// One of the /// values, /// specifying whether anonymous, authenticated, or both types of profiles /// are returned. /// The user name to search for. /// A /// that identifies which user profiles are considered inactive. If the /// value /// of a user profile occurs on or before this date and time, the profile /// is considered inactive. /// The index of the page of results to return. /// The size of the page of results to return. /// When this method returns, contains the total /// number of profiles. /// /// A containing /// user profile information for inactive profiles where the user name /// matches the supplied parameter. /// public override ProfileInfoCollection FindInactiveProfilesByUserName( ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { return GetProfiles(authenticationOption, usernameToMatch, userInactiveSinceDate, pageIndex, pageSize, out totalRecords); } /// /// When overridden in a derived class, retrieves profile information /// for profiles in which the user name matches the specified user names. /// /// One of the /// values, /// specifying whether anonymous, authenticated, or both types of profiles /// are returned. /// The user name to search for. /// The index of the page of results to return. /// The size of the page of results to return. /// When this method returns, contains the total /// number of profiles. /// /// A containing /// user-profile information for profiles where the user name matches the /// supplied parameter. /// public override ProfileInfoCollection FindProfilesByUserName( ProfileAuthenticationOption authenticationOption, string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { return GetProfiles(authenticationOption, usernameToMatch, DateTime.MinValue, pageIndex, pageSize, out totalRecords); } /// /// When overridden in a derived class, retrieves user-profile data /// from the data source for profiles in which the last activity date /// occurred on or before the specified date. /// /// One of the /// values, /// specifying whether anonymous, authenticated, or both types of profiles /// are returned. /// A /// that identifies which user profiles are considered inactive. If the /// of /// a user profile occurs on or before this date and time, the profile is /// considered inactive. /// The index of the page of results to return. /// The size of the page of results to return. /// When this method returns, contains the /// total number of profiles. /// /// A containing user-profile information about the inactive profiles. /// public override ProfileInfoCollection GetAllInactiveProfiles( ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { return GetProfiles(authenticationOption, null, userInactiveSinceDate, pageIndex, pageSize, out totalRecords); } /// /// When overridden in a derived class, retrieves user profile data for /// all profiles in the data source. /// /// One of the /// values, /// specifying whether anonymous, authenticated, or both types of profiles /// are returned. /// The index of the page of results to return. /// The size of the page of results to return. /// When this method returns, contains the /// total number of profiles. /// /// A containing /// user-profile information for all profiles in the data source. /// public override ProfileInfoCollection GetAllProfiles( ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, out int totalRecords) { return GetProfiles(authenticationOption, null, DateTime.MinValue, pageIndex, pageSize, out totalRecords); } /// /// When overridden in a derived class, returns the number of profiles /// in which the last activity date occurred on or before the specified /// date. /// /// One of the /// values, /// specifying whether anonymous, authenticated, or both types of profiles /// are returned. /// A /// that identifies which user profiles are considered inactive. If the /// of /// a user profile occurs on or before this date and time, the profile /// is considered inactive. /// /// The number of profiles in which the last activity date occurred on /// or before the specified date. /// public override int GetNumberOfInactiveProfiles( ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { using (MySqlConnection c = new MySqlConnection(connectionString)) { c.Open(); MySqlCommand queryCmd = new MySqlCommand( @"SELECT COUNT(*) FROM my_aspnet_Users WHERE applicationId = @appId AND lastActivityDate < @lastActivityDate", c); queryCmd.Parameters.AddWithValue("@appId", app.FetchId(c)); queryCmd.Parameters.AddWithValue("@lastActivityDate", userInactiveSinceDate); if (authenticationOption == ProfileAuthenticationOption.Anonymous) queryCmd.CommandText += " AND isAnonymous = 1"; else if (authenticationOption == ProfileAuthenticationOption.Authenticated) queryCmd.CommandText += " AND isAnonymous = 0"; return (int)queryCmd.ExecuteScalar(); } } /// /// Gets or sets the name of the currently running application. /// /// /// A that contains the application's shortened name, which does not contain a full path or extension, for example, SimpleAppSettings. public override string ApplicationName { get { return app.Name; } set { app.Name = value; } } /// /// Returns the collection of settings property values for the specified application instance and settings property group. /// /// A describing the current application use. /// A containing the settings property group whose values are to be retrieved. /// /// A containing the values for the specified settings property group. /// public override SettingsPropertyValueCollection GetPropertyValues( SettingsContext context, SettingsPropertyCollection collection) { SettingsPropertyValueCollection values = new SettingsPropertyValueCollection(); if (collection.Count < 1) return values; string username = (string)context["UserName"]; foreach (SettingsProperty property in collection) { if (property.PropertyType.IsPrimitive || property.PropertyType == typeof(string)) property.SerializeAs = SettingsSerializeAs.String; else property.SerializeAs = SettingsSerializeAs.Xml; values.Add(new SettingsPropertyValue(property)); } if (String.IsNullOrEmpty(username)) return values; // retrieve encoded profile data from the database try { using (MySqlConnection c = new MySqlConnection(connectionString)) { c.Open(); MySqlCommand cmd = new MySqlCommand( @"SELECT * FROM my_aspnet_Profiles p JOIN my_aspnet_Users u ON u.id = p.userId WHERE u.applicationId = @appId AND u.name = @name", c); cmd.Parameters.AddWithValue("@appId", app.FetchId(c)); cmd.Parameters.AddWithValue("@name", username); MySqlDataAdapter da = new MySqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count > 0) DecodeProfileData(dt.Rows[0], values); return values; } } catch (Exception ex) { throw new ProviderException(Resources.UnableToRetrieveProfileData, ex); } } /// /// Sets the values of the specified group of property settings. /// /// A describing the current application usage. /// A representing the group of property settings to set. public override void SetPropertyValues( SettingsContext context, SettingsPropertyValueCollection collection) { bool isAuthenticated = (bool)context["IsAuthenticated"]; string username = (string)context["UserName"]; if (String.IsNullOrEmpty(username)) return; if (collection.Count < 1) return; string index = String.Empty; string stringData = String.Empty; byte[] binaryData = null; int count = EncodeProfileData(collection, isAuthenticated, ref index, ref stringData, ref binaryData); if (count < 1) return; MySqlTransaction txn = null; // save the encoded profile data to the database using (MySqlConnection connection = new MySqlConnection(connectionString)) { try { connection.Open(); txn = connection.BeginTransaction(); // either create a new user or fetch the existing user id int userId = SchemaManager.CreateOrFetchUserId(connection, username, app.EnsureId(connection), isAuthenticated); MySqlCommand cmd = new MySqlCommand( @"INSERT INTO my_aspnet_Profiles VALUES (@userId, @index, @stringData, @binaryData, NULL) ON DUPLICATE KEY UPDATE valueindex=VALUES(valueindex), stringdata=VALUES(stringdata), binarydata=VALUES(binarydata)", connection); cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@userId", userId); cmd.Parameters.AddWithValue("@index", index); cmd.Parameters.AddWithValue("@stringData", stringData); cmd.Parameters.AddWithValue("@binaryData", binaryData); count = cmd.ExecuteNonQuery(); if (count == 0) throw new Exception(Resources.ProfileUpdateFailed); txn.Commit(); } catch (Exception ex) { if (txn != null) txn.Rollback(); throw new ProviderException(Resources.ProfileUpdateFailed, ex); } } } #endregion internal static void DeleteUserData(MySqlConnection connection, int userId) { MySqlCommand cmd = new MySqlCommand( "DELETE FROM my_aspnet_Profiles WHERE userId=@userId", connection); cmd.Parameters.AddWithValue("@userId", userId); cmd.ExecuteNonQuery(); } #region Private Methods private void DecodeProfileData(DataRow profileRow, SettingsPropertyValueCollection values) { string indexData = (string)profileRow["valueindex"]; string stringData = (string)profileRow["stringData"]; byte[] binaryData = (byte[])profileRow["binaryData"]; if (indexData == null) return; string[] indexes = indexData.Split(':'); foreach (string index in indexes) { string[] parts = index.Split('/'); SettingsPropertyValue value = values[parts[0]]; if (value == null) continue; int pos = Int32.Parse(parts[2], CultureInfo.InvariantCulture); int len = Int32.Parse(parts[3], CultureInfo.InvariantCulture); if (len == -1) { value.PropertyValue = null; value.IsDirty = false; value.Deserialized = true; } else if (parts[1].Equals("0")) value.SerializedValue = stringData.Substring(pos, len); else { byte[] buf = new byte[len]; Buffer.BlockCopy(binaryData, pos, buf, 0, len); value.SerializedValue = buf; } } } private int EncodeProfileData(SettingsPropertyValueCollection collection, bool isAuthenticated, ref string index, ref string stringData, ref byte[] binaryData) { bool itemsToSave = false; // first we need to determine if there are any items that need saving // this is an optimization foreach (SettingsPropertyValue value in collection) { if (!value.IsDirty) continue; if (value.Property.Attributes["AllowAnonymous"].Equals(false) && !isAuthenticated) continue; itemsToSave = true; break; } if (!itemsToSave) return 0; StringBuilder indexBuilder = new StringBuilder(); StringBuilder stringDataBuilder = new StringBuilder(); MemoryStream binaryBuilder = new MemoryStream(); int count = 0; // ok, we have some values that need to be saved so we go back through foreach (SettingsPropertyValue value in collection) { // if the value has not been written to and is still using the default value // no need to save it if (value.UsingDefaultValue && !value.IsDirty) continue; // we don't save properties that require the user to be authenticated when the // current user is not authenticated. if (value.Property.Attributes["AllowAnonymous"].Equals(false) && !isAuthenticated) continue; count++; object propValue = value.SerializedValue; if ((value.Deserialized && value.PropertyValue == null) || value.SerializedValue == null) indexBuilder.AppendFormat("{0}//0/-1:", value.Name); else if (propValue is string) { indexBuilder.AppendFormat("{0}/0/{1}/{2}:", value.Name, stringDataBuilder.Length, (propValue as string).Length); stringDataBuilder.Append(propValue); } else { byte[] binaryValue = (byte[])propValue; indexBuilder.AppendFormat("{0}/1/{1}/{2}:", value.Name, binaryBuilder.Position, binaryValue.Length); binaryBuilder.Write(binaryValue, 0, binaryValue.Length); } } index = indexBuilder.ToString(); stringData = stringDataBuilder.ToString(); binaryData = binaryBuilder.ToArray(); return count; } private ProfileInfoCollection GetProfiles( ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { List whereClauses = new List(); using (MySqlConnection c = new MySqlConnection(connectionString)) { c.Open(); MySqlCommand cmd = new MySqlCommand( @"SELECT p.*, u.name, u.isAnonymous, u.lastActivityDate, LENGTH(p.stringdata) + LENGTH(p.binarydata) AS profilesize FROM my_aspnet_Profiles p JOIN my_aspnet_Users u ON u.id = p.userId WHERE u.applicationId = @appId", c); cmd.Parameters.AddWithValue("@appId", app.FetchId(c)); if (usernameToMatch != null) { cmd.CommandText += " AND u.name LIKE @userName"; cmd.Parameters.AddWithValue("@userName", usernameToMatch); } if (userInactiveSinceDate != DateTime.MinValue) { cmd.CommandText += " AND u.lastActivityDate < @lastActivityDate"; cmd.Parameters.AddWithValue("@lastActivityDate", userInactiveSinceDate); } if (authenticationOption == ProfileAuthenticationOption.Anonymous) cmd.CommandText += " AND u.isAnonymous = 1"; else if (authenticationOption == ProfileAuthenticationOption.Authenticated) cmd.CommandText += " AND u.isAnonymous = 0"; cmd.CommandText += String.Format(" LIMIT {0},{1}", pageIndex * pageSize, pageSize); ProfileInfoCollection pic = new ProfileInfoCollection(); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { ProfileInfo pi = new ProfileInfo( reader.GetString("name"), reader.GetBoolean("isAnonymous"), reader.GetDateTime("lastActivityDate"), reader.GetDateTime("lastUpdatedDate"), reader.GetInt32("profilesize")); pic.Add(pi); } } cmd.CommandText = "SELECT FOUND_ROWS()"; totalRecords = Convert.ToInt32(cmd.ExecuteScalar()); return pic; } } private static string GetConfigValue(string configValue, string defaultValue) { if (string.IsNullOrEmpty(configValue)) { return defaultValue; } return configValue; } #endregion } } mysql-connector-net-6.4.3/Source/MySql.Web/SchemaManager.cs0000644000175000017500000001406611127003600024225 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // This code was contributed by Sean Wright (srwright@alcor.concordia.ca) on 2007-01-12 // The copyright was assigned and transferred under the terms of // the MySQL Contributor License Agreement (CLA) using System; using System.Data; using MySql.Data.MySqlClient; using System.Collections.Specialized; using System.Configuration.Provider; using System.Resources; using System.IO; using System.Diagnostics; using MySql.Web.Properties; namespace MySql.Web.Common { /// /// /// public static class SchemaManager { private const int schemaVersion = 6; /// /// Gets the most recent version of the schema. /// /// The most recent version number of the schema. public static int Version { get { return schemaVersion; } } internal static void CheckSchema(string connectionString, NameValueCollection config) { int ver = GetSchemaVersion(connectionString); if (ver == Version) return; try { if (String.Compare(config["autogenerateschema"], "true", true) == 0) UpgradeToCurrent(connectionString, ver); else throw new ProviderException(Resources.MissingOrWrongSchema); } catch (Exception ex) { throw new ProviderException(Resources.MissingOrWrongSchema, ex); } } private static void UpgradeToCurrent(string connectionString, int version) { ResourceManager r = new ResourceManager("MySql.Web.Properties.Resources", typeof(SchemaManager).Assembly); if (version == Version) return; using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); for (int ver = version + 1; ver <= Version; ver++) { string schema = r.GetString(String.Format("schema{0}", ver)); MySqlScript script = new MySqlScript(connection); script.Query = schema; script.Execute(); } } } private static int GetSchemaVersion(string connectionString) { // retrieve the current schema version using (MySqlConnection conn = new MySqlConnection(connectionString)) { conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM my_aspnet_SchemaVersion", conn); try { object ver = cmd.ExecuteScalar(); if (ver != null) return (int)ver; } catch (MySqlException ex) { if (ex.Number != (int)MySqlErrorCode.NoSuchTable) throw; string[] restrictions = new string[4]; restrictions[2] = "mysql_Membership"; DataTable dt = conn.GetSchema("Tables", restrictions); if (dt.Rows.Count == 1) return Convert.ToInt32(dt.Rows[0]["TABLE_COMMENT"]); } return 0; } } /// /// Creates the or fetch user id. /// /// The connection. /// The username. /// The application id. /// if set to true [authenticated]. /// internal static int CreateOrFetchUserId(MySqlConnection connection, string username, int applicationId, bool authenticated) { Debug.Assert(applicationId > 0); // first attempt to fetch an existing user id MySqlCommand cmd = new MySqlCommand(@"SELECT id FROM my_aspnet_Users WHERE applicationId = @appId AND name = @name", connection); cmd.Parameters.AddWithValue("@appId", applicationId); cmd.Parameters.AddWithValue("@name", username); object userId = cmd.ExecuteScalar(); if (userId != null) return (int)userId; cmd.CommandText = @"INSERT INTO my_aspnet_Users VALUES (NULL, @appId, @name, @isAnon, Now())"; cmd.Parameters.AddWithValue("@isAnon", !authenticated); int recordsAffected = cmd.ExecuteNonQuery(); if (recordsAffected != 1) throw new ProviderException(Resources.UnableToCreateUser); cmd.CommandText = "SELECT LAST_INSERT_ID()"; return Convert.ToInt32(cmd.ExecuteScalar()); } } }mysql-connector-net-6.4.3/Source/MySql.Web/Properties/0000755000175000017500000000000011127003600023330 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Web/Properties/schema3.sql0000644000175000017500000000774111127003600025405 0ustar directhexdirecthex/* Provider schema block -- version 3 */ /* create our application and user tables */ create table my_aspnet_Applications(id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(256), description VARCHAR(256)); create table my_aspnet_Users(id INT PRIMARY KEY AUTO_INCREMENT, applicationId INT NOT NULL, name VARCHAR(256) NOT NULL, isAnonymous TINYINT(1) NOT NULL DEFAULT 1, lastActivityDate DATETIME); create table my_aspnet_Profiles(userId INT PRIMARY KEY, valueindex longtext, stringdata longtext, binarydata longblob, lastUpdatedDate timestamp); create table my_aspnet_SchemaVersion(version INT); insert into my_aspnet_SchemaVersion VALUES (3); /* now we need to migrate all applications into our apps table */ insert into my_aspnet_Applications (name) select ApplicationName from mysql_Membership UNION select ApplicationName from mysql_UsersInRoles; /* now we make our changes to the existing tables */ alter table mysql_Membership rename to my_aspnet_Membership, drop primary key, drop column pkid, drop column IsOnline, add column userId INT FIRST, add column applicationId INT AFTER userId; alter table mysql_Roles rename to my_aspnet_Roles, drop key Rolename, add column id INT PRIMARY KEY AUTO_INCREMENT FIRST, add column applicationId INT NOT NULL AFTER id; alter table mysql_UsersInRoles drop key Username, rename to my_aspnet_UsersInRoles, add column userId INT FIRST, add column roleId INT AFTER userId, add column applicationId INT AFTER roleId; ALTER TABLE my_aspnet_Membership CONVERT TO CHARACTER SET DEFAULT; ALTER TABLE my_aspnet_Roles CONVERT TO CHARACTER SET DEFAULT; ALTER TABLE my_aspnet_UsersInRoles CONVERT TO CHARACTER SET DEFAULT; /* these next lines set the application Id on our tables appropriately */ update my_aspnet_Membership m, my_aspnet_Applications a set m.applicationId = a.id where a.name=m.ApplicationName; update my_aspnet_Roles r, my_aspnet_Applications a set r.applicationId = a.id where a.name=r.ApplicationName; update my_aspnet_UsersInRoles u, my_aspnet_Applications a set u.applicationId = a.id where a.name=u.ApplicationName; /* now merge our usernames into our users table */ insert into my_aspnet_Users (applicationId, name) select applicationId, Username from my_aspnet_Membership UNION select applicationId, Username from my_aspnet_UsersInRoles; /* now set the user ids in our tables accordingly */ update my_aspnet_Membership m, my_aspnet_Users u set m.userId = u.id where u.name=m.Username AND u.applicationId=m.applicationId; update my_aspnet_UsersInRoles r, my_aspnet_Users u set r.userId = u.id where u.name=r.Username AND u.applicationId=r.applicationId; /* now update the isanonymous and last activity date fields for the users */ update my_aspnet_Users u, my_aspnet_Membership m set u.isAnonymous=0, u.lastActivityDate=m.LastActivityDate where u.name = m.Username; /* make final changes to our tables */ alter table my_aspnet_Membership drop column Username, drop column ApplicationName, drop column applicationId, add primary key (userId); /* next we set our role id values appropriately */ update my_aspnet_UsersInRoles u, my_aspnet_Roles r set u.roleId = r.id where u.Rolename = r.Rolename and r.applicationId=u.applicationId; /* now we make the final changes to our roles tables */ alter table my_aspnet_Roles drop column ApplicationName, change column Rolename name VARCHAR(255) NOT NULL; alter table my_aspnet_UsersInRoles drop column ApplicationName, drop column applicationId, drop column Username, drop column Rolename, add primary key (userId, roleId); mysql-connector-net-6.4.3/Source/MySql.Web/Properties/Resources.Designer.cs0000644000175000017500000004756711127003600027413 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.5444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace MySql.Web.Properties { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MySql.Web.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// /// Looks up a localized string similar to Cannot delete a populated role.. /// public static string CannotDeleteAPopulatedRole { get { return ResourceManager.GetString("CannotDeleteAPopulatedRole", resourceCulture); } } /// /// Looks up a localized string similar to Setting EnablePasswordRetrieval to true when PasswordFormat is Hashed is not supported.. /// public static string CannotRetrieveHashedPasswords { get { return ResourceManager.GetString("CannotRetrieveHashedPasswords", resourceCulture); } } /// /// Looks up a localized string similar to Cannot unencode a hashed password.. /// public static string CannotUnencodeHashedPwd { get { return ResourceManager.GetString("CannotUnencodeHashedPwd", resourceCulture); } } /// /// Looks up a localized string similar to Change password operation was canceled.. /// public static string ChangePasswordCanceled { get { return ResourceManager.GetString("ChangePasswordCanceled", resourceCulture); } } /// /// Looks up a localized string similar to There was an error during membership provider initilization.. /// public static string ErrorInitOfMembershipProvider { get { return ResourceManager.GetString("ErrorInitOfMembershipProvider", resourceCulture); } } /// /// Looks up a localized string similar to There was an error during role provider initilization.. /// public static string ErrorInitOfRoleProvider { get { return ResourceManager.GetString("ErrorInitOfRoleProvider", resourceCulture); } } /// /// Looks up a localized string similar to There was an error during profile provider initilization.. /// public static string ErrorInitProfileProvider { get { return ResourceManager.GetString("ErrorInitProfileProvider", resourceCulture); } } /// /// Looks up a localized string similar to There was an error resetting the password.. /// public static string ErrorResettingPassword { get { return ResourceManager.GetString("ErrorResettingPassword", resourceCulture); } } /// /// Looks up a localized string similar to Role names must not be null or empty.. /// public static string IllegalRoleName { get { return ResourceManager.GetString("IllegalRoleName", resourceCulture); } } /// /// Looks up a localized string similar to User names must not be null or empty.. /// public static string IllegalUserName { get { return ResourceManager.GetString("IllegalUserName", resourceCulture); } } /// /// Looks up a localized string similar to Incorrect password answer.. /// public static string IncorrectPasswordAnswer { get { return ResourceManager.GetString("IncorrectPasswordAnswer", resourceCulture); } } /// /// Looks up a localized string similar to Invalid characters in user name.. /// public static string InvalidCharactersInUserName { get { return ResourceManager.GetString("InvalidCharactersInUserName", resourceCulture); } } /// /// Looks up a localized string similar to Unable to initialize provider. Missing or incorrect schema.. /// public static string MissingOrWrongSchema { get { return ResourceManager.GetString("MissingOrWrongSchema", resourceCulture); } } /// /// Looks up a localized string similar to The mono runtime did not support hashed passwords. Please use clear or encrypted passwords.. /// public static string MonoDoesNotSupportHash { get { return ResourceManager.GetString("MonoDoesNotSupportHash", resourceCulture); } } /// /// Looks up a localized string similar to Change password canceled due to New password validation failure.. /// public static string NewPasswordValidationFailed { get { return ResourceManager.GetString("NewPasswordValidationFailed", resourceCulture); } } /// /// Looks up a localized string similar to Non alpha numeric characters in '{0}' needs to be greater than or equal to '{1}'.. /// public static string NotEnoughNonAlphaNumericInPwd { get { return ResourceManager.GetString("NotEnoughNonAlphaNumericInPwd", resourceCulture); } } /// /// Looks up a localized string similar to Password answer supplied is invalid.. /// public static string PasswordAnswerInvalid { get { return ResourceManager.GetString("PasswordAnswerInvalid", resourceCulture); } } /// /// Looks up a localized string similar to The length of parameter '{0}' needs to be greater or equal to '{1}'.. /// public static string PasswordNotLongEnough { get { return ResourceManager.GetString("PasswordNotLongEnough", resourceCulture); } } /// /// Looks up a localized string similar to Password question supplied is invalid.. /// public static string PasswordQuestionInvalid { get { return ResourceManager.GetString("PasswordQuestionInvalid", resourceCulture); } } /// /// Looks up a localized string similar to Password answer required for password reset.. /// public static string PasswordRequiredForReset { get { return ResourceManager.GetString("PasswordRequiredForReset", resourceCulture); } } /// /// Looks up a localized string similar to Reset password canceled due to password validation failure.. /// public static string PasswordResetCanceledNotValid { get { return ResourceManager.GetString("PasswordResetCanceledNotValid", resourceCulture); } } /// /// Looks up a localized string similar to Password Reset is not enabled.. /// public static string PasswordResetNotEnabled { get { return ResourceManager.GetString("PasswordResetNotEnabled", resourceCulture); } } /// /// Looks up a localized string similar to Password Retrieval Not Enabled.. /// public static string PasswordRetrievalNotEnabled { get { return ResourceManager.GetString("PasswordRetrievalNotEnabled", resourceCulture); } } /// /// Looks up a localized string similar to Profile update failed.. /// public static string ProfileUpdateFailed { get { return ResourceManager.GetString("ProfileUpdateFailed", resourceCulture); } } /// /// Looks up a localized string similar to Role name already exists.. /// public static string RoleNameAlreadyExists { get { return ResourceManager.GetString("RoleNameAlreadyExists", resourceCulture); } } /// /// Looks up a localized string similar to Role name not found.. /// public static string RoleNameNotFound { get { return ResourceManager.GetString("RoleNameNotFound", resourceCulture); } } /// /// Looks up a localized string similar to CREATE TABLE mysql_Membership(`PKID` varchar(36) NOT NULL, /// Username varchar(255) NOT NULL, /// ApplicationName varchar(255) NOT NULL, /// Email varchar(128) NOT NULL, /// Comment varchar(255) default NULL, /// Password varchar(128) NOT NULL, /// PasswordQuestion varchar(255) default NULL, /// PasswordAnswer varchar(255) default NULL, /// IsApproved tinyint(1) default NULL, /// LastActivityDate datetim [rest of string was truncated]";. /// public static string schema1 { get { return ResourceManager.GetString("schema1", resourceCulture); } } /// /// Looks up a localized string similar to ALTER TABLE mysql_Membership /// ADD PasswordKey char(32) AFTER Password, /// ADD PasswordFormat tinyint AFTER PasswordKey, /// CHANGE Email Email VARCHAR(128), COMMENT='2'; /// /// /// . /// public static string schema2 { get { return ResourceManager.GetString("schema2", resourceCulture); } } /// /// Looks up a localized string similar to /* Provider schema block -- version 3 */ /// ////* create our application and user tables */ ///create table my_aspnet_Applications(id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(256), description VARCHAR(256)); ///create table my_aspnet_Users(id INT PRIMARY KEY AUTO_INCREMENT, /// applicationId INT NOT NULL, name VARCHAR(256) NOT NULL, /// isAnonymous TINYINT(1) NOT NULL DEFAULT 1, lastActivityDate DATETIME); ///create table my_aspnet_Profiles(userId INT PRIMARY KEY, valueindex longtext, stringdata longtext, binary [rest of string was truncated]";. /// public static string schema3 { get { return ResourceManager.GetString("schema3", resourceCulture); } } /// /// Looks up a localized string similar to ALTER TABLE my_aspnet_Membership CONVERT TO CHARACTER SET DEFAULT; ///ALTER TABLE my_aspnet_Roles CONVERT TO CHARACTER SET DEFAULT; ///ALTER TABLE my_aspnet_UsersInRoles CONVERT TO CHARACTER SET DEFAULT; /// ///UPDATE my_aspnet_SchemaVersion SET version=4 WHERE version=3; ///. /// public static string schema4 { get { return ResourceManager.GetString("schema4", resourceCulture); } } /// /// Looks up a localized string similar to CREATE TABLE my_aspnet_Sessions ///( /// SessionId varchar(255) NOT NULL, /// ApplicationId int NOT NULL, /// Created datetime NOT NULL, /// Expires datetime NOT NULL, /// LockDate datetime NOT NULL, /// LockId int NOT NULL, /// Timeout int NOT NULL, /// Locked tinyint(1) NOT NULL, /// SessionItems BLOB, /// Flags int NOT NULL, /// primary key (SessionId,ApplicationId) ///) DEFAULT CHARSET=latin1; /// ////* /// Cleaning up timed ou [rest of string was truncated]";. /// public static string schema5 { get { return ResourceManager.GetString("schema5", resourceCulture); } } /// /// Looks up a localized string similar to ALTER TABLE my_aspnet_Sessions CONVERT TO CHARACTER SET DEFAULT; ///ALTER TABLE my_aspnet_Sessions MODIFY SessionItems LONGBLOB; /// ///UPDATE my_aspnet_SchemaVersion SET version=6;. /// public static string schema6 { get { return ResourceManager.GetString("schema6", resourceCulture); } } /// /// Looks up a localized string similar to Unable to create application.. /// public static string UnableToCreateApplication { get { return ResourceManager.GetString("UnableToCreateApplication", resourceCulture); } } /// /// Looks up a localized string similar to Unable to create user.. /// public static string UnableToCreateUser { get { return ResourceManager.GetString("UnableToCreateUser", resourceCulture); } } /// /// Looks up a localized string similar to Unable to lock out user.. /// public static string UnableToLockOutUser { get { return ResourceManager.GetString("UnableToLockOutUser", resourceCulture); } } /// /// Looks up a localized string similar to Unable to retrieve profile data from database.. /// public static string UnableToRetrieveProfileData { get { return ResourceManager.GetString("UnableToRetrieveProfileData", resourceCulture); } } /// /// Looks up a localized string similar to Unable to update failure count. Membership database may be corrupt.. /// public static string UnableToUpdateFailureCount { get { return ResourceManager.GetString("UnableToUpdateFailureCount", resourceCulture); } } /// /// Looks up a localized string similar to Unsupported password format.. /// public static string UnsupportedPasswordFormat { get { return ResourceManager.GetString("UnsupportedPasswordFormat", resourceCulture); } } /// /// Looks up a localized string similar to User is already in role.. /// public static string UserIsAlreadyInRole { get { return ResourceManager.GetString("UserIsAlreadyInRole", resourceCulture); } } /// /// Looks up a localized string similar to The supplied user is locked out.. /// public static string UserIsLockedOut { get { return ResourceManager.GetString("UserIsLockedOut", resourceCulture); } } /// /// Looks up a localized string similar to Username not found.. /// public static string UsernameNotFound { get { return ResourceManager.GetString("UsernameNotFound", resourceCulture); } } /// /// Looks up a localized string similar to User not in role.. /// public static string UserNotInRole { get { return ResourceManager.GetString("UserNotInRole", resourceCulture); } } /// /// Looks up a localized string similar to The validate password operation was canceled.. /// public static string ValidatePasswordCanceled { get { return ResourceManager.GetString("ValidatePasswordCanceled", resourceCulture); } } } } mysql-connector-net-6.4.3/Source/MySql.Web/Properties/Resources.resx0000644000175000017500000003007711127003600026214 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Cannot delete a populated role. Setting EnablePasswordRetrieval to true when PasswordFormat is Hashed is not supported. Cannot unencode a hashed password. There was an error during membership provider initilization. There was an error during role provider initilization. There was an error during profile provider initilization. There was an error resetting the password. Incorrect password answer. Invalid characters in user name. Change password canceled due to New password validation failure. Password answer required for password reset. Reset password canceled due to password validation failure. Password Reset is not enabled. Password Retrieval Not Enabled. Profile update failed. Role name already exists. Role name not found. schema1.sql;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 schema2.sql;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 schema3.sql;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 Unable to lock out user. Unable to retrieve profile data from database. Unable to update failure count. Membership database may be corrupt. Unsupported password format. User is already in role. The supplied user is locked out. Username not found. User not in role. Unable to initialize provider. Missing or incorrect schema. Unable to create application. Unable to create user. Change password operation was canceled. Non alpha numeric characters in '{0}' needs to be greater than or equal to '{1}'. The length of parameter '{0}' needs to be greater or equal to '{1}'. The validate password operation was canceled. Password answer supplied is invalid. Password question supplied is invalid. schema4.sql;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 Role names must not be null or empty. User names must not be null or empty. The mono runtime did not support hashed passwords. Please use clear or encrypted passwords. schema5.sql;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 schema6.sql;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 mysql-connector-net-6.4.3/Source/MySql.Web/Properties/schema6.sql0000644000175000017500000000025711127003600025403 0ustar directhexdirecthexALTER TABLE my_aspnet_Sessions CONVERT TO CHARACTER SET DEFAULT; ALTER TABLE my_aspnet_Sessions MODIFY SessionItems LONGBLOB; UPDATE my_aspnet_SchemaVersion SET version=6;mysql-connector-net-6.4.3/Source/MySql.Web/Properties/AssemblyInfo.cs0000644000175000017500000000456411127003600026263 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MySql.Web")] [assembly: AssemblyDescription("ADO.Net driver for MySQL")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Oracle")] [assembly: AssemblyProduct("MySql.Web")] [assembly: AssemblyCopyright("Copyright © 2004, 2010, Oracle and/or its affiliates. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AllowPartiallyTrustedCallers()] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] #if CLR4 [assembly: SecurityRules(SecurityRuleSet.Level1)] #endif // The following GUID is for the ID of the typelib if this project is exposed to COM //[assembly: Guid("01520f33-9ecd-4574-96d0-5e6604e0f3aa")] [assembly: AssemblyKeyName("ConnectorNet")] mysql-connector-net-6.4.3/Source/MySql.Web/Properties/schema4.sql0000644000175000017500000000041211127003600025372 0ustar directhexdirecthexALTER TABLE my_aspnet_Membership CONVERT TO CHARACTER SET DEFAULT; ALTER TABLE my_aspnet_Roles CONVERT TO CHARACTER SET DEFAULT; ALTER TABLE my_aspnet_UsersInRoles CONVERT TO CHARACTER SET DEFAULT; UPDATE my_aspnet_SchemaVersion SET version=4 WHERE version=3; mysql-connector-net-6.4.3/Source/MySql.Web/Properties/schema2.sql0000644000175000017500000000037211127003600025375 0ustar directhexdirecthex ALTER TABLE mysql_Membership ADD PasswordKey char(32) AFTER Password, ADD PasswordFormat tinyint AFTER PasswordKey, CHANGE Email Email VARCHAR(128), COMMENT='2'; mysql-connector-net-6.4.3/Source/MySql.Web/Properties/schema1.sql0000644000175000017500000000343511127003600025377 0ustar directhexdirecthexCREATE TABLE mysql_Membership(`PKID` varchar(36) NOT NULL, Username varchar(255) NOT NULL, ApplicationName varchar(255) NOT NULL, Email varchar(128) NOT NULL, Comment varchar(255) default NULL, Password varchar(128) NOT NULL, PasswordQuestion varchar(255) default NULL, PasswordAnswer varchar(255) default NULL, IsApproved tinyint(1) default NULL, LastActivityDate datetime default NULL, LastLoginDate datetime default NULL, LastPasswordChangedDate datetime default NULL, CreationDate datetime default NULL, IsOnline tinyint(1) default NULL, IsLockedOut tinyint(1) default NULL, LastLockedOutDate datetime default NULL, FailedPasswordAttemptCount int(10) unsigned default NULL, FailedPasswordAttemptWindowStart datetime default NULL, FailedPasswordAnswerAttemptCount int(10) unsigned default NULL, FailedPasswordAnswerAttemptWindowStart datetime default NULL, PRIMARY KEY (`PKID`)) DEFAULT CHARSET=latin1 COMMENT='1'; CREATE TABLE mysql_UsersInRoles(`Username` varchar(255) NOT NULL, `Rolename` varchar(255) NOT NULL, `ApplicationName` varchar(255) NOT NULL, KEY `Username` (`Username`,`Rolename`,`ApplicationName`) ) DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC; CREATE TABLE mysql_Roles(`Rolename` varchar(255) NOT NULL, `ApplicationName` varchar(255) NOT NULL, KEY `Rolename` (`Rolename`,`ApplicationName`) ) DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC; mysql-connector-net-6.4.3/Source/MySql.Web/Properties/schema5.sql0000644000175000017500000000156011127003600025400 0ustar directhexdirecthexCREATE TABLE my_aspnet_Sessions ( SessionId varchar(255) NOT NULL, ApplicationId int NOT NULL, Created datetime NOT NULL, Expires datetime NOT NULL, LockDate datetime NOT NULL, LockId int NOT NULL, Timeout int NOT NULL, Locked tinyint(1) NOT NULL, SessionItems BLOB, Flags int NOT NULL, primary key (SessionId,ApplicationId) ) DEFAULT CHARSET=latin1; /* Cleaning up timed out sessions. In 5.1 events provide a support for periodic jobs. In older version we need a do-it-yourself event. */ CREATE TABLE my_aspnet_SessionCleanup ( LastRun datetime NOT NULL, IntervalMinutes int NOT NULL ); INSERT INTO my_aspnet_SessionCleanup(LastRun,IntervalMinutes) values(NOW(), 10); UPDATE my_aspnet_SchemaVersion SET version=5; mysql-connector-net-6.4.3/Source/MySql.Web/Install.cs0000644000175000017500000003715711127003600023146 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #if !MONO && !PocketPC using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration.Install; using System.Collections; using System.IO; using Microsoft.Win32; using System.Xml; using System.Reflection; using System.Security.Permissions; namespace MySql.Web.Security { [RunInstaller(true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] public class CustomInstaller : Installer { /// /// When overridden in a derived class, performs the installation. /// /// An used to save information needed to perform a commit, rollback, or uninstall operation. /// /// The parameter is null. /// /// /// An exception occurred in the event handler of one of the installers in the collection. /// -or- /// An exception occurred in the event handler of one of the installers in the collection. /// public override void Install(IDictionary stateSaver) { base.Install(stateSaver); AddProviderToMachineConfig(); } /// /// When overridden in a derived class, removes an installation. /// /// An that contains the state of the computer after the installation was complete. /// /// The saved-state might have been corrupted. /// /// /// An exception occurred while uninstalling. This exception is ignored and the uninstall continues. However, the application might not be fully uninstalled after the uninstallation completes. /// public override void Uninstall(IDictionary savedState) { base.Uninstall(savedState); RemoveProviderFromMachineConfig(); } private void AddProviderToMachineConfig() { object installRoot = Registry.GetValue( @"HKEY_LOCAL_MACHINE\Software\Microsoft\.NETFramework\", "InstallRoot", null); if (installRoot == null) throw new Exception("Unable to retrieve install root for .NET framework"); UpdateMachineConfigs(installRoot.ToString(), true); string installRoot64 = installRoot.ToString(); installRoot64 = installRoot64.Substring(0, installRoot64.Length - 1); installRoot64 = string.Format("{0}64{1}", installRoot64, Path.DirectorySeparatorChar); if (Directory.Exists(installRoot64)) UpdateMachineConfigs(installRoot64, true); } private void UpdateMachineConfigs(string rootPath, bool add) { string[] dirs = new string[2] { "v2.0.50727", "v4.0.30319" }; foreach (string frameworkDir in dirs) { string path = rootPath + frameworkDir; string configPath = String.Format(@"{0}\CONFIG", path); if (Directory.Exists(configPath)) { if (add) AddProviderToMachineConfigInDir(configPath); else RemoveProviderFromMachineConfigInDir(configPath); } } } private void AddProviderToMachineConfigInDir(string path) { string configFile = String.Format(@"{0}\machine.config", path); if (!File.Exists(configFile)) return; // now read the config file into memory StreamReader sr = new StreamReader(configFile); string configXML = sr.ReadToEnd(); sr.Close(); // load the XML into the XmlDocument XmlDocument doc = new XmlDocument(); doc.LoadXml(configXML); AddDefaultConnectionString(doc); AddMembershipProvider(doc); AddRoleProvider(doc); AddProfileProvider(doc); // Save the document to a file and auto-indent the output. XmlTextWriter writer = new XmlTextWriter(configFile, null); writer.Formatting = Formatting.Indented; doc.Save(writer); writer.Flush(); writer.Close(); } private void AddDefaultConnectionString(XmlDocument doc) { // create our new node XmlElement newNode = (XmlElement)doc.CreateNode(XmlNodeType.Element, "add", ""); // add the proper attributes newNode.SetAttribute("name", "LocalMySqlServer"); newNode.SetAttribute("connectionString", ""); XmlNodeList nodes = doc.GetElementsByTagName("connectionStrings"); XmlNode connectionStringList = nodes[0]; bool alreadyThere = false; foreach (XmlNode node in connectionStringList.ChildNodes) { string nameValue = node.Attributes["name"].Value; if (nameValue == "LocalMySqlServer") { alreadyThere = true; break; } } if (!alreadyThere) connectionStringList.AppendChild(newNode); } private void AddMembershipProvider(XmlDocument doc) { // create our new node XmlElement newNode = (XmlElement)doc.CreateNode(XmlNodeType.Element, "add", ""); // add the proper attributes newNode.SetAttribute("name", "MySQLMembershipProvider"); // add the type attribute by reflecting on the executing assembly Assembly a = Assembly.GetExecutingAssembly(); string type = String.Format("MySql.Web.Security.MySQLMembershipProvider, {0}", a.FullName.Replace("Installers", "Web")); newNode.SetAttribute("type", type); newNode.SetAttribute("connectionStringName", "LocalMySqlServer"); newNode.SetAttribute("enablePasswordRetrieval", "false"); newNode.SetAttribute("enablePasswordReset", "true"); newNode.SetAttribute("requiresQuestionAndAnswer", "true"); newNode.SetAttribute("applicationName", "/"); newNode.SetAttribute("requiresUniqueEmail", "false"); newNode.SetAttribute("passwordFormat", "Clear"); newNode.SetAttribute("maxInvalidPasswordAttempts", "5"); newNode.SetAttribute("minRequiredPasswordLength", "7"); newNode.SetAttribute("minRequiredNonalphanumericCharacters", "1"); newNode.SetAttribute("passwordAttemptWindow", "10"); newNode.SetAttribute("passwordStrengthRegularExpression", ""); XmlNodeList nodes = doc.GetElementsByTagName("membership"); XmlNode providerList = nodes[0].FirstChild; foreach (XmlNode node in providerList.ChildNodes) { string typeValue = node.Attributes["type"].Value; if (typeValue.StartsWith("MySql.Web.Security.MySQLMembershipProvider")) { providerList.RemoveChild(node); break; } } providerList.AppendChild(newNode); } private void AddRoleProvider(XmlDocument doc) { // create our new node XmlElement newNode = (XmlElement)doc.CreateNode(XmlNodeType.Element, "add", ""); // add the proper attributes newNode.SetAttribute("name", "MySQLRoleProvider"); // add the type attribute by reflecting on the executing assembly Assembly a = Assembly.GetExecutingAssembly(); string type = String.Format("MySql.Web.Security.MySQLRoleProvider, {0}", a.FullName.Replace("Installers", "Web")); newNode.SetAttribute("type", type); newNode.SetAttribute("connectionStringName", "LocalMySqlServer"); newNode.SetAttribute("applicationName", "/"); XmlNodeList nodes = doc.GetElementsByTagName("roleManager"); XmlNode providerList = nodes[0].FirstChild; foreach (XmlNode node in providerList.ChildNodes) { string typeValue = node.Attributes["type"].Value; if (typeValue.StartsWith("MySql.Web.Security.MySQLRoleProvider")) { providerList.RemoveChild(node); break; } } providerList.AppendChild(newNode); } private void AddProfileProvider(XmlDocument doc) { // create our new node XmlElement newNode = (XmlElement)doc.CreateNode(XmlNodeType.Element, "add", ""); // add the proper attributes newNode.SetAttribute("name", "MySQLProfileProvider"); // add the type attribute by reflecting on the executing assembly Assembly a = Assembly.GetExecutingAssembly(); string type = String.Format("MySql.Web.Profile.MySQLProfileProvider, {0}", a.FullName.Replace("Installers", "Web")); newNode.SetAttribute("type", type); newNode.SetAttribute("connectionStringName", "LocalMySqlServer"); newNode.SetAttribute("applicationName", "/"); XmlNodeList nodes = doc.GetElementsByTagName("profile"); XmlNode providerList = nodes[0].FirstChild; foreach (XmlNode node in providerList.ChildNodes) { string typeValue = node.Attributes["type"].Value; if (typeValue.StartsWith("MySql.Web.Profile.MySQLProfileProvider")) { providerList.RemoveChild(node); break; } } providerList.AppendChild(newNode); } private void RemoveProviderFromMachineConfig() { object installRoot = Registry.GetValue( @"HKEY_LOCAL_MACHINE\Software\Microsoft\.NETFramework\", "InstallRoot", null); if (installRoot == null) throw new Exception("Unable to retrieve install root for .NET framework"); UpdateMachineConfigs(installRoot.ToString(), false); string installRoot64 = installRoot.ToString(); installRoot64 = installRoot64.Substring(0, installRoot64.Length - 1); installRoot64 = string.Format("{0}64{1}", installRoot64, Path.DirectorySeparatorChar); if (Directory.Exists(installRoot64)) UpdateMachineConfigs(installRoot64, false); } private void RemoveProviderFromMachineConfigInDir(string path) { string configFile = String.Format(@"{0}\machine.config", path); if (!File.Exists(configFile)) return; // now read the config file into memory StreamReader sr = new StreamReader(configFile); string configXML = sr.ReadToEnd(); sr.Close(); // load the XML into the XmlDocument XmlDocument doc = new XmlDocument(); doc.LoadXml(configXML); RemoveDefaultConnectionString(doc); RemoveMembershipProvider(doc); RemoveRoleProvider(doc); RemoveProfileProvider(doc); // Save the document to a file and auto-indent the output. XmlTextWriter writer = new XmlTextWriter(configFile, null); writer.Formatting = Formatting.Indented; doc.Save(writer); writer.Flush(); writer.Close(); } private void RemoveDefaultConnectionString(XmlDocument doc) { XmlNodeList nodes = doc.GetElementsByTagName("connectionStrings"); XmlNode connectionStringList = nodes[0]; foreach (XmlNode node in connectionStringList.ChildNodes) { string name = node.Attributes["name"].Value; if (name == "LocalMySqlServer") { connectionStringList.RemoveChild(node); break; } } } private void RemoveMembershipProvider(XmlDocument doc) { XmlNodeList nodes = doc.GetElementsByTagName("membership"); XmlNode providersNode = nodes[0].FirstChild; foreach (XmlNode node in providersNode.ChildNodes) { string name = node.Attributes["name"].Value; if (name == "MySQLMembershipProvider") { providersNode.RemoveChild(node); break; } } } private void RemoveRoleProvider(XmlDocument doc) { XmlNodeList nodes = doc.GetElementsByTagName("roleManager"); XmlNode providersNode = nodes[0].FirstChild; foreach (XmlNode node in providersNode.ChildNodes) { string name = node.Attributes["name"].Value; if (name == "MySQLRoleProvider") { providersNode.RemoveChild(node); break; } } } private void RemoveProfileProvider(XmlDocument doc) { XmlNodeList nodes = doc.GetElementsByTagName("profile"); XmlNode providersNode = nodes[0].FirstChild; foreach (XmlNode node in providersNode.ChildNodes) { string name = node.Attributes["name"].Value; if (name == "MySQLProfileProvider") { providersNode.RemoveChild(node); break; } } } } } #endifmysql-connector-net-6.4.3/Source/MySql.Web/Runtime.cs0000644000175000017500000000104511127003600023146 0ustar directhexdirecthexusing System; namespace MySql.Web.Security { internal static class Runtime { private static bool inited; private static bool isMono; public static bool IsMono { get { if (!inited) Init(); return isMono; } } private static void Init() { inited = true; Type t = Type.GetType("Mono.Runtime"); isMono = t != null; } } } mysql-connector-net-6.4.3/Source/MySql.Data/0000755000175000017500000000000011127003600021330 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Data/parameter_collection.cs0000644000175000017500000004663511127003600026070 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data.Common; using System.Collections; using System.ComponentModel; using System.Collections.Generic; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { /// /// Represents a collection of parameters relevant to a as well as their respective mappings to columns in a . This class cannot be inherited. /// /// #if !CF [Editor("MySql.Data.MySqlClient.Design.DBParametersEditor,MySql.Design", typeof(System.Drawing.Design.UITypeEditor))] [ListBindable(true)] #endif public sealed class MySqlParameterCollection : DbParameterCollection { List items = new List(); //private ArrayList items = new ArrayList(); private Hashtable indexHashCS; private Hashtable indexHashCI; internal MySqlParameterCollection(MySqlCommand cmd) { indexHashCS = new Hashtable(); indexHashCI = new Hashtable(StringComparer.CurrentCultureIgnoreCase); Clear(); } #region Public Methods /// /// Gets the at the specified index. /// /// Gets the with a specified attribute. /// [C#] In C#, this property is the indexer for the class. /// public new MySqlParameter this[int index] { get { return (MySqlParameter)GetParameter(index); } set { SetParameter(index, value); } } /// /// Gets the with the specified name. /// public new MySqlParameter this[string name] { get { return (MySqlParameter)GetParameter(name); } set { SetParameter(name, value); } } /// /// Adds the specified object to the . /// /// The to add to the collection. /// The newly added object. public MySqlParameter Add(MySqlParameter value) { return InternalAdd(value, -1); } /// /// Adds a to the given the specified parameter name and value. /// /// The name of the parameter. /// The of the to add to the collection. /// The newly added object. [Obsolete("Add(String parameterName, Object value) has been deprecated. Use AddWithValue(String parameterName, Object value)")] public MySqlParameter Add(string parameterName, object value) { return Add(new MySqlParameter(parameterName, value)); } public MySqlParameter AddWithValue(string parameterName, object value) { return Add(new MySqlParameter(parameterName, value)); } /// /// Adds a to the given the parameter name and the data type. /// /// The name of the parameter. /// One of the values. /// The newly added object. public MySqlParameter Add(string parameterName, MySqlDbType dbType) { return Add(new MySqlParameter(parameterName, dbType)); } /// /// Adds a to the with the parameter name, the data type, and the column length. /// /// The name of the parameter. /// One of the values. /// The length of the column. /// The newly added object. public MySqlParameter Add(string parameterName, MySqlDbType dbType, int size) { return Add(new MySqlParameter(parameterName, dbType, size)); } /// /// Adds a to the with the parameter name, the data type, the column length, and the source column name. /// /// The name of the parameter. /// One of the values. /// The length of the column. /// The name of the source column. /// The newly added object. public MySqlParameter Add(string parameterName, MySqlDbType dbType, int size, string sourceColumn) { return Add(new MySqlParameter(parameterName, dbType, size, sourceColumn)); } #endregion #region DbParameterCollection Implementation /// /// Adds an array of values to the end of the . /// /// public override void AddRange(Array values) { foreach (DbParameter p in values) Add(p); } void CheckIndex(int index) { if (index < 0 || index >= Count) throw new IndexOutOfRangeException("Parameter index is out of range."); } /// /// Retrieve the parameter with the given name. /// /// /// protected override DbParameter GetParameter(string parameterName) { int index = IndexOf(parameterName); if (index < 0) { // check to see if the user has added the parameter without a // parameter marker. If so, kindly tell them what they did. if (parameterName.StartsWith("@") || parameterName.StartsWith("?")) { string newParameterName = parameterName.Substring(1); index = IndexOf(newParameterName); if (index != -1) return (DbParameter)items[index]; } throw new ArgumentException("Parameter '" + parameterName + "' not found in the collection."); } return (DbParameter)items[index]; } protected override DbParameter GetParameter(int index) { CheckIndex(index); return (DbParameter)items[index]; } protected override void SetParameter(string parameterName, DbParameter value) { int index = IndexOf(parameterName); if (index < 0) throw new ArgumentException("Parameter '" + parameterName + "' not found in the collection."); SetParameter(index, value); } protected override void SetParameter(int index, DbParameter value) { CheckIndex(index); MySqlParameter p = (MySqlParameter)items[index]; // first we remove the old parameter from our hashes indexHashCS.Remove(p.ParameterName); indexHashCI.Remove(p.ParameterName); // then we add in the new parameter items[index] = value; indexHashCS.Add(value.ParameterName, index); indexHashCI.Add(value.ParameterName, index); } /// /// Adds the specified object to the . /// /// The to add to the collection. /// The index of the new object. public override int Add(object value) { MySqlParameter parameter = value as MySqlParameter; if (parameter == null) throw new MySqlException("Only MySqlParameter objects may be stored"); if (parameter.ParameterName == null || parameter.ParameterName == String.Empty) throw new MySqlException("Parameters must be named"); parameter = Add(parameter); return IndexOf(parameter); } /// /// Removes all items from the collection. /// public override void Clear() { foreach (MySqlParameter p in items) p.Collection = null; items.Clear(); indexHashCS.Clear(); indexHashCI.Clear(); } /// /// Gets a value indicating whether a with the specified parameter name exists in the collection. /// /// The name of the object to find. /// true if the collection contains the parameter; otherwise, false. public override bool Contains(string parameterName) { return IndexOf(parameterName) != -1; } /// /// Gets a value indicating whether a MySqlParameter exists in the collection. /// /// The value of the object to find. /// true if the collection contains the object; otherwise, false. /// Gets a value indicating whether a exists in the collection. public override bool Contains(object value) { DbParameter parameter = value as DbParameter; if (null == parameter) throw new ArgumentException("Argument must be of type DbParameter", "value"); return items.Contains(parameter); } /// /// Copies MySqlParameter objects from the MySqlParameterCollection to the specified array. /// /// /// public override void CopyTo(Array array, int index) { items.ToArray().CopyTo(array, index); } /// /// Gets the number of MySqlParameter objects in the collection. /// public override int Count { get { return items.Count; } } /// /// Returns an enumerator that iterates through the . /// /// public override IEnumerator GetEnumerator() { return items.GetEnumerator(); } /// /// Gets the location of the in the collection with a specific parameter name. /// /// The name of the object to retrieve. /// The zero-based location of the in the collection. public override int IndexOf(string parameterName) { object o = indexHashCS[parameterName]; if (o == null) o = indexHashCI[parameterName]; if (o == null) return -1; return (int)o; } /// /// Gets the location of a in the collection. /// /// The object to locate. /// The zero-based location of the in the collection. /// Gets the location of a in the collection. public override int IndexOf(object value) { DbParameter parameter = value as DbParameter; if (null == parameter) throw new ArgumentException("Argument must be of type DbParameter", "value"); return items.IndexOf(parameter); } /// /// Inserts a MySqlParameter into the collection at the specified index. /// /// /// public override void Insert(int index, object value) { MySqlParameter parameter = value as MySqlParameter; if (parameter == null) throw new MySqlException("Only MySqlParameter objects may be stored"); InternalAdd(parameter, index); } /// /// Gets a value that indicates whether the /// has a fixed size. /// public override bool IsFixedSize { get { return (items as IList).IsFixedSize; } } /// /// Gets a value that indicates whether the /// is read-only. /// public override bool IsReadOnly { get { return (items as IList).IsReadOnly; } } /// /// Gets a value that indicates whether the /// is synchronized. /// public override bool IsSynchronized { get { return (items as IList).IsSynchronized; } } /// /// Removes the specified MySqlParameter from the collection. /// /// public override void Remove(object value) { MySqlParameter p = (value as MySqlParameter); p.Collection = null; int index = IndexOf(p); items.Remove(p); indexHashCS.Remove(p.ParameterName); indexHashCI.Remove(p.ParameterName); AdjustHashes(index, false); } /// /// Removes the specified from the collection using the parameter name. /// /// The name of the object to retrieve. public override void RemoveAt(string parameterName) { DbParameter p = GetParameter(parameterName); Remove(p); } /// /// Removes the specified from the collection using a specific index. /// /// The zero-based index of the parameter. /// Removes the specified from the collection. public override void RemoveAt(int index) { object o = items[index]; Remove(o); } /// /// Gets an object that can be used to synchronize access to the /// . /// public override object SyncRoot { get { return (items as IList).SyncRoot; } } #endregion internal void ParameterNameChanged(MySqlParameter p, string oldName, string newName) { int index = IndexOf(oldName); indexHashCS.Remove(oldName); indexHashCI.Remove(oldName); indexHashCS.Add(newName, index); indexHashCI.Add(newName, index); } private MySqlParameter InternalAdd(MySqlParameter value, int index) { if (value == null) throw new ArgumentException("The MySqlParameterCollection only accepts non-null MySqlParameter type objects.", "value"); // make sure we don't already have a parameter with this name if (IndexOf(value.ParameterName) >= 0) { throw new MySqlException( String.Format(Resources.ParameterAlreadyDefined, value.ParameterName)); } else { string inComingName = value.ParameterName; if (inComingName[0] == '@' || inComingName[0] == '?') inComingName = inComingName.Substring(1, inComingName.Length - 1); if (IndexOf(inComingName) >= 0) throw new MySqlException( String.Format(Resources.ParameterAlreadyDefined, value.ParameterName)); } if (index == -1) { items.Add(value); index = items.IndexOf(value); } else { items.Insert(index, value); AdjustHashes(index, true); } indexHashCS.Add(value.ParameterName, index); indexHashCI.Add(value.ParameterName, index); value.Collection = this; return value; } private static void AdjustHash(Hashtable hash, string parameterName, int keyIndex, bool addEntry) { if (!hash.ContainsKey(parameterName)) return; int index = (int)hash[parameterName]; if (index < keyIndex) return; hash[parameterName] = addEntry ? ++index : --index; } /// /// This method will update all the items in the index hashes when /// we insert a parameter somewhere in the middle /// /// /// private void AdjustHashes(int keyIndex, bool addEntry) { for (int i = 0; i < Count; i++) { string name = (items[i] as MySqlParameter).ParameterName; AdjustHash(indexHashCI, name, keyIndex, addEntry); AdjustHash(indexHashCS, name, keyIndex, addEntry); } } private MySqlParameter GetParameterFlexibleInternal(string baseName) { int index = IndexOf(baseName); if (-1 == index) index = IndexOf("?" + baseName); if (-1 == index) index = IndexOf("@" + baseName); if (-1 != index) return this[index]; return null; } internal MySqlParameter GetParameterFlexible(string parameterName, bool throwOnNotFound) { string baseName = parameterName; MySqlParameter p = GetParameterFlexibleInternal(baseName); if (p != null) return p; if (parameterName.StartsWith("@") || parameterName.StartsWith("?")) baseName = parameterName.Substring(1); p = GetParameterFlexibleInternal(baseName); if (p != null) return p; if (throwOnNotFound) throw new ArgumentException("Parameter '" + parameterName + "' not found in the collection."); return null; } } } mysql-connector-net-6.4.3/Source/MySql.Data/CommandBuilder.cs0000644000175000017500000003006511127003600024550 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.ComponentModel; using System.Data.Common; using System.Data; using System.Text; using MySql.Data.Common; using System.Collections; using MySql.Data.Types; using System.Globalization; using MySql.Data.MySqlClient.Properties; using System.Collections.Generic; namespace MySql.Data.MySqlClient { /// #if !CF [ToolboxItem(false)] [System.ComponentModel.DesignerCategory("Code")] #endif public sealed class MySqlCommandBuilder : DbCommandBuilder { /// public MySqlCommandBuilder() { QuotePrefix = QuoteSuffix = "`"; } /// public MySqlCommandBuilder(MySqlDataAdapter adapter) : this() { DataAdapter = adapter; } /// public new MySqlDataAdapter DataAdapter { get { return (MySqlDataAdapter)base.DataAdapter; } set { base.DataAdapter = value; } } #region Public Methods /// /// Retrieves parameter information from the stored procedure specified /// in the MySqlCommand and populates the Parameters collection of the /// specified MySqlCommand object. /// This method is not currently supported since stored procedures are /// not available in MySql. /// /// The MySqlCommand referencing the stored /// procedure from which the parameter information is to be derived. /// The derived parameters are added to the Parameters collection of the /// MySqlCommand. /// The command text is not /// a valid stored procedure name. public static void DeriveParameters(MySqlCommand command) { if (command.CommandType != CommandType.StoredProcedure) throw new InvalidOperationException(Resources.CanNotDeriveParametersForTextCommands); // retrieve the proc definition from the cache. string spName = command.CommandText; if (spName.IndexOf(".") == -1) spName = command.Connection.Database + "." + spName; try { DataSet ds = command.Connection.ProcedureCache.GetProcedure(command.Connection, spName, null); DataTable parameters = ds.Tables["Procedure Parameters"]; DataTable procTable = ds.Tables["Procedures"]; command.Parameters.Clear(); foreach (DataRow row in parameters.Rows) { MySqlParameter p = new MySqlParameter(); p.ParameterName = String.Format("@{0}", row["PARAMETER_NAME"]); if (row["ORDINAL_POSITION"].Equals(0) && p.ParameterName == "@") p.ParameterName = "@RETURN_VALUE"; p.Direction = GetDirection(row); bool unsigned = StoredProcedure.GetFlags(row["DTD_IDENTIFIER"].ToString()).IndexOf("UNSIGNED") != -1; bool real_as_float = procTable.Rows[0]["SQL_MODE"].ToString().IndexOf("REAL_AS_FLOAT") != -1; p.MySqlDbType = MetaData.NameToType(row["DATA_TYPE"].ToString(), unsigned, real_as_float, command.Connection); if (!row["CHARACTER_MAXIMUM_LENGTH"].Equals(DBNull.Value)) p.Size = (int)row["CHARACTER_MAXIMUM_LENGTH"]; if (!row["NUMERIC_PRECISION"].Equals(DBNull.Value)) p.Precision = Convert.ToByte(row["NUMERIC_PRECISION"]); if (!row["NUMERIC_SCALE"].Equals(DBNull.Value)) p.Scale = Convert.ToByte(row["NUMERIC_SCALE"]); if (p.MySqlDbType == MySqlDbType.Set || p.MySqlDbType == MySqlDbType.Enum) p.PossibleValues = GetPossibleValues(row); command.Parameters.Add(p); } } catch (InvalidOperationException ioe) { throw new MySqlException(Resources.UnableToDeriveParameters, ioe); } } private static List GetPossibleValues(DataRow row) { string[] types = new string[] { "ENUM", "SET" }; string dtdIdentifier = row["DTD_IDENTIFIER"].ToString().Trim(); int index = 0; for (; index < 2; index++) if (dtdIdentifier.StartsWith(types[index], StringComparison.InvariantCultureIgnoreCase)) break; if (index == 2) return null; dtdIdentifier = dtdIdentifier.Substring(types[index].Length).Trim(); dtdIdentifier = dtdIdentifier.Trim('(', ')').Trim(); List values = new List(); MySqlTokenizer tokenzier = new MySqlTokenizer(dtdIdentifier); string token = tokenzier.NextToken(); int start = tokenzier.StartIndex; while (true) { if (token == null || token == ",") { int end = dtdIdentifier.Length - 1; if (token == ",") end = tokenzier.StartIndex; string value = dtdIdentifier.Substring(start, end - start).Trim('\'', '\"').Trim(); values.Add(value); start = tokenzier.StopIndex; } if (token == null) break; token = tokenzier.NextToken(); } return values; } private static ParameterDirection GetDirection(DataRow row) { string mode = row["PARAMETER_MODE"].ToString(); int ordinal = Convert.ToInt32(row["ORDINAL_POSITION"]); if (0 == ordinal) return ParameterDirection.ReturnValue; else if (mode == "IN") return ParameterDirection.Input; else if (mode == "OUT") return ParameterDirection.Output; return ParameterDirection.InputOutput; } /// /// Gets the delete command. /// /// public new MySqlCommand GetDeleteCommand() { return (MySqlCommand)base.GetDeleteCommand(); } /// /// Gets the update command. /// /// public new MySqlCommand GetUpdateCommand() { return (MySqlCommand)base.GetUpdateCommand(); } /// /// Gets the insert command. /// /// public new MySqlCommand GetInsertCommand() { return (MySqlCommand)GetInsertCommand(false); } public override string QuoteIdentifier(string unquotedIdentifier) { if (unquotedIdentifier == null) throw new ArgumentNullException("unquotedIdentifier"); // don't quote again if it is already quoted if (unquotedIdentifier.StartsWith(QuotePrefix) && unquotedIdentifier.EndsWith(QuoteSuffix)) return unquotedIdentifier; unquotedIdentifier = unquotedIdentifier.Replace(QuotePrefix, QuotePrefix + QuotePrefix); return String.Format("{0}{1}{2}", QuotePrefix, unquotedIdentifier, QuoteSuffix); } public override string UnquoteIdentifier(string quotedIdentifier) { if (quotedIdentifier == null) throw new ArgumentNullException("quotedIdentifier"); // don't unquote again if it is already unquoted if (!quotedIdentifier.StartsWith(QuotePrefix) || !quotedIdentifier.EndsWith(QuoteSuffix)) return quotedIdentifier; if (quotedIdentifier.StartsWith(QuotePrefix)) quotedIdentifier = quotedIdentifier.Substring(1); if (quotedIdentifier.EndsWith(QuoteSuffix)) quotedIdentifier = quotedIdentifier.Substring(0, quotedIdentifier.Length - 1); quotedIdentifier = quotedIdentifier.Replace(QuotePrefix + QuotePrefix, QuotePrefix); return quotedIdentifier; } #endregion protected override DataTable GetSchemaTable(DbCommand sourceCommand) { DataTable schemaTable = base.GetSchemaTable(sourceCommand); foreach (DataRow row in schemaTable.Rows) if (row["BaseSchemaName"].Equals(sourceCommand.Connection.Database)) row["BaseSchemaName"] = null; return schemaTable; } /// /// /// /// /// protected override string GetParameterName(string parameterName) { StringBuilder sb = new StringBuilder(parameterName); sb.Replace(" ", ""); sb.Replace("/", "_per_"); sb.Replace("-", "_"); sb.Replace(")", "_cb_"); sb.Replace("(", "_ob_"); sb.Replace("%", "_pct_"); sb.Replace("<", "_lt_"); sb.Replace(">", "_gt_"); sb.Replace(".", "_pt_"); return String.Format("@{0}", sb.ToString()); } protected override void ApplyParameterInfo(DbParameter parameter, DataRow row, StatementType statementType, bool whereClause) { ((MySqlParameter)parameter).MySqlDbType = (MySqlDbType)row["ProviderType"]; } protected override string GetParameterName(int parameterOrdinal) { return String.Format("@p{0}", parameterOrdinal.ToString(CultureInfo.InvariantCulture)); } protected override string GetParameterPlaceholder(int parameterOrdinal) { return String.Format("@p{0}", parameterOrdinal.ToString(CultureInfo.InvariantCulture)); } protected override void SetRowUpdatingHandler(DbDataAdapter adapter) { MySqlDataAdapter myAdapter = (adapter as MySqlDataAdapter); if (adapter != base.DataAdapter) myAdapter.RowUpdating += new MySqlRowUpdatingEventHandler(RowUpdating); else myAdapter.RowUpdating -= new MySqlRowUpdatingEventHandler(RowUpdating); } private void RowUpdating(object sender, MySqlRowUpdatingEventArgs args) { base.RowUpdatingHandler(args); } } } mysql-connector-net-6.4.3/Source/MySql.Data/MySqlClientFactory.cs0000644000175000017500000001415511127003600025421 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #if !PocketPC using System.Data.Common; using System; using System.Reflection; namespace MySql.Data.MySqlClient { /// /// DBProviderFactory implementation for MysqlClient. /// public sealed class MySqlClientFactory : DbProviderFactory, IServiceProvider { /// /// Gets an instance of the . /// This can be used to retrieve strongly typed data objects. /// public static MySqlClientFactory Instance = new MySqlClientFactory(); private Type dbServicesType; private FieldInfo mySqlDbProviderServicesInstance; /// /// Returns a strongly typed instance. /// /// A new strongly typed instance of DbCommandBuilder. public override DbCommandBuilder CreateCommandBuilder() { return new MySqlCommandBuilder(); } /// /// Returns a strongly typed instance. /// /// A new strongly typed instance of DbCommand. public override DbCommand CreateCommand() { return new MySqlCommand(); } /// /// Returns a strongly typed instance. /// /// A new strongly typed instance of DbConnection. public override DbConnection CreateConnection() { return new MySqlConnection(); } /// /// Returns a strongly typed instance. /// /// A new strongly typed instance of DbDataAdapter. public override DbDataAdapter CreateDataAdapter() { return new MySqlDataAdapter(); } /// /// Returns a strongly typed instance. /// /// A new strongly typed instance of DbParameter. public override DbParameter CreateParameter() { return new MySqlParameter(); } /// /// Returns a strongly typed instance. /// /// A new strongly typed instance of DbConnectionStringBuilder. public override DbConnectionStringBuilder CreateConnectionStringBuilder() { return new MySqlConnectionStringBuilder(); } /// /// Returns true if a MySqlDataSourceEnumerator can be created; /// otherwise false. /// public override bool CanCreateDataSourceEnumerator { get { return false; } } #region IServiceProvider Members /// /// Provide a simple caching layer /// private Type DbServicesType { get { if (dbServicesType == null) { // Get the type this way so we don't have to reference System.Data.Entity // from our core provider dbServicesType = Type.GetType( @"System.Data.Common.DbProviderServices, System.Data.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", false); } return dbServicesType; } } private FieldInfo MySqlDbProviderServicesInstance { get { if (mySqlDbProviderServicesInstance == null) { string fullName = Assembly.GetExecutingAssembly().FullName; fullName = fullName.Replace("MySql.Data", "MySql.Data.Entity"); fullName = String.Format("MySql.Data.MySqlClient.MySqlProviderServices, {0}", fullName); Type providerServicesType = Type.GetType(fullName, false); mySqlDbProviderServicesInstance = providerServicesType.GetField("Instance", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); } return mySqlDbProviderServicesInstance; } } object IServiceProvider.GetService(Type serviceType) { // DbProviderServices is the only service we offer up right now if (serviceType != DbServicesType) return null; if (MySqlDbProviderServicesInstance == null) return null; return MySqlDbProviderServicesInstance.GetValue(null); } #endregion } } #endif mysql-connector-net-6.4.3/Source/MySql.Data/common/0000755000175000017500000000000011127003600022620 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Data/common/QueryNormalizer.cs0000644000175000017500000003151411127003600026323 0ustar directhexdirecthex// Copyright (c) 2009-2010 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Diagnostics; using System.Collections; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.Common { internal class QueryNormalizer { private static List keywords = new List(); private List tokens = new List(); private int pos; private string fullSql; private string queryType; static QueryNormalizer() { StringReader sr = new StringReader(Resources.keywords); string keyword = sr.ReadLine(); while (keyword != null) { keywords.Add(keyword); keyword = sr.ReadLine(); } } public string QueryType { get { return queryType; } } public string Normalize(string sql) { tokens.Clear(); StringBuilder newSql = new StringBuilder(); fullSql = sql; TokenizeSql(sql); DetermineStatementType(tokens); ProcessMathSymbols(tokens); CollapseValueLists(tokens); CollapseInLists(tokens); CollapseWhitespace(tokens); foreach (Token t in tokens) if (t.Output) newSql.Append(t.Text); return newSql.ToString(); } private void DetermineStatementType(List tok) { foreach (Token t in tok) { if (t.Type == TokenType.Keyword) { queryType = t.Text.ToUpperInvariant(); //string s = t.Text.ToLowerInvariant(); //if (s == "select") // queryType = "SELECT"; //else if (s == "update" || s == "insert") // queryType = "UPSERT"; //else // queryType = "OTHER"; break; } } } /// /// Mark - or + signs that are unary ops as no output /// /// private void ProcessMathSymbols(List tok) { Token lastToken = null; foreach (Token t in tok) { if (t.Type == TokenType.Symbol && (t.Text == "-" || t.Text == "+")) { if (lastToken != null && lastToken.Type != TokenType.Number && lastToken.Type != TokenType.Identifier && (lastToken.Type != TokenType.Symbol || lastToken.Text != ")")) t.Output = false; } if (t.IsRealToken) lastToken = t; } } private void CollapseWhitespace(List tok) { Token lastToken = null; foreach (Token t in tok) { if (t.Output && t.Type == TokenType.Whitespace && lastToken != null && lastToken.Type == TokenType.Whitespace) { t.Output = false; } if (t.Output) lastToken = t; } } private void CollapseValueLists(List tok) { int pos = -1; while (++pos < tok.Count) { Token t = tok[pos]; if (t.Type != TokenType.Keyword) continue; if (!t.Text.StartsWith("VALUE")) continue; CollapseValueList(tok, ref pos); } } private void CollapseValueList(List tok, ref int pos) { List parenIndices = new List(); // this while loop will find all closing parens in this value list while (true) { // find the close ')' while (++pos < tok.Count) { if (tok[pos].Type == TokenType.Symbol && tok[pos].Text == ")") break; if (pos == tok.Count-1) break; } parenIndices.Add(pos); // now find the next "real" token while (++pos < tok.Count) if (tok[pos].IsRealToken) break; if (pos == tok.Count) break; if (tok[pos].Text != ",") { pos--; break; } } // if we only have 1 value then we don't collapse if (parenIndices.Count < 2) return; int index = parenIndices[0]; tok[++index] = new Token(TokenType.Whitespace, " "); tok[++index] = new Token(TokenType.Comment, "/* , ... */"); index++; // now mark all the other tokens as no output while (index <= parenIndices[parenIndices.Count - 1]) tok[index++].Output = false; } private void CollapseInLists(List tok) { int pos = -1; while (++pos < tok.Count) { Token t = tok[pos]; if (t.Type != TokenType.Keyword) continue; if (!(t.Text == "IN")) continue; CollapseInList(tok, ref pos); } } private Token GetNextRealToken(List tok, ref int pos) { while (++pos < tok.Count) { if (tok[pos].IsRealToken) return tok[pos]; } return null; } private void CollapseInList(List tok, ref int pos) { Token t = GetNextRealToken(tok, ref pos); // Debug.Assert(t.Text == "("); if (t == null) return; // if the first token is a keyword then we likely have a // SELECT .. IN (SELECT ...) t = GetNextRealToken(tok, ref pos); if (t == null || t.Type == TokenType.Keyword) return; int start = pos; // first find all the tokens that make up the in list while (++pos < tok.Count) { t = tok[pos]; if (t.Type == TokenType.CommandComment) return; if (!t.IsRealToken) continue; if (t.Text == "(") return; if (t.Text == ")") break; } int stop = pos; for (int i = stop; i > start; i--) tok.RemoveAt(i); tok.Insert(++start, new Token(TokenType.Whitespace, " ")); tok.Insert(++start, new Token(TokenType.Comment, "/* , ... */")); tok.Insert(++start, new Token(TokenType.Whitespace, " ")); tok.Insert(++start, new Token(TokenType.Symbol, ")")); } private void TokenizeSql(string sql) { pos = 0; while (pos < sql.Length) { char c = sql[pos]; if (LetterStartsComment(c) && ConsumeComment()) continue; if (Char.IsWhiteSpace(c)) ConsumeWhitespace(); else if (c == '\'' || c == '\"' || c == '`') ConsumeQuotedToken(c); else if (!IsSpecialCharacter(c)) ConsumeUnquotedToken(); else ConsumeSymbol(); } } private bool LetterStartsComment(char c) { return c == '#' || c == '/' || c == '-'; } private bool IsSpecialCharacter(char c) { if (Char.IsLetterOrDigit(c) || c == '$' || c == '_' || c == '.') return false; return true; } private bool ConsumeComment() { char c = fullSql[pos]; // make sure the comment starts correctly if (c == '/' && ((pos + 1) >= fullSql.Length || fullSql[pos + 1] != '*')) return false; if (c == '-' && ((pos + 2) >= fullSql.Length || fullSql[pos + 1] != '-' || fullSql[pos + 2] != ' ')) return false; string endingPattern = "\n"; if (c == '/') endingPattern = "*/"; int startingIndex = pos; int index = fullSql.IndexOf(endingPattern, pos); if (index == -1) index = fullSql.Length - 1; else index += endingPattern.Length; string comment = fullSql.Substring(pos, index - pos); if (comment.StartsWith("/*!")) tokens.Add(new Token(TokenType.CommandComment, comment)); pos = index; return true; } private void ConsumeSymbol() { char c = fullSql[pos++]; tokens.Add(new Token(TokenType.Symbol, c.ToString())); } private void ConsumeQuotedToken(char c) { bool escaped = false; int start = pos; pos++; while (pos < fullSql.Length) { char x = fullSql[pos]; if (x == c && !escaped) break; if (escaped) escaped = false; else if (x == '\\') escaped = true; pos++; } pos++; if (c == '\'') tokens.Add(new Token(TokenType.String, "?")); else tokens.Add(new Token(TokenType.Identifier, fullSql.Substring(start, pos - start))); } private void ConsumeUnquotedToken() { int startPos = pos; while (pos < fullSql.Length && !IsSpecialCharacter(fullSql[pos])) pos++; string word = fullSql.Substring(startPos, pos - startPos); double v; if (Double.TryParse(word, out v)) tokens.Add(new Token(TokenType.Number, "?")); else { Token t = new Token(TokenType.Identifier, word); if (IsKeyword(word)) { t.Type = TokenType.Keyword; t.Text = t.Text.ToUpperInvariant(); } tokens.Add(t); } } private void ConsumeWhitespace() { tokens.Add(new Token(TokenType.Whitespace, " ")); while (pos < fullSql.Length && Char.IsWhiteSpace(fullSql[pos])) pos++; } private bool IsKeyword(string word) { return keywords.Contains(word.ToUpperInvariant()); } } internal class Token { public TokenType Type; public string Text; public bool Output; public Token(TokenType type, string text) { Type = type; Text = text; Output = true; } public bool IsRealToken { get { return Type != TokenType.Comment && Type != TokenType.CommandComment && Type != TokenType.Whitespace && Output; } } } internal enum TokenType { Keyword, String, Number, Symbol, Identifier, Comment, CommandComment, Whitespace } }mysql-connector-net-6.4.3/Source/MySql.Data/common/Platform.cs0000644000175000017500000000375611127003600024746 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; namespace MySql.Data.Common { internal class Platform { private static bool inited; private static bool isMono; /// /// By creating a private ctor, we keep the compiler from creating a default ctor /// private Platform() { } public static bool IsWindows() { OperatingSystem os = Environment.OSVersion; switch (os.Platform) { case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: return true; } return false; } public static bool IsMono() { if (!inited) Init(); return isMono; } private static void Init() { inited = true; Type t = Type.GetType("Mono.Runtime"); isMono = t != null; } } } mysql-connector-net-6.4.3/Source/MySql.Data/common/MySqlTokenizer.cs0000644000175000017500000002247511127003600026121 0ustar directhexdirecthex// Copyright 2004,2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Text; using System.IO; using System.Collections.Generic; using System.Diagnostics; namespace MySql.Data.MySqlClient { internal class MySqlTokenizer { private string sql; private int startIndex; private int stopIndex; private bool ansiQuotes; private bool backslashEscapes; private bool returnComments; private bool multiLine; private bool sqlServerMode; private bool quoted; private bool isComment; private int pos; public MySqlTokenizer() { backslashEscapes = true; multiLine = true; pos = 0; } public MySqlTokenizer(string input) : this() { sql = input; } #region Properties public string Text { get { return sql; } set { sql = value; pos = 0; } } public bool AnsiQuotes { get { return ansiQuotes; } set { ansiQuotes = value; } } public bool BackslashEscapes { get { return backslashEscapes; } set { backslashEscapes = value; } } public bool MultiLine { get { return multiLine; } set { multiLine = value; } } public bool SqlServerMode { get { return sqlServerMode; } set { sqlServerMode = value; } } public bool Quoted { get { return quoted; } private set { quoted = value; } } public bool IsComment { get { return isComment; } } public int StartIndex { get { return startIndex; } set { startIndex = value; } } public int StopIndex { get { return stopIndex; } set { stopIndex = value; } } public int Position { get { return pos; } set { pos = value; } } public bool ReturnComments { get { return returnComments; } set { returnComments = value; } } #endregion public List GetAllTokens() { List tokens = new List(); string token = NextToken(); while (token != null) { tokens.Add(token); token = NextToken(); } return tokens; } public string NextToken() { while (FindToken()) { string token = sql.Substring(startIndex, stopIndex - startIndex); return token; } return null; } public static bool IsParameter(string s) { if (String.IsNullOrEmpty(s)) return false; if (s[0] == '?') return true; if (s.Length > 1 && s[0] == '@' && s[1] != '@') return true; return false; } public string NextParameter() { while (FindToken()) { if ((stopIndex - startIndex) < 2) continue; char c1 = sql[startIndex]; char c2 = sql[startIndex+1]; if (c1 == '?' || (c1 == '@' && c2 != '@')) return sql.Substring(startIndex, stopIndex - startIndex); } return null; } public bool FindToken() { isComment = quoted = false; // reset our flags startIndex = stopIndex = -1; while (pos < sql.Length) { char c = sql[pos++]; if (Char.IsWhiteSpace(c)) continue; if (c == '`' || c == '\'' || c == '"' || (c == '[' && SqlServerMode)) ReadQuotedToken(c); else if (c == '#' || c == '-' || c == '/') { if (!ReadComment(c)) ReadSpecialToken(); } else ReadUnquotedToken(); if (startIndex != -1) return true; } return false; } public string ReadParenthesis() { StringBuilder sb = new StringBuilder("("); int start = StartIndex; string token = NextToken(); while (true) { if (token == null) throw new InvalidOperationException("Unable to parse SQL"); sb.Append(token); if (token == ")" && !Quoted) break; token = NextToken(); } return sb.ToString(); } private bool ReadComment(char c) { // make sure the comment starts correctly if (c == '/' && (pos >= sql.Length || sql[pos] != '*')) return false; if (c == '-' && ((pos + 1) >= sql.Length || sql[pos] != '-' || sql[pos + 1] != ' ')) return false; string endingPattern = "\n"; if (sql[pos] == '*') endingPattern = "*/"; int startingIndex = pos-1; int index = sql.IndexOf(endingPattern, pos); if (endingPattern == "\n") index = sql.IndexOf('\n', pos); if (index == -1) index = sql.Length - 1; else index += endingPattern.Length; pos = index; if (ReturnComments) { startIndex = startingIndex; stopIndex = index; isComment = true; } return true; } private void CalculatePosition(int start, int stop) { startIndex = start; stopIndex = stop; if (!MultiLine) return; } private void ReadUnquotedToken() { startIndex = pos-1; if (!IsSpecialCharacter(sql[startIndex])) { while (pos < sql.Length) { char c = sql[pos]; if (Char.IsWhiteSpace(c)) break; if (IsSpecialCharacter(c)) break; pos++; } } Quoted = false; stopIndex = pos; } private void ReadSpecialToken() { startIndex = pos - 1; Debug.Assert(IsSpecialCharacter(sql[startIndex])); stopIndex = pos; Quoted = false; } /// /// Read a single quoted identifier from the stream /// /// /// private void ReadQuotedToken(char quoteChar) { if (quoteChar == '[') quoteChar = ']'; startIndex = pos-1; bool escaped = false; bool found = false; while (pos < sql.Length) { char c = sql[pos]; if (c == quoteChar && !escaped) { found = true; break; } if (escaped) escaped = false; else if (c == '\\' && BackslashEscapes) escaped = true; pos++; } if (found) pos++; Quoted = found; stopIndex = pos; } private bool IsQuoteChar(char c) { return c == '`' || c == '\'' || c == '\"'; } private bool IsParameterMarker(char c) { return c == '@' || c == '?'; } private bool IsSpecialCharacter(char c) { if (Char.IsLetterOrDigit(c) || c == '$' || c == '_' || c == '.') return false; if (IsParameterMarker(c)) return false; return true; } } } mysql-connector-net-6.4.3/Source/MySql.Data/common/Version.cs0000644000175000017500000000627711127003600024610 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.Common { /// /// Summary description for Version. /// internal struct DBVersion { private int major; private int minor; private int build; private string srcString; public DBVersion( string s, int major, int minor, int build) { this.major = major; this.minor = minor; this.build = build; srcString = s; } public int Major { get { return major; } } public int Minor { get { return minor; } } public int Build { get { return build; } } public static DBVersion Parse( string versionString ) { int start = 0; int index = versionString.IndexOf('.', start); if (index == -1) throw new MySqlException(Resources.BadVersionFormat); string val = versionString.Substring(start, index-start).Trim(); int major = Convert.ToInt32(val, System.Globalization.NumberFormatInfo.InvariantInfo); start = index+1; index = versionString.IndexOf('.', start); if (index == -1) throw new MySqlException(Resources.BadVersionFormat); val = versionString.Substring(start, index-start).Trim(); int minor = Convert.ToInt32(val, System.Globalization.NumberFormatInfo.InvariantInfo); start = index+1; int i = start; while (i < versionString.Length && Char.IsDigit(versionString, i)) i++; val = versionString.Substring(start, i-start).Trim(); int build = Convert.ToInt32(val, System.Globalization.NumberFormatInfo.InvariantInfo); return new DBVersion(versionString, major, minor, build); } public bool isAtLeast(int majorNum, int minorNum, int buildNum) { if (major > majorNum) return true; if (major == majorNum && minor > minorNum) return true; if (major == majorNum && minor == minorNum && build >= buildNum) return true; return false; } public override string ToString() { return srcString; } } } mysql-connector-net-6.4.3/Source/MySql.Data/common/StreamCreator.cs0000644000175000017500000002155111127003600025726 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Diagnostics; using MySql.Data.MySqlClient.Properties; using System.Runtime.InteropServices; namespace MySql.Data.Common { /// /// Summary description for StreamCreator. /// internal class StreamCreator { string hostList; uint port; string pipeName; uint timeOut; uint keepalive; public StreamCreator(string hosts, uint port, string pipeName, uint keepalive) { hostList = hosts; if (hostList == null || hostList.Length == 0) hostList = "localhost"; this.port = port; this.pipeName = pipeName; this.keepalive = keepalive; } private Stream GetStreamFromHost(string pipeName, string hostName, uint timeout) { Stream stream = null; if (pipeName != null && pipeName.Length != 0) { #if !CF stream = NamedPipeStream.Create(pipeName, hostName, timeout); #endif } else { IPHostEntry ipHE = GetHostEntry(hostName); foreach (IPAddress address in ipHE.AddressList) { try { stream = CreateSocketStream(address, false); if (stream != null) break; } catch (Exception ex) { SocketException socketException = ex as SocketException; // if the exception is a ConnectionRefused then we eat it as we may have other address // to attempt if (socketException == null) throw; #if !CF if (socketException.SocketErrorCode != SocketError.ConnectionRefused) throw; #endif } } } return stream; } public Stream GetStream(uint timeout) { timeOut = timeout; if (hostList.StartsWith("/", StringComparison.OrdinalIgnoreCase)) return CreateSocketStream(null, true); string[] dnsHosts = hostList.Split(','); Random random = new Random((int)DateTime.Now.Ticks); int index = random.Next(dnsHosts.Length); int pos = 0; Stream stream = null; while (stream == null && pos < dnsHosts.Length) { stream = GetStreamFromHost(pipeName, dnsHosts[index++], timeout); if (index == dnsHosts.Length) index = 0; pos++; } return stream; } private IPHostEntry ParseIPAddress(string hostname) { IPHostEntry ipHE = null; #if !CF IPAddress addr; if (IPAddress.TryParse(hostname, out addr)) { ipHE = new IPHostEntry(); ipHE.AddressList = new IPAddress[1]; ipHE.AddressList[0] = addr; } #endif return ipHE; } #if CF IPHostEntry GetDnsHostEntry(string hostname) { return Dns.GetHostEntry(hostname); } #else IPHostEntry GetDnsHostEntry(string hostname) { LowResolutionStopwatch stopwatch = new LowResolutionStopwatch(); try { stopwatch.Start(); return Dns.GetHostEntry(hostname); } catch (SocketException ex) { string message = String.Format(Resources.GetHostEntryFailed, stopwatch.Elapsed, hostname, ex.SocketErrorCode, ex.ErrorCode, ex.NativeErrorCode); throw new Exception(message, ex); } finally { stopwatch.Stop(); } } #endif private IPHostEntry GetHostEntry(string hostname) { IPHostEntry ipHE = ParseIPAddress(hostname); if (ipHE != null) return ipHE; return GetDnsHostEntry(hostname); } #if !CF private static EndPoint CreateUnixEndPoint(string host) { // first we need to load the Mono.posix assembly Assembly a = Assembly.Load(@"Mono.Posix, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"); // then we need to construct a UnixEndPoint object EndPoint ep = (EndPoint)a.CreateInstance("Mono.Posix.UnixEndPoint", false, BindingFlags.CreateInstance, null, new object[1] { host }, null, null); return ep; } #endif private Stream CreateSocketStream(IPAddress ip, bool unix) { EndPoint endPoint; #if !CF if (!Platform.IsWindows() && unix) endPoint = CreateUnixEndPoint(hostList); else #endif endPoint = new IPEndPoint(ip, (int)port); Socket socket = unix ? new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP) : new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp); if (keepalive > 0) { SetKeepAlive(socket, keepalive); } IAsyncResult ias = socket.BeginConnect(endPoint, null, null); if (!ias.AsyncWaitHandle.WaitOne((int)timeOut * 1000, false)) { socket.Close(); return null; } try { socket.EndConnect(ias); } catch (Exception) { socket.Close(); throw; } MyNetworkStream stream = new MyNetworkStream(socket, true); GC.SuppressFinalize(socket); GC.SuppressFinalize(stream); return stream; } /// /// Set keepalive + timeout on socket. /// /// socket /// keepalive timeout, in seconds private static void SetKeepAlive(Socket s, uint time) { #if !CF uint on = 1; uint interval = 1000; // default interval = 1 sec uint timeMilliseconds; if (time > UInt32.MaxValue / 1000) timeMilliseconds = UInt32.MaxValue; else timeMilliseconds = time * 1000; // Use Socket.IOControl to implement equivalent of // WSAIoctl with SOL_KEEPALIVE_VALS // the native structure passed to WSAIoctl is //struct tcp_keepalive { // ULONG onoff; // ULONG keepalivetime; // ULONG keepaliveinterval; //}; // marshal the equivalent of the native structure into a byte array byte[] inOptionValues = new byte[12]; BitConverter.GetBytes(on).CopyTo(inOptionValues, 0); BitConverter.GetBytes(time).CopyTo(inOptionValues, 4); BitConverter.GetBytes(interval).CopyTo(inOptionValues, 8); try { // call WSAIoctl via IOControl s.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); return; } catch (NotImplementedException) { // Mono throws not implemented currently } #endif // Fallback if Socket.IOControl is not available ( Compact Framework ) // or not implemented ( Mono ). Keepalive option will still be set, but // with timeout is kept default. s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1); } } } mysql-connector-net-6.4.3/Source/MySql.Data/common/SocketStream.cs0000644000175000017500000000732711127003600025564 0ustar directhexdirecthex// Copyright (c) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Collections; namespace MySql.Data.Common { /// /// Summary description for MySqlSocket. /// internal sealed class SocketStream : Stream { private Socket socket; public SocketStream(AddressFamily addressFamily, SocketType socketType, ProtocolType protocol) { socket = new Socket(addressFamily, socketType, protocol); } #region Properties public Socket Socket { get { return socket; } } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { throw new NotSupportedException("SocketStream does not support seek"); } } #endregion #region Stream Implementation public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { return socket.Receive(buffer, offset, count, SocketFlags.None); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("SocketStream does not support seek"); } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) { socket.Send(buffer, offset, count, SocketFlags.None); } #endregion public bool Connect(EndPoint remoteEP, int timeout) { // set the socket to non blocking socket.Blocking = false; // then we star the connect SocketAddress addr = remoteEP.Serialize(); byte[] buff = new byte[addr.Size]; for (int i=0; i, like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Runtime.InteropServices; using System.Threading; namespace MySql.Data.Common { internal class NativeMethods { // Keep the compiler from generating a default ctor private NativeMethods() { } //Constants for dwDesiredAccess: public const UInt32 GENERIC_READ = 0x80000000; public const UInt32 GENERIC_WRITE = 0x40000000; //Constants for return value: public const Int32 INVALIDpipeHandle_VALUE = -1; //Constants for dwFlagsAndAttributes: public const UInt32 FILE_FLAG_OVERLAPPED = 0x40000000; public const UInt32 FILE_FLAG_NO_BUFFERING = 0x20000000; //Constants for dwCreationDisposition: public const UInt32 OPEN_EXISTING = 3; [StructLayout(LayoutKind.Sequential)] public class SecurityAttributes { public SecurityAttributes() { Length = Marshal.SizeOf(typeof(SecurityAttributes)); } public int Length; public IntPtr securityDescriptor = IntPtr.Zero; public bool inheritHandle; } [DllImport("Kernel32", CharSet=CharSet.Unicode)] static extern public IntPtr CreateFile( String fileName, uint desiredAccess, uint shareMode, SecurityAttributes securityAttributes, uint creationDisposition, uint flagsAndAttributes, uint templateFile); [return:MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll", EntryPoint="PeekNamedPipe", SetLastError=true)] static extern public bool PeekNamedPipe(IntPtr handle, byte[] buffer, uint nBufferSize, ref uint bytesRead, ref uint bytesAvail, ref uint BytesLeftThisMessage); [return:MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll", SetLastError=true)] static extern public bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped); [return:MarshalAs(UnmanagedType.Bool)] [DllImport("Kernel32")] public static extern bool WriteFile(IntPtr hFile, [In]byte[] buffer, uint numberOfBytesToWrite, out uint numberOfBytesWritten, IntPtr lpOverlapped); [return:MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll", SetLastError=true)] public static extern bool CloseHandle(IntPtr handle); [return: MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll", SetLastError = true)] public static extern bool CancelIo(IntPtr handle); [return:MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll", SetLastError=true)] public static extern bool FlushFileBuffers(IntPtr handle); [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr OpenEvent(uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)]bool bInheritHandle, string lpName); [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] public static extern IntPtr OpenFileMapping(uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)]bool bInheritHandle, string lpName); [DllImport("kernel32.dll")] public static extern IntPtr MapViewOfFile(IntPtr hFileMappingObject, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, IntPtr dwNumberOfBytesToMap); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool UnmapViewOfFile(IntPtr lpBaseAddress); [DllImport("kernel32.dll", SetLastError = true)] public static extern int FlushViewOfFile(IntPtr address, uint numBytes); [DllImport("kernel32.dll", SetLastError = true)] public static extern bool WaitNamedPipe(string namedPipeName, uint timeOut); #region Winsock functions // SOcket routines [DllImport("ws2_32.dll", SetLastError=true)] static extern public IntPtr socket(int af, int type, int protocol); [DllImport("ws2_32.dll", SetLastError=true)] static extern public int ioctlsocket(IntPtr socket, uint cmd, ref UInt32 arg); [DllImport("ws2_32.dll", SetLastError=true)] public static extern int WSAIoctl(IntPtr s, uint dwIoControlCode, byte[] inBuffer, uint cbInBuffer, byte[] outBuffer, uint cbOutBuffer, IntPtr lpcbBytesReturned, IntPtr lpOverlapped, IntPtr lpCompletionRoutine); [DllImport("ws2_32.dll", SetLastError=true)] static extern public int WSAGetLastError(); [DllImport("ws2_32.dll", SetLastError=true)] static extern public int connect(IntPtr socket, byte[] addr, int addrlen); [DllImport("ws2_32.dll", SetLastError=true)] static extern public int recv(IntPtr socket, byte[] buff, int len, int flags); [DllImport("ws2_32.Dll", SetLastError=true)] static extern public int send(IntPtr socket, byte[] buff, int len, int flags); #endregion } } mysql-connector-net-6.4.3/Source/MySql.Data/common/Cache.cs0000644000175000017500000000506011127003600024153 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; namespace MySql.Data.Common { internal class Cache { private int _capacity; private Queue _keyQ; private Dictionary _contents; public Cache(int initialCapacity, int capacity) { _capacity = capacity; _contents = new Dictionary(initialCapacity); if (capacity > 0) _keyQ = new Queue(initialCapacity); } public ValueType this[KeyType key] { get { ValueType val; if (_contents.TryGetValue(key, out val)) return val; else return default(ValueType); } set { InternalAdd(key, value); } } public void Add(KeyType key, ValueType value) { InternalAdd(key, value); } private void InternalAdd(KeyType key, ValueType value) { if (!_contents.ContainsKey(key)) { if (_capacity > 0) { _keyQ.Enqueue(key); if (_keyQ.Count > _capacity) _contents.Remove(_keyQ.Dequeue()); } } _contents[key] = value; } } } mysql-connector-net-6.4.3/Source/MySql.Data/common/ContextString.cs0000644000175000017500000001411511127003600025764 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Text; namespace MySql.Data.Common { internal class ContextString { string contextMarkers; bool escapeBackslash; // Create a private ctor so the compiler doesn't give us a default one public ContextString(string contextMarkers, bool escapeBackslash) { this.contextMarkers = contextMarkers; this.escapeBackslash = escapeBackslash; } public string ContextMarkers { get { return contextMarkers; } set { contextMarkers = value; } } public int IndexOf(string src, string target) { return IndexOf(src, target, 0); } public int IndexOf(string src, string target, int startIndex) { int index = src.IndexOf(target, startIndex); while (index != -1) { if (!IndexInQuotes(src, index, startIndex)) break; index = src.IndexOf(target, index + 1); } return index; } private bool IndexInQuotes(string src, int index, int startIndex) { char contextMarker = Char.MinValue; bool escaped = false; for (int i = startIndex; i < index; i++) { char c = src[i]; int contextIndex = contextMarkers.IndexOf(c); // if we have found the closing marker for our open marker, then close the context if (contextIndex > -1 && contextMarker == contextMarkers[contextIndex] && !escaped) contextMarker = Char.MinValue; // if we have found a context marker and we are not in a context yet, then start one else if (contextMarker == Char.MinValue && contextIndex > -1 && !escaped) contextMarker = c; else if (c == '\\' && escapeBackslash) escaped = !escaped; } return contextMarker != Char.MinValue || escaped; } public int IndexOf(string src, char target) { char contextMarker = Char.MinValue; bool escaped = false; int pos = 0; foreach (char c in src) { int contextIndex = contextMarkers.IndexOf(c); // if we have found the closing marker for our open marker, then close the context if (contextIndex > -1 && contextMarker == contextMarkers[contextIndex] && !escaped) contextMarker = Char.MinValue; // if we have found a context marker and we are not in a context yet, then start one else if (contextMarker == Char.MinValue && contextIndex > -1 && !escaped) contextMarker = c; else if (contextMarker == Char.MinValue && c == target) return pos; else if (c == '\\' && escapeBackslash) escaped = !escaped; pos++; } return -1; } public string[] Split(string src, string delimiters) { ArrayList parts = new ArrayList(); StringBuilder sb = new StringBuilder(); bool escaped = false; char contextMarker = Char.MinValue; foreach (char c in src) { if (delimiters.IndexOf(c) != -1 && !escaped) { if (contextMarker != Char.MinValue) sb.Append(c); else { if (sb.Length > 0) { parts.Add( sb.ToString() ); sb.Remove( 0, sb.Length ); } } } else if (c == '\\' && escapeBackslash) escaped = !escaped; else { int contextIndex = contextMarkers.IndexOf(c); if (!escaped && contextIndex != -1) { // if we have found the closing marker for our open // marker, then close the context if ((contextIndex % 2) == 1) { if (contextMarker == contextMarkers[contextIndex - 1]) contextMarker = Char.MinValue; } else { // if the opening and closing context markers are // the same then we will always find the opening // marker. if (contextMarker == contextMarkers[contextIndex + 1]) contextMarker = Char.MinValue; else if (contextMarker == Char.MinValue) contextMarker = c; } } sb.Append( c ); } } if (sb.Length > 0) parts.Add( sb.ToString() ); return (string[])parts.ToArray( typeof(string) ); } } } mysql-connector-net-6.4.3/Source/MySql.Data/common/MyNetworkStream.cs0000644000175000017500000001274111127003600026267 0ustar directhexdirecthex// Copyright (c) 2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Net.Sockets; internal class MyNetworkStream : NetworkStream { /// /// Wrapper around NetworkStream. /// /// MyNetworkStream is equivalent to NetworkStream, except /// 1. It throws TimeoutException if read or write timeout occurs, instead /// of IOException, to match behavior of other streams (named pipe and /// shared memory). This property comes handy in TimedStream. /// /// 2. It implements workarounds for WSAEWOULDBLOCK errors, that can start /// occuring after stream has times out. For a discussion about the CLR bug, /// refer to http://tinyurl.com/lhgpyf. This error should never occur, as /// we're not using asynchronous operations, but apparerntly it does occur /// directly after timeout has expired. /// The workaround is hinted in the URL above and implemented like this: /// For each IO operation, if it throws WSAEWOULDBLOCK, we explicitely set /// the socket to Blocking and retry the operation once again. /// const int MaxRetryCount = 2; Socket socket; public MyNetworkStream(Socket socket, bool ownsSocket) : base(socket, ownsSocket) { this.socket = socket; } bool IsTimeoutException(SocketException e) { #if CF return (e.NativeErrorCode == 10060); #else return (e.SocketErrorCode == SocketError.TimedOut); #endif } bool IsWouldBlockException(SocketException e) { #if CF return (e.NativeErrorCode == 10035); #else return (e.SocketErrorCode == SocketError.WouldBlock); #endif } void HandleOrRethrowException(Exception e) { Exception currentException = e; while (currentException != null) { if (currentException is SocketException) { SocketException socketException = (SocketException)currentException; if (IsWouldBlockException(socketException)) { // Workaround for WSAEWOULDBLOCK socket.Blocking= true; // return to give the caller possibility to retry the call return; } else if (IsTimeoutException(socketException)) { throw new TimeoutException(socketException.Message, e); } } currentException = currentException.InnerException; } throw (e); } public override int Read(byte[] buffer, int offset, int count) { int retry = 0; Exception exception = null; do { try { return base.Read(buffer, offset, count); } catch (Exception e) { exception = e; HandleOrRethrowException(e); } } while (++retry < MaxRetryCount); throw exception; } public override int ReadByte() { int retry = 0; Exception exception = null; do { try { return base.ReadByte(); } catch (Exception e) { exception = e; HandleOrRethrowException(e); } } while (++retry < MaxRetryCount); throw exception; } public override void Write(byte[] buffer, int offset, int count) { int retry = 0; Exception exception = null; do { try { base.Write(buffer, offset, count); return; } catch (Exception e) { exception = e; HandleOrRethrowException(e); } } while (++retry < MaxRetryCount); throw exception; } public override void Flush() { int retry = 0; Exception exception = null; do { try { base.Flush(); return; } catch (Exception e) { exception = e; HandleOrRethrowException(e); } } while (++retry < MaxRetryCount); throw exception; } }mysql-connector-net-6.4.3/Source/MySql.Data/common/LowResolutionStopwatch.cs0000644000175000017500000000573111127003600027677 0ustar directhexdirecthex// Copyright (c) 2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; namespace MySql.Data.Common { /// /// This class is modeled after .NET Stopwatch. It provides better /// performance (no system calls).It is however less precise than /// .NET Stopwatch, measuring in milliseconds. It is adequate to use /// when high-precision is not required (e.g for measuring IO timeouts), /// but not for other tasks. /// class LowResolutionStopwatch { long millis; long startTime; public static readonly long Frequency = 1000; // measure in milliseconds public static readonly bool isHighResolution = false; public LowResolutionStopwatch() { millis = 0; } public long ElapsedMilliseconds { get { return millis; } } public void Start() { startTime = Environment.TickCount; } public void Stop() { long now = Environment.TickCount; // Calculate time different, handle possible overflow long elapsed = (now < startTime)?Int32.MaxValue - startTime + now : now - startTime; millis += elapsed; } public void Reset() { millis = 0; startTime = 0; } public TimeSpan Elapsed { get { return new TimeSpan(0, 0, 0, 0, (int)millis); } } public static LowResolutionStopwatch StartNew() { LowResolutionStopwatch sw = new LowResolutionStopwatch(); sw.Start(); return sw; } public static long GetTimestamp() { return Environment.TickCount; } bool IsRunning() { return (startTime != 0); } } } mysql-connector-net-6.4.3/Source/MySql.Data/common/NamedPipeStream.cs0000644000175000017500000001713011127003600026167 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.IO; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Properties; using Microsoft.Win32.SafeHandles; using System.Threading; using System.Diagnostics; using System.Runtime.InteropServices; using System.ComponentModel; namespace MySql.Data.Common { /// /// Summary description for API. /// internal class NamedPipeStream : Stream { SafeFileHandle handle; Stream fileStream; int readTimeout = Timeout.Infinite; int writeTimeout = Timeout.Infinite; const int ERROR_PIPE_BUSY = 231; const int ERROR_SEM_TIMEOUT = 121; public NamedPipeStream(string path, FileAccess mode, uint timeout) { Open(path, mode, timeout); } void CancelIo() { bool ok = NativeMethods.CancelIo(handle.DangerousGetHandle()); if (!ok) throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } public void Open( string path, FileAccess mode ,uint timeout ) { IntPtr nativeHandle; for (; ; ) { nativeHandle = NativeMethods.CreateFile(path, NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, 0, null, NativeMethods.OPEN_EXISTING, NativeMethods.FILE_FLAG_OVERLAPPED, 0); if (nativeHandle != IntPtr.Zero) break; if (Marshal.GetLastWin32Error() != ERROR_PIPE_BUSY) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Error opening pipe"); } LowResolutionStopwatch sw = LowResolutionStopwatch.StartNew(); bool success = NativeMethods.WaitNamedPipe(path, timeout); sw.Stop(); if (!success) { if (timeout < sw.ElapsedMilliseconds || Marshal.GetLastWin32Error() == ERROR_SEM_TIMEOUT) { throw new TimeoutException("Timeout waiting for named pipe"); } else { throw new Win32Exception(Marshal.GetLastWin32Error(), "Error waiting for pipe"); } } timeout -= (uint)sw.ElapsedMilliseconds; } handle = new SafeFileHandle(nativeHandle, true); fileStream = new FileStream(handle, mode, 4096, true); } public override bool CanRead { get { return fileStream.CanRead; } } public override bool CanWrite { get { return fileStream.CanWrite; } } public override bool CanSeek { get { throw new NotSupportedException(Resources.NamedPipeNoSeek); } } public override long Length { get { throw new NotSupportedException(Resources.NamedPipeNoSeek); } } public override long Position { get { throw new NotSupportedException(Resources.NamedPipeNoSeek); } set { } } public override void Flush() { fileStream.Flush(); } public override int Read(byte[] buffer, int offset, int count) { if(readTimeout == Timeout.Infinite) { return fileStream.Read(buffer, offset, count); } IAsyncResult result = fileStream.BeginRead(buffer, offset, count, null, null); if (result.CompletedSynchronously) return fileStream.EndRead(result); if (!result.AsyncWaitHandle.WaitOne(readTimeout)) { CancelIo(); throw new TimeoutException("Timeout in named pipe read"); } return fileStream.EndRead(result); } public override void Write(byte[] buffer, int offset, int count) { if (writeTimeout == Timeout.Infinite) { fileStream.Write(buffer, offset, count); return; } IAsyncResult result = fileStream.BeginWrite(buffer, offset, count, null, null); if (result.CompletedSynchronously) { fileStream.EndWrite(result); } if (!result.AsyncWaitHandle.WaitOne(readTimeout)) { CancelIo(); throw new TimeoutException("Timeout in named pipe write"); } fileStream.EndWrite(result); } public override void Close() { if (handle != null && !handle.IsInvalid && !handle.IsClosed) { fileStream.Close(); try { handle.Close(); } catch (Exception) { } } } public override void SetLength(long length) { throw new NotSupportedException(Resources.NamedPipeNoSetLength); } public override bool CanTimeout { get { return true; } } public override int ReadTimeout { get { return readTimeout; } set { readTimeout = value; } } public override int WriteTimeout { get { return writeTimeout; } set { writeTimeout = value; } } public override long Seek( long offset, SeekOrigin origin ) { throw new NotSupportedException(Resources.NamedPipeNoSeek); } internal static Stream Create(string pipeName, string hostname, uint timeout) { string pipePath; if (0 == String.Compare(hostname, "localhost", true)) pipePath = @"\\.\pipe\" + pipeName; else pipePath = String.Format(@"\\{0}\pipe\{1}", hostname, pipeName); return new NamedPipeStream(pipePath, FileAccess.ReadWrite, timeout); } } } mysql-connector-net-6.4.3/Source/MySql.Data/common/SHA1.cs0000644000175000017500000002534411127003600023653 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /* Original Source from: http://www.faqs.org/rfcs/rfc3174.html Copyright (C) The Internet Society (2001). All Rights Reserved. This document and translations of it may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and this paragraph are included on all such copies and derivative works. However, this document itself may not be modified in any way, such as by removing the copyright notice or references to the Internet Society or other Internet organizations, except as needed for the purpose of developing Internet standards in which case the procedures for copyrights defined in the Internet Standards process must be followed, or as required to translate it into languages other than English. The limited permissions granted above are perpetual and will not be revoked by the Internet Society or its successors or assigns. This document and the information contained herein is provided on an "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Acknowledgement Funding for the RFC Editor function is currently provided by the Internet Society. */ using System; namespace MySql.Data.Common { class SHA1Hash { private const int SHA1_HASH_SIZE = 20; // Hash size in bytes // Constants defined in SHA-1 private static uint[] K = new uint[4] { 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6 }; private static uint[] sha_const_key = new uint[5] { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 }; private ulong length; // Message length in bits private uint[] intermediateHash; // Message Digest private bool computed; // Is the digest computed? // private bool corrupted; // Is the message digest corrupted? private short messageBlockIndex; // Index into message block array private byte[] messageBlock; // 512-bit message blocks public SHA1Hash() { intermediateHash = new uint[SHA1_HASH_SIZE/4]; messageBlock = new byte[64]; Reset(); } public void Reset() { /*#ifndef DBUG_OFF if (!context) return SHA_NULL; #endif*/ length = 0; messageBlockIndex = 0; intermediateHash[0] = sha_const_key[0]; intermediateHash[1] = sha_const_key[1]; intermediateHash[2] = sha_const_key[2]; intermediateHash[3] = sha_const_key[3]; intermediateHash[4] = sha_const_key[4]; computed = false; // corrupted = false; } public byte[] ComputeHash(byte[] buffer) { Reset(); Input(buffer, 0, buffer.Length); return Result(); } public void Input(byte[] buffer, int index, int bufLen) { if (buffer == null || bufLen == 0) return; if (index < 0 || index > buffer.Length - 1) throw new ArgumentException("Index must be a value between 0 and buffer.Length-1", "index"); if (bufLen < 0) throw new ArgumentException("Length must be a value > 0", "length"); if ((bufLen+index) > buffer.Length) throw new ArgumentException("Length + index would extend past the end of buffer", "length"); /*#ifndef DBUG_OFF // We assume client konows what it is doing in non-debug mode if (!context || !message_array) return SHA_NULL; if (context->Computed) return (context->Corrupted= SHA_STATE_ERROR); if (context->Corrupted) return context->Corrupted; #endif*/ while (bufLen-- > 0) { messageBlock[messageBlockIndex++] = (byte)(buffer[index++] & 0xFF); length += 8; /* Length is in bits */ /*#ifndef DBUG_OFF // Then we're not debugging we assume we never will get message longer //2^64 bits. if (context->Length == 0) return (context->Corrupted= 1); // Message is too long #endif*/ if (messageBlockIndex == 64) ProcessMessageBlock(); } } private void ProcessMessageBlock() { uint temp; // Temporary word value uint[] W; // Word sequence uint A, B, C, D, E; // Word buffers W = new uint[80]; //Initialize the first 16 words in the array W for (int t = 0; t < 16; t++) { int index=t*4; W[t] = (uint)messageBlock[index] << 24; W[t] |= (uint)messageBlock[index + 1] << 16; W[t] |= (uint)messageBlock[index + 2] << 8; W[t] |= (uint)messageBlock[index + 3]; } for (int t = 16; t < 80; t++) { W[t] = CircularShift(1, W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]); } A = intermediateHash[0]; B = intermediateHash[1]; C = intermediateHash[2]; D = intermediateHash[3]; E = intermediateHash[4]; for (int t = 0; t < 20; t++) { temp= CircularShift(5, A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0]; E = D; D = C; C = CircularShift(30, B); B = A; A = temp; } for (int t = 20; t < 40; t++) { temp = CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1]; E = D; D = C; C = CircularShift(30,B); B = A; A = temp; } for (int t = 40; t < 60; t++) { temp= (CircularShift(5,A) + ((B & C) | (B & D) | (C & D)) + E + W[t] + K[2]); E = D; D = C; C = CircularShift(30,B); B = A; A = temp; } for (int t = 60; t < 80; t++) { temp = CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3]; E = D; D = C; C = CircularShift(30,B); B = A; A = temp; } intermediateHash[0] += A; intermediateHash[1] += B; intermediateHash[2] += C; intermediateHash[3] += D; intermediateHash[4] += E; messageBlockIndex = 0; } private static uint CircularShift(int bits, uint word) { return (((word) << (bits)) | ((word) >> (32-(bits)))); } private void PadMessage() { /* Check to see if the current message block is too small to hold the initial padding bits and length. If so, we will pad the block, process it, and then continue padding into a second block. */ int i = messageBlockIndex; if (i > 55) { messageBlock[i++] = 0x80; Array.Clear(messageBlock, i, 64-i); //bzero((char*) &context->Message_Block[i], sizeof(messageBlock[0])*(64-i)); messageBlockIndex = 64; /* This function sets messageBlockIndex to zero */ ProcessMessageBlock(); Array.Clear(messageBlock, 0, 56); //bzero((char*) &context->Message_Block[0], sizeof(messageBlock[0])*56); messageBlockIndex = 56; } else { messageBlock[i++] = 0x80; Array.Clear(messageBlock, i, 56-i); //bzero((char*) &messageBlock[i], sizeof(messageBlock[0])*(56-i)); messageBlockIndex = 56; } // Store the message length as the last 8 octets messageBlock[56] = (byte)(length >> 56); messageBlock[57] = (byte)(length >> 48); messageBlock[58] = (byte)(length >> 40); messageBlock[59] = (byte)(length >> 32); messageBlock[60] = (byte)(length >> 24); messageBlock[61] = (byte)(length >> 16); messageBlock[62] = (byte)(length >> 8); messageBlock[63] = (byte)length; ProcessMessageBlock(); } public byte[] Result() { /*#ifndef DBUG_OFF if (!context || !Message_Digest) return SHA_NULL; if (context->Corrupted) return context->Corrupted; #endif*/ if (!computed) { PadMessage(); // message may be sensitive, clear it out Array.Clear(messageBlock, 0, 64); //bzero((char*) messageBlock,64); length = 0; /* and clear length */ computed = true; } byte[] messageDigest = new byte[SHA1_HASH_SIZE]; for (int i = 0; i < SHA1_HASH_SIZE; i++) messageDigest[i] = (byte)((intermediateHash[i>>2] >> 8 * ( 3 - ( i & 0x03 ) ))); return messageDigest; } } } mysql-connector-net-6.4.3/Source/MySql.Data/common/SharedMemoryStream.cs0000644000175000017500000002761411127003600026734 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Runtime.InteropServices; using System.Threading; using System.IO; using MySql.Data.MySqlClient; using System.Diagnostics; namespace MySql.Data.Common { #if !PocketPC /// /// Helper class to encapsulate shared memory functionality /// Also cares of proper cleanup of file mapping object and cew /// internal class SharedMemory : IDisposable { private const uint FILE_MAP_WRITE = 0x0002; IntPtr fileMapping; IntPtr view; public SharedMemory(string name, IntPtr size) { fileMapping = NativeMethods.OpenFileMapping(FILE_MAP_WRITE, false, name); if (fileMapping == IntPtr.Zero) { throw new MySqlException("Cannot open file mapping " + name); } view = NativeMethods.MapViewOfFile(fileMapping, FILE_MAP_WRITE, 0, 0, size); } public IntPtr View { get { return view; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (view != IntPtr.Zero) { NativeMethods.UnmapViewOfFile(view); view = IntPtr.Zero; } if (fileMapping != IntPtr.Zero) { // Free the handle NativeMethods.CloseHandle(fileMapping); fileMapping = IntPtr.Zero; } } } } /// /// Summary description for SharedMemoryStream. /// internal class SharedMemoryStream : Stream { private string memoryName; private EventWaitHandle serverRead; private EventWaitHandle serverWrote; private EventWaitHandle clientRead; private EventWaitHandle clientWrote; private EventWaitHandle connectionClosed; private SharedMemory data; private int bytesLeft; private int position; private int connectNumber; private const int BUFFERLENGTH = 16004; private int readTimeout = System.Threading.Timeout.Infinite; private int writeTimeout = System.Threading.Timeout.Infinite; public SharedMemoryStream(string memName) { memoryName = memName; } public void Open(uint timeOut) { if (connectionClosed != null) { Debug.Assert(false, "Connection is already open"); } GetConnectNumber(timeOut); SetupEvents(); } public override void Close() { if (connectionClosed != null) { bool isClosed = connectionClosed.WaitOne(0); if (!isClosed) { connectionClosed.Set(); connectionClosed.Close(); } connectionClosed = null; EventWaitHandle[] handles = {serverRead, serverWrote, clientRead, clientWrote}; for(int i=0; i< handles.Length; i++) { if(handles[i] != null) handles[i].Close(); } if (data != null) { data.Dispose(); data = null; } } } private void GetConnectNumber(uint timeOut) { EventWaitHandle connectRequest; try { connectRequest = EventWaitHandle.OpenExisting(memoryName + "_CONNECT_REQUEST"); } catch (Exception) { // If server runs as service, its shared memory is global // And if connector runs in user session, it needs to prefix // shared memory name with "Global\" string prefixedMemoryName = @"Global\" + memoryName; connectRequest = EventWaitHandle.OpenExisting(prefixedMemoryName + "_CONNECT_REQUEST"); memoryName = prefixedMemoryName; } EventWaitHandle connectAnswer = EventWaitHandle.OpenExisting(memoryName + "_CONNECT_ANSWER"); using (SharedMemory connectData = new SharedMemory(memoryName + "_CONNECT_DATA", (IntPtr)4)) { // now start the connection if (!connectRequest.Set()) throw new MySqlException("Failed to open shared memory connection"); if (!connectAnswer.WaitOne((int)(timeOut * 1000), false)) throw new MySqlException("Timeout during connection"); connectNumber = Marshal.ReadInt32(connectData.View); } } private void SetupEvents() { string prefix = memoryName + "_" + connectNumber; data = new SharedMemory(prefix + "_DATA", (IntPtr)BUFFERLENGTH); serverWrote = EventWaitHandle.OpenExisting(prefix + "_SERVER_WROTE"); serverRead = EventWaitHandle.OpenExisting(prefix + "_SERVER_READ"); clientWrote = EventWaitHandle.OpenExisting(prefix + "_CLIENT_WROTE"); clientRead = EventWaitHandle.OpenExisting(prefix + "_CLIENT_READ"); connectionClosed = EventWaitHandle.OpenExisting(prefix + "_CONNECTION_CLOSED"); // tell the server we are ready serverRead.Set(); } #region Properties public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotSupportedException("SharedMemoryStream does not support seeking - length"); } } public override long Position { get { throw new NotSupportedException("SharedMemoryStream does not support seeking - position"); } set { } } #endregion public override void Flush() { // No need to flush anything to disk ,as our shared memory is backed // by the page file } public override int Read(byte[] buffer, int offset, int count) { int timeLeft = readTimeout; WaitHandle[] waitHandles = { serverWrote, connectionClosed }; LowResolutionStopwatch stopwatch = new LowResolutionStopwatch(); while (bytesLeft == 0) { stopwatch.Start(); int index = WaitHandle.WaitAny(waitHandles, timeLeft); stopwatch.Stop(); if (index == WaitHandle.WaitTimeout) throw new TimeoutException("Timeout when reading from shared memory"); if (waitHandles[index] == connectionClosed) throw new MySqlException("Connection to server lost",true, null); if (readTimeout != System.Threading.Timeout.Infinite) { timeLeft = readTimeout - (int)stopwatch.ElapsedMilliseconds; if (timeLeft < 0) throw new TimeoutException("Timeout when reading from shared memory"); } bytesLeft = Marshal.ReadInt32(data.View); position = 4; } int len = Math.Min(count, bytesLeft); long baseMem = data.View.ToInt64() + position; for (int i = 0; i < len; i++, position++) buffer[offset + i] = Marshal.ReadByte((IntPtr)(baseMem + i)); bytesLeft -= len; if (bytesLeft == 0) clientRead.Set(); return len; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("SharedMemoryStream does not support seeking"); } public override void Write(byte[] buffer, int offset, int count) { int leftToDo = count; int buffPos = offset; WaitHandle[] waitHandles = { serverRead, connectionClosed }; LowResolutionStopwatch stopwatch = new LowResolutionStopwatch(); int timeLeft = writeTimeout; while (leftToDo > 0) { stopwatch.Start(); int index = WaitHandle.WaitAny(waitHandles, timeLeft); stopwatch.Stop(); if (waitHandles[index] == connectionClosed) throw new MySqlException("Connection to server lost",true, null); if (index == WaitHandle.WaitTimeout) throw new TimeoutException("Timeout when reading from shared memory"); if (writeTimeout != System.Threading.Timeout.Infinite) { timeLeft = writeTimeout - (int)stopwatch.ElapsedMilliseconds; if (timeLeft < 0) throw new TimeoutException("Timeout when writing to shared memory"); } int bytesToDo = Math.Min(leftToDo, BUFFERLENGTH); long baseMem = data.View.ToInt64() + 4; Marshal.WriteInt32(data.View, bytesToDo); Marshal.Copy(buffer, buffPos, (IntPtr)baseMem, bytesToDo); buffPos += bytesToDo; leftToDo -= bytesToDo; if (!clientWrote.Set()) throw new MySqlException("Writing to shared memory failed"); } } public override void SetLength(long value) { throw new NotSupportedException("SharedMemoryStream does not support seeking"); } public override bool CanTimeout { get { return true; } } public override int ReadTimeout { get { return readTimeout; } set { readTimeout = value; } } public override int WriteTimeout { get { return writeTimeout; } set { writeTimeout = value; } } } #endif } mysql-connector-net-6.4.3/Source/MySql.Data/Types/0000755000175000017500000000000011127003600022434 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlUByte.cs0000644000175000017500000000740111127003600025003 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; namespace MySql.Data.Types { internal struct MySqlUByte : IMySqlValue { private byte mValue; private bool isNull; public MySqlUByte(bool isNull) { this.isNull = isNull; mValue = 0; } public MySqlUByte(byte val) { this.isNull = false; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.UByte; } } DbType IMySqlValue.DbType { get { return DbType.Byte; } } object IMySqlValue.Value { get { return mValue; } } public byte Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(byte); } } string IMySqlValue.MySqlTypeName { get { return "TINYINT"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { byte v = (val is byte) ? (byte)val : Convert.ToByte(val); if (binary) packet.WriteByte(v); else packet.WriteStringNoNull(v.ToString()); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlUByte(true); if (length == -1) return new MySqlUByte((byte)packet.ReadByte()); else return new MySqlUByte(Byte.Parse(packet.ReadString(length))); } void IMySqlValue.SkipValue(MySqlPacket packet) { packet.ReadByte(); } #endregion internal static void SetDSInfo(DataTable dsTable) { // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. DataRow row = dsTable.NewRow(); row["TypeName"] = "TINY INT"; row["ProviderDbType"] = MySqlDbType.UByte; row["ColumnSize"] = 0; row["CreateFormat"] = "TINYINT UNSIGNED"; row["CreateParameters"] = null; row["DataType"] = "System.Byte"; row["IsAutoincrementable"] = true; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = true; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlInt64.cs0000644000175000017500000000751411127003600024664 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; namespace MySql.Data.Types { internal struct MySqlInt64 : IMySqlValue { private long mValue; private bool isNull; public MySqlInt64(bool isNull) { this.isNull = isNull; mValue = 0; } public MySqlInt64(long val) { this.isNull = false; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.Int64; } } DbType IMySqlValue.DbType { get { return DbType.Int64; } } object IMySqlValue.Value { get { return mValue; } } public long Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(long); } } string IMySqlValue.MySqlTypeName { get { return "BIGINT"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { long v = (val is Int64) ? (Int64)val : Convert.ToInt64(val); if (binary) packet.WriteInteger(v, 8); else packet.WriteStringNoNull(v.ToString()); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlInt64(true); if (length == -1) return new MySqlInt64((long)packet.ReadULong(8)); else return new MySqlInt64(Int64.Parse(packet.ReadString(length))); } void IMySqlValue.SkipValue(MySqlPacket packet) { packet.Position += 8; } #endregion internal static void SetDSInfo(DataTable dsTable) { // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. DataRow row = dsTable.NewRow(); row["TypeName"] = "BIGINT"; row["ProviderDbType"] = MySqlDbType.Int64; row["ColumnSize"] = 0; row["CreateFormat"] = "BIGINT"; row["CreateParameters"] = null; row["DataType"] = "System.Int64"; row["IsAutoincrementable"] = true; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = false; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlUInt64.cs0000644000175000017500000000750611127003600025012 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; namespace MySql.Data.Types { internal struct MySqlUInt64 : IMySqlValue { private ulong mValue; private bool isNull; public MySqlUInt64(bool isNull) { this.isNull = isNull; mValue = 0; } public MySqlUInt64(ulong val) { this.isNull = false; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.UInt64; } } DbType IMySqlValue.DbType { get { return DbType.UInt64; } } object IMySqlValue.Value { get { return mValue; } } public ulong Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(ulong); } } string IMySqlValue.MySqlTypeName { get { return "BIGINT"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { ulong v = (val is ulong) ? (ulong)val : Convert.ToUInt64(val); if (binary) packet.WriteInteger((long)v, 8); else packet.WriteStringNoNull(v.ToString()); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlUInt64(true); if (length == -1) return new MySqlUInt64(packet.ReadULong(8)); else return new MySqlUInt64(UInt64.Parse(packet.ReadString(length))); } void IMySqlValue.SkipValue(MySqlPacket packet) { packet.Position += 8; } #endregion internal static void SetDSInfo(DataTable dsTable) { // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. DataRow row = dsTable.NewRow(); row["TypeName"] = "BIGINT"; row["ProviderDbType"] = MySqlDbType.UInt64; row["ColumnSize"] = 0; row["CreateFormat"] = "BIGINT UNSIGNED"; row["CreateParameters"] = null; row["DataType"] = "System.UInt64"; row["IsAutoincrementable"] = true; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = true; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlValue.cs0000644000175000017500000000322411127003600025026 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Globalization; using MySql.Data.MySqlClient; namespace MySql.Data.Types { internal interface IMySqlValue { bool IsNull { get; } MySqlDbType MySqlDbType { get; } DbType DbType { get; } object Value { get; /*set;*/ } Type SystemType { get; } string MySqlTypeName { get; } void WriteValue(MySqlPacket packet, bool binary, object value, int length); IMySqlValue ReadValue(MySqlPacket packet, long length, bool isNull); void SkipValue(MySqlPacket packet); } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlByte.cs0000644000175000017500000001126111127003600024655 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using System.Globalization; namespace MySql.Data.Types { internal struct MySqlByte : IMySqlValue { private sbyte mValue; private bool isNull; private bool treatAsBool; public MySqlByte(bool isNull) { this.isNull = isNull; mValue = 0; treatAsBool = false; } public MySqlByte(sbyte val) { this.isNull = false; mValue = val; treatAsBool = false; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.Byte; } } DbType IMySqlValue.DbType { get { if (TreatAsBoolean) return DbType.Boolean; return DbType.SByte; } } object IMySqlValue.Value { get { if (TreatAsBoolean) return Convert.ToBoolean(mValue); return mValue; } } public sbyte Value { get { return mValue; } set { mValue = value; } } Type IMySqlValue.SystemType { get { if (TreatAsBoolean) return typeof(Boolean); return typeof(sbyte); } } string IMySqlValue.MySqlTypeName { get { return "TINYINT"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { sbyte v = (val is sbyte) ? (sbyte)val : Convert.ToSByte(val); if (binary) packet.WriteByte((byte)v); else packet.WriteStringNoNull(v.ToString()); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlByte(true); if (length == -1) return new MySqlByte((sbyte)packet.ReadByte()); else { string s = packet.ReadString(length); MySqlByte b = new MySqlByte(SByte.Parse(s, NumberStyles.Any, CultureInfo.InvariantCulture)); b.TreatAsBoolean = TreatAsBoolean; return b; } } void IMySqlValue.SkipValue(MySqlPacket packet) { packet.ReadByte(); } #endregion internal bool TreatAsBoolean { get { return treatAsBool; } set { treatAsBool = value; } } internal static void SetDSInfo(DataTable dsTable) { // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. DataRow row = dsTable.NewRow(); row["TypeName"] = "TINYINT"; row["ProviderDbType"] = MySqlDbType.Byte; row["ColumnSize"] = 0; row["CreateFormat"] = "TINYINT"; row["CreateParameters"] = null; row["DataType"] = "System.SByte"; row["IsAutoincrementable"] = true; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = false; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlDateTime.cs0000644000175000017500000003724211127003600025455 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using MySql.Data.MySqlClient; using System.Globalization; namespace MySql.Data.Types { /// /// /// public struct MySqlDateTime : IMySqlValue, IConvertible, IComparable { private bool isNull; private MySqlDbType type; private int year, month, day, hour, minute, second; private int millisecond; /// /// Constructs a new MySqlDateTime object by setting the individual time properties to /// the given values. /// /// The year to use. /// The month to use. /// The day to use. /// The hour to use. /// The minute to use. /// The second to use. public MySqlDateTime(int year, int month, int day, int hour, int minute, int second) : this(MySqlDbType.DateTime, year, month, day, hour, minute, second) { } /// /// Constructs a new MySqlDateTime object by using values from the given object. /// /// The object to copy. public MySqlDateTime(DateTime dt) : this(MySqlDbType.DateTime, dt) { } /// /// Constructs a new MySqlDateTime object by copying the current value of the given object. /// /// The MySqlDateTime object to copy. public MySqlDateTime(MySqlDateTime mdt) { year = mdt.Year; month = mdt.Month; day = mdt.Day; hour = mdt.Hour; minute = mdt.Minute; second = mdt.Second; millisecond = 0; type = MySqlDbType.DateTime; isNull = false; } /// /// Enables the contruction of a MySqlDateTime object by parsing a string. /// public MySqlDateTime(string dateTime) : this(MySqlDateTime.Parse(dateTime)) { } internal MySqlDateTime(MySqlDbType type, int year, int month, int day, int hour, int minute, int second) { this.isNull = false; this.type = type; this.year = year; this.month = month; this.day = day; this.hour = hour; this.minute = minute; this.second = second; this.millisecond = 0; } internal MySqlDateTime(MySqlDbType type, bool isNull) : this(type, 0, 0, 0, 0, 0, 0) { this.isNull = isNull; } internal MySqlDateTime(MySqlDbType type, DateTime val) : this(type, 0, 0, 0, 0, 0, 0) { this.isNull = false; year = val.Year; month = val.Month; day = val.Day; hour = val.Hour; minute = val.Minute; second = val.Second; millisecond = val.Millisecond; } #region Properties /// /// Indicates if this object contains a value that can be represented as a DateTime /// public bool IsValidDateTime { get { return year != 0 && month != 0 && day != 0; } } /// Returns the year portion of this datetime public int Year { get { return year; } set { year = value; } } /// Returns the month portion of this datetime public int Month { get { return month; } set { month = value; } } /// Returns the day portion of this datetime public int Day { get { return day; } set { day = value; } } /// Returns the hour portion of this datetime public int Hour { get { return hour; } set { hour = value; } } /// Returns the minute portion of this datetime public int Minute { get { return minute; } set { minute = value; } } /// Returns the second portion of this datetime public int Second { get { return second; } set { second = value; } } /// /// Retrieves the millisecond value of this object. /// public int Millisecond { get { return millisecond; } set { millisecond = value; } } #endregion #region IMySqlValue Members /// /// Returns true if this datetime object has a null value /// public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return type; } } DbType IMySqlValue.DbType { get { if (type == MySqlDbType.Date || type == MySqlDbType.Newdate) return DbType.Date; return DbType.DateTime; } } object IMySqlValue.Value { get { return GetDateTime(); } } /// /// Retrieves the value of this as a DateTime object. /// public DateTime Value { get { return GetDateTime(); } } Type IMySqlValue.SystemType { get { return typeof(DateTime); } } string IMySqlValue.MySqlTypeName { get { switch (type) { case MySqlDbType.Date: return "DATE"; case MySqlDbType.Newdate: return "NEWDATE"; case MySqlDbType.Timestamp: return "TIMESTAMP"; } return "DATETIME"; } } private void SerializeText(MySqlPacket packet, MySqlDateTime value) { string val = String.Empty; val = String.Format("{0:0000}-{1:00}-{2:00}", value.Year, value.Month, value.Day); if (type != MySqlDbType.Date) val = String.Format("{0} {1:00}:{2:00}:{3:00}", val, value.Hour, value.Minute, value.Second); packet.WriteStringNoNull("'" + val + "'"); } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object value, int length) { MySqlDateTime dtValue; string valueAsString = value as string; if (value is DateTime) dtValue = new MySqlDateTime(type, (DateTime)value); else if (valueAsString != null) dtValue = new MySqlDateTime(type, DateTime.Parse(valueAsString, CultureInfo.CurrentCulture)); else if (value is MySqlDateTime) dtValue = (MySqlDateTime)value; else throw new MySqlException("Unable to serialize date/time value."); if (!binary) { SerializeText(packet, dtValue); return; } if (type == MySqlDbType.Timestamp) packet.WriteByte(11); else packet.WriteByte(7); packet.WriteInteger(dtValue.Year, 2); packet.WriteByte((byte)dtValue.Month); packet.WriteByte((byte)dtValue.Day); if (type == MySqlDbType.Date) { packet.WriteByte(0); packet.WriteByte(0); packet.WriteByte(0); } else { packet.WriteByte((byte)dtValue.Hour); packet.WriteByte((byte)dtValue.Minute); packet.WriteByte((byte)dtValue.Second); } if (type == MySqlDbType.Timestamp) packet.WriteInteger(dtValue.Millisecond, 4); } static internal MySqlDateTime Parse(string s) { MySqlDateTime dt = new MySqlDateTime(); return dt.ParseMySql(s); } static internal MySqlDateTime Parse(string s, Common.DBVersion version) { MySqlDateTime dt = new MySqlDateTime(); return dt.ParseMySql(s); } private MySqlDateTime ParseMySql(string s) { string[] parts = s.Split('-', ' ', ':', '/'); int year = int.Parse(parts[0]); int month = int.Parse(parts[1]); int day = int.Parse(parts[2]); int hour = 0, minute = 0, second = 0; if (parts.Length > 3) { hour = int.Parse(parts[3]); minute = int.Parse(parts[4]); second = int.Parse(parts[5]); } return new MySqlDateTime(type, year, month, day, hour, minute, second); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlDateTime(type, true); if (length >= 0) { string value = packet.ReadString(length); return ParseMySql(value); } long bufLength = packet.ReadByte(); int year = 0, month = 0, day = 0; int hour = 0, minute = 0, second = 0; if (bufLength >= 4) { year = packet.ReadInteger(2); month = packet.ReadByte(); day = packet.ReadByte(); } if (bufLength > 4) { hour = packet.ReadByte(); minute = packet.ReadByte(); second = packet.ReadByte(); } if (bufLength > 7) packet.ReadInteger(4); return new MySqlDateTime(type, year, month, day, hour, minute, second); } void IMySqlValue.SkipValue(MySqlPacket packet) { int len = packet.ReadByte(); packet.Position += len; } #endregion /// Returns this value as a DateTime public DateTime GetDateTime() { if (!IsValidDateTime) throw new MySqlConversionException("Unable to convert MySQL date/time value to System.DateTime"); return new DateTime(year, month, day, hour, minute, second); } private static string FormatDateCustom(string format, int monthVal, int dayVal, int yearVal) { format = format.Replace("MM", "{0:00}"); format = format.Replace("M", "{0}"); format = format.Replace("dd", "{1:00}"); format = format.Replace("d", "{1}"); format = format.Replace("yyyy", "{2:0000}"); format = format.Replace("yy", "{3:00}"); format = format.Replace("y", "{4:0}"); int year2digit = yearVal - ((yearVal / 1000) * 1000); year2digit -= ((year2digit / 100) * 100); int year1digit = year2digit - ((year2digit / 10) * 10); return String.Format(format, monthVal, dayVal, yearVal, year2digit, year1digit); } /// Returns a MySQL specific string representation of this value public override string ToString() { if (this.IsValidDateTime) { DateTime d = new DateTime(year, month, day, hour, minute, second); return (type == MySqlDbType.Date) ? d.ToString("d") : d.ToString(); } string dateString = FormatDateCustom( CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern, month, day, year); if (type == MySqlDbType.Date) return dateString; DateTime dt = new DateTime(1, 2, 3, hour, minute, second); dateString = String.Format("{0} {1}", dateString, dt.ToLongTimeString()); return dateString; } /// /// /// public static explicit operator DateTime(MySqlDateTime val) { if (!val.IsValidDateTime) return DateTime.MinValue; return val.GetDateTime(); } internal static void SetDSInfo(DataTable dsTable) { string[] types = new string[] { "DATE", "DATETIME", "TIMESTAMP" }; MySqlDbType[] dbtype = new MySqlDbType[] { MySqlDbType.Date, MySqlDbType.DateTime, MySqlDbType.Timestamp }; // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. for (int x = 0; x < types.Length; x++) { DataRow row = dsTable.NewRow(); row["TypeName"] = types[x]; row["ProviderDbType"] = dbtype[x]; row["ColumnSize"] = 0; row["CreateFormat"] = types[x]; row["CreateParameters"] = null; row["DataType"] = "System.DateTime"; row["IsAutoincrementable"] = false; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = false; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } #region IConvertible Members ulong IConvertible.ToUInt64(IFormatProvider provider) { return 0; } sbyte IConvertible.ToSByte(IFormatProvider provider) { // TODO: Add MySqlDateTime.ToSByte implementation return 0; } double IConvertible.ToDouble(IFormatProvider provider) { return 0; } DateTime IConvertible.ToDateTime(IFormatProvider provider) { return this.GetDateTime(); } float IConvertible.ToSingle(IFormatProvider provider) { return 0; } bool IConvertible.ToBoolean(IFormatProvider provider) { return false; } int IConvertible.ToInt32(IFormatProvider provider) { return 0; } ushort IConvertible.ToUInt16(IFormatProvider provider) { return 0; } short IConvertible.ToInt16(IFormatProvider provider) { return 0; } string System.IConvertible.ToString(IFormatProvider provider) { return null; } byte IConvertible.ToByte(IFormatProvider provider) { return 0; } char IConvertible.ToChar(IFormatProvider provider) { return '\0'; } long IConvertible.ToInt64(IFormatProvider provider) { return 0; } System.TypeCode IConvertible.GetTypeCode() { return new System.TypeCode(); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return 0; } object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return null; } uint IConvertible.ToUInt32(IFormatProvider provider) { return 0; } #endregion #region IComparable Members int IComparable.CompareTo(object obj) { MySqlDateTime otherDate = (MySqlDateTime)obj; if (Year < otherDate.Year) return -1; else if (Year > otherDate.Year) return 1; if (Month < otherDate.Month) return -1; else if (Month > otherDate.Month) return 1; if (Day < otherDate.Day) return -1; else if (Day > otherDate.Day) return 1; if (Hour < otherDate.Hour) return -1; else if (Hour > otherDate.Hour) return 1; if (Minute < otherDate.Minute) return -1; else if (Minute > otherDate.Minute) return 1; if (Second < otherDate.Second) return -1; else if (Second > otherDate.Second) return 1; if (Millisecond < otherDate.Millisecond) return -1; else if (Millisecond > otherDate.Millisecond) return 1; return 0; } #endregion } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlUInt16.cs0000644000175000017500000000754011127003600025005 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; namespace MySql.Data.Types { internal struct MySqlUInt16 : IMySqlValue { private ushort mValue; private bool isNull; public MySqlUInt16(bool isNull) { this.isNull = isNull; mValue = 0; } public MySqlUInt16(ushort val) { this.isNull = false; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.UInt16; } } DbType IMySqlValue.DbType { get { return DbType.UInt16; } } object IMySqlValue.Value { get { return mValue; } } public ushort Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(ushort); } } string IMySqlValue.MySqlTypeName { get { return "SMALLINT"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { int v = (val is UInt16) ? (UInt16)val : Convert.ToUInt16(val); if (binary) packet.WriteInteger((long)v, 2); else packet.WriteStringNoNull(v.ToString()); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlUInt16(true); if (length == -1) return new MySqlUInt16((ushort)packet.ReadInteger(2)); else return new MySqlUInt16(UInt16.Parse(packet.ReadString(length))); } void IMySqlValue.SkipValue(MySqlPacket packet) { packet.Position += 2; } #endregion internal static void SetDSInfo(DataTable dsTable) { // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. DataRow row = dsTable.NewRow(); row["TypeName"] = "SMALLINT"; row["ProviderDbType"] = MySqlDbType.UInt16; row["ColumnSize"] = 0; row["CreateFormat"] = "SMALLINT UNSIGNED"; row["CreateParameters"] = null; row["DataType"] = "System.UInt16"; row["IsAutoincrementable"] = true; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = true; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlDouble.cs0000644000175000017500000001075411127003600025172 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Globalization; using MySql.Data.MySqlClient; namespace MySql.Data.Types { internal struct MySqlDouble : IMySqlValue { private double mValue; private bool isNull; public MySqlDouble(bool isNull) { this.isNull = isNull; mValue = 0.0; } public MySqlDouble(double val) { this.isNull = false; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.Double; } } DbType IMySqlValue.DbType { get { return DbType.Double; } } object IMySqlValue.Value { get { return mValue; } } public double Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(double); } } string IMySqlValue.MySqlTypeName { get { return "DOUBLE"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { double v = (val is double) ? (double)val : Convert.ToDouble(val); if (binary) packet.Write(BitConverter.GetBytes(v)); else packet.WriteStringNoNull(v.ToString("R", CultureInfo.InvariantCulture)); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlDouble(true); if (length == -1) { byte[] b = new byte[8]; packet.Read(b, 0, 8); return new MySqlDouble(BitConverter.ToDouble(b, 0)); } string s = packet.ReadString(length); double d; try { d = Double.Parse(s, CultureInfo.InvariantCulture); } catch (OverflowException) { // MySQL server < 5.5 can return values not compatible with // Double.Parse(), i.e out of range for double. if (s.StartsWith("-")) d = double.MinValue; else d = double.MaxValue; } return new MySqlDouble(d); } void IMySqlValue.SkipValue(MySqlPacket packet) { packet.Position += 8; } #endregion internal static void SetDSInfo(DataTable dsTable) { // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. DataRow row = dsTable.NewRow(); row["TypeName"] = "DOUBLE"; row["ProviderDbType"] = MySqlDbType.Double; row["ColumnSize"] = 0; row["CreateFormat"] = "DOUBLE"; row["CreateParameters"] = null; row["DataType"] = "System.Double"; row["IsAutoincrementable"] = false; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = false; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } }mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlConversionException.cs0000644000175000017500000000271011127003600027755 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; namespace MySql.Data.Types { /// /// Summary description for MySqlConversionException. /// #if !CF [Serializable] #endif public class MySqlConversionException : Exception { /// Ctor public MySqlConversionException(string msg) : base(msg) { } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlString.cs0000644000175000017500000001154411127003600025224 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.IO; using MySql.Data.MySqlClient; namespace MySql.Data.Types { internal struct MySqlString : IMySqlValue { private string mValue; private bool isNull; private MySqlDbType type; public MySqlString(MySqlDbType type, bool isNull) { this.type = type; this.isNull = isNull; mValue = String.Empty; } public MySqlString(MySqlDbType type, string val) { this.type = type; this.isNull = false; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return type; } } DbType IMySqlValue.DbType { get { return DbType.String; } } object IMySqlValue.Value { get { return mValue; } } public string Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(string); } } string IMySqlValue.MySqlTypeName { get { return type == MySqlDbType.Set ? "SET" : type == MySqlDbType.Enum ? "ENUM" : "VARCHAR"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { string v = val.ToString(); if (length > 0) { length = Math.Min(length, v.Length); v = v.Substring(0, length); } if (binary) packet.WriteLenString(v); else packet.WriteStringNoNull("'" + MySqlHelper.EscapeString(v) + "'"); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlString(type, true); string s = String.Empty; if (length == -1) s = packet.ReadLenString(); else s = packet.ReadString(length); MySqlString str = new MySqlString(type, s); return str; } void IMySqlValue.SkipValue(MySqlPacket packet) { int len = (int)packet.ReadFieldLength(); packet.Position += len; } #endregion internal static void SetDSInfo(DataTable dsTable) { string[] types = new string[] { "CHAR", "NCHAR", "VARCHAR", "NVARCHAR", "SET", "ENUM", "TINYTEXT", "TEXT", "MEDIUMTEXT", "LONGTEXT" }; MySqlDbType[] dbtype = new MySqlDbType[] { MySqlDbType.String, MySqlDbType.String, MySqlDbType.VarChar, MySqlDbType.VarChar, MySqlDbType.Set, MySqlDbType.Enum, MySqlDbType.TinyText, MySqlDbType.Text, MySqlDbType.MediumText, MySqlDbType.LongText }; // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. for (int x = 0; x < types.Length; x++) { DataRow row = dsTable.NewRow(); row["TypeName"] = types[x]; row["ProviderDbType"] = dbtype[x]; row["ColumnSize"] = 0; row["CreateFormat"] = x < 4 ? types[x] + "({0})" : types[x]; row["CreateParameters"] = x < 4 ? "size" : null; row["DataType"] = "System.String"; row["IsAutoincrementable"] = false; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = false; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = true; row["IsUnsigned"] = false; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } } }mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlInt32.cs0000644000175000017500000001106111127003600024647 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using System.Globalization; namespace MySql.Data.Types { internal struct MySqlInt32 : IMySqlValue { private int mValue; private bool isNull; private bool is24Bit; private MySqlInt32(MySqlDbType type) { is24Bit = type == MySqlDbType.Int24 ? true : false; isNull = true; mValue = 0; } public MySqlInt32(MySqlDbType type, bool isNull) : this(type) { this.isNull = isNull; } public MySqlInt32(MySqlDbType type, int val) : this(type) { this.isNull = false; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.Int32; } } DbType IMySqlValue.DbType { get { return DbType.Int32; } } object IMySqlValue.Value { get { return mValue; } } public int Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(Int32); } } string IMySqlValue.MySqlTypeName { get { return is24Bit ? "MEDIUMINT" : "INT"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { int v = (val is Int32) ? (int)val : Convert.ToInt32(val); if (binary) packet.WriteInteger((long)v, is24Bit ? 3 : 4); else packet.WriteStringNoNull(v.ToString()); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlInt32((this as IMySqlValue).MySqlDbType, true); if (length == -1) return new MySqlInt32((this as IMySqlValue).MySqlDbType, packet.ReadInteger(4)); else return new MySqlInt32((this as IMySqlValue).MySqlDbType, Int32.Parse(packet.ReadString(length), CultureInfo.InvariantCulture)); } void IMySqlValue.SkipValue(MySqlPacket packet) { packet.Position += 4; } #endregion internal static void SetDSInfo(DataTable dsTable) { string[] types = new string[] { "INT", "YEAR", "MEDIUMINT" }; MySqlDbType[] dbtype = new MySqlDbType[] { MySqlDbType.Int32, MySqlDbType.Year, MySqlDbType.Int24 }; // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. for (int x = 0; x < types.Length; x++) { DataRow row = dsTable.NewRow(); row["TypeName"] = types[x]; row["ProviderDbType"] = dbtype[x]; row["ColumnSize"] = 0; row["CreateFormat"] = types[x]; row["CreateParameters"] = null; row["DataType"] = "System.Int32"; row["IsAutoincrementable"] = dbtype[x] == MySqlDbType.Year ? false : true; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = false; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MetaData.cs0000644000175000017500000001251511127003600024447 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using MySql.Data.MySqlClient; using System.Globalization; namespace MySql.Data.Types { internal class MetaData { public static bool IsNumericType(string typename) { string lowerType = typename.ToLower(CultureInfo.InvariantCulture); switch (lowerType) { case "int": case "integer": case "numeric": case "decimal": case "dec": case "fixed": case "tinyint": case "mediumint": case "bigint": case "real": case "double": case "float": case "serial": case "smallint": return true; } return false; } public static bool IsTextType(string typename) { string lowerType = typename.ToLower(CultureInfo.InvariantCulture); switch (lowerType) { case "varchar": case "char": case "text": case "longtext": case "tinytext": case "mediumtext": case "nchar": case "nvarchar": case "enum": case "set": return true; } return false; } public static bool SupportScale(string typename) { string lowerType = typename.ToLower(CultureInfo.InvariantCulture); switch (lowerType) { case "numeric": case "decimal": case "dec": case "real": return true; } return false; } public static MySqlDbType NameToType(string typeName, bool unsigned, bool realAsFloat, MySqlConnection connection) { switch (typeName.ToUpper(CultureInfo.InvariantCulture)) { case "CHAR": return MySqlDbType.String; case "VARCHAR": return MySqlDbType.VarChar; case "DATE": return MySqlDbType.Date; case "DATETIME": return MySqlDbType.DateTime; case "NUMERIC": case "DECIMAL": case "DEC": case "FIXED": if (connection.driver.Version.isAtLeast(5, 0, 3)) return MySqlDbType.NewDecimal; else return MySqlDbType.Decimal; case "YEAR": return MySqlDbType.Year; case "TIME": return MySqlDbType.Time; case "TIMESTAMP": return MySqlDbType.Timestamp; case "SET": return MySqlDbType.Set; case "ENUM": return MySqlDbType.Enum; case "BIT": return MySqlDbType.Bit; case "TINYINT": return unsigned ? MySqlDbType.UByte : MySqlDbType.Byte; case "BOOL": case "BOOLEAN": return MySqlDbType.Byte; case "SMALLINT": return unsigned ? MySqlDbType.UInt16 : MySqlDbType.Int16; case "MEDIUMINT": return unsigned ? MySqlDbType.UInt24 : MySqlDbType.Int24; case "INT": case "INTEGER": return unsigned ? MySqlDbType.UInt32 : MySqlDbType.Int32; case "SERIAL": return MySqlDbType.UInt64; case "BIGINT": return unsigned ? MySqlDbType.UInt64 : MySqlDbType.Int64; case "FLOAT": return MySqlDbType.Float; case "DOUBLE": return MySqlDbType.Double; case "REAL": return realAsFloat ? MySqlDbType.Float : MySqlDbType.Double; case "TEXT": return MySqlDbType.Text; case "BLOB": return MySqlDbType.Blob; case "LONGBLOB": return MySqlDbType.LongBlob; case "LONGTEXT": return MySqlDbType.LongText; case "MEDIUMBLOB": return MySqlDbType.MediumBlob; case "MEDIUMTEXT": return MySqlDbType.MediumText; case "TINYBLOB": return MySqlDbType.TinyBlob; case "TINYTEXT": return MySqlDbType.TinyText; case "BINARY": return MySqlDbType.Binary; case "VARBINARY": return MySqlDbType.VarBinary; } throw new MySqlException("Unhandled type encountered"); } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlUInt32.cs0000644000175000017500000001102211127003600024771 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using System.Globalization; namespace MySql.Data.Types { internal struct MySqlUInt32 : IMySqlValue { private uint mValue; private bool isNull; private bool is24Bit; private MySqlUInt32(MySqlDbType type) { is24Bit = type == MySqlDbType.Int24 ? true : false; isNull = true; mValue = 0; } public MySqlUInt32(MySqlDbType type, bool isNull) : this(type) { this.isNull = isNull; } public MySqlUInt32(MySqlDbType type, uint val) : this(type) { this.isNull = false; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.UInt32; } } DbType IMySqlValue.DbType { get { return DbType.UInt32; } } object IMySqlValue.Value { get { return mValue; } } public uint Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(UInt32); } } string IMySqlValue.MySqlTypeName { get { return is24Bit ? "MEDIUMINT" : "INT"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object v, int length) { uint val = (v is uint) ? (uint)v : Convert.ToUInt32(v); if (binary) packet.WriteInteger((long)val, is24Bit ? 3 : 4); else packet.WriteStringNoNull(val.ToString()); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlUInt32((this as IMySqlValue).MySqlDbType, true); if (length == -1) return new MySqlUInt32((this as IMySqlValue).MySqlDbType, (uint)packet.ReadInteger(4)); else return new MySqlUInt32((this as IMySqlValue).MySqlDbType, UInt32.Parse(packet.ReadString(length), NumberStyles.Any, CultureInfo.InvariantCulture)); } void IMySqlValue.SkipValue(MySqlPacket packet) { packet.Position += 4; } #endregion internal static void SetDSInfo(DataTable dsTable) { string[] types = new string[] { "MEDIUMINT", "INT" }; MySqlDbType[] dbtype = new MySqlDbType[] { MySqlDbType.UInt24, MySqlDbType.UInt32 }; // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. for (int x = 0; x < types.Length; x++) { DataRow row = dsTable.NewRow(); row["TypeName"] = types[x]; row["ProviderDbType"] = dbtype[x]; row["ColumnSize"] = 0; row["CreateFormat"] = types[x] + " UNSIGNED"; row["CreateParameters"] = null; row["DataType"] = "System.UInt32"; row["IsAutoincrementable"] = true; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = true; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlBit.cs0000644000175000017500000001030611127003600024467 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; namespace MySql.Data.Types { /// /// Summary description for MySqlUInt64. /// internal struct MySqlBit : IMySqlValue { private ulong mValue; private bool isNull; private bool readAsString; public MySqlBit(bool isnull) { mValue = 0; isNull = isnull; readAsString = false; } public bool ReadAsString { get { return readAsString; } set { readAsString = value; } } public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.Bit; } } DbType IMySqlValue.DbType { get { return DbType.UInt64; } } object IMySqlValue.Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(UInt64); } } string IMySqlValue.MySqlTypeName { get { return "BIT"; } } public void WriteValue(MySqlPacket packet, bool binary, object value, int length) { ulong v = (value is UInt64) ? (UInt64)value : Convert.ToUInt64(value); if (binary) packet.WriteInteger((long)v, 8); else packet.WriteStringNoNull(v.ToString()); } public IMySqlValue ReadValue(MySqlPacket packet, long length, bool isNull) { this.isNull = isNull; if (isNull) return this; if (length == -1) length = packet.ReadFieldLength(); if (ReadAsString) mValue = UInt64.Parse(packet.ReadString(length)); else mValue = (UInt64)packet.ReadBitValue((int)length); return this; } public void SkipValue(MySqlPacket packet) { int len = (int)packet.ReadFieldLength(); packet.Position += len; } public static void SetDSInfo(DataTable dsTable) { // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. DataRow row = dsTable.NewRow(); row["TypeName"] = "BIT"; row["ProviderDbType"] = MySqlDbType.Bit; row["ColumnSize"] = 64; row["CreateFormat"] = "BIT"; row["CreateParameters"] = DBNull.Value; ; row["DataType"] = typeof(UInt64).ToString(); row["IsAutoincrementable"] = false; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = false; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = false; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = DBNull.Value; row["LiteralSuffix"] = DBNull.Value; row["NativeDataType"] = DBNull.Value; dsTable.Rows.Add(row); } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlSingle.cs0000644000175000017500000000776511127003600025211 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using System.Globalization; namespace MySql.Data.Types { internal struct MySqlSingle : IMySqlValue { private float mValue; private bool isNull; public MySqlSingle(bool isNull) { this.isNull = isNull; mValue = 0.0f; } public MySqlSingle(float val) { this.isNull = false; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.Float; } } DbType IMySqlValue.DbType { get { return DbType.Single; } } object IMySqlValue.Value { get { return mValue; } } public float Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(float); } } string IMySqlValue.MySqlTypeName { get { return "FLOAT"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { Single v = (val is Single) ? (Single)val : Convert.ToSingle(val); if (binary) packet.Write(BitConverter.GetBytes(v)); else packet.WriteStringNoNull(v.ToString("R", CultureInfo.InvariantCulture)); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlSingle(true); if (length == -1) { byte[] b = new byte[4]; packet.Read(b, 0, 4); return new MySqlSingle(BitConverter.ToSingle(b, 0)); } return new MySqlSingle(Single.Parse(packet.ReadString(length), CultureInfo.InvariantCulture)); } void IMySqlValue.SkipValue(MySqlPacket packet) { packet.Position += 4; } #endregion internal static void SetDSInfo(DataTable dsTable) { // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. DataRow row = dsTable.NewRow(); row["TypeName"] = "FLOAT"; row["ProviderDbType"] = MySqlDbType.Float; row["ColumnSize"] = 0; row["CreateFormat"] = "FLOAT"; row["CreateParameters"] = null; row["DataType"] = "System.Single"; row["IsAutoincrementable"] = false; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = false; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } }mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlInt16.cs0000644000175000017500000000751111127003600024656 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; namespace MySql.Data.Types { internal struct MySqlInt16 : IMySqlValue { private short mValue; private bool isNull; public MySqlInt16(bool isNull) { this.isNull = isNull; mValue = 0; } public MySqlInt16(short val) { this.isNull = false; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.Int16; } } DbType IMySqlValue.DbType { get { return DbType.Int16; } } object IMySqlValue.Value { get { return mValue; } } public short Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(short); } } string IMySqlValue.MySqlTypeName { get { return "SMALLINT"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { int v = (val is Int32) ? (int)val : Convert.ToInt32(val); if (binary) packet.WriteInteger((long)v, 2); else packet.WriteStringNoNull(v.ToString()); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlInt16(true); if (length == -1) return new MySqlInt16((short)packet.ReadInteger(2)); else return new MySqlInt16(Int16.Parse(packet.ReadString(length))); } void IMySqlValue.SkipValue(MySqlPacket packet) { packet.Position += 2; } #endregion internal static void SetDSInfo(DataTable dsTable) { // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. DataRow row = dsTable.NewRow(); row["TypeName"] = "SMALLINT"; row["ProviderDbType"] = MySqlDbType.Int16; row["ColumnSize"] = 0; row["CreateFormat"] = "SMALLINT"; row["CreateParameters"] = null; row["DataType"] = "System.Int16"; row["IsAutoincrementable"] = true; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = false; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlTime.cs0000644000175000017500000001351511127003600024654 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; namespace MySql.Data.Types { internal struct MySqlTimeSpan : IMySqlValue { private TimeSpan mValue; private bool isNull; public MySqlTimeSpan(bool isNull) { this.isNull = isNull; mValue = TimeSpan.MinValue; } public MySqlTimeSpan(TimeSpan val) { this.isNull = false; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.Time; } } DbType IMySqlValue.DbType { get { return DbType.Time; } } object IMySqlValue.Value { get { return mValue; } } public TimeSpan Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(TimeSpan); } } string IMySqlValue.MySqlTypeName { get { return "TIME"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { if (!(val is TimeSpan)) throw new MySqlException("Only TimeSpan objects can be serialized by MySqlTimeSpan"); TimeSpan ts = (TimeSpan)val; bool negative = ts.TotalMilliseconds < 0; ts = ts.Duration(); if (binary) { packet.WriteByte(8); packet.WriteByte((byte)(negative ? 1 : 0)); packet.WriteInteger(ts.Days, 4); packet.WriteByte((byte)ts.Hours); packet.WriteByte((byte)ts.Minutes); packet.WriteByte((byte)ts.Seconds); } else { String s = String.Format("'{0}{1} {2:00}:{3:00}:{4:00}.{5}'", negative ? "-" : "", ts.Days, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds); packet.WriteStringNoNull(s); } } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlTimeSpan(true); if (length >= 0) { string value = packet.ReadString(length); ParseMySql(value); return this; } long bufLength = packet.ReadByte(); int negate = 0; if (bufLength > 0) negate = packet.ReadByte(); isNull = false; if (bufLength == 0) isNull = true; else if (bufLength == 5) mValue = new TimeSpan(packet.ReadInteger(4), 0, 0, 0); else if (bufLength == 8) mValue = new TimeSpan(packet.ReadInteger(4), packet.ReadByte(), packet.ReadByte(), packet.ReadByte()); else mValue = new TimeSpan(packet.ReadInteger(4), packet.ReadByte(), packet.ReadByte(), packet.ReadByte(), packet.ReadInteger(4) / 1000000); if (negate == 1) mValue = mValue.Negate(); return this; } void IMySqlValue.SkipValue(MySqlPacket packet) { int len = packet.ReadByte(); packet.Position += len; } #endregion internal static void SetDSInfo(DataTable dsTable) { // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. DataRow row = dsTable.NewRow(); row["TypeName"] = "TIME"; row["ProviderDbType"] = MySqlDbType.Time; row["ColumnSize"] = 0; row["CreateFormat"] = "TIME"; row["CreateParameters"] = null; row["DataType"] = "System.TimeSpan"; row["IsAutoincrementable"] = false; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = false; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } public override string ToString() { return String.Format("{0} {1:00}:{2:00}:{3:00}.{4}", mValue.Days, mValue.Hours, mValue.Minutes, mValue.Seconds, mValue.Milliseconds); } private void ParseMySql(string s) { string[] parts = s.Split(':'); int hours = Int32.Parse(parts[0]); int mins = Int32.Parse(parts[1]); int secs = Int32.Parse(parts[2]); if (hours < 0 || parts[0].StartsWith("-")) { mins *= -1; secs *= -1; } int days = hours / 24; hours = hours - (days * 24); mValue = new TimeSpan(days, hours, mins, secs, 0); isNull = false; } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlDecimal.cs0000644000175000017500000001113511127003600025310 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using System.Globalization; namespace MySql.Data.Types { public struct MySqlDecimal : IMySqlValue { private byte precision; private byte scale; private string mValue; private bool isNull; internal MySqlDecimal(bool isNull) { this.isNull = isNull; mValue = null; precision = scale = 0; } internal MySqlDecimal(string val) { this.isNull = false; precision = scale = 0; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.Decimal; } } public byte Precision { get { return precision; } set { precision = value; } } public byte Scale { get { return scale; } set { scale = value; } } DbType IMySqlValue.DbType { get { return DbType.Decimal; } } object IMySqlValue.Value { get { return this.Value; } } public decimal Value { get { return Convert.ToDecimal(mValue, CultureInfo.InvariantCulture); } } public double ToDouble() { return Double.Parse(mValue); } public override string ToString() { return mValue; } Type IMySqlValue.SystemType { get { return typeof(decimal); } } string IMySqlValue.MySqlTypeName { get { return "DECIMAL"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { decimal v = (val is decimal) ? (decimal)val : Convert.ToDecimal(val); string valStr = v.ToString(CultureInfo.InvariantCulture); if (binary) packet.WriteLenString(valStr); else packet.WriteStringNoNull(valStr); } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { if (nullVal) return new MySqlDecimal(true); string s = String.Empty; if (length == -1) s = packet.ReadLenString(); else s = packet.ReadString(length); return new MySqlDecimal(s); } void IMySqlValue.SkipValue(MySqlPacket packet) { int len = (int)packet.ReadFieldLength(); packet.Position += len; } #endregion internal static void SetDSInfo(DataTable dsTable) { // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. DataRow row = dsTable.NewRow(); row["TypeName"] = "DECIMAL"; row["ProviderDbType"] = MySqlDbType.NewDecimal; row["ColumnSize"] = 0; row["CreateFormat"] = "DECIMAL({0},{1})"; row["CreateParameters"] = "precision,scale"; row["DataType"] = "System.Decimal"; row["IsAutoincrementable"] = false; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = true; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = false; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlGuid.cs0000644000175000017500000001551111127003600024644 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.Types { internal struct MySqlGuid : IMySqlValue { Guid mValue; private bool isNull; private byte[] bytes; private bool oldGuids; public MySqlGuid(byte[] buff) { oldGuids = false; mValue = new Guid(buff); isNull = false; bytes = buff; } public byte[] Bytes { get { return bytes; } } public bool OldGuids { get { return oldGuids; } set { oldGuids = value; } } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return MySqlDbType.Guid; } } DbType IMySqlValue.DbType { get { return DbType.Guid; } } object IMySqlValue.Value { get { return mValue; } } public Guid Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(Guid); } } string IMySqlValue.MySqlTypeName { get { return OldGuids ? "BINARY(16)" : "CHAR(36)"; } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { Guid guid = Guid.Empty; string valAsString = val as string; byte[] valAsByte = val as byte[]; if (val is Guid) guid = (Guid)val; else { try { if (valAsString != null) guid = new Guid(valAsString); else if (valAsByte != null) guid = new Guid(valAsByte); } catch (Exception ex) { throw new MySqlException(Resources.DataNotInSupportedFormat, ex); } } if (OldGuids) WriteOldGuid(packet, guid, binary); else { guid.ToString("D"); if (binary) packet.WriteLenString(guid.ToString("D")); else packet.WriteStringNoNull("'" + MySqlHelper.EscapeString(guid.ToString("D")) + "'"); } } private void WriteOldGuid(MySqlPacket packet, Guid guid, bool binary) { byte[] bytes = guid.ToByteArray(); if (binary) { packet.WriteLength(bytes.Length); packet.Write(bytes); } else { packet.WriteStringNoNull("_binary "); packet.WriteByte((byte)'\''); EscapeByteArray(bytes, bytes.Length, packet); packet.WriteByte((byte)'\''); } } private static void EscapeByteArray(byte[] bytes, int length, MySqlPacket packet) { for (int x = 0; x < length; x++) { byte b = bytes[x]; if (b == '\0') { packet.WriteByte((byte)'\\'); packet.WriteByte((byte)'0'); } else if (b == '\\' || b == '\'' || b == '\"') { packet.WriteByte((byte)'\\'); packet.WriteByte(b); } else packet.WriteByte(b); } } private MySqlGuid ReadOldGuid(MySqlPacket packet, long length) { if (length == -1) length = (long)packet.ReadFieldLength(); byte[] buff = new byte[length]; packet.Read(buff, 0, (int)length); MySqlGuid g = new MySqlGuid(buff); g.OldGuids = OldGuids; return g; } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { MySqlGuid g = new MySqlGuid(); g.isNull = true; g.OldGuids = OldGuids; if (!nullVal) { if (OldGuids) return ReadOldGuid(packet, length); string s = String.Empty; if (length == -1) s = packet.ReadLenString(); else s = packet.ReadString(length); g.mValue = new Guid(s); g.isNull = false; } return g; } void IMySqlValue.SkipValue(MySqlPacket packet) { int len = (int)packet.ReadFieldLength(); packet.Position += len; } #endregion public static void SetDSInfo(DataTable dsTable) { // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. DataRow row = dsTable.NewRow(); row["TypeName"] = "GUID"; row["ProviderDbType"] = MySqlDbType.Guid; row["ColumnSize"] = 0; row["CreateFormat"] = "BINARY(16)"; row["CreateParameters"] = null; row["DataType"] = "System.Guid"; row["IsAutoincrementable"] = false; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = true; row["IsFixedPrecisionScale"] = true; row["IsLong"] = false; row["IsNullable"] = true; row["IsSearchable"] = false; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = false; row["MaximumScale"] = 0; row["MinimumScale"] = 0; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = null; row["LiteralSuffix"] = null; row["NativeDataType"] = null; dsTable.Rows.Add(row); } } } mysql-connector-net-6.4.3/Source/MySql.Data/Types/MySqlBinary.cs0000644000175000017500000001541011127003600025176 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using MySql.Data.MySqlClient; namespace MySql.Data.Types { internal struct MySqlBinary : IMySqlValue { private MySqlDbType type; private byte[] mValue; private bool isNull; public MySqlBinary(MySqlDbType type, bool isNull) { this.type = type; this.isNull = isNull; mValue = null; } public MySqlBinary(MySqlDbType type, byte[] val) { this.type = type; this.isNull = false; mValue = val; } #region IMySqlValue Members public bool IsNull { get { return isNull; } } MySqlDbType IMySqlValue.MySqlDbType { get { return type; } } DbType IMySqlValue.DbType { get { return DbType.Binary; } } object IMySqlValue.Value { get { return mValue; } } public byte[] Value { get { return mValue; } } Type IMySqlValue.SystemType { get { return typeof(byte[]); } } string IMySqlValue.MySqlTypeName { get { switch (type) { case MySqlDbType.TinyBlob: return "TINY_BLOB"; case MySqlDbType.MediumBlob: return "MEDIUM_BLOB"; case MySqlDbType.LongBlob: return "LONG_BLOB"; case MySqlDbType.Blob: default: return "BLOB"; } } } void IMySqlValue.WriteValue(MySqlPacket packet, bool binary, object val, int length) { byte[] buffToWrite = (val as byte[]); if (buffToWrite == null) { char[] valAsChar = (val as Char[]); if (valAsChar != null) buffToWrite = packet.Encoding.GetBytes(valAsChar); else { string s = val.ToString(); if (length == 0) length = s.Length; else s = s.Substring(0, length); buffToWrite = packet.Encoding.GetBytes(s); } } // we assume zero length means write all of the value if (length == 0) length = buffToWrite.Length; if (buffToWrite == null) throw new MySqlException("Only byte arrays and strings can be serialized by MySqlBinary"); if (binary) { packet.WriteLength(length); packet.Write(buffToWrite, 0, length); } else { packet.WriteStringNoNull("_binary "); packet.WriteByte((byte)'\''); EscapeByteArray(buffToWrite, length, packet); packet.WriteByte((byte)'\''); } } private static void EscapeByteArray(byte[] bytes, int length, MySqlPacket packet) { for (int x = 0; x < length; x++) { byte b = bytes[x]; if (b == '\0') { packet.WriteByte((byte)'\\'); packet.WriteByte((byte)'0'); } else if (b == '\\' || b == '\'' || b == '\"') { packet.WriteByte((byte)'\\'); packet.WriteByte(b); } else packet.WriteByte(b); } } IMySqlValue IMySqlValue.ReadValue(MySqlPacket packet, long length, bool nullVal) { MySqlBinary b; if (nullVal) b = new MySqlBinary(type, true); else { if (length == -1) length = (long)packet.ReadFieldLength(); byte[] newBuff = new byte[length]; packet.Read(newBuff, 0, (int)length); b = new MySqlBinary(type, newBuff); } return b; } void IMySqlValue.SkipValue(MySqlPacket packet) { int len = (int)packet.ReadFieldLength(); packet.Position += len; } #endregion public static void SetDSInfo(DataTable dsTable) { string[] types = new string[] { "BLOB", "TINYBLOB", "MEDIUMBLOB", "LONGBLOB", "BINARY", "VARBINARY" }; MySqlDbType[] dbtype = new MySqlDbType[] { MySqlDbType.Blob, MySqlDbType.TinyBlob, MySqlDbType.MediumBlob, MySqlDbType.LongBlob, MySqlDbType.Binary, MySqlDbType.VarBinary }; long[] sizes = new long[] { 65535L, 255L, 16777215L, 4294967295L, 255L, 65535L }; string[] format = new string[] { null, null, null, null, "binary({0})", "varbinary({0})" }; string[] parms = new string[] { null, null, null, null, "length", "length" }; // we use name indexing because this method will only be called // when GetSchema is called for the DataSourceInformation // collection and then it wil be cached. for (int x = 0; x < types.Length; x++) { DataRow row = dsTable.NewRow(); row["TypeName"] = types[x]; row["ProviderDbType"] = dbtype[x]; row["ColumnSize"] = sizes[x]; row["CreateFormat"] = format[x]; row["CreateParameters"] = parms[x]; row["DataType"] = "System.Byte[]"; row["IsAutoincrementable"] = false; row["IsBestMatch"] = true; row["IsCaseSensitive"] = false; row["IsFixedLength"] = x < 4 ? false : true; row["IsFixedPrecisionScale"] = false; row["IsLong"] = sizes[x] > 255; row["IsNullable"] = true; row["IsSearchable"] = false; row["IsSearchableWithLike"] = false; row["IsUnsigned"] = DBNull.Value; row["MaximumScale"] = DBNull.Value; row["MinimumScale"] = DBNull.Value; row["IsConcurrencyType"] = DBNull.Value; row["IsLiteralSupported"] = false; row["LiteralPrefix"] = "0x"; row["LiteralSuffix"] = DBNull.Value; row["NativeDataType"] = DBNull.Value; dsTable.Rows.Add(row); } } } } mysql-connector-net-6.4.3/Source/MySql.Data/TimedStream.cs0000644000175000017500000002157611127003600024110 0ustar directhexdirecthex// Copyright (c) 2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.IO; using System.Net.Sockets; using System.Diagnostics; using MySql.Data.Common; namespace MySql.Data.MySqlClient { /// /// Stream that supports timeout of IO operations. /// This class is used is used to support timeouts for SQL command, where a /// typical operation involves several network reads/writes. /// Timeout here is defined as the accumulated duration of all IO operations. /// internal class TimedStream : Stream { Stream baseStream; int timeout; int lastReadTimeout; int lastWriteTimeout; LowResolutionStopwatch stopwatch; bool isClosed; enum IOKind { Read, Write }; /// /// Construct a TimedStream /// /// Undelying stream public TimedStream(Stream baseStream) { this.baseStream = baseStream; #if !CF timeout = baseStream.ReadTimeout; #else timeout = System.Threading.Timeout.Infinite; #endif isClosed = false; stopwatch = new LowResolutionStopwatch(); } /// /// Figure out whether it is necessary to reset timeout on stream. /// We track the current value of timeout and try to avoid /// changing it too often, because setting Read/WriteTimeout property /// on network stream maybe a slow operation that involves a system call /// (setsockopt). Therefore, we allow a small difference, and do not /// reset timeout if current value is slightly greater than the requested /// one (within 0.1 second). /// private bool ShouldResetStreamTimeout(int currentValue, int newValue) { if (newValue == System.Threading.Timeout.Infinite && currentValue != newValue) return true; if (newValue > currentValue) return true; if (currentValue>= newValue + 100) return true; return false; } private void StartTimer(IOKind op) { int streamTimeout; if (timeout == System.Threading.Timeout.Infinite) streamTimeout = System.Threading.Timeout.Infinite; else streamTimeout = timeout - (int)stopwatch.ElapsedMilliseconds; if (op == IOKind.Read) { if (ShouldResetStreamTimeout(lastReadTimeout, streamTimeout)) { #if !CF baseStream.ReadTimeout = streamTimeout; #endif lastReadTimeout = streamTimeout; } } else { if (ShouldResetStreamTimeout(lastWriteTimeout, streamTimeout)) { #if !CF baseStream.WriteTimeout = streamTimeout; #endif lastWriteTimeout = streamTimeout; } } if (timeout == System.Threading.Timeout.Infinite) return; stopwatch.Start(); } private void StopTimer() { if (timeout == System.Threading.Timeout.Infinite) return; stopwatch.Stop(); // Normally, a timeout exception would be thrown by stream itself, // since we set the read/write timeout for the stream. However // there is a gap between end of IO operation and stopping the // stop watch, and it makes it possible for timeout to exceed // even after IO completed successfully. if (stopwatch.ElapsedMilliseconds > timeout) { ResetTimeout(System.Threading.Timeout.Infinite); throw new TimeoutException("Timeout in IO operation"); } } public override bool CanRead { get { return baseStream.CanRead; } } public override bool CanSeek { get { return baseStream.CanSeek; } } public override bool CanWrite { get { return baseStream.CanWrite; } } public override void Flush() { try { StartTimer(IOKind.Write); baseStream.Flush(); StopTimer(); } catch (Exception e) { HandleException(e); throw; } } public override long Length { get { return baseStream.Length; } } public override long Position { get { return baseStream.Position; } set { baseStream.Position = value; } } public override int Read(byte[] buffer, int offset, int count) { try { StartTimer(IOKind.Read); int retval = baseStream.Read(buffer, offset, count); StopTimer(); return retval; } catch (Exception e) { HandleException(e); throw; } } public override int ReadByte() { try { StartTimer(IOKind.Read); int retval = baseStream.ReadByte(); StopTimer(); return retval; } catch (Exception e) { HandleException(e); throw; } } public override long Seek(long offset, SeekOrigin origin) { return baseStream.Seek(offset, origin); } public override void SetLength(long value) { baseStream.SetLength(value); } public override void Write(byte[] buffer, int offset, int count) { try { StartTimer(IOKind.Write); baseStream.Write(buffer, offset, count); StopTimer(); } catch (Exception e) { HandleException(e); throw; } } public override bool CanTimeout { get { return baseStream.CanTimeout; } } public override int ReadTimeout { get { return baseStream.ReadTimeout; } set { baseStream.ReadTimeout = value; } } public override int WriteTimeout { get { return baseStream.WriteTimeout; } set { baseStream.WriteTimeout = value; } } public override void Close() { if (isClosed) return; isClosed = true; baseStream.Close(); } public void ResetTimeout(int newTimeout) { if (newTimeout == System.Threading.Timeout.Infinite || newTimeout == 0) timeout = System.Threading.Timeout.Infinite; else timeout = newTimeout; stopwatch.Reset(); } /// /// Common handler for IO exceptions. /// Resets timeout to infinity if timeout exception is /// detected and stops the times. /// /// original exception void HandleException(Exception e) { stopwatch.Stop(); ResetTimeout(-1); } } } mysql-connector-net-6.4.3/Source/MySql.Data/MySqlStream.cs0000644000175000017500000001765011127003600024111 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.IO; using System.Diagnostics; using System.Text; using MySql.Data.Common; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { /// /// Summary description for MySqlStream. /// internal class MySqlStream { private byte sequenceByte; private MemoryStream bufferStream; private int maxBlockSize; private ulong maxPacketSize; private byte[] packetHeader = new byte[4]; MySqlPacket packet; TimedStream timedStream; Stream inStream; Stream outStream; internal Stream BaseStream { get { return timedStream; } } public MySqlStream(Encoding encoding) { // we have no idea what the real value is so we start off with the max value // The real value will be set in NativeDriver.Configure() maxPacketSize = ulong.MaxValue; // we default maxBlockSize to MaxValue since we will get the 'real' value in // the authentication handshake and we know that value will not exceed // true maxBlockSize prior to that. maxBlockSize = Int32.MaxValue; packet = new MySqlPacket(encoding); bufferStream = new MemoryStream(); } public MySqlStream(Stream baseStream, Encoding encoding, bool compress) : this(encoding) { timedStream = new TimedStream(baseStream); Stream stream; if (compress) stream = new CompressedStream(timedStream); else stream = timedStream; inStream = new BufferedStream(stream); outStream = stream; } public void Close() { outStream.Close(); inStream.Close(); timedStream.Close(); } #region Properties public Encoding Encoding { get { return packet.Encoding; } set { packet.Encoding = value; } } public void ResetTimeout(int timeout) { timedStream.ResetTimeout(timeout); } public byte SequenceByte { get { return sequenceByte; } set { sequenceByte = value; } } public int MaxBlockSize { get { return maxBlockSize; } set { maxBlockSize = value; } } public ulong MaxPacketSize { get { return maxPacketSize; } set { maxPacketSize = value; } } #endregion #region Packet methods /// /// ReadPacket is called by NativeDriver to start reading the next /// packet on the stream. /// public MySqlPacket ReadPacket() { //Debug.Assert(packet.Position == packet.Length); // make sure we have read all the data from the previous packet //Debug.Assert(HasMoreData == false, "HasMoreData is true in OpenPacket"); LoadPacket(); // now we check if this packet is a server error if (packet.Buffer[0] == 0xff) { packet.ReadByte(); // read off the 0xff int code = packet.ReadInteger(2); string msg = packet.ReadString(); if (msg.StartsWith("#")) { msg.Substring(1, 5); /* state code */ msg = msg.Substring(6); } throw new MySqlException(msg, code); } return packet; } /// /// Reads the specified number of bytes from the stream and stores them at given /// offset in the buffer. /// Throws EndOfStreamException if not all bytes can be read. /// /// Stream to read from /// Array to store bytes read from the stream /// The offset in buffer at which to begin storing the data read from the current stream. /// Number of bytes to read internal static void ReadFully(Stream stream, byte[] buffer, int offset, int count) { int numRead = 0; int numToRead = count; while (numToRead > 0) { int read = stream.Read(buffer, offset + numRead, numToRead); if (read == 0) { throw new EndOfStreamException(); } numRead += read; numToRead -= read; } } /// /// LoadPacket loads up and decodes the header of the incoming packet. /// public void LoadPacket() { try { packet.Length = 0; int offset = 0; while (true) { ReadFully(inStream, packetHeader, 0, 4); sequenceByte = (byte)(packetHeader[3]+1); int length = (int)(packetHeader[0] + (packetHeader[1] << 8) + (packetHeader[2] << 16)); // make roo for the next block packet.Length += length; ReadFully(inStream, packet.Buffer, offset, length); offset += length; // if this block was < maxBlock then it's last one in a multipacket series if (length < maxBlockSize) break; } packet.Position = 0; } catch (IOException ioex) { throw new MySqlException(Resources.ReadFromStreamFailed, true, ioex); } } public void SendPacket(MySqlPacket packet) { byte[] buffer = packet.Buffer; int length = packet.Position-4; if ((ulong)length > maxPacketSize) throw new MySqlException(Resources.QueryTooLarge, (int)MySqlErrorCode.PacketTooLarge); int offset = 0; while (length > 0) { int lenToSend = length > maxBlockSize ? maxBlockSize : length; buffer[offset] = (byte)(lenToSend & 0xff); buffer[offset+1] = (byte)((lenToSend >> 8) & 0xff); buffer[offset+2] = (byte)((lenToSend >> 16) & 0xff); buffer[offset+3] = sequenceByte++; outStream.Write(buffer, offset, lenToSend + 4); outStream.Flush(); length -= lenToSend; offset += lenToSend; } } public void SendEntirePacketDirectly(byte[] buffer, int count) { buffer[0] = (byte)(count & 0xff); buffer[1] = (byte)((count >> 8) & 0xff); buffer[2] = (byte)((count >> 16) & 0xff); buffer[3] = sequenceByte++; outStream.Write(buffer, 0, count + 4); outStream.Flush(); } #endregion } } mysql-connector-net-6.4.3/Source/MySql.Data/MysqlDefs.cs0000644000175000017500000003247411127003600023600 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; namespace MySql.Data.MySqlClient { /// /// Summary description for ClientParam. /// [Flags] internal enum ClientFlags : ulong { LONG_PASSWORD = 1, // new more secure passwords FOUND_ROWS = 2, // found instead of affected rows LONG_FLAG = 4, // Get all column flags CONNECT_WITH_DB = 8, // One can specify db on connect NO_SCHEMA = 16, // Don't allow db.table.column COMPRESS = 32, // Client can use compression protocol ODBC = 64, // ODBC client LOCAL_FILES = 128, // Can use LOAD DATA LOCAL IGNORE_SPACE = 256, // Ignore spaces before '(' PROTOCOL_41 = 512, // Support new 4.1 protocol INTERACTIVE = 1024, // This is an interactive client #if !CF SSL = 2048, // Switch to SSL after handshake #endif IGNORE_SIGPIPE = 4096, // IGNORE sigpipes TRANSACTIONS = 8192, // Client knows about transactions RESERVED = 16384, // old 4.1 protocol flag SECURE_CONNECTION = 32768, // new 4.1 authentication MULTI_STATEMENTS = 65536, // Allow multi-stmt support MULTI_RESULTS = 131072, // Allow multiple resultsets PS_MULTI_RESULTS = 1UL << 18, // allow multi results using PS protocol PLUGIN_AUTH = (1UL << 19), //Client supports plugin authentication CLIENT_SSL_VERIFY_SERVER_CERT= (1UL << 30), CLIENT_REMEMBER_OPTIONS= (1UL << 31) } [Flags] internal enum ServerStatusFlags { InTransaction = 1, // Transaction has started AutoCommitMode = 2, // Server in auto_commit mode MoreResults = 4, // More results on server AnotherQuery = 8, // Multi query - next query exists BadIndex = 16, NoIndex = 32, CursorExists = 64, LastRowSent = 128, OutputParameters = 4096 } /// /// DB Operations Code /// internal enum DBCmd : byte { SLEEP = 0, QUIT = 1, INIT_DB = 2, QUERY = 3, FIELD_LIST = 4, CREATE_DB = 5, DROP_DB = 6, RELOAD = 7, SHUTDOWN = 8, STATISTICS = 9, PROCESS_INFO = 10, CONNECT = 11, PROCESS_KILL = 12, DEBUG = 13, PING = 14, TIME = 15, DELAYED_INSERT = 16, CHANGE_USER = 17, BINLOG_DUMP = 18, TABLE_DUMP = 19, CONNECT_OUT = 20, REGISTER_SLAVE = 21, PREPARE = 22, EXECUTE = 23, LONG_DATA = 24, CLOSE_STMT = 25, RESET_STMT = 26, SET_OPTION = 27, FETCH = 28 } /// /// Specifies MySQL specific data type of a field, property, for use in a . /// public enum MySqlDbType { /// /// /// A fixed precision and scale numeric value between -1038 /// -1 and 10 38 -1. /// Decimal = 0, /// /// The signed range is -128 to 127. The unsigned /// range is 0 to 255. /// Byte = 1, /// /// A 16-bit signed integer. The signed range is /// -32768 to 32767. The unsigned range is 0 to 65535 /// Int16 = 2, /// /// Specifies a 24 (3 byte) signed or unsigned value. /// Int24 = 9, /// /// A 32-bit signed integer /// Int32 = 3, /// /// A 64-bit signed integer. /// Int64 = 8, /// /// A small (single-precision) floating-point /// number. Allowable values are -3.402823466E+38 to -1.175494351E-38, /// 0, and 1.175494351E-38 to 3.402823466E+38. /// Float = 4, /// /// A normal-size (double-precision) /// floating-point number. Allowable values are -1.7976931348623157E+308 /// to -2.2250738585072014E-308, 0, and 2.2250738585072014E-308 to /// 1.7976931348623157E+308. /// Double = 5, /// /// A timestamp. The range is '1970-01-01 00:00:00' to sometime in the /// year 2037 /// Timestamp = 7, /// ///Date The supported range is '1000-01-01' to '9999-12-31'. /// Date = 10, /// /// Time The range is '-838:59:59' to '838:59:59'. /// Time = 11, /// ///DateTime The supported range is '1000-01-01 00:00:00' to ///'9999-12-31 23:59:59'. /// DateTime = 12, /// ///Datetime The supported range is '1000-01-01 00:00:00' to ///'9999-12-31 23:59:59'. /// [Obsolete("The Datetime enum value is obsolete. Please use DateTime.")] Datetime = 12, /// /// A year in 2- or 4-digit format (default is 4-digit). The /// allowable values are 1901 to 2155, 0000 in the 4-digit year /// format, and 1970-2069 if you use the 2-digit format (70-69). /// Year = 13, /// /// Obsolete Use Datetime or Date type /// Newdate = 14, /// /// A variable-length string containing 0 to 65535 characters /// VarString = 15, /// /// Bit-field data type /// Bit = 16, /// /// New Decimal /// NewDecimal = 246, /// /// An enumeration. A string object that can have only one value, /// chosen from the list of values 'value1', 'value2', ..., NULL /// or the special "" error value. An ENUM can have a maximum of /// 65535 distinct values /// Enum = 247, /// /// A set. A string object that can have zero or more values, each /// of which must be chosen from the list of values 'value1', 'value2', /// ... A SET can have a maximum of 64 members. /// Set = 248, /// /// A binary column with a maximum length of 255 (2^8 - 1) /// characters /// TinyBlob = 249, /// /// A binary column with a maximum length of 16777215 (2^24 - 1) bytes. /// MediumBlob = 250, /// /// A binary column with a maximum length of 4294967295 or /// 4G (2^32 - 1) bytes. /// LongBlob = 251, /// /// A binary column with a maximum length of 65535 (2^16 - 1) bytes. /// Blob = 252, /// /// A variable-length string containing 0 to 255 bytes. /// VarChar = 253, /// /// A fixed-length string. /// String = 254, /// /// Geometric (GIS) data type. /// Geometry = 255, /// /// Unsigned 8-bit value. /// UByte = 501, /// /// Unsigned 16-bit value. /// UInt16 = 502, /// /// Unsigned 24-bit value. /// UInt24 = 509, /// /// Unsigned 32-bit value. /// UInt32 = 503, /// /// Unsigned 64-bit value. /// UInt64 = 508, /// /// Fixed length binary string. /// Binary = 600, /// /// Variable length binary string. /// VarBinary = 601, /// /// A text column with a maximum length of 255 (2^8 - 1) characters. /// TinyText = 749, /// /// A text column with a maximum length of 16777215 (2^24 - 1) characters. /// MediumText = 750, /// /// A text column with a maximum length of 4294967295 or /// 4G (2^32 - 1) characters. /// LongText = 751, /// /// A text column with a maximum length of 65535 (2^16 - 1) characters. /// Text = 752, /// /// A guid column /// Guid = 800 } ; internal enum Field_Type : byte { DECIMAL = 0, BYTE = 1, SHORT = 2, LONG = 3, FLOAT = 4, DOUBLE = 5, NULL = 6, TIMESTAMP = 7, LONGLONG = 8, INT24 = 9, DATE = 10, TIME = 11, DATETIME = 12, YEAR = 13, NEWDATE = 14, ENUM = 247, SET = 248, TINY_BLOB = 249, MEDIUM_BLOB = 250, LONG_BLOB = 251, BLOB = 252, VAR_STRING = 253, STRING = 254, } /// /// Allows the user to specify the type of connection that should /// be used. /// public enum MySqlConnectionProtocol { /// /// TCP/IP style connection. Works everywhere. /// Sockets = 1, Socket = 1, Tcp = 1, /// /// Named pipe connection. Works only on Windows systems. /// Pipe = 2, NamedPipe = 2, /// /// Unix domain socket connection. Works only with Unix systems. /// UnixSocket = 3, Unix = 3, /// /// Shared memory connection. Currently works only with Windows systems. /// SharedMemory = 4, Memory = 4 } /// /// SSL options for connection. /// public enum MySqlSslMode { /// /// Do not use SSL. /// None, /// /// Use SSL, if server supports it. /// Preferred, Prefered = Preferred, /// /// Always use SSL. Deny connection if server does not support SSL. /// Do not perform server certificate validation. /// Required, /// /// Always use SSL. Validate server SSL certificate, but different host name mismatch. /// VerifyCA, /// /// Always use SSL and perform full certificate validation. /// VerifyFull } /// /// Specifies the connection types supported /// public enum MySqlDriverType { /// /// Use TCP/IP sockets. /// Native, /// /// Use client library. /// Client, /// /// Use MySQL embedded server. /// Embedded } public enum MySqlCertificateStoreLocation { /// /// Do not use certificate store /// None, /// /// Use certificate store for the current user /// CurrentUser, /// /// User certificate store for the machine /// LocalMachine } }mysql-connector-net-6.4.3/Source/MySql.Data/datareader.cs0000644000175000017500000010720411127003600023757 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Data.Common; using System.Collections; using MySql.Data.Types; using System.Data.SqlTypes; using System.Collections.Generic; using System.Globalization; using MySql.Data.MySqlClient.Properties; using MySql.Data.Common; namespace MySql.Data.MySqlClient { /// public sealed class MySqlDataReader : DbDataReader, IDataReader, IDataRecord { // The DataReader should always be open when returned to the user. private bool isOpen = true; private CommandBehavior commandBehavior; private MySqlCommand command; internal long affectedRows; internal Driver driver; private PreparableStatement statement; private ResultSet resultSet; // Used in special circumstances with stored procs to avoid exceptions from DbDataAdapter // If set, AffectedRows returns -1 instead of 0. private bool disableZeroAffectedRows; /* * Keep track of the connection in order to implement the * CommandBehavior.CloseConnection flag. A null reference means * normal behavior (do not automatically close). */ private MySqlConnection connection; /* * Because the user should not be able to directly create a * DataReader object, the constructors are * marked as internal. */ internal MySqlDataReader(MySqlCommand cmd, PreparableStatement statement, CommandBehavior behavior) { this.command = cmd; connection = (MySqlConnection)command.Connection; commandBehavior = behavior; driver = connection.driver; affectedRows = -1; this.statement = statement; if (cmd.CommandType == CommandType.StoredProcedure && cmd.UpdatedRowSource == UpdateRowSource.FirstReturnedRecord) { disableZeroAffectedRows = true; } } #region Properties internal PreparableStatement Statement { get { return statement; } } internal MySqlCommand Command { get { return command; } } internal ResultSet ResultSet { get { return resultSet; } } internal CommandBehavior CommandBehavior { get { return commandBehavior; } } /// /// Gets a value indicating the depth of nesting for the current row. This method is not /// supported currently and always returns 0. /// public override int Depth { get { return 0; } } /// /// Gets the number of columns in the current row. /// public override int FieldCount { get { return resultSet == null ? 0 : resultSet.Size; } } /// /// Gets a value indicating whether the MySqlDataReader contains one or more rows. /// public override bool HasRows { get { return resultSet == null ? false : resultSet.HasRows; } } /// /// Gets a value indicating whether the data reader is closed. /// public override bool IsClosed { get { return !isOpen; } } /// /// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement. /// public override int RecordsAffected { // RecordsAffected returns the number of rows affected in batch // statments from insert/delete/update statments. This property // is not completely accurate until .Close() has been called. get { if (disableZeroAffectedRows) { // In special case of updating stored procedure called from // within data adapter, we return -1 to avoid exceptions // (s. Bug#54895) if (affectedRows == 0) return -1; } return (int)affectedRows; } } /// /// Overloaded. Gets the value of a column in its native format. /// In C#, this property is the indexer for the MySqlDataReader class. /// public override object this[int i] { get { return GetValue(i); } } /// /// Gets the value of a column in its native format. /// [C#] In C#, this property is the indexer for the MySqlDataReader class. /// public override object this[String name] { // Look up the ordinal and return // the value at that position. get { return this[GetOrdinal(name)]; } } #endregion /// /// Closes the MySqlDataReader object. /// public override void Close() { if (!isOpen) return; bool shouldCloseConnection = (commandBehavior & CommandBehavior.CloseConnection) != 0; commandBehavior = CommandBehavior.Default; // clear all remaining resultsets try { while (NextResult()) { } } catch (MySqlException ex) { // Ignore aborted queries if (!ex.IsQueryAborted) { // ignore IO exceptions. // We are closing or disposing reader, and do not // want exception to be propagated to used. If socket is // is closed on the server side, next query will run into // IO exception. If reader is closed by GC, we also would // like to avoid any exception here. bool isIOException = false; for (Exception exception = ex; exception != null; exception = exception.InnerException) { if (exception is System.IO.IOException) { isIOException = true; break; } } if (!isIOException) { // Ordinary exception (neither IO nor query aborted) throw; } } } catch (System.IO.IOException) { // eat, on the same reason we eat IO exceptions wrapped into // MySqlExceptions reasons, described above. } finally { // always ensure internal reader is null (Bug #55558) connection.Reader = null; } // we now give the command a chance to terminate. In the case of // stored procedures it needs to update out and inout parameters command.Close(this); if (this.command.Canceled && connection.driver.Version.isAtLeast(5, 1, 0)) { // Issue dummy command to clear kill flag ClearKillFlag(); } if (shouldCloseConnection) connection.Close(); command = null; connection.IsInUse = false; connection = null; isOpen = false; } #region TypeSafe Accessors /// /// Gets the value of the specified column as a Boolean. /// /// /// public bool GetBoolean(string name) { return GetBoolean(GetOrdinal(name)); } /// /// Gets the value of the specified column as a Boolean. /// /// /// public override bool GetBoolean(int i) { return Convert.ToBoolean(GetValue(i)); } /// /// Gets the value of the specified column as a byte. /// /// /// public byte GetByte(string name) { return GetByte(GetOrdinal(name)); } /// /// Gets the value of the specified column as a byte. /// /// /// public override byte GetByte(int i) { IMySqlValue v = GetFieldValue(i, false); if (v is MySqlUByte) return ((MySqlUByte)v).Value; else return (byte)((MySqlByte)v).Value; } /// /// Gets the value of the specified column as a sbyte. /// /// /// public sbyte GetSByte(string name) { return GetSByte(GetOrdinal(name)); } /// /// Gets the value of the specified column as a sbyte. /// /// /// public sbyte GetSByte(int i) { IMySqlValue v = GetFieldValue(i, false); if (v is MySqlByte) return ((MySqlByte)v).Value; else return (sbyte)((MySqlByte)v).Value; } /// /// Reads a stream of bytes from the specified column offset into the buffer an array starting at the given buffer offset. /// /// The zero-based column ordinal. /// The index within the field from which to begin the read operation. /// The buffer into which to read the stream of bytes. /// The index for buffer to begin the read operation. /// The maximum length to copy into the buffer. /// The actual number of bytes read. /// public override long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { if (i >= FieldCount) throw new IndexOutOfRangeException(); IMySqlValue val = GetFieldValue(i, false); if (!(val is MySqlBinary) && !(val is MySqlGuid)) throw new MySqlException("GetBytes can only be called on binary or guid columns"); byte[] bytes = null; if (val is MySqlBinary) bytes = ((MySqlBinary)val).Value; else bytes = ((MySqlGuid)val).Bytes; if (buffer == null) return bytes.Length; if (bufferoffset >= buffer.Length || bufferoffset < 0) throw new IndexOutOfRangeException("Buffer index must be a valid index in buffer"); if (buffer.Length < (bufferoffset + length)) throw new ArgumentException("Buffer is not large enough to hold the requested data"); if (fieldOffset < 0 || ((ulong)fieldOffset >= (ulong)bytes.Length && (ulong)bytes.Length > 0)) throw new IndexOutOfRangeException("Data index must be a valid index in the field"); // adjust the length so we don't run off the end if ((ulong)bytes.Length < (ulong)(fieldOffset + length)) { length = (int)((ulong)bytes.Length - (ulong)fieldOffset); } Buffer.BlockCopy(bytes, (int)fieldOffset, buffer, (int)bufferoffset, (int)length); return length; } private object ChangeType(IMySqlValue value, int fieldIndex, Type newType) { #if !CF resultSet.Fields[fieldIndex].AddTypeConversion(newType); #endif return Convert.ChangeType(value.Value, newType, CultureInfo.InvariantCulture); } /// /// Gets the value of the specified column as a single character. /// /// /// public char GetChar(string name) { return GetChar(GetOrdinal(name)); } /// /// Gets the value of the specified column as a single character. /// /// /// public override char GetChar(int i) { string s = GetString(i); return s[0]; } /// /// Reads a stream of characters from the specified column offset into the buffer as an array starting at the given buffer offset. /// /// /// /// /// /// /// public override long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { if (i >= FieldCount) throw new IndexOutOfRangeException(); string valAsString = GetString(i); if (buffer == null) return valAsString.Length; if (bufferoffset >= buffer.Length || bufferoffset < 0) throw new IndexOutOfRangeException("Buffer index must be a valid index in buffer"); if (buffer.Length < (bufferoffset + length)) throw new ArgumentException("Buffer is not large enough to hold the requested data"); if (fieldoffset < 0 || fieldoffset >= valAsString.Length) throw new IndexOutOfRangeException("Field offset must be a valid index in the field"); if (valAsString.Length < length) length = valAsString.Length; valAsString.CopyTo((int)fieldoffset, buffer, bufferoffset, length); return length; } /// /// Gets the name of the source data type. /// /// /// public override String GetDataTypeName(int i) { if (!isOpen) throw new Exception("No current query in data reader"); if (i >= FieldCount) throw new IndexOutOfRangeException(); // return the name of the type used on the backend IMySqlValue v = resultSet.Values[i]; return v.MySqlTypeName; } /// public MySqlDateTime GetMySqlDateTime(string column) { return GetMySqlDateTime(GetOrdinal(column)); } /// public MySqlDateTime GetMySqlDateTime(int column) { return (MySqlDateTime)GetFieldValue(column, true); } /// public DateTime GetDateTime(string column) { return GetDateTime(GetOrdinal(column)); } /// public override DateTime GetDateTime(int i) { IMySqlValue val = GetFieldValue(i, true); MySqlDateTime dt; if (val is MySqlDateTime) dt = (MySqlDateTime)val; else { // we need to do this because functions like date_add return string string s = GetString(i); dt = MySqlDateTime.Parse(s); } if (connection.Settings.ConvertZeroDateTime && !dt.IsValidDateTime) return DateTime.MinValue; else return dt.GetDateTime(); } public MySqlDecimal GetMySqlDecimal(string column) { return GetMySqlDecimal(GetOrdinal(column)); } public MySqlDecimal GetMySqlDecimal(int i) { return (MySqlDecimal)GetFieldValue(i, false); } /// public Decimal GetDecimal(string column) { return GetDecimal(GetOrdinal(column)); } /// public override Decimal GetDecimal(int i) { IMySqlValue v = GetFieldValue(i, true); if (v is MySqlDecimal) return ((MySqlDecimal)v).Value; return Convert.ToDecimal(v.Value); } /// public double GetDouble(string column) { return GetDouble(GetOrdinal(column)); } /// public override double GetDouble(int i) { IMySqlValue v = GetFieldValue(i, true); if (v is MySqlDouble) return ((MySqlDouble)v).Value; return Convert.ToDouble(v.Value); } public Type GetFieldType(string column) { return GetFieldType(GetOrdinal(column)); } /// /// Gets the Type that is the data type of the object. /// /// /// public override Type GetFieldType(int i) { if (!isOpen) throw new Exception("No current query in data reader"); if (i >= FieldCount) throw new IndexOutOfRangeException(); // we have to use the values array directly because we can't go through // GetValue IMySqlValue v = resultSet.Values[i]; if (v is MySqlDateTime) { if (!connection.Settings.AllowZeroDateTime) return typeof(DateTime); return typeof(MySqlDateTime); } return v.SystemType; } /// public float GetFloat(string column) { return GetFloat(GetOrdinal(column)); } /// public override float GetFloat(int i) { IMySqlValue v = GetFieldValue(i, true); if (v is MySqlSingle) return ((MySqlSingle)v).Value; return Convert.ToSingle(v.Value); } /// public Guid GetGuid(string column) { return GetGuid(GetOrdinal(column)); } /// public override Guid GetGuid(int i) { object v = GetValue(i); if (v is Guid) return (Guid)v; if (v is string) return new Guid(v as string); if (v is byte[]) { byte[] bytes = (byte[])v; if (bytes.Length == 16) return new Guid(bytes); } throw new MySqlException(Resources.ValueNotSupportedForGuid); } /// public Int16 GetInt16(string column) { return GetInt16(GetOrdinal(column)); } /// public override Int16 GetInt16(int i) { IMySqlValue v = GetFieldValue(i, true); if (v is MySqlInt16) return ((MySqlInt16)v).Value; return (short)ChangeType(v, i, typeof(short)); } /// public Int32 GetInt32(string column) { return GetInt32(GetOrdinal(column)); } /// public override Int32 GetInt32(int i) { IMySqlValue v = GetFieldValue(i, true); if (v is MySqlInt32) return ((MySqlInt32)v).Value; return (Int32)ChangeType(v, i, typeof(Int32)); } /// public Int64 GetInt64(string column) { return GetInt64(GetOrdinal(column)); } /// public override Int64 GetInt64(int i) { IMySqlValue v = GetFieldValue(i, true); if (v is MySqlInt64) return ((MySqlInt64)v).Value; return (Int64)ChangeType(v, i, typeof(Int64)); } /// /// Gets the name of the specified column. /// /// /// public override String GetName(int i) { if (!isOpen) throw new Exception("No current query in data reader"); if (i >= FieldCount) throw new IndexOutOfRangeException(); return resultSet.Fields[i].ColumnName; } /// /// Gets the column ordinal, given the name of the column. /// /// /// public override int GetOrdinal(string name) { if (!isOpen || resultSet == null) throw new Exception("No current query in data reader"); return resultSet.GetOrdinal(name); } /// /// Returns a DataTable that describes the column metadata of the MySqlDataReader. /// /// public override DataTable GetSchemaTable() { // Only Results from SQL SELECT Queries // get a DataTable for schema of the result // otherwise, DataTable is null reference if (FieldCount == 0) return null; DataTable dataTableSchema = new DataTable("SchemaTable"); dataTableSchema.Columns.Add("ColumnName", typeof(string)); dataTableSchema.Columns.Add("ColumnOrdinal", typeof(int)); dataTableSchema.Columns.Add("ColumnSize", typeof(int)); dataTableSchema.Columns.Add("NumericPrecision", typeof(int)); dataTableSchema.Columns.Add("NumericScale", typeof(int)); dataTableSchema.Columns.Add("IsUnique", typeof(bool)); dataTableSchema.Columns.Add("IsKey", typeof(bool)); DataColumn dc = dataTableSchema.Columns["IsKey"]; dc.AllowDBNull = true; // IsKey can have a DBNull dataTableSchema.Columns.Add("BaseCatalogName", typeof(string)); dataTableSchema.Columns.Add("BaseColumnName", typeof(string)); dataTableSchema.Columns.Add("BaseSchemaName", typeof(string)); dataTableSchema.Columns.Add("BaseTableName", typeof(string)); dataTableSchema.Columns.Add("DataType", typeof(Type)); dataTableSchema.Columns.Add("AllowDBNull", typeof(bool)); dataTableSchema.Columns.Add("ProviderType", typeof(int)); dataTableSchema.Columns.Add("IsAliased", typeof(bool)); dataTableSchema.Columns.Add("IsExpression", typeof(bool)); dataTableSchema.Columns.Add("IsIdentity", typeof(bool)); dataTableSchema.Columns.Add("IsAutoIncrement", typeof(bool)); dataTableSchema.Columns.Add("IsRowVersion", typeof(bool)); dataTableSchema.Columns.Add("IsHidden", typeof(bool)); dataTableSchema.Columns.Add("IsLong", typeof(bool)); dataTableSchema.Columns.Add("IsReadOnly", typeof(bool)); int ord = 1; for (int i = 0; i < FieldCount; i++) { MySqlField f = resultSet.Fields[i]; DataRow r = dataTableSchema.NewRow(); r["ColumnName"] = f.ColumnName; r["ColumnOrdinal"] = ord++; r["ColumnSize"] = f.IsTextField ? f.ColumnLength / f.MaxLength : f.ColumnLength; int prec = f.Precision; int pscale = f.Scale; if (prec != -1) r["NumericPrecision"] = (short)prec; if (pscale != -1) r["NumericScale"] = (short)pscale; r["DataType"] = GetFieldType(i); r["ProviderType"] = (int)f.Type; r["IsLong"] = f.IsBlob && f.ColumnLength > 255; r["AllowDBNull"] = f.AllowsNull; r["IsReadOnly"] = false; r["IsRowVersion"] = false; r["IsUnique"] = f.IsUnique; r["IsKey"] = f.IsPrimaryKey; r["IsAutoIncrement"] = f.IsAutoIncrement; r["BaseSchemaName"] = f.DatabaseName; r["BaseCatalogName"] = null; r["BaseTableName"] = f.RealTableName; r["BaseColumnName"] = f.OriginalColumnName; dataTableSchema.Rows.Add(r); } return dataTableSchema; } /// public string GetString(string column) { return GetString(GetOrdinal(column)); } /// public override String GetString(int i) { IMySqlValue val = GetFieldValue(i, true); if (val is MySqlBinary) { byte[] v = ((MySqlBinary)val).Value; return resultSet.Fields[i].Encoding.GetString(v, 0, v.Length); } return val.Value.ToString(); } /// public TimeSpan GetTimeSpan(string column) { return GetTimeSpan(GetOrdinal(column)); } /// public TimeSpan GetTimeSpan(int column) { IMySqlValue val = GetFieldValue(column, true); MySqlTimeSpan ts = (MySqlTimeSpan)val; return ts.Value; } /// /// Gets the value of the specified column in its native format. /// /// /// public override object GetValue(int i) { if (!isOpen) throw new Exception("No current query in data reader"); if (i >= FieldCount) throw new IndexOutOfRangeException(); IMySqlValue val = GetFieldValue(i, false); if (val.IsNull) return DBNull.Value; // if the column is a date/time, then we return a MySqlDateTime // so .ToString() will print '0000-00-00' correctly if (val is MySqlDateTime) { MySqlDateTime dt = (MySqlDateTime)val; if (!dt.IsValidDateTime && connection.Settings.ConvertZeroDateTime) return DateTime.MinValue; else if (connection.Settings.AllowZeroDateTime) return val; else return dt.GetDateTime(); } return val.Value; } /// /// Gets all attribute columns in the collection for the current row. /// /// /// public override int GetValues(object[] values) { int numCols = Math.Min(values.Length, FieldCount); for (int i = 0; i < numCols; i++) values[i] = GetValue(i); return numCols; } /// public UInt16 GetUInt16(string column) { return GetUInt16(GetOrdinal(column)); } /// public UInt16 GetUInt16(int column) { IMySqlValue v = GetFieldValue(column, true); if (v is MySqlUInt16) return ((MySqlUInt16)v).Value; return (UInt16)ChangeType(v, column, typeof(UInt16)); } /// public UInt32 GetUInt32(string column) { return GetUInt32(GetOrdinal(column)); } /// public UInt32 GetUInt32(int column) { IMySqlValue v = GetFieldValue(column, true); if (v is MySqlUInt32) return ((MySqlUInt32)v).Value; return (uint)ChangeType(v, column, typeof(UInt32)); } /// public UInt64 GetUInt64(string column) { return GetUInt64(GetOrdinal(column)); } /// public UInt64 GetUInt64(int column) { IMySqlValue v = GetFieldValue(column, true); if (v is MySqlUInt64) return ((MySqlUInt64)v).Value; return (UInt64)ChangeType(v, column, typeof(UInt64)); } #endregion IDataReader IDataRecord.GetData(int i) { return base.GetData(i); } /// /// Gets a value indicating whether the column contains non-existent or missing values. /// /// /// public override bool IsDBNull(int i) { return DBNull.Value == GetValue(i); } /// /// Advances the data reader to the next result, when reading the results of batch SQL statements. /// /// public override bool NextResult() { if (!isOpen) throw new MySqlException(Resources.NextResultIsClosed); bool isCaching = command.CommandType == CommandType.TableDirect && command.EnableCaching && (commandBehavior & CommandBehavior.SequentialAccess) == 0; // this will clear out any unread data if (resultSet != null) { resultSet.Close(); if (isCaching) TableCache.AddToCache(command.CommandText, resultSet); } // single result means we only return a single resultset. If we have already // returned one, then we return false // TableDirect is basically a select * from a single table so it will generate // a single result also if (resultSet != null && ((commandBehavior & CommandBehavior.SingleResult) != 0 || isCaching)) return false; // next load up the next resultset if any try { do { resultSet = null; // if we are table caching, then try to retrieve the resultSet from the cache if (isCaching) resultSet = TableCache.RetrieveFromCache(command.CommandText, command.CacheAge); if (resultSet == null) { resultSet = driver.NextResult(Statement.StatementId, false); if (resultSet == null) return false; if (resultSet.IsOutputParameters && command.CommandType == CommandType.StoredProcedure) { StoredProcedure sp = statement as StoredProcedure; sp.ProcessOutputParameters(this); resultSet.Close(); if (!sp.ServerProvidingOutputParameters) return false; // if we are using server side output parameters then we will get our ok packet // *after* the output parameters resultset resultSet = driver.NextResult(Statement.StatementId, true); } resultSet.Cached = isCaching; } if (resultSet.Size == 0) { Command.lastInsertedId = resultSet.InsertedId; if (affectedRows == -1) affectedRows = resultSet.AffectedRows; else affectedRows += resultSet.AffectedRows; } } while (resultSet.Size == 0); return true; } catch (MySqlException ex) { if (ex.IsFatal) connection.Abort(); if (ex.Number == 0) throw new MySqlException(Resources.FatalErrorReadingResult, ex); if ((commandBehavior & CommandBehavior.CloseConnection) != 0) Close(); throw; } } /// /// Advances the MySqlDataReader to the next record. /// /// public override bool Read() { if (!isOpen) throw new MySqlException("Invalid attempt to Read when reader is closed."); if (resultSet == null) return false; try { return resultSet.NextRow(commandBehavior); } catch (TimeoutException tex) { connection.HandleTimeoutOrThreadAbort(tex); throw; // unreached } catch (System.Threading.ThreadAbortException taex) { connection.HandleTimeoutOrThreadAbort(taex); throw; } catch (MySqlException ex) { if (ex.IsFatal) connection.Abort(); if (ex.IsQueryAborted) { throw; } throw new MySqlException(Resources.FatalErrorDuringRead, ex); } } private IMySqlValue GetFieldValue(int index, bool checkNull) { if (index < 0 || index >= FieldCount) throw new ArgumentException(Resources.InvalidColumnOrdinal); IMySqlValue v = resultSet[index]; if (checkNull && v.IsNull) throw new SqlNullValueException(); return v; } private void ClearKillFlag() { // This query will silently crash because of the Kill call that happened before. string dummyStatement = "SELECT * FROM bogus_table LIMIT 0"; /* dummy query used to clear kill flag */ MySqlCommand dummyCommand = new MySqlCommand(dummyStatement, connection); dummyCommand.InternallyCreated = true; try { IDataReader reader = dummyCommand.ExecuteReader(); // ExecuteReader catches the exception and returns null, which is expected. } catch (MySqlException ex) { if (ex.Number != (int)MySqlErrorCode.NoSuchTable) throw; } } private void ProcessOutputParameters() { // if we are not 5.5 or later or we are not prepared then we are simulating output parameters // with user variables and they are also string so we have to work some magic with out // column types before we read the data if (!driver.SupportsOutputParameters || !command.IsPrepared) AdjustOutputTypes(); // now read the output parameters data row if ((commandBehavior & System.Data.CommandBehavior.SchemaOnly) != 0) return; resultSet.NextRow(commandBehavior); string prefix = "@" + StoredProcedure.ParameterPrefix; for (int i = 0; i < FieldCount; i++) { string fieldName = GetName(i); if (fieldName.StartsWith(prefix)) fieldName = fieldName.Remove(0, prefix.Length); MySqlParameter parameter = command.Parameters.GetParameterFlexible(fieldName, true); parameter.Value = GetValue(i); } } private void AdjustOutputTypes() { // since MySQL likes to return user variables as strings // we reset the types of the readers internal value objects // this will allow those value objects to parse the string based // return values for (int i = 0; i < FieldCount; i++) { string fieldName = GetName(i); fieldName = fieldName.Remove(0, StoredProcedure.ParameterPrefix.Length + 1); MySqlParameter parameter = command.Parameters.GetParameterFlexible(fieldName, true); IMySqlValue v = MySqlField.GetIMySqlValue(parameter.MySqlDbType); if (v is MySqlBit) { MySqlBit bit = (MySqlBit)v; bit.ReadAsString = true; resultSet.SetValueObject(i, bit); } else resultSet.SetValueObject(i, v); } } #region IEnumerator /// /// Returns an that iterates through the . /// /// public override IEnumerator GetEnumerator() { return new DbEnumerator(this, (commandBehavior & CommandBehavior.CloseConnection) != 0); } #endregion } } mysql-connector-net-6.4.3/Source/MySql.Data/BulkLoader.cs0000644000175000017500000003220511127003600023705 0ustar directhexdirecthex// Copyright (c) 2006-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Text; using System.IO; using System.Data; using System.Collections.Specialized; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { /// /// /// public class MySqlBulkLoader { // constant values private const string defaultFieldTerminator = "\t"; private const string defaultLineTerminator = "\n"; private const char defaultEscapeCharacter = '\\'; // fields private string fieldTerminator; private string lineTerminator; private string charSet; private string tableName; private int numLinesToIgnore; private MySqlConnection connection; private string filename; private int timeout; private bool local; private string linePrefix; private char fieldQuotationCharacter; private bool fieldQuotationOptional; private char escapeChar; private MySqlBulkLoaderPriority priority; private MySqlBulkLoaderConflictOption conflictOption; private StringCollection columns; private StringCollection expressions; public MySqlBulkLoader(MySqlConnection connection) { Connection = connection; Local = true; FieldTerminator = defaultFieldTerminator; LineTerminator = defaultLineTerminator; FieldQuotationCharacter = Char.MinValue; ConflictOption = MySqlBulkLoaderConflictOption.None; columns = new StringCollection(); expressions = new StringCollection(); } #region Properties /// /// Gets or sets the connection. /// /// The connection. public MySqlConnection Connection { get { return connection; } set { connection = value; } } /// /// Gets or sets the field terminator. /// /// The field terminator. public string FieldTerminator { get { return fieldTerminator; } set { fieldTerminator = value; } } /// /// Gets or sets the line terminator. /// /// The line terminator. public string LineTerminator { get { return lineTerminator; } set { lineTerminator = value; } } /// /// Gets or sets the name of the table. /// /// The name of the table. public string TableName { get { return tableName; } set { tableName = value; } } /// /// Gets or sets the character set. /// /// The character set. public string CharacterSet { get { return charSet; } set { charSet = value; } } /// /// Gets or sets the name of the file. /// /// The name of the file. public string FileName { get { return filename; } set { filename = value; } } /// /// Gets or sets the timeout. /// /// The timeout. public int Timeout { get { return timeout; } set { timeout = value; } } /// /// Gets or sets a value indicating whether the filename that is to be loaded /// is local to the client or not /// /// true if local; otherwise, false. public bool Local { get { return local; } set { local = value; } } /// /// Gets or sets the number of lines to skip. /// /// The number of lines to skip. public int NumberOfLinesToSkip { get { return numLinesToIgnore; } set { numLinesToIgnore = value; } } /// /// Gets or sets the line prefix. /// /// The line prefix. public string LinePrefix { get { return linePrefix; } set { linePrefix = value; } } /// /// Gets or sets the field quotation character. /// /// The field quotation character. public char FieldQuotationCharacter { get { return fieldQuotationCharacter; } set { fieldQuotationCharacter = value; } } /// /// Gets or sets a value indicating whether [field quotation optional]. /// /// /// true if [field quotation optional]; otherwise, false. /// public bool FieldQuotationOptional { get { return fieldQuotationOptional; } set { fieldQuotationOptional = value; } } /// /// Gets or sets the escape character. /// /// The escape character. public char EscapeCharacter { get { return escapeChar; } set { escapeChar = value; } } /// /// Gets or sets the conflict option. /// /// The conflict option. public MySqlBulkLoaderConflictOption ConflictOption { get { return conflictOption; } set { conflictOption = value; } } /// /// Gets or sets the priority. /// /// The priority. public MySqlBulkLoaderPriority Priority { get { return priority; } set { priority = value; } } /// /// Gets the columns. /// /// The columns. public StringCollection Columns { get { return columns; } } /// /// Gets the expressions. /// /// The expressions. public StringCollection Expressions { get { return expressions; } } #endregion /// /// Execute the load operation /// /// The number of rows inserted. public int Load() { bool openedConnection = false; if (Connection == null) throw new InvalidOperationException(Resources.ConnectionNotSet); // next we open up the connetion if it is not already open if (connection.State != ConnectionState.Open) { openedConnection = true; connection.Open(); } try { string sql = BuildSqlCommand(); MySqlCommand cmd = new MySqlCommand(sql, Connection); cmd.CommandTimeout = Timeout; return cmd.ExecuteNonQuery(); } finally { if (openedConnection) connection.Close(); } } private string BuildSqlCommand() { StringBuilder sql = new StringBuilder("LOAD DATA "); if (Priority == MySqlBulkLoaderPriority.Low) sql.Append("LOW_PRIORITY "); else if (Priority == MySqlBulkLoaderPriority.Concurrent) sql.Append("CONCURRENT "); if (Local) sql.Append("LOCAL "); sql.Append("INFILE "); if (Path.DirectorySeparatorChar == '\\') sql.AppendFormat("'{0}' ", FileName.Replace(@"\", @"\\")); else sql.AppendFormat("'{0}' ", FileName); if (ConflictOption == MySqlBulkLoaderConflictOption.Ignore) sql.Append("IGNORE "); else if (ConflictOption == MySqlBulkLoaderConflictOption.Replace) sql.Append("REPLACE "); sql.AppendFormat("INTO TABLE {0} ", TableName); if (CharacterSet != null) sql.AppendFormat("CHARACTER SET {0} ", CharacterSet); StringBuilder optionSql = new StringBuilder(String.Empty); if (FieldTerminator != defaultFieldTerminator) optionSql.AppendFormat("TERMINATED BY '{0}' ", FieldTerminator); if (FieldQuotationCharacter != Char.MinValue) optionSql.AppendFormat("{0} ENCLOSED BY '{1}' ", FieldQuotationOptional ? "OPTIONALLY" : "", FieldQuotationCharacter); if (EscapeCharacter != defaultEscapeCharacter && EscapeCharacter != Char.MinValue) optionSql.AppendFormat("ESCAPED BY '{0}' ", EscapeCharacter); if (optionSql.Length > 0) sql.AppendFormat("FIELDS {0}", optionSql.ToString()); optionSql = new StringBuilder(String.Empty); if (LinePrefix != null && LinePrefix.Length > 0) optionSql.AppendFormat("STARTING BY '{0}' ", LinePrefix); if (LineTerminator != defaultLineTerminator) optionSql.AppendFormat("TERMINATED BY '{0}' ", LineTerminator); if (optionSql.Length > 0) sql.AppendFormat("LINES {0}", optionSql.ToString()); if (NumberOfLinesToSkip > 0) sql.AppendFormat("IGNORE {0} LINES ", NumberOfLinesToSkip); if (Columns.Count > 0) { sql.Append("("); sql.Append(Columns[0]); for (int i = 1; i < Columns.Count; i++) sql.AppendFormat(",{0}", Columns[i]); sql.Append(") "); } if (Expressions.Count > 0) { sql.Append("SET "); sql.Append(Expressions[0]); for (int i = 1; i < Expressions.Count; i++) sql.AppendFormat(",{0}", Expressions[i]); } return sql.ToString(); } } /// /// /// public enum MySqlBulkLoaderPriority { /// /// This is the default and indicates normal priority /// None, /// /// Low priority will cause the load operation to wait until all readers of the table /// have finished. This only affects storage engines that use only table-level locking /// such as MyISAM, Memory, and Merge. /// Low, /// /// Concurrent priority is only relevant for MyISAM tables and signals that if the table /// has no free blocks in the middle that other readers can retrieve data from the table /// while the load operation is happening. /// Concurrent } /// /// /// public enum MySqlBulkLoaderConflictOption { /// /// This is the default and indicates normal operation. In the event of a LOCAL load, this /// is the same as ignore. When the data file is on the server, then a key conflict will /// cause an error to be thrown and the rest of the data file ignored. /// None, /// /// Replace column values when a key conflict occurs. /// Replace, /// /// Ignore any rows where the primary key conflicts. /// Ignore } } mysql-connector-net-6.4.3/Source/MySql.Data/CharSetMap.cs0000644000175000017500000002074111127003600023652 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Text; using MySql.Data.Common; using System.Collections.Generic; using System.Data; namespace MySql.Data.MySqlClient { /// /// Summary description for CharSetMap. /// internal class CharSetMap { private static Dictionary defaultCollations; private static Dictionary maxLengths; private static Dictionary mapping; private static object lockObject; // we use a static constructor here since we only want to init // the mapping once static CharSetMap() { lockObject = new Object(); InitializeMapping(); } public static CharacterSet GetCharacterSet(DBVersion version, string CharSetName) { CharacterSet cs = (CharacterSet) mapping[CharSetName]; if (cs == null) throw new MySqlException("Character set '" + CharSetName + "' is not supported"); return cs; } /// /// Returns the text encoding for a given MySQL character set name /// /// Version of the connection requesting the encoding /// Name of the character set to get the encoding for /// Encoding object for the given character set name public static Encoding GetEncoding(DBVersion version, string CharSetName) { try { CharacterSet cs = GetCharacterSet(version, CharSetName); return Encoding.GetEncoding(cs.name); } catch (NotSupportedException) { return Encoding.GetEncoding(0); } } /// /// /// private static void InitializeMapping() { LoadCharsetMap(); } private static void LoadCharsetMap() { mapping = new Dictionary(); mapping.Add("latin1", new CharacterSet("windows-1252", 1)); mapping.Add("big5", new CharacterSet("big5", 2)); mapping.Add("dec8", mapping["latin1"]); mapping.Add("cp850", new CharacterSet("ibm850", 1)); mapping.Add("hp8", mapping["latin1"]); mapping.Add("koi8r", new CharacterSet("koi8-u", 1)); mapping.Add("latin2", new CharacterSet("latin2", 1)); mapping.Add("swe7", mapping["latin1"]); mapping.Add("ujis", new CharacterSet("EUC-JP", 3)); mapping.Add("eucjpms", mapping["ujis"]); mapping.Add("sjis", new CharacterSet("sjis", 2)); mapping.Add("cp932", mapping["sjis"]); mapping.Add("hebrew", new CharacterSet("hebrew", 1)); mapping.Add("tis620", new CharacterSet("windows-874", 1)); mapping.Add("euckr", new CharacterSet("euc-kr", 2)); mapping.Add("euc_kr", mapping["euckr"]); mapping.Add("koi8u", new CharacterSet("koi8-u", 1)); mapping.Add("koi8_ru", mapping["koi8u"]); mapping.Add("gb2312", new CharacterSet("gb2312", 2)); mapping.Add("gbk", mapping["gb2312"]); mapping.Add("greek", new CharacterSet("greek", 1)); mapping.Add("cp1250", new CharacterSet("windows-1250", 1)); mapping.Add("win1250", mapping["cp1250"]); mapping.Add("latin5", new CharacterSet("latin5", 1)); mapping.Add("armscii8", mapping["latin1"]); mapping.Add("utf8", new CharacterSet("utf-8", 3)); mapping.Add("ucs2", new CharacterSet("UTF-16BE", 2)); mapping.Add("cp866", new CharacterSet("cp866", 1)); mapping.Add("keybcs2", mapping["latin1"]); mapping.Add("macce", new CharacterSet("x-mac-ce", 1)); mapping.Add("macroman", new CharacterSet("x-mac-romanian", 1)); mapping.Add("cp852", new CharacterSet("ibm852", 2)); mapping.Add("latin7", new CharacterSet("iso-8859-7", 1)); mapping.Add("cp1251", new CharacterSet("windows-1251", 1)); mapping.Add("win1251ukr", mapping["cp1251"]); mapping.Add("cp1251csas", mapping["cp1251"]); mapping.Add("cp1251cias", mapping["cp1251"]); mapping.Add("win1251", mapping["cp1251"]); mapping.Add("cp1256", new CharacterSet("cp1256", 1)); mapping.Add("cp1257", new CharacterSet("windows-1257", 1)); mapping.Add("ascii", new CharacterSet("us-ascii", 1)); mapping.Add("usa7", mapping["ascii"]); mapping.Add("binary", mapping["ascii"]); mapping.Add("latin3", new CharacterSet("latin3", 1)); mapping.Add("latin4", new CharacterSet("latin4", 1)); mapping.Add("latin1_de", new CharacterSet("iso-8859-1", 1)); mapping.Add("german1", new CharacterSet("iso-8859-1", 1)); mapping.Add("danish", new CharacterSet("iso-8859-1", 1)); mapping.Add("czech", new CharacterSet("iso-8859-2", 1)); mapping.Add("hungarian", new CharacterSet("iso-8859-2", 1)); mapping.Add("croat", new CharacterSet("iso-8859-2", 1)); mapping.Add("latvian", new CharacterSet("iso-8859-13", 1)); mapping.Add("latvian1", new CharacterSet("iso-8859-13", 1)); mapping.Add("estonia", new CharacterSet("iso-8859-13", 1)); mapping.Add("dos", new CharacterSet("ibm437", 1)); mapping.Add("utf8mb4", new CharacterSet("utf-8", 4)); } internal static void InitCollections(MySqlConnection connection) { defaultCollations = new Dictionary(); maxLengths = new Dictionary(); MySqlCommand cmd = new MySqlCommand("SHOW CHARSET", connection); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { defaultCollations.Add(reader.GetString(0), reader.GetString(2)); maxLengths.Add(reader.GetString(0), Convert.ToInt32(reader.GetValue(3))); } } } internal static string GetDefaultCollation(string charset, MySqlConnection connection) { lock (lockObject) { if (defaultCollations == null) InitCollections(connection); } if (!defaultCollations.ContainsKey(charset)) return null; return defaultCollations[charset]; } internal static int GetMaxLength(string charset, MySqlConnection connection) { lock (lockObject) { if (maxLengths == null) InitCollections(connection); } if (!maxLengths.ContainsKey(charset)) return 1; return maxLengths[charset]; } } internal class CharacterSet { public string name; public int byteCount; public CharacterSet(string name, int byteCount) { this.name = name; this.byteCount = byteCount; } } }mysql-connector-net-6.4.3/Source/MySql.Data/CompressedStream.cs0000644000175000017500000002362511127003600025147 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.IO; using zlib; using MySql.Data.MySqlClient.Properties; using MySql.Data.Common; namespace MySql.Data.MySqlClient { /// /// Summary description for CompressedStream. /// internal class CompressedStream : Stream { // writing fields private Stream baseStream; private MemoryStream cache; // reading fields private byte[] localByte; private byte[] inBuffer; private byte[] lengthBytes; private WeakReference inBufferRef; private int inPos; private int maxInPos; private ZInputStream zInStream; public CompressedStream(Stream baseStream) { this.baseStream = baseStream; localByte = new byte[1]; lengthBytes = new byte[7]; cache = new MemoryStream(); inBufferRef = new WeakReference(inBuffer, false); } #region Properties public override bool CanRead { get { return baseStream.CanRead; } } public override bool CanWrite { get { return baseStream.CanWrite; } } public override bool CanSeek { get { return baseStream.CanSeek; } } public override long Length { get { return baseStream.Length; } } public override long Position { get { return baseStream.Position; } set { baseStream.Position = value; } } #endregion public override void Close() { baseStream.Close(); base.Close(); } public override void SetLength(long value) { throw new NotSupportedException(Resources.CSNoSetLength); } public override int ReadByte() { try { Read(localByte, 0, 1); return localByte[0]; } catch (EndOfStreamException) { return -1; } } public override bool CanTimeout { get { return baseStream.CanTimeout; } } public override int ReadTimeout { get { return baseStream.ReadTimeout; } set { baseStream.ReadTimeout = value; } } public override int WriteTimeout { get { return baseStream.WriteTimeout; } set { baseStream.WriteTimeout = value; } } public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException("buffer", Resources.BufferCannotBeNull); if (offset < 0 || offset >= buffer.Length) throw new ArgumentOutOfRangeException("offset", Resources.OffsetMustBeValid); if ((offset + count) > buffer.Length) throw new ArgumentException(Resources.BufferNotLargeEnough, "buffer"); if (inPos == maxInPos) PrepareNextPacket(); int countToRead = Math.Min(count, maxInPos - inPos); int countRead; if (zInStream != null) countRead = zInStream.read(buffer, offset, countToRead); else countRead = baseStream.Read(buffer, offset, countToRead); inPos += countRead; // release the weak reference if (inPos == maxInPos) { zInStream = null; if (!Platform.IsMono()) { inBufferRef = new WeakReference(inBuffer, false); inBuffer = null; } } return countRead; } private void PrepareNextPacket() { MySqlStream.ReadFully(baseStream, lengthBytes, 0, 7); int compressedLength = lengthBytes[0] + (lengthBytes[1] << 8) + (lengthBytes[2] << 16); // lengthBytes[3] is seq int unCompressedLength = lengthBytes[4] + (lengthBytes[5] << 8) + (lengthBytes[6] << 16); if (unCompressedLength == 0) { unCompressedLength = compressedLength; zInStream = null; } else { ReadNextPacket(compressedLength); MemoryStream ms = new MemoryStream(inBuffer); zInStream = new ZInputStream(ms); zInStream.maxInput = compressedLength; } inPos = 0; maxInPos = unCompressedLength; } private void ReadNextPacket(int len) { if (!Platform.IsMono()) inBuffer = inBufferRef.Target as byte[]; if (inBuffer == null || inBuffer.Length < len) inBuffer = new byte[len]; MySqlStream.ReadFully(baseStream, inBuffer, 0, len); } private MemoryStream CompressCache() { // small arrays almost never yeild a benefit from compressing if (cache.Length < 50) return null; byte[] cacheBytes = cache.GetBuffer(); MemoryStream compressedBuffer = new MemoryStream(); ZOutputStream zos = new ZOutputStream(compressedBuffer, zlibConst.Z_DEFAULT_COMPRESSION); zos.Write(cacheBytes, 0, (int) cache.Length); zos.finish(); // if the compression hasn't helped, then just return null if (compressedBuffer.Length >= cache.Length) return null; return compressedBuffer; } private void CompressAndSendCache() { long compressedLength, uncompressedLength; // we need to save the sequence byte that is written byte[] cacheBuffer = cache.GetBuffer(); byte seq = cacheBuffer[3]; cacheBuffer[3] = 0; // first we compress our current cache MemoryStream compressedBuffer = CompressCache(); // now we set our compressed and uncompressed lengths // based on if our compression is going to help or not MemoryStream memStream; if (compressedBuffer == null) { compressedLength = cache.Length; uncompressedLength = 0; memStream = cache; } else { compressedLength = compressedBuffer.Length; uncompressedLength = cache.Length; memStream = compressedBuffer; } // Make space for length prefix (7 bytes) at the start of output long dataLength = memStream.Length; int bytesToWrite = (int)dataLength + 7; memStream.SetLength(bytesToWrite); byte[] buffer = memStream.GetBuffer(); Array.Copy(buffer, 0, buffer, 7, (int)dataLength); // Write length prefix buffer[0] = (byte) (compressedLength & 0xff); buffer[1] = (byte) ((compressedLength >> 8) & 0xff); buffer[2] = (byte) ((compressedLength >> 16) & 0xff); buffer[3] = seq; buffer[4] = (byte) (uncompressedLength & 0xff); buffer[5] = (byte) ((uncompressedLength >> 8) & 0xff); buffer[6] = (byte) ((uncompressedLength >> 16) & 0xff); baseStream.Write(buffer, 0, bytesToWrite); baseStream.Flush(); cache.SetLength(0); } public override void Flush() { if (!InputDone()) return; CompressAndSendCache(); } private bool InputDone() { // if we have not done so yet, see if we can calculate how many bytes we are expecting if (cache.Length < 4) return false; byte[] buf = cache.GetBuffer(); int expectedLen = buf[0] + (buf[1] << 8) + (buf[2] << 16); if (cache.Length < (expectedLen + 4)) return false; return true; } public override void WriteByte(byte value) { cache.WriteByte(value); } public override void Write(byte[] buffer, int offset, int count) { cache.Write(buffer, offset, count); } public override long Seek(long offset, SeekOrigin origin) { return baseStream.Seek(offset, origin); } } } mysql-connector-net-6.4.3/Source/MySql.Data/dataadapter.cs0000644000175000017500000003337611127003600024145 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Data.Common; using System.ComponentModel; using System.Collections.Generic; namespace MySql.Data.MySqlClient { /// #if !CF [System.Drawing.ToolboxBitmap( typeof(MySqlDataAdapter), "MySqlClient.resources.dataadapter.bmp")] [System.ComponentModel.DesignerCategory("Code")] [Designer("MySql.Data.MySqlClient.Design.MySqlDataAdapterDesigner,MySqlClient.Design")] #endif public sealed class MySqlDataAdapter : DbDataAdapter, IDbDataAdapter, IDataAdapter, ICloneable { private bool loadingDefaults; private int updateBatchSize; List commandBatch; /// /// Occurs during Update before a command is executed against the data source. The attempt to update is made, so the event fires. /// public event MySqlRowUpdatingEventHandler RowUpdating; /// /// Occurs during Update after a command is executed against the data source. The attempt to update is made, so the event fires. /// public event MySqlRowUpdatedEventHandler RowUpdated; /// public MySqlDataAdapter() { loadingDefaults = true; updateBatchSize = 1; } /// public MySqlDataAdapter(MySqlCommand selectCommand) : this() { SelectCommand = selectCommand; } /// public MySqlDataAdapter(string selectCommandText, MySqlConnection connection) : this() { SelectCommand = new MySqlCommand(selectCommandText, connection); } /// public MySqlDataAdapter(string selectCommandText, string selectConnString) : this() { SelectCommand = new MySqlCommand(selectCommandText, new MySqlConnection(selectConnString) ); } #region Properties /// #if !CF [Description("Used during Update for deleted rows in Dataset.")] #endif public new MySqlCommand DeleteCommand { get { return (MySqlCommand)base.DeleteCommand; } set { base.DeleteCommand = value; } } /// #if !CF [Description("Used during Update for new rows in Dataset.")] #endif public new MySqlCommand InsertCommand { get { return (MySqlCommand)base.InsertCommand; } set { base.InsertCommand = value; } } /// #if !CF [Description("Used during Fill/FillSchema")] [Category("Fill")] #endif public new MySqlCommand SelectCommand { get { return (MySqlCommand)base.SelectCommand; } set { base.SelectCommand = value; } } /// #if !CF [Description("Used during Update for modified rows in Dataset.")] #endif public new MySqlCommand UpdateCommand { get { return (MySqlCommand)base.UpdateCommand; } set { base.UpdateCommand = value; } } internal bool LoadDefaults { get { return loadingDefaults; } set { loadingDefaults = value; } } #endregion /// /// Open connection if it was closed. /// Necessary to workaround "connection must be open and valid" error /// with batched updates. /// /// Row state /// list of opened connections /// If connection is opened by this function, the list is updated /// /// true if connection was opened private void OpenConnectionIfClosed(DataRowState state, List openedConnections) { MySqlCommand cmd = null; switch (state) { case DataRowState.Added: cmd = InsertCommand; break; case DataRowState.Deleted: cmd = DeleteCommand; break; case DataRowState.Modified: cmd = UpdateCommand; break; default: return; } if (cmd != null && cmd.Connection != null && cmd.Connection.connectionState == ConnectionState.Closed) { cmd.Connection.Open(); openedConnections.Add(cmd.Connection); } } protected override int Update(DataRow[] dataRows, DataTableMapping tableMapping) { List connectionsOpened = new List(); try { // Open connections for insert/update/update commands, if // connections are closed. foreach(DataRow row in dataRows) { OpenConnectionIfClosed(row.RowState, connectionsOpened); } int ret = base.Update(dataRows, tableMapping); return ret; } finally { foreach(MySqlConnection c in connectionsOpened) c.Close(); } } #region Batching Support public override int UpdateBatchSize { get { return updateBatchSize; } set { updateBatchSize = value; } } protected override void InitializeBatching() { commandBatch = new List(); } protected override int AddToBatch(IDbCommand command) { // the first time each command is asked to be batched, we ask // that command to prepare its batchable command text. We only want // to do this one time for each command MySqlCommand commandToBatch = (MySqlCommand)command; if (commandToBatch.BatchableCommandText == null) commandToBatch.GetCommandTextForBatching(); IDbCommand cloneCommand = (IDbCommand)((ICloneable)command).Clone(); commandBatch.Add(cloneCommand); return commandBatch.Count - 1; } protected override int ExecuteBatch() { int recordsAffected = 0; int index = 0; while (index < commandBatch.Count) { MySqlCommand cmd = (MySqlCommand)commandBatch[index++]; for (int index2 = index; index2 < commandBatch.Count; index2++,index++) { MySqlCommand cmd2 = (MySqlCommand)commandBatch[index2]; if (cmd2.BatchableCommandText == null || cmd2.CommandText != cmd.CommandText) break; cmd.AddToBatch(cmd2); } recordsAffected += cmd.ExecuteNonQuery(); } return recordsAffected; } protected override void ClearBatch() { if (commandBatch.Count > 0) { MySqlCommand cmd = (MySqlCommand)commandBatch[0]; if (cmd.Batch != null) cmd.Batch.Clear(); } commandBatch.Clear(); } protected override void TerminateBatching() { ClearBatch(); commandBatch = null; } protected override IDataParameter GetBatchedParameter(int commandIdentifier, int parameterIndex) { return (IDataParameter)commandBatch[commandIdentifier].Parameters[parameterIndex]; } #endregion /// /// Overridden. See . /// /// /// /// /// /// override protected RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) { return new MySqlRowUpdatedEventArgs(dataRow, command, statementType, tableMapping); } /// /// Overridden. See . /// /// /// /// /// /// override protected RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) { return new MySqlRowUpdatingEventArgs(dataRow, command, statementType, tableMapping); } /// /// Overridden. Raises the RowUpdating event. /// /// A MySqlRowUpdatingEventArgs that contains the event data. override protected void OnRowUpdating(RowUpdatingEventArgs value) { if (RowUpdating != null) RowUpdating(this, (value as MySqlRowUpdatingEventArgs)); } /// /// Overridden. Raises the RowUpdated event. /// /// A MySqlRowUpdatedEventArgs that contains the event data. override protected void OnRowUpdated(RowUpdatedEventArgs value) { if (RowUpdated != null) RowUpdated(this, (value as MySqlRowUpdatedEventArgs)); } } /// /// Represents the method that will handle the event of a . /// public delegate void MySqlRowUpdatingEventHandler(object sender, MySqlRowUpdatingEventArgs e); /// /// Represents the method that will handle the event of a . /// public delegate void MySqlRowUpdatedEventHandler(object sender, MySqlRowUpdatedEventArgs e); /// /// Provides data for the RowUpdating event. This class cannot be inherited. /// public sealed class MySqlRowUpdatingEventArgs : RowUpdatingEventArgs { /// /// Initializes a new instance of the MySqlRowUpdatingEventArgs class. /// /// The to /// . /// The to execute during . /// One of the values that specifies the type of query executed. /// The sent through an . public MySqlRowUpdatingEventArgs(DataRow row, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) : base(row, command, statementType, tableMapping) { } /// /// Gets or sets the MySqlCommand to execute when performing the Update. /// new public MySqlCommand Command { get { return (MySqlCommand)base.Command; } set { base.Command = value; } } } /// /// Provides data for the RowUpdated event. This class cannot be inherited. /// public sealed class MySqlRowUpdatedEventArgs : RowUpdatedEventArgs { /// /// Initializes a new instance of the MySqlRowUpdatedEventArgs class. /// /// The sent through an . /// The executed when is called. /// One of the values that specifies the type of query executed. /// The sent through an . public MySqlRowUpdatedEventArgs(DataRow row, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) : base(row, command, statementType, tableMapping) { } /// /// Gets or sets the MySqlCommand executed when Update is called. /// new public MySqlCommand Command { get { return (MySqlCommand)base.Command; } } } } mysql-connector-net-6.4.3/Source/MySql.Data/MySqlError.cs0000644000175000017500000025456311127003600023755 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA namespace MySql.Data.MySqlClient { /// /// Collection of error codes that can be returned by the server /// public class MySqlError { private string level; private int code; private string message; /// /// /// /// public MySqlError(string level, int code, string message) { this.level = level; this.code = code; this.message = message; } /// /// Error level /// public string Level { get { return level; } } /// /// Error code /// public int Code { get { return code; } } /// /// Error message /// public string Message { get { return message; } } }; /// /// Provides a reference to error codes returned by MySQL. /// public enum MySqlErrorCode { None = 0, /// ///ER_HASHCHK HashCheck = 1000, /// ///ER_NISAMCHK ISAMCheck = 1001, /// ///ER_NO No = 1002, /// ///ER_YES Yes = 1003, ///The file couldn't be created. ///ER_CANT_CREATE_FILE CannotCreateFile = 1004, ///The table couldn't be created. ///ER_CANT_CREATE_TABLE CannotCreateTable = 1005, ///The database couldn't be created. ///ER_CANT_CREATE_DB CannotCreateDatabase = 1006, ///The database couldn't be created, it already exists. ///ER_DB_CREATE_EXISTS DatabaseCreateExists = 1007, ///The database couldn't be dropped, it doesn't exist. ///ER_DB_DROP_EXISTS DatabaseDropExists = 1008, ///The database couldn't be dropped, the file can't be deleted. ///ER_DB_DROP_DELETE DatabaseDropDelete = 1009, ///The database couldn't be dropped, the directory can't be deleted. ///ER_DB_DROP_RMDIR DatabaseDropRemoveDir = 1010, ///The file couldn't be deleted. ///ER_CANT_DELETE_FILE CannotDeleteFile = 1011, ///The record couldn't be read from the system table. ///ER_CANT_FIND_SYSTEM_REC CannotFindSystemRecord = 1012, ///The status couldn't be retrieved. ///ER_CANT_GET_STAT CannotGetStatus = 1013, ///The working directory couldn't be retrieved. ///ER_CANT_GET_WD CannotGetWorkingDirectory = 1014, ///The file couldn't be locked. ///ER_CANT_LOCK CannotLock = 1015, ///The file couldn't be opened. ///ER_CANT_OPEN_FILE CannotOpenFile = 1016, ///The file couldn't be found. ///ER_FILE_NOT_FOUND FileNotFound = 1017, ///The directory couldn't be read. ///ER_CANT_READ_DIR CannotReadDirectory = 1018, ///The working directory couldn't be entered. ///ER_CANT_SET_WD CannotSetWorkingDirectory = 1019, ///The record changed since it was last read. ///ER_CHECKREAD CheckRead = 1020, ///The disk is full. ///ER_DISK_FULL DiskFull = 1021, /// /// There is already a key with the given values. /// DuplicateKey = 1022, ///An error occurred when closing the file. ///ER_ERROR_ON_CLOSE ErrorOnClose = 1023, ///An error occurred when reading from the file. ///ER_ERROR_ON_READ ErrorOnRead = 1024, ///An error occurred when renaming then file. ///ER_ERROR_ON_RENAME ErrorOnRename = 1025, ///An error occurred when writing to the file. ///ER_ERROR_ON_WRITE ErrorOnWrite = 1026, ///The file is in use. ///ER_FILE_USED FileUsed = 1027, ///Sorting has been aborted. ///ER_FILSORT_ABORT FileSortAborted = 1028, ///The view doesn't exist. ///ER_FORM_NOT_FOUND FormNotFound = 1029, ///Got the specified error from the table storage engine. ///ER_GET_ERRNO GetErrorNumber = 1030, ///The table storage engine doesn't support the specified option. ///ER_ILLEGAL_HA IllegalHA = 1031, /// /// The specified key was not found. /// KeyNotFound = 1032, ///The file contains incorrect information. ///ER_NOT_FORM_FILE NotFormFile = 1033, ///The key file is incorrect for the table, it should be repaired. ///ER_NOT_KEYFILE NotKeyFile = 1034, ///The key file is old for the table, it should be repaired. ///ER_OLD_KEYFILE OldKeyFile = 1035, ///The table is read-only ///ER_OPEN_AS_READONLY OpenAsReadOnly = 1036, ///The server is out of memory, it should be restarted. ///ER_OUTOFMEMORY OutOfMemory = 1037, ///The server is out of sort-memory, the sort buffer size should be increased. ///ER_OUT_OF_SORTMEMORY OutOfSortMemory = 1038, ///An unexpected EOF was found when reading from the file. ///ER_UNEXPECTED_EOF UnexepectedEOF = 1039, ///Too many connections are open. ///ER_CON_COUNT_ERROR ConnectionCountError = 1040, ///The server is out of resources, check if MySql or some other process is using all available memory. ///ER_OUT_OF_RESOURCES OutOfResources = 1041, /// /// Given when the connection is unable to successfully connect to host. /// UnableToConnectToHost = 1042, ///The handshake was invalid. ///ER_HANDSHAKE_ERROR HandshakeError = 1043, ///Access was denied for the specified user using the specified database. ///ER_DBACCESS_DENIED_ERROR DatabaseAccessDenied = 1044, /// /// Normally returned when an incorrect password is given /// AccessDenied = 1045, ///No database has been selected. ///ER_NO_DB_ERROR NoDatabaseSelected = 1046, ///The command is unknown. ///ER_UNKNOWN_COM_ERROR UnknownCommand = 1047, ///The specified column cannot be NULL. ///ER_BAD_NULL_ERROR ColumnCannotBeNull = 1048, /// The specified database is not known. UnknownDatabase = 1049, ///The specified table already exists. ///ER_TABLE_EXISTS_ERROR TableExists = 1050, ///The specified table is unknown. ///ER_BAD_TABLE_ERROR BadTable = 1051, ///The specified column is ambiguous. ///ER_NON_UNIQ_ERROR NonUnique = 1052, ///The server is currently being shutdown. ///ER_SERVER_SHUTDOWN ServerShutdown = 1053, ///The specified columns is unknown. ///ER_BAD_FIELD_ERROR BadFieldError = 1054, ///The specified column isn't in GROUP BY. ///ER_WRONG_FIELD_WITH_GROUP WrongFieldWithGroup = 1055, ///The specified columns cannot be grouped on. ///ER_WRONG_GROUP_FIELD WrongGroupField = 1056, ///There are sum functions and columns in the same statement. ///ER_WRONG_SUM_SELECT WrongSumSelected = 1057, ///The column count doesn't match the value count. ///ER_WRONG_VALUE_COUNT WrongValueCount = 1058, ///The identifier name is too long. ///ER_TOO_LONG_IDENT TooLongIdentifier = 1059, ///The column name is duplicated. ///ER_DUP_FIELDNAME DuplicateFieldName = 1060, /// /// Duplicate Key Name /// DuplicateKeyName = 1061, /// /// Duplicate Key Entry /// DuplicateKeyEntry = 1062, ///The column specifier is incorrect. ///ER_WRONG_FIELD_SPEC WrongFieldSpecifier = 1063, ///An error occurred when parsing the statement. ///ER_PARSE_ERROR ParseError = 1064, ///The statement is empty. ///ER_EMPTY_QUERY EmptyQuery = 1065, ///The table alias isn't unique. ///ER_NONUNIQ_TABLE NonUniqueTable = 1066, ///The default value is invalid for the specified field. ///ER_INVALID_DEFAULT InvalidDefault = 1067, ///The table has multiple primary keys defined. ///ER_MULTIPLE_PRI_KEY MultiplePrimaryKey = 1068, ///Too many keys were defined for the table. ///ER_TOO_MANY_KEYS TooManyKeys = 1069, ///Too many parts to the keys were defined for the table. ///ER_TOO_MANY_KEY_PARTS TooManyKeysParts = 1070, ///The specified key is too long ///ER_TOO_LONG_KEY TooLongKey = 1071, ///The specified key column doesn't exist in the table. ///ER_KEY_COLUMN_DOES_NOT_EXITS KeyColumnDoesNotExist = 1072, ///The BLOB column was used as a key, this can't be done. ///ER_BLOB_USED_AS_KEY BlobUsedAsKey = 1073, ///The column length is too big for the specified column type. ///ER_TOO_BIG_FIELDLENGTH TooBigFieldLength = 1074, ///There can only be one auto-column, and it must be defined as a PK. ///ER_WRONG_AUTO_KEY WrongAutoKey = 1075, ///The server is ready to accept connections. ///ER_READY Ready = 1076, /// ///ER_NORMAL_SHUTDOWN NormalShutdown = 1077, ///The server received the specified signal and is aborting. ///ER_GOT_SIGNAL GotSignal = 1078, ///The server shutdown is complete. ///ER_SHUTDOWN_COMPLETE ShutdownComplete = 1079, ///The server is forcing close of the specified thread. ///ER_FORCING_CLOSE ForcingClose = 1080, ///An error occurred when creating the IP socket. ///ER_IPSOCK_ERROR IPSocketError = 1081, ///The table has no index like the one used in CREATE INDEX. ///ER_NO_SUCH_INDEX NoSuchIndex = 1082, ///The field separator argument is not what is expected, check the manual. ///ER_WRONG_FIELD_TERMINATORS WrongFieldTerminators = 1083, ///The BLOB columns must terminated, fixed row lengths cannot be used. ///ER_BLOBS_AND_NO_TERMINATED BlobsAndNoTerminated = 1084, ///The text file cannot be read. ///ER_TEXTFILE_NOT_READABLE TextFileNotReadable = 1085, ///The specified file already exists. ///ER_FILE_EXISTS_ERROR FileExists = 1086, ///Information returned by the LOAD statement. ///ER_LOAD_INFO LoadInfo = 1087, ///Information returned by an UPDATE statement. ///ER_ALTER_INFO AlterInfo = 1088, ///The prefix key is incorrect. ///ER_WRONG_SUB_KEY WrongSubKey = 1089, ///All columns cannot be removed from a table, use DROP TABLE instead. ///ER_CANT_REMOVE_ALL_FIELDS CannotRemoveAllFields = 1090, ///Cannot DROP, check that the column or key exists. ///ER_CANT_DROP_FIELD_OR_KEY CannotDropFieldOrKey = 1091, ///Information returned by an INSERT statement. ///ER_INSERT_INFO InsertInfo = 1092, ///The target table cannot be specified for update in FROM clause. ///ER_UPDATE_TABLE_USED UpdateTableUsed = 1093, ///The specified thread ID is unknown. ///ER_NO_SUCH_THREAD NoSuchThread = 1094, ///The thread cannot be killed, the current user is not the owner. ///ER_KILL_DENIED_ERROR KillDenied = 1095, ///No tables used in the statement. ///ER_NO_TABLES_USED NoTablesUsed = 1096, ///Too many string have been used for the specified column and SET. ///ER_TOO_BIG_SET TooBigSet = 1097, ///A unique filename couldn't be generated. ///ER_NO_UNIQUE_LOGFILE NoUniqueLogFile = 1098, ///The specified table was locked with a READ lock, and can't be updated. ///ER_TABLE_NOT_LOCKED_FOR_WRITE TableNotLockedForWrite = 1099, ///The specified table was not locked with LOCK TABLES. ///ER_TABLE_NOT_LOCKED TableNotLocked = 1100, ///BLOB and Text columns cannot have a default value. ///ER_BLOB_CANT_HAVE_DEFAULT BlobCannotHaveDefault = 1101, ///The specified database name is incorrect. ///ER_WRONG_DB_NAME WrongDatabaseName = 1102, ///The specified table name is incorrect. ///ER_WRONG_TABLE_NAME WrongTableName = 1103, ///The SELECT command would examine more than MAX_JOIN_SIZE rows, check the WHERE clause and use SET SQL_BIG_SELECTS=1 or SET SQL_MAX_JOIN_SIZE=# if the SELECT is ok. ///ER_TOO_BIG_SELECT TooBigSelect = 1104, ///An unknown error occurred. ///ER_UNKNOWN_ERROR UnknownError = 1105, ///The specified procedure is unknown. ///ER_UNKNOWN_PROCEDURE UnknownProcedure = 1106, ///The number of parameters provided for the specified procedure is incorrect. ///ER_WRONG_PARAMCOUNT_TO_PROCEDURE WrongParameterCountToProcedure = 1107, ///The parameters provided for the specified procedure are incorrect. ///ER_WRONG_PARAMETERS_TO_PROCEDURE WrongParametersToProcedure = 1108, ///The specified table is unknown. ///ER_UNKNOWN_TABLE UnknownTable = 1109, ///The specified column has been specified twice. ///ER_FIELD_SPECIFIED_TWICE FieldSpecifiedTwice = 1110, ///The group function has been incorrectly used. ///ER_INVALID_GROUP_FUNC_USE InvalidGroupFunctionUse = 1111, ///The specified table uses an extension that doesn't exist in this MySQL version. ///ER_UNSUPPORTED_EXTENSION UnsupportedExtenstion = 1112, ///The table must have at least one column. ///ER_TABLE_MUST_HAVE_COLUMNS TableMustHaveColumns = 1113, ///The specified table is full. ///ER_RECORD_FILE_FULL RecordFileFull = 1114, ///The specified character set is unknown. ///ER_UNKNOWN_CHARACTER_SET UnknownCharacterSet = 1115, ///Too many tables, MySQL can only use the specified number of tables in a JOIN. ///ER_TOO_MANY_TABLES TooManyTables = 1116, ///Too many columns ///ER_TOO_MANY_FIELDS TooManyFields = 1117, ///The row size is too large, the maximum row size for the used tables (not counting BLOBS) is specified, change some columns or BLOBS. ///ER_TOO_BIG_ROWSIZE TooBigRowSize = 1118, ///A thread stack overrun occurred. Stack statistics are specified. ///ER_STACK_OVERRUN StackOverrun = 1119, ///A cross dependency was found in the OUTER JOIN, examine the ON conditions. ///ER_WRONG_OUTER_JOIN WrongOuterJoin = 1120, ///The table handler doesn't support NULL in the given index, change specified column to be NOT NULL or use another handler. ///ER_NULL_COLUMN_IN_INDEX NullColumnInIndex = 1121, ///The specified user defined function cannot be loaded. ///ER_CANT_FIND_UDF CannotFindUDF = 1122, ///The specified user defined function cannot be initialised. ///ER_CANT_INITIALIZE_UDF CannotInitializeUDF = 1123, ///No paths are allowed for the shared library. ///ER_UDF_NO_PATHS UDFNoPaths = 1124, ///The specified user defined function already exists. ///ER_UDF_EXISTS UDFExists = 1125, ///The specified shared library cannot be opened. ///ER_CANT_OPEN_LIBRARY CannotOpenLibrary = 1126, ///The specified symbol cannot be found in the library. ///ER_CANT_FIND_DL_ENTRY CannotFindDLEntry = 1127, ///The specified function is not defined. ///ER_FUNCTION_NOT_DEFINED FunctionNotDefined = 1128, ///The specified host is blocked because of too many connection errors, unblock with 'mysqladmin flush-hosts'. ///ER_HOST_IS_BLOCKED HostIsBlocked = 1129, /// /// The given host is not allowed to connect /// HostNotPrivileged = 1130, /// /// The anonymous user is not allowed to connect /// AnonymousUser = 1131, /// /// The given password is not allowed /// PasswordNotAllowed = 1132, /// /// The given password does not match /// PasswordNoMatch = 1133, ///Information returned by an UPDATE statement. ///ER_UPDATE_INFO UpdateInfo = 1134, ///A new thread couldn't be created. ///ER_CANT_CREATE_THREAD CannotCreateThread = 1135, ///The column count doesn't match the value count. ///ER_WRONG_VALUE_COUNT_ON_ROW WrongValueCountOnRow = 1136, ///The specified table can't be re-opened. ///ER_CANT_REOPEN_TABLE CannotReopenTable = 1137, ///The NULL value has been used incorrectly. ///ER_INVALID_USE_OF_NULL InvalidUseOfNull = 1138, ///The regular expression contains an error. ///ER_REGEXP_ERROR RegExpError = 1139, ///GROUP columns (MIN(), MAX(), COUNT(), ...) cannot be mixes with no GROUP columns if there is not GROUP BY clause. ///ER_MIX_OF_GROUP_FUNC_AND_FIELDS MixOfGroupFunctionAndFields = 1140, /// ///ER_NONEXISTING_GRANT NonExistingGrant = 1141, /// ///ER_TABLEACCESS_DENIED_ERROR TableAccessDenied = 1142, /// ///ER_COLUMNACCESS_DENIED_ERROR ColumnAccessDenied = 1143, /// ///ER_ILLEGAL_GRANT_FOR_TABLE IllegalGrantForTable = 1144, /// ///ER_GRANT_WRONG_HOST_OR_USER GrantWrongHostOrUser = 1145, /// ///ER_NO_SUCH_TABLE NoSuchTable = 1146, /// ///ER_NONEXISTING_TABLE_GRANT NonExistingTableGrant = 1147, /// ///ER_NOT_ALLOWED_COMMAND NotAllowedCommand = 1148, /// ///ER_SYNTAX_ERROR SyntaxError = 1149, /// ///ER_DELAYED_CANT_CHANGE_LOCK DelayedCannotChangeLock = 1150, /// ///ER_TOO_MANY_DELAYED_THREADS TooManyDelayedThreads = 1151, /// ///ER_ABORTING_CONNECTION AbortingConnection = 1152, /// /// An attempt was made to send or receive a packet larger than /// max_allowed_packet_size /// PacketTooLarge = 1153, /// ///ER_NET_READ_ERROR_FROM_PIPE NetReadErrorFromPipe = 1154, /// ///ER_NET_FCNTL_ERROR NetFCntlError = 1155, /// ///ER_NET_PACKETS_OUT_OF_ORDER NetPacketsOutOfOrder = 1156, /// ///ER_NET_UNCOMPRESS_ERROR NetUncompressError = 1157, /// ///ER_NET_READ_ERROR NetReadError = 1158, /// ///ER_NET_READ_INTERRUPTED NetReadInterrupted = 1159, /// ///ER_NET_ERROR_ON_WRITE NetErrorOnWrite = 1160, /// ///ER_NET_WRITE_INTERRUPTED NetWriteInterrupted = 1161, /// ///ER_TOO_LONG_STRING TooLongString = 1162, /// ///ER_TABLE_CANT_HANDLE_BLOB TableCannotHandleBlob = 1163, /// ///ER_TABLE_CANT_HANDLE_AUTO_INCREMENT TableCannotHandleAutoIncrement = 1164, /// ///ER_DELAYED_INSERT_TABLE_LOCKED DelayedInsertTableLocked = 1165, /// ///ER_WRONG_COLUMN_NAME WrongColumnName = 1166, /// ///ER_WRONG_KEY_COLUMN WrongKeyColumn = 1167, /// ///ER_WRONG_MRG_TABLE WrongMergeTable = 1168, /// ///ER_DUP_UNIQUE DuplicateUnique = 1169, /// ///ER_BLOB_KEY_WITHOUT_LENGTH BlobKeyWithoutLength = 1170, /// ///ER_PRIMARY_CANT_HAVE_NULL PrimaryCannotHaveNull = 1171, /// ///ER_TOO_MANY_ROWS TooManyRows = 1172, /// ///ER_REQUIRES_PRIMARY_KEY RequiresPrimaryKey = 1173, /// ///ER_NO_RAID_COMPILED NoRAIDCompiled = 1174, /// ///ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE UpdateWithoutKeysInSafeMode = 1175, /// ///ER_KEY_DOES_NOT_EXITS KeyDoesNotExist = 1176, /// ///ER_CHECK_NO_SUCH_TABLE CheckNoSuchTable = 1177, /// ///ER_CHECK_NOT_IMPLEMENTED CheckNotImplemented = 1178, /// ///ER_CANT_DO_THIS_DURING_AN_TRANSACTION CannotDoThisDuringATransaction = 1179, /// ///ER_ERROR_DURING_COMMIT ErrorDuringCommit = 1180, /// ///ER_ERROR_DURING_ROLLBACK ErrorDuringRollback = 1181, /// ///ER_ERROR_DURING_FLUSH_LOGS ErrorDuringFlushLogs = 1182, /// ///ER_ERROR_DURING_CHECKPOINT ErrorDuringCheckpoint = 1183, /// ///ER_NEW_ABORTING_CONNECTION NewAbortingConnection = 1184, /// ///ER_DUMP_NOT_IMPLEMENTED DumpNotImplemented = 1185, /// ///ER_FLUSH_MASTER_BINLOG_CLOSED FlushMasterBinLogClosed = 1186, /// ///ER_INDEX_REBUILD IndexRebuild = 1187, /// ///ER_MASTER MasterError = 1188, /// ///ER_MASTER_NET_READ MasterNetRead = 1189, /// ///ER_MASTER_NET_WRITE MasterNetWrite = 1190, /// ///ER_FT_MATCHING_KEY_NOT_FOUND FullTextMatchingKeyNotFound = 1191, /// ///ER_LOCK_OR_ACTIVE_TRANSACTION LockOrActiveTransaction = 1192, /// ///ER_UNKNOWN_SYSTEM_VARIABLE UnknownSystemVariable = 1193, /// ///ER_CRASHED_ON_USAGE CrashedOnUsage = 1194, /// ///ER_CRASHED_ON_REPAIR CrashedOnRepair = 1195, /// ///ER_WARNING_NOT_COMPLETE_ROLLBACK WarningNotCompleteRollback = 1196, /// ///ER_TRANS_CACHE_FULL TransactionCacheFull = 1197, /// ///ER_SLAVE_MUST_STOP SlaveMustStop = 1198, /// ///ER_SLAVE_NOT_RUNNING SlaveNotRunning = 1199, /// ///ER_BAD_SLAVE BadSlave = 1200, /// ///ER_MASTER_INFO MasterInfo = 1201, /// ///ER_SLAVE_THREAD SlaveThread = 1202, /// ///ER_TOO_MANY_USER_CONNECTIONS TooManyUserConnections = 1203, /// ///ER_SET_CONSTANTS_ONLY SetConstantsOnly = 1204, /// ///ER_LOCK_WAIT_TIMEOUT LockWaitTimeout = 1205, /// ///ER_LOCK_TABLE_FULL LockTableFull = 1206, /// ///ER_READ_ONLY_TRANSACTION ReadOnlyTransaction = 1207, /// ///ER_DROP_DB_WITH_READ_LOCK DropDatabaseWithReadLock = 1208, /// ///ER_CREATE_DB_WITH_READ_LOCK CreateDatabaseWithReadLock = 1209, /// ///ER_WRONG_ARGUMENTS WrongArguments = 1210, /// ///ER_NO_PERMISSION_TO_CREATE_USER NoPermissionToCreateUser = 1211, /// ///ER_UNION_TABLES_IN_DIFFERENT_DIR UnionTablesInDifferentDirectory = 1212, /// ///ER_LOCK_DEADLOCK LockDeadlock = 1213, /// ///ER_TABLE_CANT_HANDLE_FT TableCannotHandleFullText = 1214, /// ///ER_CANNOT_ADD_FOREIGN CannotAddForeignConstraint = 1215, /// ///ER_NO_REFERENCED_ROW NoReferencedRow = 1216, /// ///ER_ROW_IS_REFERENCED RowIsReferenced = 1217, /// ///ER_CONNECT_TO_MASTER ConnectToMaster = 1218, /// ///ER_QUERY_ON_MASTER QueryOnMaster = 1219, /// ///ER_ERROR_WHEN_EXECUTING_COMMAND ErrorWhenExecutingCommand = 1220, /// ///ER_WRONG_USAGE WrongUsage = 1221, /// ///ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT WrongNumberOfColumnsInSelect = 1222, /// ///ER_CANT_UPDATE_WITH_READLOCK CannotUpdateWithReadLock = 1223, /// ///ER_MIXING_NOT_ALLOWED MixingNotAllowed = 1224, /// ///ER_DUP_ARGUMENT DuplicateArgument = 1225, /// ///ER_USER_LIMIT_REACHED UserLimitReached = 1226, /// ///ER_SPECIFIC_ACCESS_DENIED_ERROR SpecifiedAccessDeniedError = 1227, /// ///ER_LOCAL_VARIABLE LocalVariableError = 1228, /// ///ER_GLOBAL_VARIABLE GlobalVariableError = 1229, /// ///ER_NO_DEFAULT NotDefaultError = 1230, /// ///ER_WRONG_VALUE_FOR_VAR WrongValueForVariable = 1231, /// ///ER_WRONG_TYPE_FOR_VAR WrongTypeForVariable = 1232, /// ///ER_VAR_CANT_BE_READ VariableCannotBeRead = 1233, /// ///ER_CANT_USE_OPTION_HERE CannotUseOptionHere = 1234, /// ///ER_NOT_SUPPORTED_YET NotSupportedYet = 1235, /// ///ER_MASTER_FATAL_ERROR_READING_BINLOG MasterFatalErrorReadingBinLog = 1236, /// ///ER_SLAVE_IGNORED_TABLE SlaveIgnoredTable = 1237, /// ///ER_INCORRECT_GLOBAL_LOCAL_VAR IncorrectGlobalLocalVariable = 1238, /// ///ER_WRONG_FK_DEF WrongForeignKeyDefinition = 1239, /// ///ER_KEY_REF_DO_NOT_MATCH_TABLE_REF KeyReferenceDoesNotMatchTableReference = 1240, /// ///ER_OPERAND_COLUMNS OpearnColumnsError = 1241, /// ///ER_SUBQUERY_NO_1_ROW SubQueryNoOneRow = 1242, /// ///ER_UNKNOWN_STMT_HANDLER UnknownStatementHandler = 1243, /// ///ER_CORRUPT_HELP_DB CorruptHelpDatabase = 1244, /// ///ER_CYCLIC_REFERENCE CyclicReference = 1245, /// ///ER_AUTO_CONVERT AutoConvert = 1246, /// ///ER_ILLEGAL_REFERENCE IllegalReference = 1247, /// ///ER_DERIVED_MUST_HAVE_ALIAS DerivedMustHaveAlias = 1248, /// ///ER_SELECT_REDUCED SelectReduced = 1249, /// ///ER_TABLENAME_NOT_ALLOWED_HERE TableNameNotAllowedHere = 1250, /// ///ER_NOT_SUPPORTED_AUTH_MODE NotSupportedAuthMode = 1251, /// ///ER_SPATIAL_CANT_HAVE_NULL SpatialCannotHaveNull = 1252, /// ///ER_COLLATION_CHARSET_MISMATCH CollationCharsetMismatch = 1253, /// ///ER_SLAVE_WAS_RUNNING SlaveWasRunning = 1254, /// ///ER_SLAVE_WAS_NOT_RUNNING SlaveWasNotRunning = 1255, /// ///ER_TOO_BIG_FOR_UNCOMPRESS TooBigForUncompress = 1256, /// ///ER_ZLIB_Z_MEM_ERROR ZipLibMemoryError = 1257, /// ///ER_ZLIB_Z_BUF_ERROR ZipLibBufferError = 1258, /// ///ER_ZLIB_Z_DATA_ERROR ZipLibDataError = 1259, /// ///ER_CUT_VALUE_GROUP_CONCAT CutValueGroupConcat = 1260, /// ///ER_WARN_TOO_FEW_RECORDS WarningTooFewRecords = 1261, /// ///ER_WARN_TOO_MANY_RECORDS WarningTooManyRecords = 1262, /// ///ER_WARN_NULL_TO_NOTNULL WarningNullToNotNull = 1263, /// ///ER_WARN_DATA_OUT_OF_RANGE WarningDataOutOfRange = 1264, /// ///WARN_DATA_TRUNCATED WaningDataTruncated = 1265, /// ///ER_WARN_USING_OTHER_HANDLER WaningUsingOtherHandler = 1266, /// ///ER_CANT_AGGREGATE_2COLLATIONS CannotAggregateTwoCollations = 1267, /// ///ER_DROP_USER DropUserError = 1268, /// ///ER_REVOKE_GRANTS RevokeGrantsError = 1269, /// ///ER_CANT_AGGREGATE_3COLLATIONS CannotAggregateThreeCollations = 1270, /// ///ER_CANT_AGGREGATE_NCOLLATIONS CannotAggregateNCollations = 1271, /// ///ER_VARIABLE_IS_NOT_STRUCT VariableIsNotStructure = 1272, /// ///ER_UNKNOWN_COLLATION UnknownCollation = 1273, /// ///ER_SLAVE_IGNORED_SSL_PARAMS SlaveIgnoreSSLParameters = 1274, /// ///ER_SERVER_IS_IN_SECURE_AUTH_MODE ServerIsInSecureAuthMode = 1275, /// ///ER_WARN_FIELD_RESOLVED WaningFieldResolved = 1276, /// ///ER_BAD_SLAVE_UNTIL_COND BadSlaveUntilCondition = 1277, /// ///ER_MISSING_SKIP_SLAVE MissingSkipSlave = 1278, /// ///ER_UNTIL_COND_IGNORED ErrorUntilConditionIgnored = 1279, /// ///ER_WRONG_NAME_FOR_INDEX WrongNameForIndex = 1280, /// ///ER_WRONG_NAME_FOR_CATALOG WrongNameForCatalog = 1281, /// ///ER_WARN_QC_RESIZE WarningQueryCacheResize = 1282, /// ///ER_BAD_FT_COLUMN BadFullTextColumn = 1283, /// ///ER_UNKNOWN_KEY_CACHE UnknownKeyCache = 1284, /// ///ER_WARN_HOSTNAME_WONT_WORK WarningHostnameWillNotWork = 1285, /// ///ER_UNKNOWN_STORAGE_ENGINE UnknownStorageEngine = 1286, /// ///ER_WARN_DEPRECATED_SYNTAX WaningDeprecatedSyntax = 1287, /// ///ER_NON_UPDATABLE_TABLE NonUpdateableTable = 1288, /// ///ER_FEATURE_DISABLED FeatureDisabled = 1289, /// ///ER_OPTION_PREVENTS_STATEMENT OptionPreventsStatement = 1290, /// ///ER_DUPLICATED_VALUE_IN_TYPE DuplicatedValueInType = 1291, /// ///ER_TRUNCATED_WRONG_VALUE TruncatedWrongValue = 1292, /// ///ER_TOO_MUCH_AUTO_TIMESTAMP_COLS TooMuchAutoTimestampColumns = 1293, /// ///ER_INVALID_ON_UPDATE InvalidOnUpdate = 1294, /// ///ER_UNSUPPORTED_PS UnsupportedPreparedStatement = 1295, /// ///ER_GET_ERRMSG GetErroMessage = 1296, /// ///ER_GET_TEMPORARY_ERRMSG GetTemporaryErrorMessage = 1297, /// ///ER_UNKNOWN_TIME_ZONE UnknownTimeZone = 1298, /// ///ER_WARN_INVALID_TIMESTAMP WarningInvalidTimestamp = 1299, /// ///ER_INVALID_CHARACTER_STRING InvalidCharacterString = 1300, /// ///ER_WARN_ALLOWED_PACKET_OVERFLOWED WarningAllowedPacketOverflowed = 1301, /// ///ER_CONFLICTING_DECLARATIONS ConflictingDeclarations = 1302, /// ///ER_SP_NO_RECURSIVE_CREATE StoredProcedureNoRecursiveCreate = 1303, /// ///ER_SP_ALREADY_EXISTS StoredProcedureAlreadyExists = 1304, /// ///ER_SP_DOES_NOT_EXIST StoredProcedureDoesNotExist = 1305, /// ///ER_SP_DROP_FAILED StoredProcedureDropFailed = 1306, /// ///ER_SP_STORE_FAILED StoredProcedureStoreFailed = 1307, /// ///ER_SP_LILABEL_MISMATCH StoredProcedureLiLabelMismatch = 1308, /// ///ER_SP_LABEL_REDEFINE StoredProcedureLabelRedefine = 1309, /// ///ER_SP_LABEL_MISMATCH StoredProcedureLabelMismatch = 1310, /// ///ER_SP_UNINIT_VAR StoredProcedureUninitializedVariable = 1311, /// ///ER_SP_BADSELECT StoredProcedureBadSelect = 1312, /// ///ER_SP_BADRETURN StoredProcedureBadReturn = 1313, /// ///ER_SP_BADSTATEMENT StoredProcedureBadStatement = 1314, /// ///ER_UPDATE_LOG_DEPRECATED_IGNORED UpdateLogDeprecatedIgnored = 1315, /// ///ER_UPDATE_LOG_DEPRECATED_TRANSLATED UpdateLogDeprecatedTranslated = 1316, /// ///ER_QUERY_INTERRUPTED QueryInterrupted = 1317, /// ///ER_SP_WRONG_NO_OF_ARGS StoredProcedureNumberOfArguments = 1318, /// ///ER_SP_COND_MISMATCH StoredProcedureConditionMismatch = 1319, /// ///ER_SP_NORETURN StoredProcedureNoReturn = 1320, /// ///ER_SP_NORETURNEND StoredProcedureNoReturnEnd = 1321, /// ///ER_SP_BAD_CURSOR_QUERY StoredProcedureBadCursorQuery = 1322, /// ///ER_SP_BAD_CURSOR_SELECT StoredProcedureBadCursorSelect = 1323, /// ///ER_SP_CURSOR_MISMATCH StoredProcedureCursorMismatch = 1324, /// ///ER_SP_CURSOR_ALREADY_OPEN StoredProcedureAlreadyOpen = 1325, /// ///ER_SP_CURSOR_NOT_OPEN StoredProcedureCursorNotOpen = 1326, /// ///ER_SP_UNDECLARED_VAR StoredProcedureUndeclaredVariabel = 1327, /// ///ER_SP_WRONG_NO_OF_FETCH_ARGS StoredProcedureWrongNumberOfFetchArguments = 1328, /// ///ER_SP_FETCH_NO_DATA StoredProcedureFetchNoData = 1329, /// ///ER_SP_DUP_PARAM StoredProcedureDuplicateParameter = 1330, /// ///ER_SP_DUP_VAR StoredProcedureDuplicateVariable = 1331, /// ///ER_SP_DUP_COND StoredProcedureDuplicateCondition = 1332, /// ///ER_SP_DUP_CURS StoredProcedureDuplicateCursor = 1333, /// ///ER_SP_CANT_ALTER StoredProcedureCannotAlter = 1334, /// ///ER_SP_SUBSELECT_NYI StoredProcedureSubSelectNYI = 1335, /// ///ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG StatementNotAllowedInStoredFunctionOrTrigger = 1336, /// ///ER_SP_VARCOND_AFTER_CURSHNDLR StoredProcedureVariableConditionAfterCursorHandler = 1337, /// ///ER_SP_CURSOR_AFTER_HANDLER StoredProcedureCursorAfterHandler = 1338, /// ///ER_SP_CASE_NOT_FOUND StoredProcedureCaseNotFound = 1339, /// ///ER_FPARSER_TOO_BIG_FILE FileParserTooBigFile = 1340, /// ///ER_FPARSER_BAD_HEADER FileParserBadHeader = 1341, /// ///ER_FPARSER_EOF_IN_COMMENT FileParserEOFInComment = 1342, /// ///ER_FPARSER_ERROR_IN_PARAMETER FileParserErrorInParameter = 1343, /// ///ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER FileParserEOFInUnknownParameter = 1344, /// ///ER_VIEW_NO_EXPLAIN ViewNoExplain = 1345, /// ///ER_FRM_UNKNOWN_TYPE FrmUnknownType = 1346, /// ///ER_WRONG_OBJECT WrongObject = 1347, /// ///ER_NONUPDATEABLE_COLUMN NonUpdateableColumn = 1348, /// ///ER_VIEW_SELECT_DERIVED ViewSelectDerived = 1349, /// ///ER_VIEW_SELECT_CLAUSE ViewSelectClause = 1350, /// ///ER_VIEW_SELECT_VARIABLE ViewSelectVariable = 1351, /// ///ER_VIEW_SELECT_TMPTABLE ViewSelectTempTable = 1352, /// ///ER_VIEW_WRONG_LIST ViewWrongList = 1353, /// ///ER_WARN_VIEW_MERGE WarningViewMerge = 1354, /// ///ER_WARN_VIEW_WITHOUT_KEY WarningViewWithoutKey = 1355, /// ///ER_VIEW_INVALID ViewInvalid = 1356, /// ///ER_SP_NO_DROP_SP StoredProcedureNoDropStoredProcedure = 1357, /// ///ER_SP_GOTO_IN_HNDLR StoredProcedureGotoInHandler = 1358, /// ///ER_TRG_ALREADY_EXISTS TriggerAlreadyExists = 1359, /// ///ER_TRG_DOES_NOT_EXIST TriggerDoesNotExist = 1360, /// ///ER_TRG_ON_VIEW_OR_TEMP_TABLE TriggerOnViewOrTempTable = 1361, /// ///ER_TRG_CANT_CHANGE_ROW TriggerCannotChangeRow = 1362, /// ///ER_TRG_NO_SUCH_ROW_IN_TRG TriggerNoSuchRowInTrigger = 1363, /// ///ER_NO_DEFAULT_FOR_FIELD NoDefaultForField = 1364, /// ///ER_DIVISION_BY_ZERO DivisionByZero = 1365, /// ///ER_TRUNCATED_WRONG_VALUE_FOR_FIELD TruncatedWrongValueForField = 1366, /// ///ER_ILLEGAL_VALUE_FOR_TYPE IllegalValueForType = 1367, /// ///ER_VIEW_NONUPD_CHECK ViewNonUpdatableCheck = 1368, /// ///ER_VIEW_CHECK_FAILED ViewCheckFailed = 1369, /// ///ER_PROCACCESS_DENIED_ERROR PrecedureAccessDenied = 1370, /// ///ER_RELAY_LOG_FAIL RelayLogFail = 1371, /// ///ER_PASSWD_LENGTH PasswordLength = 1372, /// ///ER_UNKNOWN_TARGET_BINLOG UnknownTargetBinLog = 1373, /// ///ER_IO_ERR_LOG_INDEX_READ IOErrorLogIndexRead = 1374, /// ///ER_BINLOG_PURGE_PROHIBITED BinLogPurgeProhibited = 1375, /// ///ER_FSEEK_FAIL FSeekFail = 1376, /// ///ER_BINLOG_PURGE_FATAL_ERR BinLogPurgeFatalError = 1377, /// ///ER_LOG_IN_USE LogInUse = 1378, /// ///ER_LOG_PURGE_UNKNOWN_ERR LogPurgeUnknownError = 1379, /// ///ER_RELAY_LOG_INIT RelayLogInit = 1380, /// ///ER_NO_BINARY_LOGGING NoBinaryLogging = 1381, /// ///ER_RESERVED_SYNTAX ReservedSyntax = 1382, /// ///ER_WSAS_FAILED WSAStartupFailed = 1383, /// ///ER_DIFF_GROUPS_PROC DifferentGroupsProcedure = 1384, /// ///ER_NO_GROUP_FOR_PROC NoGroupForProcedure = 1385, /// ///ER_ORDER_WITH_PROC OrderWithProcedure = 1386, /// ///ER_LOGGING_PROHIBIT_CHANGING_OF LoggingProhibitsChangingOf = 1387, /// ///ER_NO_FILE_MAPPING NoFileMapping = 1388, /// ///ER_WRONG_MAGIC WrongMagic = 1389, /// ///ER_PS_MANY_PARAM PreparedStatementManyParameters = 1390, /// ///ER_KEY_PART_0 KeyPartZero = 1391, /// ///ER_VIEW_CHECKSUM ViewChecksum = 1392, /// ///ER_VIEW_MULTIUPDATE ViewMultiUpdate = 1393, /// ///ER_VIEW_NO_INSERT_FIELD_LIST ViewNoInsertFieldList = 1394, /// ///ER_VIEW_DELETE_MERGE_VIEW ViewDeleteMergeView = 1395, /// ///ER_CANNOT_USER CannotUser = 1396, /// ///ER_XAER_NOTA XAERNotA = 1397, /// ///ER_XAER_INVAL XAERInvalid = 1398, /// ///ER_XAER_RMFAIL XAERRemoveFail = 1399, /// ///ER_XAER_OUTSIDE XAEROutside = 1400, /// ///ER_XAER_RMERR XAERRemoveError = 1401, /// ///ER_XA_RBROLLBACK XARBRollback = 1402, /// ///ER_NONEXISTING_PROC_GRANT NonExistingProcedureGrant = 1403, /// ///ER_PROC_AUTO_GRANT_FAIL ProcedureAutoGrantFail = 1404, /// ///ER_PROC_AUTO_REVOKE_FAIL ProcedureAutoRevokeFail = 1405, /// ///ER_DATA_TOO_LONG DataTooLong = 1406, /// ///ER_SP_BAD_SQLSTATE StoredProcedureSQLState = 1407, /// ///ER_STARTUP StartupError = 1408, /// ///ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR LoadFromFixedSizeRowsToVariable = 1409, /// ///ER_CANT_CREATE_USER_WITH_GRANT CannotCreateUserWithGrant = 1410, /// ///ER_WRONG_VALUE_FOR_TYPE WrongValueForType = 1411, /// ///ER_TABLE_DEF_CHANGED TableDefinitionChanged = 1412, /// ///ER_SP_DUP_HANDLER StoredProcedureDuplicateHandler = 1413, /// ///ER_SP_NOT_VAR_ARG StoredProcedureNotVariableArgument = 1414, /// ///ER_SP_NO_RETSET StoredProcedureNoReturnSet = 1415, /// ///ER_CANT_CREATE_GEOMETRY_OBJECT CannotCreateGeometryObject = 1416, /// ///ER_FAILED_ROUTINE_BREAK_BINLOG FailedRoutineBreaksBinLog = 1417, /// ///ER_BINLOG_UNSAFE_ROUTINE BinLogUnsafeRoutine = 1418, /// ///ER_BINLOG_CREATE_ROUTINE_NEED_SUPER BinLogCreateRoutineNeedSuper = 1419, /// ///ER_EXEC_STMT_WITH_OPEN_CURSOR ExecuteStatementWithOpenCursor = 1420, /// ///ER_STMT_HAS_NO_OPEN_CURSOR StatementHasNoOpenCursor = 1421, /// ///ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG CommitNotAllowedIfStoredFunctionOrTrigger = 1422, /// ///ER_NO_DEFAULT_FOR_VIEW_FIELD NoDefaultForViewField = 1423, /// ///ER_SP_NO_RECURSION StoredProcedureNoRecursion = 1424, /// ///ER_TOO_BIG_SCALE TooBigScale = 1425, /// ///ER_TOO_BIG_PRECISION TooBigPrecision = 1426, /// ///ER_M_BIGGER_THAN_D MBiggerThanD = 1427, /// ///ER_WRONG_LOCK_OF_SYSTEM_TABLE WrongLockOfSystemTable = 1428, /// ///ER_CONNECT_TO_FOREIGN_DATA_SOURCE ConnectToForeignDataSource = 1429, /// ///ER_QUERY_ON_FOREIGN_DATA_SOURCE QueryOnForeignDataSource = 1430, /// ///ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST ForeignDataSourceDoesNotExist = 1431, /// ///ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE ForeignDataStringInvalidCannotCreate = 1432, /// ///ER_FOREIGN_DATA_STRING_INVALID ForeignDataStringInvalid = 1433, /// ///ER_CANT_CREATE_FEDERATED_TABLE CannotCreateFederatedTable = 1434, /// ///ER_TRG_IN_WRONG_SCHEMA TriggerInWrongSchema = 1435, /// ///ER_STACK_OVERRUN_NEED_MORE StackOverrunNeedMore = 1436, /// ///ER_TOO_LONG_BODY TooLongBody = 1437, /// ///ER_WARN_CANT_DROP_DEFAULT_KEYCACHE WarningCannotDropDefaultKeyCache = 1438, /// ///ER_TOO_BIG_DISPLAYWIDTH TooBigDisplayWidth = 1439, /// ///ER_XAER_DUPID XAERDuplicateID = 1440, /// ///ER_DATETIME_FUNCTION_OVERFLOW DateTimeFunctionOverflow = 1441, /// ///ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG CannotUpdateUsedTableInStoredFunctionOrTrigger = 1442, /// ///ER_VIEW_PREVENT_UPDATE ViewPreventUpdate = 1443, /// ///ER_PS_NO_RECURSION PreparedStatementNoRecursion = 1444, /// ///ER_SP_CANT_SET_AUTOCOMMIT StoredProcedureCannotSetAutoCommit = 1445, /// ///ER_MALFORMED_DEFINER MalformedDefiner = 1446, /// ///ER_VIEW_FRM_NO_USER ViewFrmNoUser = 1447, /// ///ER_VIEW_OTHER_USER ViewOtherUser = 1448, /// ///ER_NO_SUCH_USER NoSuchUser = 1449, /// ///ER_FORBID_SCHEMA_CHANGE ForbidSchemaChange = 1450, /// ///ER_ROW_IS_REFERENCED_2 RowIsReferenced2 = 1451, /// ///ER_NO_REFERENCED_ROW_2 NoReferencedRow2 = 1452, /// ///ER_SP_BAD_VAR_SHADOW StoredProcedureBadVariableShadow = 1453, /// ///ER_TRG_NO_DEFINER TriggerNoDefiner = 1454, /// ///ER_OLD_FILE_FORMAT OldFileFormat = 1455, /// ///ER_SP_RECURSION_LIMIT StoredProcedureRecursionLimit = 1456, /// ///ER_SP_PROC_TABLE_CORRUPT StoredProcedureTableCorrupt = 1457, /// ///ER_SP_WRONG_NAME StoredProcedureWrongName = 1458, /// ///ER_TABLE_NEEDS_UPGRADE TableNeedsUpgrade = 1459, /// ///ER_SP_NO_AGGREGATE StoredProcedureNoAggregate = 1460, /// ///ER_MAX_PREPARED_STMT_COUNT_REACHED MaxPreparedStatementCountReached = 1461, /// ///ER_VIEW_RECURSIVE ViewRecursive = 1462, /// ///ER_NON_GROUPING_FIELD_USED NonGroupingFieldUsed = 1463, /// ///ER_TABLE_CANT_HANDLE_SPKEYS TableCannotHandleSpatialKeys = 1464, /// ///ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA NoTriggersOnSystemSchema = 1465, /// ///ER_REMOVED_SPACES RemovedSpaces = 1466, /// ///ER_AUTOINC_READ_FAILED AutoIncrementReadFailed = 1467, /// ///ER_USERNAME UserNameError = 1468, /// ///ER_HOSTNAME HostNameError = 1469, /// ///ER_WRONG_STRING_LENGTH WrongStringLength = 1470, /// ///ER_NON_INSERTABLE_TABLE NonInsertableTable = 1471, /// ///ER_ADMIN_WRONG_MRG_TABLE AdminWrongMergeTable = 1472, /// ///ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT TooHighLevelOfNestingForSelect = 1473, /// ///ER_NAME_BECOMES_EMPTY NameBecomesEmpty = 1474, /// ///ER_AMBIGUOUS_FIELD_TERM AmbiguousFieldTerm = 1475, /// ///ER_FOREIGN_SERVER_EXISTS ForeignServerExists = 1476, /// ///ER_FOREIGN_SERVER_DOESNT_EXIST ForeignServerDoesNotExist = 1477, /// ///ER_ILLEGAL_HA_CREATE_OPTION IllegalHACreateOption = 1478, /// ///ER_PARTITION_REQUIRES_VALUES_ERROR PartitionRequiresValues = 1479, /// ///ER_PARTITION_WRONG_VALUES_ERROR PartitionWrongValues = 1480, /// ///ER_PARTITION_MAXVALUE_ERROR PartitionMaxValue = 1481, /// ///ER_PARTITION_SUBPARTITION_ERROR PartitionSubPartition = 1482, /// ///ER_PARTITION_SUBPART_MIX_ERROR PartitionSubPartMix = 1483, /// ///ER_PARTITION_WRONG_NO_PART_ERROR PartitionWrongNoPart = 1484, /// ///ER_PARTITION_WRONG_NO_SUBPART_ERROR PartitionWrongNoSubPart = 1485, /// ///ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR WrongExpressionInParitionFunction = 1486, /// ///ER_NO_CONST_EXPR_IN_RANGE_OR_LIST_ERROR NoConstantExpressionInRangeOrListError = 1487, /// ///ER_FIELD_NOT_FOUND_PART_ERROR FieldNotFoundPartitionErrror = 1488, /// ///ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR ListOfFieldsOnlyInHash = 1489, /// ///ER_INCONSISTENT_PARTITION_INFO_ERROR InconsistentPartitionInfo = 1490, /// ///ER_PARTITION_FUNC_NOT_ALLOWED_ERROR PartitionFunctionNotAllowed = 1491, /// ///ER_PARTITIONS_MUST_BE_DEFINED_ERROR PartitionsMustBeDefined = 1492, /// ///ER_RANGE_NOT_INCREASING_ERROR RangeNotIncreasing = 1493, /// ///ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR InconsistentTypeOfFunctions = 1494, /// ///ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR MultipleDefinitionsConstantInListPartition = 1495, /// ///ER_PARTITION_ENTRY_ERROR PartitionEntryError = 1496, /// ///ER_MIX_HANDLER_ERROR MixHandlerError = 1497, /// ///ER_PARTITION_NOT_DEFINED_ERROR PartitionNotDefined = 1498, /// ///ER_TOO_MANY_PARTITIONS_ERROR TooManyPartitions = 1499, /// ///ER_SUBPARTITION_ERROR SubPartitionError = 1500, /// ///ER_CANT_CREATE_HANDLER_FILE CannotCreateHandlerFile = 1501, /// ///ER_BLOB_FIELD_IN_PART_FUNC_ERROR BlobFieldInPartitionFunction = 1502, /// ///ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF UniqueKeyNeedAllFieldsInPartitioningFunction = 1503, /// ///ER_NO_PARTS_ERROR NoPartitions = 1504, /// ///ER_PARTITION_MGMT_ON_NONPARTITIONED PartitionManagementOnNoPartitioned = 1505, /// ///ER_FOREIGN_KEY_ON_PARTITIONED ForeignKeyOnPartitioned = 1506, /// ///ER_DROP_PARTITION_NON_EXISTENT DropPartitionNonExistent = 1507, /// ///ER_DROP_LAST_PARTITION DropLastPartition = 1508, /// ///ER_COALESCE_ONLY_ON_HASH_PARTITION CoalesceOnlyOnHashPartition = 1509, /// ///ER_REORG_HASH_ONLY_ON_SAME_NO ReorganizeHashOnlyOnSameNumber = 1510, /// ///ER_REORG_NO_PARAM_ERROR ReorganizeNoParameter = 1511, /// ///ER_ONLY_ON_RANGE_LIST_PARTITION OnlyOnRangeListPartition = 1512, /// ///ER_ADD_PARTITION_SUBPART_ERROR AddPartitionSubPartition = 1513, /// ///ER_ADD_PARTITION_NO_NEW_PARTITION AddPartitionNoNewPartition = 1514, /// ///ER_COALESCE_PARTITION_NO_PARTITION CoalescePartitionNoPartition = 1515, /// ///ER_REORG_PARTITION_NOT_EXIST ReorganizePartitionNotExist = 1516, /// ///ER_SAME_NAME_PARTITION SameNamePartition = 1517, /// ///ER_NO_BINLOG_ERROR NoBinLog = 1518, /// ///ER_CONSECUTIVE_REORG_PARTITIONS ConsecutiveReorganizePartitions = 1519, /// ///ER_REORG_OUTSIDE_RANGE ReorganizeOutsideRange = 1520, /// ///ER_PARTITION_FUNCTION_FAILURE PartitionFunctionFailure = 1521, /// ///ER_PART_STATE_ERROR PartitionStateError = 1522, /// ///ER_LIMITED_PART_RANGE LimitedPartitionRange = 1523, /// ///ER_PLUGIN_IS_NOT_LOADED PluginIsNotLoaded = 1524, /// ///ER_WRONG_VALUE WrongValue = 1525, /// ///ER_NO_PARTITION_FOR_GIVEN_VALUE NoPartitionForGivenValue = 1526, /// ///ER_FILEGROUP_OPTION_ONLY_ONCE FileGroupOptionOnlyOnce = 1527, /// ///ER_CREATE_FILEGROUP_FAILED CreateFileGroupFailed = 1528, /// ///ER_DROP_FILEGROUP_FAILED DropFileGroupFailed = 1529, /// ///ER_TABLESPACE_AUTO_EXTEND_ERROR TableSpaceAutoExtend = 1530, /// ///ER_WRONG_SIZE_NUMBER WrongSizeNumber = 1531, /// ///ER_SIZE_OVERFLOW_ERROR SizeOverflow = 1532, /// ///ER_ALTER_FILEGROUP_FAILED AlterFileGroupFailed = 1533, /// ///ER_BINLOG_ROW_LOGGING_FAILED BinLogRowLogginFailed = 1534, /// ///ER_BINLOG_ROW_WRONG_TABLE_DEF BinLogRowWrongTableDefinition = 1535, /// ///ER_BINLOG_ROW_RBR_TO_SBR BinLogRowRBRToSBR = 1536, /// ///ER_EVENT_ALREADY_EXISTS EventAlreadyExists = 1537, /// ///ER_EVENT_STORE_FAILED EventStoreFailed = 1538, /// ///ER_EVENT_DOES_NOT_EXIST EventDoesNotExist = 1539, /// ///ER_EVENT_CANT_ALTER EventCannotAlter = 1540, /// ///ER_EVENT_DROP_FAILED EventDropFailed = 1541, /// ///ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG EventIntervalNotPositiveOrTooBig = 1542, /// ///ER_EVENT_ENDS_BEFORE_STARTS EventEndsBeforeStarts = 1543, /// ///ER_EVENT_EXEC_TIME_IN_THE_PAST EventExecTimeInThePast = 1544, /// ///ER_EVENT_OPEN_TABLE_FAILED EventOpenTableFailed = 1545, /// ///ER_EVENT_NEITHER_M_EXPR_NOR_M_AT EventNeitherMExpresssionNorMAt = 1546, /// ///ER_COL_COUNT_DOESNT_MATCH_CORRUPTED ColumnCountDoesNotMatchCorrupted = 1547, /// ///ER_CANNOT_LOAD_FROM_TABLE CannotLoadFromTable = 1548, /// ///ER_EVENT_CANNOT_DELETE EventCannotDelete = 1549, /// ///ER_EVENT_COMPILE_ERROR EventCompileError = 1550, /// ///ER_EVENT_SAME_NAME EventSameName = 1551, /// ///ER_EVENT_DATA_TOO_LONG EventDataTooLong = 1552, /// ///ER_DROP_INDEX_FK DropIndexForeignKey = 1553, /// ///ER_WARN_DEPRECATED_SYNTAX_WITH_VER WarningDeprecatedSyntaxWithVersion = 1554, /// ///ER_CANT_WRITE_LOCK_LOG_TABLE CannotWriteLockLogTable = 1555, /// ///ER_CANT_LOCK_LOG_TABLE CannotLockLogTable = 1556, /// ///ER_FOREIGN_DUPLICATE_KEY ForeignDuplicateKey = 1557, /// ///ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE ColumnCountDoesNotMatchPleaseUpdate = 1558, /// ///ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR TemoraryTablePreventSwitchOutOfRBR = 1559, /// ///ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT StoredFunctionPreventsSwitchBinLogFormat = 1560, /// ///ER_NDB_CANT_SWITCH_BINLOG_FORMAT NDBCannotSwitchBinLogFormat = 1561, /// ///ER_PARTITION_NO_TEMPORARY PartitionNoTemporary = 1562, /// ///ER_PARTITION_CONST_DOMAIN_ERROR PartitionConstantDomain = 1563, /// ///ER_PARTITION_FUNCTION_IS_NOT_ALLOWED PartitionFunctionIsNotAllowed = 1564, /// ///ER_DDL_LOG_ERROR DDLLogError = 1565, /// ///ER_NULL_IN_VALUES_LESS_THAN NullInValuesLessThan = 1566, /// ///ER_WRONG_PARTITION_NAME WrongPartitionName = 1567, /// ///ER_CANT_CHANGE_TX_ISOLATION CannotChangeTransactionIsolation = 1568, /// ///ER_DUP_ENTRY_AUTOINCREMENT_CASE DuplicateEntryAutoIncrementCase = 1569, /// ///ER_EVENT_MODIFY_QUEUE_ERROR EventModifyQueueError = 1570, /// ///ER_EVENT_SET_VAR_ERROR EventSetVariableError = 1571, /// ///ER_PARTITION_MERGE_ERROR PartitionMergeError = 1572, /// ///ER_CANT_ACTIVATE_LOG CannotActivateLog = 1573, /// ///ER_RBR_NOT_AVAILABLE RBRNotAvailable = 1574, /// ///ER_BASE64_DECODE_ERROR Base64DecodeError = 1575, /// ///ER_EVENT_RECURSION_FORBIDDEN EventRecursionForbidden = 1576, /// ///ER_EVENTS_DB_ERROR EventsDatabaseError = 1577, /// ///ER_ONLY_INTEGERS_ALLOWED OnlyIntegersAllowed = 1578, /// ///ER_UNSUPORTED_LOG_ENGINE UnsupportedLogEngine = 1579, /// ///ER_BAD_LOG_STATEMENT BadLogStatement = 1580, /// ///ER_CANT_RENAME_LOG_TABLE CannotRenameLogTable = 1581, /// ///ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT WrongParameterCountToNativeFCT = 1582, /// ///ER_WRONG_PARAMETERS_TO_NATIVE_FCT WrongParametersToNativeFCT = 1583, /// ///ER_WRONG_PARAMETERS_TO_STORED_FCT WrongParametersToStoredFCT = 1584, /// ///ER_NATIVE_FCT_NAME_COLLISION NativeFCTNameCollision = 1585, /// ///ER_DUP_ENTRY_WITH_KEY_NAME DuplicateEntryWithKeyName = 1586, /// ///ER_BINLOG_PURGE_EMFILE BinLogPurgeEMFile = 1587, /// ///ER_EVENT_CANNOT_CREATE_IN_THE_PAST EventCannotCreateInThePast = 1588, /// ///ER_EVENT_CANNOT_ALTER_IN_THE_PAST EventCannotAlterInThePast = 1589, /// ///ER_SLAVE_INCIDENT SlaveIncident = 1590, /// ///ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT NoPartitionForGivenValueSilent = 1591, /// ///ER_BINLOG_UNSAFE_STATEMENT BinLogUnsafeStatement = 1592, /// ///ER_SLAVE_FATAL_ERROR SlaveFatalError = 1593, /// ///ER_SLAVE_RELAY_LOG_READ_FAILURE SlaveRelayLogReadFailure = 1594, /// ///ER_SLAVE_RELAY_LOG_WRITE_FAILURE SlaveRelayLogWriteFailure = 1595, /// ///ER_SLAVE_CREATE_EVENT_FAILURE SlaveCreateEventFailure = 1596, /// ///ER_SLAVE_MASTER_COM_FAILURE SlaveMasterComFailure = 1597, /// ///ER_BINLOG_LOGGING_IMPOSSIBLE BinLogLoggingImpossible = 1598, /// ///ER_VIEW_NO_CREATION_CTX ViewNoCreationContext = 1599, /// ///ER_VIEW_INVALID_CREATION_CTX ViewInvalidCreationContext = 1600, /// ///ER_SR_INVALID_CREATION_CTX StoredRoutineInvalidCreateionContext = 1601, /// ///ER_TRG_CORRUPTED_FILE TiggerCorruptedFile = 1602, /// ///ER_TRG_NO_CREATION_CTX TriggerNoCreationContext = 1603, /// ///ER_TRG_INVALID_CREATION_CTX TriggerInvalidCreationContext = 1604, /// ///ER_EVENT_INVALID_CREATION_CTX EventInvalidCreationContext = 1605, /// ///ER_TRG_CANT_OPEN_TABLE TriggerCannotOpenTable = 1606, /// ///ER_CANT_CREATE_SROUTINE CannoCreateSubRoutine = 1607, /// ///ER_SLAVE_AMBIGOUS_EXEC_MODE SlaveAmbiguousExecMode = 1608, /// ///ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT NoFormatDescriptionEventBeforeBinLogStatement = 1609, /// ///ER_SLAVE_CORRUPT_EVENT SlaveCorruptEvent = 1610, /// ///ER_LOAD_DATA_INVALID_COLUMN LoadDataInvalidColumn = 1611, /// ///ER_LOG_PURGE_NO_FILE LogPurgeNoFile = 1612, /// ///ER_XA_RBTIMEOUT XARBTimeout = 1613, /// ///ER_XA_RBDEADLOCK XARBDeadlock = 1614, /// ///ER_NEED_REPREPARE NeedRePrepare = 1615, /// ///ER_DELAYED_NOT_SUPPORTED DelayedNotSupported = 1616, /// ///WARN_NO_MASTER_INFO WarningNoMasterInfo = 1617, /// ///WARN_OPTION_IGNORED WarningOptionIgnored = 1618, /// ///WARN_PLUGIN_DELETE_BUILTIN WarningPluginDeleteBuiltIn = 1619, /// ///WARN_PLUGIN_BUSY WarningPluginBusy = 1620, /// ///ER_VARIABLE_IS_READONLY VariableIsReadonly = 1621, /// ///ER_WARN_ENGINE_TRANSACTION_ROLLBACK WarningEngineTransactionRollback = 1622, /// ///ER_SLAVE_HEARTBEAT_FAILURE SlaveHeartbeatFailure = 1623, /// ///ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE SlaveHeartbeatValueOutOfRange = 1624, /// ///ER_NDB_REPLICATION_SCHEMA_ERROR NDBReplicationSchemaError = 1625, /// ///ER_CONFLICT_FN_PARSE_ERROR ConflictFunctionParseError = 1626, /// ///ER_EXCEPTIONS_WRITE_ERROR ExcepionsWriteError = 1627, /// ///ER_TOO_LONG_TABLE_COMMENT TooLongTableComment = 1628, /// ///ER_TOO_LONG_FIELD_COMMENT TooLongFieldComment = 1629, /// ///ER_FUNC_INEXISTENT_NAME_COLLISION FunctionInExistentNameCollision = 1630, /// ///ER_DATABASE_NAME DatabaseNameError = 1631, /// ///ER_TABLE_NAME TableNameErrror = 1632, /// ///ER_PARTITION_NAME PartitionNameError = 1633, /// ///ER_SUBPARTITION_NAME SubPartitionNameError = 1634, /// ///ER_TEMPORARY_NAME TemporaryNameError = 1635, /// ///ER_RENAMED_NAME RenamedNameError = 1636, /// ///ER_TOO_MANY_CONCURRENT_TRXS TooManyConcurrentTransactions = 1637, /// ///WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED WarningNonASCIISeparatorNotImplemented = 1638, /// ///ER_DEBUG_SYNC_TIMEOUT DebugSyncTimeout = 1639, /// ///ER_DEBUG_SYNC_HIT_LIMIT DebugSyncHitLimit = 1640, /// ///ER_ERROR_LAST ErrorLast = 1640 } } mysql-connector-net-6.4.3/Source/MySql.Data/command.cs0000644000175000017500000011123511127003600023300 0ustar directhexdirecthex // Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Data.Common; using System.IO; using System.Collections; using System.Text; using MySql.Data.Common; using System.ComponentModel; using System.Threading; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using MySql.Data.MySqlClient.Properties; #if !CF using System.Transactions; #endif namespace MySql.Data.MySqlClient { /// #if !CF [System.Drawing.ToolboxBitmap(typeof(MySqlCommand), "MySqlClient.resources.command.bmp")] [System.ComponentModel.DesignerCategory("Code")] #endif public sealed class MySqlCommand : DbCommand, ICloneable { MySqlConnection connection; MySqlTransaction curTransaction; string cmdText; CommandType cmdType; long updatedRowCount; UpdateRowSource updatedRowSource; MySqlParameterCollection parameters; private IAsyncResult asyncResult; private bool designTimeVisible; internal Int64 lastInsertedId; private PreparableStatement statement; private int commandTimeout; private bool canceled; private bool resetSqlSelect; List batch; private string batchableCommandText; CommandTimer commandTimer; private bool useDefaultTimeout; private bool shouldCache; private int cacheAge; private bool internallyCreated; /// public MySqlCommand() { designTimeVisible = true; cmdType = CommandType.Text; parameters = new MySqlParameterCollection(this); updatedRowSource = UpdateRowSource.Both; cmdText = String.Empty; useDefaultTimeout = true; } /// public MySqlCommand(string cmdText) : this() { CommandText = cmdText; } /// public MySqlCommand(string cmdText, MySqlConnection connection) : this(cmdText) { Connection = connection; } /// public MySqlCommand(string cmdText, MySqlConnection connection, MySqlTransaction transaction) : this(cmdText, connection) { curTransaction = transaction; } #region Properties /// #if !CF [Browsable(false)] #endif public Int64 LastInsertedId { get { return lastInsertedId; } } /// #if !CF [Category("Data")] [Description("Command text to execute")] [Editor("MySql.Data.Common.Design.SqlCommandTextEditor,MySqlClient.Design", typeof(System.Drawing.Design.UITypeEditor))] #endif public override string CommandText { get { return cmdText; } set { cmdText = value; statement = null; batchableCommandText = null; if (cmdText != null && cmdText.EndsWith("DEFAULT VALUES")) { cmdText = cmdText.Substring(0, cmdText.Length - 14); cmdText = cmdText + "() VALUES ()"; } } } /// #if !CF [Category("Misc")] [Description("Time to wait for command to execute")] [DefaultValue(30)] #endif public override int CommandTimeout { get { return useDefaultTimeout ? 30 : commandTimeout; } set { if (commandTimeout < 0) throw new ArgumentException("Command timeout must not be negative"); // Timeout in milliseconds should not exceed maximum for 32 bit // signed integer (~24 days), because underlying driver (and streams) // use milliseconds expressed ints for timeout values. // Hence, truncate the value. int timeout = Math.Min(value, Int32.MaxValue / 1000); if (timeout != value) { MySqlTrace.LogWarning(connection.ServerThread, "Command timeout value too large (" + value + " seconds). Changed to max. possible value (" + timeout + " seconds)"); } commandTimeout = timeout; useDefaultTimeout = false; } } /// #if !CF [Category("Data")] #endif public override CommandType CommandType { get { return cmdType; } set { cmdType = value; } } /// #if !CF [Browsable(false)] #endif public bool IsPrepared { get { return statement != null && statement.IsPrepared; } } /// #if !CF [Category("Behavior")] [Description("Connection used by the command")] #endif public new MySqlConnection Connection { get { return connection; } set { /* * The connection is associated with the transaction * so set the transaction object to return a null reference if the connection * is reset. */ if (connection != value) Transaction = null; connection = value; // if the user has not already set the command timeout, then // take the default from the connection if (connection != null) { if (useDefaultTimeout) { commandTimeout = (int)connection.Settings.DefaultCommandTimeout; useDefaultTimeout = false; } EnableCaching = connection.Settings.TableCaching; CacheAge = connection.Settings.DefaultTableCacheAge; } } } /// #if !CF [Category("Data")] [Description("The parameters collection")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] #endif public new MySqlParameterCollection Parameters { get { return parameters; } } /// #if !CF [Browsable(false)] #endif public new MySqlTransaction Transaction { get { return curTransaction; } set { curTransaction = value; } } public bool EnableCaching { get { return shouldCache; } set { shouldCache = value; } } public int CacheAge { get { return cacheAge; } set { cacheAge = value; } } /* /// #if !CF [Category("Behavior")] #endif public override UpdateRowSource UpdatedRowSource { get { return updatedRowSource; } set { updatedRowSource = value; } }*/ internal List Batch { get { return batch; } } internal bool Canceled { get { return canceled; } } internal string BatchableCommandText { get { return batchableCommandText; } } internal bool InternallyCreated { get { return internallyCreated; } set { internallyCreated = value; } } #endregion #region Methods /// /// Attempts to cancel the execution of a currently active command /// /// /// Cancelling a currently active query only works with MySQL versions 5.0.0 and higher. /// public override void Cancel() { connection.CancelQuery(connection.ConnectionTimeout); canceled = true; } /// /// Creates a new instance of a object. /// /// /// This method is a strongly-typed version of . /// /// A object. /// public new MySqlParameter CreateParameter() { return (MySqlParameter)CreateDbParameter(); } /// /// Check the connection to make sure /// - it is open /// - it is not currently being used by a reader /// - and we have the right version of MySQL for the requested command type /// private void CheckState() { // There must be a valid and open connection. if (connection == null) throw new InvalidOperationException("Connection must be valid and open."); if (connection.State != ConnectionState.Open && !connection.SoftClosed) throw new InvalidOperationException("Connection must be valid and open."); // Data readers have to be closed first if (connection.IsInUse && !this.internallyCreated) throw new MySqlException("There is already an open DataReader associated with this Connection which must be closed first."); } /// public override int ExecuteNonQuery() { using (MySqlDataReader reader = ExecuteReader()) { reader.Close(); return reader.RecordsAffected; } } internal void ClearCommandTimer() { if (commandTimer != null) { commandTimer.Dispose(); commandTimer = null; } } internal void Close(MySqlDataReader reader) { if (statement != null) statement.Close(reader); ResetSqlSelectLimit(); if (statement != null && connection != null && connection.driver != null) connection.driver.CloseQuery(connection, statement.StatementId); ClearCommandTimer(); } /// /// Reset reader to null, to avoid "There is already an open data reader" /// on the next ExecuteReader(). Used in error handling scenarios. /// private void ResetReader() { if (connection != null && connection.Reader != null) { connection.Reader.Close(); connection.Reader = null; } } /// /// Reset SQL_SELECT_LIMIT that could have been modified by CommandBehavior. /// internal void ResetSqlSelectLimit() { // if we are supposed to reset the sql select limit, do that here if (resetSqlSelect) { resetSqlSelect = false; MySqlCommand command = new MySqlCommand("SET SQL_SELECT_LIMIT=DEFAULT", connection); command.internallyCreated = true; command.ExecuteNonQuery(); } } /// public new MySqlDataReader ExecuteReader() { return ExecuteReader(CommandBehavior.Default); } /// public new MySqlDataReader ExecuteReader (CommandBehavior behavior) { bool success = false; CheckState(); Driver driver = connection.driver; lock (driver) { // We have to recheck that there is no reader, after we got the lock if (connection.Reader != null) { throw new MySqlException(Resources.DataReaderOpen); } #if !CF System.Transactions.Transaction curTrans = System.Transactions.Transaction.Current; if (curTrans != null) { bool inRollback = false; if (driver.CurrentTransaction!= null) inRollback = driver.CurrentTransaction.InRollback; if (!inRollback) { TransactionStatus status = TransactionStatus.InDoubt; try { // in some cases (during state transitions) this throws // an exception. Ignore exceptions, we're only interested // whether transaction was aborted or not. status = curTrans.TransactionInformation.Status; } catch (TransactionException) { } if (status == TransactionStatus.Aborted) throw new TransactionAbortedException(); } } #endif commandTimer = new CommandTimer(connection, CommandTimeout); lastInsertedId = -1; cmdText = cmdText.Trim(); if (String.IsNullOrEmpty(cmdText)) throw new InvalidOperationException(Resources.CommandTextNotInitialized); string sql = cmdText.Trim(';'); if (CommandType == CommandType.TableDirect) sql = "SELECT * FROM " + sql; // if we are on a replicated connection, we are only allow readonly statements if (connection.Settings.Replication && !InternallyCreated) EnsureCommandIsReadOnly(sql); if (statement == null || !statement.IsPrepared) { if (CommandType == CommandType.StoredProcedure) statement = new StoredProcedure(this, sql); else statement = new PreparableStatement(this, sql); } // stored procs are the only statement type that need do anything during resolve statement.Resolve(false); // Now that we have completed our resolve step, we can handle our // command behaviors HandleCommandBehaviors(behavior); updatedRowCount = -1; try { MySqlDataReader reader = new MySqlDataReader(this, statement, behavior); connection.Reader = reader; canceled = false; // execute the statement statement.Execute(); // wait for data to return reader.NextResult(); success = true; return reader; } catch (TimeoutException tex) { connection.HandleTimeoutOrThreadAbort(tex); throw; //unreached } catch (ThreadAbortException taex) { connection.HandleTimeoutOrThreadAbort(taex); throw; } catch (IOException ioex) { connection.Abort(); // Closes connection without returning it to the pool throw new MySqlException(Resources.FatalErrorDuringExecute, ioex); } catch (MySqlException ex) { if (ex.InnerException is TimeoutException) throw; // already handled try { ResetReader(); ResetSqlSelectLimit(); } catch (Exception) { // Reset SqlLimit did not work, connection is hosed. Connection.Abort(); throw new MySqlException(ex.Message, true, ex); } // if we caught an exception because of a cancel, then just return null if (ex.IsQueryAborted) return null; if (ex.IsFatal) Connection.Close(); if (ex.Number == 0) throw new MySqlException(Resources.FatalErrorDuringExecute, ex); throw; } finally { if (connection != null) { if (connection.Reader == null) { // Something went seriously wrong, and reader would not // be able to clear timeout on closing. // So we clear timeout here. ClearCommandTimer(); } if (!success) { // ExecuteReader failed.Close Reader and set to null to // prevent subsequent errors with DataReaderOpen ResetReader(); } } } } } private void EnsureCommandIsReadOnly(string sql) { sql = sql.ToLower(CultureInfo.InvariantCulture); if (!sql.StartsWith("select") && !sql.StartsWith("show")) throw new MySqlException(Resources.ReplicatedConnectionsAllowOnlyReadonlyStatements); if (sql.EndsWith("for update") || sql.EndsWith("lock in share mode")) throw new MySqlException(Resources.ReplicatedConnectionsAllowOnlyReadonlyStatements); } /// public override object ExecuteScalar() { lastInsertedId = -1; object val = null; using (MySqlDataReader reader = ExecuteReader()) { if (reader.Read()) val = reader.GetValue(0); } return val; } private void HandleCommandBehaviors(CommandBehavior behavior) { if ((behavior & CommandBehavior.SchemaOnly) != 0) { new MySqlCommand("SET SQL_SELECT_LIMIT=0", connection).ExecuteNonQuery(); resetSqlSelect = true; } else if ((behavior & CommandBehavior.SingleRow) != 0) { new MySqlCommand("SET SQL_SELECT_LIMIT=1", connection).ExecuteNonQuery(); resetSqlSelect = true; } } /// private void Prepare(int cursorPageSize) { using (new CommandTimer(Connection, CommandTimeout)) { // if the length of the command text is zero, then just return string psSQL = CommandText; if (psSQL == null || psSQL.Trim().Length == 0) return; if (CommandType == CommandType.StoredProcedure) statement = new StoredProcedure(this, CommandText); else statement = new PreparableStatement(this, CommandText); statement.Resolve(true); statement.Prepare(); } } /// public override void Prepare() { if (connection == null) throw new InvalidOperationException("The connection property has not been set."); if (connection.State != ConnectionState.Open) throw new InvalidOperationException("The connection is not open."); if (connection.Settings.IgnorePrepare) return; Prepare(0); } #endregion #region Async Methods internal delegate object AsyncDelegate(int type, CommandBehavior behavior); internal AsyncDelegate caller = null; internal Exception thrownException; internal object AsyncExecuteWrapper(int type, CommandBehavior behavior) { thrownException = null; try { if (type == 1) return ExecuteReader(behavior); return ExecuteNonQuery(); } catch (Exception ex) { thrownException = ex; } return null; } /// /// Initiates the asynchronous execution of the SQL statement or stored procedure /// that is described by this , and retrieves one or more /// result sets from the server. /// /// An that can be used to poll, wait for results, /// or both; this value is also needed when invoking EndExecuteReader, /// which returns a instance that can be used to retrieve /// the returned rows. public IAsyncResult BeginExecuteReader() { return BeginExecuteReader(CommandBehavior.Default); } /// /// Initiates the asynchronous execution of the SQL statement or stored procedure /// that is described by this using one of the /// CommandBehavior values. /// /// One of the values, indicating /// options for statement execution and data retrieval. /// An that can be used to poll, wait for results, /// or both; this value is also needed when invoking EndExecuteReader, /// which returns a instance that can be used to retrieve /// the returned rows. public IAsyncResult BeginExecuteReader(CommandBehavior behavior) { if (caller != null) throw new MySqlException(Resources.UnableToStartSecondAsyncOp); caller = new AsyncDelegate(AsyncExecuteWrapper); asyncResult = caller.BeginInvoke(1, behavior, null, null); return asyncResult; } /// /// Finishes asynchronous execution of a SQL statement, returning the requested /// . /// /// The returned by the call to /// . /// A MySqlDataReader object that can be used to retrieve the requested rows. public MySqlDataReader EndExecuteReader(IAsyncResult result) { result.AsyncWaitHandle.WaitOne(); AsyncDelegate c = caller; caller = null; if (thrownException != null) throw thrownException; return (MySqlDataReader)c.EndInvoke(result); } /// /// Initiates the asynchronous execution of the SQL statement or stored procedure /// that is described by this . /// /// /// An delegate that is invoked when the command's /// execution has completed. Pass a null reference (Nothing in Visual Basic) /// to indicate that no callback is required. /// A user-defined state object that is passed to the /// callback procedure. Retrieve this object from within the callback procedure /// using the property. /// An that can be used to poll or wait for results, /// or both; this value is also needed when invoking , /// which returns the number of affected rows. public IAsyncResult BeginExecuteNonQuery(AsyncCallback callback, object stateObject) { if (caller != null) throw new MySqlException(Resources.UnableToStartSecondAsyncOp); caller = new AsyncDelegate(AsyncExecuteWrapper); asyncResult = caller.BeginInvoke(2, CommandBehavior.Default, callback, stateObject); return asyncResult; } /// /// Initiates the asynchronous execution of the SQL statement or stored procedure /// that is described by this . /// /// An that can be used to poll or wait for results, /// or both; this value is also needed when invoking , /// which returns the number of affected rows. public IAsyncResult BeginExecuteNonQuery() { if (caller != null) throw new MySqlException(Resources.UnableToStartSecondAsyncOp); caller = new AsyncDelegate(AsyncExecuteWrapper); asyncResult = caller.BeginInvoke(2, CommandBehavior.Default, null, null); return asyncResult; } /// /// Finishes asynchronous execution of a SQL statement. /// /// The returned by the call /// to . /// public int EndExecuteNonQuery(IAsyncResult asyncResult) { asyncResult.AsyncWaitHandle.WaitOne(); AsyncDelegate c = caller; caller = null; if (thrownException != null) throw thrownException; return (int)c.EndInvoke(asyncResult); } #endregion #region Private Methods /* private ArrayList PrepareSqlBuffers(string sql) { ArrayList buffers = new ArrayList(); MySqlStreamWriter writer = new MySqlStreamWriter(new MemoryStream(), connection.Encoding); writer.Version = connection.driver.Version; // if we are executing as a stored procedure, then we need to add the call // keyword. if (CommandType == CommandType.StoredProcedure) { if (storedProcedure == null) storedProcedure = new StoredProcedure(this); sql = storedProcedure.Prepare( CommandText ); } // tokenize the SQL sql = sql.TrimStart(';').TrimEnd(';'); ArrayList tokens = TokenizeSql( sql ); foreach (string token in tokens) { if (token.Trim().Length == 0) continue; if (token == ";" && ! connection.driver.SupportsBatch) { MemoryStream ms = (MemoryStream)writer.Stream; if (ms.Length > 0) buffers.Add( ms ); writer = new MySqlStreamWriter(new MemoryStream(), connection.Encoding); writer.Version = connection.driver.Version; continue; } else if (token[0] == parameters.ParameterMarker) { if (SerializeParameter(writer, token)) continue; } // our fall through case is to write the token to the byte stream writer.WriteStringNoNull(token); } // capture any buffer that is left over MemoryStream mStream = (MemoryStream)writer.Stream; if (mStream.Length > 0) buffers.Add( mStream ); return buffers; }*/ internal long EstimatedSize() { long size = CommandText.Length; foreach (MySqlParameter parameter in Parameters) size += parameter.EstimatedSize(); return size; } #endregion #region ICloneable /// /// Creates a clone of this MySqlCommand object. CommandText, Connection, and Transaction properties /// are included as well as the entire parameter list. /// /// The cloned MySqlCommand object public MySqlCommand Clone() { MySqlCommand clone = new MySqlCommand(cmdText, connection, curTransaction); clone.CommandType = CommandType; clone.commandTimeout = commandTimeout; clone.useDefaultTimeout = useDefaultTimeout; clone.batchableCommandText = batchableCommandText; clone.UpdatedRowSource = UpdatedRowSource; clone.EnableCaching = EnableCaching; clone.CacheAge = CacheAge; foreach (MySqlParameter p in parameters) { clone.Parameters.Add(p.Clone()); } return clone; } object ICloneable.Clone() { return this.Clone(); } #endregion #region Batching support internal void AddToBatch(MySqlCommand command) { if (batch == null) batch = new List(); batch.Add(command); } internal string GetCommandTextForBatching() { if (batchableCommandText == null) { // if the command starts with insert and is "simple" enough, then // we can use the multi-value form of insert if (String.Compare(CommandText.Substring(0, 6), "INSERT", true) == 0) { MySqlCommand cmd = new MySqlCommand("SELECT @@sql_mode", Connection); string sql_mode = cmd.ExecuteScalar().ToString().ToUpper(CultureInfo.InvariantCulture); MySqlTokenizer tokenizer = new MySqlTokenizer(CommandText); tokenizer.AnsiQuotes = sql_mode.IndexOf("ANSI_QUOTES") != -1; tokenizer.BackslashEscapes = sql_mode.IndexOf("NO_BACKSLASH_ESCAPES") == -1; string token = tokenizer.NextToken().ToLower(CultureInfo.InvariantCulture); while (token != null) { if (token.ToUpper(CultureInfo.InvariantCulture) == "VALUES" && !tokenizer.Quoted) { token = tokenizer.NextToken(); Debug.Assert(token == "("); // find matching right paren, and ensure that parens // are balanced. int openParenCount = 1; while (token != null) { batchableCommandText += token; token = tokenizer.NextToken(); if (token == "(") openParenCount++; else if (token == ")") openParenCount--; if (openParenCount == 0) break; } if (token != null) batchableCommandText += token; token = tokenizer.NextToken(); if (token != null && (token == "," || token.ToUpper(CultureInfo.InvariantCulture) == "ON")) { batchableCommandText = null; break; } } token = tokenizer.NextToken(); } } // Otherwise use the command verbatim else batchableCommandText = CommandText; } return batchableCommandText; } #endregion protected override void Dispose(bool disposing) { if (disposing) { if (statement != null && statement.IsPrepared) statement.CloseStatement(); } base.Dispose(disposing); } /// /// Gets or sets a value indicating whether the command object should be visible in a Windows Form Designer control. /// #if !CF [Browsable(false)] #endif public override bool DesignTimeVisible { get { return designTimeVisible; } set { designTimeVisible = value; } } /// /// Gets or sets how command results are applied to the DataRow when used by the /// Update method of the DbDataAdapter. /// public override UpdateRowSource UpdatedRowSource { get { return updatedRowSource; } set { updatedRowSource = value; } } protected override DbParameter CreateDbParameter() { return new MySqlParameter(); } protected override DbConnection DbConnection { get { return Connection; } set { Connection = (MySqlConnection)value; } } protected override DbParameterCollection DbParameterCollection { get { return Parameters; } } protected override DbTransaction DbTransaction { get { return Transaction; } set { Transaction = (MySqlTransaction)value; } } protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { return ExecuteReader(behavior); } } } mysql-connector-net-6.4.3/Source/MySql.Data/ProcedureCache.cs0000644000175000017500000001376611127003600024550 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Data; using System.Collections.Generic; using MySql.Data.MySqlClient.Properties; using System.Diagnostics; using System.Text; using System.Globalization; namespace MySql.Data.MySqlClient { internal class ProcedureCache { private Hashtable procHash; private Queue hashQueue; private int maxSize; public ProcedureCache(int size) { maxSize = size; hashQueue = new Queue(maxSize); procHash = new Hashtable(maxSize); } public DataSet GetProcedure(MySqlConnection conn, string spName, string cacheKey) { DataSet ds = null; if (cacheKey != null) { int hash = cacheKey.GetHashCode(); lock (procHash.SyncRoot) { ds = (DataSet)procHash[hash]; } } if (ds == null) { ds = AddNew(conn, spName); #if !CF conn.PerfMonitor.AddHardProcedureQuery(); #endif if (conn.Settings.Logging) MySqlTrace.LogInformation(conn.ServerThread, String.Format(Resources.HardProcQuery, spName)); } else { #if !CF conn.PerfMonitor.AddSoftProcedureQuery(); #endif if (conn.Settings.Logging) MySqlTrace.LogInformation(conn.ServerThread, String.Format(Resources.SoftProcQuery, spName)); } return ds; } internal string GetCacheKey(string spName, DataSet procData) { string retValue = String.Empty; StringBuilder key = new StringBuilder(spName); key.Append("("); string delimiter = ""; if (procData.Tables.Contains("Procedure Parameters")) { foreach (DataRow row in procData.Tables["Procedure Parameters"].Rows) { if (row["ORDINAL_POSITION"].Equals(0)) retValue = "?="; else { key.AppendFormat(CultureInfo.InvariantCulture, "{0}?", delimiter); delimiter = ","; } } } key.Append(")"); return retValue + key.ToString(); } private DataSet AddNew(MySqlConnection connection, string spName) { DataSet procData = GetProcData(connection, spName); if (maxSize > 0) { string cacheKey = GetCacheKey(spName, procData); int hash = cacheKey.GetHashCode(); lock (procHash.SyncRoot) { if (procHash.Keys.Count >= maxSize) TrimHash(); if (!procHash.ContainsKey(hash)) { procHash[hash] = procData; hashQueue.Enqueue(hash); } } } return procData; } private void TrimHash() { int oldestHash = hashQueue.Dequeue(); procHash.Remove(oldestHash); } private static DataSet GetProcData(MySqlConnection connection, string spName) { string schema = String.Empty; string name = spName; int dotIndex = spName.IndexOf("."); if (dotIndex != -1) { schema = spName.Substring(0, dotIndex); name = spName.Substring(dotIndex + 1, spName.Length - dotIndex - 1); } string[] restrictions = new string[4]; restrictions[1] = schema.Length > 0 ? schema : connection.CurrentDatabase(); restrictions[2] = name; DataTable procTable = connection.GetSchema("procedures", restrictions); if (procTable.Rows.Count > 1) throw new MySqlException(Resources.ProcAndFuncSameName); if (procTable.Rows.Count == 0) throw new MySqlException(String.Format(Resources.InvalidProcName, name, schema)); DataSet ds = new DataSet(); ds.Tables.Add(procTable); // we don't use GetSchema here because that would cause another // query of procedures and we don't need that since we already // know the procedure we care about. ISSchemaProvider isp = new ISSchemaProvider(connection); string[] rest = isp.CleanRestrictions(restrictions); DataTable parametersTable = isp.GetProcedureParameters(rest, procTable); ds.Tables.Add(parametersTable); return ds; } } }mysql-connector-net-6.4.3/Source/MySql.Data/SSPI.cs0000644000175000017500000003472411127003600022447 0ustar directhexdirecthex// Copyright (c) 2010 Oracle and its affiliates. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using System.Net.Sockets; using HANDLE = System.IntPtr; using System; using System.IO; namespace MySql.Data.MySqlClient { internal class SSPI { const int SEC_E_OK = 0; const int SEC_I_CONTINUE_NEEDED = 0x90312; const int SEC_I_COMPLETE_NEEDED = 0x1013; const int SEC_I_COMPLETE_AND_CONTINUE = 0x1014; const int SECPKG_CRED_OUTBOUND = 2; const int SECURITY_NETWORK_DREP = 0; const int SECURITY_NATIVE_DREP = 0x10; const int SECPKG_CRED_INBOUND = 1; const int MAX_TOKEN_SIZE = 12288; const int SECPKG_ATTR_SIZES = 0; const int STANDARD_CONTEXT_ATTRIBUTES = 0; SECURITY_HANDLE outboundCredentials = new SECURITY_HANDLE(0); SECURITY_HANDLE clientContext = new SECURITY_HANDLE(0); Stream stream; String targetName; byte[] packetHeader; int seq = 3; [DllImport("secur32", CharSet = CharSet.Auto)] static extern int AcquireCredentialsHandle( string pszPrincipal, string pszPackage, int fCredentialUse, IntPtr PAuthenticationID, IntPtr pAuthData, int pGetKeyFn, IntPtr pvGetKeyArgument, ref SECURITY_HANDLE phCredential, ref SECURITY_INTEGER ptsExpiry); [DllImport("secur32", CharSet = CharSet.Auto, SetLastError = true)] static extern int InitializeSecurityContext( ref SECURITY_HANDLE phCredential, IntPtr phContext, string pszTargetName, int fContextReq, int Reserved1, int TargetDataRep, IntPtr pInput, int Reserved2, out SECURITY_HANDLE phNewContext, out SecBufferDesc pOutput, out uint pfContextAttr, out SECURITY_INTEGER ptsExpiry); [DllImport("secur32", CharSet = CharSet.Auto, SetLastError = true)] static extern int InitializeSecurityContext( ref SECURITY_HANDLE phCredential, ref SECURITY_HANDLE phContext, string pszTargetName, int fContextReq, int Reserved1, int TargetDataRep, ref SecBufferDesc SecBufferDesc, int Reserved2, out SECURITY_HANDLE phNewContext, out SecBufferDesc pOutput, out uint pfContextAttr, out SECURITY_INTEGER ptsExpiry); [DllImport("secur32", CharSet = CharSet.Auto, SetLastError = true)] static extern int CompleteAuthToken( ref SECURITY_HANDLE phContext, ref SecBufferDesc pToken ); [DllImport("secur32.Dll", CharSet = CharSet.Auto, SetLastError = false)] public static extern int QueryContextAttributes( ref SECURITY_HANDLE phContext, uint ulAttribute, out SecPkgContext_Sizes pContextAttributes); [DllImport("secur32.Dll", CharSet = CharSet.Auto, SetLastError = false)] public static extern int FreeCredentialsHandle(ref SECURITY_HANDLE pCred); [DllImport("secur32.Dll", CharSet = CharSet.Auto, SetLastError = false)] public static extern int DeleteSecurityContext(ref SECURITY_HANDLE pCred); public SSPI(string targetName, Stream stream, int seqNo) { this.targetName = null; this.stream = stream; packetHeader = new byte[4]; seq = seqNo; } // Read MySQL packet // since SSPI blobs data cannot be larger than ~12K, // handling just single packet is sufficient private byte[] ReadData() { byte[] buffer; MySqlStream.ReadFully(stream, packetHeader, 0, 4); int length = (int)(packetHeader[0] + (packetHeader[1] << 8) + (packetHeader[2] << 16)); seq = packetHeader[3]+1; buffer = new byte[length]; MySqlStream.ReadFully(stream, buffer, 0, length); return buffer; } // Write MySQL packet private void WriteData(byte[] buffer) { int count = buffer.Length; packetHeader[0] = (byte)(count & 0xff); packetHeader[1] = (byte)((count >> 8) & 0xff); packetHeader[2] = (byte)((count >> 16) & 0xff); packetHeader[3] = (byte)(seq); stream.Write(packetHeader, 0, 4); stream.Write(buffer, 0, count); stream.Flush(); } public void AuthenticateClient() { bool continueProcessing = true; byte[] clientBlob = null; byte[] serverBlob = null; SECURITY_INTEGER lifetime = new SECURITY_INTEGER(0); int ss; ss = AcquireCredentialsHandle(null, "Negotiate", SECPKG_CRED_OUTBOUND, IntPtr.Zero, IntPtr.Zero, 0, IntPtr.Zero, ref outboundCredentials, ref lifetime); if(ss != SEC_E_OK) { throw new MySqlException( "AcquireCredentialsHandle failed with errorcode" + ss); } try { while (continueProcessing) { InitializeClient(out clientBlob, serverBlob, out continueProcessing); if (clientBlob != null && clientBlob.Length > 0) { WriteData(clientBlob); if (continueProcessing) serverBlob = ReadData(); } } } finally { FreeCredentialsHandle(ref outboundCredentials); DeleteSecurityContext(ref clientContext); } } void InitializeClient(out byte[] clientBlob, byte[] serverBlob, out bool continueProcessing) { clientBlob = null; continueProcessing = true; SecBufferDesc clientBufferDesc = new SecBufferDesc(MAX_TOKEN_SIZE); SECURITY_INTEGER lifetime = new SECURITY_INTEGER(0); int ss = -1; try { uint ContextAttributes = 0; if (serverBlob == null) { ss = InitializeSecurityContext( ref outboundCredentials, IntPtr.Zero, targetName, STANDARD_CONTEXT_ATTRIBUTES, 0, SECURITY_NETWORK_DREP, IntPtr.Zero, /* always zero first time around */ 0, out clientContext, out clientBufferDesc, out ContextAttributes, out lifetime); } else { String s = System.Text.Encoding.UTF8.GetString(serverBlob, 0, serverBlob.Length); SecBufferDesc serverBufferDesc = new SecBufferDesc(serverBlob); try { ss = InitializeSecurityContext(ref outboundCredentials, ref clientContext, targetName, STANDARD_CONTEXT_ATTRIBUTES, 0, SECURITY_NETWORK_DREP, ref serverBufferDesc, 0, out clientContext, out clientBufferDesc, out ContextAttributes, out lifetime); } finally { serverBufferDesc.Dispose(); } } if ((SEC_I_COMPLETE_NEEDED == ss) || (SEC_I_COMPLETE_AND_CONTINUE == ss)) { CompleteAuthToken(ref clientContext, ref clientBufferDesc); } if (ss != SEC_E_OK && ss != SEC_I_CONTINUE_NEEDED && ss != SEC_I_COMPLETE_NEEDED && ss != SEC_I_COMPLETE_AND_CONTINUE) { throw new MySqlException( "InitializeSecurityContext() failed with errorcode "+ss); } clientBlob = clientBufferDesc.GetSecBufferByteArray(); } finally { clientBufferDesc.Dispose(); } continueProcessing = (ss != SEC_E_OK && ss != SEC_I_COMPLETE_NEEDED); } } [StructLayout(LayoutKind.Sequential)] struct SecBufferDesc : IDisposable { public int ulVersion; public int cBuffers; public IntPtr pBuffers; //Point to SecBuffer public SecBufferDesc(int bufferSize) { ulVersion = (int)SecBufferType.SECBUFFER_VERSION; cBuffers = 1; SecBuffer secBuffer = new SecBuffer(bufferSize); pBuffers = Marshal.AllocHGlobal(Marshal.SizeOf(secBuffer)); Marshal.StructureToPtr(secBuffer, pBuffers, false); } public SecBufferDesc(byte[] secBufferBytes) { ulVersion = (int)SecBufferType.SECBUFFER_VERSION; cBuffers = 1; SecBuffer ThisSecBuffer = new SecBuffer(secBufferBytes); pBuffers = Marshal.AllocHGlobal(Marshal.SizeOf(ThisSecBuffer)); Marshal.StructureToPtr(ThisSecBuffer, pBuffers, false); } public void Dispose() { if (pBuffers != IntPtr.Zero) { Debug.Assert(cBuffers == 1); SecBuffer ThisSecBuffer = (SecBuffer)Marshal.PtrToStructure(pBuffers, typeof(SecBuffer)); ThisSecBuffer.Dispose(); Marshal.FreeHGlobal(pBuffers); pBuffers = IntPtr.Zero; } } public byte[] GetSecBufferByteArray() { byte[] Buffer = null; if (pBuffers == IntPtr.Zero) { throw new InvalidOperationException("Object has already been disposed!!!"); } Debug.Assert(cBuffers == 1); SecBuffer secBuffer = (SecBuffer)Marshal.PtrToStructure(pBuffers, typeof(SecBuffer)); if (secBuffer.cbBuffer > 0) { Buffer = new byte[secBuffer.cbBuffer]; Marshal.Copy(secBuffer.pvBuffer, Buffer, 0, secBuffer.cbBuffer); } return (Buffer); } } public enum SecBufferType { SECBUFFER_VERSION = 0, SECBUFFER_EMPTY = 0, SECBUFFER_DATA = 1, SECBUFFER_TOKEN = 2 } [StructLayout(LayoutKind.Sequential)] public struct SecHandle //=PCtxtHandle { IntPtr dwLower; // ULONG_PTR translates to IntPtr not to uint IntPtr dwUpper; // this is crucial for 64-Bit Platforms } [StructLayout(LayoutKind.Sequential)] public struct SecBuffer : IDisposable { public int cbBuffer; public int BufferType; public IntPtr pvBuffer; public SecBuffer(int bufferSize) { cbBuffer = bufferSize; BufferType = (int)SecBufferType.SECBUFFER_TOKEN; pvBuffer = Marshal.AllocHGlobal(bufferSize); } public SecBuffer(byte[] secBufferBytes) { cbBuffer = secBufferBytes.Length; BufferType = (int)SecBufferType.SECBUFFER_TOKEN; pvBuffer = Marshal.AllocHGlobal(cbBuffer); Marshal.Copy(secBufferBytes, 0, pvBuffer, cbBuffer); } public SecBuffer(byte[] secBufferBytes, SecBufferType bufferType) { cbBuffer = secBufferBytes.Length; BufferType = (int)bufferType; pvBuffer = Marshal.AllocHGlobal(cbBuffer); Marshal.Copy(secBufferBytes, 0, pvBuffer, cbBuffer); } public void Dispose() { if (pvBuffer != IntPtr.Zero) { Marshal.FreeHGlobal(pvBuffer); pvBuffer = IntPtr.Zero; } } } [StructLayout(LayoutKind.Sequential)] public struct SECURITY_INTEGER { public uint LowPart; public int HighPart; public SECURITY_INTEGER(int dummy) { LowPart = 0; HighPart = 0; } }; [StructLayout(LayoutKind.Sequential)] public struct SECURITY_HANDLE { public uint LowPart; public uint HighPart; public SECURITY_HANDLE(int dummy) { LowPart = HighPart = 0; } }; [StructLayout(LayoutKind.Sequential)] public struct SecPkgContext_Sizes { public uint cbMaxToken; public uint cbMaxSignature; public uint cbBlockSize; public uint cbSecurityTrailer; }; } mysql-connector-net-6.4.3/Source/MySql.Data/MySqlTrace.cs0000644000175000017500000001156411127003600023712 0ustar directhexdirecthex// Copyright (c) 2009-2010 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Reflection; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { public class MySqlTrace { private static string qaHost; private static bool qaEnabled = false; #if !CF private static TraceSource source = new TraceSource("mysql"); static MySqlTrace() { foreach (TraceListener listener in source.Listeners) { if (listener.GetType().ToString().Contains("MySql.EMTrace.EMTraceListener")) { qaEnabled = true; break; } } } public static TraceListenerCollection Listeners { get { return source.Listeners; } } public static SourceSwitch Switch { get { return source.Switch; } set { source.Switch = value; } } public static bool QueryAnalysisEnabled { get { return qaEnabled; } } public static void EnableQueryAnalyzer(string host, int postInterval) { if (qaEnabled) return; // create a EMTraceListener and add it to our source TraceListener l = (TraceListener)Activator.CreateInstance("MySql.EMTrace", "MySql.EMTrace.EMTraceListener", false, BindingFlags.CreateInstance, null, new object[] { host, postInterval }, null, null, null).Unwrap(); if (l == null) throw new MySqlException(Resources.UnableToEnableQueryAnalysis); source.Listeners.Add(l); Switch.Level = SourceLevels.All; } public static void DisableQueryAnalyzer() { qaEnabled = false; foreach (TraceListener l in source.Listeners) if (l.GetType().ToString().Contains("EMTraceListener")) { source.Listeners.Remove(l); break; } } internal static TraceSource Source { get { return source; } } #endif internal static void LogInformation(int id, string msg) { #if !CF Source.TraceEvent(TraceEventType.Information, id, msg, MySqlTraceEventType.NonQuery, -1); Trace.TraceInformation(msg); #endif } internal static void LogWarning(int id, string msg) { #if !CF Source.TraceEvent(TraceEventType.Warning, id, msg, MySqlTraceEventType.NonQuery, -1); Trace.TraceWarning(msg); #endif } internal static void LogError(int id, string msg) { #if !CF Source.TraceEvent(TraceEventType.Error, id, msg, MySqlTraceEventType.NonQuery, -1); Trace.TraceError(msg); #endif } #if !CF internal static void TraceEvent(TraceEventType eventType, MySqlTraceEventType mysqlEventType, string msgFormat, params object[] args) { Source.TraceEvent(eventType, (int)mysqlEventType, msgFormat, args); } #endif } public enum MySqlTraceEventType : int { ConnectionOpened = 1, ConnectionClosed, QueryOpened, ResultOpened, ResultClosed, QueryClosed, StatementPrepared, StatementExecuted, StatementClosed, NonQuery, UsageAdvisorWarning, Warning, Error, QueryNormalized } public enum UsageAdvisorWarningFlags { NoIndex = 1, BadIndex, SkippedRows, SkippedColumns, FieldConversion } } mysql-connector-net-6.4.3/Source/MySql.Data/Driver.cs0000644000175000017500000004265111127003600023122 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Globalization; using System.Text; using MySql.Data.Common; using MySql.Data.Types; using MySql.Data.MySqlClient.Properties; using System.Diagnostics; using System.Collections.Generic; using System.Security; namespace MySql.Data.MySqlClient { /// /// Summary description for BaseDriver. /// internal class Driver : IDisposable { protected Encoding encoding; protected MySqlConnectionStringBuilder connectionString; protected bool isOpen; protected DateTime creationTime; protected string serverCharSet; protected int serverCharSetIndex; protected Hashtable serverProps; protected Hashtable charSets; protected long maxPacketSize; private DateTime idleSince; #if !CF protected MySqlPromotableTransaction currentTransaction; protected bool inActiveUse; #endif protected MySqlPool pool; private bool firstResult; protected IDriver handler; internal MySqlDataReader reader; private bool disposeInProgress; /// /// For pooled connections, time when the driver was /// put into idle queue /// public DateTime IdleSince { get { return idleSince; } set { idleSince = value; } } public Driver(MySqlConnectionStringBuilder settings) { encoding = Encoding.GetEncoding(1252); if (encoding == null) throw new MySqlException(Resources.DefaultEncodingNotFound); connectionString = settings; serverCharSet = "latin1"; serverCharSetIndex = -1; maxPacketSize = 1024; handler = new NativeDriver(this); } ~Driver() { Dispose(false); } #region Properties public int ThreadID { get { return handler.ThreadId; } } public DBVersion Version { get { return handler.Version; } } public MySqlConnectionStringBuilder Settings { get { return connectionString; } set { connectionString = value; } } public Encoding Encoding { get { return encoding; } set { encoding = value; } } #if !CF public MySqlPromotableTransaction CurrentTransaction { get { return currentTransaction; } set { currentTransaction = value; } } public bool IsInActiveUse { get { return inActiveUse; } set { inActiveUse = value; } } #endif public bool IsOpen { get { return isOpen; } } public MySqlPool Pool { get { return pool; } set { pool = value; } } public long MaxPacketSize { get { return maxPacketSize; } } internal int ConnectionCharSetIndex { get { return serverCharSetIndex; } set { serverCharSetIndex = value; } } internal Hashtable CharacterSets { get { return charSets; } } public bool SupportsOutputParameters { get { return Version.isAtLeast(5,5,0); } } public bool SupportsBatch { get { return (handler.Flags & ClientFlags.MULTI_STATEMENTS) != 0; } } #endregion public string Property(string key) { return (string) serverProps[key]; } public bool ConnectionLifetimeExpired() { TimeSpan ts = DateTime.Now.Subtract(creationTime); if (Settings.ConnectionLifeTime != 0 && ts.TotalSeconds > Settings.ConnectionLifeTime) return true; return false; } public static Driver Create(MySqlConnectionStringBuilder settings) { Driver d = null; #if !CF try { if (MySqlTrace.QueryAnalysisEnabled || settings.Logging || settings.UseUsageAdvisor) d = new TracingDriver(settings); } catch (TypeInitializationException ex) { if (!(ex.InnerException is SecurityException)) throw ex; //Only rethrow if InnerException is not a SecurityException. If it is a SecurityException then //we couldn't initialize MySqlTrace because we don't have unmanaged code permissions. } #endif if ( d == null ) d = new Driver(settings); d.Open(); return d; } public bool HasStatus(ServerStatusFlags flag) { return (handler.ServerStatus & flag) != 0; } public virtual void Open() { creationTime = DateTime.Now; handler.Open(); isOpen = true; } public virtual void Close() { Dispose(); } public virtual void Configure(MySqlConnection connection) { bool firstConfigure = false; // if we have not already configured our server variables // then do so now if (serverProps == null) { firstConfigure = true; // if we are in a pool and the user has said it's ok to cache the // properties, then grab it from the pool if (Pool != null && Settings.CacheServerProperties) { if (Pool.ServerProperties == null) Pool.ServerProperties = LoadServerProperties(connection); serverProps = Pool.ServerProperties; } else serverProps = LoadServerProperties(connection); LoadCharacterSets(connection); } #if AUTHENTICATED string licenseType = serverProps["license"]; if (licenseType == null || licenseType.Length == 0 || licenseType != "commercial") throw new MySqlException( "This client library licensed only for use with commercially-licensed MySQL servers." ); #endif // if the user has indicated that we are not to reset // the connection and this is not our first time through, // then we are done. if (!Settings.ConnectionReset && !firstConfigure) return; string charSet = connectionString.CharacterSet; if (charSet == null || charSet.Length == 0) { if (serverCharSetIndex >= 0) charSet = (string) charSets[serverCharSetIndex]; else charSet = serverCharSet; } // now tell the server which character set we will send queries in and which charset we // want results in MySqlCommand charSetCmd = new MySqlCommand("SET character_set_results=NULL", connection); charSetCmd.InternallyCreated = true; object clientCharSet = serverProps["character_set_client"]; object connCharSet = serverProps["character_set_connection"]; if ((clientCharSet != null && clientCharSet.ToString() != charSet) || (connCharSet != null && connCharSet.ToString() != charSet)) { MySqlCommand setNamesCmd = new MySqlCommand("SET NAMES " + charSet, connection); setNamesCmd.InternallyCreated = true; setNamesCmd.ExecuteNonQuery(); } charSetCmd.ExecuteNonQuery(); if (charSet != null) Encoding = CharSetMap.GetEncoding(Version, charSet); else Encoding = CharSetMap.GetEncoding(Version, "latin1"); handler.Configure(); } /// /// Loads the properties from the connected server into a hashtable /// /// /// private Hashtable LoadServerProperties(MySqlConnection connection) { // load server properties Hashtable hash = new Hashtable(); MySqlCommand cmd = new MySqlCommand("SHOW VARIABLES", connection); using (MySqlDataReader reader = cmd.ExecuteReader()) { try { while (reader.Read()) { string key = reader.GetString(0); string value = reader.GetString(1); hash[key] = value; } } catch (Exception ex) { MySqlTrace.LogError(ThreadID, ex.Message); throw; } } if (hash.Contains("max_allowed_packet")) maxPacketSize = Convert.ToInt64(hash["max_allowed_packet"]); return hash; } /// /// Loads all the current character set names and ids for this server /// into the charSets hashtable /// private void LoadCharacterSets(MySqlConnection connection) { MySqlCommand cmd = new MySqlCommand("SHOW COLLATION", connection); // now we load all the currently active collations try { using (MySqlDataReader reader = cmd.ExecuteReader()) { charSets = new Hashtable(); while (reader.Read()) { charSets[Convert.ToInt32(reader["id"], NumberFormatInfo.InvariantInfo)] = reader.GetString(reader.GetOrdinal("charset")); } } } catch (Exception ex) { MySqlTrace.LogError(ThreadID, ex.Message); throw; } } public virtual List ReportWarnings(MySqlConnection connection) { List warnings = new List(); MySqlCommand cmd = new MySqlCommand("SHOW WARNINGS", connection); cmd.InternallyCreated = true; using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { warnings.Add(new MySqlError(reader.GetString(0), reader.GetInt32(1), reader.GetString(2))); } } MySqlInfoMessageEventArgs args = new MySqlInfoMessageEventArgs(); args.errors = warnings.ToArray(); if (connection != null) connection.OnInfoMessage(args); return warnings; } public virtual void SendQuery(MySqlPacket p) { handler.SendQuery(p); firstResult = true; } public virtual ResultSet NextResult(int statementId, bool force) { if (!force && !firstResult && !HasStatus(ServerStatusFlags.AnotherQuery | ServerStatusFlags.MoreResults)) return null; firstResult = false; int affectedRows = -1, insertedId = -1, warnings = 0; int fieldCount = GetResult(statementId, ref affectedRows, ref insertedId); if (fieldCount == -1) return null; if (fieldCount > 0) return new ResultSet(this, statementId, fieldCount); else return new ResultSet(affectedRows, insertedId); } protected virtual int GetResult(int statementId, ref int affectedRows, ref int insertedId) { return handler.GetResult(ref affectedRows, ref insertedId); } public virtual bool FetchDataRow(int statementId, int columns) { return handler.FetchDataRow(statementId, columns); } public virtual bool SkipDataRow() { return FetchDataRow(-1, 0); } public virtual void ExecuteDirect(string sql) { MySqlPacket p = new MySqlPacket(Encoding); p.WriteString(sql); SendQuery(p); NextResult(0, false); } public MySqlField[] GetColumns(int count) { MySqlField[] fields = new MySqlField[count]; for (int i = 0; i < count; i++) fields[i] = new MySqlField(this); handler.GetColumnsData(fields); return fields; } public virtual int PrepareStatement(string sql, ref MySqlField[] parameters) { return handler.PrepareStatement(sql, ref parameters); } public IMySqlValue ReadColumnValue(int index, MySqlField field, IMySqlValue value) { return handler.ReadColumnValue(index, field, value); } public void SkipColumnValue(IMySqlValue valObject) { handler.SkipColumnValue(valObject); } public void ResetTimeout(int timeoutMilliseconds) { handler.ResetTimeout(timeoutMilliseconds); } public bool Ping() { return handler.Ping(); } public virtual void SetDatabase(string dbName) { handler.SetDatabase(dbName); } public virtual void ExecuteStatement(MySqlPacket packetToExecute) { handler.ExecuteStatement(packetToExecute); } public virtual void CloseStatement(int id) { handler.CloseStatement(id); } public virtual void Reset() { handler.Reset(); } public virtual void CloseQuery(MySqlConnection connection, int statementId) { if (handler.WarningCount > 0) ReportWarnings(connection); } #region IDisposable Members protected virtual void Dispose(bool disposing) { // Avoid cyclic calls to Dispose. if (disposeInProgress) return; disposeInProgress = true; try { ResetTimeout(1000); if (disposing) handler.Close(isOpen); // if we are pooling, then release ourselves if (connectionString.Pooling) MySqlPoolManager.RemoveConnection(this); } catch (Exception) { if (disposing) throw; } finally { reader = null; isOpen = false; disposeInProgress = false; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } internal interface IDriver { int ThreadId { get; } DBVersion Version { get; } ServerStatusFlags ServerStatus { get; } ClientFlags Flags { get; } void Configure(); void Open(); void SendQuery(MySqlPacket packet); void Close(bool isOpen); bool Ping(); int GetResult(ref int affectedRows, ref int insertedId); bool FetchDataRow(int statementId, int columns); int PrepareStatement(string sql, ref MySqlField[] parameters); void ExecuteStatement(MySqlPacket packet); void CloseStatement(int statementId); void SetDatabase(string dbName); void Reset(); IMySqlValue ReadColumnValue(int index, MySqlField field, IMySqlValue valObject); void SkipColumnValue(IMySqlValue valueObject); void GetColumnsData(MySqlField[] columns); void ResetTimeout(int timeout); int WarningCount { get; } } } mysql-connector-net-6.4.3/Source/MySql.Data/MySqlPoolManager.cs0000644000175000017500000001462511127003600025061 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Collections; using System.Diagnostics; using System.Collections.Generic; using System.Threading; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { /// /// Summary description for MySqlPoolManager. /// internal class MySqlPoolManager { private static Hashtable pools = new Hashtable(); private static List clearingPools = new List(); // Timeout in seconds, after which an unused (idle) connection // should be closed. static internal int maxConnectionIdleTime = 180; private static Timer timer = new Timer(new TimerCallback(CleanIdleConnections), null, maxConnectionIdleTime*1000, maxConnectionIdleTime*1000); private static string GetKey(MySqlConnectionStringBuilder settings) { string key = settings.ConnectionString; #if !CF if(settings.IntegratedSecurity && !settings.ConnectionReset) { try { // Append SID to the connection string to generate a key // With Integrated security different Windows users with the same // connection string may be mapped to different MySQL accounts. System.Security.Principal.WindowsIdentity id = System.Security.Principal.WindowsIdentity.GetCurrent(); key += ";" + id.User; } catch (System.Security.SecurityException ex) { // Documentation for WindowsIdentity.GetCurrent() states // SecurityException can be thrown. In this case the // connection can only be pooled if reset is done. throw new MySqlException(Resources.NoWindowsIdentity, ex ); } } #endif return key; } public static MySqlPool GetPool(MySqlConnectionStringBuilder settings) { string text = GetKey(settings); lock (pools.SyncRoot) { MySqlPool pool = (pools[text] as MySqlPool); if (pool == null) { pool = new MySqlPool(settings); pools.Add(text, pool); } else pool.Settings = settings; return pool; } } public static void RemoveConnection(Driver driver) { Debug.Assert(driver != null); MySqlPool pool = driver.Pool; if (pool == null) return; pool.RemoveConnection(driver); } public static void ReleaseConnection(Driver driver) { Debug.Assert(driver != null); MySqlPool pool = driver.Pool; if (pool == null) return; pool.ReleaseConnection(driver); } public static void ClearPool(MySqlConnectionStringBuilder settings) { Debug.Assert(settings != null); string text; try { text = GetKey(settings); } catch (MySqlException) { // Cannot retrieve windows identity for IntegratedSecurity=true // This can be ignored. return; } ClearPoolByText(text); } private static void ClearPoolByText(string key) { lock (pools.SyncRoot) { // if pools doesn't have it, then this pool must already have been cleared if (!pools.ContainsKey(key)) return; // add the pool to our list of pools being cleared MySqlPool pool = (pools[key] as MySqlPool); clearingPools.Add(pool); // now tell the pool to clear itself pool.Clear(); // and then remove the pool from the active pools list pools.Remove(key); } } public static void ClearAllPools() { lock (pools.SyncRoot) { // Create separate keys list. List keys = new List(pools.Count); foreach (string key in pools.Keys) keys.Add(key); // Remove all pools by key. foreach (string key in keys) ClearPoolByText(key); } } public static void RemoveClearedPool(MySqlPool pool) { Debug.Assert(clearingPools.Contains(pool)); clearingPools.Remove(pool); } /// /// Remove drivers that have been idle for too long. /// public static void CleanIdleConnections(object obj) { List oldDrivers = new List(); lock (pools.SyncRoot) { foreach (string key in pools.Keys) { MySqlPool pool = (pools[key] as MySqlPool); oldDrivers.AddRange(pool.RemoveOldIdleConnections()); } } foreach(Driver driver in oldDrivers) { driver.Close(); } } } }mysql-connector-net-6.4.3/Source/MySql.Data/Crypt.cs0000644000175000017500000003215711127003600022770 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Globalization; using System.Text; using MySql.Data.Common; using MySql.Data.MySqlClient.Properties; //using System.Security.Cryptography; //#if CF //using OpenNETCF.Security.Cryptography; //#endif namespace MySql.Data.MySqlClient { /// /// Summary description for Crypt. /// internal class Crypt { // private ctor to prevent creating a default one private Crypt() { } /* private void Create41Password( string password ) { SHA1 sha = new SHA1CryptoServiceProvider(); byte[] firstPassBytes = sha.ComputeHash( System.Text.Encoding.Default.GetBytes( password )); byte[] salt = packet.GetBuffer(); byte[] input = new byte[ firstPassBytes.Length + 4 ]; salt.CopyTo( input, 0 ); firstPassBytes.CopyTo( input, 4 ); byte[] outPass = new byte[100]; byte[] secondPassBytes = sha.ComputeHash( input ); byte[] cryptSalt = new byte[20]; Security.ArrayCrypt( salt, 4, cryptSalt, 0, secondPassBytes, 20 ); Security.ArrayCrypt( cryptSalt, 0, firstPassBytes, 0, firstPassBytes, 20 ); // send the packet packet = CreatePacket(null); packet.Write( firstPassBytes, 0, 20 ); SendPacket(packet); } */ /// /// Simple XOR scramble /// /// Source array /// Index inside source array /// Destination array /// Index inside destination array /// Password used to xor the bits /// Number of bytes to scramble private static void XorScramble(byte[] from, int fromIndex, byte[] to, int toIndex, byte[] password, int length) { // make sure we were called properly if (fromIndex < 0 || fromIndex >= from.Length) throw new ArgumentException(Resources.IndexMustBeValid, "fromIndex"); if ((fromIndex + length) > from.Length) throw new ArgumentException(Resources.FromAndLengthTooBig, "fromIndex"); if (from == null) throw new ArgumentException(Resources.BufferCannotBeNull, "from"); if (to == null) throw new ArgumentException(Resources.BufferCannotBeNull, "to"); if (toIndex < 0 || toIndex >= to.Length) throw new ArgumentException(Resources.IndexMustBeValid, "toIndex"); if ((toIndex + length) > to.Length) throw new ArgumentException(Resources.IndexAndLengthTooBig, "toIndex"); if (password == null || password.Length < length) throw new ArgumentException(Resources.PasswordMustHaveLegalChars, "password"); if (length < 0) throw new ArgumentException(Resources.ParameterCannotBeNegative, "count"); // now perform the work for (int i = 0; i < length; i++) to[toIndex++] = (byte) (from[fromIndex++] ^ password[i]); } /// /// Generate a scrambled password for 4.1.0 using new passwords /// /// The password to scramble /// The seedbytes used to scramble /// Array of bytes containing the scrambled password public static byte[] Get410Password(string password, byte[] seedBytes) { SHA1Hash sha = new SHA1Hash(); //SHA1 sha = new SHA1CryptoServiceProvider(); // clean it and then digest it password = password.Replace(" ", "").Replace("\t", ""); byte[] passBytes = Encoding.Default.GetBytes(password); byte[] firstPass = sha.ComputeHash(passBytes); byte[] input = new byte[24]; Array.Copy(seedBytes, 0, input, 0, 4); Array.Copy(firstPass, 0, input, 4, 20); byte[] secondPass = sha.ComputeHash(input); byte[] scrambledBuff = new byte[20]; XorScramble(seedBytes, 4, scrambledBuff, 0, secondPass, 20); byte[] finalBuff = new byte[20]; XorScramble(scrambledBuff, 0, finalBuff, 0, firstPass, 20); return finalBuff; } /// /// Generates a proper hash for old style 4.1.0 passwords. This would be used /// if a 4.1.0 server contained old 16 byte hashes. /// /// The password to hash /// Seed bytes received from the server /// Byte array containing the password hash public static byte[] GetOld410Password(string password, byte[] seedBytes) { long[] passwordHash = Hash(password); string passHex = String.Format(CultureInfo.InvariantCulture, "{0,8:X}{1,8:X}", passwordHash[0], passwordHash[1]); int[] salt = getSaltFromPassword(passHex); // compute binary password byte[] binaryPassword = new byte[20]; int offset = 0; for (int i = 0; i < 2; i++) { int val = salt[i]; for (int t = 3; t >= 0; t--) { binaryPassword[t + offset] = (byte) (val%256); val >>= 8; /* Scroll 8 bits to get next part*/ } offset += 4; } //SHA1 sha = new SHA1CryptoServiceProvider(); SHA1Hash sha = new SHA1Hash(); byte[] temp = new byte[8]; Buffer.BlockCopy(binaryPassword, 0, temp, 0, 8); byte[] binaryHash = sha.ComputeHash(temp); byte[] scrambledBuff = new byte[20]; XorScramble(seedBytes, 4, scrambledBuff, 0, binaryHash, 20); string scrambleString = Encoding.Default.GetString(scrambledBuff, 0, scrambledBuff.Length).Substring(0, 8); long[] hashPass = Hash(password); long[] hashMessage = Hash(scrambleString); long max = 0x3FFFFFFFL; byte[] to = new byte[20]; int msgPos = 0; int msgLength = scrambleString.Length; int toPos = 0; long seed1 = (hashPass[0] ^ hashMessage[0])%max; long seed2 = (hashPass[1] ^ hashMessage[1])%max; while (msgPos++ < msgLength) to[toPos++] = (byte) (Math.Floor(rand(ref seed1, ref seed2, max)*31) + 64); /* Make it harder to break */ byte extra = (byte) (Math.Floor(rand(ref seed1, ref seed2, max)*31)); for (int i = 0; i < 8; i++) to[i] ^= extra; return to; } /// /// Returns a byte array containing the proper encryption of the /// given password/seed according to the new 4.1.1 authentication scheme. /// /// /// /// public static byte[] Get411Password(string password, string seed) { // if we have no password, then we just return 1 zero byte if (password.Length == 0) return new byte[1]; //SHA1 sha = new SHA1CryptoServiceProvider(); SHA1Hash sha = new SHA1Hash(); byte[] firstHash = sha.ComputeHash(Encoding.Default.GetBytes(password)); byte[] secondHash = sha.ComputeHash(firstHash); byte[] seedBytes = Encoding.Default.GetBytes(seed); byte[] input = new byte[seedBytes.Length + secondHash.Length]; Array.Copy(seedBytes, 0, input, 0, seedBytes.Length); Array.Copy(secondHash, 0, input, seedBytes.Length, secondHash.Length); byte[] thirdHash = sha.ComputeHash(input); byte[] finalHash = new byte[thirdHash.Length + 1]; finalHash[0] = 0x14; Array.Copy(thirdHash, 0, finalHash, 1, thirdHash.Length); for (int i = 1; i < finalHash.Length; i++) finalHash[i] = (byte) (finalHash[i] ^ firstHash[i - 1]); return finalHash; } private static int[] getSaltFromPassword(String password) { int[] result = new int[6]; if (password == null || password.Length == 0) return result; int resultPos = 0; int pos = 0; while (pos < password.Length) { int val = 0; for (int i = 0; i < 8; i++) val = (val << 4) + HexValue(password[pos++]); result[resultPos++] = val; } return result; } private static int HexValue(char c) { if (c >= 'A' && c <= 'Z') return (c - 'A') + 10; if (c >= 'a' && c <= 'z') return (c - 'a') + 10; return c - '0'; } private static double rand(ref long seed1, ref long seed2, long max) { seed1 = (seed1*3) + seed2; seed1 %= max; seed2 = (seed1 + seed2 + 33)%max; return (seed1/(double) max); } /// /// Encrypts a password using the MySql encryption scheme /// /// The password to encrypt /// The encryption seed the server gave us /// Indicates if we should use the old or new encryption scheme /// public static String EncryptPassword(String password, String seed, bool new_ver) { long max = 0x3fffffff; if (! new_ver) max = 0x01FFFFFF; if (password == null || password.Length == 0) return password; long[] hash_seed = Hash(seed); long[] hash_pass = Hash(password); long seed1 = (hash_seed[0] ^ hash_pass[0])%max; long seed2 = (hash_seed[1] ^ hash_pass[1])%max; if (! new_ver) seed2 = seed1/2; char[] scrambled = new char[seed.Length]; for (int x = 0; x < seed.Length; x++) { double r = rand(ref seed1, ref seed2, max); scrambled[x] = (char) (Math.Floor(r*31) + 64); } if (new_ver) { /* Make it harder to break */ char extra = (char) Math.Floor(rand(ref seed1, ref seed2, max)*31); for (int x = 0; x < scrambled.Length; x++) scrambled[x] ^= extra; } return new string(scrambled); } /// /// Hashes a password using the algorithm from Monty's code. /// The first element in the return is the result of the "old" hash. /// The second element is the rest of the "new" hash. /// /// Password to be hashed /// Two element array containing the hashed values private static long[] Hash(String P) { long val1 = 1345345333; long val2 = 0x12345671; long inc = 7; for (int i = 0; i < P.Length; i++) { if (P[i] == ' ' || P[i] == '\t') continue; long temp = (0xff & P[i]); val1 ^= (((val1 & 63) + inc)*temp) + (val1 << 8); val2 += (val2 << 8) ^ val1; inc += temp; } long[] hash = new long[2]; hash[0] = val1 & 0x7fffffff; hash[1] = val2 & 0x7fffffff; return hash; } } }mysql-connector-net-6.4.3/Source/MySql.Data/MySqlPool.cs0000644000175000017500000002607211127003600023565 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { /// /// Summary description for MySqlPool. /// internal sealed class MySqlPool { private List inUsePool; private Queue idlePool; private MySqlConnectionStringBuilder settings; private uint minSize; private uint maxSize; private ProcedureCache procedureCache; private bool beingCleared; private int available; private AutoResetEvent autoEvent; private void EnqueueIdle(Driver driver) { driver.IdleSince = DateTime.Now; idlePool.Enqueue(driver); } public MySqlPool(MySqlConnectionStringBuilder settings) { minSize = settings.MinimumPoolSize; maxSize = settings.MaximumPoolSize; available = (int)maxSize; autoEvent = new AutoResetEvent(false); if (minSize > maxSize) minSize = maxSize; this.settings = settings; inUsePool = new List((int)maxSize); idlePool = new Queue((int)maxSize); // prepopulate the idle pool to minSize for (int i = 0; i < minSize; i++) EnqueueIdle(CreateNewPooledConnection()); procedureCache = new ProcedureCache((int)settings.ProcedureCacheSize); } #region Properties public MySqlConnectionStringBuilder Settings { get { return settings; } set { settings = value; } } public ProcedureCache ProcedureCache { get { return procedureCache; } } /// /// It is assumed that this property will only be used from inside an active /// lock. /// private bool HasIdleConnections { get { return idlePool.Count > 0; } } private int NumConnections { get { return idlePool.Count + inUsePool.Count; } } /// /// Indicates whether this pool is being cleared. /// public bool BeingCleared { get { return beingCleared; } } internal Hashtable ServerProperties { get; set; } #endregion /// /// It is assumed that this method is only called from inside an active lock. /// private Driver GetPooledConnection() { Driver driver = null; // if we don't have an idle connection but we have room for a new // one, then create it here. lock ((idlePool as ICollection).SyncRoot) { if (HasIdleConnections) driver = idlePool.Dequeue(); } // Obey the connection timeout if (driver != null) { try { driver.ResetTimeout((int)Settings.ConnectionTimeout * 1000); } catch (Exception) { driver.Close(); driver = null; } } if (driver != null) { // first check to see that the server is still alive if (!driver.Ping()) { driver.Close(); driver = null; } else if (settings.ConnectionReset) // if the user asks us to ping/reset pooled connections // do so now driver.Reset(); } if (driver == null) driver = CreateNewPooledConnection(); Debug.Assert(driver != null); lock ((inUsePool as ICollection).SyncRoot) { inUsePool.Add(driver); } return driver; } /// /// It is assumed that this method is only called from inside an active lock. /// private Driver CreateNewPooledConnection() { Debug.Assert((maxSize - NumConnections) > 0, "Pool out of sync."); Driver driver = Driver.Create(settings); driver.Pool = this; return driver; } public void ReleaseConnection(Driver driver) { lock ((inUsePool as ICollection).SyncRoot) { if (inUsePool.Contains(driver)) inUsePool.Remove(driver); } if (driver.ConnectionLifetimeExpired() || beingCleared) { driver.Close(); Debug.Assert(!idlePool.Contains(driver)); } else { lock ((idlePool as ICollection).SyncRoot) { EnqueueIdle(driver); } } Interlocked.Increment(ref available); autoEvent.Set(); } /// /// Removes a connection from the in use pool. The only situations where this method /// would be called are when a connection that is in use gets some type of fatal exception /// or when the connection is being returned to the pool and it's too old to be /// returned. /// /// public void RemoveConnection(Driver driver) { lock ((inUsePool as ICollection).SyncRoot) { if (inUsePool.Contains(driver)) { inUsePool.Remove(driver); Interlocked.Increment(ref available); autoEvent.Set(); } } // if we are being cleared and we are out of connections then have // the manager destroy us. if (beingCleared && NumConnections == 0) MySqlPoolManager.RemoveClearedPool(this); } private Driver TryToGetDriver() { int count = Interlocked.Decrement(ref available); if (count < 0) { Interlocked.Increment(ref available); return null; } try { Driver driver = GetPooledConnection(); return driver; } catch (Exception ex) { MySqlTrace.LogError(-1, ex.Message); Interlocked.Increment(ref available); throw; } } public Driver GetConnection() { int fullTimeOut = (int)settings.ConnectionTimeout * 1000; int timeOut = fullTimeOut; DateTime start = DateTime.Now; while (timeOut > 0) { Driver driver = TryToGetDriver(); if (driver != null) return driver; // We have no tickets right now, lets wait for one. if (!autoEvent.WaitOne(timeOut, false)) break; timeOut = fullTimeOut - (int)DateTime.Now.Subtract(start).TotalMilliseconds; } throw new MySqlException(Resources.TimeoutGettingConnection); } /// /// Clears this pool of all idle connections and marks this pool and being cleared /// so all other connections are closed when they are returned. /// internal void Clear() { lock ((idlePool as ICollection).SyncRoot) { // first, mark ourselves as being cleared beingCleared = true; // then we remove all connections sitting in the idle pool while (idlePool.Count > 0) { Driver d = idlePool.Dequeue(); d.Close(); } // there is nothing left to do here. Now we just wait for all // in use connections to be returned to the pool. When they are // they will be closed. When the last one is closed, the pool will // be destroyed. } } /// /// Remove expired drivers from the idle pool /// /// /// /// Closing driver is a potentially lengthy operation involving network /// IO. Therefore we do not close expired drivers while holding /// idlePool.SyncRoot lock. We just remove the old drivers from the idle /// queue and return them to the caller. The caller will need to close /// them (or let GC close them) /// internal List RemoveOldIdleConnections() { List oldDrivers = new List(); DateTime now = DateTime.Now; lock ((idlePool as ICollection).SyncRoot) { // The drivers appear to be ordered by their age, i.e it is // sufficient to remove them until the first element is not // too old. while(idlePool.Count > minSize) { Driver d = idlePool.Peek(); DateTime expirationTime = d.IdleSince.Add( new TimeSpan(0,0, MySqlPoolManager.maxConnectionIdleTime)); if (expirationTime.CompareTo(now) < 0) { oldDrivers.Add(d); idlePool.Dequeue(); } else { break; } } } return oldDrivers; } } } mysql-connector-net-6.4.3/Source/MySql.Data/MySql.Data.csproj0000644000175000017500000002055711127003600024500 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} Library Properties MySql.Data.MySqlClient MySql.Data 512 v4.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true full false bin\Debug\ DEBUG;TRACE;CLR4 prompt 4 AllRules.ruleset pdbonly true bin\Release\ TRACE;CLR4 prompt 4 AllRules.ruleset Component Component Designer PublicResXFileCodeGenerator Resources.Designer.cs True True Resources.resx CHANGES mysql-connector-net-6.4.3/Source/MySql.Data/Exception.cs0000644000175000017500000000574311127003600023626 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data.Common; #if !CF using System.Runtime.Serialization; #endif namespace MySql.Data.MySqlClient { /// /// The exception that is thrown when MySQL returns an error. This class cannot be inherited. /// /// #if !CF [Serializable] #endif public sealed class MySqlException : DbException { private int errorCode; private bool isFatal; internal MySqlException() { } internal MySqlException(string msg) : base(msg) { } internal MySqlException(string msg, Exception ex) : base(msg, ex) { } internal MySqlException(string msg, bool isFatal, Exception inner) : base (msg, inner) { this.isFatal = isFatal; } internal MySqlException(string msg, int errno, Exception inner) : this(msg, inner) { errorCode = errno; #if !CF Data.Add("Server Error Code", errno); #endif } internal MySqlException(string msg, int errno) : this(msg, errno, null) { } #if !CF private MySqlException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif /// /// Gets a number that identifies the type of error. /// public int Number { get { return errorCode; } } /// /// True if this exception was fatal and cause the closing of the connection, false otherwise. /// internal bool IsFatal { get { return isFatal; } } internal bool IsQueryAborted { get { return (errorCode == (int)MySqlErrorCode.QueryInterrupted || errorCode == (int)MySqlErrorCode.FileSortAborted); } } } } mysql-connector-net-6.4.3/Source/MySql.Data/MySqlScript.cs0000644000175000017500000003550611127003600024122 0ustar directhexdirecthex// Copyright (c) 2006-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using MySql.Data.Common; using System.Collections.Generic; using System.Text; using System; using System.Data; using System.Globalization; using System.IO; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { /// /// Provides a class capable of executing a SQL script containing /// multiple SQL statements including CREATE PROCEDURE statements /// that require changing the delimiter /// public class MySqlScript { private MySqlConnection connection; private string query; private string delimiter; public event MySqlStatementExecutedEventHandler StatementExecuted; public event MySqlScriptErrorEventHandler Error; public event EventHandler ScriptCompleted; #region Constructors /// /// Initializes a new instance of the /// class. /// public MySqlScript() { Delimiter = ";"; } /// /// Initializes a new instance of the /// class. /// /// The connection. public MySqlScript(MySqlConnection connection) : this() { this.connection = connection; } /// /// Initializes a new instance of the /// class. /// /// The query. public MySqlScript(string query) : this() { this.query = query; } /// /// Initializes a new instance of the /// class. /// /// The connection. /// The query. public MySqlScript(MySqlConnection connection, string query) :this() { this.connection = connection; this.query = query; } #endregion #region Properties /// /// Gets or sets the connection. /// /// The connection. public MySqlConnection Connection { get { return connection; } set { connection = value; } } /// /// Gets or sets the query. /// /// The query. public string Query { get { return query; } set { query = value; } } /// /// Gets or sets the delimiter. /// /// The delimiter. public string Delimiter { get { return delimiter; } set { delimiter = value; } } #endregion #region Public Methods /// /// Executes this instance. /// /// The number of statements executed as part of the script. public int Execute() { bool openedConnection = false; if (connection == null) throw new InvalidOperationException(Resources.ConnectionNotSet); if (query == null || query.Length == 0) return 0; // next we open up the connetion if it is not already open if (connection.State != ConnectionState.Open) { openedConnection = true; connection.Open(); } // since we don't allow setting of parameters on a script we can // therefore safely allow the use of user variables. no one should be using // this connection while we are using it so we can temporarily tell it // to allow the use of user variables bool allowUserVars = connection.Settings.AllowUserVariables; connection.Settings.AllowUserVariables = true; try { string mode = connection.driver.Property("sql_mode"); mode = mode.ToUpper(CultureInfo.InvariantCulture); bool ansiQuotes = mode.IndexOf("ANSI_QUOTES") != -1; bool noBackslashEscapes = mode.IndexOf("NO_BACKSLASH_ESCAPES") != -1; // first we break the query up into smaller queries List statements = BreakIntoStatements(ansiQuotes, noBackslashEscapes); int count = 0; MySqlCommand cmd = new MySqlCommand(null, connection); foreach (ScriptStatement statement in statements) { if (String.IsNullOrEmpty(statement.text)) continue; cmd.CommandText = statement.text; try { cmd.ExecuteNonQuery(); count++; OnQueryExecuted(statement); } catch (Exception ex) { if (Error == null) throw; if (!OnScriptError(ex)) break; } } OnScriptCompleted(); return count; } finally { connection.Settings.AllowUserVariables = allowUserVars; if (openedConnection) { connection.Close(); } } } #endregion private void OnQueryExecuted(ScriptStatement statement) { if (StatementExecuted != null) { MySqlScriptEventArgs args = new MySqlScriptEventArgs(); args.Statement = statement; StatementExecuted(this, args); } } private void OnScriptCompleted() { if (ScriptCompleted != null) ScriptCompleted(this, EventArgs.Empty); } private bool OnScriptError(Exception ex) { if (Error != null) { MySqlScriptErrorEventArgs args = new MySqlScriptErrorEventArgs(ex); Error(this, args); return args.Ignore; } return false; } private List BreakScriptIntoLines() { List lineNumbers = new List(); StringReader sr = new StringReader(query); string line = sr.ReadLine(); int pos = 0; while (line != null) { lineNumbers.Add(pos); pos += line.Length; line = sr.ReadLine(); } return lineNumbers; } private static int FindLineNumber(int position, List lineNumbers) { int i = 0; while (i < lineNumbers.Count && position < lineNumbers[i]) i++; return i; } private List BreakIntoStatements(bool ansiQuotes, bool noBackslashEscapes) { string currentDelimiter = Delimiter; int startPos = 0; List statements = new List(); List lineNumbers = BreakScriptIntoLines(); MySqlTokenizer tokenizer = new MySqlTokenizer(query); tokenizer.AnsiQuotes = ansiQuotes; tokenizer.BackslashEscapes = !noBackslashEscapes; string token = tokenizer.NextToken(); while (token != null) { if (!tokenizer.Quoted) { if (token.ToLower(CultureInfo.InvariantCulture) == "delimiter") { tokenizer.NextToken(); AdjustDelimiterEnd(tokenizer); currentDelimiter = query.Substring(tokenizer.StartIndex, tokenizer.StopIndex - tokenizer.StartIndex + 1).Trim(); startPos = tokenizer.StopIndex; } else { // this handles the case where our tokenizer reads part of the // delimiter if (currentDelimiter.StartsWith(token)) { if ((tokenizer.StartIndex + currentDelimiter.Length) <= query.Length) { if (query.Substring(tokenizer.StartIndex, currentDelimiter.Length) == currentDelimiter) { token = currentDelimiter; tokenizer.Position = tokenizer.StartIndex + currentDelimiter.Length; tokenizer.StopIndex = tokenizer.Position; } } } int delimiterPos = token.IndexOf(currentDelimiter, StringComparison.InvariantCultureIgnoreCase); if (delimiterPos != -1) { int endPos = tokenizer.StopIndex - token.Length + delimiterPos; if (tokenizer.StopIndex == query.Length - 1) endPos++; string currentQuery = query.Substring(startPos, endPos - startPos); ScriptStatement statement = new ScriptStatement(); statement.text = currentQuery.Trim(); statement.line = FindLineNumber(startPos, lineNumbers); statement.position = startPos - lineNumbers[statement.line]; statements.Add(statement); startPos = endPos + currentDelimiter.Length; } } } token = tokenizer.NextToken(); } // now clean up the last statement if (startPos < query.Length-1) { string sqlLeftOver = query.Substring(startPos).Trim(); if (!String.IsNullOrEmpty(sqlLeftOver)) { ScriptStatement statement = new ScriptStatement(); statement.text = sqlLeftOver; statement.line = FindLineNumber(startPos, lineNumbers); statement.position = startPos - lineNumbers[statement.line]; statements.Add(statement); } } return statements; } private void AdjustDelimiterEnd(MySqlTokenizer tokenizer) { int pos = tokenizer.StopIndex; char c = query[pos]; while (!Char.IsWhiteSpace(c) && pos < (query.Length-1)) { c = query[++pos]; } tokenizer.StopIndex = pos; tokenizer.Position = pos; } } /// /// /// public delegate void MySqlStatementExecutedEventHandler(object sender, MySqlScriptEventArgs args); /// /// /// public delegate void MySqlScriptErrorEventHandler(object sender, MySqlScriptErrorEventArgs args); /// /// /// public class MySqlScriptEventArgs : EventArgs { private ScriptStatement statement; internal ScriptStatement Statement { set { this.statement = value; } } /// /// Gets the statement text. /// /// The statement text. public string StatementText { get { return statement.text; } } /// /// Gets the line. /// /// The line. public int Line { get { return statement.line; } } /// /// Gets the position. /// /// The position. public int Position { get { return statement.position; } } } /// /// /// public class MySqlScriptErrorEventArgs : MySqlScriptEventArgs { private Exception exception; private bool ignore; /// /// Initializes a new instance of the class. /// /// The exception. public MySqlScriptErrorEventArgs(Exception exception) : base() { this.exception = exception; } /// /// Gets the exception. /// /// The exception. public Exception Exception { get { return exception; } } /// /// Gets or sets a value indicating whether this is ignore. /// /// true if ignore; otherwise, false. public bool Ignore { get { return ignore; } set { ignore = value; } } } struct ScriptStatement { public string text; public int line; public int position; } } mysql-connector-net-6.4.3/Source/MySql.Data/parameter.cs0000644000175000017500000006445011127003600023650 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Data.Common; using MySql.Data.Types; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.Text; using System.Collections; #if !CF using System.ComponentModel.Design.Serialization; #endif namespace MySql.Data.MySqlClient { /// /// Represents a parameter to a , and optionally, its mapping to columns. This class cannot be inherited. /// #if !CF [TypeConverter(typeof(MySqlParameterConverter))] #endif public sealed class MySqlParameter : DbParameter, IDataParameter, IDbDataParameter, ICloneable { private const int UNSIGNED_MASK = 0x8000; private object paramValue; private ParameterDirection direction = ParameterDirection.Input; private bool isNullable; private string paramName; private string sourceColumn; private DataRowVersion sourceVersion = DataRowVersion.Current; private int size; private byte precision; private byte scale; private MySqlDbType mySqlDbType; private DbType dbType; private bool inferType; private bool sourceColumnNullMapping; private MySqlParameterCollection collection; IMySqlValue valueObject; private Encoding encoding; private IList possibleValues; #region Constructors /// /// Initializes a new instance of the MySqlParameter class. /// public MySqlParameter() { inferType = true; } /// /// Initializes a new instance of the class with the parameter name and a value of the new MySqlParameter. /// /// The name of the parameter to map. /// An that is the value of the . public MySqlParameter(string parameterName, object value) : this() { ParameterName = parameterName; Value = value; } /// /// Initializes a new instance of the class with the parameter name and the data type. /// /// The name of the parameter to map. /// One of the values. public MySqlParameter(string parameterName, MySqlDbType dbType) : this(parameterName, null) { MySqlDbType = dbType; } /// /// Initializes a new instance of the class with the parameter name, the , and the size. /// /// The name of the parameter to map. /// One of the values. /// The length of the parameter. public MySqlParameter(string parameterName, MySqlDbType dbType, int size) : this(parameterName, dbType) { this.size = size; } /// /// Initializes a new instance of the class with the parameter name, the , the size, and the source column name. /// /// The name of the parameter to map. /// One of the values. /// The length of the parameter. /// The name of the source column. public MySqlParameter(string parameterName, MySqlDbType dbType, int size, string sourceColumn) : this(parameterName, dbType) { this.size = size; direction = ParameterDirection.Input; this.sourceColumn = sourceColumn; sourceVersion = DataRowVersion.Current; } internal MySqlParameter(string name, MySqlDbType type, ParameterDirection dir, string col, DataRowVersion ver, object val) : this(name, type) { direction = dir; sourceColumn = col; sourceVersion = ver; Value = val; } /// /// Initializes a new instance of the class with the parameter name, the type of the parameter, the size of the parameter, a , the precision of the parameter, the scale of the parameter, the source column, a to use, and the value of the parameter. /// /// The name of the parameter to map. /// One of the values. /// The length of the parameter. /// One of the values. /// true if the value of the field can be null, otherwise false. /// The total number of digits to the left and right of the decimal point to which is resolved. /// The total number of decimal places to which is resolved. /// The name of the source column. /// One of the values. /// An that is the value of the . /// public MySqlParameter(string parameterName, MySqlDbType dbType, int size, ParameterDirection direction, bool isNullable, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value) : this(parameterName, dbType, size, sourceColumn) { this.direction = direction; this.sourceVersion = sourceVersion; Value = value; } #endregion #region Properties internal MySqlParameterCollection Collection { get { return collection; } set { collection = value; } } internal bool TypeHasBeenSet { get { return inferType == false; } } internal Encoding Encoding { get { return encoding; } set { encoding = value; } } internal string BaseName { get { if (ParameterName.StartsWith("@") || ParameterName.StartsWith("?")) return ParameterName.Substring(1); return ParameterName; } } /// /// Gets or sets the of the parameter. /// public override DbType DbType { get { return dbType; } set { SetDbType(value); inferType = false; } } /// /// Gets or sets a value indicating whether the parameter is input-only, output-only, bidirectional, or a stored procedure return value parameter. /// As of MySql version 4.1 and earlier, input-only is the only valid choice. /// #if !CF [Category("Data")] #endif public override ParameterDirection Direction { get { return direction; } set { direction = value; } } /// /// Gets or sets a value indicating whether the parameter accepts null values. /// #if !CF [Browsable(false)] #endif public override Boolean IsNullable { get { return isNullable; } set { isNullable = value; } } /// /// Gets or sets the MySqlDbType of the parameter. /// #if !CF [Category("Data")] [DbProviderSpecificTypeProperty(true)] #endif public MySqlDbType MySqlDbType { get { return mySqlDbType; } set { SetMySqlDbType(value); inferType = false; } } /// /// Gets or sets the name of the MySqlParameter. /// #if !CF [Category("Misc")] #endif public override String ParameterName { get { return paramName; } set { if (collection != null) collection.ParameterNameChanged(this, paramName, value); paramName = value; } } /// /// Gets or sets the maximum number of digits used to represent the property. /// #if !CF [Category("Data")] #endif public byte Precision { get { return precision; } set { precision = value; } } /// /// Gets or sets the number of decimal places to which is resolved. /// #if !CF [Category("Data")] #endif public byte Scale { get { return scale; } set { scale = value; } } /// /// Gets or sets the maximum size, in bytes, of the data within the column. /// #if !CF [Category("Data")] #endif public override int Size { get { return size; } set { size = value; } } /// /// Gets or sets the name of the source column that is mapped to the and used for loading or returning the . /// #if !CF [Category("Data")] #endif public override String SourceColumn { get { return sourceColumn; } set { sourceColumn = value; } } /// /// Gets or sets the to use when loading . /// #if !CF [Category("Data")] #endif public override DataRowVersion SourceVersion { get { return sourceVersion; } set { sourceVersion = value; } } /// /// Gets or sets the value of the parameter. /// #if !CF [TypeConverter(typeof (StringConverter))] [Category("Data")] #endif public override object Value { get { return paramValue; } set { paramValue = value; byte[] valueAsByte = value as byte[]; string valueAsString = value as string; if (valueAsByte != null) size = valueAsByte.Length; else if (valueAsString != null) size = valueAsString.Length; if (inferType) SetTypeFromValue(); } } private IMySqlValue ValueObject { get { return valueObject; } } /// /// Returns the possible values for this parameter if this parameter is of type /// SET or ENUM. Returns null otherwise. /// public IList PossibleValues { get { return possibleValues; } internal set { possibleValues = value; } } #endregion /// /// Overridden. Gets a string containing the . /// /// public override string ToString() { return paramName; } internal int GetPSType() { switch (mySqlDbType) { case MySqlDbType.Bit: return (int) MySqlDbType.Int64 | UNSIGNED_MASK; case MySqlDbType.UByte: return (int) MySqlDbType.Byte | UNSIGNED_MASK; case MySqlDbType.UInt64: return (int) MySqlDbType.Int64 | UNSIGNED_MASK; case MySqlDbType.UInt32: return (int) MySqlDbType.Int32 | UNSIGNED_MASK; case MySqlDbType.UInt24: return (int) MySqlDbType.Int32 | UNSIGNED_MASK; case MySqlDbType.UInt16: return (int) MySqlDbType.Int16 | UNSIGNED_MASK; default: return (int) mySqlDbType; } } internal void Serialize(MySqlPacket packet, bool binary, MySqlConnectionStringBuilder settings) { if (!binary && (paramValue == null || paramValue == DBNull.Value)) packet.WriteStringNoNull("NULL"); else { if (ValueObject.MySqlDbType == MySqlDbType.Guid) { MySqlGuid g = (MySqlGuid)ValueObject; g.OldGuids = settings.OldGuids; valueObject = g; } ValueObject.WriteValue(packet, binary, paramValue, size); } } private void SetMySqlDbType(MySqlDbType mysql_dbtype) { mySqlDbType = mysql_dbtype; valueObject = MySqlField.GetIMySqlValue(mySqlDbType); switch (mySqlDbType) { case MySqlDbType.Decimal: dbType = DbType.Decimal; break; case MySqlDbType.Byte: dbType = DbType.SByte; break; case MySqlDbType.UByte: dbType = DbType.Byte; break; case MySqlDbType.Int16: dbType = DbType.Int16; break; case MySqlDbType.UInt16: dbType = DbType.UInt16; break; case MySqlDbType.Int24: case MySqlDbType.Int32: dbType = DbType.Int32; break; case MySqlDbType.UInt24: case MySqlDbType.UInt32: dbType = DbType.UInt32; break; case MySqlDbType.Int64: dbType = DbType.Int64; break; case MySqlDbType.UInt64: dbType = DbType.UInt64; break; case MySqlDbType.Bit: dbType = DbType.UInt64; break; case MySqlDbType.Float: dbType = DbType.Single; break; case MySqlDbType.Double: dbType = DbType.Double; break; case MySqlDbType.Timestamp: case MySqlDbType.DateTime: dbType = DbType.DateTime; break; case MySqlDbType.Date: case MySqlDbType.Newdate: case MySqlDbType.Year: dbType = DbType.Date; break; case MySqlDbType.Time: dbType = DbType.Time; break; case MySqlDbType.Enum: case MySqlDbType.Set: case MySqlDbType.VarChar: dbType = DbType.String; break; case MySqlDbType.TinyBlob: case MySqlDbType.MediumBlob: case MySqlDbType.LongBlob: case MySqlDbType.Blob: dbType = DbType.Object; break; case MySqlDbType.String: dbType = DbType.StringFixedLength; break; case MySqlDbType.Guid: dbType = DbType.Guid; break; } } private void SetDbType(DbType db_type) { dbType = db_type; switch (dbType) { case DbType.Guid: mySqlDbType = MySqlDbType.Guid; break; case DbType.AnsiString: case DbType.String: mySqlDbType = MySqlDbType.VarChar; break; case DbType.AnsiStringFixedLength: case DbType.StringFixedLength: mySqlDbType = MySqlDbType.String; break; case DbType.Boolean: case DbType.Byte: mySqlDbType = MySqlDbType.UByte; break; case DbType.SByte: mySqlDbType = MySqlDbType.Byte; break; case DbType.Date: mySqlDbType = MySqlDbType.Date; break; case DbType.DateTime: mySqlDbType = MySqlDbType.DateTime; break; case DbType.Time: mySqlDbType = MySqlDbType.Time; break; case DbType.Single: mySqlDbType = MySqlDbType.Float; break; case DbType.Double: mySqlDbType = MySqlDbType.Double; break; case DbType.Int16: mySqlDbType = MySqlDbType.Int16; break; case DbType.UInt16: mySqlDbType = MySqlDbType.UInt16; break; case DbType.Int32: mySqlDbType = MySqlDbType.Int32; break; case DbType.UInt32: mySqlDbType = MySqlDbType.UInt32; break; case DbType.Int64: mySqlDbType = MySqlDbType.Int64; break; case DbType.UInt64: mySqlDbType = MySqlDbType.UInt64; break; case DbType.Decimal: case DbType.Currency: mySqlDbType = MySqlDbType.Decimal; break; case DbType.Object: case DbType.VarNumeric: case DbType.Binary: default: mySqlDbType = MySqlDbType.Blob; break; } valueObject = MySqlField.GetIMySqlValue(mySqlDbType); } private void SetTypeFromValue() { if (paramValue == null || paramValue == DBNull.Value) return; if (paramValue is Guid) DbType = DbType.Guid; else if (paramValue is TimeSpan) DbType = DbType.Time; else if (paramValue is bool) DbType = DbType.Byte; else { TypeCode tc = Type.GetTypeCode(paramValue.GetType()); switch (tc) { case TypeCode.SByte: DbType = DbType.SByte; break; case TypeCode.Byte: DbType = DbType.Byte; break; case TypeCode.Int16: DbType = DbType.Int16; break; case TypeCode.UInt16: DbType = DbType.UInt16; break; case TypeCode.Int32: DbType = DbType.Int32; break; case TypeCode.UInt32: DbType = DbType.UInt32; break; case TypeCode.Int64: DbType = DbType.Int64; break; case TypeCode.UInt64: DbType = DbType.UInt64; break; case TypeCode.DateTime: DbType = DbType.DateTime; break; case TypeCode.String: DbType = DbType.String; break; case TypeCode.Single: DbType = DbType.Single; break; case TypeCode.Double: DbType = DbType.Double; break; case TypeCode.Decimal: DbType = DbType.Decimal; break; case TypeCode.Object: default: DbType = DbType.Object; break; } } } #region ICloneable public MySqlParameter Clone() { MySqlParameter clone = new MySqlParameter(paramName, mySqlDbType, direction, sourceColumn, sourceVersion, paramValue); // if we have not had our type set yet then our clone should not either clone.inferType = inferType; return clone; } object ICloneable.Clone() { return this.Clone(); } #endregion /// /// Resets the DbType property to its original settings. /// public override void ResetDbType() { inferType = true; } /// /// Sets or gets a value which indicates whether the source column is nullable. /// This allows to correctly generate Update statements /// for nullable columns. /// public override bool SourceColumnNullMapping { get { return sourceColumnNullMapping; } set { sourceColumnNullMapping = value; } } // this method is pretty dumb but we want it to be fast. it doesn't return size based // on value and type but just on the value. internal long EstimatedSize() { if (Value == null || Value == DBNull.Value) return 4; // size of NULL if (Value is byte[]) return (Value as byte[]).Length; if (Value is string) return (Value as string).Length * 4; // account for UTF-8 (yeah I know) if (Value is decimal || Value is float) return 64; return 32; } } #if !CF internal class MySqlParameterConverter : TypeConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) { return true; } // Always call the base to see if it can perform the conversion. return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(InstanceDescriptor)) { ConstructorInfo ci = typeof(MySqlParameter).GetConstructor( new Type[] { typeof (string), typeof (MySqlDbType), typeof (int), typeof (ParameterDirection), typeof (bool), typeof (byte), typeof (byte), typeof (string), typeof (DataRowVersion), typeof (object) }); MySqlParameter p = (MySqlParameter)value; return new InstanceDescriptor(ci, new object[] { p.ParameterName, p.DbType, p.Size, p.Direction, p.IsNullable, p.Precision, p.Scale, p.SourceColumn, p.SourceVersion, p.Value }); } // Always call base, even if you can't convert. return base.ConvertTo(context, culture, value, destinationType); } } #endif } mysql-connector-net-6.4.3/Source/MySql.Data/NativeDriver.cs0000644000175000017500000010504111127003600024262 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Diagnostics; using System.IO; using MySql.Data.Common; using MySql.Data.Types; using System.Security.Cryptography.X509Certificates; using MySql.Data.MySqlClient.Properties; using System.Text; #if !CF using System.Net.Security; using System.Security.Authentication; using System.Globalization; #endif namespace MySql.Data.MySqlClient { /// /// Summary description for Driver. /// internal class NativeDriver : IDriver { private DBVersion version; private int threadId; protected String encryptionSeed; protected ServerStatusFlags serverStatus; protected MySqlStream stream; protected Stream baseStream; private BitArray nullMap; private MySqlPacket packet; private ClientFlags connectionFlags; private Driver owner; private int warnings; // Windows authentication method string, used by the protocol. // Also known as "client plugin name". const string AuthenticationWindowsPlugin = "authentication_windows_client"; // Predefined username for IntegratedSecurity const string AuthenticationWindowsUser = "auth_windows"; public NativeDriver(Driver owner) { this.owner = owner; threadId = -1; } public ClientFlags Flags { get { return connectionFlags; } } public int ThreadId { get { return threadId; } } public DBVersion Version { get { return version; } } public ServerStatusFlags ServerStatus { get { return serverStatus; } } public int WarningCount { get { return warnings; } } public MySqlPacket Packet { get { return packet; } } private MySqlConnectionStringBuilder Settings { get { return owner.Settings; } } private Encoding Encoding { get { return owner.Encoding; } } private void HandleException(MySqlException ex) { if (ex.IsFatal) owner.Close(); } private void ReadOk(bool read) { try { if (read) packet = stream.ReadPacket(); byte marker = (byte) packet.ReadByte(); if (marker != 0) { throw new MySqlException("Out of sync with server", true, null); } packet.ReadFieldLength(); /* affected rows */ packet.ReadFieldLength(); /* last insert id */ if (packet.HasMoreData) { serverStatus = (ServerStatusFlags) packet.ReadInteger(2); packet.ReadInteger(2); /* warning count */ if (packet.HasMoreData) { packet.ReadLenString(); /* message */ } } } catch (MySqlException ex) { HandleException(ex); throw; } } /// /// Sets the current database for the this connection /// /// public void SetDatabase(string dbName) { byte[] dbNameBytes = Encoding.GetBytes(dbName); packet.Clear(); packet.WriteByte((byte)DBCmd.INIT_DB); packet.Write(dbNameBytes); ExecutePacket(packet); ReadOk(true); } public void Configure() { stream.MaxPacketSize = (ulong)owner.MaxPacketSize; stream.Encoding = Encoding; } public void Open() { // connect to one of our specified hosts try { #if !CF if (Settings.ConnectionProtocol == MySqlConnectionProtocol.SharedMemory) { SharedMemoryStream str = new SharedMemoryStream(Settings.SharedMemoryName); str.Open(Settings.ConnectionTimeout); baseStream = str; } else { #endif string pipeName = Settings.PipeName; if (Settings.ConnectionProtocol != MySqlConnectionProtocol.NamedPipe) pipeName = null; StreamCreator sc = new StreamCreator(Settings.Server, Settings.Port, pipeName, Settings.Keepalive); baseStream = sc.GetStream(Settings.ConnectionTimeout); #if !CF } #endif } catch (Exception ex) { throw new MySqlException(Resources.UnableToConnectToHost, (int) MySqlErrorCode.UnableToConnectToHost, ex); } if (baseStream == null) throw new MySqlException(Resources.UnableToConnectToHost, (int)MySqlErrorCode.UnableToConnectToHost); int maxSinglePacket = 255*255*255; stream = new MySqlStream(baseStream, Encoding, false); stream.ResetTimeout((int)Settings.ConnectionTimeout*1000); // read off the welcome packet and parse out it's values packet = stream.ReadPacket(); int protocol = packet.ReadByte(); string versionString = packet.ReadString(); version = DBVersion.Parse(versionString); if (!version.isAtLeast(5, 0, 0)) throw new NotSupportedException(Resources.ServerTooOld); threadId = packet.ReadInteger(4); encryptionSeed = packet.ReadString(); maxSinglePacket = (256*256*256) - 1; // read in Server capabilities if they are provided ClientFlags serverCaps = 0; if (packet.HasMoreData) serverCaps = (ClientFlags) packet.ReadInteger(2); /* New protocol with 16 bytes to describe server characteristics */ owner.ConnectionCharSetIndex = (int)packet.ReadByte(); serverStatus = (ServerStatusFlags) packet.ReadInteger(2); // Since 5.5, high bits of server caps are stored after status. // Previously, it was part of reserved always 0x00 13-byte filler. uint serverCapsHigh = (uint)packet.ReadInteger(2); serverCaps |= (ClientFlags)(serverCapsHigh << 16); packet.Position += 11; string seedPart2 = packet.ReadString(); encryptionSeed += seedPart2; string authenticationMethod = ""; if ((serverCaps & ClientFlags.PLUGIN_AUTH)!=0) { authenticationMethod = packet.ReadString(); } // based on our settings, set our connection flags SetConnectionFlags(serverCaps); packet.Clear(); packet.WriteInteger((int) connectionFlags, 4); #if !CF if ((serverCaps & ClientFlags.SSL) ==0) { if ((Settings.SslMode != MySqlSslMode.None) && (Settings.SslMode != MySqlSslMode.Preferred)) { // Client requires SSL connections. string message = String.Format(Resources.NoServerSSLSupport, Settings.Server); throw new MySqlException(message); } } else if (Settings.SslMode != MySqlSslMode.None) { stream.SendPacket(packet); StartSSL(); packet.Clear(); packet.WriteInteger((int) connectionFlags, 4); } #endif packet.WriteInteger(maxSinglePacket, 4); packet.WriteByte(8); packet.Write(new byte[23]); Authenticate(false); // if we are using compression, then we use our CompressedStream class // to hide the ugliness of managing the compression if ((connectionFlags & ClientFlags.COMPRESS) != 0) stream = new MySqlStream(baseStream, Encoding, true); // give our stream the server version we are connected to. // We may have some fields that are read differently based // on the version of the server we are connected to. packet.Version = version; stream.MaxBlockSize = maxSinglePacket; } #if !CF #region SSL /// /// Retrieve client SSL certificates. Dependent on connection string /// settings we use either file or store based certificates. /// private X509CertificateCollection GetClientCertificates() { X509CertificateCollection certs = new X509CertificateCollection(); // Check for file-based certificate if (Settings.CertificateFile != null) { if (!Version.isAtLeast(5, 1, 0)) throw new MySqlException(Properties.Resources.FileBasedCertificateNotSupported); X509Certificate2 clientCert = new X509Certificate2(Settings.CertificateFile, Settings.CertificatePassword); certs.Add(clientCert); return certs; } if (Settings.CertificateStoreLocation == MySqlCertificateStoreLocation.None) return certs; StoreLocation location = (Settings.CertificateStoreLocation == MySqlCertificateStoreLocation.CurrentUser) ? StoreLocation.CurrentUser : StoreLocation.LocalMachine; // Check for store-based certificate X509Store store = new X509Store(StoreName.My, location); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); if (Settings.CertificateThumbprint == null) { // Return all certificates from the store. certs.AddRange(store.Certificates); return certs; } // Find certificate with given thumbprint certs.AddRange(store.Certificates.Find(X509FindType.FindByThumbprint, Settings.CertificateThumbprint, true)); if (certs.Count == 0) { throw new MySqlException("Certificate with Thumbprint " + Settings.CertificateThumbprint + " not found"); } return certs; } private void StartSSL() { RemoteCertificateValidationCallback sslValidateCallback = new RemoteCertificateValidationCallback(ServerCheckValidation); SslStream ss = new SslStream(baseStream, true, sslValidateCallback, null); X509CertificateCollection certs = GetClientCertificates(); ss.AuthenticateAsClient(Settings.Server, certs, SslProtocols.Default, false); baseStream = ss; stream = new MySqlStream(ss, Encoding, false); stream.SequenceByte = 2; } private bool ServerCheckValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true; if (Settings.SslMode == MySqlSslMode.Preferred || Settings.SslMode == MySqlSslMode.Required) { //Tolerate all certificate errors. return true; } if (Settings.SslMode == MySqlSslMode.VerifyCA && sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch) { // Tolerate name mismatch in certificate, if full validation is not requested. return true; } return false; } #endregion #endif #region Authentication /// /// Return the appropriate set of connection flags for our /// server capabilities and our user requested options. /// private void SetConnectionFlags(ClientFlags serverCaps) { // allow load data local infile ClientFlags flags = ClientFlags.LOCAL_FILES; if (!Settings.UseAffectedRows) flags |= ClientFlags.FOUND_ROWS; flags |= ClientFlags.PROTOCOL_41; // Need this to get server status values flags |= ClientFlags.TRANSACTIONS; // user allows/disallows batch statements if (Settings.AllowBatch) flags |= ClientFlags.MULTI_STATEMENTS; // We always allow multiple result sets flags |= ClientFlags.MULTI_RESULTS; // if the server allows it, tell it that we want long column info if ((serverCaps & ClientFlags.LONG_FLAG) != 0) flags |= ClientFlags.LONG_FLAG; // if the server supports it and it was requested, then turn on compression if ((serverCaps & ClientFlags.COMPRESS) != 0 && Settings.UseCompression) flags |= ClientFlags.COMPRESS; flags |= ClientFlags.LONG_PASSWORD; // for long passwords // did the user request an interactive session? if (Settings.InteractiveSession) flags |= ClientFlags.INTERACTIVE; // if the server allows it and a database was specified, then indicate // that we will connect with a database name if ((serverCaps & ClientFlags.CONNECT_WITH_DB) != 0 && Settings.Database != null && Settings.Database.Length > 0) flags |= ClientFlags.CONNECT_WITH_DB; // if the server is requesting a secure connection, then we oblige if ((serverCaps & ClientFlags.SECURE_CONNECTION) != 0) flags |= ClientFlags.SECURE_CONNECTION; #if !CF // if the server is capable of SSL and the user is requesting SSL if ((serverCaps & ClientFlags.SSL) != 0 && Settings.SslMode != MySqlSslMode.None) flags |= ClientFlags.SSL; #endif // if the server supports output parameters, then we do too if ((serverCaps & ClientFlags.PS_MULTI_RESULTS) != 0) flags |= ClientFlags.PS_MULTI_RESULTS; if(Settings.IntegratedSecurity) { if ((serverCaps & ClientFlags.PLUGIN_AUTH) != 0) flags |= ClientFlags.PLUGIN_AUTH; } connectionFlags = flags; } private void AuthenticateSSPI() { string targetName = ""; // target name (required by Kerberos) // First packet sent by server should include target name (for // Kerberos) as UTF8 string. It might however be prepended by junk // at the start of the string (0xfe"authentication_win_client"\0, // see Bug#57442), this junk will be ignored. Target name can also // be an empty string if server is not running in a domain environment, // in this case authentication will fallback to NTLM. // Note that 0xfe byte at the start could also indicate that windows // authentication is not supported by srver, we throw an exception // if this happens. packet = stream.ReadPacket(); byte b = packet.ReadByte(); if (b == 0xfe) { string authMethod = packet.ReadString(); if (authMethod.Equals(AuthenticationWindowsPlugin)) { targetName = packet.ReadString(Encoding.UTF8); } else { // User has requested Windows authentication, bail out. throw new MySqlException("unexpected authentication method " + authMethod); } } else { targetName = Encoding.UTF8.GetString(packet.Buffer, 0, packet.Buffer.Length); } // Do SSPI authentication handshake SSPI sspi = new SSPI(targetName, stream.BaseStream, stream.SequenceByte); sspi.AuthenticateClient(); // read ok packet. packet = stream.ReadPacket(); ReadOk(false); } /// /// Perform an authentication against a 4.1.1 server /// /// True, if this function is called as part of CHANGE_USER request /// (connection reset) /// False, for first-time logon /// /// private void AuthenticateNew(bool reset) { if ((connectionFlags & ClientFlags.SECURE_CONNECTION) == 0) AuthenticateOld(); packet.Write(Crypt.Get411Password(Settings.Password, encryptionSeed)); if ((connectionFlags & ClientFlags.CONNECT_WITH_DB) != 0 && Settings.Database != null) packet.WriteString(Settings.Database); else packet.WriteString(""); // Add a null termination to the string. if (Settings.IntegratedSecurity) { // Append authentication method after the database name in the // handshake authentication packet.If we're sending CHANGE_USER // also write charset number after database name prior to plugin name if (reset) { packet.WriteInteger(8, 2); // Charset number } packet.WriteString(AuthenticationWindowsPlugin); stream.SendPacket(packet); AuthenticateSSPI(); return; } else { stream.SendPacket(packet); } // this result means the server wants us to send the password using // old encryption packet = stream.ReadPacket(); if (packet.IsLastPacket) { packet.Clear(); packet.WriteString(Crypt.EncryptPassword( Settings.Password, encryptionSeed.Substring(0, 8), true)); stream.SendPacket(packet); ReadOk(true); } ReadOk(false); } private void AuthenticateOld() { packet.WriteString(Crypt.EncryptPassword( Settings.Password, encryptionSeed, true)); if ((connectionFlags & ClientFlags.CONNECT_WITH_DB) != 0 && Settings.Database != null) packet.WriteString(Settings.Database); stream.SendPacket(packet); ReadOk(true); } public void Authenticate(bool reset) { if (Settings.IntegratedSecurity) { packet.WriteString(AuthenticationWindowsUser); } else { // write the user id to the auth packet packet.WriteString(Settings.UserID); } AuthenticateNew(reset); } #endregion public void Reset() { warnings = 0; stream.Encoding = this.Encoding; stream.SequenceByte = 0; packet.Clear(); packet.WriteByte((byte)DBCmd.CHANGE_USER); Authenticate(true); } /// /// Query is the method that is called to send all queries to the server /// public void SendQuery(MySqlPacket queryPacket) { warnings = 0; queryPacket.Buffer[4] = (byte)DBCmd.QUERY; ExecutePacket(queryPacket); // the server will respond in one of several ways with the first byte indicating // the type of response. // 0 == ok packet. This indicates non-select queries // 0xff == error packet. This is handled in stream.OpenPacket // > 0 = number of columns in select query // We don't actually read the result here since a single query can generate // multiple resultsets and we don't want to duplicate code. See ReadResult // Instead we set our internal server status flag to indicate that we have a query waiting. // This flag will be maintained by ReadResult serverStatus |= ServerStatusFlags.AnotherQuery; } public void Close(bool isOpen) { try { if (isOpen) { try { packet.Clear(); packet.WriteByte((byte)DBCmd.QUIT); ExecutePacket(packet); } catch (Exception) { // Eat exception here. We should try to closing // the stream anyway. } } if (stream != null) stream.Close(); stream = null; } catch (Exception) { // we are just going to eat any exceptions // generated here } } public bool Ping() { try { packet.Clear(); packet.WriteByte((byte)DBCmd.PING); ExecutePacket(packet); ReadOk(true); return true; } catch (Exception) { return false; } } public int GetResult(ref int affectedRow, ref int insertedId) { try { packet = stream.ReadPacket(); } catch (TimeoutException) { // Do not reset serverStatus, allow to reenter, e.g when // ResultSet is closed. throw; } catch (Exception) { serverStatus = 0; throw; } int fieldCount = (int)packet.ReadFieldLength(); if (-1 == fieldCount) { string filename = packet.ReadString(); SendFileToServer(filename); return GetResult(ref affectedRow, ref insertedId); } else if (fieldCount == 0) { // the code to read last packet will set these server status vars // again if necessary. serverStatus &= ~(ServerStatusFlags.AnotherQuery | ServerStatusFlags.MoreResults); affectedRow = (int)packet.ReadFieldLength(); insertedId = (int)packet.ReadFieldLength(); serverStatus = (ServerStatusFlags)packet.ReadInteger(2); warnings += packet.ReadInteger(2); if (packet.HasMoreData) { packet.ReadLenString(); //TODO: server message } } return fieldCount; } /// /// Sends the specified file to the server. /// This supports the LOAD DATA LOCAL INFILE /// /// private void SendFileToServer(string filename) { byte[] buffer = new byte[8196]; long len = 0; try { using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { len = fs.Length; while (len > 0) { int count = fs.Read(buffer, 4, (int)(len > 8192 ? 8192 : len)); stream.SendEntirePacketDirectly(buffer, count); len -= count; } stream.SendEntirePacketDirectly(buffer, 0); } } catch (Exception ex) { throw new MySqlException("Error during LOAD DATA LOCAL INFILE", ex); } } private void ReadNullMap(int fieldCount) { // if we are binary, then we need to load in our null bitmap nullMap = null; byte[] nullMapBytes = new byte[(fieldCount + 9)/8]; packet.ReadByte(); packet.Read(nullMapBytes, 0, nullMapBytes.Length); nullMap = new BitArray(nullMapBytes); } public IMySqlValue ReadColumnValue(int index, MySqlField field, IMySqlValue valObject) { long length = -1; bool isNull; if (nullMap != null) isNull = nullMap[index + 2]; else { length = packet.ReadFieldLength(); isNull = length == -1; } packet.Encoding = field.Encoding; packet.Version = version; return valObject.ReadValue(packet, length, isNull); } public void SkipColumnValue(IMySqlValue valObject) { int length = -1; if (nullMap == null) { length = (int)packet.ReadFieldLength(); if (length == -1) return; } if (length > -1) packet.Position += length; else valObject.SkipValue(packet); } public void GetColumnsData(MySqlField[] columns) { for (int i = 0; i < columns.Length; i++) GetColumnData(columns[i]); ReadEOF(); } private void GetColumnData(MySqlField field) { stream.Encoding = Encoding; packet = stream.ReadPacket(); field.Encoding = Encoding; field.CatalogName = packet.ReadLenString(); field.DatabaseName = packet.ReadLenString(); field.TableName = packet.ReadLenString(); field.RealTableName = packet.ReadLenString(); field.ColumnName = packet.ReadLenString(); field.OriginalColumnName = packet.ReadLenString(); packet.ReadByte(); field.CharacterSetIndex = packet.ReadInteger(2); field.ColumnLength = packet.ReadInteger(4); MySqlDbType type = (MySqlDbType)packet.ReadByte(); ColumnFlags colFlags; if ((connectionFlags & ClientFlags.LONG_FLAG) != 0) colFlags = (ColumnFlags)packet.ReadInteger(2); else colFlags = (ColumnFlags)packet.ReadByte(); field.Scale = (byte)packet.ReadByte(); if (packet.HasMoreData) { packet.ReadInteger(2); // reserved } if (type == MySqlDbType.Decimal || type == MySqlDbType.NewDecimal) { field.Precision = (byte)(field.ColumnLength - 2); if ((colFlags & ColumnFlags.UNSIGNED) != 0) field.Precision++; } field.SetTypeAndFlags(type, colFlags); } private void ExecutePacket(MySqlPacket packetToExecute) { try { warnings = 0; stream.SequenceByte = 0; stream.SendPacket(packetToExecute); } catch (MySqlException ex) { HandleException(ex); throw; } } public void ExecuteStatement(MySqlPacket packetToExecute) { warnings = 0; packetToExecute.Buffer[4] = (byte)DBCmd.EXECUTE; ExecutePacket(packetToExecute); serverStatus |= ServerStatusFlags.AnotherQuery; } private void CheckEOF() { if (!packet.IsLastPacket) throw new MySqlException("Expected end of data packet"); packet.ReadByte(); // read off the 254 if (packet.HasMoreData) { warnings += packet.ReadInteger(2); serverStatus = (ServerStatusFlags)packet.ReadInteger(2); // if we are at the end of this cursor based resultset, then we remove // the last row sent status flag so our next fetch doesn't abort early // and we remove this command result from our list of active CommandResult objects. // if ((serverStatus & ServerStatusFlags.LastRowSent) != 0) // { // serverStatus &= ~ServerStatusFlags.LastRowSent; // commandResults.Remove(lastCommandResult); // } } } private void ReadEOF() { packet = stream.ReadPacket(); CheckEOF(); } public int PrepareStatement(string sql, ref MySqlField[] parameters) { //TODO: check this //ClearFetchedRow(); packet.Length = sql.Length*4 + 5; byte[] buffer = packet.Buffer; int len = Encoding.GetBytes(sql, 0, sql.Length, packet.Buffer, 5); packet.Position = len + 5; buffer[4] = (byte)DBCmd.PREPARE; ExecutePacket(packet); packet = stream.ReadPacket(); int marker = packet.ReadByte(); if (marker != 0) throw new MySqlException("Expected prepared statement marker"); int statementId = packet.ReadInteger(4); int numCols = packet.ReadInteger(2); int numParams = packet.ReadInteger(2); //TODO: find out what this is needed for packet.ReadInteger(3); if (numParams > 0) { parameters = owner.GetColumns(numParams); // we set the encoding for each parameter back to our connection encoding // since we can't trust what is coming back from the server for (int i = 0; i < parameters.Length; i++) parameters[i].Encoding = Encoding; } if (numCols > 0) { while (numCols-- > 0) { packet = stream.ReadPacket(); //TODO: handle streaming packets } ReadEOF(); } return statementId; } // private void ClearFetchedRow() // { // if (lastCommandResult == 0) return; //TODO /* CommandResult result = (CommandResult)commandResults[lastCommandResult]; result.ReadRemainingColumns(); stream.OpenPacket(); if (! stream.IsLastPacket) throw new MySqlException("Cursor reading out of sync"); ReadEOF(false); lastCommandResult = 0;*/ // } /// /// FetchDataRow is the method that the data reader calls to see if there is another /// row to fetch. In the non-prepared mode, it will simply read the next data packet. /// In the prepared mode (statementId > 0), it will /// public bool FetchDataRow(int statementId, int columns) { /* ClearFetchedRow(); if (!commandResults.ContainsKey(statementId)) return false; if ( (serverStatus & ServerStatusFlags.LastRowSent) != 0) return false; stream.StartPacket(9, true); stream.WriteByte((byte)DBCmd.FETCH); stream.WriteInteger(statementId, 4); stream.WriteInteger(1, 4); stream.Flush(); lastCommandResult = statementId; */ packet = stream.ReadPacket(); if (packet.IsLastPacket) { CheckEOF(); return false; } nullMap = null; if (statementId > 0) ReadNullMap(columns); return true; } public void CloseStatement(int statementId) { packet.Clear(); packet.WriteByte((byte)DBCmd.CLOSE_STMT); packet.WriteInteger((long)statementId, 4); stream.SequenceByte = 0; stream.SendPacket(packet); } /// /// Execution timeout, in milliseconds. When the accumulated time for network IO exceeds this value /// TimeoutException is thrown. This timeout needs to be reset for every new command /// /// public void ResetTimeout(int timeout) { if (stream != null) stream.ResetTimeout(timeout); } } } mysql-connector-net-6.4.3/Source/MySql.Data/MySqlConnectionStringBuilder.cs0000644000175000017500000012017611127003600027451 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data.Common; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Text.RegularExpressions; using System.Text; using MySql.Data.MySqlClient.Properties; using System.Collections; using System.Globalization; namespace MySql.Data.MySqlClient { public class MySqlConnectionStringBuilder : DbConnectionStringBuilder { private static Dictionary validKeywords = new Dictionary(StringComparer.OrdinalIgnoreCase); private static Dictionary defaultValues = new Dictionary(StringComparer.OrdinalIgnoreCase); private Dictionary values = new Dictionary(StringComparer.OrdinalIgnoreCase); private bool hasProcAccess = true; static MySqlConnectionStringBuilder() { // load up our valid keywords and default values only once Initialize(); } public MySqlConnectionStringBuilder() { Clear(); } public MySqlConnectionStringBuilder(string connStr) : this() { ConnectionString = connStr; } #region Server Properties /// /// Gets or sets the name of the server. /// /// The server. [Category("Connection")] [Description("Server to connect to")] [DefaultValue("")] [ValidKeywords("host, data source, datasource, address, addr, network address")] [RefreshProperties(RefreshProperties.All)] public string Server { get { return values["server"] as string; } set { SetValue("server", value); } } /// /// Gets or sets the name of the database the connection should /// initially connect to. /// [Category("Connection")] [Description("Database to use initially")] [DefaultValue("")] [ValidKeywords("initial catalog")] [RefreshProperties(RefreshProperties.All)] public string Database { get { return values["database"] as string; } set { SetValue("database", value); } } /// /// Gets or sets the protocol that should be used for communicating /// with MySQL. /// [Category("Connection")] [DisplayName("Connection Protocol")] [Description("Protocol to use for connection to MySQL")] [DefaultValue(MySqlConnectionProtocol.Sockets)] [ValidKeywords("protocol")] [RefreshProperties(RefreshProperties.All)] public MySqlConnectionProtocol ConnectionProtocol { get { return (MySqlConnectionProtocol)values["Connection Protocol"]; } set { SetValue("Connection Protocol", value); } } /// /// Gets or sets the name of the named pipe that should be used /// for communicating with MySQL. /// [Category("Connection")] [DisplayName("Pipe Name")] [Description("Name of pipe to use when connecting with named pipes (Win32 only)")] [DefaultValue("MYSQL")] [ValidKeywords("pipe")] [RefreshProperties(RefreshProperties.All)] public string PipeName { get { return (string)values["Pipe Name"]; } set { SetValue("Pipe Name", value); } } /// /// Gets or sets a boolean value that indicates whether this connection /// should use compression. /// [Category("Connection")] [DisplayName("Use Compression")] [Description("Should the connection ues compression")] [DefaultValue(false)] [ValidKeywords("compress")] [RefreshProperties(RefreshProperties.All)] public bool UseCompression { get { return (bool)values["Use Compression"]; } set { SetValue("Use Compression", value); } } /// /// Gets or sets a boolean value that indicates whether this connection will allow /// commands to send multiple SQL statements in one execution. /// [Category("Connection")] [DisplayName("Allow Batch")] [Description("Allows execution of multiple SQL commands in a single statement")] [DefaultValue(true)] [RefreshProperties(RefreshProperties.All)] public bool AllowBatch { get { return (bool)values["Allow Batch"]; } set { SetValue("Allow Batch", value); } } /// /// Gets or sets a boolean value that indicates whether logging is enabled. /// [Category("Connection")] [Description("Enables output of diagnostic messages")] [DefaultValue(false)] [RefreshProperties(RefreshProperties.All)] public bool Logging { get { return (bool)values["Logging"]; } set { SetValue("Logging", value); } } /// /// Gets or sets the base name of the shared memory objects used to /// communicate with MySQL when the shared memory protocol is being used. /// [Category("Connection")] [DisplayName("Shared Memory Name")] [Description("Name of the shared memory object to use")] [DefaultValue("MYSQL")] [RefreshProperties(RefreshProperties.All)] public string SharedMemoryName { get { return (string)values["Shared Memory Name"]; } set { SetValue("Shared Memory Name", value); } } /// /// Gets or sets a boolean value that indicates whether this connection uses /// the old style (@) parameter markers or the new (?) style. /// [Category("Connection")] [DisplayName("Use Old Syntax")] [Description("Allows the use of old style @ syntax for parameters")] [DefaultValue(false)] [ValidKeywords("old syntax, oldsyntax")] [RefreshProperties(RefreshProperties.All)] [Obsolete("Use Old Syntax is no longer needed. See documentation")] public bool UseOldSyntax { get { return (bool)values["Use Old Syntax"]; } set { SetValue("Use Old Syntax", value); } } /// /// Gets or sets the port number that is used when the socket /// protocol is being used. /// [Category("Connection")] [Description("Port to use for TCP/IP connections")] [DefaultValue(3306)] [RefreshProperties(RefreshProperties.All)] public uint Port { get { return (uint)values["Port"]; } set { SetValue("Port", value); } } /// /// Gets or sets the connection timeout. /// [Category("Connection")] [DisplayName("Connect Timeout")] [Description("The length of time (in seconds) to wait for a connection " + "to the server before terminating the attempt and generating an error.")] [DefaultValue(15)] [ValidKeywords("connection timeout")] [RefreshProperties(RefreshProperties.All)] public uint ConnectionTimeout { get { return (uint)values["Connect Timeout"]; } set { // Timeout in milliseconds should not exceed maximum for 32 bit // signed integer (~24 days). We truncate the value if it exceeds // maximum (MySqlCommand.CommandTimeout uses the same technique uint timeout = Math.Min(value, Int32.MaxValue / 1000); if (timeout != value) { MySqlTrace.LogWarning(-1, "Connection timeout value too large (" + value + " seconds). Changed to max. possible value" + + timeout + " seconds)"); } SetValue("Connect Timeout", timeout); } } /// /// Gets or sets the default command timeout. /// [Category("Connection")] [DisplayName("Default Command Timeout")] [Description(@"The default timeout that MySqlCommand objects will use unless changed.")] [DefaultValue(30)] [ValidKeywords("command timeout")] [RefreshProperties(RefreshProperties.All)] public uint DefaultCommandTimeout { get { return (uint)values["Default Command Timeout"]; } set { SetValue("Default Command Timeout", value); } } #endregion #region Authentication Properties /// /// Gets or sets the user id that should be used to connect with. /// [Category("Security")] [DisplayName("User Id")] [Description("Indicates the user ID to be used when connecting to the data source.")] [DefaultValue("")] [ValidKeywords("uid, username, user name, user")] [RefreshProperties(RefreshProperties.All)] public string UserID { get { return (string)values["User Id"]; } set { SetValue("User Id", value); } } /// /// Gets or sets the password that should be used to connect with. /// [Category("Security")] [Description("Indicates the password to be used when connecting to the data source.")] [PasswordPropertyText(true)] [DefaultValue("")] [ValidKeywords("pwd")] [RefreshProperties(RefreshProperties.All)] public string Password { get { return (string)values["Password"]; } set { SetValue("Password", value); } } /// /// Gets or sets a boolean value that indicates if the password should be persisted /// in the connection string. /// [Category("Security")] [DisplayName("Persist Security Info")] [Description("When false, security-sensitive information, such as the password, " + "is not returned as part of the connection if the connection is open or " + "has ever been in an open state.")] [DefaultValue(false)] [RefreshProperties(RefreshProperties.All)] public bool PersistSecurityInfo { get { return (bool)values["Persist Security Info"]; } set { SetValue("Persist Security Info", value); } } #if !CF [Category("Authentication")] [Description("Should the connection use SSL.")] [DefaultValue(false)] [Obsolete("Use Ssl Mode instead.")] internal bool Encrypt { get { return SslMode != MySqlSslMode.None; } set { SetValue("Ssl Mode", value ? MySqlSslMode.Prefered : MySqlSslMode.None); } } [Category("Authentication")] [DisplayName("Certificate File")] [Description("Certificate file in PKCS#12 format (.pfx)")] [DefaultValue(null)] public string CertificateFile { get { return (string) values["Certificate File"];} set { SetValue("Certificate File", value); } } [Category("Authentication")] [DisplayName("Certificate Password")] [Description("Password for certificate file")] [DefaultValue(null)] public string CertificatePassword { get { return (string)values["Certificate Password"];} set { SetValue("Certificate Password", value); } } [Category("Authentication")] [DisplayName("Certificate Store Location")] [Description("Certificate Store Location for client certificates")] [DefaultValue(MySqlCertificateStoreLocation.None)] public MySqlCertificateStoreLocation CertificateStoreLocation { get { return (MySqlCertificateStoreLocation)values["Certificate Store Location"]; } set { SetValue("Certificate Store Location", value); } } [Category("Authentication")] [DisplayName("Certificate Thumbprint")] [Description("Certificate thumbprint. Can be used together with Certificate "+ "Store Location parameter to uniquely identify certificate to be used "+ "for SSL authentication.")] [DefaultValue(null)] public string CertificateThumbprint { get { return (string)values["Certificate Thumbprint"]; } set { SetValue("Certificate Thumbprint", value); } } #endif [Category("Authentication")] [DisplayName("Integrated Security")] [Description("Use windows authentication when connecting to server")] [DefaultValue(false)] public bool IntegratedSecurity { get { object val = values["Integrated Security"]; return (bool)val; } set { if (!MySql.Data.Common.Platform.IsWindows()) throw new MySqlException("IntegratedSecurity is supported on Windows only"); SetValue("Integrated Security", value); } } #endregion #region Other Properties /// /// Gets or sets a boolean value that indicates if zero date time values are supported. /// [Category("Advanced")] [DisplayName("Allow Zero Datetime")] [Description("Should zero datetimes be supported")] [DefaultValue(false)] [RefreshProperties(RefreshProperties.All)] public bool AllowZeroDateTime { get { return (bool)values["Allow Zero Datetime"]; } set { SetValue("Allow Zero DateTime", value); } } /// /// Gets or sets a boolean value indicating if zero datetime values should be /// converted to DateTime.MinValue. /// [Category("Advanced")] [DisplayName("Convert Zero Datetime")] [Description("Should illegal datetime values be converted to DateTime.MinValue")] [DefaultValue(false)] [RefreshProperties(RefreshProperties.All)] public bool ConvertZeroDateTime { get { return (bool)values["Convert Zero Datetime"]; } set { SetValue("Convert Zero DateTime", value); } } /// /// Gets or sets a boolean value indicating if the Usage Advisor should be enabled. /// [Category("Advanced")] [DisplayName("Use Usage Advisor")] [Description("Logs inefficient database operations")] [DefaultValue(false)] [ValidKeywords("usage advisor")] [RefreshProperties(RefreshProperties.All)] public bool UseUsageAdvisor { get { return (bool)values["Use Usage Advisor"]; } set { SetValue("Use Usage Advisor", value); } } /// /// Gets or sets the size of the stored procedure cache. /// [Category("Advanced")] [DisplayName("Procedure Cache Size")] [Description("Indicates how many stored procedures can be cached at one time. " + "A value of 0 effectively disables the procedure cache.")] [DefaultValue(25)] [ValidKeywords("procedure cache, procedurecache")] [RefreshProperties(RefreshProperties.All)] public uint ProcedureCacheSize { get { return (uint)values["Procedure Cache Size"]; } set { SetValue("Procedure Cache Size", value); } } /// /// Gets or sets a boolean value indicating if the permon hooks should be enabled. /// [Category("Advanced")] [DisplayName("Use Performance Monitor")] [Description("Indicates that performance counters should be updated during execution.")] [DefaultValue(false)] [ValidKeywords("userperfmon, perfmon")] [RefreshProperties(RefreshProperties.All)] public bool UsePerformanceMonitor { get { return (bool)values["Use Performance Monitor"]; } set { SetValue("Use Performance Monitor", value); } } /// /// Gets or sets a boolean value indicating if calls to Prepare() should be ignored. /// [Category("Advanced")] [DisplayName("Ignore Prepare")] [Description("Instructs the provider to ignore any attempts to prepare a command.")] [DefaultValue(true)] [RefreshProperties(RefreshProperties.All)] public bool IgnorePrepare { get { return (bool)values["Ignore Prepare"]; } set { SetValue("Ignore Prepare", value); } } [Category("Advanced")] [DisplayName("Use Procedure Bodies")] [Description("Indicates if stored procedure bodies will be available for parameter detection.")] [DefaultValue(true)] [ValidKeywords("procedure bodies")] [Obsolete("Use CheckParameters instead")] public bool UseProcedureBodies { get { return (bool)values["Check Parameters"]; } set { SetValue("Check Parameters", value); } } [Category("Advanced")] [DisplayName("Auto Enlist")] [Description("Should the connetion automatically enlist in the active connection, if there are any.")] [DefaultValue(true)] [RefreshProperties(RefreshProperties.All)] public bool AutoEnlist { get { return (bool)values["Auto Enlist"]; } set { SetValue("Auto Enlist", value); } } [Category("Advanced")] [DisplayName("Respect Binary Flags")] [Description("Should binary flags on column metadata be respected.")] [DefaultValue(true)] [RefreshProperties(RefreshProperties.All)] public bool RespectBinaryFlags { get { return (bool)values["Respect Binary Flags"]; } set { SetValue("Respect Binary Flags", value); } } [Category("Advanced")] [DisplayName("Treat Tiny As Boolean")] [Description("Should the provider treat TINYINT(1) columns as boolean.")] [DefaultValue(true)] [RefreshProperties(RefreshProperties.All)] public bool TreatTinyAsBoolean { get { return (bool)values["Treat Tiny As Boolean"]; } set { SetValue("Treat Tiny As Boolean", value); } } [Category("Advanced")] [DisplayName("Allow User Variables")] [Description("Should the provider expect user variables to appear in the SQL.")] [DefaultValue(false)] [RefreshProperties(RefreshProperties.All)] public bool AllowUserVariables { get { return (bool)values["Allow User Variables"]; } set { SetValue("Allow User Variables", value); } } [Category("Advanced")] [DisplayName("Interactive Session")] [Description("Should this session be considered interactive?")] [DefaultValue(false)] [ValidKeywords("interactive")] [RefreshProperties(RefreshProperties.All)] public bool InteractiveSession { get { return (bool)values["Interactive Session"]; } set { SetValue("Interactive Session", value); } } [Category("Advanced")] [DisplayName("Functions Return String")] [Description("Should all server functions be treated as returning string?")] [DefaultValue(false)] public bool FunctionsReturnString { get { return (bool)values["Functions Return String"]; } set { SetValue("Functions Return String", value); } } [Category("Advanced")] [DisplayName("Use Affected Rows")] [Description("Should the returned affected row count reflect affected rows instead of found rows?")] [DefaultValue(false)] public bool UseAffectedRows { get { return (bool)values["Use Affected Rows"]; } set { SetValue("Use Affected Rows", value); } } [Category("Advanced")] [DisplayName("Old Guids")] [Description("Treat binary(16) columns as guids")] [DefaultValue(false)] public bool OldGuids { get { return (bool)values["Old Guids"]; } set { SetValue("Old Guids", value); } } [DisplayName("Keep Alive")] [Description("For TCP connections, idle connection time measured in seconds, before the first keepalive packet is sent." + "A value of 0 indicates that keepalive is not used.")] [DefaultValue(0)] public uint Keepalive { get { return (uint)values["Keep Alive"]; } set { SetValue("Keep Alive", value); } } [Category("Advanced")] [DisplayName("Sql Server Mode")] [Description("Allow Sql Server syntax. " + "A value of yes allows symbols to be enclosed with [] instead of ``. This does incur " + "a performance hit so only use when necessary.")] [DefaultValue(false)] [ValidKeywords("sqlservermode, sql server mode")] public bool SqlServerMode { get { return (bool)values["Sql Server Mode"]; } set { SetValue("Sql Server Mode", value); } } [Category("Advanced")] [DisplayName("Table Cache")] [Description(@"Enables or disables caching of TableDirect command. A value of yes enables the cache while no disables it.")] [DefaultValue(false)] [ValidKeywords("tablecache, table cache")] public bool TableCaching { get { return (bool)values["Table Cache"]; } set { SetValue("Table Cache", value); } } [Category("Advanced")] [DisplayName("Default Table Cache Age")] [Description(@"Specifies how long a TableDirect result should be cached in seconds.")] [DefaultValue(60)] public int DefaultTableCacheAge { get { return (int)values["Default Table Cache Age"]; } set { SetValue("Default Table Cache Age", value); } } [Category("Advanced")] [DisplayName("Check Parameters")] [Description("Indicates if stored routine parameters should be checked against the server.")] [DefaultValue(true)] public bool CheckParameters { get { return (bool)values["Check Parameters"]; } set { SetValue("Check Parameters", value); } } [Category("Advanced")] [DisplayName("Replication")] [Description("Indicates if this connection is to use replicated servers.")] [DefaultValue(false)] public bool Replication { get { return (bool)values["Replication"]; } set { SetValue("Replication", value); } } #endregion #region Pooling Properties /// /// Gets or sets the lifetime of a pooled connection. /// [Category("Pooling")] [DisplayName("Connection Lifetime")] [Description("The minimum amount of time (in seconds) for this connection to " + "live in the pool before being destroyed.")] [DefaultValue(0)] [RefreshProperties(RefreshProperties.All)] public uint ConnectionLifeTime { get { return (uint)values["Connection LifeTime"]; } set { SetValue("Connection LifeTime", value); } } /// /// Gets or sets a boolean value indicating if connection pooling is enabled. /// [Category("Pooling")] [Description("When true, the connection object is drawn from the appropriate " + "pool, or if necessary, is created and added to the appropriate pool.")] [DefaultValue(true)] [RefreshProperties(RefreshProperties.All)] public bool Pooling { get { return (bool)values["Pooling"]; } set { SetValue("Pooling", value); } } /// /// Gets the minimum connection pool size. /// [Category("Pooling")] [DisplayName("Minimum Pool Size")] [Description("The minimum number of connections allowed in the pool.")] [DefaultValue(0)] [ValidKeywords("min pool size")] [RefreshProperties(RefreshProperties.All)] public uint MinimumPoolSize { get { return (uint)values["Minimum Pool Size"]; } set { SetValue("Minimum Pool Size", value); } } /// /// Gets or sets the maximum connection pool setting. /// [Category("Pooling")] [DisplayName("Maximum Pool Size")] [Description("The maximum number of connections allowed in the pool.")] [DefaultValue(100)] [ValidKeywords("max pool size")] [RefreshProperties(RefreshProperties.All)] public uint MaximumPoolSize { get { return (uint)values["Maximum Pool Size"]; } set { SetValue("Maximum Pool Size", value); } } /// /// Gets or sets a boolean value indicating if the connection should be reset when retrieved /// from the pool. /// [Category("Pooling")] [DisplayName("Connection Reset")] [Description("When true, indicates the connection state is reset when " + "removed from the pool.")] [DefaultValue(false)] [RefreshProperties(RefreshProperties.All)] public bool ConnectionReset { get { return (bool)values["Connection Reset"]; } set { SetValue("Connection Reset", value); } } [Category("Pooling")] [DisplayName("Cache Server Properties")] [Description("When true, server properties will be cached after the first server in the pool is created")] [DefaultValue(false)] [RefreshProperties(RefreshProperties.All)] public bool CacheServerProperties { get { return (bool)values["Cache Server Properties"]; } set { SetValue("Cache Server Properties", value); } } #endregion #region Language and Character Set Properties /// /// Gets or sets the character set that should be used for sending queries to the server. /// [DisplayName("Character Set")] [Category("Advanced")] [Description("Character set this connection should use")] [DefaultValue("")] [ValidKeywords("charset")] [RefreshProperties(RefreshProperties.All)] public string CharacterSet { get { return (string)values["Character Set"]; } set { SetValue("Character Set", value); } } /// /// Indicates whether the driver should treat binary blobs as UTF8 /// [DisplayName("Treat Blobs As UTF8")] [Category("Advanced")] [Description("Should binary blobs be treated as UTF8")] [DefaultValue(false)] [RefreshProperties(RefreshProperties.All)] public bool TreatBlobsAsUTF8 { get { return (bool)values["Treat Blobs As UTF8"]; } set { SetValue("Treat Blobs As UTF8", value); } } /// /// Gets or sets the pattern that matches the columns that should be treated as UTF8 /// [Category("Advanced")] [Description("Pattern that matches columns that should be treated as UTF8")] [DefaultValue("")] [RefreshProperties(RefreshProperties.All)] public string BlobAsUTF8IncludePattern { get { return (string)values["BlobAsUTF8IncludePattern"]; } set { SetValue("BlobAsUTF8IncludePattern", value); } } /// /// Gets or sets the pattern that matches the columns that should not be treated as UTF8 /// [Category("Advanced")] [Description("Pattern that matches columns that should not be treated as UTF8")] [DefaultValue("")] [RefreshProperties(RefreshProperties.All)] public string BlobAsUTF8ExcludePattern { get { return (string)values["BlobAsUTF8ExcludePattern"]; } set { SetValue("BlobAsUTF8ExcludePattern", value); } } #if !CF /// /// Indicates whether to use SSL connections and how to handle server certificate errors. /// [DisplayName("Ssl Mode")] [Category("Security")] [Description("SSL properties for connection")] [DefaultValue(MySqlSslMode.None)] public MySqlSslMode SslMode { get { return (MySqlSslMode)values["Ssl Mode"]; } set { SetValue("Ssl Mode", value); } } #endif #endregion internal bool HasProcAccess { get { return hasProcAccess; } set { hasProcAccess = value; } } internal Regex GetBlobAsUTF8IncludeRegex() { if (String.IsNullOrEmpty(BlobAsUTF8IncludePattern)) return null; return new Regex(BlobAsUTF8IncludePattern); } internal Regex GetBlobAsUTF8ExcludeRegex() { if (String.IsNullOrEmpty(BlobAsUTF8ExcludePattern)) return null; return new Regex(BlobAsUTF8ExcludePattern); } #if !CF public override bool ContainsKey(string keyword) { try { object value; ValidateKeyword(keyword); return values.TryGetValue(validKeywords[keyword], out value); } catch (Exception) { return false; } } #endif public override object this[string keyword] { get { return values[validKeywords[keyword]]; } set { ValidateKeyword(keyword); if (value == null) Remove(keyword); else SetValue(keyword, value); } } public override void Clear() { base.Clear(); // make a copy of our default values array foreach (string key in defaultValues.Keys) values[key] = defaultValues[key].DefaultValue; } #if !CF public override bool Remove(string keyword) { ValidateKeyword(keyword); string primaryKey = validKeywords[keyword]; values.Remove(primaryKey); base.Remove(primaryKey); values[primaryKey] = defaultValues[primaryKey].DefaultValue; return true; } public override bool TryGetValue(string keyword, out object value) { ValidateKeyword(keyword); return values.TryGetValue(validKeywords[keyword], out value); } #endif public string GetConnectionString(bool includePass) { if (includePass) return ConnectionString; StringBuilder conn = new StringBuilder(); string delimiter = ""; foreach (string key in this.Keys) { if (String.Compare(key, "password", true) == 0 || String.Compare(key, "pwd", true) == 0) continue; conn.AppendFormat(CultureInfo.CurrentCulture, "{0}{1}={2}", delimiter, key, this[key]); delimiter = ";"; } return conn.ToString(); } private void SetValue(string keyword, object value) { ValidateKeyword(keyword); keyword = validKeywords[keyword]; Remove(keyword); NormalizeValue(keyword, ref value); object val = null; if (value is string && defaultValues[keyword].DefaultValue is Enum) val = ParseEnum(defaultValues[keyword].Type, (string)value, keyword); else if (value is string && string.IsNullOrEmpty(value.ToString())) val = defaultValues[keyword].DefaultValue; else val = ChangeType(value, defaultValues[keyword].Type); HandleObsolete(keyword, val); values[keyword] = val; base[keyword] = val; } private static void NormalizeValue(string keyword, ref object value) { // Handle special case "Integrated Security=SSPI" // Integrated Security is a logically bool parameter, SSPI value // for it is the same as "true" (SSPI is SQL Server legacy value if (keyword == "Integrated Security" && value is string && ((string)value).ToLower(CultureInfo.InvariantCulture) == "sspi") { value = true; } } private void HandleObsolete(string keyword, object value) { if (String.Compare(keyword, "Use Old Syntax", true) == 0) MySqlTrace.LogWarning(-1, "Use Old Syntax is now obsolete. Please see documentation"); #if !CF else if (String.Compare(keyword, "Encrypt", true) == 0) { MySqlTrace.LogWarning(-1, "Encrypt is now obsolete. Use Ssl Mode instead"); Encrypt = (bool)value; } #endif else if (String.Compare(keyword, "Use Procedure Bodies", true) == 0) { MySqlTrace.LogWarning(-1, "Use Procedure Bodies is now obsolete. Use Check Parameters instead"); CheckParameters = (bool)value; } } private object ParseEnum(Type t, string requestedValue, string key) { try { return Enum.Parse(t, requestedValue, true); } catch (ArgumentException) { throw new InvalidOperationException(String.Format( Resources.InvalidConnectionStringValue, requestedValue, key)); } } private object ChangeType(object value, Type t) { if (t == typeof(bool) && value is string) { string s = value.ToString().ToLower(CultureInfo.InvariantCulture); if (s == "yes" || s == "true") return true; if (s == "no" || s == "false") return false; throw new FormatException(String.Format(Resources.InvalidValueForBoolean, value)); } else return Convert.ChangeType(value, t, CultureInfo.CurrentCulture); } private void ValidateKeyword(string keyword) { string key = keyword.ToLower(CultureInfo.InvariantCulture); if (!validKeywords.ContainsKey(key)) throw new ArgumentException(Resources.KeywordNotSupported, keyword); #if CF if (validKeywords[key] == "Certificate File" || validKeywords[key] == "Certificate Password" || validKeywords[key] == "SSL Mode" || validKeywords[key] == "Encrypt" || validKeywords[key] == "Certificate Store Location" || validKeywords[key] == "Certificate Thumbprint") throw new ArgumentException(Resources.KeywordNotSupported, validKeywords[key]); #endif } private static void Initialize() { PropertyInfo[] properties = typeof(MySqlConnectionStringBuilder).GetProperties(); foreach (PropertyInfo pi in properties) AddKeywordFromProperty(pi); #if !CF // remove this starting with 6.4 PropertyInfo encrypt = typeof(MySqlConnectionStringBuilder).GetProperty( "Encrypt", BindingFlags.Instance | BindingFlags.NonPublic); AddKeywordFromProperty(encrypt); #endif } private static void AddKeywordFromProperty(PropertyInfo pi) { string name = pi.Name.ToLower(CultureInfo.InvariantCulture); string displayName = name; // now see if we have defined a display name for this property object[] attr = pi.GetCustomAttributes(false); foreach (Attribute a in attr) if (a is DisplayNameAttribute) { displayName = (a as DisplayNameAttribute).DisplayName; break; } validKeywords[name] = displayName; validKeywords[displayName] = displayName; foreach (Attribute a in attr) { if (a is ValidKeywordsAttribute) { foreach (string keyword in (a as ValidKeywordsAttribute).Keywords) validKeywords[keyword.ToLower(CultureInfo.InvariantCulture).Trim()] = displayName; } else if (a is DefaultValueAttribute) { defaultValues[displayName] = new PropertyDefaultValue(pi.PropertyType, Convert.ChangeType((a as DefaultValueAttribute).Value, pi.PropertyType, CultureInfo.CurrentCulture)); } } } } internal struct PropertyDefaultValue { public PropertyDefaultValue(Type t, object v) { Type = t; DefaultValue = v; } public Type Type; public object DefaultValue; } internal class ValidKeywordsAttribute : Attribute { private string keywords; public ValidKeywordsAttribute(string keywords) { this.keywords = keywords.ToLower(CultureInfo.InvariantCulture); } public string[] Keywords { get { return keywords.Split(','); } } } } mysql-connector-net-6.4.3/Source/MySql.Data/ResultSet.cs0000644000175000017500000002647011127003600023622 0ustar directhexdirecthex// Copyright (c) 2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Data; using MySql.Data.MySqlClient.Properties; using MySql.Data.Types; using System.Diagnostics; using System.Collections.Generic; namespace MySql.Data.MySqlClient { internal class ResultSet { private Driver driver; private bool hasRows; private bool[] uaFieldsUsed; private MySqlField[] fields; private IMySqlValue[] values; private Hashtable fieldHashCS; private Hashtable fieldHashCI; private int rowIndex; private bool readDone; private bool isSequential; private int seqIndex; private bool isOutputParameters; private int affectedRows; private int insertedId; private int statementId; private int totalRows; private int skippedRows; private bool cached; private List cachedValues; public ResultSet(int affectedRows, int insertedId) { this.affectedRows = affectedRows; this.insertedId = insertedId; readDone = true; } public ResultSet(Driver d, int statementId, int numCols) { affectedRows = -1; insertedId = -1; driver = d; this.statementId = statementId; rowIndex = -1; LoadColumns(numCols); isOutputParameters = IsOutputParameterResultSet(); hasRows = GetNextRow(); readDone = !hasRows; } #region Properties public bool HasRows { get { return hasRows; } } public int Size { get { return fields == null ? 0 : fields.Length; } } public MySqlField[] Fields { get { return fields; } } public IMySqlValue[] Values { get { return values; } } public bool IsOutputParameters { get { return isOutputParameters; } set { isOutputParameters = value; } } public int AffectedRows { get { return affectedRows; } } public int InsertedId { get { return insertedId; } } public int TotalRows { get { return totalRows; } } public int SkippedRows { get { return skippedRows; } } public bool Cached { get { return cached; } set { cached = value; if (cached && cachedValues == null) cachedValues = new List(); } } #endregion /// /// return the ordinal for the given column name /// /// /// public int GetOrdinal(string name) { // first we try a quick hash lookup object ordinal = fieldHashCS[name]; if (ordinal != null) return (int)ordinal; // ok that failed so we use our CI hash ordinal = fieldHashCI[name]; if (ordinal != null) return (int)ordinal; // Throw an exception if the ordinal cannot be found. throw new IndexOutOfRangeException( String.Format(Resources.CouldNotFindColumnName, name)); } /// /// Retrieve the value as the given column index /// /// The column value to retrieve /// The value as the given column public IMySqlValue this[int index] { get { if (rowIndex < 0) throw new MySqlException(Resources.AttemptToAccessBeforeRead); // keep count of how many columns we have left to access uaFieldsUsed[index] = true; if (isSequential && index != seqIndex) { if (index < seqIndex) throw new MySqlException(Resources.ReadingPriorColumnUsingSeqAccess); while (seqIndex < (index - 1)) driver.SkipColumnValue(values[++seqIndex]); values[index] = driver.ReadColumnValue(index, fields[index], values[index]); seqIndex = index; } return values[index]; } } private bool GetNextRow() { bool fetched = driver.FetchDataRow(statementId, Size); if (fetched) totalRows++; return fetched; } public bool NextRow(CommandBehavior behavior) { if (readDone) { if (Cached) return CachedNextRow(behavior); return false; } if ((behavior & CommandBehavior.SingleRow) != 0 && rowIndex == 0) return false; isSequential = (behavior & CommandBehavior.SequentialAccess) != 0; seqIndex = -1; // if we are at row index >= 0 then we need to fetch the data row and load it if (rowIndex >= 0) { bool fetched = false; try { fetched = GetNextRow(); } catch (MySqlException ex) { if (ex.IsQueryAborted) { // avoid hanging on Close() readDone = true; } throw; } if (!fetched) { readDone = true; return false; } } if (!isSequential) ReadColumnData(false); rowIndex++; return true; } private bool CachedNextRow(CommandBehavior behavior) { if ((behavior & CommandBehavior.SingleRow) != 0 && rowIndex == 0) return false; if (rowIndex == (totalRows - 1)) return false; rowIndex++; values = cachedValues[rowIndex]; return true; } /// /// Closes the current resultset, dumping any data still on the wire /// public void Close() { if (!readDone) { // if we have rows but the user didn't read the first one then mark it as skipped if (HasRows && rowIndex == -1) skippedRows++; try { while (driver.IsOpen && driver.SkipDataRow()) { totalRows++; skippedRows++; } } catch (System.IO.IOException) { // it is ok to eat IO exceptions here, we just want to // close the result set } readDone = true; } else if (driver == null) CacheClose(); driver = null; if (Cached) CacheReset(); } private void CacheClose() { skippedRows = totalRows - rowIndex - 1; } private void CacheReset() { if (!Cached) return; rowIndex = -1; affectedRows = -1; insertedId = -1; skippedRows = 0; } public bool FieldRead(int index) { Debug.Assert(Size > index); return uaFieldsUsed[index]; } public void SetValueObject(int i, IMySqlValue valueObject) { Debug.Assert(values != null); Debug.Assert(i < values.Length); values[i] = valueObject; } private bool IsOutputParameterResultSet() { if (driver.HasStatus(ServerStatusFlags.OutputParameters)) return true; if (fields.Length == 0) return false; for (int x = 0; x < fields.Length; x++) if (!fields[x].ColumnName.StartsWith("@" + StoredProcedure.ParameterPrefix)) return false; return true; } /// /// Loads the column metadata for the current resultset /// private void LoadColumns(int numCols) { fields = driver.GetColumns(numCols); values = new IMySqlValue[numCols]; uaFieldsUsed = new bool[numCols]; fieldHashCS = new Hashtable(); fieldHashCI = new Hashtable(StringComparer.InvariantCultureIgnoreCase); for (int i = 0; i < fields.Length; i++) { string columnName = fields[i].ColumnName; if (!fieldHashCS.ContainsKey(columnName)) fieldHashCS.Add(columnName, i); if (!fieldHashCI.ContainsKey(columnName)) fieldHashCI.Add(columnName, i); values[i] = fields[i].GetValueObject(); } } private void ReadColumnData(bool outputParms) { for (int i = 0; i < Size; i++) values[i] = driver.ReadColumnValue(i, fields[i], values[i]); // if we are caching then we need to save a copy of this row of data values if (Cached) cachedValues.Add((IMySqlValue[])values.Clone()); // we don't need to worry about caching the following since you won't have output // params with TableDirect commands if (outputParms) { bool rowExists = driver.FetchDataRow(statementId, fields.Length); rowIndex = 0; if (rowExists) throw new MySqlException(Resources.MoreThanOneOPRow); } } } } mysql-connector-net-6.4.3/Source/MySql.Data/transaction.cs0000644000175000017500000001107711127003600024212 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Data.Common; namespace MySql.Data.MySqlClient { /// public sealed class MySqlTransaction : DbTransaction { private IsolationLevel level; private MySqlConnection conn; private bool open; internal MySqlTransaction(MySqlConnection c, IsolationLevel il) { conn = c; level = il; open = true; } #region Properties /// /// Gets the object associated with the transaction, or a null reference (Nothing in Visual Basic) if the transaction is no longer valid. /// /// The object associated with this transaction. /// /// A single application may have multiple database connections, each /// with zero or more transactions. This property enables you to /// determine the connection object associated with a particular /// transaction created by . /// public new MySqlConnection Connection { get { return conn; } } /// /// Specifies the for this transaction. /// /// /// The for this transaction. The default is ReadCommitted. /// /// /// Parallel transactions are not supported. Therefore, the IsolationLevel /// applies to the entire transaction. /// public override IsolationLevel IsolationLevel { get { return level; } } protected override DbConnection DbConnection { get { return conn; } } #endregion protected override void Dispose(bool disposing) { if ((conn != null && conn.State == ConnectionState.Open || conn.SoftClosed) && open) Rollback(); base.Dispose(disposing); } /// public override void Commit() { if (conn == null || (conn.State != ConnectionState.Open && !conn.SoftClosed)) throw new InvalidOperationException("Connection must be valid and open to commit transaction"); if (!open) throw new InvalidOperationException("Transaction has already been committed or is not pending"); MySqlCommand cmd = new MySqlCommand("COMMIT", conn); cmd.ExecuteNonQuery(); open = false; } /// public override void Rollback() { if (conn == null || (conn.State != ConnectionState.Open && !conn.SoftClosed)) throw new InvalidOperationException("Connection must be valid and open to rollback transaction"); if (!open) throw new InvalidOperationException("Transaction has already been rolled back or is not pending"); MySqlCommand cmd = new MySqlCommand("ROLLBACK", conn); cmd.ExecuteNonQuery(); open = false; } } } mysql-connector-net-6.4.3/Source/MySql.Data/ISSchemaProvider.cs0000644000175000017500000007334311127003600025040 0ustar directhexdirecthex// Copyright 2004,2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Text; using MySql.Data.Common; using System.Globalization; using System.Diagnostics; using System.Data.SqlTypes; using MySql.Data.Types; using System.Collections; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { internal class ISSchemaProvider : SchemaProvider { public ISSchemaProvider(MySqlConnection connection) : base(connection) { } protected override DataTable GetCollections() { DataTable dt = base.GetCollections(); object[][] collections = new object[][] { new object[] {"Views", 2, 3}, new object[] {"ViewColumns", 3, 4}, new object[] {"Procedure Parameters", 5, 1}, new object[] {"Procedures", 4, 3}, new object[] {"Triggers", 2, 4} }; FillTable(dt, collections); return dt; } protected override DataTable GetRestrictions() { DataTable dt = base.GetRestrictions(); object[][] restrictions = new object[][] { new object[] {"Procedure Parameters", "Database", "", 0}, new object[] {"Procedure Parameters", "Schema", "", 1}, new object[] {"Procedure Parameters", "Name", "", 2}, new object[] {"Procedure Parameters", "Type", "", 3}, new object[] {"Procedure Parameters", "Parameter", "", 4}, new object[] {"Procedures", "Database", "", 0}, new object[] {"Procedures", "Schema", "", 1}, new object[] {"Procedures", "Name", "", 2}, new object[] {"Procedures", "Type", "", 3}, new object[] {"Views", "Database", "", 0}, new object[] {"Views", "Schema", "", 1}, new object[] {"Views", "Table", "", 2}, new object[] {"ViewColumns", "Database", "", 0}, new object[] {"ViewColumns", "Schema", "", 1}, new object[] {"ViewColumns", "Table", "", 2}, new object[] {"ViewColumns", "Column", "", 3}, new object[] {"Triggers", "Database", "", 0}, new object[] {"Triggers", "Schema", "", 1}, new object[] {"Triggers", "Name", "", 2}, new object[] {"Triggers", "EventObjectTable", "", 3}, }; FillTable(dt, restrictions); return dt; } public override DataTable GetDatabases(string[] restrictions) { string[] keys = new string[1]; keys[0] = "SCHEMA_NAME"; DataTable dt = Query("SCHEMATA", "", keys, restrictions); dt.Columns[1].ColumnName = "database_name"; dt.TableName = "Databases"; return dt; } public override DataTable GetTables(string[] restrictions) { string[] keys = new string[4]; keys[0] = "TABLE_CATALOG"; keys[1] = "TABLE_SCHEMA"; keys[2] = "TABLE_NAME"; keys[3] = "TABLE_TYPE"; DataTable dt = Query("TABLES", "TABLE_TYPE != 'VIEW'", keys, restrictions); dt.TableName = "Tables"; return dt; } public override DataTable GetColumns(string[] restrictions) { string[] keys = new string[4]; keys[0] = "TABLE_CATALOG"; keys[1] = "TABLE_SCHEMA"; keys[2] = "TABLE_NAME"; keys[3] = "COLUMN_NAME"; DataTable dt = Query("COLUMNS", null, keys, restrictions); dt.Columns.Remove("CHARACTER_OCTET_LENGTH"); dt.TableName = "Columns"; QuoteDefaultValues(dt); return dt; } private DataTable GetViews(string[] restrictions) { string[] keys = new string[3]; keys[0] = "TABLE_CATALOG"; keys[1] = "TABLE_SCHEMA"; keys[2] = "TABLE_NAME"; DataTable dt = Query("VIEWS", null, keys, restrictions); dt.TableName = "Views"; return dt; } private DataTable GetViewColumns(string[] restrictions) { StringBuilder where = new StringBuilder(); StringBuilder sql = new StringBuilder( "SELECT C.* FROM information_schema.columns C"); sql.Append(" JOIN information_schema.views V "); sql.Append("ON C.table_schema=V.table_schema AND C.table_name=V.table_name "); if (restrictions != null && restrictions.Length >= 2 && restrictions[1] != null) where.AppendFormat(CultureInfo.InvariantCulture, "C.table_schema='{0}' ", restrictions[1]); if (restrictions != null && restrictions.Length >= 3 && restrictions[2] != null) { if (where.Length > 0) where.Append("AND "); where.AppendFormat(CultureInfo.InvariantCulture, "C.table_name='{0}' ", restrictions[2]); } if (restrictions != null && restrictions.Length == 4 && restrictions[3] != null) { if (where.Length > 0) where.Append("AND "); where.AppendFormat(CultureInfo.InvariantCulture, "C.column_name='{0}' ", restrictions[3]); } if (where.Length > 0) sql.AppendFormat(CultureInfo.InvariantCulture, " WHERE {0}", where); DataTable dt = GetTable(sql.ToString()); dt.TableName = "ViewColumns"; dt.Columns[0].ColumnName = "VIEW_CATALOG"; dt.Columns[1].ColumnName = "VIEW_SCHEMA"; dt.Columns[2].ColumnName = "VIEW_NAME"; QuoteDefaultValues(dt); return dt; } private DataTable GetTriggers(string[] restrictions) { string[] keys = new string[4]; keys[0] = "TRIGGER_CATALOG"; keys[1] = "TRIGGER_SCHEMA"; keys[2] = "EVENT_OBJECT_TABLE"; keys[3] = "TRIGGER_NAME"; DataTable dt = Query("TRIGGERS", null, keys, restrictions); dt.TableName = "Triggers"; return dt; } /// /// Return schema information about procedures and functions /// Restrictions supported are: /// schema, name, type /// /// /// public override DataTable GetProcedures(string[] restrictions) { try { if (connection.Settings.HasProcAccess) return base.GetProcedures(restrictions); } catch (MySqlException ex) { if (ex.Number == (int)MySqlErrorCode.TableAccessDenied) connection.Settings.HasProcAccess = false; else throw; } string[] keys = new string[4]; keys[0] = "ROUTINE_CATALOG"; keys[1] = "ROUTINE_SCHEMA"; keys[2] = "ROUTINE_NAME"; keys[3] = "ROUTINE_TYPE"; DataTable dt = Query("ROUTINES", null, keys, restrictions); dt.TableName = "Procedures"; return dt; } private DataTable GetProceduresWithParameters(string[] restrictions) { DataTable dt = GetProcedures(restrictions); dt.Columns.Add("ParameterList", typeof(string)); foreach (DataRow row in dt.Rows) { row["ParameterList"] = GetProcedureParameterLine(row); } return dt; } private string GetProcedureParameterLine(DataRow isRow) { string sql = "SHOW CREATE {0} `{1}`.`{2}`"; sql = String.Format(sql, isRow["ROUTINE_TYPE"], isRow["ROUTINE_SCHEMA"], isRow["ROUTINE_NAME"]); MySqlCommand cmd = new MySqlCommand(sql, connection); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); // if we are not the owner of this proc or have permissions // then we will get null for the body if (reader.IsDBNull(2)) return null; string sql_mode = reader.GetString(1); string body = reader.GetString(2); MySqlTokenizer tokenizer = new MySqlTokenizer(body); tokenizer.AnsiQuotes = sql_mode.IndexOf("ANSI_QUOTES") != -1; tokenizer.BackslashEscapes = sql_mode.IndexOf("NO_BACKSLASH_ESCAPES") == -1; string token = tokenizer.NextToken(); while (token != "(") token = tokenizer.NextToken(); int start = tokenizer.StartIndex + 1; token = tokenizer.NextToken(); while (token != ")" || tokenizer.Quoted) { token = tokenizer.NextToken(); // if we see another ( and we are not quoted then we // are in a size element and we need to look for the closing paren if (token == "(" && !tokenizer.Quoted) { while (token != ")" || tokenizer.Quoted) token = tokenizer.NextToken(); token = tokenizer.NextToken(); } } return body.Substring(start, tokenizer.StartIndex - start); } } private void GetParametersForRoutineFromIS(DataTable dt, string[] restrictions) { Debug.Assert(dt != null); string[] keys = new string[5]; keys[0] = "SPECIFIC_CATALOG"; keys[1] = "SPECIFIC_SCHEMA"; keys[2] = "SPECIFIC_NAME"; keys[3] = "ROUTINE_TYPE"; keys[4] = "PARAMETER_NAME"; StringBuilder sql = new StringBuilder(@"SELECT * FROM INFORMATION_SCHEMA.PARAMETERS"); // now get our where clause and append it if there is one string where = GetWhereClause(null, keys, restrictions); if (!String.IsNullOrEmpty(where)) sql.AppendFormat(CultureInfo.InvariantCulture, " WHERE {0}", where); MySqlDataAdapter da = new MySqlDataAdapter(sql.ToString(), connection); da.Fill(dt); } private DataTable GetParametersFromIS(string[] restrictions, DataTable routines) { DataTable parms = new DataTable(); if (routines == null || routines.Rows.Count == 0) { if (restrictions == null) { // first fill our table with the proper structure MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM INFORMATION_SCHEMA.PARAMETERS WHERE 1=2", connection); da.Fill(parms); } else GetParametersForRoutineFromIS(parms, restrictions); } else foreach (DataRow routine in routines.Rows) { if (restrictions != null && restrictions.Length >= 3) restrictions[2] = routine["ROUTINE_NAME"].ToString(); GetParametersForRoutineFromIS(parms, restrictions); } parms.TableName = "Procedure Parameters"; return parms; } internal DataTable CreateParametersTable() { DataTable dt = new DataTable("Procedure Parameters"); dt.Columns.Add("SPECIFIC_CATALOG", typeof(string)); dt.Columns.Add("SPECIFIC_SCHEMA", typeof(string)); dt.Columns.Add("SPECIFIC_NAME", typeof(string)); dt.Columns.Add("ORDINAL_POSITION", typeof(Int32)); dt.Columns.Add("PARAMETER_MODE", typeof(string)); dt.Columns.Add("PARAMETER_NAME", typeof(string)); dt.Columns.Add("DATA_TYPE", typeof(string)); dt.Columns.Add("CHARACTER_MAXIMUM_LENGTH", typeof(Int32)); dt.Columns.Add("CHARACTER_OCTET_LENGTH", typeof(Int32)); dt.Columns.Add("NUMERIC_PRECISION", typeof(byte)); dt.Columns.Add("NUMERIC_SCALE", typeof(Int32)); dt.Columns.Add("CHARACTER_SET_NAME", typeof(string)); dt.Columns.Add("COLLATION_NAME", typeof(string)); dt.Columns.Add("DTD_IDENTIFIER", typeof(string)); dt.Columns.Add("ROUTINE_TYPE", typeof(string)); return dt; } /// /// Return schema information about parameters for procedures and functions /// Restrictions supported are: /// schema, name, type, parameter name /// public virtual DataTable GetProcedureParameters(string[] restrictions, DataTable routines) { bool is55 = connection.driver.Version.isAtLeast(5, 5, 3); try { // we want to avoid using IS if we can as it is painfully slow DataTable dt = CreateParametersTable(); GetParametersFromShowCreate(dt, restrictions, routines); return dt; } catch (Exception) { if (!is55) throw; // we get here by not having access and we are on 5.5 or later so just use IS return GetParametersFromIS(restrictions, routines); } } protected override DataTable GetSchemaInternal(string collection, string[] restrictions) { DataTable dt = base.GetSchemaInternal(collection, restrictions); if (dt != null) return dt; switch (collection) { case "VIEWS": return GetViews(restrictions); case "PROCEDURES": return GetProcedures(restrictions); case "PROCEDURES WITH PARAMETERS": return GetProceduresWithParameters(restrictions); case "PROCEDURE PARAMETERS": return GetProcedureParameters(restrictions, null); case "TRIGGERS": return GetTriggers(restrictions); case "VIEWCOLUMNS": return GetViewColumns(restrictions); } return null; } private static string GetWhereClause(string initial_where, string[] keys, string[] values) { StringBuilder where = new StringBuilder(initial_where); if (values != null) { for (int i = 0; i < keys.Length; i++) { if (i >= values.Length) break; if (values[i] == null || values[i] == String.Empty) continue; if (where.Length > 0) where.Append(" AND "); where.AppendFormat(CultureInfo.InvariantCulture, "{0} LIKE '{1}'", keys[i], values[i]); } } return where.ToString(); } private DataTable Query(string table_name, string initial_where, string[] keys, string[] values) { StringBuilder query = new StringBuilder("SELECT * FROM INFORMATION_SCHEMA."); query.Append(table_name); string where = GetWhereClause(initial_where, keys, values); if (where.Length > 0) query.AppendFormat(CultureInfo.InvariantCulture, " WHERE {0}", where); return GetTable(query.ToString()); } private DataTable GetTable(string sql) { DataTable table = new DataTable(); MySqlDataAdapter da = new MySqlDataAdapter(sql, connection); da.Fill(table); return table; } public override DataTable GetForeignKeys(string[] restrictions) { if (!connection.driver.Version.isAtLeast(5, 1, 16)) return base.GetForeignKeys(restrictions); string sql = @"SELECT rc.constraint_catalog, rc.constraint_schema, rc.constraint_name, kcu.table_catalog, kcu.table_schema, rc.table_name, rc.match_option, rc.update_rule, rc.delete_rule, NULL as referenced_table_catalog, kcu.referenced_table_schema, rc.referenced_table_name FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu ON kcu.constraint_catalog <=> rc.constraint_catalog AND kcu.constraint_schema <=> rc.constraint_schema AND kcu.constraint_name <=> rc.constraint_name AND kcu.ORDINAL_POSITION=1 WHERE 1=1"; StringBuilder where =new StringBuilder(); if (restrictions.Length >= 2 && !String.IsNullOrEmpty(restrictions[1])) where.AppendFormat(CultureInfo.InvariantCulture, " AND rc.constraint_schema LIKE '{0}'", restrictions[1]); if (restrictions.Length >= 3 && !String.IsNullOrEmpty(restrictions[2])) where.AppendFormat(CultureInfo.InvariantCulture, " AND rc.table_name LIKE '{0}'", restrictions[2]); if (restrictions.Length >= 4 && !String.IsNullOrEmpty(restrictions[3])) where.AppendFormat(CultureInfo.InvariantCulture, " AND rc.constraint_name LIKE '{0}'", restrictions[2]); sql += where.ToString(); return GetTable(sql); } public override DataTable GetForeignKeyColumns(string[] restrictions) { if (!connection.driver.Version.isAtLeast(5, 0, 6)) return base.GetForeignKeyColumns(restrictions); string sql = @"SELECT kcu.* FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu WHERE kcu.referenced_table_name IS NOT NULL"; StringBuilder where = new StringBuilder(); if (restrictions.Length >= 2 && !String.IsNullOrEmpty(restrictions[1])) where.AppendFormat(CultureInfo.InvariantCulture, " AND kcu.constraint_schema LIKE '{0}'", restrictions[1]); if (restrictions.Length >= 3 && !String.IsNullOrEmpty(restrictions[2])) where.AppendFormat(CultureInfo.InvariantCulture, " AND kcu.table_name LIKE '{0}'", restrictions[2]); if (restrictions.Length >= 4 && !String.IsNullOrEmpty(restrictions[3])) where.AppendFormat(CultureInfo.InvariantCulture, " AND kcu.constraint_name LIKE '{0}'", restrictions[3]); sql += where.ToString(); return GetTable(sql); } #region Procedures Support Rouines internal void GetParametersFromShowCreate(DataTable parametersTable, string[] restrictions, DataTable routines) { // this allows us to pass in a pre-populated routines table // and avoid the querying for them again. // we use this when calling a procedure or function if (routines == null) routines = GetSchema("procedures", restrictions); MySqlCommand cmd = connection.CreateCommand(); foreach (DataRow routine in routines.Rows) { string showCreateSql = String.Format("SHOW CREATE {0} `{1}`.`{2}`", routine["ROUTINE_TYPE"], routine["ROUTINE_SCHEMA"], routine["ROUTINE_NAME"]); cmd.CommandText = showCreateSql; try { string nameToRestrict = null; if (restrictions != null && restrictions.Length == 5 && restrictions[4] != null) nameToRestrict = restrictions[4]; using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string body = reader.GetString(2); reader.Close(); ParseProcedureBody(parametersTable, body, routine, nameToRestrict); } } catch (SqlNullValueException snex) { throw new InvalidOperationException( String.Format(Resources.UnableToRetrieveParameters, routine["ROUTINE_NAME"]), snex); } } } private void ParseProcedureBody(DataTable parametersTable, string body, DataRow row, string nameToRestrict) { ArrayList modes = new ArrayList(new string[3] { "IN", "OUT", "INOUT" }); string sqlMode = row["SQL_MODE"].ToString(); int pos = 1; MySqlTokenizer tokenizer = new MySqlTokenizer(body); tokenizer.AnsiQuotes = sqlMode.IndexOf("ANSI_QUOTES") != -1; tokenizer.BackslashEscapes = sqlMode.IndexOf("NO_BACKSLASH_ESCAPES") == -1; tokenizer.ReturnComments = false; string token = tokenizer.NextToken(); // this block will scan for the opening paren while also determining // if this routine is a function. If so, then we need to add a // parameter row for the return parameter since it is ordinal position // 0 and should appear first. while (token != "(") { if (String.Compare(token, "FUNCTION", true) == 0 && nameToRestrict == null) { parametersTable.Rows.Add(parametersTable.NewRow()); InitParameterRow(row, parametersTable.Rows[0]); } token = tokenizer.NextToken(); } token = tokenizer.NextToken(); // now move to the next token past the ( while (token != ")") { DataRow parmRow = parametersTable.NewRow(); InitParameterRow(row, parmRow); parmRow["ORDINAL_POSITION"] = pos++; // handle mode and name for the parameter string mode = token.ToUpper(CultureInfo.InvariantCulture); if (!tokenizer.Quoted && modes.Contains(mode)) { parmRow["PARAMETER_MODE"] = mode; token = tokenizer.NextToken(); } if (tokenizer.Quoted) token = token.Substring(1, token.Length - 2); parmRow["PARAMETER_NAME"] = token; // now parse data type token = ParseDataType(parmRow, tokenizer); if (token == ",") token = tokenizer.NextToken(); // now determine if we should include this row after all // we need to parse it before this check so we are correctly // positioned for the next parameter if (nameToRestrict == null || String.Compare(parmRow["PARAMETER_NAME"].ToString(), nameToRestrict, true) == 0) parametersTable.Rows.Add(parmRow); } // now parse out the return parameter if there is one. token = tokenizer.NextToken().ToUpper(CultureInfo.InvariantCulture); if (String.Compare(token, "RETURNS", true) == 0) { DataRow parameterRow = parametersTable.Rows[0]; parameterRow["PARAMETER_NAME"] = "RETURN_VALUE"; ParseDataType(parameterRow, tokenizer); } } /// /// Initializes a new row for the procedure parameters table. /// private static void InitParameterRow(DataRow procedure, DataRow parameter) { parameter["SPECIFIC_CATALOG"] = null; parameter["SPECIFIC_SCHEMA"] = procedure["ROUTINE_SCHEMA"]; parameter["SPECIFIC_NAME"] = procedure["ROUTINE_NAME"]; parameter["PARAMETER_MODE"] = "IN"; parameter["ORDINAL_POSITION"] = 0; parameter["ROUTINE_TYPE"] = procedure["ROUTINE_TYPE"]; } /// /// Parses out the elements of a procedure parameter data type. /// private string ParseDataType(DataRow row, MySqlTokenizer tokenizer) { StringBuilder dtd = new StringBuilder( tokenizer.NextToken().ToUpper(CultureInfo.InvariantCulture)); row["DATA_TYPE"] = dtd.ToString(); string type = row["DATA_TYPE"].ToString(); string token = tokenizer.NextToken(); if (token == "(") { token = tokenizer.ReadParenthesis(); dtd.AppendFormat(CultureInfo.InvariantCulture, "{0}", token); if (type != "ENUM" && type != "SET") ParseDataTypeSize(row, token); token = tokenizer.NextToken(); } else dtd.Append(GetDataTypeDefaults(type, row)); while (token != ")" && token != "," && String.Compare(token, "begin", true) != 0 && String.Compare(token, "return", true) != 0) { if (String.Compare(token, "CHARACTER", true) == 0 || String.Compare(token, "BINARY", true) == 0) { } // we don't need to do anything with this else if (String.Compare(token, "SET", true) == 0 || String.Compare(token, "CHARSET", true) == 0) row["CHARACTER_SET_NAME"] = tokenizer.NextToken(); else if (String.Compare(token, "ASCII", true) == 0) row["CHARACTER_SET_NAME"] = "latin1"; else if (String.Compare(token, "UNICODE", true) == 0) row["CHARACTER_SET_NAME"] = "ucs2"; else if (String.Compare(token, "COLLATE", true) == 0) row["COLLATION_NAME"] = tokenizer.NextToken(); else dtd.AppendFormat(CultureInfo.InvariantCulture, " {0}", token); token = tokenizer.NextToken(); } if (dtd.Length > 0) row["DTD_IDENTIFIER"] = dtd.ToString(); // now default the collation if one wasn't given if (row["COLLATION_NAME"].ToString().Length == 0 && row["CHARACTER_SET_NAME"].ToString().Length > 0) row["COLLATION_NAME"] = CharSetMap.GetDefaultCollation( row["CHARACTER_SET_NAME"].ToString(), connection); // now set the octet length if (row["CHARACTER_MAXIMUM_LENGTH"] != DBNull.Value) row["CHARACTER_OCTET_LENGTH"] = CharSetMap.GetMaxLength(row["CHARACTER_SET_NAME"].ToString(), connection) * (int)row["CHARACTER_MAXIMUM_LENGTH"]; return token; } private static string GetDataTypeDefaults(string type, DataRow row) { string format = "({0},{1})"; if (MetaData.IsNumericType(type) && row["NUMERIC_PRECISION"].ToString().Length == 0) { row["NUMERIC_PRECISION"] = 10; row["NUMERIC_SCALE"] = 0; if (!MetaData.SupportScale(type)) format = "({0})"; return String.Format(format, row["NUMERIC_PRECISION"], row["NUMERIC_SCALE"]); } return String.Empty; } private static void ParseDataTypeSize(DataRow row, string size) { size = size.Trim('(', ')'); string[] parts = size.Split(','); if (!MetaData.IsNumericType(row["DATA_TYPE"].ToString())) { row["CHARACTER_MAXIMUM_LENGTH"] = Int32.Parse(parts[0]); // will set octet length in a minute } else { row["NUMERIC_PRECISION"] = Int32.Parse(parts[0]); if (parts.Length == 2) row["NUMERIC_SCALE"] = Int32.Parse(parts[1]); } } #endregion } } mysql-connector-net-6.4.3/Source/MySql.Data/Statement.cs0000644000175000017500000002064511127003600023632 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.IO; using System.Text; using MySql.Data.Common; using System.Data; using MySql.Data.MySqlClient.Properties; using System.Collections.Generic; namespace MySql.Data.MySqlClient { internal abstract class Statement { protected MySqlCommand command; protected string commandText; private ArrayList buffers; private Statement(MySqlCommand cmd) { command = cmd; buffers = new ArrayList(); } public Statement(MySqlCommand cmd, string text) : this(cmd) { commandText = text; } #region Properties public virtual string ResolvedCommandText { get { return commandText; } } protected Driver Driver { get { return command.Connection.driver; } } protected MySqlConnection Connection { get { return command.Connection; } } protected MySqlParameterCollection Parameters { get { return command.Parameters; } } #endregion public virtual void Close(MySqlDataReader reader) { } public virtual void Resolve(bool preparing) { } public virtual void Execute() { // we keep a reference to this until we are done BindParameters(); ExecuteNext(); } public virtual bool ExecuteNext() { if (buffers.Count == 0) return false; MySqlPacket packet = (MySqlPacket)buffers[0]; //MemoryStream ms = stream.InternalBuffer; Driver.SendQuery(packet); buffers.RemoveAt(0); return true; } protected virtual void BindParameters() { MySqlParameterCollection parameters = command.Parameters; int index = 0; while (true) { InternalBindParameters(ResolvedCommandText, parameters, null); // if we are not batching, then we are done. This is only really relevant the // first time through if (command.Batch == null) return; while (index < command.Batch.Count) { MySqlCommand batchedCmd = command.Batch[index++]; MySqlPacket packet = (MySqlPacket)buffers[buffers.Count - 1]; // now we make a guess if this statement will fit in our current stream long estimatedCmdSize = batchedCmd.EstimatedSize(); if (((packet.Length-4) + estimatedCmdSize) > Connection.driver.MaxPacketSize) { // it won't, so we setup to start a new run from here parameters = batchedCmd.Parameters; break; } // looks like we might have room for it so we remember the current end of the stream buffers.RemoveAt(buffers.Count - 1); //long originalLength = packet.Length - 4; // and attempt to stream the next command string text = ResolvedCommandText; if (text.StartsWith("(")) packet.WriteStringNoNull(", "); else packet.WriteStringNoNull("; "); InternalBindParameters(text, batchedCmd.Parameters, packet); if ((packet.Length-4) > Connection.driver.MaxPacketSize) { //TODO //stream.InternalBuffer.SetLength(originalLength); parameters = batchedCmd.Parameters; break; } } if (index == command.Batch.Count) return; } } private void InternalBindParameters(string sql, MySqlParameterCollection parameters, MySqlPacket packet) { bool sqlServerMode = command.Connection.Settings.SqlServerMode; if (packet == null) { packet = new MySqlPacket(Driver.Encoding); packet.Version = Driver.Version; packet.WriteByte(0); } MySqlTokenizer tokenizer = new MySqlTokenizer(sql); tokenizer.ReturnComments = true; tokenizer.SqlServerMode = sqlServerMode; int pos = 0; string token = tokenizer.NextToken(); while (token != null) { // serialize everything that came before the token (i.e. whitespace) packet.WriteStringNoNull(sql.Substring(pos, tokenizer.StartIndex - pos)); pos = tokenizer.StopIndex; if (MySqlTokenizer.IsParameter(token)) { if (SerializeParameter(parameters, packet, token)) token = null; } if (token != null) { if (sqlServerMode && tokenizer.Quoted && token.StartsWith("[")) token = String.Format("`{0}`", token.Substring(1, token.Length - 2)); packet.WriteStringNoNull(token); } token = tokenizer.NextToken(); } buffers.Add(packet); } protected virtual bool ShouldIgnoreMissingParameter(string parameterName) { if (Connection.Settings.AllowUserVariables) return true; if (parameterName.StartsWith("@" +StoredProcedure.ParameterPrefix)) return true; if (parameterName.Length > 1 && (parameterName[1] == '`' || parameterName[1] == '\'')) return true; return false; } /// /// Serializes the given parameter to the given memory stream /// /// /// This method is called by PrepareSqlBuffers to convert the given /// parameter to bytes and write those bytes to the given memory stream. /// /// /// True if the parameter was successfully serialized, false otherwise. private bool SerializeParameter(MySqlParameterCollection parameters, MySqlPacket packet, string parmName) { MySqlParameter parameter = parameters.GetParameterFlexible(parmName, false); if (parameter == null) { // if we are allowing user variables and the parameter name starts with @ // then we can't throw an exception if (parmName.StartsWith("@") && ShouldIgnoreMissingParameter(parmName)) return false; throw new MySqlException( String.Format(Resources.ParameterMustBeDefined, parmName)); } parameter.Serialize(packet, false, Connection.Settings); return true; } } } mysql-connector-net-6.4.3/Source/MySql.Data/PerformanceMonitor.cs0000644000175000017500000000706411127003600025477 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Diagnostics; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { internal class PerformanceMonitor { private MySqlConnection connection; private static PerformanceCounter procedureHardQueries; private static PerformanceCounter procedureSoftQueries; public PerformanceMonitor(MySqlConnection connection) { this.connection = connection; string categoryName = Resources.PerfMonCategoryName; if (connection.Settings.UsePerformanceMonitor && procedureHardQueries == null) { try { procedureHardQueries = new PerformanceCounter(categoryName, "HardProcedureQueries", false); procedureSoftQueries = new PerformanceCounter(categoryName, "SoftProcedureQueries", false); } catch (Exception ex) { MySqlTrace.LogError(connection.ServerThread, ex.Message); } } } #if DEBUG private void EnsurePerfCategoryExist() { CounterCreationDataCollection ccdc = new CounterCreationDataCollection(); CounterCreationData ccd = new CounterCreationData(); ccd.CounterType = PerformanceCounterType.NumberOfItems32; ccd.CounterName = "HardProcedureQueries"; ccdc.Add(ccd); ccd = new CounterCreationData(); ccd.CounterType = PerformanceCounterType.NumberOfItems32; ccd.CounterName = "SoftProcedureQueries"; ccdc.Add(ccd); if (!PerformanceCounterCategory.Exists(Resources.PerfMonCategoryName)) PerformanceCounterCategory.Create(Resources.PerfMonCategoryName, null, ccdc); } #endif public void AddHardProcedureQuery() { if (!connection.Settings.UsePerformanceMonitor || procedureHardQueries == null) return; procedureHardQueries.Increment(); } public void AddSoftProcedureQuery() { if (!connection.Settings.UsePerformanceMonitor || procedureSoftQueries == null) return; procedureSoftQueries.Increment(); } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/0000755000175000017500000000000011127003600022270 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Data/zlib/Adler32.cs0000644000175000017500000001114011127003600024010 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { sealed class Adler32 { // largest prime smaller than 65536 private const int BASE = 65521; // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 private const int NMAX = 5552; internal long adler32(long adler, byte[] buf, int index, int len) { if (buf == null) { return 1L; } long s1 = adler & 0xffff; long s2 = (adler >> 16) & 0xffff; int k; while (len > 0) { k = len < NMAX?len:NMAX; len -= k; while (k >= 16) { s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; s1 += (buf[index++] & 0xff); s2 += s1; k -= 16; } if (k != 0) { do { s1 += (buf[index++] & 0xff); s2 += s1; } while (--k != 0); } s1 %= BASE; s2 %= BASE; } return (s2 << 16) | s1; } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/Tree.cs0000644000175000017500000004064311127003600023525 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { sealed class Tree { private const int MAX_BITS = 15; private const int BL_CODES = 19; private const int D_CODES = 30; private const int LITERALS = 256; private const int LENGTH_CODES = 29; private static readonly int L_CODES = (LITERALS + 1 + LENGTH_CODES); private static readonly int HEAP_SIZE = (2 * L_CODES + 1); // Bit length codes must not exceed MAX_BL_BITS bits internal const int MAX_BL_BITS = 7; // end of block literal code internal const int END_BLOCK = 256; // repeat previous bit length 3-6 times (2 bits of repeat count) internal const int REP_3_6 = 16; // repeat a zero length 3-10 times (3 bits of repeat count) internal const int REPZ_3_10 = 17; // repeat a zero length 11-138 times (7 bits of repeat count) internal const int REPZ_11_138 = 18; // extra bits for each length code internal static readonly int[] extra_lbits = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; // extra bits for each distance code internal static readonly int[] extra_dbits = new int[]{0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; // extra bits for each bit length code internal static readonly int[] extra_blbits = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; internal static readonly byte[] bl_order = new byte[]{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; // The lengths of the bit length codes are sent in order of decreasing // probability, to avoid transmitting the lengths for unused bit // length codes. internal const int Buf_size = 8 * 2; // see definition of array dist_code below internal const int DIST_CODE_LEN = 512; internal static readonly byte[] _dist_code = new byte[]{0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29}; internal static readonly byte[] _length_code = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28}; internal static readonly int[] base_length = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0}; internal static readonly int[] base_dist = new int[]{0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576}; // Mapping from a distance to a distance code. dist is the distance - 1 and // must not have side effects. _dist_code[256] and _dist_code[257] are never // used. internal static int d_code(int dist) { return ((dist) < 256?_dist_code[dist]:_dist_code[256 + (SupportClass.URShift((dist), 7))]); } internal short[] dyn_tree; // the dynamic tree internal int max_code; // largest code with non zero frequency internal StaticTree stat_desc; // the corresponding static tree // Compute the optimal bit lengths for a tree and update the total bit length // for the current block. // IN assertion: the fields freq and dad are set, heap[heap_max] and // above are the tree nodes sorted by increasing frequency. // OUT assertions: the field len is set to the optimal bit length, the // array bl_count contains the frequencies for each bit length. // The length opt_len is updated; static_len is also updated if stree is // not null. internal void gen_bitlen(Deflate s) { short[] tree = dyn_tree; short[] stree = stat_desc.static_tree; int[] extra = stat_desc.extra_bits; int base_Renamed = stat_desc.extra_base; int max_length = stat_desc.max_length; int h; // heap index int n, m; // iterate over the tree elements int bits; // bit length int xbits; // extra bits short f; // frequency int overflow = 0; // number of elements with bit length too large for (bits = 0; bits <= MAX_BITS; bits++) s.bl_count[bits] = 0; // In a first pass, compute the optimal bit lengths (which may // overflow in the case of the bit length tree). tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1] = (short) bits; // We overwrite tree[n*2+1] which is no longer needed if (n > max_code) continue; // not a leaf node s.bl_count[bits]++; xbits = 0; if (n >= base_Renamed) xbits = extra[n - base_Renamed]; f = tree[n * 2]; s.opt_len += f * (bits + xbits); if (stree != null) s.static_len += f * (stree[n * 2 + 1] + xbits); } if (overflow == 0) return ; // This happens for example on obj2 and pic of the Calgary corpus // Find the first bit length which could increase: do { bits = max_length - 1; while (s.bl_count[bits] == 0) bits--; s.bl_count[bits]--; // move one leaf down the tree s.bl_count[bits + 1] = (short) (s.bl_count[bits + 1] + 2); // move one overflow item as its brother s.bl_count[max_length]--; // The brother of the overflow item also moves one step up, // but this does not affect bl_count[max_length] overflow -= 2; } while (overflow > 0); for (bits = max_length; bits != 0; bits--) { n = s.bl_count[bits]; while (n != 0) { m = s.heap[--h]; if (m > max_code) continue; if (tree[m * 2 + 1] != bits) { s.opt_len = (int) (s.opt_len + ((long) bits - (long) tree[m * 2 + 1]) * (long) tree[m * 2]); tree[m * 2 + 1] = (short) bits; } n--; } } } // Construct one Huffman tree and assigns the code bit strings and lengths. // Update the total bit length for the current block. // IN assertion: the field freq is set for all tree elements. // OUT assertions: the fields len and code are set to the optimal bit length // and corresponding code. The length opt_len is updated; static_len is // also updated if stree is not null. The field max_code is set. internal void build_tree(Deflate s) { short[] tree = dyn_tree; short[] stree = stat_desc.static_tree; int elems = stat_desc.elems; int n, m; // iterate over heap elements int max_code = - 1; // largest code with non zero frequency int node; // new node being created // Construct the initial heap, with least frequent element in // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. // heap[0] is not used. s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2] != 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1] = 0; } } // The pkzip format requires that at least one distance code exists, // and that at least one bit should be sent even if there is only one // possible code. So to avoid special checks later on we force at least // two codes of non zero frequency. while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2?++max_code:0); tree[node * 2] = 1; s.depth[node] = 0; s.opt_len--; if (stree != null) s.static_len -= stree[node * 2 + 1]; // node is 0 or 1 so it does not have extra bits } this.max_code = max_code; // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, // establish sub-heaps of increasing lengths: for (n = s.heap_len / 2; n >= 1; n--) s.pqdownheap(tree, n); // Construct the Huffman tree by repeatedly combining the least two // frequent nodes. node = elems; // next internal node of the tree do { // n = node of least frequency n = s.heap[1]; s.heap[1] = s.heap[s.heap_len--]; s.pqdownheap(tree, 1); m = s.heap[1]; // m = node of next least frequency s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency s.heap[--s.heap_max] = m; // Create a new node father of n and m tree[node * 2] = (short) (tree[n * 2] + tree[m * 2]); s.depth[node] = (byte) (System.Math.Max((byte) s.depth[n], (byte) s.depth[m]) + 1); tree[n * 2 + 1] = tree[m * 2 + 1] = (short) node; // and insert the new node in the heap s.heap[1] = node++; s.pqdownheap(tree, 1); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1]; // At this point, the fields freq and dad are set. We can now // generate the bit lengths. gen_bitlen(s); // The field len is now set, we can generate the bit codes gen_codes(tree, max_code, s.bl_count); } // Generate the codes for a given tree and bit counts (which need not be // optimal). // IN assertion: the array bl_count contains the bit length statistics for // the given tree and the field len is set for all tree elements. // OUT assertion: the field code is set for all tree elements of non // zero code length. internal static void gen_codes(short[] tree, int max_code, short[] bl_count) { short[] next_code = new short[MAX_BITS + 1]; // next code value for each bit length short code = 0; // running code value int bits; // bit index int n; // code index // The distribution counts are first used to generate the code values // without bit reversal. for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (short) ((code + bl_count[bits - 1]) << 1); } // Check that the bit counts in bl_count are consistent. The last code // must be all ones. //Assert (code + bl_count[MAX_BITS]-1 == (1< 0); return SupportClass.URShift(res, 1); } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/SupportClass.cs0000644000175000017500000002026111127003600025262 0ustar directhexdirecthexusing System; /* Contains conversion support elements such as classes, interfaces and static methods. */ namespace zlib { class SupportClass { /// /// This method returns the literal value received /// /// The literal to return /// The received value public static long Identity(long literal) { return literal; } /// /// This method returns the literal value received /// /// The literal to return /// The received value public static ulong Identity(ulong literal) { return literal; } /// /// This method returns the literal value received /// /// The literal to return /// The received value public static float Identity(float literal) { return literal; } /// /// This method returns the literal value received /// /// The literal to return /// The received value public static double Identity(double literal) { return literal; } /*******************************/ /// /// Performs an unsigned bitwise right shift with the specified number /// /// Number to operate on /// Ammount of bits to shift /// The resulting number from the shift operation public static int URShift(int number, int bits) { if ( number >= 0) return number >> bits; else return (number >> bits) + (2 << ~bits); } /// /// Performs an unsigned bitwise right shift with the specified number /// /// Number to operate on /// Ammount of bits to shift /// The resulting number from the shift operation public static int URShift(int number, long bits) { return URShift(number, (int)bits); } /// /// Performs an unsigned bitwise right shift with the specified number /// /// Number to operate on /// Ammount of bits to shift /// The resulting number from the shift operation public static long URShift(long number, int bits) { if ( number >= 0) return number >> bits; else return (number >> bits) + (2L << ~bits); } /// /// Performs an unsigned bitwise right shift with the specified number /// /// Number to operate on /// Ammount of bits to shift /// The resulting number from the shift operation public static long URShift(long number, long bits) { return URShift(number, (int)bits); } /*******************************/ /// Reads a number of characters from the current source Stream and writes the data to the target array at the specified index. /// The source Stream to read from. /// Contains the array of characteres read from the source Stream. /// The starting index of the target array. /// The maximum number of characters to read from the source Stream. /// The number of characters read. The number will be less than or equal to count depending on the data available in the source Stream. Returns -1 if the end of the stream is reached. public static System.Int32 ReadInput(System.IO.Stream sourceStream, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) return 0; byte[] receiver = new byte[target.Length]; int bytesRead = sourceStream.Read(receiver, start, count); // Returns -1 if EOF if (bytesRead == 0) return -1; for(int i = start; i < start + bytesRead; i++) target[i] = (byte)receiver[i]; return bytesRead; } /// Reads a number of characters from the current source TextReader and writes the data to the target array at the specified index. /// The source TextReader to read from /// Contains the array of characteres read from the source TextReader. /// The starting index of the target array. /// The maximum number of characters to read from the source TextReader. /// The number of characters read. The number will be less than or equal to count depending on the data available in the source TextReader. Returns -1 if the end of the stream is reached. public static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count) { // Returns 0 bytes if not enough space in target if (target.Length == 0) return 0; char[] charArray = new char[target.Length]; int bytesRead = sourceTextReader.Read(charArray, start, count); // Returns -1 if EOF if (bytesRead == 0) return -1; for(int index=start; index /// Converts a string to an array of bytes /// /// The string to be converted /// The new array of bytes public static byte[] ToByteArray(System.String sourceString) { return System.Text.UTF8Encoding.UTF8.GetBytes(sourceString); } /// /// Converts an array of bytes to an array of chars /// /// The array of bytes to convert /// The new array of chars public static char[] ToCharArray(byte[] byteArray) { return System.Text.UTF8Encoding.UTF8.GetChars(byteArray); } #if !CF /*******************************/ /// /// Writes an object to the specified Stream /// /// The target Stream /// The object to be sent public static void Serialize(System.IO.Stream stream, System.Object objectToSend) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(stream, objectToSend); } /// /// Writes an object to the specified BinaryWriter /// /// The target BinaryWriter /// The object to be sent public static void Serialize(System.IO.BinaryWriter binaryWriter, System.Object objectToSend) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); formatter.Serialize(binaryWriter.BaseStream, objectToSend); } /*******************************/ /// /// Deserializes an object, or an entire graph of connected objects, and returns the object intance /// /// Reader instance used to read the object /// The object instance public static System.Object Deserialize(System.IO.BinaryReader binaryReader) { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); return formatter.Deserialize(binaryReader.BaseStream); } #endif /*******************************/ /// /// Writes the exception stack trace to the received stream /// /// Exception to obtain information from /// Output sream used to write to public static void WriteStackTrace(System.Exception throwable, System.IO.TextWriter stream) { stream.Write(throwable.StackTrace); stream.Flush(); } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/StaticTree.cs0000644000175000017500000001604511127003600024674 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { sealed class StaticTree { private const int MAX_BITS = 15; private const int BL_CODES = 19; private const int D_CODES = 30; private const int LITERALS = 256; private const int LENGTH_CODES = 29; private static readonly int L_CODES = (LITERALS + 1 + LENGTH_CODES); // Bit length codes must not exceed MAX_BL_BITS bits internal const int MAX_BL_BITS = 7; internal static readonly short[] static_ltree = new short[]{12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7 , 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8}; internal static readonly short[] static_dtree = new short[]{0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5}; internal static StaticTree static_l_desc; internal static StaticTree static_d_desc; internal static StaticTree static_bl_desc; internal short[] static_tree; // static tree or null internal int[] extra_bits; // extra bits for each code or null internal int extra_base; // base index for extra_bits internal int elems; // max number of elements in the tree internal int max_length; // max bit length for the codes internal StaticTree(short[] static_tree, int[] extra_bits, int extra_base, int elems, int max_length) { this.static_tree = static_tree; this.extra_bits = extra_bits; this.extra_base = extra_base; this.elems = elems; this.max_length = max_length; } static StaticTree() { static_l_desc = new StaticTree(static_ltree, Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); static_d_desc = new StaticTree(static_dtree, Tree.extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc = new StaticTree(null, Tree.extra_blbits, 0, BL_CODES, MAX_BL_BITS); } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/ZInputStream.cs0000644000175000017500000001453611127003600025235 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2001 Lapo Luchini. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { class ZInputStream : System.IO.BinaryReader { public long maxInput; private void InitBlock() { flush = zlibConst.Z_NO_FLUSH; buf = new byte[bufsize]; } virtual public int FlushMode { get { return (flush); } set { this.flush = value; } } /// Returns the total number of bytes input so far. virtual public long TotalIn { get { return z.total_in; } } /// Returns the total number of bytes output so far. virtual public long TotalOut { get { return z.total_out; } } protected internal ZStream z = new ZStream(); protected internal int bufsize = 512; protected internal int flush; protected internal byte[] buf, buf1 = new byte[1]; protected internal bool compress; private System.IO.Stream in_Renamed = null; public ZInputStream(System.IO.Stream in_Renamed) : base(in_Renamed) { InitBlock(); this.in_Renamed = in_Renamed; z.inflateInit(); compress = false; z.next_in = buf; z.next_in_index = 0; z.avail_in = 0; } public ZInputStream(System.IO.Stream in_Renamed, int level) : base(in_Renamed) { InitBlock(); this.in_Renamed = in_Renamed; z.deflateInit(level); compress = true; z.next_in = buf; z.next_in_index = 0; z.avail_in = 0; } /*public int available() throws IOException { return inf.finished() ? 0 : 1; }*/ public override int Read() { if (read(buf1, 0, 1) == -1) return (-1); return (buf1[0] & 0xFF); } private bool nomoreinput = false; public int read(byte[] b, int off, int len) { if (len == 0) return (0); int err; z.next_out = b; z.next_out_index = off; z.avail_out = len; do { if ((z.avail_in == 0) && (!nomoreinput)) { // if buffer is empty and more input is avaiable, refill it z.next_in_index = 0; int inToRead = bufsize; if (maxInput > 0) { if (TotalIn < maxInput) inToRead = (int)(Math.Min(maxInput - TotalIn, (long)bufsize)); else z.avail_in = -1; } if (z.avail_in != -1) z.avail_in = SupportClass.ReadInput(in_Renamed, buf, 0, inToRead); //(bufsize 0 && err == zlibConst.Z_OK); //while (z.avail_out == len && err == zlibConst.Z_OK); //System.err.print("("+(len-z.avail_out)+")"); return (len - z.avail_out); } public long skip(long n) { int len = 512; if (n < len) len = (int)n; byte[] tmp = new byte[len]; return ((long)SupportClass.ReadInput(BaseStream, tmp, 0, tmp.Length)); } public override void Close() { in_Renamed.Close(); } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/ZStreamException.cs0000644000175000017500000000651011127003600026065 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { // [Serializable] class ZStreamException:System.IO.IOException { public ZStreamException():base() { } public ZStreamException(System.String s):base(s) { } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/ZStream.cs0000644000175000017500000002014011127003600024201 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { sealed class ZStream { private const int MAX_WBITS = 15; // 32K LZ77 window private static readonly int DEF_WBITS = MAX_WBITS; private const int Z_NO_FLUSH = 0; private const int Z_PARTIAL_FLUSH = 1; private const int Z_SYNC_FLUSH = 2; private const int Z_FULL_FLUSH = 3; private const int Z_FINISH = 4; private const int MAX_MEM_LEVEL = 9; private const int Z_OK = 0; private const int Z_STREAM_END = 1; private const int Z_NEED_DICT = 2; private const int Z_ERRNO = -1; private const int Z_STREAM_ERROR = -2; private const int Z_DATA_ERROR = -3; private const int Z_MEM_ERROR = -4; private const int Z_BUF_ERROR = -5; private const int Z_VERSION_ERROR = -6; public byte[] next_in; // next input byte public int next_in_index; public int avail_in; // number of bytes available at next_in public long total_in; // total nb of input bytes read so far public byte[] next_out; // next output byte should be put there public int next_out_index; public int avail_out; // remaining free space at next_out public long total_out; // total nb of bytes output so far public System.String msg; internal Deflate dstate; internal Inflate istate; internal int data_type; // best guess about the data type: ascii or binary public long adler; internal Adler32 _adler = new Adler32(); public int inflateInit() { return inflateInit(DEF_WBITS); } public int inflateInit(int w) { istate = new Inflate(); return istate.inflateInit(this, w); } public int inflate(int f) { if (istate == null) return Z_STREAM_ERROR; return istate.inflate(this, f); } public int inflateEnd() { if (istate == null) return Z_STREAM_ERROR; int ret = istate.inflateEnd(this); istate = null; return ret; } public int inflateSync() { if (istate == null) return Z_STREAM_ERROR; return istate.inflateSync(this); } public int inflateSetDictionary(byte[] dictionary, int dictLength) { if (istate == null) return Z_STREAM_ERROR; return istate.inflateSetDictionary(this, dictionary, dictLength); } public int deflateInit(int level) { return deflateInit(level, MAX_WBITS); } public int deflateInit(int level, int bits) { dstate = new Deflate(); return dstate.deflateInit(this, level, bits); } public int deflate(int flush) { if (dstate == null) { return Z_STREAM_ERROR; } return dstate.deflate(this, flush); } public int deflateEnd() { if (dstate == null) return Z_STREAM_ERROR; int ret = dstate.deflateEnd(); dstate = null; return ret; } public int deflateParams(int level, int strategy) { if (dstate == null) return Z_STREAM_ERROR; return dstate.deflateParams(this, level, strategy); } public int deflateSetDictionary(byte[] dictionary, int dictLength) { if (dstate == null) return Z_STREAM_ERROR; return dstate.deflateSetDictionary(this, dictionary, dictLength); } // Flush as much pending output as possible. All deflate() output goes // through this function so some applications may wish to modify it // to avoid allocating a large strm->next_out buffer and copying into it. // (See also read_buf()). internal void flush_pending() { int len = dstate.pending; if (len > avail_out) len = avail_out; if (len == 0) return; if (dstate.pending_buf.Length <= dstate.pending_out || next_out.Length <= next_out_index || dstate.pending_buf.Length < (dstate.pending_out + len) || next_out.Length < (next_out_index + len)) { System.Console.Out.WriteLine(dstate.pending_buf.Length + ", " + dstate.pending_out + ", " + next_out.Length + ", " + next_out_index + ", " + len); System.Console.Out.WriteLine("avail_out=" + avail_out); } Array.Copy(dstate.pending_buf, dstate.pending_out, next_out, next_out_index, len); next_out_index += len; dstate.pending_out += len; total_out += len; avail_out -= len; dstate.pending -= len; if (dstate.pending == 0) { dstate.pending_out = 0; } } // Read a new buffer from the current input stream, update the adler32 // and total number of bytes read. All deflate() input goes through // this function so some applications may wish to modify it to avoid // allocating a large strm->next_in buffer and copying from it. // (See also flush_pending()). internal int read_buf(byte[] buf, int start, int size) { int len = avail_in; if (len > size) len = size; if (len == 0) return 0; avail_in -= len; if (dstate.noheader == 0) { adler = _adler.adler32(adler, next_in, next_in_index, len); } Array.Copy(next_in, next_in_index, buf, start, len); next_in_index += len; total_in += len; return len; } public void free() { next_in = null; next_out = null; msg = null; _adler = null; } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/ZOutputStream.cs0000644000175000017500000002163211127003600025431 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2001 Lapo Luchini. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { class ZOutputStream:System.IO.Stream { private void InitBlock() { flush_Renamed_Field = zlibConst.Z_NO_FLUSH; buf = new byte[bufsize]; } virtual public int FlushMode { get { return (flush_Renamed_Field); } set { this.flush_Renamed_Field = value; } } /// Returns the total number of bytes input so far. virtual public long TotalIn { get { return z.total_in; } } /// Returns the total number of bytes output so far. virtual public long TotalOut { get { return z.total_out; } } protected internal ZStream z = new ZStream(); protected internal int bufsize = 512; protected internal int flush_Renamed_Field; protected internal byte[] buf, buf1 = new byte[1]; protected internal bool compress; private System.IO.Stream out_Renamed; public ZOutputStream(System.IO.Stream out_Renamed):base() { InitBlock(); this.out_Renamed = out_Renamed; z.inflateInit(); compress = false; } public ZOutputStream(System.IO.Stream out_Renamed, int level):base() { InitBlock(); this.out_Renamed = out_Renamed; z.deflateInit(level); compress = true; } public void WriteByte(int b) { buf1[0] = (byte) b; Write(buf1, 0, 1); } //UPGRADE_TODO: The differences in the Expected value of parameters for method 'WriteByte' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1092_3"' public override void WriteByte(byte b) { WriteByte((int) b); } public override void Write(System.Byte[] b1, int off, int len) { if (len == 0) return ; int err; byte[] b = new byte[b1.Length]; System.Array.Copy(b1,b,b1.Length); z.next_in = b; z.next_in_index = off; z.avail_in = len; do { z.next_out = buf; z.next_out_index = 0; z.avail_out = bufsize; if (compress) err = z.deflate(flush_Renamed_Field); else err = z.inflate(flush_Renamed_Field); if (err != zlibConst.Z_OK) throw new ZStreamException((compress?"de":"in") + "flating: " + z.msg); out_Renamed.Write(buf, 0, bufsize - z.avail_out); } while (z.avail_in > 0 || z.avail_out == 0); } public virtual void finish() { int err; do { z.next_out = buf; z.next_out_index = 0; z.avail_out = bufsize; if (compress) { err = z.deflate(zlibConst.Z_FINISH); } else { err = z.inflate(zlibConst.Z_FINISH); } if (err != zlibConst.Z_STREAM_END && err != zlibConst.Z_OK) throw new ZStreamException((compress?"de":"in") + "flating: " + z.msg); if (bufsize - z.avail_out > 0) { out_Renamed.Write(buf, 0, bufsize - z.avail_out); } } while (z.avail_in > 0 || z.avail_out == 0); try { Flush(); } catch { } } public virtual void end() { if (compress) { z.deflateEnd(); } else { z.inflateEnd(); } z.free(); z = null; } public override void Close() { try { try { finish(); } catch { } } finally { end(); out_Renamed.Close(); out_Renamed = null; } } public override void Flush() { out_Renamed.Flush(); } //UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"' public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) { return 0; } //UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"' public override void SetLength(System.Int64 value) { } //UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"' public override System.Int64 Seek(System.Int64 offset, System.IO.SeekOrigin origin) { return 0; } //UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"' public override System.Boolean CanRead { get { return false; } } //UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"' public override System.Boolean CanSeek { get { return false; } } //UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"' public override System.Boolean CanWrite { get { return false; } } //UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"' public override System.Int64 Length { get { return 0; } } //UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"' public override System.Int64 Position { get { return 0; } set { } } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/InfTree.cs0000644000175000017500000004406111127003600024160 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { sealed class InfTree { private const int MANY = 1440; private const int Z_OK = 0; private const int Z_STREAM_END = 1; private const int Z_NEED_DICT = 2; private const int Z_ERRNO = - 1; private const int Z_STREAM_ERROR = - 2; private const int Z_DATA_ERROR = - 3; private const int Z_MEM_ERROR = - 4; private const int Z_BUF_ERROR = - 5; private const int Z_VERSION_ERROR = - 6; internal const int fixed_bl = 9; internal const int fixed_bd = 5; internal static readonly int[] fixed_tl = new int[]{96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 160, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 176, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 244, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 194, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 154, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 230, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 174, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 190, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 193, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 205, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 173, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 221, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 147, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 243, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 235, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 159, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 223, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 255}; internal static readonly int[] fixed_td = new int[]{80, 5, 1, 87, 5, 257, 83, 5, 17, 91, 5, 4097, 81, 5, 5, 89, 5, 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, 513, 84, 5, 33, 92, 5, 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, 80, 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5, 7, 89, 5, 1537, 85, 5, 97, 93, 5, 24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92, 5, 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577}; // Tables for deflate from PKZIP's appnote.txt. internal static readonly int[] cplens = new int[]{3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; internal static readonly int[] cplext = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; internal static readonly int[] cpdist = new int[]{1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; internal static readonly int[] cpdext = new int[]{0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; // If BMAX needs to be larger than 16, then h and x[] should be uLong. internal const int BMAX = 15; // maximum bit length of any code internal static int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[] t, int[] m, int[] hp, int[] hn, int[] v) { // Given a list of code lengths and a maximum table size, make a set of // tables to decode that set of codes. Return Z_OK on success, Z_BUF_ERROR // if the given code set is incomplete (the tables are still built in this // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of // lengths), or Z_MEM_ERROR if not enough memory. int a; // counter for codes of length k int[] c = new int[BMAX + 1]; // bit length count table int f; // i repeats in table every f entries int g; // maximum code length int h; // table level int i; // counter, current code int j; // counter int k; // number of bits in current code int l; // bits per table (returned in m) int mask; // (1 << w) - 1, to avoid cc -O bug on HP int p; // pointer into c[], b[], or v[] int q; // points to current table int[] r = new int[3]; // table entry for structure assignment int[] u = new int[BMAX]; // table stack int w; // bits before this table == (l * h) int[] x = new int[BMAX + 1]; // bit offsets, then code stack int xp; // pointer into x int y; // number of dummy codes added int z; // number of entries in current table // Generate counts for each bit length p = 0; i = n; do { c[b[bindex + p]]++; p++; i--; // assume all entries <= BMAX } while (i != 0); if (c[0] == n) { // null input--all zero length codes t[0] = - 1; m[0] = 0; return Z_OK; } // Find minimum and maximum length, bound *m by those l = m[0]; for (j = 1; j <= BMAX; j++) if (c[j] != 0) break; k = j; // minimum code length if (l < j) { l = j; } for (i = BMAX; i != 0; i--) { if (c[i] != 0) break; } g = i; // maximum code length if (l > i) { l = i; } m[0] = l; // Adjust last length count to fill out codes, if needed for (y = 1 << j; j < i; j++, y <<= 1) { if ((y -= c[j]) < 0) { return Z_DATA_ERROR; } } if ((y -= c[i]) < 0) { return Z_DATA_ERROR; } c[i] += y; // Generate starting offsets into the value table for each length x[1] = j = 0; p = 1; xp = 2; while (--i != 0) { // note that i == g from above x[xp] = (j += c[p]); xp++; p++; } // Make a table of values in order of bit lengths i = 0; p = 0; do { if ((j = b[bindex + p]) != 0) { v[x[j]++] = i; } p++; } while (++i < n); n = x[g]; // set n to length of v // Generate the Huffman codes and for each, make the table entries x[0] = i = 0; // first Huffman code is zero p = 0; // grab values in bit order h = - 1; // no tables yet--level -1 w = - l; // bits decoded == (l * h) u[0] = 0; // just to keep compilers happy q = 0; // ditto z = 0; // ditto // go through the bit lengths (k already is bits in shortest code) for (; k <= g; k++) { a = c[k]; while (a-- != 0) { // here i is the Huffman code of length k bits for value *p // make tables up to required level while (k > w + l) { h++; w += l; // previous table always l bits // compute minimum size table less than or equal to l bits z = g - w; z = (z > l)?l:z; // table size upper limit if ((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table // too few codes for k-w bit table f -= (a + 1); // deduct codes from patterns left xp = k; if (j < z) { while (++j < z) { // try smaller tables up to z bits if ((f <<= 1) <= c[++xp]) break; // enough codes to use up j bits f -= c[xp]; // else deduct codes from patterns } } } z = 1 << j; // table entries for j-bit table // allocate new table if (hn[0] + z > MANY) // (note: doesn't matter for fixed) return Z_DATA_ERROR; // overflow of MANY u[h] = q = hn[0]; // DEBUG hn[0] += z; // connect to last table, if there is one if (h != 0) { x[h] = i; // save pattern for backing up r[0] = (byte) j; // bits in this table r[1] = (byte) l; // bits to dump before this table j = SupportClass.URShift(i, (w - l)); r[2] = (int) (q - u[h - 1] - j); // offset to this table Array.Copy(r, 0, hp, (u[h - 1] + j) * 3, 3); // connect to last table } else { t[0] = q; // first table is returned result } } // set up table entry in r r[1] = (byte) (k - w); if (p >= n) { r[0] = 128 + 64; // out of values--invalid code } else if (v[p] < s) { r[0] = (byte) (v[p] < 256?0:32 + 64); // 256 is end-of-block r[2] = v[p++]; // simple code is just the value } else { r[0] = (byte) (e[v[p] - s] + 16 + 64); // non-simple--look up in lists r[2] = d[v[p++] - s]; } // fill code-like entries with r f = 1 << (k - w); for (j = SupportClass.URShift(i, w); j < z; j += f) { Array.Copy(r, 0, hp, (q + j) * 3, 3); } // backwards increment the k-bit code i for (j = 1 << (k - 1); (i & j) != 0; j = SupportClass.URShift(j, 1)) { i ^= j; } i ^= j; // backup over finished tables mask = (1 << w) - 1; // needed on HP, cc -O bug while ((i & mask) != x[h]) { h--; // don't need to update q w -= l; mask = (1 << w) - 1; } } } // Return Z_BUF_ERROR if we were given an incomplete table return y != 0 && g != 1?Z_BUF_ERROR:Z_OK; } internal static int inflate_trees_bits(int[] c, int[] bb, int[] tb, int[] hp, ZStream z) { int r; int[] hn = new int[1]; // hufts used in space int[] v = new int[19]; // work area for huft_build r = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v); if (r == Z_DATA_ERROR) { z.msg = "oversubscribed dynamic bit lengths tree"; } else if (r == Z_BUF_ERROR || bb[0] == 0) { z.msg = "incomplete dynamic bit lengths tree"; r = Z_DATA_ERROR; } return r; } internal static int inflate_trees_dynamic(int nl, int nd, int[] c, int[] bl, int[] bd, int[] tl, int[] td, int[] hp, ZStream z) { int r; int[] hn = new int[1]; // hufts used in space int[] v = new int[288]; // work area for huft_build // build literal/length tree r = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v); if (r != Z_OK || bl[0] == 0) { if (r == Z_DATA_ERROR) { z.msg = "oversubscribed literal/length tree"; } else if (r != Z_MEM_ERROR) { z.msg = "incomplete literal/length tree"; r = Z_DATA_ERROR; } return r; } // build distance tree r = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v); if (r != Z_OK || (bd[0] == 0 && nl > 257)) { if (r == Z_DATA_ERROR) { z.msg = "oversubscribed distance tree"; } else if (r == Z_BUF_ERROR) { z.msg = "incomplete distance tree"; r = Z_DATA_ERROR; } else if (r != Z_MEM_ERROR) { z.msg = "empty distance tree with lengths"; r = Z_DATA_ERROR; } return r; } return Z_OK; } internal static int inflate_trees_fixed(int[] bl, int[] bd, int[][] tl, int[][] td, ZStream z) { bl[0] = fixed_bl; bd[0] = fixed_bd; tl[0] = fixed_tl; td[0] = fixed_td; return Z_OK; } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/Deflate.cs0000644000175000017500000016360411127003600024175 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { sealed class Deflate { private const int MAX_MEM_LEVEL = 9; private const int Z_DEFAULT_COMPRESSION = - 1; private const int MAX_WBITS = 15; // 32K LZ77 window private const int DEF_MEM_LEVEL = 8; internal class Config { internal int good_length; // reduce lazy search above this match length internal int max_lazy; // do not perform lazy search above this match length internal int nice_length; // quit search above this match length internal int max_chain; internal int func; internal Config(int good_length, int max_lazy, int nice_length, int max_chain, int func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; } } private const int STORED = 0; private const int FAST = 1; private const int SLOW = 2; private static Config[] config_table; private static readonly System.String[] z_errmsg = new System.String[]{"need dictionary", "stream end", "", "file error", "stream error", "data error", "insufficient memory", "buffer error", "incompatible version", ""}; // block not completed, need more input or more output private const int NeedMore = 0; // block flush performed private const int BlockDone = 1; // finish started, need only more output at next deflate private const int FinishStarted = 2; // finish done, accept no more input or output private const int FinishDone = 3; // preset dictionary flag in zlib header private const int PRESET_DICT = 0x20; private const int Z_FILTERED = 1; private const int Z_HUFFMAN_ONLY = 2; private const int Z_DEFAULT_STRATEGY = 0; private const int Z_NO_FLUSH = 0; private const int Z_PARTIAL_FLUSH = 1; private const int Z_SYNC_FLUSH = 2; private const int Z_FULL_FLUSH = 3; private const int Z_FINISH = 4; private const int Z_OK = 0; private const int Z_STREAM_END = 1; private const int Z_NEED_DICT = 2; private const int Z_ERRNO = - 1; private const int Z_STREAM_ERROR = - 2; private const int Z_DATA_ERROR = - 3; private const int Z_MEM_ERROR = - 4; private const int Z_BUF_ERROR = - 5; private const int Z_VERSION_ERROR = - 6; private const int INIT_STATE = 42; private const int BUSY_STATE = 113; private const int FINISH_STATE = 666; // The deflate compression method private const int Z_DEFLATED = 8; private const int STORED_BLOCK = 0; private const int STATIC_TREES = 1; private const int DYN_TREES = 2; // The three kinds of block type private const int Z_BINARY = 0; private const int Z_ASCII = 1; private const int Z_UNKNOWN = 2; private const int Buf_size = 8 * 2; // repeat previous bit length 3-6 times (2 bits of repeat count) private const int REP_3_6 = 16; // repeat a zero length 3-10 times (3 bits of repeat count) private const int REPZ_3_10 = 17; // repeat a zero length 11-138 times (7 bits of repeat count) private const int REPZ_11_138 = 18; private const int MIN_MATCH = 3; private const int MAX_MATCH = 258; private static readonly int MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); private const int MAX_BITS = 15; private const int D_CODES = 30; private const int BL_CODES = 19; private const int LENGTH_CODES = 29; private const int LITERALS = 256; private static readonly int L_CODES = (LITERALS + 1 + LENGTH_CODES); private static readonly int HEAP_SIZE = (2 * L_CODES + 1); private const int END_BLOCK = 256; internal ZStream strm; // pointer back to this zlib stream internal int status; // as the name implies internal byte[] pending_buf; // output still pending internal int pending_buf_size; // size of pending_buf internal int pending_out; // next pending byte to output to the stream internal int pending; // nb of bytes in the pending buffer internal int noheader; // suppress zlib header and adler32 internal byte data_type; // UNKNOWN, BINARY or ASCII internal byte method; // STORED (for zip only) or DEFLATED internal int last_flush; // value of flush param for previous deflate call internal int w_size; // LZ77 window size (32K by default) internal int w_bits; // log2(w_size) (8..16) internal int w_mask; // w_size - 1 internal byte[] window; // Sliding window. Input bytes are read into the second half of the window, // and move to the first half later to keep a dictionary of at least wSize // bytes. With this organization, matches are limited to a distance of // wSize-MAX_MATCH bytes, but this ensures that IO is always // performed with a length multiple of the block size. Also, it limits // the window size to 64K, which is quite useful on MSDOS. // To do: use the user input buffer as sliding window. internal int window_size; // Actual size of window: 2*wSize, except when the user input buffer // is directly used as sliding window. internal short[] prev; // Link to older string with same hash index. To limit the size of this // array to 64K, this link is maintained only for the last 32K strings. // An index in this array is thus a window index modulo 32K. internal short[] head; // Heads of the hash chains or NIL. internal int ins_h; // hash index of string to be inserted internal int hash_size; // number of elements in hash table internal int hash_bits; // log2(hash_size) internal int hash_mask; // hash_size-1 // Number of bits by which ins_h must be shifted at each input // step. It must be such that after MIN_MATCH steps, the oldest // byte no longer takes part in the hash key, that is: // hash_shift * MIN_MATCH >= hash_bits internal int hash_shift; // Window position at the beginning of the current output block. Gets // negative when the window is moved backwards. internal int block_start; internal int match_length; // length of best match internal int prev_match; // previous match internal int match_available; // set if previous match exists internal int strstart; // start of string to insert internal int match_start; // start of matching string internal int lookahead; // number of valid bytes ahead in window // Length of the best match at previous step. Matches not greater than this // are discarded. This is used in the lazy match evaluation. internal int prev_length; // To speed up deflation, hash chains are never searched beyond this // length. A higher limit improves compression ratio but degrades the speed. internal int max_chain_length; // Attempt to find a better match only when the current match is strictly // smaller than this value. This mechanism is used only for compression // levels >= 4. internal int max_lazy_match; // Insert new strings in the hash table only if the match length is not // greater than this length. This saves time but degrades compression. // max_insert_length is used only for compression levels <= 3. internal int level; // compression level (1..9) internal int strategy; // favor or force Huffman coding // Use a faster search when the previous match is longer than this internal int good_match; // Stop searching when current match exceeds this internal int nice_match; internal short[] dyn_ltree; // literal and length tree internal short[] dyn_dtree; // distance tree internal short[] bl_tree; // Huffman tree for bit lengths internal Tree l_desc = new Tree(); // desc for literal tree internal Tree d_desc = new Tree(); // desc for distance tree internal Tree bl_desc = new Tree(); // desc for bit length tree // number of codes at each bit length for an optimal tree internal short[] bl_count = new short[MAX_BITS + 1]; // heap used to build the Huffman trees internal int[] heap = new int[2 * L_CODES + 1]; internal int heap_len; // number of elements in the heap internal int heap_max; // element of largest frequency // The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. // The same heap array is used to build all trees. // Depth of each subtree used as tie breaker for trees of equal frequency internal byte[] depth = new byte[2 * L_CODES + 1]; internal int l_buf; // index for literals or lengths */ // Size of match buffer for literals/lengths. There are 4 reasons for // limiting lit_bufsize to 64K: // - frequencies can be kept in 16 bit counters // - if compression is not successful for the first block, all input // data is still in the window so we can still emit a stored block even // when input comes from standard input. (This can also be done for // all blocks if lit_bufsize is not greater than 32K.) // - if compression is not successful for a file smaller than 64K, we can // even emit a stored file instead of a stored block (saving 5 bytes). // This is applicable only for zip (not gzip or zlib). // - creating new Huffman trees less frequently may not provide fast // adaptation to changes in the input data statistics. (Take for // example a binary file with poorly compressible code followed by // a highly compressible string table.) Smaller buffer sizes give // fast adaptation but have of course the overhead of transmitting // trees more frequently. // - I can't count above 4 internal int lit_bufsize; internal int last_lit; // running index in l_buf // Buffer for distances. To simplify the code, d_buf and l_buf have // the same number of elements. To use different lengths, an extra flag // array would be necessary. internal int d_buf; // index of pendig_buf internal int opt_len; // bit length of current block with optimal trees internal int static_len; // bit length of current block with static trees internal int matches; // number of string matches in current block internal int last_eob_len; // bit length of EOB code for last block // Output buffer. bits are inserted starting at the bottom (least // significant bits). internal short bi_buf; // Number of valid bits in bi_buf. All bits above the last valid bit // are always zero. internal int bi_valid; internal Deflate() { dyn_ltree = new short[HEAP_SIZE * 2]; dyn_dtree = new short[(2 * D_CODES + 1) * 2]; // distance tree bl_tree = new short[(2 * BL_CODES + 1) * 2]; // Huffman tree for bit lengths } internal void lm_init() { window_size = 2 * w_size; head[hash_size - 1] = 0; for (int i = 0; i < hash_size - 1; i++) { head[i] = 0; } // Set the default configuration parameters: max_lazy_match = Deflate.config_table[level].max_lazy; good_match = Deflate.config_table[level].good_length; nice_match = Deflate.config_table[level].nice_length; max_chain_length = Deflate.config_table[level].max_chain; strstart = 0; block_start = 0; lookahead = 0; match_length = prev_length = MIN_MATCH - 1; match_available = 0; ins_h = 0; } // Initialize the tree data structures for a new zlib stream. internal void tr_init() { l_desc.dyn_tree = dyn_ltree; l_desc.stat_desc = StaticTree.static_l_desc; d_desc.dyn_tree = dyn_dtree; d_desc.stat_desc = StaticTree.static_d_desc; bl_desc.dyn_tree = bl_tree; bl_desc.stat_desc = StaticTree.static_bl_desc; bi_buf = 0; bi_valid = 0; last_eob_len = 8; // enough lookahead for inflate // Initialize the first block of the first file: init_block(); } internal void init_block() { // Initialize the trees. for (int i = 0; i < L_CODES; i++) dyn_ltree[i * 2] = 0; for (int i = 0; i < D_CODES; i++) dyn_dtree[i * 2] = 0; for (int i = 0; i < BL_CODES; i++) bl_tree[i * 2] = 0; dyn_ltree[END_BLOCK * 2] = 1; opt_len = static_len = 0; last_lit = matches = 0; } // Restore the heap property by moving down the tree starting at node k, // exchanging a node with the smallest of its two sons if necessary, stopping // when the heap property is re-established (each father smaller than its // two sons). internal void pqdownheap(short[] tree, int k) { int v = heap[k]; int j = k << 1; // left son of k while (j <= heap_len) { // Set j to the smallest of the two sons: if (j < heap_len && smaller(tree, heap[j + 1], heap[j], depth)) { j++; } // Exit if v is smaller than both sons if (smaller(tree, v, heap[j], depth)) break; // Exchange v with the smallest son heap[k] = heap[j]; k = j; // And continue down the tree, setting j to the left son of k j <<= 1; } heap[k] = v; } internal static bool smaller(short[] tree, int n, int m, byte[] depth) { return (tree[n * 2] < tree[m * 2] || (tree[n * 2] == tree[m * 2] && depth[n] <= depth[m])); } // Scan a literal or distance tree to determine the frequencies of the codes // in the bit length tree. internal void scan_tree(short[] tree, int max_code) { int n; // iterates over all tree elements int prevlen = - 1; // last emitted length int curlen; // length of current code int nextlen = tree[0 * 2 + 1]; // length of next code int count = 0; // repeat count of the current code int max_count = 7; // max repeat count int min_count = 4; // min repeat count if (nextlen == 0) { max_count = 138; min_count = 3; } tree[(max_code + 1) * 2 + 1] = (short) SupportClass.Identity(0xffff); // guard for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { bl_tree[curlen * 2] = (short) (bl_tree[curlen * 2] + count); } else if (curlen != 0) { if (curlen != prevlen) bl_tree[curlen * 2]++; bl_tree[REP_3_6 * 2]++; } else if (count <= 10) { bl_tree[REPZ_3_10 * 2]++; } else { bl_tree[REPZ_11_138 * 2]++; } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138; min_count = 3; } else if (curlen == nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } // Construct the Huffman tree for the bit lengths and return the index in // bl_order of the last bit length code to send. internal int build_bl_tree() { int max_blindex; // index of last bit length code of non zero freq // Determine the bit length frequencies for literal and distance trees scan_tree(dyn_ltree, l_desc.max_code); scan_tree(dyn_dtree, d_desc.max_code); // Build the bit length tree: bl_desc.build_tree(this); // opt_len now includes the length of the tree representations, except // the lengths of the bit lengths codes and the 5+5+4 bits for the counts. // Determine the number of bit length codes to send. The pkzip format // requires that at least 4 bit length codes be sent. (appnote.txt says // 3 but the actual value used is 4.) for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] != 0) break; } // Update opt_len to include the bit length tree and counts opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; return max_blindex; } // Send the header for a block using dynamic Huffman trees: the counts, the // lengths of the bit length codes, the literal tree and the distance tree. // IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. internal void send_all_trees(int lcodes, int dcodes, int blcodes) { int rank; // index in bl_order send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt send_bits(dcodes - 1, 5); send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt for (rank = 0; rank < blcodes; rank++) { send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3); } send_tree(dyn_ltree, lcodes - 1); // literal tree send_tree(dyn_dtree, dcodes - 1); // distance tree } // Send a literal or distance tree in compressed form, using the codes in // bl_tree. internal void send_tree(short[] tree, int max_code) { int n; // iterates over all tree elements int prevlen = - 1; // last emitted length int curlen; // length of current code int nextlen = tree[0 * 2 + 1]; // length of next code int count = 0; // repeat count of the current code int max_count = 7; // max repeat count int min_count = 4; // min repeat count if (nextlen == 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]; if (++count < max_count && curlen == nextlen) { continue; } else if (count < min_count) { do { send_code(curlen, bl_tree); } while (--count != 0); } else if (curlen != 0) { if (curlen != prevlen) { send_code(curlen, bl_tree); count--; } send_code(REP_3_6, bl_tree); send_bits(count - 3, 2); } else if (count <= 10) { send_code(REPZ_3_10, bl_tree); send_bits(count - 3, 3); } else { send_code(REPZ_11_138, bl_tree); send_bits(count - 11, 7); } count = 0; prevlen = curlen; if (nextlen == 0) { max_count = 138; min_count = 3; } else if (curlen == nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } // Output a byte on the stream. // IN assertion: there is enough room in pending_buf. internal void put_byte(byte[] p, int start, int len) { Array.Copy(p, start, pending_buf, pending, len); pending += len; } internal void put_byte(byte c) { pending_buf[pending++] = c; } internal void put_short(int w) { put_byte((byte) (w)); put_byte((byte) (SupportClass.URShift(w, 8))); } internal void putShortMSB(int b) { put_byte((byte) (b >> 8)); put_byte((byte) (b)); } internal void send_code(int c, short[] tree) { send_bits((tree[c * 2] & 0xffff), (tree[c * 2 + 1] & 0xffff)); } internal void send_bits(int value_Renamed, int length) { int len = length; if (bi_valid > (int) Buf_size - len) { int val = value_Renamed; // bi_buf |= (val << bi_valid); bi_buf = (short) ((ushort) bi_buf | (ushort) (((val << bi_valid) & 0xffff))); put_short(bi_buf); bi_buf = (short) (SupportClass.URShift(val, (Buf_size - bi_valid))); bi_valid += len - Buf_size; } else { // bi_buf |= (value) << bi_valid; bi_buf = (short)((ushort)bi_buf | (ushort)((((value_Renamed) << bi_valid) & 0xffff))); bi_valid += len; } } // Send one empty static block to give enough lookahead for inflate. // This takes 10 bits, of which 7 may remain in the bit buffer. // The current inflate code requires 9 bits of lookahead. If the // last two codes for the previous block (real code plus EOB) were coded // on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode // the last real code. In this case we send two empty static blocks instead // of one. (There are no problems if the previous block is stored or fixed.) // To simplify the code, we assume the worst case of last real code encoded // on one bit only. internal void _tr_align() { send_bits(STATIC_TREES << 1, 3); send_code(END_BLOCK, StaticTree.static_ltree); bi_flush(); // Of the 10 bits for the empty block, we have already sent // (10 - bi_valid) bits. The lookahead for the last real code (before // the EOB of the previous block) was thus at least one plus the length // of the EOB plus what we have just sent of the empty static block. if (1 + last_eob_len + 10 - bi_valid < 9) { send_bits(STATIC_TREES << 1, 3); send_code(END_BLOCK, StaticTree.static_ltree); bi_flush(); } last_eob_len = 7; } // Save the match info and tally the frequency counts. Return true if // the current block must be flushed. internal bool _tr_tally(int dist, int lc) { pending_buf[d_buf + last_lit * 2] = (byte) (SupportClass.URShift(dist, 8)); pending_buf[d_buf + last_lit * 2 + 1] = (byte) dist; pending_buf[l_buf + last_lit] = (byte) lc; last_lit++; if (dist == 0) { // lc is the unmatched char dyn_ltree[lc * 2]++; } else { matches++; // Here, lc is the match length - MIN_MATCH dist--; // dist = match distance - 1 dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++; dyn_dtree[Tree.d_code(dist) * 2]++; } if ((last_lit & 0x1fff) == 0 && level > 2) { // Compute an upper bound for the compressed length int out_length = last_lit * 8; int in_length = strstart - block_start; int dcode; for (dcode = 0; dcode < D_CODES; dcode++) { out_length = (int) (out_length + (int) dyn_dtree[dcode * 2] * (5L + Tree.extra_dbits[dcode])); } out_length = SupportClass.URShift(out_length, 3); if ((matches < (last_lit / 2)) && out_length < in_length / 2) return true; } return (last_lit == lit_bufsize - 1); // We avoid equality with lit_bufsize because of wraparound at 64K // on 16 bit machines and because stored blocks are restricted to // 64K-1 bytes. } // Send the block data compressed using the given Huffman trees internal void compress_block(short[] ltree, short[] dtree) { int dist; // distance of matched string int lc; // match length or unmatched char (if dist == 0) int lx = 0; // running index in l_buf int code; // the code to send int extra; // number of extra bits to send if (last_lit != 0) { do { dist = ((pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (pending_buf[d_buf + lx * 2 + 1] & 0xff); lc = (pending_buf[l_buf + lx]) & 0xff; lx++; if (dist == 0) { send_code(lc, ltree); // send a literal byte } else { // Here, lc is the match length - MIN_MATCH code = Tree._length_code[lc]; send_code(code + LITERALS + 1, ltree); // send the length code extra = Tree.extra_lbits[code]; if (extra != 0) { lc -= Tree.base_length[code]; send_bits(lc, extra); // send the extra length bits } dist--; // dist is now the match distance - 1 code = Tree.d_code(dist); send_code(code, dtree); // send the distance code extra = Tree.extra_dbits[code]; if (extra != 0) { dist -= Tree.base_dist[code]; send_bits(dist, extra); // send the extra distance bits } } // literal or match pair ? // Check that the overlay between pending_buf and d_buf+l_buf is ok: } while (lx < last_lit); } send_code(END_BLOCK, ltree); last_eob_len = ltree[END_BLOCK * 2 + 1]; } // Set the data type to ASCII or BINARY, using a crude approximation: // binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise. // IN assertion: the fields freq of dyn_ltree are set and the total of all // frequencies does not exceed 64K (to fit in an int on 16 bit machines). internal void set_data_type() { int n = 0; int ascii_freq = 0; int bin_freq = 0; while (n < 7) { bin_freq += dyn_ltree[n * 2]; n++; } while (n < 128) { ascii_freq += dyn_ltree[n * 2]; n++; } while (n < LITERALS) { bin_freq += dyn_ltree[n * 2]; n++; } data_type = (byte) (bin_freq > (SupportClass.URShift(ascii_freq, 2))?Z_BINARY:Z_ASCII); } // Flush the bit buffer, keeping at most 7 bits in it. internal void bi_flush() { if (bi_valid == 16) { put_short(bi_buf); bi_buf = 0; bi_valid = 0; } else if (bi_valid >= 8) { put_byte((byte) bi_buf); bi_buf = (short) (SupportClass.URShift(bi_buf, 8)); bi_valid -= 8; } } // Flush the bit buffer and align the output on a byte boundary internal void bi_windup() { if (bi_valid > 8) { put_short(bi_buf); } else if (bi_valid > 0) { put_byte((byte) bi_buf); } bi_buf = 0; bi_valid = 0; } // Copy a stored block, storing first the length and its // one's complement if requested. internal void copy_block(int buf, int len, bool header) { bi_windup(); // align on byte boundary last_eob_len = 8; // enough lookahead for inflate if (header) { put_short((short) len); put_short((short) ~ len); } // while(len--!=0) { // put_byte(window[buf+index]); // index++; // } put_byte(window, buf, len); } internal void flush_block_only(bool eof) { _tr_flush_block(block_start >= 0?block_start:- 1, strstart - block_start, eof); block_start = strstart; strm.flush_pending(); } // Copy without compression as much as possible from the input stream, return // the current block state. // This function does not insert new strings in the dictionary since // uncompressible data is probably not useful. This function is used // only for the level=0 compression option. // NOTE: this function should be optimized to avoid extra copying from // window to pending_buf. internal int deflate_stored(int flush) { // Stored blocks are limited to 0xffff bytes, pending_buf is limited // to pending_buf_size, and each stored block has a 5 byte header: int max_block_size = 0xffff; int max_start; if (max_block_size > pending_buf_size - 5) { max_block_size = pending_buf_size - 5; } // Copy as much as possible from input to output: while (true) { // Fill the window as much as possible: if (lookahead <= 1) { fill_window(); if (lookahead == 0 && flush == Z_NO_FLUSH) return NeedMore; if (lookahead == 0) break; // flush the current block } strstart += lookahead; lookahead = 0; // Emit a stored block if pending_buf will be full: max_start = block_start + max_block_size; if (strstart == 0 || strstart >= max_start) { // strstart == 0 is possible when wraparound on 16-bit machine lookahead = (int) (strstart - max_start); strstart = (int) max_start; flush_block_only(false); if (strm.avail_out == 0) return NeedMore; } // Flush if we may have to slide, otherwise block_start may become // negative and the data will be gone: if (strstart - block_start >= w_size - MIN_LOOKAHEAD) { flush_block_only(false); if (strm.avail_out == 0) return NeedMore; } } flush_block_only(flush == Z_FINISH); if (strm.avail_out == 0) return (flush == Z_FINISH)?FinishStarted:NeedMore; return flush == Z_FINISH?FinishDone:BlockDone; } // Send a stored block internal void _tr_stored_block(int buf, int stored_len, bool eof) { send_bits((STORED_BLOCK << 1) + (eof?1:0), 3); // send block type copy_block(buf, stored_len, true); // with header } // Determine the best encoding for the current block: dynamic trees, static // trees or store, and output the encoded block to the zip file. internal void _tr_flush_block(int buf, int stored_len, bool eof) { int opt_lenb, static_lenb; // opt_len and static_len in bytes int max_blindex = 0; // index of last bit length code of non zero freq // Build the Huffman trees unless a stored block is forced if (level > 0) { // Check if the file is ascii or binary if (data_type == Z_UNKNOWN) set_data_type(); // Construct the literal and distance trees l_desc.build_tree(this); d_desc.build_tree(this); // At this point, opt_len and static_len are the total bit lengths of // the compressed block data, excluding the tree representations. // Build the bit length tree for the above two trees, and get the index // in bl_order of the last bit length code to send. max_blindex = build_bl_tree(); // Determine the best encoding. Compute first the block length in bytes opt_lenb = SupportClass.URShift((opt_len + 3 + 7), 3); static_lenb = SupportClass.URShift((static_len + 3 + 7), 3); if (static_lenb <= opt_lenb) opt_lenb = static_lenb; } else { opt_lenb = static_lenb = stored_len + 5; // force a stored block } if (stored_len + 4 <= opt_lenb && buf != - 1) { // 4: two words for the lengths // The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. // Otherwise we can't have processed more than WSIZE input bytes since // the last block flush, because compression would have been // successful. If LIT_BUFSIZE <= WSIZE, it is never too late to // transform a block into a stored block. _tr_stored_block(buf, stored_len, eof); } else if (static_lenb == opt_lenb) { send_bits((STATIC_TREES << 1) + (eof?1:0), 3); compress_block(StaticTree.static_ltree, StaticTree.static_dtree); } else { send_bits((DYN_TREES << 1) + (eof?1:0), 3); send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1, max_blindex + 1); compress_block(dyn_ltree, dyn_dtree); } // The above check is made mod 2^32, for files larger than 512 MB // and uLong implemented on 32 bits. init_block(); if (eof) { bi_windup(); } } // Fill the window when the lookahead becomes insufficient. // Updates strstart and lookahead. // // IN assertion: lookahead < MIN_LOOKAHEAD // OUT assertions: strstart <= window_size-MIN_LOOKAHEAD // At least one byte has been read, or avail_in == 0; reads are // performed for at least two bytes (required for the zip translate_eol // option -- not supported here). internal void fill_window() { int n, m; int p; int more; // Amount of free space at the end of the window. do { more = (window_size - lookahead - strstart); // Deal with !@#$% 64K limit: if (more == 0 && strstart == 0 && lookahead == 0) { more = w_size; } else if (more == - 1) { // Very unlikely, but possible on 16 bit machine if strstart == 0 // and lookahead == 1 (input done one byte at time) more--; // If the window is almost full and there is insufficient lookahead, // move the upper half to the lower one to make room in the upper half. } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) { Array.Copy(window, w_size, window, 0, w_size); match_start -= w_size; strstart -= w_size; // we now have strstart >= MAX_DIST block_start -= w_size; // Slide the hash table (could be avoided with 32 bit values // at the expense of memory usage). We slide even when level == 0 // to keep the hash table consistent if we switch back to level > 0 // later. (Using level 0 permanently is not an optimal usage of // zlib, so we don't care about this pathological case.) n = hash_size; p = n; do { m = (head[--p] & 0xffff); head[p] = (short)(m >= w_size?(m - w_size):0); //head[p] = (m >= w_size?(short) (m - w_size):0); } while (--n != 0); n = w_size; p = n; do { m = (prev[--p] & 0xffff); prev[p] = (short)(m >= w_size?(m - w_size):0); //prev[p] = (m >= w_size?(short) (m - w_size):0); // If n is not on any hash chain, prev[n] is garbage but // its value will never be used. } while (--n != 0); more += w_size; } if (strm.avail_in == 0) return ; // If there was no sliding: // strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && // more == window_size - lookahead - strstart // => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) // => more >= window_size - 2*WSIZE + 2 // In the BIG_MEM or MMAP case (not yet supported), // window_size == input_size + MIN_LOOKAHEAD && // strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. // Otherwise, window_size == 2*WSIZE so more >= 2. // If there was sliding, more >= WSIZE. So in all cases, more >= 2. n = strm.read_buf(window, strstart + lookahead, more); lookahead += n; // Initialize the hash value now that we have some input: if (lookahead >= MIN_MATCH) { ins_h = window[strstart] & 0xff; ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask; } // If the whole input has less than MIN_MATCH bytes, ins_h is garbage, // but this is not important since only literal bytes will be emitted. } while (lookahead < MIN_LOOKAHEAD && strm.avail_in != 0); } // Compress as much as possible from the input stream, return the current // block state. // This function does not perform lazy evaluation of matches and inserts // new strings in the dictionary only for unmatched strings or for short // matches. It is used only for the fast compression options. internal int deflate_fast(int flush) { // short hash_head = 0; // head of the hash chain int hash_head = 0; // head of the hash chain bool bflush; // set if current block must be flushed while (true) { // Make sure that we always have enough lookahead, except // at the end of the input file. We need MAX_MATCH bytes // for the next match, plus MIN_MATCH bytes to insert the // string following the next match. if (lookahead < MIN_LOOKAHEAD) { fill_window(); if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return NeedMore; } if (lookahead == 0) break; // flush the current block } // Insert the string window[strstart .. strstart+2] in the // dictionary, and set hash_head to the head of the hash chain: if (lookahead >= MIN_MATCH) { ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h]; hash_head = (head[ins_h] & 0xffff); prev[strstart & w_mask] = head[ins_h]; head[ins_h] = (short) strstart; } // Find the longest match, discarding those <= prev_length. // At this point we have always match_length < MIN_MATCH if (hash_head != 0L && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) { // To simplify the code, we prevent matches with the string // of window index 0 (in particular we have to avoid a match // of the string with itself at the start of the input file). if (strategy != Z_HUFFMAN_ONLY) { match_length = longest_match(hash_head); } // longest_match() sets match_start } if (match_length >= MIN_MATCH) { // check_match(strstart, match_start, match_length); bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH); lookahead -= match_length; // Insert new strings in the hash table only if the match length // is not too large. This saves time but degrades compression. if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) { match_length--; // string at strstart already in hash table do { strstart++; ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h]; hash_head = (head[ins_h] & 0xffff); prev[strstart & w_mask] = head[ins_h]; head[ins_h] = (short) strstart; // strstart never exceeds WSIZE-MAX_MATCH, so there are // always MIN_MATCH bytes ahead. } while (--match_length != 0); strstart++; } else { strstart += match_length; match_length = 0; ins_h = window[strstart] & 0xff; ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask; // If lookahead < MIN_MATCH, ins_h is garbage, but it does not // matter since it will be recomputed at next deflate call. } } else { // No match, output a literal byte bflush = _tr_tally(0, window[strstart] & 0xff); lookahead--; strstart++; } if (bflush) { flush_block_only(false); if (strm.avail_out == 0) return NeedMore; } } flush_block_only(flush == Z_FINISH); if (strm.avail_out == 0) { if (flush == Z_FINISH) return FinishStarted; else return NeedMore; } return flush == Z_FINISH?FinishDone:BlockDone; } // Same as above, but achieves better compression. We use a lazy // evaluation for matches: a match is finally adopted only if there is // no better match at the next window position. internal int deflate_slow(int flush) { // short hash_head = 0; // head of hash chain int hash_head = 0; // head of hash chain bool bflush; // set if current block must be flushed // Process the input block. while (true) { // Make sure that we always have enough lookahead, except // at the end of the input file. We need MAX_MATCH bytes // for the next match, plus MIN_MATCH bytes to insert the // string following the next match. if (lookahead < MIN_LOOKAHEAD) { fill_window(); if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { return NeedMore; } if (lookahead == 0) break; // flush the current block } // Insert the string window[strstart .. strstart+2] in the // dictionary, and set hash_head to the head of the hash chain: if (lookahead >= MIN_MATCH) { ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; // prev[strstart&w_mask]=hash_head=head[ins_h]; hash_head = (head[ins_h] & 0xffff); prev[strstart & w_mask] = head[ins_h]; head[ins_h] = (short) strstart; } // Find the longest match, discarding those <= prev_length. prev_length = match_length; prev_match = match_start; match_length = MIN_MATCH - 1; if (hash_head != 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) { // To simplify the code, we prevent matches with the string // of window index 0 (in particular we have to avoid a match // of the string with itself at the start of the input file). if (strategy != Z_HUFFMAN_ONLY) { match_length = longest_match(hash_head); } // longest_match() sets match_start if (match_length <= 5 && (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) { // If prev_match is also MIN_MATCH, match_start is garbage // but we will ignore the current match anyway. match_length = MIN_MATCH - 1; } } // If there was a match at the previous step and the current // match is not better, output the previous match: if (prev_length >= MIN_MATCH && match_length <= prev_length) { int max_insert = strstart + lookahead - MIN_MATCH; // Do not insert strings in hash table beyond this. // check_match(strstart-1, prev_match, prev_length); bflush = _tr_tally(strstart - 1 - prev_match, prev_length - MIN_MATCH); // Insert in hash table all strings up to the end of the match. // strstart-1 and strstart are already inserted. If there is not // enough lookahead, the last two strings are not inserted in // the hash table. lookahead -= (prev_length - 1); prev_length -= 2; do { if (++strstart <= max_insert) { ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; //prev[strstart&w_mask]=hash_head=head[ins_h]; hash_head = (head[ins_h] & 0xffff); prev[strstart & w_mask] = head[ins_h]; head[ins_h] = (short) strstart; } } while (--prev_length != 0); match_available = 0; match_length = MIN_MATCH - 1; strstart++; if (bflush) { flush_block_only(false); if (strm.avail_out == 0) return NeedMore; } } else if (match_available != 0) { // If there was no match at the previous position, output a // single literal. If there was a match but the current match // is longer, truncate the previous match to a single literal. bflush = _tr_tally(0, window[strstart - 1] & 0xff); if (bflush) { flush_block_only(false); } strstart++; lookahead--; if (strm.avail_out == 0) return NeedMore; } else { // There is no previous match to compare with, wait for // the next step to decide. match_available = 1; strstart++; lookahead--; } } if (match_available != 0) { bflush = _tr_tally(0, window[strstart - 1] & 0xff); match_available = 0; } flush_block_only(flush == Z_FINISH); if (strm.avail_out == 0) { if (flush == Z_FINISH) return FinishStarted; else return NeedMore; } return flush == Z_FINISH?FinishDone:BlockDone; } internal int longest_match(int cur_match) { int chain_length = max_chain_length; // max hash chain length int scan = strstart; // current string int match; // matched string int len; // length of current match int best_len = prev_length; // best match length so far int limit = strstart > (w_size - MIN_LOOKAHEAD)?strstart - (w_size - MIN_LOOKAHEAD):0; int nice_match = this.nice_match; // Stop when cur_match becomes <= limit. To simplify the code, // we prevent matches with the string of window index 0. int wmask = w_mask; int strend = strstart + MAX_MATCH; byte scan_end1 = window[scan + best_len - 1]; byte scan_end = window[scan + best_len]; // The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. // It is easy to get rid of this optimization if necessary. // Do not waste too much time if we already have a good match: if (prev_length >= good_match) { chain_length >>= 2; } // Do not look for matches beyond the end of the input. This is necessary // to make deflate deterministic. if (nice_match > lookahead) nice_match = lookahead; do { match = cur_match; // Skip to next match if the match length cannot increase // or if the match length is less than 2: if (window[match + best_len] != scan_end || window[match + best_len - 1] != scan_end1 || window[match] != window[scan] || window[++match] != window[scan + 1]) continue; // The check at best_len-1 can be removed because it will be made // again later. (This heuristic is not always a win.) // It is not necessary to compare scan[2] and match[2] since they // are always equal when the other bytes match, given that // the hash keys are equal and that HASH_BITS >= 8. scan += 2; match++; // We check for insufficient lookahead only every 8th comparison; // the 256th check will be made at strstart+258. do { } while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend); len = MAX_MATCH - (int) (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { match_start = cur_match; best_len = len; if (len >= nice_match) break; scan_end1 = window[scan + best_len - 1]; scan_end = window[scan + best_len]; } } while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit && --chain_length != 0); if (best_len <= lookahead) return best_len; return lookahead; } internal int deflateInit(ZStream strm, int level, int bits) { return deflateInit2(strm, level, Z_DEFLATED, bits, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } internal int deflateInit(ZStream strm, int level) { return deflateInit(strm, level, MAX_WBITS); } internal int deflateInit2(ZStream strm, int level, int method, int windowBits, int memLevel, int strategy) { int noheader = 0; // byte[] my_version=ZLIB_VERSION; // // if (version == null || version[0] != my_version[0] // || stream_size != sizeof(z_stream)) { // return Z_VERSION_ERROR; // } strm.msg = null; if (level == Z_DEFAULT_COMPRESSION) level = 6; if (windowBits < 0) { // undocumented feature: suppress zlib header noheader = 1; windowBits = - windowBits; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || windowBits < 9 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) { return Z_STREAM_ERROR; } strm.dstate = (Deflate) this; this.noheader = noheader; w_bits = windowBits; w_size = 1 << w_bits; w_mask = w_size - 1; hash_bits = memLevel + 7; hash_size = 1 << hash_bits; hash_mask = hash_size - 1; hash_shift = ((hash_bits + MIN_MATCH - 1) / MIN_MATCH); window = new byte[w_size * 2]; prev = new short[w_size]; head = new short[hash_size]; lit_bufsize = 1 << (memLevel + 6); // 16K elements by default // We overlay pending_buf and d_buf+l_buf. This works since the average // output size for (length,distance) codes is <= 24 bits. pending_buf = new byte[lit_bufsize * 4]; pending_buf_size = lit_bufsize * 4; d_buf = lit_bufsize / 2; l_buf = (1 + 2) * lit_bufsize; this.level = level; //System.out.println("level="+level); this.strategy = strategy; this.method = (byte) method; return deflateReset(strm); } internal int deflateReset(ZStream strm) { strm.total_in = strm.total_out = 0; strm.msg = null; // strm.data_type = Z_UNKNOWN; pending = 0; pending_out = 0; if (noheader < 0) { noheader = 0; // was set to -1 by deflate(..., Z_FINISH); } status = (noheader != 0)?BUSY_STATE:INIT_STATE; strm.adler = strm._adler.adler32(0, null, 0, 0); last_flush = Z_NO_FLUSH; tr_init(); lm_init(); return Z_OK; } internal int deflateEnd() { if (status != INIT_STATE && status != BUSY_STATE && status != FINISH_STATE) { return Z_STREAM_ERROR; } // Deallocate in reverse order of allocations: pending_buf = null; head = null; prev = null; window = null; // free // dstate=null; return status == BUSY_STATE?Z_DATA_ERROR:Z_OK; } internal int deflateParams(ZStream strm, int _level, int _strategy) { int err = Z_OK; if (_level == Z_DEFAULT_COMPRESSION) { _level = 6; } if (_level < 0 || _level > 9 || _strategy < 0 || _strategy > Z_HUFFMAN_ONLY) { return Z_STREAM_ERROR; } if (config_table[level].func != config_table[_level].func && strm.total_in != 0) { // Flush the last buffer: err = strm.deflate(Z_PARTIAL_FLUSH); } if (level != _level) { level = _level; max_lazy_match = config_table[level].max_lazy; good_match = config_table[level].good_length; nice_match = config_table[level].nice_length; max_chain_length = config_table[level].max_chain; } strategy = _strategy; return err; } internal int deflateSetDictionary(ZStream strm, byte[] dictionary, int dictLength) { int length = dictLength; int index = 0; if (dictionary == null || status != INIT_STATE) return Z_STREAM_ERROR; strm.adler = strm._adler.adler32(strm.adler, dictionary, 0, dictLength); if (length < MIN_MATCH) return Z_OK; if (length > w_size - MIN_LOOKAHEAD) { length = w_size - MIN_LOOKAHEAD; index = dictLength - length; // use the tail of the dictionary } Array.Copy(dictionary, index, window, 0, length); strstart = length; block_start = length; // Insert all strings in the hash table (except for the last two bytes). // s->lookahead stays null, so s->ins_h will be recomputed at the next // call of fill_window. ins_h = window[0] & 0xff; ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask; for (int n = 0; n <= length - MIN_MATCH; n++) { ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask; prev[n & w_mask] = head[ins_h]; head[ins_h] = (short) n; } return Z_OK; } internal int deflate(ZStream strm, int flush) { int old_flush; if (flush > Z_FINISH || flush < 0) { return Z_STREAM_ERROR; } if (strm.next_out == null || (strm.next_in == null && strm.avail_in != 0) || (status == FINISH_STATE && flush != Z_FINISH)) { strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)]; return Z_STREAM_ERROR; } if (strm.avail_out == 0) { strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)]; return Z_BUF_ERROR; } this.strm = strm; // just in case old_flush = last_flush; last_flush = flush; // Write the zlib header if (status == INIT_STATE) { int header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8; int level_flags = ((level - 1) & 0xff) >> 1; if (level_flags > 3) level_flags = 3; header |= (level_flags << 6); if (strstart != 0) header |= PRESET_DICT; header += 31 - (header % 31); status = BUSY_STATE; putShortMSB(header); // Save the adler32 of the preset dictionary: if (strstart != 0) { putShortMSB((int) (SupportClass.URShift(strm.adler, 16))); putShortMSB((int) (strm.adler & 0xffff)); } strm.adler = strm._adler.adler32(0, null, 0, 0); } // Flush as much pending output as possible if (pending != 0) { strm.flush_pending(); if (strm.avail_out == 0) { //System.out.println(" avail_out==0"); // Since avail_out is 0, deflate will be called again with // more output space, but possibly with both pending and // avail_in equal to zero. There won't be anything to do, // but this is not an error situation so make sure we // return OK instead of BUF_ERROR at next call of deflate: last_flush = - 1; return Z_OK; } // Make sure there is something to do and avoid duplicate consecutive // flushes. For repeated and useless calls with Z_FINISH, we keep // returning Z_STREAM_END instead of Z_BUFF_ERROR. } else if (strm.avail_in == 0 && flush <= old_flush && flush != Z_FINISH) { strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)]; return Z_BUF_ERROR; } // User must not provide more input after the first FINISH: if (status == FINISH_STATE && strm.avail_in != 0) { strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)]; return Z_BUF_ERROR; } // Start a new block or continue the current one. if (strm.avail_in != 0 || lookahead != 0 || (flush != Z_NO_FLUSH && status != FINISH_STATE)) { int bstate = - 1; switch (config_table[level].func) { case STORED: bstate = deflate_stored(flush); break; case FAST: bstate = deflate_fast(flush); break; case SLOW: bstate = deflate_slow(flush); break; default: break; } if (bstate == FinishStarted || bstate == FinishDone) { status = FINISH_STATE; } if (bstate == NeedMore || bstate == FinishStarted) { if (strm.avail_out == 0) { last_flush = - 1; // avoid BUF_ERROR next call, see above } return Z_OK; // If flush != Z_NO_FLUSH && avail_out == 0, the next call // of deflate should use the same flush parameter to make sure // that the flush is complete. So we don't have to output an // empty block here, this will be done at next call. This also // ensures that for a very small output buffer, we emit at most // one empty block. } if (bstate == BlockDone) { if (flush == Z_PARTIAL_FLUSH) { _tr_align(); } else { // FULL_FLUSH or SYNC_FLUSH _tr_stored_block(0, 0, false); // For a full flush, this empty block will be recognized // as a special marker by inflate_sync(). if (flush == Z_FULL_FLUSH) { //state.head[s.hash_size-1]=0; for (int i = 0; i < hash_size; i++) // forget history head[i] = 0; } } strm.flush_pending(); if (strm.avail_out == 0) { last_flush = - 1; // avoid BUF_ERROR at next call, see above return Z_OK; } } } if (flush != Z_FINISH) return Z_OK; if (noheader != 0) return Z_STREAM_END; // Write the zlib trailer (adler32) putShortMSB((int) (SupportClass.URShift(strm.adler, 16))); putShortMSB((int) (strm.adler & 0xffff)); strm.flush_pending(); // If avail_out is zero, the application will call deflate again // to flush the rest. noheader = - 1; // write the trailer only once! return pending != 0?Z_OK:Z_STREAM_END; } static Deflate() { { config_table = new Config[10]; // good lazy nice chain config_table[0] = new Config(0, 0, 0, 0, STORED); config_table[1] = new Config(4, 4, 8, 4, FAST); config_table[2] = new Config(4, 5, 16, 8, FAST); config_table[3] = new Config(4, 6, 32, 32, FAST); config_table[4] = new Config(4, 4, 16, 16, SLOW); config_table[5] = new Config(8, 16, 32, 32, SLOW); config_table[6] = new Config(8, 16, 128, 128, SLOW); config_table[7] = new Config(8, 32, 128, 256, SLOW); config_table[8] = new Config(32, 128, 258, 1024, SLOW); config_table[9] = new Config(32, 258, 258, 4096, SLOW); } } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/Inflate.cs0000644000175000017500000003276711127003600024220 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { sealed class Inflate { private const int MAX_WBITS = 15; // 32K LZ77 window // preset dictionary flag in zlib header private const int PRESET_DICT = 0x20; internal const int Z_NO_FLUSH = 0; internal const int Z_PARTIAL_FLUSH = 1; internal const int Z_SYNC_FLUSH = 2; internal const int Z_FULL_FLUSH = 3; internal const int Z_FINISH = 4; private const int Z_DEFLATED = 8; private const int Z_OK = 0; private const int Z_STREAM_END = 1; private const int Z_NEED_DICT = 2; private const int Z_ERRNO = - 1; private const int Z_STREAM_ERROR = - 2; private const int Z_DATA_ERROR = - 3; private const int Z_MEM_ERROR = - 4; private const int Z_BUF_ERROR = - 5; private const int Z_VERSION_ERROR = - 6; private const int METHOD = 0; // waiting for method byte private const int FLAG = 1; // waiting for flag byte private const int DICT4 = 2; // four dictionary check bytes to go private const int DICT3 = 3; // three dictionary check bytes to go private const int DICT2 = 4; // two dictionary check bytes to go private const int DICT1 = 5; // one dictionary check byte to go private const int DICT0 = 6; // waiting for inflateSetDictionary private const int BLOCKS = 7; // decompressing blocks private const int CHECK4 = 8; // four check bytes to go private const int CHECK3 = 9; // three check bytes to go private const int CHECK2 = 10; // two check bytes to go private const int CHECK1 = 11; // one check byte to go private const int DONE = 12; // finished check, done private const int BAD = 13; // got an error--stay here internal int mode; // current inflate mode // mode dependent information internal int method; // if FLAGS, method byte // if CHECK, check values to compare internal long[] was = new long[1]; // computed check value internal long need; // stream check value // if BAD, inflateSync's marker bytes count internal int marker; // mode independent information internal int nowrap; // flag for no wrapper internal int wbits; // log2(window size) (8..15, defaults to 15) internal InfBlocks blocks; // current inflate_blocks state internal int inflateReset(ZStream z) { if (z == null || z.istate == null) return Z_STREAM_ERROR; z.total_in = z.total_out = 0; z.msg = null; z.istate.mode = z.istate.nowrap != 0?BLOCKS:METHOD; z.istate.blocks.reset(z, null); return Z_OK; } internal int inflateEnd(ZStream z) { if (blocks != null) blocks.free(z); blocks = null; // ZFREE(z, z->state); return Z_OK; } internal int inflateInit(ZStream z, int w) { z.msg = null; blocks = null; // handle undocumented nowrap option (no zlib header or check) nowrap = 0; if (w < 0) { w = - w; nowrap = 1; } // set window size if (w < 8 || w > 15) { inflateEnd(z); return Z_STREAM_ERROR; } wbits = w; z.istate.blocks = new InfBlocks(z, z.istate.nowrap != 0?null:this, 1 << w); // reset state inflateReset(z); return Z_OK; } internal int inflate(ZStream z, int f) { int r; int b; if (z == null || z.istate == null || z.next_in == null) return Z_STREAM_ERROR; f = f == Z_FINISH?Z_BUF_ERROR:Z_OK; r = Z_BUF_ERROR; while (true) { //System.out.println("mode: "+z.istate.mode); switch (z.istate.mode) { case METHOD: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; if (((z.istate.method = z.next_in[z.next_in_index++]) & 0xf) != Z_DEFLATED) { z.istate.mode = BAD; z.msg = "unknown compression method"; z.istate.marker = 5; // can't try inflateSync break; } if ((z.istate.method >> 4) + 8 > z.istate.wbits) { z.istate.mode = BAD; z.msg = "invalid window size"; z.istate.marker = 5; // can't try inflateSync break; } z.istate.mode = FLAG; goto case FLAG; case FLAG: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; b = (z.next_in[z.next_in_index++]) & 0xff; if ((((z.istate.method << 8) + b) % 31) != 0) { z.istate.mode = BAD; z.msg = "incorrect header check"; z.istate.marker = 5; // can't try inflateSync break; } if ((b & PRESET_DICT) == 0) { z.istate.mode = BLOCKS; break; } z.istate.mode = DICT4; goto case DICT4; case DICT4: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 24) & unchecked((int) 0xff000000L); z.istate.mode = DICT3; goto case DICT3; case DICT3: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += (((z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L); z.istate.mode = DICT2; goto case DICT2; case DICT2: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += (((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L); z.istate.mode = DICT1; goto case DICT1; case DICT1: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += (z.next_in[z.next_in_index++] & 0xffL); z.adler = z.istate.need; z.istate.mode = DICT0; return Z_NEED_DICT; case DICT0: z.istate.mode = BAD; z.msg = "need dictionary"; z.istate.marker = 0; // can try inflateSync return Z_STREAM_ERROR; case BLOCKS: r = z.istate.blocks.proc(z, r); if (r == Z_DATA_ERROR) { z.istate.mode = BAD; z.istate.marker = 0; // can try inflateSync break; } if (r == Z_OK) { r = f; } if (r != Z_STREAM_END) { return r; } r = f; z.istate.blocks.reset(z, z.istate.was); if (z.istate.nowrap != 0) { z.istate.mode = DONE; break; } z.istate.mode = CHECK4; goto case CHECK4; case CHECK4: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 24) & unchecked((int) 0xff000000L); z.istate.mode = CHECK3; goto case CHECK3; case CHECK3: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += (((z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L); z.istate.mode = CHECK2; goto case CHECK2; case CHECK2: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += (((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L); z.istate.mode = CHECK1; goto case CHECK1; case CHECK1: if (z.avail_in == 0) return r; r = f; z.avail_in--; z.total_in++; z.istate.need += (z.next_in[z.next_in_index++] & 0xffL); if (((int) (z.istate.was[0])) != ((int) (z.istate.need))) { z.istate.mode = BAD; z.msg = "incorrect data check"; z.istate.marker = 5; // can't try inflateSync break; } z.istate.mode = DONE; goto case DONE; case DONE: return Z_STREAM_END; case BAD: return Z_DATA_ERROR; default: return Z_STREAM_ERROR; } } } internal int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength) { int index = 0; int length = dictLength; if (z == null || z.istate == null || z.istate.mode != DICT0) return Z_STREAM_ERROR; if (z._adler.adler32(1L, dictionary, 0, dictLength) != z.adler) { return Z_DATA_ERROR; } z.adler = z._adler.adler32(0, null, 0, 0); if (length >= (1 << z.istate.wbits)) { length = (1 << z.istate.wbits) - 1; index = dictLength - length; } z.istate.blocks.set_dictionary(dictionary, index, length); z.istate.mode = BLOCKS; return Z_OK; } private static byte[] mark = new byte[]{(byte) 0, (byte) 0, (byte) SupportClass.Identity(0xff), (byte) SupportClass.Identity(0xff)}; internal int inflateSync(ZStream z) { int n; // number of bytes to look at int p; // pointer to bytes int m; // number of marker bytes found in a row long r, w; // temporaries to save total_in and total_out // set up if (z == null || z.istate == null) return Z_STREAM_ERROR; if (z.istate.mode != BAD) { z.istate.mode = BAD; z.istate.marker = 0; } if ((n = z.avail_in) == 0) return Z_BUF_ERROR; p = z.next_in_index; m = z.istate.marker; // search while (n != 0 && m < 4) { if (z.next_in[p] == mark[m]) { m++; } else if (z.next_in[p] != 0) { m = 0; } else { m = 4 - m; } p++; n--; } // restore z.total_in += p - z.next_in_index; z.next_in_index = p; z.avail_in = n; z.istate.marker = m; // return no joy or set up to restart on a new block if (m != 4) { return Z_DATA_ERROR; } r = z.total_in; w = z.total_out; inflateReset(z); z.total_in = r; z.total_out = w; z.istate.mode = BLOCKS; return Z_OK; } // Returns true if inflate is currently at the end of a block generated // by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP // implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH // but removes the length bytes of the resulting empty stored block. When // decompressing, PPP checks that at the end of input packet, inflate is // waiting for these length bytes. internal int inflateSyncPoint(ZStream z) { if (z == null || z.istate == null || z.istate.blocks == null) return Z_STREAM_ERROR; return z.istate.blocks.sync_point(); } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/InfCodes.cs0000644000175000017500000005122211127003600024313 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { sealed class InfCodes { private static readonly int[] inflate_mask = new int[]{0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff}; private const int Z_OK = 0; private const int Z_STREAM_END = 1; private const int Z_NEED_DICT = 2; private const int Z_ERRNO = - 1; private const int Z_STREAM_ERROR = - 2; private const int Z_DATA_ERROR = - 3; private const int Z_MEM_ERROR = - 4; private const int Z_BUF_ERROR = - 5; private const int Z_VERSION_ERROR = - 6; // waiting for "i:"=input, // "o:"=output, // "x:"=nothing private const int START = 0; // x: set up for LEN private const int LEN = 1; // i: get length/literal/eob next private const int LENEXT = 2; // i: getting length extra (have base) private const int DIST = 3; // i: get distance next private const int DISTEXT = 4; // i: getting distance extra private const int COPY = 5; // o: copying bytes in window, waiting for space private const int LIT = 6; // o: got literal, waiting for output space private const int WASH = 7; // o: got eob, possibly still output waiting private const int END = 8; // x: got eob and all data flushed private const int BADCODE = 9; // x: got error internal int mode; // current inflate_codes mode // mode dependent information internal int len; internal int[] tree; // pointer into tree internal int tree_index = 0; internal int need; // bits needed internal int lit; // if EXT or COPY, where and how much internal int get_Renamed; // bits to get for extra internal int dist; // distance back to copy from internal byte lbits; // ltree bits decoded per branch internal byte dbits; // dtree bits decoder per branch internal int[] ltree; // literal/length/eob tree internal int ltree_index; // literal/length/eob tree internal int[] dtree; // distance tree internal int dtree_index; // distance tree internal InfCodes(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index, ZStream z) { mode = START; lbits = (byte) bl; dbits = (byte) bd; ltree = tl; ltree_index = tl_index; dtree = td; dtree_index = td_index; } internal InfCodes(int bl, int bd, int[] tl, int[] td, ZStream z) { mode = START; lbits = (byte) bl; dbits = (byte) bd; ltree = tl; ltree_index = 0; dtree = td; dtree_index = 0; } internal int proc(InfBlocks s, ZStream z, int r) { int j; // temporary storage //int[] t; // temporary pointer int tindex; // temporary pointer int e; // extra bits or operation int b = 0; // bit buffer int k = 0; // bits in bit buffer int p = 0; // input data pointer int n; // bytes available there int q; // output window write pointer int m; // bytes to end of window or read pointer int f; // pointer to copy strings from // copy input/output information to locals (UPDATE macro restores) p = z.next_in_index; n = z.avail_in; b = s.bitb; k = s.bitk; q = s.write; m = q < s.read?s.read - q - 1:s.end - q; // process input and output based on current state while (true) { switch (mode) { // waiting for "i:"=input, "o:"=output, "x:"=nothing case START: // x: set up for LEN if (m >= 258 && n >= 10) { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; r = inflate_fast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, s, z); p = z.next_in_index; n = z.avail_in; b = s.bitb; k = s.bitk; q = s.write; m = q < s.read?s.read - q - 1:s.end - q; if (r != Z_OK) { mode = r == Z_STREAM_END?WASH:BADCODE; break; } } need = lbits; tree = ltree; tree_index = ltree_index; mode = LEN; goto case LEN; case LEN: // i: get length/literal/eob next j = need; while (k < (j)) { if (n != 0) r = Z_OK; else { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } tindex = (tree_index + (b & inflate_mask[j])) * 3; b = SupportClass.URShift(b, (tree[tindex + 1])); k -= (tree[tindex + 1]); e = tree[tindex]; if (e == 0) { // literal lit = tree[tindex + 2]; mode = LIT; break; } if ((e & 16) != 0) { // length get_Renamed = e & 15; len = tree[tindex + 2]; mode = LENEXT; break; } if ((e & 64) == 0) { // next table need = e; tree_index = tindex / 3 + tree[tindex + 2]; break; } if ((e & 32) != 0) { // end of block mode = WASH; break; } mode = BADCODE; // invalid code z.msg = "invalid literal/length code"; r = Z_DATA_ERROR; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); case LENEXT: // i: getting length extra (have base) j = get_Renamed; while (k < (j)) { if (n != 0) r = Z_OK; else { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } len += (b & inflate_mask[j]); b >>= j; k -= j; need = dbits; tree = dtree; tree_index = dtree_index; mode = DIST; goto case DIST; case DIST: // i: get distance next j = need; while (k < (j)) { if (n != 0) r = Z_OK; else { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } tindex = (tree_index + (b & inflate_mask[j])) * 3; b >>= tree[tindex + 1]; k -= tree[tindex + 1]; e = (tree[tindex]); if ((e & 16) != 0) { // distance get_Renamed = e & 15; dist = tree[tindex + 2]; mode = DISTEXT; break; } if ((e & 64) == 0) { // next table need = e; tree_index = tindex / 3 + tree[tindex + 2]; break; } mode = BADCODE; // invalid code z.msg = "invalid distance code"; r = Z_DATA_ERROR; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); case DISTEXT: // i: getting distance extra j = get_Renamed; while (k < (j)) { if (n != 0) r = Z_OK; else { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } dist += (b & inflate_mask[j]); b >>= j; k -= j; mode = COPY; goto case COPY; case COPY: // o: copying bytes in window, waiting for space f = q - dist; while (f < 0) { // modulo window size-"while" instead f += s.end; // of "if" handles invalid distances } while (len != 0) { if (m == 0) { if (q == s.end && s.read != 0) { q = 0; m = q < s.read?s.read - q - 1:s.end - q; } if (m == 0) { s.write = q; r = s.inflate_flush(z, r); q = s.write; m = q < s.read?s.read - q - 1:s.end - q; if (q == s.end && s.read != 0) { q = 0; m = q < s.read?s.read - q - 1:s.end - q; } if (m == 0) { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } } } s.window[q++] = s.window[f++]; m--; if (f == s.end) f = 0; len--; } mode = START; break; case LIT: // o: got literal, waiting for output space if (m == 0) { if (q == s.end && s.read != 0) { q = 0; m = q < s.read?s.read - q - 1:s.end - q; } if (m == 0) { s.write = q; r = s.inflate_flush(z, r); q = s.write; m = q < s.read?s.read - q - 1:s.end - q; if (q == s.end && s.read != 0) { q = 0; m = q < s.read?s.read - q - 1:s.end - q; } if (m == 0) { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } } } r = Z_OK; s.window[q++] = (byte) lit; m--; mode = START; break; case WASH: // o: got eob, possibly more output if (k > 7) { // return unused byte, if any k -= 8; n++; p--; // can always return one } s.write = q; r = s.inflate_flush(z, r); q = s.write; m = q < s.read?s.read - q - 1:s.end - q; if (s.read != s.write) { s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } mode = END; goto case END; case END: r = Z_STREAM_END; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); case BADCODE: // x: got error r = Z_DATA_ERROR; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); default: r = Z_STREAM_ERROR; s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return s.inflate_flush(z, r); } } } internal void free(ZStream z) { // ZFREE(z, c); } // Called with number of bytes left to write in window at least 258 // (the maximum string length) and number of input bytes available // at least ten. The ten bytes are six bytes for the longest length/ // distance pair plus four bytes for overloading the bit buffer. internal int inflate_fast(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index, InfBlocks s, ZStream z) { int t; // temporary pointer int[] tp; // temporary pointer int tp_index; // temporary pointer int e; // extra bits or operation int b; // bit buffer int k; // bits in bit buffer int p; // input data pointer int n; // bytes available there int q; // output window write pointer int m; // bytes to end of window or read pointer int ml; // mask for literal/length tree int md; // mask for distance tree int c; // bytes to copy int d; // distance back to copy from int r; // copy source pointer // load input, output, bit values p = z.next_in_index; n = z.avail_in; b = s.bitb; k = s.bitk; q = s.write; m = q < s.read?s.read - q - 1:s.end - q; // initialize masks ml = inflate_mask[bl]; md = inflate_mask[bd]; // do until not enough input or output space for fast loop do { // assume called with m >= 258 && n >= 10 // get literal/length code while (k < (20)) { // max bits for literal/length code n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } t = b & ml; tp = tl; tp_index = tl_index; if ((e = tp[(tp_index + t) * 3]) == 0) { b >>= (tp[(tp_index + t) * 3 + 1]); k -= (tp[(tp_index + t) * 3 + 1]); s.window[q++] = (byte) tp[(tp_index + t) * 3 + 2]; m--; continue; } do { b >>= (tp[(tp_index + t) * 3 + 1]); k -= (tp[(tp_index + t) * 3 + 1]); if ((e & 16) != 0) { e &= 15; c = tp[(tp_index + t) * 3 + 2] + ((int) b & inflate_mask[e]); b >>= e; k -= e; // decode distance base of block to copy while (k < (15)) { // max bits for distance code n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } t = b & md; tp = td; tp_index = td_index; e = tp[(tp_index + t) * 3]; do { b >>= (tp[(tp_index + t) * 3 + 1]); k -= (tp[(tp_index + t) * 3 + 1]); if ((e & 16) != 0) { // get extra bits to add to distance base e &= 15; while (k < (e)) { // get extra bits (up to 13) n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } d = tp[(tp_index + t) * 3 + 2] + (b & inflate_mask[e]); b >>= (e); k -= (e); // do the copy m -= c; if (q >= d) { // offset before dest // just copy r = q - d; if (q - r > 0 && 2 > (q - r)) { s.window[q++] = s.window[r++]; c--; // minimum count is three, s.window[q++] = s.window[r++]; c--; // so unroll loop a little } else { Array.Copy(s.window, r, s.window, q, 2); q += 2; r += 2; c -= 2; } } else { // else offset after destination r = q - d; do { r += s.end; // force pointer in window } while (r < 0); // covers invalid distances e = s.end - r; if (c > e) { // if source crosses, c -= e; // wrapped copy if (q - r > 0 && e > (q - r)) { do { s.window[q++] = s.window[r++]; } while (--e != 0); } else { Array.Copy(s.window, r, s.window, q, e); q += e; r += e; e = 0; } r = 0; // copy rest from start of window } } // copy all or what's left if (q - r > 0 && c > (q - r)) { do { s.window[q++] = s.window[r++]; } while (--c != 0); } else { Array.Copy(s.window, r, s.window, q, c); q += c; r += c; c = 0; } break; } else if ((e & 64) == 0) { t += tp[(tp_index + t) * 3 + 2]; t += (b & inflate_mask[e]); e = tp[(tp_index + t) * 3]; } else { z.msg = "invalid distance code"; c = z.avail_in - n; c = (k >> 3) < c?k >> 3:c; n += c; p -= c; k -= (c << 3); s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return Z_DATA_ERROR; } } while (true); break; } if ((e & 64) == 0) { t += tp[(tp_index + t) * 3 + 2]; t += (b & inflate_mask[e]); if ((e = tp[(tp_index + t) * 3]) == 0) { b >>= (tp[(tp_index + t) * 3 + 1]); k -= (tp[(tp_index + t) * 3 + 1]); s.window[q++] = (byte) tp[(tp_index + t) * 3 + 2]; m--; break; } } else if ((e & 32) != 0) { c = z.avail_in - n; c = (k >> 3) < c?k >> 3:c; n += c; p -= c; k -= (c << 3); s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return Z_STREAM_END; } else { z.msg = "invalid literal/length code"; c = z.avail_in - n; c = (k >> 3) < c?k >> 3:c; n += c; p -= c; k -= (c << 3); s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return Z_DATA_ERROR; } } while (true); } while (m >= 258 && n >= 10); // not enough input or output--restore pointers and return c = z.avail_in - n; c = (k >> 3) < c?k >> 3:c; n += c; p -= c; k -= (c << 3); s.bitb = b; s.bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; s.write = q; return Z_OK; } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/InfBlocks.cs0000644000175000017500000004721511127003600024502 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { sealed class InfBlocks { private const int MANY = 1440; // And'ing with mask[n] masks the lower n bits private static readonly int[] inflate_mask = new int[]{0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff}; // Table for deflate from PKZIP's appnote.txt. internal static readonly int[] border = new int[]{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; private const int Z_OK = 0; private const int Z_STREAM_END = 1; private const int Z_NEED_DICT = 2; private const int Z_ERRNO = - 1; private const int Z_STREAM_ERROR = - 2; private const int Z_DATA_ERROR = - 3; private const int Z_MEM_ERROR = - 4; private const int Z_BUF_ERROR = - 5; private const int Z_VERSION_ERROR = - 6; private const int TYPE = 0; // get type bits (3, including end bit) private const int LENS = 1; // get lengths for stored private const int STORED = 2; // processing stored block private const int TABLE = 3; // get table lengths private const int BTREE = 4; // get bit lengths tree for a dynamic block private const int DTREE = 5; // get length, distance trees for a dynamic block private const int CODES = 6; // processing fixed or dynamic block private const int DRY = 7; // output remaining window bytes private const int DONE = 8; // finished last block, done private const int BAD = 9; // ot a data error--stuck here internal int mode; // current inflate_block mode internal int left; // if STORED, bytes left to copy internal int table; // table lengths (14 bits) internal int index; // index into blens (or border) internal int[] blens; // bit lengths of codes internal int[] bb = new int[1]; // bit length tree depth internal int[] tb = new int[1]; // bit length decoding tree internal InfCodes codes; // if CODES, current state internal int last; // true if this block is the last block // mode independent information internal int bitk; // bits in bit buffer internal int bitb; // bit buffer internal int[] hufts; // single malloc for tree space internal byte[] window; // sliding window internal int end; // one byte after sliding window internal int read; // window read pointer internal int write; // window write pointer internal System.Object checkfn; // check function internal long check; // check on output internal InfBlocks(ZStream z, System.Object checkfn, int w) { hufts = new int[MANY * 3]; window = new byte[w]; end = w; this.checkfn = checkfn; mode = TYPE; reset(z, null); } internal void reset(ZStream z, long[] c) { if (c != null) c[0] = check; if (mode == BTREE || mode == DTREE) { blens = null; } if (mode == CODES) { codes.free(z); } mode = TYPE; bitk = 0; bitb = 0; read = write = 0; if (checkfn != null) z.adler = check = z._adler.adler32(0L, null, 0, 0); } internal int proc(ZStream z, int r) { int t; // temporary storage int b; // bit buffer int k; // bits in bit buffer int p; // input data pointer int n; // bytes available there int q; // output window write pointer int m; // bytes to end of window or read pointer // copy input/output information to locals (UPDATE macro restores) { p = z.next_in_index; n = z.avail_in; b = bitb; k = bitk; } { q = write; m = (int) (q < read?read - q - 1:end - q); } // process input based on current state while (true) { switch (mode) { case TYPE: while (k < (3)) { if (n != 0) { r = Z_OK; } else { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } ; n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } t = (int) (b & 7); last = t & 1; switch (SupportClass.URShift(t, 1)) { case 0: // stored { b = SupportClass.URShift(b, (3)); k -= (3); } t = k & 7; // go to byte boundary { b = SupportClass.URShift(b, (t)); k -= (t); } mode = LENS; // get length of stored block break; case 1: // fixed { int[] bl = new int[1]; int[] bd = new int[1]; int[][] tl = new int[1][]; int[][] td = new int[1][]; InfTree.inflate_trees_fixed(bl, bd, tl, td, z); codes = new InfCodes(bl[0], bd[0], tl[0], td[0], z); } { b = SupportClass.URShift(b, (3)); k -= (3); } mode = CODES; break; case 2: // dynamic { b = SupportClass.URShift(b, (3)); k -= (3); } mode = TABLE; break; case 3: // illegal { b = SupportClass.URShift(b, (3)); k -= (3); } mode = BAD; z.msg = "invalid block type"; r = Z_DATA_ERROR; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } break; case LENS: while (k < (32)) { if (n != 0) { r = Z_OK; } else { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } ; n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } if (((SupportClass.URShift((~ b), 16)) & 0xffff) != (b & 0xffff)) { mode = BAD; z.msg = "invalid stored block lengths"; r = Z_DATA_ERROR; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } left = (b & 0xffff); b = k = 0; // dump bits mode = left != 0?STORED:(last != 0?DRY:TYPE); break; case STORED: if (n == 0) { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } if (m == 0) { if (q == end && read != 0) { q = 0; m = (int) (q < read?read - q - 1:end - q); } if (m == 0) { write = q; r = inflate_flush(z, r); q = write; m = (int) (q < read?read - q - 1:end - q); if (q == end && read != 0) { q = 0; m = (int) (q < read?read - q - 1:end - q); } if (m == 0) { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } } } r = Z_OK; t = left; if (t > n) t = n; if (t > m) t = m; Array.Copy(z.next_in, p, window, q, t); p += t; n -= t; q += t; m -= t; if ((left -= t) != 0) break; mode = last != 0?DRY:TYPE; break; case TABLE: while (k < (14)) { if (n != 0) { r = Z_OK; } else { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } ; n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } table = t = (b & 0x3fff); if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) { mode = BAD; z.msg = "too many length or distance symbols"; r = Z_DATA_ERROR; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f); blens = new int[t]; { b = SupportClass.URShift(b, (14)); k -= (14); } index = 0; mode = BTREE; goto case BTREE; case BTREE: while (index < 4 + (SupportClass.URShift(table, 10))) { while (k < (3)) { if (n != 0) { r = Z_OK; } else { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } ; n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } blens[border[index++]] = b & 7; { b = SupportClass.URShift(b, (3)); k -= (3); } } while (index < 19) { blens[border[index++]] = 0; } bb[0] = 7; t = InfTree.inflate_trees_bits(blens, bb, tb, hufts, z); if (t != Z_OK) { r = t; if (r == Z_DATA_ERROR) { blens = null; mode = BAD; } bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } index = 0; mode = DTREE; goto case DTREE; case DTREE: while (true) { t = table; if (!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))) { break; } int i, j, c; t = bb[0]; while (k < (t)) { if (n != 0) { r = Z_OK; } else { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } ; n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } if (tb[0] == - 1) { //System.err.println("null..."); } t = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 1]; c = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 2]; if (c < 16) { b = SupportClass.URShift(b, (t)); k -= (t); blens[index++] = c; } else { // c == 16..18 i = c == 18?7:c - 14; j = c == 18?11:3; while (k < (t + i)) { if (n != 0) { r = Z_OK; } else { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } ; n--; b |= (z.next_in[p++] & 0xff) << k; k += 8; } b = SupportClass.URShift(b, (t)); k -= (t); j += (b & inflate_mask[i]); b = SupportClass.URShift(b, (i)); k -= (i); i = index; t = table; if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)) { blens = null; mode = BAD; z.msg = "invalid bit length repeat"; r = Z_DATA_ERROR; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } c = c == 16?blens[i - 1]:0; do { blens[i++] = c; } while (--j != 0); index = i; } } tb[0] = - 1; { int[] bl = new int[1]; int[] bd = new int[1]; int[] tl = new int[1]; int[] td = new int[1]; bl[0] = 9; // must be <= 9 for lookahead assumptions bd[0] = 6; // must be <= 9 for lookahead assumptions t = table; t = InfTree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl, bd, tl, td, hufts, z); if (t != Z_OK) { if (t == Z_DATA_ERROR) { blens = null; mode = BAD; } r = t; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } codes = new InfCodes(bl[0], bd[0], hufts, tl[0], hufts, td[0], z); } blens = null; mode = CODES; goto case CODES; case CODES: bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; if ((r = codes.proc(this, z, r)) != Z_STREAM_END) { return inflate_flush(z, r); } r = Z_OK; codes.free(z); p = z.next_in_index; n = z.avail_in; b = bitb; k = bitk; q = write; m = (int) (q < read?read - q - 1:end - q); if (last == 0) { mode = TYPE; break; } mode = DRY; goto case DRY; case DRY: write = q; r = inflate_flush(z, r); q = write; m = (int) (q < read?read - q - 1:end - q); if (read != write) { bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } mode = DONE; goto case DONE; case DONE: r = Z_STREAM_END; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); case BAD: r = Z_DATA_ERROR; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); default: r = Z_STREAM_ERROR; bitb = b; bitk = k; z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p; write = q; return inflate_flush(z, r); } } } internal void free(ZStream z) { reset(z, null); window = null; hufts = null; //ZFREE(z, s); } internal void set_dictionary(byte[] d, int start, int n) { Array.Copy(d, start, window, 0, n); read = write = n; } // Returns true if inflate is currently at the end of a block generated // by Z_SYNC_FLUSH or Z_FULL_FLUSH. internal int sync_point() { return mode == LENS?1:0; } // copy as much as possible from the sliding window to the output area internal int inflate_flush(ZStream z, int r) { int n; int p; int q; // local copies of source and destination pointers p = z.next_out_index; q = read; // compute number of bytes to copy as far as end of window n = (int) ((q <= write?write:end) - q); if (n > z.avail_out) n = z.avail_out; if (n != 0 && r == Z_BUF_ERROR) r = Z_OK; // update counters z.avail_out -= n; z.total_out += n; // update check information if (checkfn != null) z.adler = check = z._adler.adler32(check, window, q, n); // copy as far as end of window Array.Copy(window, q, z.next_out, p, n); p += n; q += n; // see if more to copy at beginning of window if (q == end) { // wrap pointers q = 0; if (write == end) write = 0; // compute bytes to copy n = write - q; if (n > z.avail_out) n = z.avail_out; if (n != 0 && r == Z_BUF_ERROR) r = Z_OK; // update counters z.avail_out -= n; z.total_out += n; // update check information if (checkfn != null) z.adler = check = z._adler.adler32(check, window, q, n); // copy Array.Copy(window, q, z.next_out, p, n); p += n; q += n; } // update pointers z.next_out_index = p; read = q; // done return r; } } }mysql-connector-net-6.4.3/Source/MySql.Data/zlib/Zlib.cs0000644000175000017500000001030711127003600023520 0ustar directhexdirecthex// Copyright (c) 2006, ComponentAce // http://www.componentace.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /* Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * This program is based on zlib-1.1.3, so all credit should go authors * Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) * and contributors of zlib. */ using System; namespace zlib { sealed class zlibConst { private const System.String version_Renamed_Field = "1.0.2"; public static System.String version() { return version_Renamed_Field; } // compression levels public const int Z_NO_COMPRESSION = 0; public const int Z_BEST_SPEED = 1; public const int Z_BEST_COMPRESSION = 9; public const int Z_DEFAULT_COMPRESSION = (- 1); // compression strategy public const int Z_FILTERED = 1; public const int Z_HUFFMAN_ONLY = 2; public const int Z_DEFAULT_STRATEGY = 0; public const int Z_NO_FLUSH = 0; public const int Z_PARTIAL_FLUSH = 1; public const int Z_SYNC_FLUSH = 2; public const int Z_FULL_FLUSH = 3; public const int Z_FINISH = 4; public const int Z_OK = 0; public const int Z_STREAM_END = 1; public const int Z_NEED_DICT = 2; public const int Z_ERRNO = - 1; public const int Z_STREAM_ERROR = - 2; public const int Z_DATA_ERROR = - 3; public const int Z_MEM_ERROR = - 4; public const int Z_BUF_ERROR = - 5; public const int Z_VERSION_ERROR = - 6; } }mysql-connector-net-6.4.3/Source/MySql.Data/docs/0000755000175000017500000000000011127003600022260 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Data/docs/MySqlTransaction.xml0000644000175000017500000002736611127003600026273 0ustar directhexdirecthex Represents a SQL transaction to be made in a MySQL database. This class cannot be inherited. The application creates a MySqlTransaction object by calling on the object. All subsequent operations associated with the transaction (for example, committing or aborting the transaction), are performed on the MySqlTransaction object. The following example creates a and a MySqlTransaction. It also demonstrates how to use the , , and methods. Public Sub RunTransaction(myConnString As String) Dim myConnection As New MySqlConnection(myConnString) myConnection.Open() Dim myCommand As MySqlCommand = myConnection.CreateCommand() Dim myTrans As MySqlTransaction ' Start a local transaction myTrans = myConnection.BeginTransaction() ' Must assign both transaction object and connection ' to Command object for a pending local transaction myCommand.Connection = myConnection myCommand.Transaction = myTrans Try myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')" myCommand.ExecuteNonQuery() myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')" myCommand.ExecuteNonQuery() myTrans.Commit() Console.WriteLine("Both records are written to database.") Catch e As Exception Try myTrans.Rollback() Catch ex As MySqlException If Not myTrans.Connection Is Nothing Then Console.WriteLine("An exception of type " & ex.GetType().ToString() & _ " was encountered while attempting to roll back the transaction.") End If End Try Console.WriteLine("An exception of type " & e.GetType().ToString() & _ "was encountered while inserting the data.") Console.WriteLine("Neither record was written to database.") Finally myConnection.Close() End Try End Sub 'RunTransaction public void RunTransaction(string myConnString) { MySqlConnection myConnection = new MySqlConnection(myConnString); myConnection.Open(); MySqlCommand myCommand = myConnection.CreateCommand(); MySqlTransaction myTrans; // Start a local transaction myTrans = myConnection.BeginTransaction(); // Must assign both transaction object and connection // to Command object for a pending local transaction myCommand.Connection = myConnection; myCommand.Transaction = myTrans; try { myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')"; myCommand.ExecuteNonQuery(); myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')"; myCommand.ExecuteNonQuery(); myTrans.Commit(); Console.WriteLine("Both records are written to database."); } catch(Exception e) { try { myTrans.Rollback(); } catch (MySqlException ex) { if (myTrans.Connection != null) { Console.WriteLine("An exception of type " + ex.GetType() + " was encountered while attempting to roll back the transaction."); } } Console.WriteLine("An exception of type " + e.GetType() + " was encountered while inserting the data."); Console.WriteLine("Neither record was written to database."); } finally { myConnection.Close(); } } Rolls back a transaction from a pending state. The Rollback method is equivalent to the MySQL statement ROLLBACK. The transaction can only be rolled back from a pending state (after BeginTransaction has been called, but before Commit is called). The following example creates a and a . It also demonstrates how to use the , , and Rollback methods. Public Sub RunSqlTransaction(myConnString As String) Dim myConnection As New MySqlConnection(myConnString) myConnection.Open() Dim myCommand As MySqlCommand = myConnection.CreateCommand() Dim myTrans As MySqlTransaction ' Start a local transaction myTrans = myConnection.BeginTransaction() ' Must assign both transaction object and connection ' to Command object for a pending local transaction myCommand.Connection = myConnection myCommand.Transaction = myTrans Try myCommand.CommandText = "Insert into mytable (id, desc) VALUES (100, 'Description')" myCommand.ExecuteNonQuery() myCommand.CommandText = "Insert into mytable (id, desc) VALUES (101, 'Description')" myCommand.ExecuteNonQuery() myTrans.Commit() Console.WriteLine("Success.") Catch e As Exception Try myTrans.Rollback() Catch ex As MySqlException If Not myTrans.Connection Is Nothing Then Console.WriteLine("An exception of type " & ex.GetType().ToString() & _ " was encountered while attempting to roll back the transaction.") End If End Try Console.WriteLine("An exception of type " & e.GetType().ToString() & _ "was encountered while inserting the data.") Console.WriteLine("Neither record was written to database.") Finally myConnection.Close() End Try End Sub public void RunSqlTransaction(string myConnString) { MySqlConnection myConnection = new MySqlConnection(myConnString); myConnection.Open(); MySqlCommand myCommand = myConnection.CreateCommand(); MySqlTransaction myTrans; // Start a local transaction myTrans = myConnection.BeginTransaction(); // Must assign both transaction object and connection // to Command object for a pending local transaction myCommand.Connection = myConnection; myCommand.Transaction = myTrans; try { myCommand.CommandText = "Insert into mytable (id, desc) VALUES (100, 'Description')"; myCommand.ExecuteNonQuery(); myCommand.CommandText = "Insert into mytable (id, desc) VALUES (101, 'Description')"; myCommand.ExecuteNonQuery(); myTrans.Commit(); Console.WriteLine("Both records are written to database."); } catch(Exception e) { try { myTrans.Rollback(); } catch (MySqlException ex) { if (myTrans.Connection != null) { Console.WriteLine("An exception of type " + ex.GetType() + " was encountered while attempting to roll back the transaction."); } } Console.WriteLine("An exception of type " + e.GetType() + " was encountered while inserting the data."); Console.WriteLine("Neither record was written to database."); } finally { myConnection.Close(); } } Commits the database transaction. The Commit method is equivalent to the MySQL SQL statement COMMIT. The following example creates a and a . It also demonstrates how to use the , , and Rollback methods. Public Sub RunSqlTransaction(myConnString As String) Dim myConnection As New MySqlConnection(myConnString) myConnection.Open() Dim myCommand As MySqlCommand = myConnection.CreateCommand() Dim myTrans As MySqlTransaction ' Start a local transaction myTrans = myConnection.BeginTransaction() ' Must assign both transaction object and connection ' to Command object for a pending local transaction myCommand.Connection = myConnection myCommand.Transaction = myTrans Try myCommand.CommandText = "Insert into mytable (id, desc) VALUES (100, 'Description')" myCommand.ExecuteNonQuery() myCommand.CommandText = "Insert into mytable (id, desc) VALUES (101, 'Description')" myCommand.ExecuteNonQuery() myTrans.Commit() Console.WriteLine("Success.") Catch e As Exception Try myTrans.Rollback() Catch ex As MySqlException If Not myTrans.Connection Is Nothing Then Console.WriteLine("An exception of type " & ex.GetType().ToString() & _ " was encountered while attempting to roll back the transaction.") End If End Try Console.WriteLine("An exception of type " & e.GetType().ToString() & _ "was encountered while inserting the data.") Console.WriteLine("Neither record was written to database.") Finally myConnection.Close() End Try End Sub public void RunSqlTransaction(string myConnString) { MySqlConnection myConnection = new MySqlConnection(myConnString); myConnection.Open(); MySqlCommand myCommand = myConnection.CreateCommand(); MySqlTransaction myTrans; // Start a local transaction myTrans = myConnection.BeginTransaction(); // Must assign both transaction object and connection // to Command object for a pending local transaction myCommand.Connection = myConnection; myCommand.Transaction = myTrans; try { myCommand.CommandText = "Insert into mytable (id, desc) VALUES (100, 'Description')"; myCommand.ExecuteNonQuery(); myCommand.CommandText = "Insert into mytable (id, desc) VALUES (101, 'Description')"; myCommand.ExecuteNonQuery(); myTrans.Commit(); Console.WriteLine("Both records are written to database."); } catch(Exception e) { try { myTrans.Rollback(); } catch (MySqlException ex) { if (myTrans.Connection != null) { Console.WriteLine("An exception of type " + ex.GetType() + " was encountered while attempting to roll back the transaction."); } } Console.WriteLine("An exception of type " + e.GetType() + " was encountered while inserting the data."); Console.WriteLine("Neither record was written to database."); } finally { myConnection.Close(); } } mysql-connector-net-6.4.3/Source/MySql.Data/docs/MySqlConnection.xml0000644000175000017500000014336311127003600026101 0ustar directhexdirecthex Initializes a new instance of the class. When a new instance of is created, the read/write properties are set to the following initial values unless they are specifically set using their associated keywords in the property. Properties Initial Value empty string ("") 15 empty string ("") empty string ("") empty string ("") You can change the value for these properties only by using the ConnectionString property. Initializes a new instance of the class. Initializes a new instance of the class when given a string containing the connection string. When a new instance of is created, the read/write properties are set to the following initial values unless they are specifically set using their associated keywords in the property. Properties Initial Value empty string ("") 15 empty string ("") empty string ("") empty string ("") You can change the value for these properties only by using the ConnectionString property. The connection properties used to open the MySQL database. Opens a database connection with the property settings specified by the ConnectionString. Cannot open a connection without specifying a data source or server. A connection-level error occurred while opening the connection. The draws an open connection from the connection pool if one is available. Otherwise, it establishes a new connection to an instance of MySQL. The following example creates a , opens it, displays some of its properties, then closes the connection. Public Sub CreateMySqlConnection(myConnString As String) Dim myConnection As New MySqlConnection(myConnString) myConnection.Open() MessageBox.Show("ServerVersion: " + myConnection.ServerVersion _ + ControlChars.Cr + "State: " + myConnection.State.ToString()) myConnection.Close() End Sub public void CreateMySqlConnection(string myConnString) { MySqlConnection myConnection = new MySqlConnection(myConnString); myConnection.Open(); MessageBox.Show("ServerVersion: " + myConnection.ServerVersion + "\nState: " + myConnection.State.ToString()); myConnection.Close(); } Gets the name of the current database or the database to be used after a connection is opened. The name of the current database or the name of the database to be used after a connection is opened. The default value is an empty string. The Database property does not update dynamically. If you change the current database using a SQL statement, then this property may reflect the wrong value. If you change the current database using the method, this property is updated to reflect the new database. The following example creates a and displays some of its read-only properties. Public Sub CreateMySqlConnection() Dim myConnString As String = _ "Persist Security Info=False;database=test;server=localhost;user id=joeuser;pwd=pass" Dim myConnection As New MySqlConnection( myConnString ) myConnection.Open() MessageBox.Show( "Server Version: " + myConnection.ServerVersion _ + ControlChars.NewLine + "Database: " + myConnection.Database ) myConnection.ChangeDatabase( "test2" ) MessageBox.Show( "ServerVersion: " + myConnection.ServerVersion _ + ControlChars.NewLine + "Database: " + myConnection.Database ) myConnection.Close() End Sub public void CreateMySqlConnection() { string myConnString = "Persist Security Info=False;database=test;server=localhost;user id=joeuser;pwd=pass"; MySqlConnection myConnection = new MySqlConnection( myConnString ); myConnection.Open(); MessageBox.Show( "Server Version: " + myConnection.ServerVersion + "\nDatabase: " + myConnection.Database ); myConnection.ChangeDatabase( "test2" ); MessageBox.Show( "ServerVersion: " + myConnection.ServerVersion + "\nDatabase: " + myConnection.Database ); myConnection.Close(); } Gets the current state of the connection. A bitwise combination of the values. The default is Closed. The allowed state changes are: From Closed to Open, using the Open method of the connection object. From Open to Closed, using either the Close method or the Dispose method of the connection object. The following example creates a , opens it, displays some of its properties, then closes the connection. Public Sub CreateMySqlConnection(myConnString As String) Dim myConnection As New MySqlConnection(myConnString) myConnection.Open() MessageBox.Show("ServerVersion: " + myConnection.ServerVersion _ + ControlChars.Cr + "State: " + myConnection.State.ToString()) myConnection.Close() End Sub public void CreateMySqlConnection(string myConnString) { MySqlConnection myConnection = new MySqlConnection(myConnString); myConnection.Open(); MessageBox.Show("ServerVersion: " + myConnection.ServerVersion + "\nState: " + myConnection.State.ToString()); myConnection.Close(); } Gets a string containing the version of the MySQL server to which the client is connected. The version of the instance of MySQL. The connection is closed. The following example creates a , opens it, displays some of its properties, then closes the connection. Public Sub CreateMySqlConnection(myConnString As String) Dim myConnection As New MySqlConnection(myConnString) myConnection.Open() MessageBox.Show("ServerVersion: " + myConnection.ServerVersion _ + ControlChars.Cr + "State: " + myConnection.State.ToString()) myConnection.Close() End Sub public void CreateMySqlConnection(string myConnString) { MySqlConnection myConnection = new MySqlConnection(myConnString); myConnection.Open(); MessageBox.Show("ServerVersion: " + myConnection.ServerVersion + "\nState: " + myConnection.State.ToString()); myConnection.Close(); } Closes the connection to the database. This is the preferred method of closing any open connection. The Close method rolls back any pending transactions. It then releases the connection to the connection pool, or closes the connection if connection pooling is disabled. An application can call Close more than one time. No exception is generated. The following example creates a , opens it, displays some of its properties, then closes the connection. Public Sub CreateMySqlConnection(myConnString As String) Dim myConnection As New MySqlConnection(myConnString) myConnection.Open() MessageBox.Show("ServerVersion: " + myConnection.ServerVersion _ + ControlChars.Cr + "State: " + myConnection.State.ToString()) myConnection.Close() End Sub public void CreateMySqlConnection(string myConnString) { MySqlConnection myConnection = new MySqlConnection(myConnString); myConnection.Open(); MessageBox.Show("ServerVersion: " + myConnection.ServerVersion + "\nState: " + myConnection.State.ToString()); myConnection.Close(); } Creates and returns a object associated with the . A object. Begins a database transaction. An object representing the new transaction. Parallel transactions are not supported. This command is equivalent to the MySQL BEGIN TRANSACTION command. You must explicitly commit or roll back the transaction using the or method. If you do not specify an isolation level, the default isolation level is used. To specify an isolation level with the method, use the overload that takes the iso parameter. Also note that any attempt to begin a transaction while a transaction is in progress will throw an exception on MySQL 4.1 and higher. On MySQL 4.0, an exception will not be thrown because servers 4.0 and earlier did not report their transacation status. The following example creates a and a . It also demonstrates how to use the BeginTransaction, a , and methods. Public Sub RunTransaction(myConnString As String) Dim myConnection As New MySqlConnection(myConnString) myConnection.Open() Dim myCommand As MySqlCommand = myConnection.CreateCommand() Dim myTrans As MySqlTransaction ' Start a local transaction myTrans = myConnection.BeginTransaction() ' Must assign both transaction object and connection ' to Command object for a pending local transaction myCommand.Connection = myConnection myCommand.Transaction = myTrans Try myCommand.CommandText = "Insert into Test (id, desc) VALUES (100, 'Description')" myCommand.ExecuteNonQuery() myCommand.CommandText = "Insert into Test (id, desc) VALUES (101, 'Description')" myCommand.ExecuteNonQuery() myTrans.Commit() Console.WriteLine("Both records are written to database.") Catch e As Exception Try myTrans.Rollback() Catch ex As MySqlException If Not myTrans.Connection Is Nothing Then Console.WriteLine("An exception of type " + ex.GetType().ToString() + _ " was encountered while attempting to roll back the transaction.") End If End Try Console.WriteLine("An exception of type " + e.GetType().ToString() + _ "was encountered while inserting the data.") Console.WriteLine("Neither record was written to database.") Finally myConnection.Close() End Try End Sub public void RunTransaction(string myConnString) { MySqlConnection myConnection = new MySqlConnection(myConnString); myConnection.Open(); MySqlCommand myCommand = myConnection.CreateCommand(); MySqlTransaction myTrans; // Start a local transaction myTrans = myConnection.BeginTransaction(); // Must assign both transaction object and connection // to Command object for a pending local transaction myCommand.Connection = myConnection; myCommand.Transaction = myTrans; try { myCommand.CommandText = "insert into Test (id, desc) VALUES (100, 'Description')"; myCommand.ExecuteNonQuery(); myCommand.CommandText = "insert into Test (id, desc) VALUES (101, 'Description')"; myCommand.ExecuteNonQuery(); myTrans.Commit(); Console.WriteLine("Both records are written to database."); } catch(Exception e) { try { myTrans.Rollback(); } catch (SqlException ex) { if (myTrans.Connection != null) { Console.WriteLine("An exception of type " + ex.GetType() + " was encountered while attempting to roll back the transaction."); } } Console.WriteLine("An exception of type " + e.GetType() + " was encountered while inserting the data."); Console.WriteLine("Neither record was written to database."); } finally { myConnection.Close(); } } Begins a database transaction with the specified isolation level. The isolation level under which the transaction should run. An object representing the new transaction. Parallel exceptions are not supported. This command is equivalent to the MySQL BEGIN TRANSACTION command. You must explicitly commit or roll back the transaction using the or method. If you do not specify an isolation level, the default isolation level is used. To specify an isolation level with the method, use the overload that takes the iso parameter. Also note that any attempt to begin a transaction while a transaction is in progress will throw an exception on MySQL 4.1 and higher. On MySQL 4.0, an exception will not be thrown because servers 4.0 and earlier did not report their transacation status. The following example creates a and a . It also demonstrates how to use the BeginTransaction, a , and methods. Public Sub RunTransaction(myConnString As String) Dim myConnection As New MySqlConnection(myConnString) myConnection.Open() Dim myCommand As MySqlCommand = myConnection.CreateCommand() Dim myTrans As MySqlTransaction ' Start a local transaction myTrans = myConnection.BeginTransaction() ' Must assign both transaction object and connection ' to Command object for a pending local transaction myCommand.Connection = myConnection myCommand.Transaction = myTrans Try myCommand.CommandText = "Insert into Test (id, desc) VALUES (100, 'Description')" myCommand.ExecuteNonQuery() myCommand.CommandText = "Insert into Test (id, desc) VALUES (101, 'Description')" myCommand.ExecuteNonQuery() myTrans.Commit() Console.WriteLine("Both records are written to database.") Catch e As Exception Try myTrans.Rollback() Catch ex As MySqlException If Not myTrans.Connection Is Nothing Then Console.WriteLine("An exception of type " + ex.GetType().ToString() + _ " was encountered while attempting to roll back the transaction.") End If End Try Console.WriteLine("An exception of type " + e.GetType().ToString() + _ "was encountered while inserting the data.") Console.WriteLine("Neither record was written to database.") Finally myConnection.Close() End Try End Sub public void RunTransaction(string myConnString) { MySqlConnection myConnection = new MySqlConnection(myConnString); myConnection.Open(); MySqlCommand myCommand = myConnection.CreateCommand(); MySqlTransaction myTrans; // Start a local transaction myTrans = myConnection.BeginTransaction(); // Must assign both transaction object and connection // to Command object for a pending local transaction myCommand.Connection = myConnection; myCommand.Transaction = myTrans; try { myCommand.CommandText = "insert into Test (id, desc) VALUES (100, 'Description')"; myCommand.ExecuteNonQuery(); myCommand.CommandText = "insert into Test (id, desc) VALUES (101, 'Description')"; myCommand.ExecuteNonQuery(); myTrans.Commit(); Console.WriteLine("Both records are written to database."); } catch(Exception e) { try { myTrans.Rollback(); } catch (SqlException ex) { if (myTrans.Connection != null) { Console.WriteLine("An exception of type " + ex.GetType() + " was encountered while attempting to roll back the transaction."); } } Console.WriteLine("An exception of type " + e.GetType() + " was encountered while inserting the data."); Console.WriteLine("Neither record was written to database."); } finally { myConnection.Close(); } } Changes the current database for an open MySqlConnection. The name of the database to use. The value supplied in the database parameter must be a valid database name. The database parameter cannot contain a null value, an empty string, or a string with only blank characters. When you are using connection pooling against MySQL, and you close the connection, it is returned to the connection pool. The next time the connection is retrieved from the pool, the reset connection request executes before the user performs any operations. The database name is not valid. The connection is not open. Cannot change the database. The following example creates a and displays some of its read-only properties. Public Sub CreateMySqlConnection() Dim myConnString As String = _ "Persist Security Info=False;database=test;server=localhost;user id=joeuser;pwd=pass" Dim myConnection As New MySqlConnection( myConnString ) myConnection.Open() MessageBox.Show( "Server Version: " + myConnection.ServerVersion _ + ControlChars.NewLine + "Database: " + myConnection.Database ) myConnection.ChangeDatabase( "test2" ) MessageBox.Show( "ServerVersion: " + myConnection.ServerVersion _ + ControlChars.NewLine + "Database: " + myConnection.Database ) myConnection.Close() End Sub public void CreateMySqlConnection() { string myConnString = "Persist Security Info=False;database=test;server=localhost;user id=joeuser;pwd=pass"; MySqlConnection myConnection = new MySqlConnection( myConnString ); myConnection.Open(); MessageBox.Show( "Server Version: " + myConnection.ServerVersion + "\nDatabase: " + myConnection.Database ); myConnection.ChangeDatabase( "test2" ); MessageBox.Show( "ServerVersion: " + myConnection.ServerVersion + "\nDatabase: " + myConnection.Database ); myConnection.Close(); } Occurs when the state of the connection changes. The StateChange event fires whenever the changes from closed to opened, or from opened to closed. StateChange fires immediately after the transitions. If an event handler throws an exception from within the StateChange event, the exception propagates to the caller of the or method. The StateChange event is not raised unless you explicitly call Close or Dispose. Raised. The event handler receives an argument of type containing data related to this event. The following StateChangeEventArgs properties provide information specific to this event. Property Description Gets the new state of the connection. The connection object will be in the new state already when the event is fired. Gets the original state of the connection. Occurs when MySQL returns warnings as a result of executing a command or query. Represents an open connection to a MySQL Server database. This class cannot be inherited. A MySqlConnection object represents a session to a MySQL Server data source. When you create an instance of MySqlConnection, all properties are set to their initial values. For a list of these values, see the MySqlConnection constructor. If the MySqlConnection goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling or . The following example creates a and a MySqlConnection. The MySqlConnection is opened and set as the for the MySqlCommand. The example then calls , and closes the connection. To accomplish this, the ExecuteNonQuery is passed a connection string and a query string that is a SQL INSERT statement. Public Sub InsertRow(myConnectionString As String) ' If the connection string is null, use a default. If myConnectionString = "" Then myConnectionString = "Database=Test;Data Source=localhost;User Id=username;Password=pass" End If Dim myConnection As New MySqlConnection(myConnectionString) Dim myInsertQuery As String = "INSERT INTO Orders (id, customerId, amount) Values(1001, 23, 30.66)" Dim myCommand As New MySqlCommand(myInsertQuery) myCommand.Connection = myConnection myConnection.Open() myCommand.ExecuteNonQuery() myCommand.Connection.Close() End Sub public void InsertRow(string myConnectionString) { // If the connection string is null, use a default. if(myConnectionString == "") { myConnectionString = "Database=Test;Data Source=localhost;User Id=username;Password=pass"; } MySqlConnection myConnection = new MySqlConnection(myConnectionString); string myInsertQuery = "INSERT INTO Orders (id, customerId, amount) Values(1001, 23, 30.66)"; MySqlCommand myCommand = new MySqlCommand(myInsertQuery); myCommand.Connection = myConnection; myConnection.Open(); myCommand.ExecuteNonQuery(); myCommand.Connection.Close(); } Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error. The value set is less than 0. A value of 0 indicates no limit, and should be avoided in a because an attempt to connect will wait indefinitely. The following example creates a MySqlConnection and sets some of its properties in the connection string. Public Sub CreateSqlConnection() Dim myConnection As New MySqlConnection() myConnection.ConnectionString = "Persist Security Info=False;Username=user;Password=pass;database=test1;server=localhost;Connect Timeout=30" myConnection.Open() End Sub public void CreateSqlConnection() { MySqlConnection myConnection = new MySqlConnection(); myConnection.ConnectionString = "Persist Security Info=False;Username=user;Password=pass;database=test1;server=localhost;Connect Timeout=30"; myConnection.Open(); } Gets or sets the string used to connect to a MySQL Server database. The ConnectionString returned may not be exactly like what was originally set but will be indentical in terms of keyword/value pairs. Security information will not be included unless the Persist Security Info value is set to true. You can use the ConnectionString property to connect to a database. The following example illustrates a typical connection string. "Persist Security Info=False;database=MyDB;server=MySqlServer;user id=myUser;Password=myPass" The ConnectionString property can be set only when the connection is closed. Many of the connection string values have corresponding read-only properties. When the connection string is set, all of these properties are updated, except when an error is detected. In this case, none of the properties are updated. properties return only those settings contained in the ConnectionString. To connect to a local machine, specify "localhost" for the server. If you do not specify a server, localhost is assumed. Resetting the ConnectionString on a closed connection resets all connection string values (and related properties) including the password. For example, if you set a connection string that includes "Database= MyDb", and then reset the connection string to "Data Source=myserver;User Id=myUser;Password=myPass", the property is no longer set to MyDb. The connection string is parsed immediately after being set. If errors in syntax are found when parsing, a runtime exception, such as , is generated. Other errors can be found only when an attempt is made to open the connection. The basic format of a connection string consists of a series of keyword/value pairs separated by semicolons. The equal sign (=) connects each keyword and its value. To include values that contain a semicolon, single-quote character, or double-quote character, the value must be enclosed in double quotes. If the value contains both a semicolon and a double-quote character, the value can be enclosed in single quotes. The single quote is also useful if the value begins with a double-quote character. Conversely, the double quote can be used if the value begins with a single quote. If the value contains both single-quote and double-quote characters, the quote character used to enclose the value must be doubled each time it occurs within the value. To include preceding or trailing spaces in the string value, the value must be enclosed in either single quotes or double quotes. Any leading or trailing spaces around integer, Boolean, or enumerated values are ignored, even if enclosed in quotes. However, spaces within a string literal keyword or value are preserved. Using .NET Framework version 1.1, single or double quotes may be used within a connection string without using delimiters (for example, Data Source= my'Server or Data Source= my"Server), unless a quote character is the first or last character in the value. To include an equal sign (=) in a keyword or value, it must be preceded by another equal sign. For example, in the hypothetical connection string "key==word=value" the keyword is "key=word" and the value is "value". If a specific keyword in a keyword= value pair occurs multiple times in a connection string, the last occurrence listed is used in the value set. Keywords are not case sensitive. The following table lists the valid names for keyword values within the ConnectionString.
Name Default Description
Connect Timeout -or- Connection Timeout 15 The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.
Host -or- Server -or- Data Source -or- DataSource -or- Address -or- Addr -or- Network Address localhost The name or network address of the instance of MySQL to which to connect. Multiple hosts can be specified separated by &. This can be useful where multiple MySQL servers are configured for replication and you are not concerned about the precise server you are connecting to. No attempt is made by the provider to synchronize writes to the database so care should be taken when using this option. In Unix environment with Mono, this can be a fully qualified path to MySQL socket filename. With this configuration, the Unix socket will be used instead of TCP/IP socket. Currently only a single socket name can be given so accessing MySQL in a replicated environment using Unix sockets is not currently supported.
Port 3306 The port MySQL is using to listen for connections. This value is ignored if the connection protocol is anything but socket.
Protocol socket Specifies the type of connection to make to the server.Values can be: socket or tcp for a socket connection
pipe for a named pipe connection
unix for a Unix socket connection
memory to use MySQL shared memory
CharSet -or Character Set Specifies the character set that should be used to encode all queries sent to the server. Resultsets are still returned in the character set of the data returned.
Logging false When true, various pieces of information is output to any configured TraceListeners.
Allow Batch true When true, multiple SQL statements can be sent with one command execution.

-Note-
Starting with MySQL 4.1.1, batch statements should be separated by the server-defined seperator character.
Commands sent to earlier versions of MySQL should be seperated with ';'.
Encrypt false When true, SSL/TLS encryption is used for all data sent between the client and server if the server has a certificate installed. Recognized values are true, false, yes, and no.
Initial Catalog -or- Database mysql The name of the database to use intially
Password -or- pwd The password for the MySQL account being used.
Persist Security Info false When set to false or no (strongly recommended), security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Resetting the connection string resets all connection string values including the password. Recognized values are true, false, yes, and no.
User Id -or- Username -or- Uid -or- User name The MySQL login account being used.
Shared Memory Name MYSQL The name of the shared memory object to use for communication if the connection protocol is set to memory.
Allow Zero Datetime false True to have MySqlDataReader.GetValue() return a MySqlDateTime for date or datetime columns that have illegal values. False will cause a DateTime object to be returned for legal values and an exception will be thrown for illegal values.
Convert Zero Datetime false True to have MySqlDataReader.GetValue() and MySqlDataReader.GetDateTime() return DateTime.MinValue for date or datetime columns that have illegal values.
Pipe Name -or- Pipe mysql When set to the name of a named pipe, the MySqlConnection will attempt to connect to MySQL on that named pipe.

This settings only applies to the Windows platform.
Use Performance Monitor -or- UsePerformanceMonitor false Posts performance data that can be tracked using perfmon
Procedure Cache Size 25 How many stored procedure definitions can be held in the cache
Ignore Prepare true Instructs the provider to ignore any attempts to prepare commands. This option was added to allow a user to disable prepared statements in an entire application without modifying the code. A user might want to do this if errors or bugs are encountered with MySQL prepared statements.
Use Procedure Bodies true Instructs the provider to attempt to call the procedure without first resolving the metadata. This is useful in situations where the calling user does not have access to the mysql.proc table. To use this mode, the parameters for the procedure must be added to the command in the same order as they appear in the procedure definition and their types must be explicitly set.
Auto Enlist true Indicates whether the connection should automatically enlist in the current transaction, if there is one.
Respect Binary Flags true Indicates whether the connection should respect all binary flags sent to the client as part of column metadata. False will cause the connector to behave like Connector/Net 5.0 and earlier.
BlobAsUTF8IncludePattern null Pattern that should be used to indicate which blob columns should be treated as UTF-8.
BlobAsUTF8ExcludePattern null Pattern that should be used to indicate which blob columns should not be treated as UTF-8.
Default Command Timeout 30 The default timeout that new MySqlCommand objects will use unless changed.
Allow User Variables false Should the provider expect user variables in the SQL.
Interactive -or- Interactive Session false Should this session be considered interactive?
Functions Return String false Set this option to true to force the return value of SQL functions to be string.
Use Affected Rows false Set this option to true to cause the affected rows reported to reflect only the rows that are actually changed. By default, the number of rows that are matched is returned.
The following table lists the valid names for connection pooling values within the ConnectionString. For more information about connection pooling, see Connection Pooling for the MySql Data Provider.
Name Default Description
Connection Lifetime 0 When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by Connection Lifetime. This is useful in clustered configurations to force load balancing between a running server and a server just brought online. A value of zero (0) causes pooled connections to have the maximum connection timeout.
Max Pool Size 100 The maximum number of connections allowed in the pool.
Min Pool Size 0 The minimum number of connections allowed in the pool.
Pooling true When true, the MySqlConnection object is drawn from the appropriate pool, or if necessary, is created and added to the appropriate pool. Recognized values are true, false, yes, and no.
Connection Reset false Specifies whether the database connection should be reset when being drawn from the pool. Leaving this as false will yeild much faster connection opens but the user should understand the side effects of doing this such as temporary tables and user variables from the previous session not being cleared out.
Cache Server Properties false Specifies whether the server variables are cached between pooled connections. On systems where the variables change infrequently and there are lots of connection attempts, this can speed up things dramatically.
When setting keyword or connection pooling values that require a Boolean value, you can use 'yes' instead of 'true', and 'no' instead of 'false'. Note The MySql Data Provider uses the native socket protocol to communicate with MySQL. Therefore, it does not support the use of an ODBC data source name (DSN) when connecting to MySQL because it does not add an ODBC layer. CAUTION In this release, the application should use caution when constructing a connection string based on user input (for example when retrieving user ID and password information from a dialog box, and appending it to the connection string). The application should ensure that a user cannot embed extra connection string parameters in these values (for example, entering a password as "validpassword;database=somedb" in an attempt to attach to a different database). The following example creates a and sets some of its properties Public Sub CreateConnection() Dim myConnection As New MySqlConnection() myConnection.ConnectionString = "Persist Security Info=False;database=myDB;server=myHost;Connect Timeout=30;user id=myUser; pwd=myPass" myConnection.Open() End Sub 'CreateConnection public void CreateConnection() { MySqlConnection myConnection = new MySqlConnection(); myConnection.ConnectionString = "Persist Security Info=False;database=myDB;server=myHost;Connect Timeout=30;user id=myUser; pwd=myPass"; myConnection.Open(); } The following example creates a in Unix environment with Mono installed. MySQL socket filename used in this example is "/var/lib/mysql/mysql.sock". The actual filename depends on your MySQL configuration. Public Sub CreateConnection() Dim myConnection As New MySqlConnection() myConnection.ConnectionString = "database=myDB;server=/var/lib/mysql/mysql.sock;user id=myUser; pwd=myPass" myConnection.Open() End Sub 'CreateConnection public void CreateConnection() { MySqlConnection myConnection = new MySqlConnection(); myConnection.ConnectionString = "database=myDB;server=/var/lib/mysql/mysql.sock;user id=myUser; pwd=myPass"; myConnection.Open(); } Empties the connection pool associated with the specified connection. The associated with the pool to be cleared. ClearPool clears the connection pool that is associated with the connection. If additional connections associated with connection are in use at the time of the call, they are marked appropriately and are discarded (instead of being returned to the pool) when Close is called on them. Clears all connection pools. ClearAllPools essentially performs a on all current connection pools. mysql-connector-net-6.4.3/Source/MySql.Data/docs/MySqlConnectionStringBuilder.xml0000644000175000017500000000255711127003600030576 0ustar directhexdirecthex Gets or sets the name or address of the MySQL instance to connect to. If this property is not set, then the provider will attempt to connect to localhost even though this property will return String.Empty. Gets or sets the name of the database that should be selected when the connection is first opened. There is no default for this property and, if not set, the connection will not have a current database until one is set using the method. Gets or sets the connection protocol that is being used for this connection. Gets or sets the name of the named pipe object that the provider should use. This property has no effect unless the property has been set to NamedPipe. mysql-connector-net-6.4.3/Source/MySql.Data/docs/MySqlCommand.xml0000644000175000017500000010171211127003600025350 0ustar directhexdirecthex Represents a SQL statement to execute against a MySQL database. This class cannot be inherited. MySqlCommand features the following methods for executing commands at a MySQL database: Item Description ExecuteReader Executes commands that return rows. ExecuteNonQuery Executes commands such as SQL INSERT, DELETE, and UPDATE statements. ExecuteScalar Retrieves a single value (for example, an aggregate value) from a database. You can reset the CommandText property and reuse the MySqlCommand object. However, you must close the MySqlDataReader before you can execute a new or previous command. If a MySqlException is generated by the method executing a MySqlCommand, the MySqlConnection remains open. It is the responsibility of the programmer to close the connection. Using the '@' symbol for paramters is now the preferred approach although the old pattern of using '?' is still supported. Please be aware though that using '@' can cause conflicts when user variables are also used. To help with this situation please see the documentation on the 'allow user variables' connection string option. The 'old syntax' connection string option has now been deprecated. The following example creates a MySqlCommand and a MySqlConnection. The MySqlConnection is opened and set as the Connection for the MySqlCommand. The example then calls ExecuteNonQuery, and closes the connection. To accomplish this, the ExecuteNonQuery is passed a connection string and a query string that is a SQL INSERT statement. Public Sub InsertRow(myConnectionString As String) " If the connection string is null, use a default. If myConnectionString = "" Then myConnectionString = "Database=Test;Data Source=localhost;User Id=username;Password=pass" End If Dim myConnection As New MySqlConnection(myConnectionString) Dim myInsertQuery As String = "INSERT INTO Orders (id, customerId, amount) Values(1001, 23, 30.66)" Dim myCommand As New MySqlCommand(myInsertQuery) myCommand.Connection = myConnection myConnection.Open() myCommand.ExecuteNonQuery() myCommand.Connection.Close() End Sub public void InsertRow(string myConnectionString) { // If the connection string is null, use a default. if(myConnectionString == "") { myConnectionString = "Database=Test;Data Source=localhost;User Id=username;Password=pass"; } MySqlConnection myConnection = new MySqlConnection(myConnectionString); string myInsertQuery = "INSERT INTO Orders (id, customerId, amount) Values(1001, 23, 30.66)"; MySqlCommand myCommand = new MySqlCommand(myInsertQuery); myCommand.Connection = myConnection; myConnection.Open(); myCommand.ExecuteNonQuery(); myCommand.Connection.Close(); } Initializes a new instance of the MySqlCommand class. The following example creates a MySqlCommand and sets some of its properties. This example shows how to use one of the overloaded versions of the MySqlCommand constructor. For other examples that might be available, see the individual overload topics. Public Sub CreateMySqlCommand() Dim myConnection As New MySqlConnection _ ("Persist Security Info=False;database=test;server=myServer") myConnection.Open() Dim myTrans As MySqlTransaction = myConnection.BeginTransaction() Dim mySelectQuery As String = "SELECT * FROM MyTable" Dim myCommand As New MySqlCommand(mySelectQuery, myConnection, myTrans) myCommand.CommandTimeout = 20 End Sub public void CreateMySqlCommand() { MySqlConnection myConnection = new MySqlConnection("Persist Security Info=False; database=test;server=myServer"); myConnection.Open(); MySqlTransaction myTrans = myConnection.BeginTransaction(); string mySelectQuery = "SELECT * FROM myTable"; MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection,myTrans); myCommand.CommandTimeout = 20; } public: void CreateMySqlCommand() { MySqlConnection* myConnection = new MySqlConnection(S"Persist Security Info=False; database=test;server=myServer"); myConnection->Open(); MySqlTransaction* myTrans = myConnection->BeginTransaction(); String* mySelectQuery = S"SELECT * FROM myTable"; MySqlCommand* myCommand = new MySqlCommand(mySelectQuery, myConnection, myTrans); myCommand->CommandTimeout = 20; }; Initializes a new instance of the MySqlCommand class. The base constructor initializes all fields to their default values. The following table shows initial property values for an instance of . Properties Initial Value empty string ("") 0 CommandType.Text Null You can change the value for any of these properties through a separate call to the property. The following example creates a and sets some of its properties. Public Sub CreateMySqlCommand() Dim myCommand As New MySqlCommand() myCommand.CommandType = CommandType.Text End Sub public void CreateMySqlCommand() { MySqlCommand myCommand = new MySqlCommand(); myCommand.CommandType = CommandType.Text; } Initializes a new instance of the class with the text of the query. The text of the query. When an instance of is created, the following read/write properties are set to initial values. Properties Initial Value cmdText 0 CommandType.Text Null You can change the value for any of these properties through a separate call to the property. The following example creates a and sets some of its properties. Public Sub CreateMySqlCommand() Dim sql as String = "SELECT * FROM mytable" Dim myCommand As New MySqlCommand(sql) myCommand.CommandType = CommandType.Text End Sub public void CreateMySqlCommand() { string sql = "SELECT * FROM mytable"; MySqlCommand myCommand = new MySqlCommand(sql); myCommand.CommandType = CommandType.Text; } Initializes a new instance of the class with the text of the query and a . The text of the query. A that represents the connection to an instance of SQL Server. When an instance of is created, the following read/write properties are set to initial values. Properties Initial Value cmdText 0 CommandType.Text connection You can change the value for any of these properties through a separate call to the property. The following example creates a and sets some of its properties. Public Sub CreateMySqlCommand() Dim conn as new MySqlConnection("server=myServer") Dim sql as String = "SELECT * FROM mytable" Dim myCommand As New MySqlCommand(sql, conn) myCommand.CommandType = CommandType.Text End Sub public void CreateMySqlCommand() { MySqlConnection conn = new MySqlConnection("server=myserver") string sql = "SELECT * FROM mytable"; MySqlCommand myCommand = new MySqlCommand(sql, conn); myCommand.CommandType = CommandType.Text; } Initializes a new instance of the class with the text of the query, a , and the . The text of the query. A that represents the connection to an instance of SQL Server. The in which the executes. When an instance of is created, the following read/write properties are set to initial values. Properties Initial Value cmdText 0 CommandType.Text connection You can change the value for any of these properties through a separate call to the property. The following example creates a and sets some of its properties. Public Sub CreateMySqlCommand() Dim conn as new MySqlConnection("server=myServer") conn.Open(); Dim txn as MySqlTransaction = conn.BeginTransaction() Dim sql as String = "SELECT * FROM mytable" Dim myCommand As New MySqlCommand(sql, conn, txn) myCommand.CommandType = CommandType.Text End Sub public void CreateMySqlCommand() { MySqlConnection conn = new MySqlConnection("server=myserver") conn.Open(); MySqlTransaction txn = conn.BeginTransaction(); string sql = "SELECT * FROM mytable"; MySqlCommand myCommand = new MySqlCommand(sql, conn, txn); myCommand.CommandType = CommandType.Text; } Executes a SQL statement against the connection and returns the number of rows affected. Number of rows affected You can use ExecuteNonQuery to perform any type of database operation, however any resultsets returned will not be available. Any output parameters used in calling a stored procedure will be populated with data and can be retrieved after execution is complete. For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1. The following example creates a MySqlCommand and then executes it using ExecuteNonQuery. The example is passed a string that is a SQL statement (such as UPDATE, INSERT, or DELETE) and a string to use to connect to the data source. Public Sub CreateMySqlCommand(myExecuteQuery As String, myConnection As MySqlConnection) Dim myCommand As New MySqlCommand(myExecuteQuery, myConnection) myCommand.Connection.Open() myCommand.ExecuteNonQuery() myConnection.Close() End Sub public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection) { MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection); myCommand.Connection.Open(); myCommand.ExecuteNonQuery(); myConnection.Close(); } Sends the to the Connection, and builds a using one of the values. One of the values. When the property is set to StoredProcedure, the property should be set to the name of the stored procedure. The command executes this stored procedure when you call ExecuteReader. The supports a special mode that enables large binary values to be read efficiently. For more information, see the SequentialAccess setting for . While the is in use, the associated is busy serving the MySqlDataReader. While in this state, no other operations can be performed on the MySqlConnection other than closing it. This is the case until the method of the MySqlDataReader is called. If the MySqlDataReader is created with CommandBehavior set to CloseConnection, closing the MySqlDataReader closes the connection automatically. When calling ExecuteReader with the SingleRow behavior, you should be aware that using a limit clause in your SQL will cause all rows (up to the limit given) to be retrieved by the client. The method will still return false after the first row but pulling all rows of data into the client will have a performance impact. If the limit clause is not necessary, it should be avoided. A object. Sends the to the Connection and builds a . A object. When the property is set to StoredProcedure, the property should be set to the name of the stored procedure. The command executes this stored procedure when you call ExecuteReader. While the is in use, the associated is busy serving the MySqlDataReader. While in this state, no other operations can be performed on the MySqlConnection other than closing it. This is the case until the method of the MySqlDataReader is called. The following example creates a , then executes it by passing a string that is a SQL SELECT statement, and a string to use to connect to the data source. Public Sub CreateMySqlDataReader(mySelectQuery As String, myConnection As MySqlConnection) Dim myCommand As New MySqlCommand(mySelectQuery, myConnection) myConnection.Open() Dim myReader As MySqlDataReader myReader = myCommand.ExecuteReader() Try While myReader.Read() Console.WriteLine(myReader.GetString(0)) End While Finally myReader.Close myConnection.Close End Try End Sub public void CreateMySqlDataReader(string mySelectQuery, MySqlConnection myConnection) { MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection); myConnection.Open(); MMySqlDataReader myReader; myReader = myCommand.ExecuteReader(); try { while(myReader.Read()) { Console.WriteLine(myReader.GetString(0)); } } finally { myReader.Close(); myConnection.Close(); } } Creates a prepared version of the command on an instance of MySQL Server. Prepared statements are only supported on MySQL version 4.1 and higher. Calling prepare while connected to earlier versions of MySQL will succeed but will execute the statement in the same way as unprepared. The following example demonstrates the use of the Prepare method. public sub PrepareExample() Dim cmd as New MySqlCommand("INSERT INTO mytable VALUES (@val)", myConnection) cmd.Parameters.Add( "@val", 10 ) cmd.Prepare() cmd.ExecuteNonQuery() cmd.Parameters(0).Value = 20 cmd.ExecuteNonQuery() end sub private void PrepareExample() { MySqlCommand cmd = new MySqlCommand("INSERT INTO mytable VALUES (@val)", myConnection); cmd.Parameters.Add( "@val", 10 ); cmd.Prepare(); cmd.ExecuteNonQuery(); cmd.Parameters[0].Value = 20; cmd.ExecuteNonQuery(); } Executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored. The first column of the first row in the result set, or a null reference if the result set is empty Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the method, and then performing the operations necessary to generate the single value using the data returned by a The following example creates a and then executes it using ExecuteScalar. The example is passed a string that is a SQL statement that returns an aggregate result, and a string to use to connect to the data source. Public Sub CreateMySqlCommand(myScalarQuery As String, myConnection As MySqlConnection) Dim myCommand As New MySqlCommand(myScalarQuery, myConnection) myCommand.Connection.Open() myCommand.ExecuteScalar() myConnection.Close() End Sub public void CreateMySqlCommand(string myScalarQuery, MySqlConnection myConnection) { MySqlCommand myCommand = new MySqlCommand(myScalarQuery, myConnection); myCommand.Connection.Open(); myCommand.ExecuteScalar(); myConnection.Close(); } public: void CreateMySqlCommand(String* myScalarQuery, MySqlConnection* myConnection) { MySqlCommand* myCommand = new MySqlCommand(myScalarQuery, myConnection); myCommand->Connection->Open(); myCommand->ExecuteScalar(); myConnection->Close(); } Gets or sets the SQL statement to execute at the data source. The SQL statement or stored procedure to execute. The default is an empty string. When the property is set to StoredProcedure, the CommandText property should be set to the name of the stored procedure. The user may be required to use escape character syntax if the stored procedure name contains any special characters. The command executes this stored procedure when you call one of the Execute methods. Starting with Connector/Net 5.0, having both a stored function and stored procedure with the same name in the same database is not supported. It is suggested that you provide unqiue names for your stored routines. The following example creates a and sets some of its properties. Public Sub CreateMySqlCommand() Dim myCommand As New MySqlCommand() myCommand.CommandText = "SELECT * FROM Mytable ORDER BY id" myCommand.CommandType = CommandType.Text End Sub public void CreateMySqlCommand() { MySqlCommand myCommand = new MySqlCommand(); myCommand.CommandText = "SELECT * FROM mytable ORDER BY id"; myCommand.CommandType = CommandType.Text; } Gets or sets the wait time before terminating the attempt to execute a command and generating an error. The time (in seconds) to wait for the command to execute. The default is 30 seconds. CommandTimeout is dependent on the ability of MySQL to cancel an executing query. Because of this, CommandTimeout is only supported when connected to MySQL version 5.0.0 or higher. Gets or sets a value indicating how the property is to be interpreted. One of the values. The default is Text. When you set the CommandType property to StoredProcedure, you should set the property to the name of the stored procedure. The command executes this stored procedure when you call one of the Execute methods. The following example creates a and sets some of its properties. Public Sub CreateMySqlCommand() Dim myCommand As New MySqlCommand() myCommand.CommandType = CommandType.Text End Sub public void CreateMySqlCommand() { MySqlCommand myCommand = new MySqlCommand(); myCommand.CommandType = CommandType.Text; } Gets or sets the used by this instance of the . The connection to a data source. The default value is a null reference (Nothing in Visual Basic). If you set Connection while a transaction is in progress and the property is not null, an is generated. If the Transaction property is not null and the transaction has already been committed or rolled back, Transaction is set to null. The following example creates a and sets some of its properties. Public Sub CreateMySqlCommand() Dim mySelectQuery As String = "SELECT * FROM mytable ORDER BY id" Dim myConnectString As String = "Persist Security Info=False;database=test;server=myServer" Dim myCommand As New MySqlCommand(mySelectQuery) myCommand.Connection = New MySqlConnection(myConnectString) myCommand.CommandType = CommandType.Text End Sub public void CreateMySqlCommand() { string mySelectQuery = "SELECT * FROM mytable ORDER BY id"; string myConnectString = "Persist Security Info=False;database=test;server=myServer"; MySqlCommand myCommand = new MySqlCommand(mySelectQuery); myCommand.Connection = new MySqlConnection(myConnectString); myCommand.CommandType = CommandType.Text; } Provides the id of the last inserted row. Id of the last inserted row. -1 if none exists. An important point to remember is that this property can be used in batch SQL scenarios but it's important to remember that it will only reflect the insert id from the last insert statement in the batch. This property can also be used when the batch includes select statements and ExecuteReader is used. This property can be consulted during result set processing. Get the The parameters of the SQL statement or stored procedure. The default is an empty collection. Connector/Net does not support unnamed parameters. Every parameter added to the collection must have an associated name. The following example creates a and displays its parameters. To accomplish this, the method is passed a , a query string that is a SQL SELECT statement, and an array of objects. Public Sub CreateMySqlCommand(myConnection As MySqlConnection, _ mySelectQuery As String, myParamArray() As MySqlParameter) Dim myCommand As New MySqlCommand(mySelectQuery, myConnection) myCommand.CommandText = "SELECT id, name FROM mytable WHERE age=@age" myCommand.UpdatedRowSource = UpdateRowSource.Both myCommand.Parameters.Add(myParamArray) Dim j As Integer For j = 0 To myCommand.Parameters.Count - 1 myCommand.Parameters.Add(myParamArray(j)) Next j Dim myMessage As String = "" Dim i As Integer For i = 0 To myCommand.Parameters.Count - 1 myMessage += myCommand.Parameters(i).ToString() & ControlChars.Cr Next i Console.WriteLine(myMessage) End Sub public void CreateMySqlCommand(MySqlConnection myConnection, string mySelectQuery, MySqlParameter[] myParamArray) { MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection); myCommand.CommandText = "SELECT id, name FROM mytable WHERE age=@age"; myCommand.Parameters.Add(myParamArray); for (int j=0; j<myParamArray.Length; j++) { myCommand.Parameters.Add(myParamArray[j]) ; } string myMessage = ""; for (int i = 0; i < myCommand.Parameters.Count; i++) { myMessage += myCommand.Parameters[i].ToString() + "\n"; } MessageBox.Show(myMessage); } Gets or sets the within which the executes. The . The default value is a null reference (Nothing in Visual Basic). You cannot set the Transaction property if it is already set to a specific value, and the command is in the process of executing. If you set the transaction property to a object that is not connected to the same as the object, an exception will be thrown the next time you attempt to execute a statement. Gets or sets how command results are applied to the when used by the method of the . One of the values. The default value is Both unless the command is automatically generated (as in the case of the ), in which case the default is None. mysql-connector-net-6.4.3/Source/MySql.Data/docs/MySqlDataAdapter.xml0000644000175000017500000010451511127003600026150 0ustar directhexdirecthex Represents a set of data commands and a database connection that are used to fill a dataset and update a MySQL database. This class cannot be inherited. The MySQLDataAdapter, serves as a bridge between a and MySQL for retrieving and saving data. The MySQLDataAdapter provides this bridge by mapping , which changes the data in the DataSet to match the data in the data source, and , which changes the data in the data source to match the data in the DataSet, using the appropriate SQL statements against the data source. When the MySQLDataAdapter fills a DataSet, it will create the necessary tables and columns for the returned data if they do not already exist. However, primary key information will not be included in the implicitly created schema unless the property is set to . You may also have the MySQLDataAdapter create the schema of the DataSet, including primary key information, before filling it with data using . MySQLDataAdapter is used in conjunction with and to increase performance when connecting to a MySQL database. The MySQLDataAdapter also includes the , , , , and properties to facilitate the loading and updating of data. When an instance of MySQLDataAdapter is created, the read/write properties are set to initial values. For a list of these values, see the MySQLDataAdapter constructor. Please be aware that the class allows only Int16, Int32, and Int64 to have the AutoIncrement property set. If you plan to use autoincremement columns with MySQL, you should consider using signed integer columns. The following example creates a and a . The MySqlConnection is opened and set as the for the MySqlCommand. The example then calls , and closes the connection. To accomplish this, the ExecuteNonQuery is passed a connection string and a query string that is a SQL INSERT statement. Public Function SelectRows(dataSet As DataSet, connection As String, query As String) As DataSet Dim conn As New MySqlConnection(connection) Dim adapter As New MySqlDataAdapter() adapter.SelectCommand = new MySqlCommand(query, conn) adapter.Fill(dataset) Return dataset End Function public DataSet SelectRows(DataSet dataset,string connection,string query) { MySqlConnection conn = new MySqlConnection(connection); MySqlDataAdapter adapter = new MySqlDataAdapter(); adapter.SelectCommand = new MySqlCommand(query, conn); adapter.Fill(dataset); return dataset; } Initializes a new instance of the MySqlDataAdapter class. When an instance of is created, the following read/write properties are set to the following initial values. Properties Initial Value MissingMappingAction.Passthrough MissingSchemaAction.Add You can change the value of any of these properties through a separate call to the property. The following example creates a and sets some of its properties. Public Sub CreateSqlDataAdapter() Dim conn As MySqlConnection = New MySqlConnection("Data Source=localhost;" & _ "database=test") Dim da As MySqlDataAdapter = New MySqlDataAdapter da.MissingSchemaAction = MissingSchemaAction.AddWithKey da.SelectCommand = New MySqlCommand("SELECT id, name FROM mytable", conn) da.InsertCommand = New MySqlCommand("INSERT INTO mytable (id, name) " & _ "VALUES (@id, @name)", conn) da.UpdateCommand = New MySqlCommand("UPDATE mytable SET id=@id, name=@name " & _ "WHERE id=@oldId", conn) da.DeleteCommand = New MySqlCommand("DELETE FROM mytable WHERE id=@id", conn) da.InsertCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id") da.InsertCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name") da.UpdateCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id") da.UpdateCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name") da.UpdateCommand.Parameters.Add("@oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original da.DeleteCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original End Sub public static void CreateSqlDataAdapter() { MySqlConnection conn = new MySqlConnection("Data Source=localhost;database=test"); MySqlDataAdapter da = new MySqlDataAdapter(); da.MissingSchemaAction = MissingSchemaAction.AddWithKey; da.SelectCommand = new MySqlCommand("SELECT id, name FROM mytable", conn); da.InsertCommand = new MySqlCommand("INSERT INTO mytable (id, name) " + "VALUES (@id, @name)", conn); da.UpdateCommand = new MySqlCommand("UPDATE mytable SET id=@id, name=@name " + "WHERE id=@oldId", conn); da.DeleteCommand = new MySqlCommand("DELETE FROM mytable WHERE id=@id", conn); da.InsertCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id"); da.InsertCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name"); da.UpdateCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id"); da.UpdateCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name"); da.UpdateCommand.Parameters.Add("@oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original; da.DeleteCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original; } Initializes a new instance of the class with the specified as the property. that is a SQL SELECT statement or stored procedure and is set as the property of the . When an instance of is created, the following read/write properties are set to the following initial values. Properties Initial Value MissingMappingAction.Passthrough MissingSchemaAction.Add You can change the value of any of these properties through a separate call to the property. When SelectCommand (or any of the other command properties) is assigned to a previously created , the MySqlCommand is not cloned. The SelectCommand maintains a reference to the previously created MySqlCommand object. The following example creates a and sets some of its properties. Public Sub CreateSqlDataAdapter() Dim conn As MySqlConnection = New MySqlConnection("Data Source=localhost;" & _ "database=test") Dim cmd as new MySqlCommand("SELECT id, name FROM mytable", conn) Dim da As MySqlDataAdapter = New MySqlDataAdapter(cmd) da.MissingSchemaAction = MissingSchemaAction.AddWithKey da.InsertCommand = New MySqlCommand("INSERT INTO mytable (id, name) " & _ "VALUES (@id, @name)", conn) da.UpdateCommand = New MySqlCommand("UPDATE mytable SET id=@id, name=@name " & _ "WHERE id=@oldId", conn) da.DeleteCommand = New MySqlCommand("DELETE FROM mytable WHERE id=@id", conn) da.InsertCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id") da.InsertCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name") da.UpdateCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id") da.UpdateCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name") da.UpdateCommand.Parameters.Add("@oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original da.DeleteCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original End Sub public static void CreateSqlDataAdapter() { MySqlConnection conn = new MySqlConnection("Data Source=localhost;database=test"); MySqlCommand cmd = new MySqlCommand("SELECT id, name FROM mytable", conn); MySqlDataAdapter da = new MySqlDataAdapter(cmd); da.MissingSchemaAction = MissingSchemaAction.AddWithKey; da.InsertCommand = new MySqlCommand("INSERT INTO mytable (id, name) " + "VALUES (@id, @name)", conn); da.UpdateCommand = new MySqlCommand("UPDATE mytable SET id=@id, name=@name " + "WHERE id=@oldId", conn); da.DeleteCommand = new MySqlCommand("DELETE FROM mytable WHERE id=@id", conn); da.InsertCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id"); da.InsertCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name"); da.UpdateCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id"); da.UpdateCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name"); da.UpdateCommand.Parameters.Add("@oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original; da.DeleteCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original; } Initializes a new instance of the class with a and a object. A String that is a SQL SELECT statement or stored procedure to be used by the property of the . A that represents the connection. This implementation of the opens and closes a if it is not already open. This can be useful in a an application that must call the method for two or more MySqlDataAdapter objects. If the MySqlConnection is already open, you must explicitly call or to close it. When an instance of is created, the following read/write properties are set to the following initial values. Properties Initial Value MissingMappingAction.Passthrough MissingSchemaAction.Add You can change the value of any of these properties through a separate call to the property. The following example creates a and sets some of its properties. Public Sub CreateSqlDataAdapter() Dim conn As MySqlConnection = New MySqlConnection("Data Source=localhost;" & _ "database=test") Dim da As MySqlDataAdapter = New MySqlDataAdapter("SELECT id, name FROM mytable", conn) da.MissingSchemaAction = MissingSchemaAction.AddWithKey da.InsertCommand = New MySqlCommand("INSERT INTO mytable (id, name) " & _ "VALUES (@id, @name)", conn) da.UpdateCommand = New MySqlCommand("UPDATE mytable SET id=@id, name=@name " & _ "WHERE id=@oldId", conn) da.DeleteCommand = New MySqlCommand("DELETE FROM mytable WHERE id=@id", conn) da.InsertCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id") da.InsertCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name") da.UpdateCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id") da.UpdateCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name") da.UpdateCommand.Parameters.Add("@oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original da.DeleteCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original End Sub public static void CreateSqlDataAdapter() { MySqlConnection conn = new MySqlConnection("Data Source=localhost;database=test"); MySqlDataAdapter da = new MySqlDataAdapter("SELECT id, name FROM mytable", conn); da.MissingSchemaAction = MissingSchemaAction.AddWithKey; da.InsertCommand = new MySqlCommand("INSERT INTO mytable (id, name) " + "VALUES (@id, @name)", conn); da.UpdateCommand = new MySqlCommand("UPDATE mytable SET id=@id, name=@name " + "WHERE id=@oldId", conn); da.DeleteCommand = new MySqlCommand("DELETE FROM mytable WHERE id=@id", conn); da.InsertCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id"); da.InsertCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name"); da.UpdateCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id"); da.UpdateCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name"); da.UpdateCommand.Parameters.Add("@oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original; da.DeleteCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original; } Initializes a new instance of the class with a and a connection string. A that is a SQL SELECT statement or stored procedure to be used by the property of the . The connection string When an instance of is created, the following read/write properties are set to the following initial values. Properties Initial Value MissingMappingAction.Passthrough MissingSchemaAction.Add You can change the value of any of these properties through a separate call to the property. The following example creates a and sets some of its properties. Public Sub CreateSqlDataAdapter() Dim da As MySqlDataAdapter = New MySqlDataAdapter("SELECT id, name FROM mytable", "Data Source=localhost;database=test") Dim conn As MySqlConnection = da.SelectCommand.Connection da.MissingSchemaAction = MissingSchemaAction.AddWithKey da.InsertCommand = New MySqlCommand("INSERT INTO mytable (id, name) " & _ "VALUES (@id, @name)", conn) da.UpdateCommand = New MySqlCommand("UPDATE mytable SET id=@id, name=@name " & _ "WHERE id=@oldId", conn) da.DeleteCommand = New MySqlCommand("DELETE FROM mytable WHERE id=@id", conn) da.InsertCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id") da.InsertCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name") da.UpdateCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id") da.UpdateCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name") da.UpdateCommand.Parameters.Add("@oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original da.DeleteCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original End Sub public static void CreateSqlDataAdapter() { MySqlDataAdapter da = new MySqlDataAdapter("SELECT id, name FROM mytable", "Data Source=localhost;database=test"); MySqlConnection conn = da.SelectCommand.Connection; da.MissingSchemaAction = MissingSchemaAction.AddWithKey; da.InsertCommand = new MySqlCommand("INSERT INTO mytable (id, name) " + "VALUES (@id, @name)", conn); da.UpdateCommand = new MySqlCommand("UPDATE mytable SET id=@id, name=@name " + "WHERE id=@oldId", conn); da.DeleteCommand = new MySqlCommand("DELETE FROM mytable WHERE id=@id", conn); da.InsertCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id"); da.InsertCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name"); da.UpdateCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id"); da.UpdateCommand.Parameters.Add("@name", MySqlDbType.VarChar, 40, "name"); da.UpdateCommand.Parameters.Add("@oldId", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original; da.DeleteCommand.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id").SourceVersion = DataRowVersion.Original; } Gets or sets a SQL statement or stored procedure used to delete records from the data set. A used during to delete records in the database that correspond to deleted rows in the . During , if this property is not set and primary key information is present in the , the DeleteCommand can be generated automatically if you set the property and use the . Then, any additional commands that you do not set are generated by the MySqlCommandBuilder. This generation logic requires key column information to be present in the DataSet. When DeleteCommand is assigned to a previously created , the MySqlCommand is not cloned. The DeleteCommand maintains a reference to the previously created MySqlCommand object. The following example creates a and sets the and DeleteCommand properties. It assumes you have already created a object. Public Shared Function CreateCustomerAdapter(conn As MySqlConnection) As MySqlDataAdapter Dim da As MySqlDataAdapter = New MySqlDataAdapter() Dim cmd As MySqlCommand Dim parm As MySqlParameter ' Create the SelectCommand. cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn) cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15) cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15) da.SelectCommand = cmd ' Create the DeleteCommand. cmd = New MySqlCommand("DELETE FROM mytable WHERE id=@id", conn) parm = cmd.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id") parm.SourceVersion = DataRowVersion.Original da.DeleteCommand = cmd Return da End Function public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn) { MySqlDataAdapter da = new MySqlDataAdapter(); MySqlCommand cmd; MySqlParameter parm; // Create the SelectCommand. cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn); cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15); cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15); da.SelectCommand = cmd; // Create the DeleteCommand. cmd = new MySqlCommand("DELETE FROM mytable WHERE id=@id", conn); parm = cmd.Parameters.Add("@id", MySqlDbType.VarChar, 5, "id"); parm.SourceVersion = DataRowVersion.Original; da.DeleteCommand = cmd; return da; } Gets or sets a SQL statement or stored procedure used to insert records into the data set. A used during to insert records into the database that correspond to new rows in the . During , if this property is not set and primary key information is present in the , the InsertCommand can be generated automatically if you set the property and use the . Then, any additional commands that you do not set are generated by the MySqlCommandBuilder. This generation logic requires key column information to be present in the DataSet. When InsertCommand is assigned to a previously created , the MySqlCommand is not cloned. The InsertCommand maintains a reference to the previously created MySqlCommand object. If execution of this command returns rows, these rows may be added to the DataSet depending on how you set the property of the MySqlCommand object. The following example creates a and sets the and InsertCommand properties. It assumes you have already created a object. Public Shared Function CreateCustomerAdapter(conn As MySqlConnection) As MySqlDataAdapter Dim da As MySqlDataAdapter = New MySqlDataAdapter() Dim cmd As MySqlCommand Dim parm As MySqlParameter ' Create the SelectCommand. cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn) cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15) cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15) da.SelectCommand = cmd ' Create the InsertCommand. cmd = New MySqlCommand("INSERT INTO mytable (id,name) VALUES (@id, @name)", conn) cmd.Parameters.Add( "@id", MySqlDbType.VarChar, 15, "id" ) cmd.Parameters.Add( "@name", MySqlDbType.VarChar, 15, "name" ) da.InsertCommand = cmd Return da End Function public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn) { MySqlDataAdapter da = new MySqlDataAdapter(); MySqlCommand cmd; MySqlParameter parm; // Create the SelectCommand. cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn); cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15); cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15); da.SelectCommand = cmd; // Create the InsertCommand. cmd = new MySqlCommand("INSERT INTO mytable (id,name) VALUES (@id,@name)", conn); cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15, "id" ); cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15, "name" ); da.InsertCommand = cmd; return da; } Gets or sets a SQL statement or stored procedure used to updated records in the data source. A used during to update records in the database with data from the . During , if this property is not set and primary key information is present in the , the UpdateCommand can be generated automatically if you set the property and use the . Then, any additional commands that you do not set are generated by the MySqlCommandBuilder. This generation logic requires key column information to be present in the DataSet. When UpdateCommand is assigned to a previously created , the MySqlCommand is not cloned. The UpdateCommand maintains a reference to the previously created MySqlCommand object. If execution of this command returns rows, these rows may be merged with the DataSet depending on how you set the property of the MySqlCommand object. The following example creates a and sets the and UpdateCommand properties. It assumes you have already created a object. Public Shared Function CreateCustomerAdapter(conn As MySqlConnection) As MySqlDataAdapter Dim da As MySqlDataAdapter = New MySqlDataAdapter() Dim cmd As MySqlCommand Dim parm As MySqlParameter ' Create the SelectCommand. cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn) cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15) cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15) da.SelectCommand = cmd ' Create the UpdateCommand. cmd = New MySqlCommand("UPDATE mytable SET id=@id, name=@name WHERE id=@oldId", conn) cmd.Parameters.Add( "@id", MySqlDbType.VarChar, 15, "id" ) cmd.Parameters.Add( "@name", MySqlDbType.VarChar, 15, "name" ) parm = cmd.Parameters.Add("@oldId", MySqlDbType.VarChar, 15, "id") parm.SourceVersion = DataRowVersion.Original da.UpdateCommand = cmd Return da End Function public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn) { MySqlDataAdapter da = new MySqlDataAdapter(); MySqlCommand cmd; MySqlParameter parm; // Create the SelectCommand. cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn); cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15); cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15); da.SelectCommand = cmd; // Create the UpdateCommand. cmd = new MySqlCommand("UPDATE mytable SET id=@id, name=@name WHERE id=@oldId", conn); cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15, "id" ); cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15, "name" ); parm = cmd.Parameters.Add( "@oldId", MySqlDbType.VarChar, 15, "id" ); parm.SourceVersion = DataRowVersion.Original; da.UpdateCommand = cmd; return da; } Gets or sets a SQL statement or stored procedure used to select records in the data source. A used during to select records from the database for placement in the . When SelectCommand is assigned to a previously created , the MySqlCommand is not cloned. The SelectCommand maintains a reference to the previously created MySqlCommand object. If the SelectCommand does not return any rows, no tables are added to the , and no exception is raised. The following example creates a and sets the and InsertCommand properties. It assumes you have already created a object. Public Shared Function CreateCustomerAdapter(conn As MySqlConnection) As MySqlDataAdapter Dim da As MySqlDataAdapter = New MySqlDataAdapter() Dim cmd As MySqlCommand Dim parm As MySqlParameter ' Create the SelectCommand. cmd = New MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn) cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15) cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15) da.SelectCommand = cmd ' Create the InsertCommand. cmd = New MySqlCommand("INSERT INTO mytable (id,name) VALUES (@id, @name)", conn) cmd.Parameters.Add( "@id", MySqlDbType.VarChar, 15, "id" ) cmd.Parameters.Add( "@name", MySqlDbType.VarChar, 15, "name" ) da.InsertCommand = cmd Return da End Function public static MySqlDataAdapter CreateCustomerAdapter(MySqlConnection conn) { MySqlDataAdapter da = new MySqlDataAdapter(); MySqlCommand cmd; MySqlParameter parm; // Create the SelectCommand. cmd = new MySqlCommand("SELECT * FROM mytable WHERE id=@id AND name=@name", conn); cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15); cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15); da.SelectCommand = cmd; // Create the InsertCommand. cmd = new MySqlCommand("INSERT INTO mytable (id,name) VALUES (@id,@name)", conn); cmd.Parameters.Add("@id", MySqlDbType.VarChar, 15, "id" ); cmd.Parameters.Add("@name", MySqlDbType.VarChar, 15, "name" ); da.InsertCommand = cmd; return da; } mysql-connector-net-6.4.3/Source/MySql.Data/docs/MySqlDataReader.xml0000644000175000017500000004300611127003600025767 0ustar directhexdirecthex Provides a means of reading a forward-only stream of rows from a MySQL database. This class cannot be inherited. To create a MySQLDataReader, you must call the method of the object, rather than directly using a constructor. While the MySqlDataReader is in use, the associated is busy serving the MySqlDataReader, and no other operations can be performed on the MySqlConnection other than closing it. This is the case until the method of the MySqlDataReader is called. and are the only properties that you can call after the MySqlDataReader is closed. Though the RecordsAffected property may be accessed at any time while the MySqlDataReader exists, always call Close before returning the value of RecordsAffected to ensure an accurate return value. For optimal performance, MySqlDataReader avoids creating unnecessary objects or making unnecessary copies of data. As a result, multiple calls to methods such as return a reference to the same object. Use caution if you are modifying the underlying value of the objects returned by methods such as GetValue. The following example creates a , a , and a MySqlDataReader. The example reads through the data, writing it out to the console. Finally, the example closes the MySqlDataReader, then the MySqlConnection. Public Sub ReadMyData(myConnString As String) Dim mySelectQuery As String = "SELECT OrderID, CustomerID FROM Orders" Dim myConnection As New MySqlConnection(myConnString) Dim myCommand As New MySqlCommand(mySelectQuery, myConnection) myConnection.Open() Dim myReader As MySqlDataReader myReader = myCommand.ExecuteReader() ' Always call Read before accessing data. While myReader.Read() Console.WriteLine((myReader.GetInt32(0) & ", " & myReader.GetString(1))) End While ' always call Close when done reading. myReader.Close() ' Close the connection when done with it. myConnection.Close() End Sub 'ReadMyData public void ReadMyData(string myConnString) { string mySelectQuery = "SELECT OrderID, CustomerID FROM Orders"; MySqlConnection myConnection = new MySqlConnection(myConnString); MySqlCommand myCommand = new MySqlCommand(mySelectQuery,myConnection); myConnection.Open(); MySqlDataReader myReader; myReader = myCommand.ExecuteReader(); // Always call Read before accessing data. while (myReader.Read()) { Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(1)); } // always call Close when done reading. myReader.Close(); // Close the connection when done with it. myConnection.Close(); } GetBytes returns the number of available bytes in the field. In most cases this is the exact length of the field. However, the number returned may be less than the true length of the field if GetBytes has already been used to obtain bytes from the field. This may be the case, for example, if the is reading a large data structure into a buffer. For more information, see the SequentialAccess setting for . If you pass a buffer that is a null reference (Nothing in Visual Basic), GetBytes returns the length of the field in bytes. No conversions are performed; therefore the data retrieved must already be a byte array. Gets the value of the specified column as a object. No conversions are performed; therefore, the data retrieved must already be a Time value. Call IsDBNull to check for null values before calling this method. The zero-based column ordinal or column name. The value of the specified column. Gets the value of the specified column as a object. No conversions are performed; therefore, the data retrieved must already be a DateTime object. Call IsDBNull to check for null values before calling this method. MySql allows date columns to contain the value '0000-00-00' and datetime columns to contain the value '0000-00-00 00:00:00'. The DateTime structure cannot contain or represent these values. To read a datetime value from a column that might contain zero values, use . The behavior of reading a zero datetime column using this method is defined by the ZeroDateTimeBehavior connection string option. For more information on this option, please refer to . The zero-based column ordinal. The value of the specified column. Gets the value of the specified column as a object. No conversions are performed; therefore, the data retrieved must already be a DateTime object. Call IsDBNull to check for null values before calling this method. MySql allows date columns to contain the value '0000-00-00' and datetime columns to contain the value '0000-00-00 00:00:00'. The DateTime structure cannot contain or represent these values. To read a datetime value from a column that might contain zero values, use . The behavior of reading a zero datetime column using this method is defined by the ZeroDateTimeBehavior connection string option. For more information on this option, please refer to . The column name. The value of the specified column. Gets the value of the specified column as a object. No conversions are performed; therefore, the data retrieved must already be a DateTime object. Call IsDBNull to check for null values before calling this method. The zero-based column ordinal or column name. The value of the specified column. Gets the value of the specified column as a object. No conversions are performed; therefore, the data retrieved must already be a String object. Call IsDBNull to check for null values before calling this method. The zero-based column ordinal. The value of the specified column. Gets the value of the specified column as a object. No conversions are performed; therefore, the data retrieved must already be a String object. Call IsDBNull to check for null values before calling this method. The column name. The value of the specified column. Gets the value of the specified column as a object. No conversions are performed; therefore, the data retrieved must already be a Decimal object. Call IsDBNull to check for null values before calling this method. The zero-based column ordinal The value of the specified column. Gets the value of the specified column as a object. No conversions are performed; therefore, the data retrieved must already be a Decimal object. Call IsDBNull to check for null values before calling this method. The column name The value of the specified column. Gets the value of the specified column as a double-precision floating point number. No conversions are performed; therefore, the data retrieved must already be a Double object. Call IsDBNull to check for null values before calling this method. The zero-based column ordinal. The value of the specified column. Gets the value of the specified column as a double-precision floating point number. No conversions are performed; therefore, the data retrieved must already be a Double object. Call IsDBNull to check for null values before calling this method. The column name The value of the specified column. Gets the value of the specified column as a single-precision floating point number. No conversions are performed; therefore, the data retrieved must already be a Float object. Call IsDBNull to check for null values before calling this method. The zero-based column ordinal. The value of the specified column. Gets the value of the specified column as a single-precision floating point number. No conversions are performed; therefore, the data retrieved must already be a Float object. Call IsDBNull to check for null values before calling this method. The column name The value of the specified column. Gets the value of the specified column as a globally-unique identifier (GUID). The zero-based column ordinal. The value of the specified column. Gets the value of the specified column as a globally-unique identifier (GUID). The column name The value of the specified column. Gets the value of the specified column as a 16-bit signed integer. No conversions are performed; therefore, the data retrieved must already be a 16 bit integer value. Call IsDBNull to check for null values before calling this method. The zero-based column ordinal. The value of the specified column. Gets the value of the specified column as a 16-bit signed integer. No conversions are performed; threfore, the data retrieved must already be a 16 bit integer value. Call IsDBNull to check for null values before calling this method. The column name The value of the specified column. Gets the value of the specified column as a 32-bit signed integer. No conversions are performed; therefore, the data retrieved must already be a 32 bit integer value. Call IsDBNull to check for null values before calling this method. The zero-based column ordinal. The value of the specified column. Gets the value of the specified column as a 32-bit signed integer. No conversions are performed; therefore, the data retrieved must already be a 32 bit integer value. Call IsDBNull to check for null values before calling this method. The column name. The value of the specified column. Gets the value of the specified column as a 64-bit signed integer. No conversions are performed; therefore, the data retrieved must already be a 64 bit integer value. Call IsDBNull to check for null values before calling this method. The zero-based column ordinal. The value of the specified column. Gets the value of the specified column as a 64-bit signed integer. No conversions are performed; therefore, the data retrieved must already be a 64 bit integer value. Call IsDBNull to check for null values before calling this method. The column name. The value of the specified column. Gets the value of the specified column as a 16-bit unsigned integer. No conversions are performed; therefore, the data retrieved must already be a 16 bit unsigned integer value. Call IsDBNull to check for null values before calling this method. The zero-based column ordinal or column name. The value of the specified column. Gets the value of the specified column as a 32-bit unsigned integer. No conversions are performed; therefore, the data retrieved must already be a 32 bit unsigned integer value. Call IsDBNull to check for null values before calling this method. The zero-based column ordinal or column name. The value of the specified column. Gets the value of the specified column as a 64-bit unsigned integer. No conversions are performed; therefore, the data retrieved must already be a 64 bit unsigned integer value. Call IsDBNull to check for null values before calling this method. The zero-based column ordinal or column name. The value of the specified column. mysql-connector-net-6.4.3/Source/MySql.Data/docs/MySqlCommandBuilder.xml0000644000175000017500000003315511127003600026664 0ustar directhexdirecthex Automatically generates single-table commands used to reconcile changes made to a DataSet with the associated MySQL database. This class cannot be inherited. The does not automatically generate the SQL statements required to reconcile changes made to a DataSet with the associated instance of MySQL. However, you can create a MySqlCommandBuilder object to automatically generate SQL statements for single-table updates if you set the SelectCommand property of the MySqlDataAdapter. Then, any additional SQL statements that you do not set are generated by the MySqlCommandBuilder. The MySqlCommandBuilder registers itself as a listener for RowUpdating events whenever you set the property. You can only associate one MySqlDataAdapter or MySqlCommandBuilder object with each other at one time. To generate INSERT, UPDATE, or DELETE statements, the MySqlCommandBuilder uses the SelectCommand property to retrieve a required set of metadata automatically. If you change the SelectCommand after the metadata has is retrieved (for example, after the first update), you should call the method to update the metadata. The SelectCommand must also return at least one primary key or unique column. If none are present, an InvalidOperation exception is generated, and the commands are not generated. The MySqlCommandBuilder also uses the Connection, CommandTimeout, and Transaction properties referenced by the SelectCommand. The user should call RefreshSchema if any of these properties are modified, or if the SelectCommand itself is replaced. Otherwise the InsertCommand, UpdateCommand, and DeleteCommand properties retain their previous values. If you call Dispose, the MySqlCommandBuilder is disassociated from the MySqlDataAdapter, and the generated commands are no longer used. Caution must be used when using MySqlCOmmandBuilder on MySql 4.0 systems. With MySql 4.0, database/schema information is not provided to the connector for a query. This means that a query that pulls columns from two identically named tables in two or more different databases will not cause an exception to be thrown but will not work correctly. Even more dangerous is the situation where your select statement references database X but is executed in database Y and both databases have tables with similar layouts. This situation can cause unwanted changes or deletes. This note does not apply to MySQL versions 4.1 and later. The following example uses the , along and , to select rows from a data source. The example is passed an initialized , a connection string, a query string that is a SQL SELECT statement, and a string that is the name of the database table. The example then creates a MySqlCommandBuilder. Public Shared Function SelectRows(myConnection As String, mySelectQuery As String, myTableName As String) As DataSet Dim myConn As New MySqlConnection(myConnection) Dim myDataAdapter As New MySqlDataAdapter() myDataAdapter.SelectCommand = New MySqlCommand(mySelectQuery, myConn) Dim cb As SqlCommandBuilder = New MySqlCommandBuilder(myDataAdapter) myConn.Open() Dim ds As DataSet = New DataSet myDataAdapter.Fill(ds, myTableName) ' Code to modify data in DataSet here ' Without the MySqlCommandBuilder this line would fail. myDataAdapter.Update(ds, myTableName) myConn.Close() End Function 'SelectRows public static DataSet SelectRows(string myConnection, string mySelectQuery, string myTableName) { MySqlConnection myConn = new MySqlConnection(myConnection); MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(); myDataAdapter.SelectCommand = new MySqlCommand(mySelectQuery, myConn); MySqlCommandBuilder cb = new MySqlCommandBuilder(myDataAdapter); myConn.Open(); DataSet ds = new DataSet(); myDataAdapter.Fill(ds, myTableName); //code to modify data in DataSet here //Without the MySqlCommandBuilder this line would fail myDataAdapter.Update(ds, myTableName); myConn.Close(); return ds; } Initializes a new instance of the class. Initializes a new instance of the class with the associated object. The to use. The registers itself as a listener for events that are generated by the specified in this property. When you create a new instance MySqlCommandBuilder, any existing MySqlCommandBuilder associated with this MySqlDataAdapter is released. Gets or sets a object for which SQL statements are automatically generated. A object. The registers itself as a listener for events that are generated by the specified in this property. When you create a new instance MySqlCommandBuilder, any existing MySqlCommandBuilder associated with this MySqlDataAdapter is released. Gets or sets the beginning character or characters to use when specifying MySQL database objects (for example, tables or columns) whose names contain characters such as spaces or reserved tokens. The beginning character or characters to use. The default value is `. Database objects in MySQL can contain special characters such as spaces that would make normal SQL strings impossible to correctly parse. Use of the QuotePrefix and the properties allows the to build SQL commands that handle this situation. Gets or sets the beginning character or characters to use when specifying MySQL database objects (for example, tables or columns) whose names contain characters such as spaces or reserved tokens. The beginning character or characters to use. The default value is `. Database objects in MySQL can contain special characters such as spaces that would make normal SQL strings impossible to correctly parse. Use of the and the QuoteSuffix properties allows the to build SQL commands that handle this situation. Gets the automatically generated object required to perform deletions on the database. The object generated to handle delete operations. An application can use the GetDeleteCommand method for informational or troubleshooting purposes because it returns the object to be executed. You can also use GetDeleteCommand as the basis of a modified command. For example, you might call GetDeleteCommand and modify the value, and then explicitly set that on the . After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the GetDeleteCommand will be still be using information from the previous statement, which might not be correct. The SQL statements are first generated either when the application calls or GetDeleteCommand. Gets the automatically generated object required to perform insertions on the database. The object generated to handle insert operations. An application can use the GetInsertCommand method for informational or troubleshooting purposes because it returns the object to be executed. You can also use the GetInsertCommand as the basis of a modified command. For example, you might call GetInsertCommand and modify the value, and then explicitly set that on the . After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the GetInsertCommand will be still be using information from the previous statement, which might not be correct. The SQL statements are first generated either when the application calls or GetInsertCommand. Gets the automatically generated object required to perform updates on the database. The object generated to handle update operations. An application can use the GetUpdateCommand method for informational or troubleshooting purposes because it returns the object to be executed. You can also use GetUpdateCommand as the basis of a modified command. For example, you might call GetUpdateCommand and modify the value, and then explicitly set that on the . After the SQL statement is first generated, the application must explicitly call if it changes the statement in any way. Otherwise, the GetUpdateCommand will be still be using information from the previous statement, which might not be correct. The SQL statements are first generated either when the application calls or GetUpdateCommand. Refreshes the database schema information used to generate INSERT, UPDATE, or DELETE statements. An application should call RefreshSchema whenever the SELECT statement associated with the changes. An application should call RefreshSchema whenever the value of the changes. mysql-connector-net-6.4.3/Source/MySql.Data/docs/MySqlException.xml0000644000175000017500000000315711127003600025734 0ustar directhexdirecthex This class is created whenever the MySql Data Provider encounters an error generated from the server. Any open connections are not automatically closed when an exception is thrown. If the client application determines that the exception is fatal, it should close any open objects or objects. The following example generates a MySqlException due to a missing server, and then displays the exception. Public Sub ShowException() Dim mySelectQuery As String = "SELECT column1 FROM table1" Dim myConnection As New MySqlConnection ("Data Source=localhost;Database=Sample;") Dim myCommand As New MySqlCommand(mySelectQuery, myConnection) Try myCommand.Connection.Open() Catch e As MySqlException MessageBox.Show( e.Message ) End Try End Sub public void ShowException() { string mySelectQuery = "SELECT column1 FROM table1"; MySqlConnection myConnection = new MySqlConnection("Data Source=localhost;Database=Sample;"); MySqlCommand myCommand = new MySqlCommand(mySelectQuery,myConnection); try { myCommand.Connection.Open(); } catch (MySqlException e) { MessageBox.Show( e.Message ); } } mysql-connector-net-6.4.3/Source/MySql.Data/docs/MySqlParameterCollection.xml0000644000175000017500000000314011127003600027722 0ustar directhexdirecthex The number of the parameters in the collection must be equal to the number of parameter placeholders within the command text, or an exception will be generated. The following example creates multiple instances of through the MySqlParameterCollection collection within the . These parameters are used to select data within the data source and place the data in the . This code assumes that a DataSet and a MySqlDataAdapter have already been created with the appropriate schema, commands, and connection. Public Sub AddParameters() ' ... ' create myDataSet and myDataAdapter ' ... myDataAdapter.SelectCommand.Parameters.Add("@CategoryName", MySqlDbType.VarChar, 80).Value = "toasters" myDataAdapter.SelectCommand.Parameters.Add("@SerialNum", MySqlDbType.Long).Value = 239 myDataAdapter.Fill(myDataSet) End Sub 'AddSqlParameters public void AddSqlParameters() { // ... // create myDataSet and myDataAdapter // ... myDataAdapter.SelectCommand.Parameters.Add("@CategoryName", MySqlDbType.VarChar, 80).Value = "toasters"; myDataAdapter.SelectCommand.Parameters.Add("@SerialNum", MySqlDbType.Long).Value = 239; myDataAdapter.Fill(myDataSet); } mysql-connector-net-6.4.3/Source/MySql.Data/docs/MySqlHelper.xml0000644000175000017500000000315711127003600025215 0ustar directhexdirecthex This class is created whenever the MySql Data Provider encounters an error generated from the server. Any open connections are not automatically closed when an exception is thrown. If the client application determines that the exception is fatal, it should close any open objects or objects. The following example generates a MySqlException due to a missing server, and then displays the exception. Public Sub ShowException() Dim mySelectQuery As String = "SELECT column1 FROM table1" Dim myConnection As New MySqlConnection ("Data Source=localhost;Database=Sample;") Dim myCommand As New MySqlCommand(mySelectQuery, myConnection) Try myCommand.Connection.Open() Catch e As MySqlException MessageBox.Show( e.Message ) End Try End Sub public void ShowException() { string mySelectQuery = "SELECT column1 FROM table1"; MySqlConnection myConnection = new MySqlConnection("Data Source=localhost;Database=Sample;"); MySqlCommand myCommand = new MySqlCommand(mySelectQuery,myConnection); try { myCommand.Connection.Open(); } catch (MySqlException e) { MessageBox.Show( e.Message ); } } mysql-connector-net-6.4.3/Source/MySql.Data/docs/MySqlParameter.xml0000644000175000017500000000273711127003600025721 0ustar directhexdirecthex Parameter names are not case sensitive. The following example creates multiple instances of MySqlParameter through the collection within the . These parameters are used to select data from the data source and place the data in the . This example assumes that a DataSet and a MySqlDataAdapter have already been created with the appropriate schema, commands, and connection. Public Sub AddSqlParameters() ' ... ' create myDataSet and myDataAdapter ' ... myDataAdapter.SelectCommand.Parameters.Add("@CategoryName", MySqlDbType.VarChar, 80).Value = "toasters" myDataAdapter.SelectCommand.Parameters.Add("@SerialNum", MySqlDbType.Long).Value = 239 myDataAdapter.Fill(myDataSet) End Sub 'AddSqlParameters public void AddSqlParameters() { // ... // create myDataSet and myDataAdapter // ... myDataAdapter.SelectCommand.Parameters.Add("@CategoryName", MySqlDbType.VarChar, 80).Value = "toasters"; myDataAdapter.SelectCommand.Parameters.Add("@SerialNum", MySqlDbType.Long).Value = 239; myDataAdapter.Fill(myDataSet); } mysql-connector-net-6.4.3/Source/MySql.Data/MySqlHelper.cs0000644000175000017500000004661211127003600024075 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Data; using MySql.Data.MySqlClient; using System.Text; namespace MySql.Data.MySqlClient { /// /// Helper class that makes it easier to work with the provider. /// public sealed class MySqlHelper { enum CharClass : byte { None, Quote, Backslash } private static string stringOfBackslashChars = "\u005c\u00a5\u0160\u20a9\u2216\ufe68\uff3c"; private static string stringOfQuoteChars = "\u0027\u0060\u00b4\u02b9\u02ba\u02bb\u02bc\u02c8\u02ca\u02cb\u02d9\u0300\u0301\u2018\u2019\u201a\u2032\u2035\u275b\u275c\uff07"; private static CharClass[] charClassArray = makeCharClassArray(); // this class provides only static methods private MySqlHelper() { } #region ExecuteNonQuery /// /// Executes a single command against a MySQL database. The is assumed to be /// open when the method is called and remains open after the method completes. /// /// object to use /// SQL command to be executed /// Array of objects to use with the command. /// public static int ExecuteNonQuery( MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters ) { //create a command and prepare it for execution MySqlCommand cmd = new MySqlCommand(); cmd.Connection = connection; cmd.CommandText = commandText; cmd.CommandType = CommandType.Text; if (commandParameters != null) foreach (MySqlParameter p in commandParameters) cmd.Parameters.Add( p ); int result = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return result; } /// /// Executes a single command against a MySQL database. A new is created /// using the given. /// /// to use /// SQL command to be executed /// Array of objects to use with the command. /// public static int ExecuteNonQuery( string connectionString, string commandText, params MySqlParameter[] parms ) { //create & open a SqlConnection, and dispose of it after we are done. using (MySqlConnection cn = new MySqlConnection(connectionString)) { cn.Open(); //call the overload that takes a connection in place of the connection string return ExecuteNonQuery(cn, commandText, parms ); } } #endregion #region ExecuteDataSet /// /// Executes a single SQL command and returns the first row of the resultset. A new MySqlConnection object /// is created, opened, and closed during this method. /// /// Settings to be used for the connection /// Command to execute /// Parameters to use for the command /// DataRow containing the first row of the resultset public static DataRow ExecuteDataRow( string connectionString, string commandText, params MySqlParameter[] parms ) { DataSet ds = ExecuteDataset( connectionString, commandText, parms ); if (ds == null) return null; if (ds.Tables.Count == 0) return null; if (ds.Tables[0].Rows.Count == 0) return null; return ds.Tables[0].Rows[0]; } /// /// Executes a single SQL command and returns the resultset in a . /// A new MySqlConnection object is created, opened, and closed during this method. /// /// Settings to be used for the connection /// Command to execute /// containing the resultset public static DataSet ExecuteDataset(string connectionString, string commandText) { //pass through the call providing null for the set of SqlParameters return ExecuteDataset(connectionString, commandText, (MySqlParameter[])null); } /// /// Executes a single SQL command and returns the resultset in a . /// A new MySqlConnection object is created, opened, and closed during this method. /// /// Settings to be used for the connection /// Command to execute /// Parameters to use for the command /// containing the resultset public static DataSet ExecuteDataset(string connectionString, string commandText, params MySqlParameter[] commandParameters) { //create & open a SqlConnection, and dispose of it after we are done. using (MySqlConnection cn = new MySqlConnection(connectionString)) { cn.Open(); //call the overload that takes a connection in place of the connection string return ExecuteDataset(cn, commandText, commandParameters); } } /// /// Executes a single SQL command and returns the resultset in a . /// The state of the object remains unchanged after execution /// of this method. /// /// object to use /// Command to execute /// containing the resultset public static DataSet ExecuteDataset(MySqlConnection connection, string commandText) { //pass through the call providing null for the set of SqlParameters return ExecuteDataset(connection, commandText, (MySqlParameter[])null); } /// /// Executes a single SQL command and returns the resultset in a . /// The state of the object remains unchanged after execution /// of this method. /// /// object to use /// Command to execute /// Parameters to use for the command /// containing the resultset public static DataSet ExecuteDataset(MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters) { //create a command and prepare it for execution MySqlCommand cmd = new MySqlCommand(); cmd.Connection = connection; cmd.CommandText = commandText; cmd.CommandType = CommandType.Text; if (commandParameters != null) foreach (MySqlParameter p in commandParameters) cmd.Parameters.Add( p ); //create the DataAdapter & DataSet MySqlDataAdapter da = new MySqlDataAdapter(cmd); DataSet ds = new DataSet(); //fill the DataSet using default values for DataTable names, etc. da.Fill(ds); // detach the MySqlParameters from the command object, so they can be used again. cmd.Parameters.Clear(); //return the dataset return ds; } /// /// Updates the given table with data from the given /// /// Settings to use for the update /// Command text to use for the update /// containing the new data to use in the update /// Tablename in the dataset to update public static void UpdateDataSet( string connectionString, string commandText, DataSet ds, string tablename ) { MySqlConnection cn = new MySqlConnection( connectionString ); cn.Open(); MySqlDataAdapter da = new MySqlDataAdapter( commandText, cn ); MySqlCommandBuilder cb = new MySqlCommandBuilder(da); cb.ToString(); da.Update( ds, tablename ); cn.Close(); } #endregion #region ExecuteDataReader /// /// Executes a single command against a MySQL database, possibly inside an existing transaction. /// /// object to use for the command /// object to use for the command /// Command text to use /// Array of objects to use with the command /// True if the connection should be preserved, false if not /// object ready to read the results of the command private static MySqlDataReader ExecuteReader(MySqlConnection connection, MySqlTransaction transaction, string commandText, MySqlParameter[] commandParameters, bool ExternalConn ) { //create a command and prepare it for execution MySqlCommand cmd = new MySqlCommand(); cmd.Connection = connection; cmd.Transaction = transaction; cmd.CommandText = commandText; cmd.CommandType = CommandType.Text; if (commandParameters != null) foreach (MySqlParameter p in commandParameters) cmd.Parameters.Add( p ); //create a reader MySqlDataReader dr; // call ExecuteReader with the appropriate CommandBehavior if (ExternalConn) { dr = cmd.ExecuteReader(); } else { dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); } // detach the SqlParameters from the command object, so they can be used again. cmd.Parameters.Clear(); return dr; } /// /// Executes a single command against a MySQL database. /// /// Settings to use for this command /// Command text to use /// object ready to read the results of the command public static MySqlDataReader ExecuteReader(string connectionString, string commandText) { //pass through the call providing null for the set of SqlParameters return ExecuteReader(connectionString, commandText, (MySqlParameter[])null); } /// /// Executes a single command against a MySQL database. /// /// object to use for the command /// Command text to use /// object ready to read the results of the command public static MySqlDataReader ExecuteReader(MySqlConnection connection, string commandText) { //pass through the call providing null for the set of SqlParameters return ExecuteReader(connection, null, commandText, (MySqlParameter[])null, true); } /// /// Executes a single command against a MySQL database. /// /// Settings to use for this command /// Command text to use /// Array of objects to use with the command /// object ready to read the results of the command public static MySqlDataReader ExecuteReader(string connectionString, string commandText, params MySqlParameter[] commandParameters) { //create & open a SqlConnection MySqlConnection cn = new MySqlConnection(connectionString); cn.Open(); //call the private overload that takes an internally owned connection in place of the connection string return ExecuteReader(cn, null, commandText, commandParameters, false); } /// /// Executes a single command against a MySQL database. /// /// Connection to use for the command /// Command text to use /// Array of objects to use with the command /// object ready to read the results of the command public static MySqlDataReader ExecuteReader(MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters) { //call the private overload that takes an internally owned connection in place of the connection string return ExecuteReader(connection, null, commandText, commandParameters, true); } #endregion #region ExecuteScalar /// /// Execute a single command against a MySQL database. /// /// Settings to use for the update /// Command text to use for the update /// The first column of the first row in the result set, or a null reference if the result set is empty. public static object ExecuteScalar(string connectionString, string commandText) { //pass through the call providing null for the set of MySqlParameters return ExecuteScalar(connectionString, commandText, (MySqlParameter[])null); } /// /// Execute a single command against a MySQL database. /// /// Settings to use for the command /// Command text to use for the command /// Parameters to use for the command /// The first column of the first row in the result set, or a null reference if the result set is empty. public static object ExecuteScalar(string connectionString, string commandText, params MySqlParameter[] commandParameters) { //create & open a SqlConnection, and dispose of it after we are done. using (MySqlConnection cn = new MySqlConnection(connectionString)) { cn.Open(); //call the overload that takes a connection in place of the connection string return ExecuteScalar(cn, commandText, commandParameters); } } /// /// Execute a single command against a MySQL database. /// /// object to use /// Command text to use for the command /// The first column of the first row in the result set, or a null reference if the result set is empty. public static object ExecuteScalar(MySqlConnection connection, string commandText) { //pass through the call providing null for the set of MySqlParameters return ExecuteScalar(connection, commandText, (MySqlParameter[])null); } /// /// Execute a single command against a MySQL database. /// /// object to use /// Command text to use for the command /// Parameters to use for the command /// The first column of the first row in the result set, or a null reference if the result set is empty. public static object ExecuteScalar(MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters) { //create a command and prepare it for execution MySqlCommand cmd = new MySqlCommand(); cmd.Connection = connection; cmd.CommandText = commandText; cmd.CommandType = CommandType.Text; if (commandParameters != null) foreach (MySqlParameter p in commandParameters) cmd.Parameters.Add( p ); //execute the command & return the results object retval = cmd.ExecuteScalar(); // detach the SqlParameters from the command object, so they can be used again. cmd.Parameters.Clear(); return retval; } #endregion #region Utility methods private static CharClass[] makeCharClassArray() { CharClass[] a = new CharClass[65536]; foreach (char c in stringOfBackslashChars) { a[c] = CharClass.Backslash; } foreach (char c in stringOfQuoteChars) { a[c] = CharClass.Quote; } return a; } private static bool needsQuoting(string s) { foreach (char c in s) { if (charClassArray[c] != CharClass.None) { return true; } } return false; } /// /// Escapes the string. /// /// The string to escape /// The string with all quotes escaped. public static string EscapeString(string value) { if (!needsQuoting(value)) return value; StringBuilder sb = new StringBuilder(); foreach (char c in value) { CharClass charClass = charClassArray[c]; if (charClass != CharClass.None) { sb.Append("\\"); } sb.Append(c); } return sb.ToString(); } public static string DoubleQuoteString(string value) { if (!needsQuoting(value)) return value; StringBuilder sb = new StringBuilder(); foreach (char c in value) { CharClass charClass = charClassArray[c]; if (charClass == CharClass.Quote) sb.Append(c); else if (charClass == CharClass.Backslash) sb.Append("\\"); sb.Append(c); } return sb.ToString(); } #endregion } } mysql-connector-net-6.4.3/Source/MySql.Data/MySqlPacket.cs0000644000175000017500000002424611127003600024064 0ustar directhexdirecthex// Copyright © 2004,2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Diagnostics; using System.Text; using System.IO; using MySql.Data.Common; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { class MySqlPacket { private byte[] tempBuffer = new byte[256]; private Encoding encoding; private MemoryStream buffer = new MemoryStream(5); private DBVersion version; private MySqlPacket() { Clear(); } public MySqlPacket(Encoding enc) : this() { Encoding = enc; } public MySqlPacket(MemoryStream stream) : this() { buffer = stream; } #region Properties public Encoding Encoding { get { return encoding; } set { Debug.Assert(value != null); encoding = value; } } public bool HasMoreData { get { return buffer.Position < buffer.Length; } } public int Position { get { return (int)buffer.Position; } set { buffer.Position = (long)value; } } public int Length { get { return (int)buffer.Length; } set { buffer.SetLength(value); } } public bool IsLastPacket { get { byte[] bits = buffer.GetBuffer(); return bits[0] == 0xfe && Length <= 5; } } public byte[] Buffer { get { return buffer.GetBuffer(); } } public DBVersion Version { get { return version; } set { version = value; } } #endregion public void Clear() { Position = 4; } #region Byte methods public byte ReadByte() { return (byte)buffer.ReadByte(); } public int Read(byte[] byteBuffer, int offset, int count) { return buffer.Read(byteBuffer, offset, count); } public void WriteByte(byte b) { buffer.WriteByte(b); } public void Write(byte[] bytesToWrite) { Write(bytesToWrite, 0, bytesToWrite.Length); } public void Write(byte[] bytesToWrite, int offset, int countToWrite) { buffer.Write(bytesToWrite, offset, countToWrite); } public int ReadNBytes() { byte c = ReadByte(); if (c < 1 || c > 4) throw new MySqlException(Resources.IncorrectTransmission); return ReadInteger(c); } #endregion #region Integer methods public long ReadFieldLength() { byte c = ReadByte(); switch (c) { case 251: return -1; case 252: return ReadInteger(2); case 253: return ReadInteger(3); case 254: return ReadLong(8); default: return c; } } public ulong ReadBitValue(int numbytes) { ulong value = 0; int pos = (int)buffer.Position; byte[] bits = buffer.GetBuffer(); int shift = 0; for (int i = 0; i < numbytes; i++) { value <<= shift; value |= bits[pos++]; shift = 8; } buffer.Position += numbytes; return value; } public long ReadLong(int numbytes) { Debug.Assert((buffer.Position + numbytes) <= buffer.Length); byte[] bytes = buffer.GetBuffer(); int pos = (int)buffer.Position; buffer.Position += numbytes; switch (numbytes) { case 2: return BitConverter.ToUInt16(bytes, pos); case 4: return BitConverter.ToUInt32(bytes, pos); case 8: return BitConverter.ToInt64(bytes, pos); } throw new NotSupportedException("Only byte lengths of 2, 4, or 8 are supported"); } public ulong ReadULong(int numbytes) { Debug.Assert((buffer.Position + numbytes) <= buffer.Length); byte[] bytes = buffer.GetBuffer(); int pos = (int)buffer.Position; buffer.Position += numbytes; switch (numbytes) { case 2: return BitConverter.ToUInt16(bytes, pos); case 4: return BitConverter.ToUInt32(bytes, pos); case 8: return BitConverter.ToUInt64(bytes, pos); } throw new NotSupportedException("Only byte lengths of 2, 4, or 8 are supported"); } public int Read3ByteInt() { int value = 0; int pos = (int)buffer.Position; byte[] bits = buffer.GetBuffer(); int shift = 0; for (int i = 0; i < 3; i++) { value |= (int)(bits[pos++] << shift); shift += 8; } buffer.Position += 3; return value; } public int ReadInteger(int numbytes) { if (numbytes == 3) return Read3ByteInt(); Debug.Assert(numbytes <= 4); return (int)ReadLong(numbytes); } /// /// WriteInteger /// /// /// public void WriteInteger(long v, int numbytes) { long val = v; Debug.Assert(numbytes > 0 && numbytes < 9); for (int x = 0; x < numbytes; x++) { tempBuffer[x] = (byte)(val & 0xff); val >>= 8; } Write(tempBuffer, 0, numbytes); } public int ReadPackedInteger() { byte c = ReadByte(); switch (c) { case 251: return -1; case 252: return ReadInteger(2); case 253: return ReadInteger(3); case 254: return ReadInteger(4); default: return c; } } public void WriteLength(long length) { if (length < 251) WriteByte((byte)length); else if (length < 65536L) { WriteByte(252); WriteInteger(length, 2); } else if (length < 16777216L) { WriteByte(253); WriteInteger(length, 3); } else { WriteByte(254); WriteInteger(length, 4); } } #endregion #region String methods public void WriteLenString(string s) { byte[] bytes = encoding.GetBytes(s); WriteLength(bytes.Length); Write(bytes, 0, bytes.Length); } public void WriteStringNoNull(string v) { byte[] bytes = encoding.GetBytes(v); Write(bytes, 0, bytes.Length); } public void WriteString(string v) { WriteStringNoNull(v); WriteByte(0); } public string ReadLenString() { long len = ReadPackedInteger(); return ReadString(len); } public string ReadAsciiString(long length) { if (length == 0) return String.Empty; // byte[] buf = new byte[length]; Read(tempBuffer, 0, (int)length); return ASCIIEncoding.ASCII.GetString(tempBuffer, 0, (int)length); //return encoding.GetString(tempBuffer, 0, (int)length); //buf.Length); } public string ReadString(long length) { if (length == 0) return String.Empty; if (tempBuffer == null || length > tempBuffer.Length) tempBuffer = new byte[length]; Read(tempBuffer, 0, (int)length); return encoding.GetString(tempBuffer, 0, (int)length); } public string ReadString(Encoding enc) { byte[] bits = buffer.GetBuffer(); int end = (int)buffer.Position; while (end < (int)buffer.Length && bits[end] != 0 && (int)bits[end] != -1) end++; string s = enc.GetString(bits, (int)buffer.Position, end - (int)buffer.Position); buffer.Position = end + 1; return s; } public string ReadString() { return ReadString(this.encoding); } #endregion } } mysql-connector-net-6.4.3/Source/MySql.Data/PreparableStatement.cs0000644000175000017500000001760311127003600025630 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Text; using System.Collections.Generic; using MySql.Data.MySqlClient.Properties; using System.Data; namespace MySql.Data.MySqlClient { /// /// Summary description for PreparedStatement. /// internal class PreparableStatement : Statement { private int executionCount; private int statementId; BitArray nullMap; List parametersToSend = new List(); MySqlPacket packet; int dataPosition; int nullMapPosition; public PreparableStatement(MySqlCommand command, string text) : base(command, text) { } #region Properties public int ExecutionCount { get { return executionCount; } set { executionCount = value; } } public bool IsPrepared { get { return statementId > 0; } } public int StatementId { get { return statementId; } } #endregion public virtual void Prepare() { // strip out names from parameter markers string text; List parameter_names = PrepareCommandText(out text); // ask our connection to send the prepare command MySqlField[] paramList = null; statementId = Driver.PrepareStatement(text, ref paramList); // now we need to assign our field names since we stripped them out // for the prepare for (int i = 0; i < parameter_names.Count; i++) { //paramList[i].ColumnName = (string) parameter_names[i]; string parameterName = (string)parameter_names[i]; MySqlParameter p = Parameters.GetParameterFlexible(parameterName, false); if (p == null) throw new InvalidOperationException( String.Format(Resources.ParameterNotFoundDuringPrepare, parameterName)); p.Encoding = paramList[i].Encoding; parametersToSend.Add(p); } // now prepare our null map int numNullBytes = 0; if (paramList != null && paramList.Length > 0) { nullMap = new BitArray(paramList.Length); numNullBytes = (nullMap.Count + 7) / 8; } packet = new MySqlPacket(Driver.Encoding); // write out some values that do not change run to run packet.WriteByte(0); packet.WriteInteger(statementId, 4); packet.WriteByte((byte)0); // flags; always 0 for 4.1 packet.WriteInteger(1, 4); // interation count; 1 for 4.1 nullMapPosition = packet.Position; packet.Position += numNullBytes; // leave room for our null map packet.WriteByte(1); // rebound flag // write out the parameter types foreach (MySqlParameter p in parametersToSend) packet.WriteInteger(p.GetPSType(), 2); dataPosition = packet.Position; } public override void Execute() { // if we are not prepared, then call down to our base if (!IsPrepared) { base.Execute(); return; } //TODO: support long data here // create our null bitmap // we check this because Mono doesn't ignore the case where nullMapBytes // is zero length. // if (nullMapBytes.Length > 0) // { // byte[] bits = packet.Buffer; // nullMap.CopyTo(bits, // nullMap.CopyTo(nullMapBytes, 0); // start constructing our packet // if (Parameters.Count > 0) // nullMap.CopyTo(packet.Buffer, nullMapPosition); //if (parameters != null && parameters.Count > 0) //else // packet.WriteByte( 0 ); //TODO: only send rebound if parms change // now write out all non-null values packet.Position = dataPosition; for (int i = 0; i < parametersToSend.Count; i++) { MySqlParameter p = parametersToSend[i]; nullMap[i] = (p.Value == DBNull.Value || p.Value == null) || p.Direction == ParameterDirection.Output; if (nullMap[i]) continue; packet.Encoding = p.Encoding; p.Serialize(packet, true, Connection.Settings); } if (nullMap != null) nullMap.CopyTo(packet.Buffer, nullMapPosition); executionCount++; Driver.ExecuteStatement(packet); } public override bool ExecuteNext() { if (!IsPrepared) return base.ExecuteNext(); return false; } /// /// Prepares CommandText for use with the Prepare method /// /// Command text stripped of all paramter names /// /// Takes the output of TokenizeSql and creates a single string of SQL /// that only contains '?' markers for each parameter. It also creates /// the parameterMap array list that includes all the paramter names in the /// order they appeared in the SQL /// private List PrepareCommandText(out string stripped_sql) { StringBuilder newSQL = new StringBuilder(); List parameterMap = new List(); int startPos = 0; string sql = ResolvedCommandText; MySqlTokenizer tokenizer = new MySqlTokenizer(sql); string parameter = tokenizer.NextParameter(); while (parameter != null) { if (parameter.IndexOf(StoredProcedure.ParameterPrefix) == -1) { newSQL.Append(sql.Substring(startPos, tokenizer.StartIndex - startPos)); newSQL.Append("?"); parameterMap.Add(parameter); startPos = tokenizer.StopIndex; } parameter = tokenizer.NextParameter(); } newSQL.Append(sql.Substring(startPos)); stripped_sql = newSQL.ToString(); return parameterMap; } public virtual void CloseStatement() { if (!IsPrepared) return; Driver.CloseStatement(statementId); statementId = 0; } } } mysql-connector-net-6.4.3/Source/MySql.Data/TableCache.cs0000644000175000017500000001051411127003600023633 0ustar directhexdirecthex// Copyright (c) 2011 Oracle Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Data; using System.Collections.Generic; using MySql.Data.MySqlClient.Properties; using System.Diagnostics; using System.Text; using System.Globalization; namespace MySql.Data.MySqlClient { internal class TableCache { private static BaseTableCache cache; static TableCache() { cache = new BaseTableCache(480 /* 8 hour max by default */); } public static void AddToCache(string commandText, ResultSet resultSet) { cache.AddToCache(commandText, resultSet); } public static ResultSet RetrieveFromCache(string commandText, int cacheAge) { return (ResultSet)cache.RetrieveFromCache(commandText, cacheAge); } public static void RemoveFromCache(string commandText) { cache.RemoveFromCache(commandText); } public static void DumpCache() { cache.Dump(); } } public class BaseTableCache { protected int MaxCacheAge; private Dictionary cache = new Dictionary(); public BaseTableCache(int maxCacheAge) { MaxCacheAge = maxCacheAge; } public virtual void AddToCache(string commandText, object resultSet) { CleanCache(); CacheEntry entry = new CacheEntry(); entry.CacheTime = DateTime.Now; entry.CacheElement = resultSet; lock (cache) { if (cache.ContainsKey(commandText)) return; cache.Add(commandText, entry); } } public virtual object RetrieveFromCache(string commandText, int cacheAge) { CleanCache(); lock (cache) { if (!cache.ContainsKey(commandText)) return null; CacheEntry entry = cache[commandText]; if (DateTime.Now.Subtract(entry.CacheTime).TotalSeconds > cacheAge) return null; return entry.CacheElement; } } public void RemoveFromCache(string commandText) { lock (cache) { if (!cache.ContainsKey(commandText)) return; cache.Remove(commandText); } } public virtual void Dump() { lock (cache) cache.Clear(); } protected virtual void CleanCache() { DateTime now = DateTime.Now; List keysToRemove =new List(); lock (cache) { foreach (string key in cache.Keys) { TimeSpan diff = now.Subtract(cache[key].CacheTime); if (diff.TotalSeconds > MaxCacheAge) keysToRemove.Add(key); } foreach (string key in keysToRemove) cache.Remove(key); } } private struct CacheEntry { public DateTime CacheTime; public object CacheElement; } } }mysql-connector-net-6.4.3/Source/MySql.Data/StoredProcedure.cs0000644000175000017500000003256211127003600025000 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Globalization; using System.Text; using MySql.Data.Types; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { /// /// Summary description for StoredProcedure. /// internal class StoredProcedure : PreparableStatement { private string outSelect; private DataTable parametersTable; private string resolvedCommandText; private bool serverProvidingOutputParameters; // Prefix used for to generate inout or output parameters names internal const string ParameterPrefix = "_cnet_param_"; public StoredProcedure(MySqlCommand cmd, string text) : base(cmd, text) { } private MySqlParameter GetReturnParameter() { if (Parameters != null) foreach (MySqlParameter p in Parameters) if (p.Direction == ParameterDirection.ReturnValue) return p; return null; } public bool ServerProvidingOutputParameters { get { return serverProvidingOutputParameters; } } public override string ResolvedCommandText { get { return resolvedCommandText; } } internal string GetCacheKey(string spName) { string retValue = String.Empty; StringBuilder key = new StringBuilder(spName); key.Append("("); string delimiter = ""; foreach (MySqlParameter p in command.Parameters) { if (p.Direction == ParameterDirection.ReturnValue) retValue = "?="; else { key.AppendFormat(CultureInfo.InvariantCulture, "{0}?", delimiter); delimiter = ","; } } key.Append(")"); return retValue + key.ToString(); } private void GetParameters(string procName, out DataTable proceduresTable, out DataTable parametersTable) { string procCacheKey = GetCacheKey(procName); DataSet ds = Connection.ProcedureCache.GetProcedure(Connection, procName, procCacheKey); lock (ds) { proceduresTable = ds.Tables["procedures"]; parametersTable = ds.Tables["procedure parameters"]; } } public static string GetFlags(string dtd) { int x = dtd.Length - 1; while (x > 0 && (Char.IsLetterOrDigit(dtd[x]) || dtd[x] == ' ')) x--; return dtd.Substring(x).ToUpper(CultureInfo.InvariantCulture); } private string FixProcedureName(string name) { string[] parts = name.Split('.'); for (int i = 0; i < parts.Length; i++) if (!parts[i].StartsWith("`")) parts[i] = String.Format("`{0}`", parts[i]); if (parts.Length == 1) return parts[0]; return String.Format("{0}.{1}", parts[0], parts[1]); } private MySqlParameter GetAndFixParameter(string spName, DataRow param, bool realAsFloat, MySqlParameter returnParameter) { string mode = (string)param["PARAMETER_MODE"]; string pName = (string)param["PARAMETER_NAME"]; if (param["ORDINAL_POSITION"].Equals(0)) { if (returnParameter == null) throw new InvalidOperationException( String.Format(Resources.RoutineRequiresReturnParameter, spName)); pName = returnParameter.ParameterName; } // make sure the parameters given to us have an appropriate type set if it's not already MySqlParameter p = command.Parameters.GetParameterFlexible(pName, true); if (!p.TypeHasBeenSet) { string datatype = (string)param["DATA_TYPE"]; bool unsigned = GetFlags(param["DTD_IDENTIFIER"].ToString()).IndexOf("UNSIGNED") != -1; p.MySqlDbType = MetaData.NameToType(datatype, unsigned, realAsFloat, Connection); } return p; } private MySqlParameterCollection CheckParameters(string spName) { MySqlParameterCollection newParms = new MySqlParameterCollection(command); MySqlParameter returnParameter = GetReturnParameter(); DataTable procTable; GetParameters(spName, out procTable, out parametersTable); if (procTable.Rows.Count == 0) throw new InvalidOperationException(String.Format(Resources.RoutineNotFound, spName)); bool realAsFloat = procTable.Rows[0]["SQL_MODE"].ToString().IndexOf("REAL_AS_FLOAT") != -1; foreach (DataRow param in parametersTable.Rows) newParms.Add(GetAndFixParameter(spName, param, realAsFloat, returnParameter)); return newParms; } public override void Resolve(bool preparing) { // check to see if we are already resolved if (resolvedCommandText != null) return; serverProvidingOutputParameters = Driver.SupportsOutputParameters && preparing; // first retrieve the procedure definition from our // procedure cache string spName = commandText; if (spName.IndexOf(".") == -1 && !String.IsNullOrEmpty(Connection.Database)) spName = Connection.Database + "." + spName; spName = FixProcedureName(spName); MySqlParameter returnParameter = GetReturnParameter(); MySqlParameterCollection parms = command.Connection.Settings.CheckParameters ? CheckParameters(spName) : Parameters; string setSql = SetUserVariables(parms, preparing); string callSql = CreateCallStatement(spName, returnParameter, parms); string outSql = CreateOutputSelect(parms, preparing); resolvedCommandText = String.Format("{0}{1}{2}", setSql, callSql, outSql); } private string SetUserVariables(MySqlParameterCollection parms, bool preparing) { StringBuilder setSql = new StringBuilder(); if (serverProvidingOutputParameters) return setSql.ToString(); string delimiter = String.Empty; foreach (MySqlParameter p in parms) { if (p.Direction != ParameterDirection.InputOutput) continue; string pName = "@" + p.BaseName; string uName = "@" + ParameterPrefix + p.BaseName; string sql = String.Format("SET {0}={1}", uName, pName); if (command.Connection.Settings.AllowBatch && !preparing) { setSql.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}", delimiter, sql); delimiter = "; "; } else { MySqlCommand cmd = new MySqlCommand(sql, command.Connection); cmd.Parameters.Add(p); cmd.ExecuteNonQuery(); } } if (setSql.Length > 0) setSql.Append("; "); return setSql.ToString(); } private string CreateCallStatement(string spName, MySqlParameter returnParameter, MySqlParameterCollection parms) { StringBuilder callSql = new StringBuilder(); string delimiter = String.Empty; foreach (MySqlParameter p in parms) { if (p.Direction == ParameterDirection.ReturnValue) continue; string pName = "@" + p.BaseName; string uName = "@" + ParameterPrefix + p.BaseName; bool useRealVar = p.Direction == ParameterDirection.Input || serverProvidingOutputParameters; callSql.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}", delimiter, useRealVar ? pName : uName); delimiter = ", "; } if (returnParameter == null) return String.Format("CALL {0}({1})", spName, callSql.ToString()); else return String.Format("SET @{0}{1}={2}({3})", ParameterPrefix, returnParameter.BaseName, spName, callSql.ToString()); } private string CreateOutputSelect(MySqlParameterCollection parms, bool preparing) { StringBuilder outSql = new StringBuilder(); string delimiter = String.Empty; foreach (MySqlParameter p in parms) { if (p.Direction == ParameterDirection.Input) continue; if ((p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Output) && serverProvidingOutputParameters) continue; string pName = "@" + p.BaseName; string uName = "@" + ParameterPrefix + p.BaseName; outSql.AppendFormat(CultureInfo.InvariantCulture, "{0}{1}", delimiter, uName); delimiter = ", "; } if (outSql.Length == 0) return String.Empty; if (command.Connection.Settings.AllowBatch && !preparing) return String.Format(";SELECT {0}", outSql.ToString()); outSelect = String.Format("SELECT {0}", outSql.ToString()); return String.Empty; } internal void ProcessOutputParameters(MySqlDataReader reader) { // We apparently need to always adjust our output types since the server // provided data types are not always right AdjustOutputTypes(reader); // now read the output parameters data row CommandBehavior behavior = reader.CommandBehavior; if ((behavior & CommandBehavior.SchemaOnly) != 0) return; if (!reader.Read()) return; //reader.ResultSet.NextRow(behavior); string prefix = "@" + StoredProcedure.ParameterPrefix; for (int i = 0; i < reader.FieldCount; i++) { string fieldName = reader.GetName(i); if (fieldName.StartsWith(prefix)) fieldName = fieldName.Remove(0, prefix.Length); MySqlParameter parameter = command.Parameters.GetParameterFlexible(fieldName, true); parameter.Value = reader.GetValue(i); } } private void AdjustOutputTypes(MySqlDataReader reader) { // since MySQL likes to return user variables as strings // we reset the types of the readers internal value objects // this will allow those value objects to parse the string based // return values for (int i = 0; i < reader.FieldCount; i++) { string fieldName = reader.GetName(i); if (fieldName.IndexOf(StoredProcedure.ParameterPrefix) != -1) fieldName = fieldName.Remove(0, StoredProcedure.ParameterPrefix.Length + 1); MySqlParameter parameter = command.Parameters.GetParameterFlexible(fieldName, true); IMySqlValue v = MySqlField.GetIMySqlValue(parameter.MySqlDbType); if (v is MySqlBit) { MySqlBit bit = (MySqlBit)v; bit.ReadAsString = true; reader.ResultSet.SetValueObject(i, bit); } else reader.ResultSet.SetValueObject(i, v); } } public override void Close(MySqlDataReader reader) { base.Close(reader); if (String.IsNullOrEmpty(outSelect)) return; if ((reader.CommandBehavior & CommandBehavior.SchemaOnly) != 0) return; MySqlCommand cmd = new MySqlCommand(outSelect, command.Connection); using (MySqlDataReader rdr = cmd.ExecuteReader(reader.CommandBehavior)) { ProcessOutputParameters(rdr); } } } } mysql-connector-net-6.4.3/Source/MySql.Data/Properties/0000755000175000017500000000000011127003600023464 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Data/Properties/VersionInfo.cs0000644000175000017500000000307211127003600026256 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Security; // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("6.4.3")] mysql-connector-net-6.4.3/Source/MySql.Data/Properties/Resources.Designer.cs0000644000175000017500000013466311127003600027541 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.5446 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace MySql.Data.MySqlClient.Properties { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. #if !CF [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] #endif public class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MySql.Data.MySqlClient.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// /// Looks up a localized string similar to Improper MySqlCommandBuilder state: adapter is null. /// public static string AdapterIsNull { get { return ResourceManager.GetString("AdapterIsNull", resourceCulture); } } /// /// Looks up a localized string similar to Improper MySqlCommandBuilder state: adapter's SelectCommand is null. /// public static string AdapterSelectIsNull { get { return ResourceManager.GetString("AdapterSelectIsNull", resourceCulture); } } /// /// Looks up a localized string similar to Invalid attempt to access a field before calling Read(). /// public static string AttemptToAccessBeforeRead { get { return ResourceManager.GetString("AttemptToAccessBeforeRead", resourceCulture); } } /// /// Looks up a localized string similar to Version string not in acceptable format. /// public static string BadVersionFormat { get { return ResourceManager.GetString("BadVersionFormat", resourceCulture); } } /// /// Looks up a localized string similar to The buffer cannot be null. /// public static string BufferCannotBeNull { get { return ResourceManager.GetString("BufferCannotBeNull", resourceCulture); } } /// /// Looks up a localized string similar to Buffer is not large enough. /// public static string BufferNotLargeEnough { get { return ResourceManager.GetString("BufferNotLargeEnough", resourceCulture); } } /// /// Looks up a localized string similar to Canceling an executing query requires MySQL 5.0 or higher.. /// public static string CancelNeeds50 { get { return ResourceManager.GetString("CancelNeeds50", resourceCulture); } } /// /// Looks up a localized string similar to Canceling an active query is only supported on MySQL 5.0.0 and above. . /// public static string CancelNotSupported { get { return ResourceManager.GetString("CancelNotSupported", resourceCulture); } } /// /// Looks up a localized string similar to Parameters can only be derived for commands using the StoredProcedure command type.. /// public static string CanNotDeriveParametersForTextCommands { get { return ResourceManager.GetString("CanNotDeriveParametersForTextCommands", resourceCulture); } } /// /// Looks up a localized string similar to MySqlCommandBuilder does not support multi-table statements. /// public static string CBMultiTableNotSupported { get { return ResourceManager.GetString("CBMultiTableNotSupported", resourceCulture); } } /// /// Looks up a localized string similar to MySqlCommandBuilder cannot operate on tables with no unique or key columns. /// public static string CBNoKeyColumn { get { return ResourceManager.GetString("CBNoKeyColumn", resourceCulture); } } /// /// Looks up a localized string similar to Chaos isolation level is not supported. /// public static string ChaosNotSupported { get { return ResourceManager.GetString("ChaosNotSupported", resourceCulture); } } /// /// Looks up a localized string similar to The CommandText property has not been properly initialized.. /// public static string CommandTextNotInitialized { get { return ResourceManager.GetString("CommandTextNotInitialized", resourceCulture); } } /// /// Looks up a localized string similar to The connection is already open.. /// public static string ConnectionAlreadyOpen { get { return ResourceManager.GetString("ConnectionAlreadyOpen", resourceCulture); } } /// /// Looks up a localized string similar to Connection unexpectedly terminated.. /// public static string ConnectionBroken { get { return ResourceManager.GetString("ConnectionBroken", resourceCulture); } } /// /// Looks up a localized string similar to Connection must be valid and open. /// public static string ConnectionMustBeOpen { get { return ResourceManager.GetString("ConnectionMustBeOpen", resourceCulture); } } /// /// Looks up a localized string similar to The connection is not open.. /// public static string ConnectionNotOpen { get { return ResourceManager.GetString("ConnectionNotOpen", resourceCulture); } } /// /// Looks up a localized string similar to The connection property has not been set or is null.. /// public static string ConnectionNotSet { get { return ResourceManager.GetString("ConnectionNotSet", resourceCulture); } } /// /// Looks up a localized string similar to Could not find specified column in results: {0}. /// public static string CouldNotFindColumnName { get { return ResourceManager.GetString("CouldNotFindColumnName", resourceCulture); } } /// /// Looks up a localized string similar to Count cannot be negative. /// public static string CountCannotBeNegative { get { return ResourceManager.GetString("CountCannotBeNegative", resourceCulture); } } /// /// Looks up a localized string similar to SetLength is not a valid operation on CompressedStream. /// public static string CSNoSetLength { get { return ResourceManager.GetString("CSNoSetLength", resourceCulture); } } /// /// Looks up a localized string similar to The given value was not in a supported format.. /// public static string DataNotInSupportedFormat { get { return ResourceManager.GetString("DataNotInSupportedFormat", resourceCulture); } } /// /// Looks up a localized string similar to There is already an open DataReader associated with this Connection which must be closed first.. /// public static string DataReaderOpen { get { return ResourceManager.GetString("DataReaderOpen", resourceCulture); } } /// /// Looks up a localized string similar to The default connection encoding was not found. Please report this as a bug along with your connection string and system details.. /// public static string DefaultEncodingNotFound { get { return ResourceManager.GetString("DefaultEncodingNotFound", resourceCulture); } } /// /// Looks up a localized string similar to MySQL Connector/Net does not currently support distributed transactions.. /// public static string DistributedTxnNotSupported { get { return ResourceManager.GetString("DistributedTxnNotSupported", resourceCulture); } } /// /// Looks up a localized string similar to Error creating socket connection. /// public static string ErrorCreatingSocket { get { return ResourceManager.GetString("ErrorCreatingSocket", resourceCulture); } } /// /// Looks up a localized string similar to Fatal error encountered during command execution.. /// public static string FatalErrorDuringExecute { get { return ResourceManager.GetString("FatalErrorDuringExecute", resourceCulture); } } /// /// Looks up a localized string similar to Fatal error encountered during data read.. /// public static string FatalErrorDuringRead { get { return ResourceManager.GetString("FatalErrorDuringRead", resourceCulture); } } /// /// Looks up a localized string similar to Fatal error encountered attempting to read the resultset.. /// public static string FatalErrorReadingResult { get { return ResourceManager.GetString("FatalErrorReadingResult", resourceCulture); } } /// /// Looks up a localized string similar to File based certificates are only supported when connecting to MySQL Server 5.1 or greater.. /// public static string FileBasedCertificateNotSupported { get { return ResourceManager.GetString("FileBasedCertificateNotSupported", resourceCulture); } } /// /// Looks up a localized string similar to From index and length use more bytes than from contains. /// public static string FromAndLengthTooBig { get { return ResourceManager.GetString("FromAndLengthTooBig", resourceCulture); } } /// /// Looks up a localized string similar to From index must be a valid index inside the from buffer. /// public static string FromIndexMustBeValid { get { return ResourceManager.GetString("FromIndexMustBeValid", resourceCulture); } } /// /// Looks up a localized string similar to Call to GetHostEntry failed after {0} while querying for hostname '{1}': SocketErrorCode={2}, ErrorCode={3}, NativeErrorCode={4}.. /// public static string GetHostEntryFailed { get { return ResourceManager.GetString("GetHostEntryFailed", resourceCulture); } } /// /// Looks up a localized string similar to Retrieving procedure metadata for {0} from server.. /// public static string HardProcQuery { get { return ResourceManager.GetString("HardProcQuery", resourceCulture); } } /// /// Looks up a localized string similar to Value has an unsupported format.. /// public static string ImproperValueFormat { get { return ResourceManager.GetString("ImproperValueFormat", resourceCulture); } } /// /// Looks up a localized string similar to An incorrect response was received from the server.. /// public static string IncorrectTransmission { get { return ResourceManager.GetString("IncorrectTransmission", resourceCulture); } } /// /// Looks up a localized string similar to Index and length use more bytes than to has room for. /// public static string IndexAndLengthTooBig { get { return ResourceManager.GetString("IndexAndLengthTooBig", resourceCulture); } } /// /// Looks up a localized string similar to Index must be a valid position in the buffer. /// public static string IndexMustBeValid { get { return ResourceManager.GetString("IndexMustBeValid", resourceCulture); } } /// /// Looks up a localized string similar to You have specified an invalid column ordinal.. /// public static string InvalidColumnOrdinal { get { return ResourceManager.GetString("InvalidColumnOrdinal", resourceCulture); } } /// /// Looks up a localized string similar to The requested value '{0}' is invalid for the given keyword '{1}'.. /// public static string InvalidConnectionStringValue { get { return ResourceManager.GetString("InvalidConnectionStringValue", resourceCulture); } } /// /// Looks up a localized string similar to Procedure or function '{0}' cannot be found in database '{1}'.. /// public static string InvalidProcName { get { return ResourceManager.GetString("InvalidProcName", resourceCulture); } } /// /// Looks up a localized string similar to '{0}' is an illegal value for a boolean option.. /// public static string InvalidValueForBoolean { get { return ResourceManager.GetString("InvalidValueForBoolean", resourceCulture); } } /// /// Looks up a localized string similar to Keyword does not allow null values.. /// public static string KeywordNoNull { get { return ResourceManager.GetString("KeywordNoNull", resourceCulture); } } /// /// Looks up a localized string similar to Keyword not supported.. /// public static string KeywordNotSupported { get { return ResourceManager.GetString("KeywordNotSupported", resourceCulture); } } /// /// Looks up a localized string similar to ACCESSIBLE ///ADD ///ALL ///ALTER ///ANALYZE ///AND ///AS ///ASC ///ASENSITIVE ///BEFORE ///BETWEEN ///BIGINT ///BINARY ///BLOB ///BOTH ///BY ///CALL ///CASCADE ///CASE ///CHANGE ///CHAR ///CHARACTER ///CHECK ///COLLATE ///COLUMN ///CONDITION ///CONNECTION ///CONSTRAINT ///CONTINUE ///CONVERT ///CREATE ///CROSS ///CURRENT_DATE ///CURRENT_TIME ///CURRENT_TIMESTAMP ///CURRENT_USER ///CURSOR ///DATABASE ///DATABASES ///DAY_HOUR ///DAY_MICROSECOND ///DAY_MINUTE ///DAY_SECOND ///DEC ///DECIMAL ///DECLARE ///DEFAULT ///DELAYED ///DELETE ///DESC ///DESCRIBE ///DETERMINISTIC ///DISTINCT ///DISTINCTROW ///DIV ///DOUBLE ///DROP ///DUAL ///EACH ///ELSE ///ELSEIF ///ENCLOSED ///ESCAPED ///EXISTS ///EXIT ///EXP [rest of string was truncated]";. /// public static string keywords { get { return ResourceManager.GetString("keywords", resourceCulture); } } /// /// Looks up a localized string similar to INTERNAL ERROR: More than one output parameter row detected.. /// public static string MoreThanOneOPRow { get { return ResourceManager.GetString("MoreThanOneOPRow", resourceCulture); } } /// /// Looks up a localized string similar to Multiple simultaneous connections or connections with different connection strings inside the same transaction are not currently supported.. /// public static string MultipleConnectionsInTransactionNotSupported { get { return ResourceManager.GetString("MultipleConnectionsInTransactionNotSupported", resourceCulture); } } /// /// Looks up a localized string similar to NamedPipeStream does not support seeking. /// public static string NamedPipeNoSeek { get { return ResourceManager.GetString("NamedPipeNoSeek", resourceCulture); } } /// /// Looks up a localized string similar to NamedPipeStream doesn't support SetLength. /// public static string NamedPipeNoSetLength { get { return ResourceManager.GetString("NamedPipeNoSetLength", resourceCulture); } } /// /// Looks up a localized string similar to Invalid attempt to call NextResult when the reader is closed.. /// public static string NextResultIsClosed { get { return ResourceManager.GetString("NextResultIsClosed", resourceCulture); } } /// /// Looks up a localized string similar to When calling stored procedures and 'Use Procedure Bodies' is false, all parameters must have their type explicitly set.. /// public static string NoBodiesAndTypeNotSet { get { return ResourceManager.GetString("NoBodiesAndTypeNotSet", resourceCulture); } } /// /// Looks up a localized string similar to Nested transactions are not supported.. /// public static string NoNestedTransactions { get { return ResourceManager.GetString("NoNestedTransactions", resourceCulture); } } /// /// Looks up a localized string similar to The host {0} does not support SSL connections.. /// public static string NoServerSSLSupport { get { return ResourceManager.GetString("NoServerSSLSupport", resourceCulture); } } /// /// Looks up a localized string similar to Cannot retrieve Windows identity for current user. Connections that use IntegratedSecurity cannot be pooled. Use either 'ConnectionReset=true' or 'Pooling=false' in the connection string to fix.. /// public static string NoWindowsIdentity { get { return ResourceManager.GetString("NoWindowsIdentity", resourceCulture); } } /// /// Looks up a localized string similar to The object is not open or has been disposed.. /// public static string ObjectDisposed { get { return ResourceManager.GetString("ObjectDisposed", resourceCulture); } } /// /// Looks up a localized string similar to Offset cannot be negative. /// public static string OffsetCannotBeNegative { get { return ResourceManager.GetString("OffsetCannotBeNegative", resourceCulture); } } /// /// Looks up a localized string similar to Offset must be a valid position in buffer. /// public static string OffsetMustBeValid { get { return ResourceManager.GetString("OffsetMustBeValid", resourceCulture); } } /// /// Looks up a localized string similar to Parameter '{0}' has already been defined.. /// public static string ParameterAlreadyDefined { get { return ResourceManager.GetString("ParameterAlreadyDefined", resourceCulture); } } /// /// Looks up a localized string similar to Parameter cannot have a negative value. /// public static string ParameterCannotBeNegative { get { return ResourceManager.GetString("ParameterCannotBeNegative", resourceCulture); } } /// /// Looks up a localized string similar to Parameter cannot be null. /// public static string ParameterCannotBeNull { get { return ResourceManager.GetString("ParameterCannotBeNull", resourceCulture); } } /// /// Looks up a localized string similar to Parameter is invalid.. /// public static string ParameterIsInvalid { get { return ResourceManager.GetString("ParameterIsInvalid", resourceCulture); } } /// /// Looks up a localized string similar to Parameter '{0}' must be defined.. /// public static string ParameterMustBeDefined { get { return ResourceManager.GetString("ParameterMustBeDefined", resourceCulture); } } /// /// Looks up a localized string similar to Parameter '{0}' was not found during prepare.. /// public static string ParameterNotFoundDuringPrepare { get { return ResourceManager.GetString("ParameterNotFoundDuringPrepare", resourceCulture); } } /// /// Looks up a localized string similar to Password must be valid and contain length characters. /// public static string PasswordMustHaveLegalChars { get { return ResourceManager.GetString("PasswordMustHaveLegalChars", resourceCulture); } } /// /// Looks up a localized string similar to This category includes a series of counters for MySQL.. /// public static string PerfMonCategoryHelp { get { return ResourceManager.GetString("PerfMonCategoryHelp", resourceCulture); } } /// /// Looks up a localized string similar to .NET Data Provider for MySQL. /// public static string PerfMonCategoryName { get { return ResourceManager.GetString("PerfMonCategoryName", resourceCulture); } } /// /// Looks up a localized string similar to The number of times a procedures metadata had to be queried from the server.. /// public static string PerfMonHardProcHelp { get { return ResourceManager.GetString("PerfMonHardProcHelp", resourceCulture); } } /// /// Looks up a localized string similar to Hard Procedure Queries. /// public static string PerfMonHardProcName { get { return ResourceManager.GetString("PerfMonHardProcName", resourceCulture); } } /// /// Looks up a localized string similar to The number of times a procedures metadata was retrieved from the client-side cache.. /// public static string PerfMonSoftProcHelp { get { return ResourceManager.GetString("PerfMonSoftProcHelp", resourceCulture); } } /// /// Looks up a localized string similar to Soft Procedure Queries. /// public static string PerfMonSoftProcName { get { return ResourceManager.GetString("PerfMonSoftProcName", resourceCulture); } } /// /// Looks up a localized string similar to same name are not supported.. /// public static string ProcAndFuncSameName { get { return ResourceManager.GetString("ProcAndFuncSameName", resourceCulture); } } /// /// Looks up a localized string similar to Packets larger than max_allowed_packet are not allowed.. /// public static string QueryTooLarge { get { return ResourceManager.GetString("QueryTooLarge", resourceCulture); } } /// /// Looks up a localized string similar to Reading from the stream has failed.. /// public static string ReadFromStreamFailed { get { return ResourceManager.GetString("ReadFromStreamFailed", resourceCulture); } } /// /// Looks up a localized string similar to Invalid attempt to read a prior column using SequentialAccess. /// public static string ReadingPriorColumnUsingSeqAccess { get { return ResourceManager.GetString("ReadingPriorColumnUsingSeqAccess", resourceCulture); } } /// /// Looks up a localized string similar to Replicated connections allow only readonly statements.. /// public static string ReplicatedConnectionsAllowOnlyReadonlyStatements { get { return ResourceManager.GetString("ReplicatedConnectionsAllowOnlyReadonlyStatements", resourceCulture); } } /// /// Looks up a localized string similar to Routine '{0}' cannot be found. Either check the spelling or make sure you have sufficient rights to execute the routine.. /// public static string RoutineNotFound { get { return ResourceManager.GetString("RoutineNotFound", resourceCulture); } } /// /// Looks up a localized string similar to Attempt to call stored function '{0}' without specifying a return parameter. /// public static string RoutineRequiresReturnParameter { get { return ResourceManager.GetString("RoutineRequiresReturnParameter", resourceCulture); } } /// /// Looks up a localized string similar to Connector/Net no longer supports server versions prior to 5.0. /// public static string ServerTooOld { get { return ResourceManager.GetString("ServerTooOld", resourceCulture); } } /// /// Looks up a localized string similar to Snapshot isolation level is not supported.. /// public static string SnapshotNotSupported { get { return ResourceManager.GetString("SnapshotNotSupported", resourceCulture); } } /// /// Looks up a localized string similar to Socket streams do not support seeking. /// public static string SocketNoSeek { get { return ResourceManager.GetString("SocketNoSeek", resourceCulture); } } /// /// Looks up a localized string similar to Retrieving procedure metadata for {0} from procedure cache.. /// public static string SoftProcQuery { get { return ResourceManager.GetString("SoftProcQuery", resourceCulture); } } /// /// Looks up a localized string similar to Stored procedures are not supported on this version of MySQL. /// public static string SPNotSupported { get { return ResourceManager.GetString("SPNotSupported", resourceCulture); } } /// /// Looks up a localized string similar to The stream has already been closed. /// public static string StreamAlreadyClosed { get { return ResourceManager.GetString("StreamAlreadyClosed", resourceCulture); } } /// /// Looks up a localized string similar to The stream does not support reading. /// public static string StreamNoRead { get { return ResourceManager.GetString("StreamNoRead", resourceCulture); } } /// /// Looks up a localized string similar to The stream does not support writing. /// public static string StreamNoWrite { get { return ResourceManager.GetString("StreamNoWrite", resourceCulture); } } /// /// Looks up a localized string similar to Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.. /// public static string Timeout { get { return ResourceManager.GetString("Timeout", resourceCulture); } } /// /// Looks up a localized string similar to error connecting: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.. /// public static string TimeoutGettingConnection { get { return ResourceManager.GetString("TimeoutGettingConnection", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Connection Closed. /// public static string TraceCloseConnection { get { return ResourceManager.GetString("TraceCloseConnection", resourceCulture); } } /// /// Looks up a localized string similar to Unable to trace. There are more than Int32.MaxValue connections in use.. /// public static string TraceErrorMoreThanMaxValueConnections { get { return ResourceManager.GetString("TraceErrorMoreThanMaxValueConnections", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Error encountered during row fetch. Number = {1}, Message={2}. /// public static string TraceFetchError { get { return ResourceManager.GetString("TraceFetchError", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Connection Opened: connection string = '{1}'. /// public static string TraceOpenConnection { get { return ResourceManager.GetString("TraceOpenConnection", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Error encountered attempting to open result: Number={1}, Message={2}. /// public static string TraceOpenResultError { get { return ResourceManager.GetString("TraceOpenResultError", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Query Closed. /// public static string TraceQueryDone { get { return ResourceManager.GetString("TraceQueryDone", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Query Normalized: {2}. /// public static string TraceQueryNormalized { get { return ResourceManager.GetString("TraceQueryNormalized", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Query Opened: {2}. /// public static string TraceQueryOpened { get { return ResourceManager.GetString("TraceQueryOpened", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Resultset Opened: field(s) = {1}, affected rows = {2}, inserted id = {3}. /// public static string TraceResult { get { return ResourceManager.GetString("TraceResult", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Resultset Closed. Total rows={1}, skipped rows={2}, size (bytes)={3}. /// public static string TraceResultClosed { get { return ResourceManager.GetString("TraceResultClosed", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Set Database: {1}. /// public static string TraceSetDatabase { get { return ResourceManager.GetString("TraceSetDatabase", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Statement closed: statement id = {1}. /// public static string TraceStatementClosed { get { return ResourceManager.GetString("TraceStatementClosed", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Statement executed: statement id = {1}. /// public static string TraceStatementExecuted { get { return ResourceManager.GetString("TraceStatementExecuted", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Statement prepared: sql='{1}', statement id={2}. /// public static string TraceStatementPrepared { get { return ResourceManager.GetString("TraceStatementPrepared", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Usage Advisor Warning: Query is using a bad index. /// public static string TraceUAWarningBadIndex { get { return ResourceManager.GetString("TraceUAWarningBadIndex", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Usage Advisor Warning: The field '{2}' was converted to the following types: {3}. /// public static string TraceUAWarningFieldConversion { get { return ResourceManager.GetString("TraceUAWarningFieldConversion", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Usage Advisor Warning: Query does not use an index. /// public static string TraceUAWarningNoIndex { get { return ResourceManager.GetString("TraceUAWarningNoIndex", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Usage Advisor Warning: The following columns were not accessed: {2}. /// public static string TraceUAWarningSkippedColumns { get { return ResourceManager.GetString("TraceUAWarningSkippedColumns", resourceCulture); } } /// /// Looks up a localized string similar to {0}: Usage Advisor Warning: Skipped {2} rows. Consider a more focused query.. /// public static string TraceUAWarningSkippedRows { get { return ResourceManager.GetString("TraceUAWarningSkippedRows", resourceCulture); } } /// /// Looks up a localized string similar to {0}: MySql Warning: Level={1}, Code={2}, Message={3}. /// public static string TraceWarning { get { return ResourceManager.GetString("TraceWarning", resourceCulture); } } /// /// Looks up a localized string similar to Unable to connect to any of the specified MySQL hosts.. /// public static string UnableToConnectToHost { get { return ResourceManager.GetString("UnableToConnectToHost", resourceCulture); } } /// /// Looks up a localized string similar to Unable to derive stored routine parameters. The 'Parameters' information schema table is not available and access to the stored procedure body has been disabled.. /// public static string UnableToDeriveParameters { get { return ResourceManager.GetString("UnableToDeriveParameters", resourceCulture); } } /// /// Looks up a localized string similar to Unable to enable query analysis. Be sure the MySql.Data.EMTrace assembly is properly located and registered.. /// public static string UnableToEnableQueryAnalysis { get { return ResourceManager.GetString("UnableToEnableQueryAnalysis", resourceCulture); } } /// /// Looks up a localized string similar to An error occured attempting to enumerate the user-defined functions. Do you have SELECT privileges on the mysql.func table?. /// public static string UnableToEnumerateUDF { get { return ResourceManager.GetString("UnableToEnumerateUDF", resourceCulture); } } /// /// Looks up a localized string similar to Unable to execute stored procedure '{0}'.. /// public static string UnableToExecuteSP { get { return ResourceManager.GetString("UnableToExecuteSP", resourceCulture); } } /// /// Looks up a localized string similar to There was an error parsing the foreign key definition.. /// public static string UnableToParseFK { get { return ResourceManager.GetString("UnableToParseFK", resourceCulture); } } /// /// Looks up a localized string similar to Unable to retrieve stored procedure metadata for routine '{0}'. Either grant SELECT privilege to mysql.proc for this user or use "check parameters=false" with your connection string.. /// public static string UnableToRetrieveParameters { get { return ResourceManager.GetString("UnableToRetrieveParameters", resourceCulture); } } /// /// Looks up a localized string similar to Unable to start a second async operation while one is running.. /// public static string UnableToStartSecondAsyncOp { get { return ResourceManager.GetString("UnableToStartSecondAsyncOp", resourceCulture); } } /// /// Looks up a localized string similar to Unix sockets are not supported on Windows. /// public static string UnixSocketsNotSupported { get { return ResourceManager.GetString("UnixSocketsNotSupported", resourceCulture); } } /// /// Looks up a localized string similar to The requested column value could not be treated as or conveted to a Guid.. /// public static string ValueNotSupportedForGuid { get { return ResourceManager.GetString("ValueNotSupportedForGuid", resourceCulture); } } /// /// Looks up a localized string similar to Writing to the stream failed.. /// public static string WriteToStreamFailed { get { return ResourceManager.GetString("WriteToStreamFailed", resourceCulture); } } /// /// Looks up a localized string similar to Parameter '{0}' is not found but a parameter with the name '{1}' is found. Parameter names must include the leading parameter marker.. /// public static string WrongParameterName { get { return ResourceManager.GetString("WrongParameterName", resourceCulture); } } } } mysql-connector-net-6.4.3/Source/MySql.Data/Properties/Resources.resx0000644000175000017500000005657111127003600026357 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Version string not in acceptable format NamedPipeStream does not support seeking The stream has already been closed The buffer cannot be null Buffer is not large enough Offset cannot be negative Count cannot be negative The stream does not support reading NamedPipeStream doesn't support SetLength The stream does not support writing Error creating socket connection Socket streams do not support seeking Unix sockets are not supported on Windows Offset must be a valid position in buffer SetLength is not a valid operation on CompressedStream From index must be a valid index inside the from buffer From index and length use more bytes than from contains Index must be a valid position in the buffer Index and length use more bytes than to has room for Password must be valid and contain length characters Parameter cannot have a negative value Connection must be valid and open There is already an open DataReader associated with this Connection which must be closed first. Stored procedures are not supported on this version of MySQL The connection property has not been set or is null. The connection is not open. Improper MySqlCommandBuilder state: adapter is null Improper MySqlCommandBuilder state: adapter's SelectCommand is null MySqlCommandBuilder does not support multi-table statements MySqlCommandBuilder cannot operate on tables with no unique or key columns Parameter cannot be null Chaos isolation level is not supported Parameter is invalid. The connection is already open. Keyword not supported. Writing to the stream failed. Reading from the stream has failed. Packets larger than max_allowed_packet are not allowed. Unable to execute stored procedure '{0}'. same name are not supported. Keyword does not allow null values. Value has an unsupported format. Procedure or function '{0}' cannot be found in database '{1}'. Retrieving procedure metadata for {0} from server. Retrieving procedure metadata for {0} from procedure cache. Connection unexpectedly terminated. An incorrect response was received from the server. Canceling an active query is only supported on MySQL 5.0.0 and above. Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. Canceling an executing query requires MySQL 5.0 or higher. Nested transactions are not supported. The CommandText property has not been properly initialized. There was an error parsing the foreign key definition. This category includes a series of counters for MySQL. .NET Data Provider for MySQL The number of times a procedures metadata had to be queried from the server. Hard Procedure Queries The number of times a procedures metadata was retrieved from the client-side cache. Soft Procedure Queries Parameter '{0}' is not found but a parameter with the name '{1}' is found. Parameter names must include the leading parameter marker. Unable to connect to any of the specified MySQL hosts. Unable to retrieve stored procedure metadata for routine '{0}'. Either grant SELECT privilege to mysql.proc for this user or use "check parameters=false" with your connection string. Invalid attempt to call NextResult when the reader is closed. When calling stored procedures and 'Use Procedure Bodies' is false, all parameters must have their type explicitly set. error connecting: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached. Parameter '{0}' has already been defined. Parameter '{0}' must be defined. The object is not open or has been disposed. Multiple simultaneous connections or connections with different connection strings inside the same transaction are not currently supported. MySQL Connector/Net does not currently support distributed transactions. Fatal error encountered during command execution. Fatal error encountered during data read. Fatal error encountered attempting to read the resultset. Routine '{0}' cannot be found. Either check the spelling or make sure you have sufficient rights to execute the routine. Parameter '{0}' was not found during prepare. The requested column value could not be treated as or conveted to a Guid. Unable to derive stored routine parameters. The 'Parameters' information schema table is not available and access to the stored procedure body has been disabled. The default connection encoding was not found. Please report this as a bug along with your connection string and system details. Call to GetHostEntry failed after {0} while querying for hostname '{1}': SocketErrorCode={2}, ErrorCode={3}, NativeErrorCode={4}. An error occured attempting to enumerate the user-defined functions. Do you have SELECT privileges on the mysql.func table? The given value was not in a supported format. The host {0} does not support SSL connections. Could not find specified column in results: {0} You have specified an invalid column ordinal. Invalid attempt to read a prior column using SequentialAccess Invalid attempt to access a field before calling Read() Unable to start a second async operation while one is running. INTERNAL ERROR: More than one output parameter row detected. '{0}' is an illegal value for a boolean option. Connector/Net no longer supports server versions prior to 5.0 The requested value '{0}' is invalid for the given keyword '{1}'. {0}: Connection Closed {0}: Connection Opened: connection string = '{1}' {0}: Query Opened: {2} {0}: Resultset Opened: field(s) = {1}, affected rows = {2}, inserted id = {3} {0}: Query Closed {0}: Set Database: {1} {0}: Usage Advisor Warning: Query is using a bad index {0}: Usage Advisor Warning: Query does not use an index {0}: Resultset Closed. Total rows={1}, skipped rows={2}, size (bytes)={3} {0}: Usage Advisor Warning: Skipped {2} rows. Consider a more focused query. {0}: Usage Advisor Warning: The following columns were not accessed: {2} {0}: Usage Advisor Warning: The field '{2}' was converted to the following types: {3} {0}: Error encountered attempting to open result: Number={1}, Message={2} {0}: Error encountered during row fetch. Number = {1}, Message={2} {0}: MySql Warning: Level={1}, Code={2}, Message={3} Unable to trace. There are more than Int32.MaxValue connections in use. {0}: Statement prepared: sql='{1}', statement id={2} {0}: Statement closed: statement id = {1} {0}: Statement executed: statement id = {1} Unable to enable query analysis. Be sure the MySql.Data.EMTrace assembly is properly located and registered. keywords.txt;System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 {0}: Query Normalized: {2} Cannot retrieve Windows identity for current user. Connections that use IntegratedSecurity cannot be pooled. Use either 'ConnectionReset=true' or 'Pooling=false' in the connection string to fix. Attempt to call stored function '{0}' without specifying a return parameter Parameters can only be derived for commands using the StoredProcedure command type. Replicated connections allow only readonly statements. File based certificates are only supported when connecting to MySQL Server 5.1 or greater. Snapshot isolation level is not supported. mysql-connector-net-6.4.3/Source/MySql.Data/Properties/keywords.txt0000644000175000017500000000341111127003600026073 0ustar directhexdirecthexACCESSIBLE ADD ALL ALTER ANALYZE AND AS ASC ASENSITIVE BEFORE BETWEEN BIGINT BINARY BLOB BOTH BY CALL CASCADE CASE CHANGE CHAR CHARACTER CHECK COLLATE COLUMN CONDITION CONNECTION CONSTRAINT CONTINUE CONVERT CREATE CROSS CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURSOR DATABASE DATABASES DAY_HOUR DAY_MICROSECOND DAY_MINUTE DAY_SECOND DEC DECIMAL DECLARE DEFAULT DELAYED DELETE DESC DESCRIBE DETERMINISTIC DISTINCT DISTINCTROW DIV DOUBLE DROP DUAL EACH ELSE ELSEIF ENCLOSED ESCAPED EXISTS EXIT EXPLAIN FALSE FETCH FLOAT FLOAT4 FLOAT8 FOR FORCE FOREIGN FROM FULLTEXT GOTO GRANT GROUP HAVING HIGH_PRIORITY HOUR_MICROSECOND HOUR_MINUTE HOUR_SECOND IF IGNORE IN INDEX INFILE INNER INOUT INSENSITIVE INSERT INT INT1 INT2 INT3 INT4 INT8 INTEGER INTERVAL INTO IS ITERATE JOIN KEY KEYS KILL LABEL LEADING LEAVE LEFT LIKE LIMIT LINEAR LINES LOAD LOCALTIME LOCALTIMESTAMP LOCK LONG LONGBLOB LONGTEXT LOOP LOW_PRIORITY MASTER_SSL_VERIFY_SERVER_CERT MATCH MEDIUMBLOB MEDIUMINT MEDIUMTEXT MIDDLEINT MINUTE_MICROSECOND MINUTE_SECOND MOD MODIFIES NATURAL NOT NO_WRITE_TO_BINLOG NULL NUMERIC ON OPTIMIZE OPTION OPTIONALLY OR ORDER OUT OUTER OUTFILE PRECISION PRIMARY PROCEDURE PURGE RANGE READ READS READ_ONLY READ_WRITE REAL REFERENCES REGEXP RELEASE RENAME REPEAT REPLACE REQUIRE RESTRICT RETURN REVOKE RIGHT RLIKE SCHEMA SCHEMAS SECOND_MICROSECOND SELECT SENSITIVE SEPARATOR SET SHOW SMALLINT SPATIAL SPECIFIC SQL SQLEXCEPTION SQLSTATE SQLWARNING SQL_BIG_RESULT SQL_CALC_FOUND_ROWS SQL_SMALL_RESULT SSL STARTING STRAIGHT_JOIN TABLE TERMINATED THEN TINYBLOB TINYINT TINYTEXT TO TRAILING TRIGGER TRUE UNDO UNION UNIQUE UNLOCK UNSIGNED UPDATE UPGRADE USAGE USE USING UTC_DATE UTC_TIME UTC_TIMESTAMP VALUE VALUES VARBINARY VARCHAR VARCHARACTER VARYING WHEN WHERE WHILE WITH WRITE XOR YEAR_MONTH ZEROFILLmysql-connector-net-6.4.3/Source/MySql.Data/Properties/AssemblyInfo.cs0000644000175000017500000001063011127003600026406 0ustar directhexdirecthex// Copyright 2004,2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Security; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyDescription("ADO.Net driver for MySQL")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Oracle")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Copyright 2004, 2010, Oracle and/or its affiliates. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(false)] #if !CF [assembly: AssemblyTitle("MySql.Data.dll")] [assembly: AllowPartiallyTrustedCallers()] #else [assembly: AssemblyTitle("MySql.Data.CF.dll")] #endif #if CLR4 [assembly: SecurityRules(SecurityRuleSet.Level1)] #endif // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyName("ConnectorNet")] [assembly: InternalsVisibleTo("MySql.Data.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d973bda91f71752c78294126974a41a08643168271f65fc0fb3cd45f658da01fbca75ac74067d18e7afbf1467d7a519ce0248b13719717281bb4ddd4ecd71a580dfe0912dfc3690b1d24c7e1975bf7eed90e4ab14e10501eedf763bff8ac204f955c9c15c2cf4ebf6563d8320b6ea8d1ea3807623141f4b81ae30a6c886b3ee1")] [assembly: InternalsVisibleTo("MySql.Data.CF.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d973bda91f71752c78294126974a41a08643168271f65fc0fb3cd45f658da01fbca75ac74067d18e7afbf1467d7a519ce0248b13719717281bb4ddd4ecd71a580dfe0912dfc3690b1d24c7e1975bf7eed90e4ab14e10501eedf763bff8ac204f955c9c15c2cf4ebf6563d8320b6ea8d1ea3807623141f4b81ae30a6c886b3ee1")] #if CF [assembly: AssemblyFlags(AssemblyNameFlags.Retargetable)] #endifmysql-connector-net-6.4.3/Source/MySql.Data/Properties/ReservedWords.txt0000644000175000017500000000360711127003600027031 0ustar directhexdirecthexACCESSIBLE ADD ALL ALTER ANALYZE AND AS ASC ASENSITIVE BEFORE BETWEEN BIGINT BINARY BLOB BOTH BY CALL CASCADE CASE CHANGE CHAR CHARACTER CHECK COLLATE COLUMN CONDITION CONNECTION CONSTRAINT CONTINUE CONTRIBUTORS CONVERT CREATE CROSS CURRENT_DATE CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURSOR DATABASE DATABASES DAY_HOUR DAY_MICROSECOND DAY_MINUTE DAY_SECOND DEC DECIMAL DECLARE DEFAULT DELAYED DELETE DESC DESCRIBE DETERMINISTIC DISTINCT DISTINCTROW DIV DOUBLE DROP DUAL EACH ELSE ELSEIF ENCLOSED ESCAPED EXISTS EXIT EXPLAIN FALSE FETCH FLOAT FLOAT4 FLOAT8 FOR FORCE FOREIGN FROM FULLTEXT GRANT GROUP HAVING HIGH_PRIORITY HOUR_MICROSECOND HOUR_MINUTE HOUR_SECOND IF IGNORE IN INDEX INFILE INNER INOUT INSENSITIVE INSERT INT INT1 INT2 INT3 INT4 INT8 INTEGER INTERVAL INTO IS ITERATE JOIN KEY KEYS KILL LEADING LEAVE LEFT LIKE LIMIT LINEAR LINES LOAD LOCALTIME LOCALTIMESTAMP LOCK LONG LONGBLOB LONGTEXT LOOP LOW_PRIORITY MATCH MEDIUMBLOB MEDIUMINT MEDIUMTEXT MIDDLEINT MINUTE_MICROSECOND MINUTE_SECOND MOD MODIFIES NATURAL NOT NO_WRITE_TO_BINLOG NULL NUMERIC ON OPTIMIZE OPTION OPTIONALLY OR ORDER OUT OUTER OUTFILE PRECISION PRIMARY PROCEDURE PURGE RANGE READ READS READ_ONLY READ_WRITE REAL REFERENCES REGEXP RELEASE RENAME REPEAT REPLACE REQUIRE RESTRICT RETURN REVOKE RIGHT RLIKE SCHEMA SCHEMAS SECOND_MICROSECOND SELECT SENSITIVE SEPARATOR SET SHOW SMALLINT SPATIAL SPECIFIC SQL SQLEXCEPTION SQLSTATE SQLWARNING SQL_BIG_RESULT SQL_CALC_FOUND_ROWS SQL_SMALL_RESULT SSL STARTING STRAIGHT_JOIN TABLE TERMINATED THEN TINYBLOB TINYINT TINYTEXT TO TRAILING TRIGGER TRUE UNDO UNION UNIQUE UNLOCK UNSIGNED UPDATE UPGRADE USAGE USE USING UTC_DATE UTC_TIME UTC_TIMESTAMP VALUES VARBINARY VARCHAR VARCHARACTER VARYING WHEN WHERE WHILE WITH WRITE X509 XOR YEAR_MONTH ZEROFILL mysql-connector-net-6.4.3/Source/MySql.Data/MySqlPromotableTransaction.cs0000644000175000017500000001615711127003600027171 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Transactions; using System.Collections; using System.Collections.Generic; using System.Data; using System.Threading; namespace MySql.Data.MySqlClient { /// /// Represents a single(not nested) TransactionScope /// internal class MySqlTransactionScope { public MySqlConnection connection; public Transaction baseTransaction; public MySqlTransaction simpleTransaction; public int rollbackThreadId; public MySqlTransactionScope(MySqlConnection con, Transaction trans, MySqlTransaction simpleTransaction) { connection = con; baseTransaction = trans; this.simpleTransaction = simpleTransaction; } public void Rollback(SinglePhaseEnlistment singlePhaseEnlistment) { // prevent commands in main thread to run concurrently Driver driver = connection.driver; lock (driver) { rollbackThreadId = Thread.CurrentThread.ManagedThreadId; while (connection.Reader != null) { // wait for reader to finish. Maybe we should not wait // forever and cancel it after some time? System.Threading.Thread.Sleep(100); } simpleTransaction.Rollback(); singlePhaseEnlistment.Aborted(); DriverTransactionManager.RemoveDriverInTransaction(baseTransaction); driver.CurrentTransaction = null; if (connection.State == ConnectionState.Closed) connection.CloseFully(); rollbackThreadId = 0; } } public void SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment) { simpleTransaction.Commit(); singlePhaseEnlistment.Committed(); DriverTransactionManager.RemoveDriverInTransaction(baseTransaction); connection.driver.CurrentTransaction = null; if (connection.State == ConnectionState.Closed) connection.CloseFully(); } } internal sealed class MySqlPromotableTransaction : IPromotableSinglePhaseNotification, ITransactionPromoter { // Per-thread stack to manage nested transaction scopes [ThreadStatic] static Stack globalScopeStack; MySqlConnection connection; Transaction baseTransaction; Stack scopeStack; public MySqlPromotableTransaction(MySqlConnection connection, Transaction baseTransaction) { this.connection = connection; this.baseTransaction = baseTransaction; } public Transaction BaseTransaction { get { if (scopeStack.Count > 0) return scopeStack.Peek().baseTransaction; else return null; } } public bool InRollback { get { if (scopeStack.Count > 0) { MySqlTransactionScope currentScope = scopeStack.Peek(); if (currentScope.rollbackThreadId == Thread.CurrentThread.ManagedThreadId) { return true; } } return false; } } void IPromotableSinglePhaseNotification.Initialize() { string valueName = Enum.GetName( typeof(System.Transactions.IsolationLevel), baseTransaction.IsolationLevel); System.Data.IsolationLevel dataLevel = (System.Data.IsolationLevel)Enum.Parse( typeof(System.Data.IsolationLevel), valueName); MySqlTransaction simpleTransaction = connection.BeginTransaction(dataLevel); // We need to save the per-thread scope stack locally. // We cannot always use thread static variable in rollback: when scope // times out, rollback is issued by another thread. if (globalScopeStack == null) { globalScopeStack = new Stack(); } scopeStack = globalScopeStack; scopeStack.Push(new MySqlTransactionScope(connection, baseTransaction, simpleTransaction)); } void IPromotableSinglePhaseNotification.Rollback(SinglePhaseEnlistment singlePhaseEnlistment) { MySqlTransactionScope current = scopeStack.Peek(); current.Rollback(singlePhaseEnlistment); scopeStack.Pop(); } void IPromotableSinglePhaseNotification.SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment) { scopeStack.Pop().SinglePhaseCommit(singlePhaseEnlistment); } byte[] ITransactionPromoter.Promote() { throw new NotSupportedException(); } } internal class DriverTransactionManager { private static Hashtable driversInUse = new Hashtable(); public static Driver GetDriverInTransaction(Transaction transaction) { lock (driversInUse.SyncRoot) { Driver d = (Driver)driversInUse[transaction.GetHashCode()]; return d; } } public static void SetDriverInTransaction(Driver driver) { lock (driversInUse.SyncRoot) { driversInUse[driver.CurrentTransaction.BaseTransaction.GetHashCode()] = driver; } } public static void RemoveDriverInTransaction(Transaction transaction) { lock (driversInUse.SyncRoot) { driversInUse.Remove(transaction.GetHashCode()); } } } } mysql-connector-net-6.4.3/Source/MySql.Data/Field.cs0000644000175000017500000003332311127003600022706 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Text; using MySql.Data.Common; using MySql.Data.Types; using System.Globalization; using System.Text.RegularExpressions; using System; using System.Collections; using System.Collections.Generic; namespace MySql.Data.MySqlClient { internal enum ColumnFlags : int { NOT_NULL = 1, PRIMARY_KEY = 2, UNIQUE_KEY = 4, MULTIPLE_KEY = 8, BLOB = 16, UNSIGNED = 32, ZERO_FILL = 64, BINARY = 128, ENUM = 256, AUTO_INCREMENT = 512, TIMESTAMP = 1024, SET = 2048, NUMBER = 32768 } ; /// /// Summary description for Field. /// internal class MySqlField { #region Fields // public fields public string CatalogName; public int ColumnLength; public string ColumnName; public string OriginalColumnName; public string TableName; public string RealTableName; public string DatabaseName; public Encoding Encoding; public int maxLength; // protected fields protected ColumnFlags colFlags; protected int charSetIndex; protected byte precision; protected byte scale; protected MySqlDbType mySqlDbType; protected DBVersion connVersion; protected Driver driver; protected bool binaryOk; protected List typeConversions = new List(); #endregion public MySqlField(Driver driver) { this.driver = driver; connVersion = driver.Version; maxLength = 1; binaryOk = true; } #region Properties public int CharacterSetIndex { get { return charSetIndex; } set { charSetIndex = value; SetFieldEncoding(); } } public MySqlDbType Type { get { return mySqlDbType; } } public byte Precision { get { return precision; } set { precision = value; } } public byte Scale { get { return scale; } set { scale = value; } } public int MaxLength { get { return maxLength; } set { maxLength = value; } } public ColumnFlags Flags { get { return colFlags; } } public bool IsAutoIncrement { get { return (colFlags & ColumnFlags.AUTO_INCREMENT) > 0; } } public bool IsNumeric { get { return (colFlags & ColumnFlags.NUMBER) > 0; } } public bool AllowsNull { get { return (colFlags & ColumnFlags.NOT_NULL) == 0; } } public bool IsUnique { get { return (colFlags & ColumnFlags.UNIQUE_KEY) > 0; } } public bool IsPrimaryKey { get { return (colFlags & ColumnFlags.PRIMARY_KEY) > 0; } } public bool IsBlob { get { return (mySqlDbType >= MySqlDbType.TinyBlob && mySqlDbType <= MySqlDbType.Blob) || (mySqlDbType >= MySqlDbType.TinyText && mySqlDbType <= MySqlDbType.Text) || (colFlags & ColumnFlags.BLOB) > 0; } } public bool IsBinary { get { return binaryOk && (CharacterSetIndex == 63); } } public bool IsUnsigned { get { return (colFlags & ColumnFlags.UNSIGNED) > 0; } } public bool IsTextField { get { return Type == MySqlDbType.VarString || Type == MySqlDbType.VarChar || (IsBlob && !IsBinary); } } public int CharacterLength { get { return ColumnLength / MaxLength; } } public List TypeConversions { get { return typeConversions; } } #endregion public void SetTypeAndFlags(MySqlDbType type, ColumnFlags flags) { colFlags = flags; mySqlDbType = type; if (String.IsNullOrEmpty(TableName) && String.IsNullOrEmpty(RealTableName) && IsBinary && driver.Settings.FunctionsReturnString) { CharacterSetIndex = driver.ConnectionCharSetIndex; } // if our type is an unsigned number, then we need // to bump it up into our unsigned types // we're trusting that the server is not going to set the UNSIGNED // flag unless we are a number if (IsUnsigned) { switch (type) { case MySqlDbType.Byte: mySqlDbType = MySqlDbType.UByte; return; case MySqlDbType.Int16: mySqlDbType = MySqlDbType.UInt16; return; case MySqlDbType.Int24: mySqlDbType = MySqlDbType.UInt24; return; case MySqlDbType.Int32: mySqlDbType = MySqlDbType.UInt32; return; case MySqlDbType.Int64: mySqlDbType = MySqlDbType.UInt64; return; } } if (IsBlob) { // handle blob to UTF8 conversion if requested. This is only activated // on binary blobs if (IsBinary && driver.Settings.TreatBlobsAsUTF8) { bool convertBlob = false; Regex includeRegex = driver.Settings.GetBlobAsUTF8IncludeRegex(); Regex excludeRegex = driver.Settings.GetBlobAsUTF8ExcludeRegex(); if (includeRegex != null && includeRegex.IsMatch(ColumnName)) convertBlob = true; else if (includeRegex == null && excludeRegex != null && !excludeRegex.IsMatch(ColumnName)) convertBlob = true; if (convertBlob) { binaryOk = false; Encoding = System.Text.Encoding.GetEncoding("UTF-8"); charSetIndex = -1; // lets driver know we are in charge of encoding maxLength = 4; } } if (!IsBinary) { if (type == MySqlDbType.TinyBlob) mySqlDbType = MySqlDbType.TinyText; else if (type == MySqlDbType.MediumBlob) mySqlDbType = MySqlDbType.MediumText; else if (type == MySqlDbType.Blob) mySqlDbType = MySqlDbType.Text; else if (type == MySqlDbType.LongBlob) mySqlDbType = MySqlDbType.LongText; } } // now determine if we really should be binary if (driver.Settings.RespectBinaryFlags) CheckForExceptions(); if (Type == MySqlDbType.String && CharacterLength == 36 && !driver.Settings.OldGuids) mySqlDbType = MySqlDbType.Guid; if (!IsBinary) return; if (driver.Settings.RespectBinaryFlags) { if (type == MySqlDbType.String) mySqlDbType = MySqlDbType.Binary; else if (type == MySqlDbType.VarChar || type == MySqlDbType.VarString) mySqlDbType = MySqlDbType.VarBinary; } if (CharacterSetIndex == 63) CharacterSetIndex = driver.ConnectionCharSetIndex; if (Type == MySqlDbType.Binary && ColumnLength == 16 && driver.Settings.OldGuids) mySqlDbType = MySqlDbType.Guid; } public void AddTypeConversion(Type t) { if (TypeConversions.Contains(t)) return; TypeConversions.Add(t); } private void CheckForExceptions() { string colName = String.Empty; if (OriginalColumnName != null) colName = OriginalColumnName.ToUpper(CultureInfo.InvariantCulture); if (colName.StartsWith("CHAR(")) binaryOk = false; } public IMySqlValue GetValueObject() { IMySqlValue v = GetIMySqlValue(Type); if (v is MySqlByte && ColumnLength == 1 && driver.Settings.TreatTinyAsBoolean) { MySqlByte b = (MySqlByte)v; b.TreatAsBoolean = true; v = b; } else if (v is MySqlGuid) { MySqlGuid g = (MySqlGuid)v; g.OldGuids = driver.Settings.OldGuids; v = g; } return v; } public static IMySqlValue GetIMySqlValue(MySqlDbType type) { switch (type) { case MySqlDbType.Byte: return new MySqlByte(); case MySqlDbType.UByte: return new MySqlUByte(); case MySqlDbType.Int16: return new MySqlInt16(); case MySqlDbType.UInt16: return new MySqlUInt16(); case MySqlDbType.Int24: case MySqlDbType.Int32: case MySqlDbType.Year: return new MySqlInt32(type, true); case MySqlDbType.UInt24: case MySqlDbType.UInt32: return new MySqlUInt32(type, true); case MySqlDbType.Bit: return new MySqlBit(); case MySqlDbType.Int64: return new MySqlInt64(); case MySqlDbType.UInt64: return new MySqlUInt64(); case MySqlDbType.Time: return new MySqlTimeSpan(); case MySqlDbType.Date: case MySqlDbType.DateTime: case MySqlDbType.Newdate: case MySqlDbType.Timestamp: return new MySqlDateTime(type, true); case MySqlDbType.Decimal: case MySqlDbType.NewDecimal: return new MySqlDecimal(); case MySqlDbType.Float: return new MySqlSingle(); case MySqlDbType.Double: return new MySqlDouble(); case MySqlDbType.Set: case MySqlDbType.Enum: case MySqlDbType.String: case MySqlDbType.VarString: case MySqlDbType.VarChar: case MySqlDbType.Text: case MySqlDbType.TinyText: case MySqlDbType.MediumText: case MySqlDbType.LongText: case (MySqlDbType) Field_Type.NULL: return new MySqlString(type, true); case MySqlDbType.Geometry: case MySqlDbType.Blob: case MySqlDbType.MediumBlob: case MySqlDbType.LongBlob: case MySqlDbType.TinyBlob: case MySqlDbType.Binary: case MySqlDbType.VarBinary: return new MySqlBinary(type, true); case MySqlDbType.Guid: return new MySqlGuid(); default: throw new MySqlException("Unknown data type"); } } private void SetFieldEncoding() { Hashtable charSets = driver.CharacterSets; DBVersion version = driver.Version; if (charSets == null || CharacterSetIndex == -1) return; if (charSets[CharacterSetIndex] == null) return; CharacterSet cs = CharSetMap.GetCharacterSet(version, (string)charSets[CharacterSetIndex]); // starting with 6.0.4 utf8 has a maxlen of 4 instead of 3. The old // 3 byte utf8 is utf8mb3 if (cs.name.ToLower(System.Globalization.CultureInfo.InvariantCulture) == "utf-8" && version.Major >= 6) MaxLength = 4; else MaxLength = cs.byteCount; Encoding = CharSetMap.GetEncoding(version, (string)charSets[CharacterSetIndex]); } } } mysql-connector-net-6.4.3/Source/MySql.Data/SchemaProvider.cs0000644000175000017500000013761111127003600024603 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Data.Common; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using MySql.Data.Common; using MySql.Data.Types; using System.Collections.Specialized; using System.Collections; using System.Text.RegularExpressions; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { internal class SchemaProvider { protected MySqlConnection connection; public static string MetaCollection = "MetaDataCollections"; public SchemaProvider(MySqlConnection connectionToUse) { connection = connectionToUse; } public virtual DataTable GetSchema(string collection, String[] restrictions) { if (connection.State != ConnectionState.Open) throw new MySqlException("GetSchema can only be called on an open connection."); collection = collection.ToUpper(CultureInfo.InvariantCulture); DataTable dt = GetSchemaInternal(collection, restrictions); if (dt == null) throw new MySqlException("Invalid collection name"); return dt; } public virtual DataTable GetDatabases(string[] restrictions) { Regex regex = null; int caseSetting = Int32.Parse(connection.driver.Property("lower_case_table_names")); string sql = "SHOW DATABASES"; // if lower_case_table_names is zero, then case lookup should be sensitive // so we can use LIKE to do the matching. if (caseSetting == 0) { if (restrictions != null && restrictions.Length >= 1) sql = sql + " LIKE '" + restrictions[0] + "'"; } else if (restrictions != null && restrictions.Length >= 1 && restrictions[0] != null) regex = new Regex(restrictions[0], RegexOptions.IgnoreCase); MySqlDataAdapter da = new MySqlDataAdapter(sql, connection); DataTable dt = new DataTable(); da.Fill(dt); DataTable table = new DataTable("Databases"); table.Columns.Add("CATALOG_NAME", typeof (string)); table.Columns.Add("SCHEMA_NAME", typeof (string)); foreach (DataRow row in dt.Rows) { if (caseSetting != 0 && regex != null && !regex.Match(row[0].ToString()).Success) continue; DataRow newRow = table.NewRow(); newRow[1] = row[0]; table.Rows.Add(newRow); } return table; } public virtual DataTable GetTables(string[] restrictions) { DataTable dt = new DataTable("Tables"); dt.Columns.Add("TABLE_CATALOG", typeof (string)); dt.Columns.Add("TABLE_SCHEMA", typeof (string)); dt.Columns.Add("TABLE_NAME", typeof (string)); dt.Columns.Add("TABLE_TYPE", typeof (string)); dt.Columns.Add("ENGINE", typeof (string)); dt.Columns.Add("VERSION", typeof (ulong)); dt.Columns.Add("ROW_FORMAT", typeof (string)); dt.Columns.Add("TABLE_ROWS", typeof (ulong)); dt.Columns.Add("AVG_ROW_LENGTH", typeof (ulong)); dt.Columns.Add("DATA_LENGTH", typeof (ulong)); dt.Columns.Add("MAX_DATA_LENGTH", typeof (ulong)); dt.Columns.Add("INDEX_LENGTH", typeof (ulong)); dt.Columns.Add("DATA_FREE", typeof (ulong)); dt.Columns.Add("AUTO_INCREMENT", typeof (ulong)); dt.Columns.Add("CREATE_TIME", typeof (DateTime)); dt.Columns.Add("UPDATE_TIME", typeof (DateTime)); dt.Columns.Add("CHECK_TIME", typeof (DateTime)); dt.Columns.Add("TABLE_COLLATION", typeof (string)); dt.Columns.Add("CHECKSUM", typeof (ulong)); dt.Columns.Add("CREATE_OPTIONS", typeof (string)); dt.Columns.Add("TABLE_COMMENT", typeof (string)); // we have to new up a new restriction array here since // GetDatabases takes the database in the first slot string[] dbRestriction = new string[4]; if (restrictions != null && restrictions.Length >= 2) dbRestriction[0] = restrictions[1]; DataTable databases = GetDatabases(dbRestriction); if (restrictions != null) Array.Copy(restrictions, dbRestriction, Math.Min(dbRestriction.Length, restrictions.Length)); foreach (DataRow db in databases.Rows) { dbRestriction[1] = db["SCHEMA_NAME"].ToString(); FindTables(dt, dbRestriction); } return dt; } protected void QuoteDefaultValues(DataTable dt) { if (dt == null) return; if (!dt.Columns.Contains("COLUMN_DEFAULT")) return; foreach (DataRow row in dt.Rows) { object defaultValue = row["COLUMN_DEFAULT"]; if (MetaData.IsTextType(row["DATA_TYPE"].ToString())) row["COLUMN_DEFAULT"] = String.Format("'{0}'", defaultValue); } } public virtual DataTable GetColumns(string[] restrictions) { DataTable dt = new DataTable("Columns"); dt.Columns.Add("TABLE_CATALOG", typeof (string)); dt.Columns.Add("TABLE_SCHEMA", typeof (string)); dt.Columns.Add("TABLE_NAME", typeof (string)); dt.Columns.Add("COLUMN_NAME", typeof (string)); dt.Columns.Add("ORDINAL_POSITION", typeof (ulong)); dt.Columns.Add("COLUMN_DEFAULT", typeof (string)); dt.Columns.Add("IS_NULLABLE", typeof (string)); dt.Columns.Add("DATA_TYPE", typeof (string)); dt.Columns.Add("CHARACTER_MAXIMUM_LENGTH", typeof (ulong)); dt.Columns.Add("CHARACTER_OCTET_LENGTH", typeof (ulong)); dt.Columns.Add("NUMERIC_PRECISION", typeof (ulong)); dt.Columns.Add("NUMERIC_SCALE", typeof (ulong)); dt.Columns.Add("CHARACTER_SET_NAME", typeof (string)); dt.Columns.Add("COLLATION_NAME", typeof (string)); dt.Columns.Add("COLUMN_TYPE", typeof (string)); dt.Columns.Add("COLUMN_KEY", typeof (string)); dt.Columns.Add("EXTRA", typeof (string)); dt.Columns.Add("PRIVILEGES", typeof (string)); dt.Columns.Add("COLUMN_COMMENT", typeof (string)); // we don't allow restricting on table type here string columnName = null; if (restrictions != null && restrictions.Length == 4) { columnName = restrictions[3]; restrictions[3] = null; } DataTable tables = GetTables(restrictions); foreach (DataRow row in tables.Rows) LoadTableColumns(dt, row["TABLE_SCHEMA"].ToString(), row["TABLE_NAME"].ToString(), columnName); QuoteDefaultValues(dt); return dt; } private void LoadTableColumns(DataTable dt, string schema, string tableName, string columnRestriction) { string sql = String.Format("SHOW FULL COLUMNS FROM `{0}`.`{1}`", schema, tableName); MySqlCommand cmd = new MySqlCommand(sql, connection); int pos = 1; using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { string colName = reader.GetString(0); if (columnRestriction != null && colName != columnRestriction) continue; DataRow row = dt.NewRow(); row["TABLE_CATALOG"] = DBNull.Value; row["TABLE_SCHEMA"] = schema; row["TABLE_NAME"] = tableName; row["COLUMN_NAME"] = colName; row["ORDINAL_POSITION"] = pos++; row["COLUMN_DEFAULT"] = reader.GetValue(5); row["IS_NULLABLE"] = reader.GetString(3); row["DATA_TYPE"] = reader.GetString(1); row["CHARACTER_MAXIMUM_LENGTH"] = DBNull.Value; row["CHARACTER_OCTET_LENGTH"] = DBNull.Value; row["NUMERIC_PRECISION"] = DBNull.Value; row["NUMERIC_SCALE"] = DBNull.Value; row["CHARACTER_SET_NAME"] = reader.GetValue(2); row["COLLATION_NAME"] = row["CHARACTER_SET_NAME"]; row["COLUMN_TYPE"] = reader.GetString(1); row["COLUMN_KEY"] = reader.GetString(4); row["EXTRA"] = reader.GetString(6); row["PRIVILEGES"] = reader.GetString(7); row["COLUMN_COMMENT"] = reader.GetString(8); ParseColumnRow(row); dt.Rows.Add(row); } } } private static void ParseColumnRow(DataRow row) { // first parse the character set name string charset = row["CHARACTER_SET_NAME"].ToString(); int index = charset.IndexOf('_'); if (index != -1) row["CHARACTER_SET_NAME"] = charset.Substring(0, index); // now parse the data type string dataType = row["DATA_TYPE"].ToString(); index = dataType.IndexOf('('); if (index == -1) return; row["DATA_TYPE"] = dataType.Substring(0, index); int stop = dataType.IndexOf(')', index); string dataLen = dataType.Substring(index + 1, stop - (index + 1)); string lowerType = row["DATA_TYPE"].ToString().ToLower(); if (lowerType == "char" || lowerType == "varchar") row["CHARACTER_MAXIMUM_LENGTH"] = dataLen; else if (lowerType == "real" || lowerType == "decimal") { string[] lenparts = dataLen.Split(new char[] {','}); row["NUMERIC_PRECISION"] = lenparts[0]; if (lenparts.Length == 2) row["NUMERIC_SCALE"] = lenparts[1]; } } public virtual DataTable GetIndexes(string[] restrictions) { DataTable dt = new DataTable("Indexes"); dt.Columns.Add("INDEX_CATALOG", typeof (string)); dt.Columns.Add("INDEX_SCHEMA", typeof (string)); dt.Columns.Add("INDEX_NAME", typeof (string)); dt.Columns.Add("TABLE_NAME", typeof (string)); dt.Columns.Add("UNIQUE", typeof (bool)); dt.Columns.Add("PRIMARY", typeof (bool)); dt.Columns.Add("TYPE", typeof(string)); dt.Columns.Add("COMMENT", typeof(string)); // Get the list of tables first int max = restrictions == null ? 4 : restrictions.Length; string[] tableRestrictions = new string[Math.Max(max, 4)]; if (restrictions != null) restrictions.CopyTo(tableRestrictions, 0); tableRestrictions[3] = "BASE TABLE"; DataTable tables = GetTables(tableRestrictions); foreach (DataRow table in tables.Rows) { string sql = String.Format("SHOW INDEX FROM `{0}`.`{1}`", MySqlHelper.DoubleQuoteString((string)table["TABLE_SCHEMA"]), MySqlHelper.DoubleQuoteString((string)table["TABLE_NAME"])); MySqlDataAdapter da = new MySqlDataAdapter(sql, connection); DataTable indexes = new DataTable(); da.Fill(indexes); foreach (DataRow index in indexes.Rows) { long seq_index = (long) index["SEQ_IN_INDEX"]; if (seq_index != 1) continue; if (restrictions != null && restrictions.Length == 4 && restrictions[3] != null && !index["KEY_NAME"].Equals(restrictions[3])) continue; DataRow row = dt.NewRow(); row["INDEX_CATALOG"] = null; row["INDEX_SCHEMA"] = table["TABLE_SCHEMA"]; row["INDEX_NAME"] = index["KEY_NAME"]; row["TABLE_NAME"] = index["TABLE"]; row["UNIQUE"] = (long) index["NON_UNIQUE"] == 0; row["PRIMARY"] = index["KEY_NAME"].Equals("PRIMARY"); row["TYPE"] = index["INDEX_TYPE"]; row["COMMENT"] = index["COMMENT"]; dt.Rows.Add(row); } } return dt; } public virtual DataTable GetIndexColumns(string[] restrictions) { DataTable dt = new DataTable("IndexColumns"); dt.Columns.Add("INDEX_CATALOG", typeof (string)); dt.Columns.Add("INDEX_SCHEMA", typeof (string)); dt.Columns.Add("INDEX_NAME", typeof (string)); dt.Columns.Add("TABLE_NAME", typeof (string)); dt.Columns.Add("COLUMN_NAME", typeof (string)); dt.Columns.Add("ORDINAL_POSITION", typeof (int)); dt.Columns.Add("SORT_ORDER", typeof(string)); int max = restrictions == null ? 4 : restrictions.Length; string[] tableRestrictions = new string[Math.Max(max, 4)]; if (restrictions != null) restrictions.CopyTo(tableRestrictions, 0); tableRestrictions[3] = "BASE TABLE"; DataTable tables = GetTables(tableRestrictions); foreach (DataRow table in tables.Rows) { string sql = String.Format("SHOW INDEX FROM `{0}`.`{1}`", table["TABLE_SCHEMA"], table["TABLE_NAME"]); MySqlCommand cmd = new MySqlCommand(sql, connection); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { string key_name = GetString(reader, reader.GetOrdinal("KEY_NAME")); string col_name = GetString(reader, reader.GetOrdinal("COLUMN_NAME")); if (restrictions != null) { if (restrictions.Length >= 4 && restrictions[3] != null && key_name != restrictions[3]) continue; if (restrictions.Length >= 5 && restrictions[4] != null && col_name != restrictions[4]) continue; } DataRow row = dt.NewRow(); row["INDEX_CATALOG"] = null; row["INDEX_SCHEMA"] = table["TABLE_SCHEMA"]; row["INDEX_NAME"] = key_name; row["TABLE_NAME"] = GetString(reader, reader.GetOrdinal("TABLE")); row["COLUMN_NAME"] = col_name; row["ORDINAL_POSITION"] = reader.GetValue(reader.GetOrdinal("SEQ_IN_INDEX")); row["SORT_ORDER"] = reader.GetString("COLLATION"); dt.Rows.Add(row); } } } return dt; } public virtual DataTable GetForeignKeys(string[] restrictions) { DataTable dt = new DataTable("Foreign Keys"); dt.Columns.Add("CONSTRAINT_CATALOG", typeof (string)); dt.Columns.Add("CONSTRAINT_SCHEMA", typeof (string)); dt.Columns.Add("CONSTRAINT_NAME", typeof (string)); dt.Columns.Add("TABLE_CATALOG", typeof(string)); dt.Columns.Add("TABLE_SCHEMA", typeof (string)); dt.Columns.Add("TABLE_NAME", typeof (string)); dt.Columns.Add("MATCH_OPTION", typeof(string)); dt.Columns.Add("UPDATE_RULE", typeof(string)); dt.Columns.Add("DELETE_RULE", typeof(string)); dt.Columns.Add("REFERENCED_TABLE_CATALOG", typeof (string)); dt.Columns.Add("REFERENCED_TABLE_SCHEMA", typeof (string)); dt.Columns.Add("REFERENCED_TABLE_NAME", typeof (string)); // first we use our restrictions to get a list of tables that should be // consulted. We save the keyname restriction since GetTables doesn't // understand that. string keyName = null; if (restrictions != null && restrictions.Length >= 4) { keyName = restrictions[3]; restrictions[3] = null; } DataTable tables = GetTables(restrictions); // now for each table retrieved, we call our helper function to // parse it's foreign keys foreach (DataRow table in tables.Rows) GetForeignKeysOnTable(dt, table, keyName, false); return dt; } public virtual DataTable GetForeignKeyColumns(string[] restrictions) { DataTable dt = new DataTable("Foreign Keys"); dt.Columns.Add("CONSTRAINT_CATALOG", typeof(string)); dt.Columns.Add("CONSTRAINT_SCHEMA", typeof(string)); dt.Columns.Add("CONSTRAINT_NAME", typeof(string)); dt.Columns.Add("TABLE_CATALOG", typeof(string)); dt.Columns.Add("TABLE_SCHEMA", typeof(string)); dt.Columns.Add("TABLE_NAME", typeof(string)); dt.Columns.Add("COLUMN_NAME", typeof(string)); dt.Columns.Add("ORDINAL_POSITION", typeof(int)); dt.Columns.Add("REFERENCED_TABLE_CATALOG", typeof(string)); dt.Columns.Add("REFERENCED_TABLE_SCHEMA", typeof(string)); dt.Columns.Add("REFERENCED_TABLE_NAME", typeof(string)); dt.Columns.Add("REFERENCED_COLUMN_NAME", typeof(string)); // first we use our restrictions to get a list of tables that should be // consulted. We save the keyname restriction since GetTables doesn't // understand that. string keyName = null; if (restrictions != null && restrictions.Length >= 4) { keyName = restrictions[3]; restrictions[3] = null; } DataTable tables = GetTables(restrictions); // now for each table retrieved, we call our helper function to // parse it's foreign keys foreach (DataRow table in tables.Rows) GetForeignKeysOnTable(dt, table, keyName, true); return dt; } private string GetSqlMode() { MySqlCommand cmd = new MySqlCommand("SELECT @@SQL_MODE", connection); return cmd.ExecuteScalar().ToString(); } #region Foreign Key routines /// /// GetForeignKeysOnTable retrieves the foreign keys on the given table. /// Since MySQL supports foreign keys on versions prior to 5.0, we can't use /// information schema. MySQL also does not include any type of SHOW command /// for foreign keys so we have to resort to use SHOW CREATE TABLE and parsing /// the output. /// /// The table to store the key info in. /// The table to get the foeign key info for. /// Only get foreign keys that match this name. /// Should column information be included in the table. private void GetForeignKeysOnTable(DataTable fkTable, DataRow tableToParse, string filterName, bool includeColumns) { string sqlMode = GetSqlMode(); if (filterName != null) filterName = filterName.ToLower(CultureInfo.InvariantCulture); string sql = string.Format("SHOW CREATE TABLE `{0}`.`{1}`", tableToParse["TABLE_SCHEMA"], tableToParse["TABLE_NAME"]); string lowerBody = null, body = null; MySqlCommand cmd = new MySqlCommand(sql, connection); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); body = reader.GetString(1); lowerBody = body.ToLower(CultureInfo.InvariantCulture); } MySqlTokenizer tokenizer = new MySqlTokenizer(lowerBody); tokenizer.AnsiQuotes = sqlMode.IndexOf("ANSI_QUOTES") != -1; tokenizer.BackslashEscapes = sqlMode.IndexOf("NO_BACKSLASH_ESCAPES") != -1; while (true) { string token = tokenizer.NextToken(); // look for a starting contraint while (token != null && (token != "constraint" || tokenizer.Quoted)) token = tokenizer.NextToken(); if (token == null) break; ParseConstraint(fkTable, tableToParse, tokenizer, includeColumns); } } private static void ParseConstraint(DataTable fkTable, DataRow table, MySqlTokenizer tokenizer, bool includeColumns) { string name = tokenizer.NextToken(); DataRow row = fkTable.NewRow(); // make sure this constraint is a FK string token = tokenizer.NextToken(); if (token != "foreign" || tokenizer.Quoted) return; tokenizer.NextToken(); // read off the 'KEY' symbol tokenizer.NextToken(); // read off the '(' symbol row["CONSTRAINT_CATALOG"] = table["TABLE_CATALOG"]; row["CONSTRAINT_SCHEMA"] = table["TABLE_SCHEMA"]; row["TABLE_CATALOG"] = table["TABLE_CATALOG"]; row["TABLE_SCHEMA"] = table["TABLE_SCHEMA"]; row["TABLE_NAME"] = table["TABLE_NAME"]; row["REFERENCED_TABLE_CATALOG"] = null; row["CONSTRAINT_NAME"] = name.Trim(new char[] { '\'', '`' }); ArrayList srcColumns = includeColumns ? ParseColumns(tokenizer) : null; // now look for the references section while (token != "references" || tokenizer.Quoted) token = tokenizer.NextToken(); string target1 = tokenizer.NextToken(); string target2 = tokenizer.NextToken(); if (target2.StartsWith(".")) { row["REFERENCED_TABLE_SCHEMA"] = target1; row["REFERENCED_TABLE_NAME"] = target2.Substring(1).Trim(new char[] { '\'', '`' }); tokenizer.NextToken(); // read off the '(' } else { row["REFERENCED_TABLE_SCHEMA"] = table["TABLE_SCHEMA"]; row["REFERENCED_TABLE_NAME"] = target1.Substring(1).Trim(new char[] { '\'', '`' }); ; } // if we are supposed to include columns, read the target columns ArrayList targetColumns = includeColumns ? ParseColumns(tokenizer) : null; if (includeColumns) ProcessColumns(fkTable, row, srcColumns, targetColumns); else fkTable.Rows.Add(row); } private static ArrayList ParseColumns(MySqlTokenizer tokenizer) { ArrayList sc = new ArrayList(); string token = tokenizer.NextToken(); while (token != ")") { if (token != ",") sc.Add(token); token = tokenizer.NextToken(); } return sc; } private static void ProcessColumns(DataTable fkTable, DataRow row, ArrayList srcColumns, ArrayList targetColumns) { for (int i = 0; i < srcColumns.Count; i++) { DataRow newRow = fkTable.NewRow(); newRow.ItemArray = row.ItemArray; newRow["COLUMN_NAME"] = (string)srcColumns[i]; newRow["ORDINAL_POSITION"] = i; newRow["REFERENCED_COLUMN_NAME"] = (string)targetColumns[i]; fkTable.Rows.Add(newRow); } } #endregion public virtual DataTable GetUsers(string[] restrictions) { StringBuilder sb = new StringBuilder("SELECT Host, User FROM mysql.user"); if (restrictions != null && restrictions.Length > 0) sb.AppendFormat(CultureInfo.InvariantCulture, " WHERE User LIKE '{0}'", restrictions[0]); MySqlDataAdapter da = new MySqlDataAdapter(sb.ToString(), connection); DataTable dt = new DataTable(); da.Fill(dt); dt.TableName = "Users"; dt.Columns[0].ColumnName = "HOST"; dt.Columns[1].ColumnName = "USERNAME"; return dt; } public virtual DataTable GetProcedures(string[] restrictions) { DataTable dt = new DataTable("Procedures"); dt.Columns.Add(new DataColumn("SPECIFIC_NAME", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_CATALOG", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_SCHEMA", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_NAME", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_TYPE", typeof(string))); dt.Columns.Add(new DataColumn("DTD_IDENTIFIER", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_BODY", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_DEFINITION", typeof(string))); dt.Columns.Add(new DataColumn("EXTERNAL_NAME", typeof(string))); dt.Columns.Add(new DataColumn("EXTERNAL_LANGUAGE", typeof(string))); dt.Columns.Add(new DataColumn("PARAMETER_STYLE", typeof(string))); dt.Columns.Add(new DataColumn("IS_DETERMINISTIC", typeof(string))); dt.Columns.Add(new DataColumn("SQL_DATA_ACCESS", typeof(string))); dt.Columns.Add(new DataColumn("SQL_PATH", typeof(string))); dt.Columns.Add(new DataColumn("SECURITY_TYPE", typeof(string))); dt.Columns.Add(new DataColumn("CREATED", typeof(DateTime))); dt.Columns.Add(new DataColumn("LAST_ALTERED", typeof(DateTime))); dt.Columns.Add(new DataColumn("SQL_MODE", typeof(string))); dt.Columns.Add(new DataColumn("ROUTINE_COMMENT", typeof(string))); dt.Columns.Add(new DataColumn("DEFINER", typeof(string))); StringBuilder sql = new StringBuilder("SELECT * FROM mysql.proc WHERE 1=1"); if (restrictions != null) { if (restrictions.Length >= 2 && restrictions[1] != null) sql.AppendFormat(CultureInfo.InvariantCulture, " AND db LIKE '{0}'", restrictions[1]); if (restrictions.Length >= 3 && restrictions[2] != null) sql.AppendFormat(CultureInfo.InvariantCulture, " AND name LIKE '{0}'", restrictions[2]); if (restrictions.Length >= 4 && restrictions[3] != null) sql.AppendFormat(CultureInfo.InvariantCulture, " AND type LIKE '{0}'", restrictions[3]); } MySqlCommand cmd = new MySqlCommand(sql.ToString(), connection); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { DataRow row = dt.NewRow(); row["SPECIFIC_NAME"] = reader.GetString("specific_name"); row["ROUTINE_CATALOG"] = DBNull.Value; row["ROUTINE_SCHEMA"] = reader.GetString("db"); row["ROUTINE_NAME"] = reader.GetString("name"); string routineType = reader.GetString("type"); row["ROUTINE_TYPE"] = routineType; row["DTD_IDENTIFIER"] = routineType.ToLower(CultureInfo.InvariantCulture) == "function" ? (object)reader.GetString("returns") : DBNull.Value; row["ROUTINE_BODY"] = "SQL"; row["ROUTINE_DEFINITION"] = reader.GetString("body"); row["EXTERNAL_NAME"] = DBNull.Value; row["EXTERNAL_LANGUAGE"] = DBNull.Value; row["PARAMETER_STYLE"] = "SQL"; row["IS_DETERMINISTIC"] = reader.GetString("is_deterministic"); row["SQL_DATA_ACCESS"] = reader.GetString("sql_data_access"); row["SQL_PATH"] = DBNull.Value; row["SECURITY_TYPE"] = reader.GetString("security_type"); row["CREATED"] = reader.GetDateTime("created"); row["LAST_ALTERED"] = reader.GetDateTime("modified"); row["SQL_MODE"] = reader.GetString("sql_mode"); row["ROUTINE_COMMENT"] = reader.GetString("comment"); row["DEFINER"] = reader.GetString("definer"); dt.Rows.Add(row); } } return dt; } protected virtual DataTable GetCollections() { object[][] collections = new object[][] { new object[] {"MetaDataCollections", 0, 0}, new object[] {"DataSourceInformation", 0, 0}, new object[] {"DataTypes", 0, 0}, new object[] {"Restrictions", 0, 0}, new object[] {"ReservedWords", 0, 0}, new object[] {"Databases", 1, 1}, new object[] {"Tables", 4, 2}, new object[] {"Columns", 4, 4}, new object[] {"Users", 1, 1}, new object[] {"Foreign Keys", 4, 3}, new object[] {"IndexColumns", 5, 4}, new object[] {"Indexes", 4, 3}, new object[] {"Foreign Key Columns", 4, 3}, new object[] {"UDF", 1, 1} }; DataTable dt = new DataTable("MetaDataCollections"); dt.Columns.Add(new DataColumn("CollectionName", typeof (string))); dt.Columns.Add(new DataColumn("NumberOfRestrictions", typeof(int))); dt.Columns.Add(new DataColumn("NumberOfIdentifierParts", typeof (int))); FillTable(dt, collections); return dt; } private DataTable GetDataSourceInformation() { #if CF throw new NotSupportedException(); #else DataTable dt = new DataTable("DataSourceInformation"); dt.Columns.Add("CompositeIdentifierSeparatorPattern", typeof (string)); dt.Columns.Add("DataSourceProductName", typeof (string)); dt.Columns.Add("DataSourceProductVersion", typeof (string)); dt.Columns.Add("DataSourceProductVersionNormalized", typeof (string)); dt.Columns.Add("GroupByBehavior", typeof (GroupByBehavior)); dt.Columns.Add("IdentifierPattern", typeof (string)); dt.Columns.Add("IdentifierCase", typeof (IdentifierCase)); dt.Columns.Add("OrderByColumnsInSelect", typeof (bool)); dt.Columns.Add("ParameterMarkerFormat", typeof (string)); dt.Columns.Add("ParameterMarkerPattern", typeof (string)); dt.Columns.Add("ParameterNameMaxLength", typeof (int)); dt.Columns.Add("ParameterNamePattern", typeof (string)); dt.Columns.Add("QuotedIdentifierPattern", typeof (string)); dt.Columns.Add("QuotedIdentifierCase", typeof (IdentifierCase)); dt.Columns.Add("StatementSeparatorPattern", typeof (string)); dt.Columns.Add("StringLiteralPattern", typeof (string)); dt.Columns.Add("SupportedJoinOperators", typeof (SupportedJoinOperators)); DBVersion v = connection.driver.Version; string ver = String.Format("{0:0}.{1:0}.{2:0}", v.Major, v.Minor, v.Build); DataRow row = dt.NewRow(); row["CompositeIdentifierSeparatorPattern"] = "\\."; row["DataSourceProductName"] = "MySQL"; row["DataSourceProductVersion"] = connection.ServerVersion; row["DataSourceProductVersionNormalized"] = ver; row["GroupByBehavior"] = GroupByBehavior.Unrelated; row["IdentifierPattern"] = @"(^\`\p{Lo}\p{Lu}\p{Ll}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Nd}@$#_]*$)|(^\`[^\`\0]|\`\`+\`$)|(^\"" + [^\""\0]|\""\""+\""$)"; row["IdentifierCase"] = IdentifierCase.Insensitive; row["OrderByColumnsInSelect"] = false; row["ParameterMarkerFormat"] = "{0}"; row["ParameterMarkerPattern"] = "(@[A-Za-z0-9_$#]*)"; row["ParameterNameMaxLength"] = 128; row["ParameterNamePattern"] = @"^[\p{Lo}\p{Lu}\p{Ll}\p{Lm}_@#][\p{Lo}\p{Lu}\p{Ll}\p{Lm}\p{Nd}\uff3f_@#\$]*(?=\s+|$)"; row["QuotedIdentifierPattern"] = @"(([^\`]|\`\`)*)"; row["QuotedIdentifierCase"] = IdentifierCase.Sensitive; row["StatementSeparatorPattern"] = ";"; row["StringLiteralPattern"] = "'(([^']|'')*)'"; row["SupportedJoinOperators"] = 15; dt.Rows.Add(row); return dt; #endif } private static DataTable GetDataTypes() { DataTable dt = new DataTable("DataTypes"); dt.Columns.Add(new DataColumn("TypeName", typeof (string))); dt.Columns.Add(new DataColumn("ProviderDbType", typeof (int))); dt.Columns.Add(new DataColumn("ColumnSize", typeof (long))); dt.Columns.Add(new DataColumn("CreateFormat", typeof (string))); dt.Columns.Add(new DataColumn("CreateParameters", typeof (string))); dt.Columns.Add(new DataColumn("DataType", typeof (string))); dt.Columns.Add(new DataColumn("IsAutoincrementable", typeof (bool))); dt.Columns.Add(new DataColumn("IsBestMatch", typeof (bool))); dt.Columns.Add(new DataColumn("IsCaseSensitive", typeof (bool))); dt.Columns.Add(new DataColumn("IsFixedLength", typeof (bool))); dt.Columns.Add(new DataColumn("IsFixedPrecisionScale", typeof (bool))); dt.Columns.Add(new DataColumn("IsLong", typeof (bool))); dt.Columns.Add(new DataColumn("IsNullable", typeof (bool))); dt.Columns.Add(new DataColumn("IsSearchable", typeof (bool))); dt.Columns.Add(new DataColumn("IsSearchableWithLike", typeof (bool))); dt.Columns.Add(new DataColumn("IsUnsigned", typeof (bool))); dt.Columns.Add(new DataColumn("MaximumScale", typeof (short))); dt.Columns.Add(new DataColumn("MinimumScale", typeof (short))); dt.Columns.Add(new DataColumn("IsConcurrencyType", typeof (bool))); dt.Columns.Add(new DataColumn("IsLiteralSupported", typeof (bool))); dt.Columns.Add(new DataColumn("LiteralPrefix", typeof (string))); dt.Columns.Add(new DataColumn("LiteralSuffix", typeof (string))); dt.Columns.Add(new DataColumn("NativeDataType", typeof (string))); // have each one of the types contribute to the datatypes collection MySqlBit.SetDSInfo(dt); MySqlBinary.SetDSInfo(dt); MySqlDateTime.SetDSInfo(dt); MySqlTimeSpan.SetDSInfo(dt); MySqlString.SetDSInfo(dt); MySqlDouble.SetDSInfo(dt); MySqlSingle.SetDSInfo(dt); MySqlByte.SetDSInfo(dt); MySqlInt16.SetDSInfo(dt); MySqlInt32.SetDSInfo(dt); MySqlInt64.SetDSInfo(dt); MySqlDecimal.SetDSInfo(dt); MySqlUByte.SetDSInfo(dt); MySqlUInt16.SetDSInfo(dt); MySqlUInt32.SetDSInfo(dt); MySqlUInt64.SetDSInfo(dt); return dt; } protected virtual DataTable GetRestrictions() { object[][] restrictions = new object[][] { new object[] {"Users", "Name", "", 0}, new object[] {"Databases", "Name", "", 0}, new object[] {"Tables", "Database", "", 0}, new object[] {"Tables", "Schema", "", 1}, new object[] {"Tables", "Table", "", 2}, new object[] {"Tables", "TableType", "", 3}, new object[] {"Columns", "Database", "", 0}, new object[] {"Columns", "Schema", "", 1}, new object[] {"Columns", "Table", "", 2}, new object[] {"Columns", "Column", "", 3}, new object[] {"Indexes", "Database", "", 0}, new object[] {"Indexes", "Schema", "", 1}, new object[] {"Indexes", "Table", "", 2}, new object[] {"Indexes", "Name", "", 3}, new object[] {"IndexColumns", "Database", "", 0}, new object[] {"IndexColumns", "Schema", "", 1}, new object[] {"IndexColumns", "Table", "", 2}, new object[] {"IndexColumns", "ConstraintName", "", 3}, new object[] {"IndexColumns", "Column", "", 4}, new object[] {"Foreign Keys", "Database", "", 0}, new object[] {"Foreign Keys", "Schema", "", 1}, new object[] {"Foreign Keys", "Table", "", 2}, new object[] {"Foreign Keys", "Constraint Name", "", 3}, new object[] {"Foreign Key Columns", "Catalog", "", 0}, new object[] {"Foreign Key Columns", "Schema", "", 1}, new object[] {"Foreign Key Columns", "Table", "", 2}, new object[] {"Foreign Key Columns", "Constraint Name", "", 3}, new object[] {"UDF", "Name", "", 0} }; DataTable dt = new DataTable("Restrictions"); dt.Columns.Add(new DataColumn("CollectionName", typeof (string))); dt.Columns.Add(new DataColumn("RestrictionName", typeof (string))); dt.Columns.Add(new DataColumn("RestrictionDefault", typeof (string))); dt.Columns.Add(new DataColumn("RestrictionNumber", typeof (int))); FillTable(dt, restrictions); return dt; } private static DataTable GetReservedWords() { DataTable dt = new DataTable("ReservedWords"); dt.Columns.Add(new DataColumn(DbMetaDataColumnNames.ReservedWord, typeof(string))); Stream str = Assembly.GetExecutingAssembly().GetManifestResourceStream( "MySql.Data.MySqlClient.Properties.ReservedWords.txt"); StreamReader sr = new StreamReader(str); string line = sr.ReadLine(); while (line != null) { string[] keywords = line.Split(new char[] {' '}); foreach (string s in keywords) { if (String.IsNullOrEmpty(s)) continue; DataRow row = dt.NewRow(); row[0] = s; dt.Rows.Add(row); } line = sr.ReadLine(); } sr.Close(); str.Close(); return dt; } protected static void FillTable(DataTable dt, object[][] data) { foreach (object[] dataItem in data) { DataRow row = dt.NewRow(); for (int i = 0; i < dataItem.Length; i++) row[i] = dataItem[i]; dt.Rows.Add(row); } } private void FindTables(DataTable schemaTable, string[] restrictions) { StringBuilder sql = new StringBuilder(); StringBuilder where = new StringBuilder(); sql.AppendFormat(CultureInfo.InvariantCulture, "SHOW TABLE STATUS FROM `{0}`", restrictions[1]); if (restrictions != null && restrictions.Length >= 3 && restrictions[2] != null) where.AppendFormat(CultureInfo.InvariantCulture, " LIKE '{0}'", restrictions[2]); sql.Append(where.ToString()); string table_type = restrictions[1].ToLower() == "information_schema" ? "SYSTEM VIEW" : "BASE TABLE"; MySqlCommand cmd = new MySqlCommand(sql.ToString(), connection); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { DataRow row = schemaTable.NewRow(); row["TABLE_CATALOG"] = null; row["TABLE_SCHEMA"] = restrictions[1]; row["TABLE_NAME"] = reader.GetString(0); row["TABLE_TYPE"] = table_type; row["ENGINE"] = GetString(reader, 1); row["VERSION"] = reader.GetValue(2); row["ROW_FORMAT"] = GetString(reader, 3); row["TABLE_ROWS"] = reader.GetValue(4); row["AVG_ROW_LENGTH"] = reader.GetValue(5); row["DATA_LENGTH"] = reader.GetValue(6); row["MAX_DATA_LENGTH"] = reader.GetValue(7); row["INDEX_LENGTH"] = reader.GetValue(8); row["DATA_FREE"] = reader.GetValue(9); row["AUTO_INCREMENT"] = reader.GetValue(10); row["CREATE_TIME"] = reader.GetValue(11); row["UPDATE_TIME"] = reader.GetValue(12); row["CHECK_TIME"] = reader.GetValue(13); row["TABLE_COLLATION"] = GetString(reader, 14); row["CHECKSUM"] = reader.GetValue(15); row["CREATE_OPTIONS"] = GetString(reader, 16); row["TABLE_COMMENT"] = GetString(reader, 17); schemaTable.Rows.Add(row); } } } private static string GetString(MySqlDataReader reader, int index) { if (reader.IsDBNull(index)) return null; return reader.GetString(index); } public virtual DataTable GetUDF(string[] restrictions) { string sql = "SELECT name,ret,dl FROM mysql.func"; if (restrictions != null) { if (restrictions.Length >= 1 && !String.IsNullOrEmpty(restrictions[0])) sql += String.Format(" WHERE name LIKE '{0}'", restrictions[0]); } DataTable dt = new DataTable("User-defined Functions"); dt.Columns.Add("NAME", typeof(string)); dt.Columns.Add("RETURN_TYPE", typeof(int)); dt.Columns.Add("LIBRARY_NAME", typeof(string)); MySqlCommand cmd = new MySqlCommand(sql, connection); try { using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { DataRow row = dt.NewRow(); row[0] = reader.GetString(0); row[1] = reader.GetInt32(1); row[2] = reader.GetString(2); dt.Rows.Add(row); } } } catch (MySqlException ex) { if (ex.Number != (int)MySqlErrorCode.TableAccessDenied) throw; throw new MySqlException(Resources.UnableToEnumerateUDF, ex); } return dt; } protected virtual DataTable GetSchemaInternal(string collection, string[] restrictions) { switch (collection) { // common collections case "METADATACOLLECTIONS": return GetCollections(); case "DATASOURCEINFORMATION": return GetDataSourceInformation(); case "DATATYPES": return GetDataTypes(); case "RESTRICTIONS": return GetRestrictions(); case "RESERVEDWORDS": return GetReservedWords(); // collections specific to our provider case "USERS": return GetUsers(restrictions); case "DATABASES": return GetDatabases(restrictions); case "UDF": return GetUDF(restrictions); } // if we have a current database and our users have // not specified a database, then default to the currently // selected one. if (restrictions == null) restrictions = new string[2]; if (connection != null && connection.Database != null && connection.Database.Length > 0 && restrictions.Length > 1 && restrictions[1] == null) restrictions[1] = connection.Database; switch (collection) { case "TABLES": return GetTables(restrictions); case "COLUMNS": return GetColumns(restrictions); case "INDEXES": return GetIndexes(restrictions); case "INDEXCOLUMNS": return GetIndexColumns(restrictions); case "FOREIGN KEYS": return GetForeignKeys(restrictions); case "FOREIGN KEY COLUMNS": return GetForeignKeyColumns(restrictions); } return null; } internal string[] CleanRestrictions(string[] restrictionValues) { string[] restrictions = null; if (restrictionValues != null) { restrictions = (string[])restrictionValues.Clone(); for (int x = 0; x < restrictions.Length; x++) { string s = restrictions[x]; if (s == null) continue; restrictions[x] = s.Trim('`'); } } return restrictions; } } } mysql-connector-net-6.4.3/Source/MySql.Data/Installer.cs0000644000175000017500000002043111127003600023614 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #if !MONO && !PocketPC using System.Configuration.Install; using System.ComponentModel; using System.Reflection; using System; using Microsoft.Win32; using System.Xml; using System.IO; using System.Diagnostics; using System.Security; using System.Security.Permissions; namespace MySql.Data.MySqlClient { /// /// We are adding a custom installer class to our assembly so our installer /// can make proper changes to the machine.config file. /// [RunInstaller(true)] [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] [PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")] public class CustomInstaller : Installer { /// /// We override Install so we can add our assembly to the proper /// machine.config files. /// /// public override void Install(System.Collections.IDictionary stateSaver) { base.Install(stateSaver); AddProviderToMachineConfig(); } private static void AddProviderToMachineConfig() { object installRoot = Registry.GetValue( @"HKEY_LOCAL_MACHINE\Software\Microsoft\.NETFramework\", "InstallRoot", null); if (installRoot == null) throw new Exception("Unable to retrieve install root for .NET framework"); UpdateMachineConfigs(installRoot.ToString(), true); string installRoot64 = installRoot.ToString(); installRoot64 = installRoot64.Substring(0, installRoot64.Length - 1); installRoot64 = string.Format("{0}64{1}", installRoot64, Path.DirectorySeparatorChar); if (Directory.Exists(installRoot64)) UpdateMachineConfigs(installRoot64, true); } private static void UpdateMachineConfigs(string rootPath, bool add) { string[] dirs = new string[2] { "v2.0.50727", "v4.0.30319" }; foreach (string frameworkDir in dirs) { string path = rootPath + frameworkDir; string configPath = String.Format(@"{0}\CONFIG", path); if (Directory.Exists(configPath)) { if (add) AddProviderToMachineConfigInDir(configPath); else RemoveProviderFromMachineConfigInDir(configPath); } } } private static void AddProviderToMachineConfigInDir(string path) { string configFile = String.Format(@"{0}\machine.config", path); if (!File.Exists(configFile)) return; // now read the config file into memory StreamReader sr = new StreamReader(configFile); string configXML = sr.ReadToEnd(); sr.Close(); // load the XML into the XmlDocument XmlDocument doc = new XmlDocument(); doc.LoadXml(configXML); // create our new node XmlElement newNode = (XmlElement)doc.CreateNode(XmlNodeType.Element, "add", ""); // add the proper attributes newNode.SetAttribute("name", "MySQL Data Provider"); newNode.SetAttribute("invariant", "MySql.Data.MySqlClient"); newNode.SetAttribute("description", ".Net Framework Data Provider for MySQL"); // add the type attribute by reflecting on the executing assembly Assembly a = Assembly.GetExecutingAssembly(); string type = String.Format("MySql.Data.MySqlClient.MySqlClientFactory, {0}", a.FullName.Replace("Installers", "Data")); newNode.SetAttribute("type", type); XmlNodeList nodes = doc.GetElementsByTagName("DbProviderFactories"); foreach (XmlNode node in nodes[0].ChildNodes) { if (node.Attributes == null) continue; foreach (XmlAttribute attr in node.Attributes) { if (attr.Name == "invariant" && attr.Value == "MySql.Data.MySqlClient") { nodes[0].RemoveChild(node); break; } } } nodes[0].AppendChild(newNode); // Save the document to a file and auto-indent the output. XmlTextWriter writer = new XmlTextWriter(configFile, null); writer.Formatting = Formatting.Indented; doc.Save(writer); writer.Flush(); writer.Close(); } /// /// We override Uninstall so we can remove out assembly from the /// machine.config files. /// /// public override void Uninstall(System.Collections.IDictionary savedState) { base.Uninstall(savedState); RemoveProviderFromMachineConfig(); } private static void RemoveProviderFromMachineConfig() { object installRoot = Registry.GetValue( @"HKEY_LOCAL_MACHINE\Software\Microsoft\.NETFramework\", "InstallRoot", null); if (installRoot == null) throw new Exception("Unable to retrieve install root for .NET framework"); UpdateMachineConfigs(installRoot.ToString(), false); string installRoot64 = installRoot.ToString(); installRoot64 = installRoot64.Substring(0, installRoot64.Length - 1); installRoot64 = string.Format("{0}64{1}", installRoot64, Path.DirectorySeparatorChar); if (Directory.Exists(installRoot64)) UpdateMachineConfigs(installRoot64, false); } private static void RemoveProviderFromMachineConfigInDir(string path) { string configFile = String.Format(@"{0}\machine.config", path); if (!File.Exists(configFile)) return; // now read the config file into memory StreamReader sr = new StreamReader(configFile); string configXML = sr.ReadToEnd(); sr.Close(); // load the XML into the XmlDocument XmlDocument doc = new XmlDocument(); doc.LoadXml(configXML); XmlNodeList nodes = doc.GetElementsByTagName("DbProviderFactories"); foreach (XmlNode node in nodes[0].ChildNodes) { if (node.Attributes == null) continue; string name = node.Attributes["name"].Value; if (name == "MySQL Data Provider") { nodes[0].RemoveChild(node); break; } } // Save the document to a file and auto-indent the output. XmlTextWriter writer = new XmlTextWriter(configFile, null); writer.Formatting = Formatting.Indented; doc.Save(writer); writer.Flush(); writer.Close(); } } } #endif mysql-connector-net-6.4.3/Source/MySql.Data/TracingDriver.cs0000644000175000017500000002476511127003600024440 0ustar directhexdirecthex// Copyright (c) 2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Text; using MySql.Data.Types; using System.Diagnostics; using System.Collections.Generic; using MySql.Data.MySqlClient.Properties; using System.Threading; using MySql.Data.Common; namespace MySql.Data.MySqlClient { internal class TracingDriver : Driver { private static long driverCounter; private long driverId; private ResultSet activeResult; private int rowSizeInBytes; public TracingDriver(MySqlConnectionStringBuilder settings) : base(settings) { driverId = Interlocked.Increment(ref driverCounter); } public override void Open() { base.Open(); MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.ConnectionOpened, Resources.TraceOpenConnection, driverId, Settings.ConnectionString, ThreadID); } public override void Close() { base.Close(); MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.ConnectionClosed, Resources.TraceCloseConnection, driverId); } public override void SendQuery(MySqlPacket p) { rowSizeInBytes = 0; string cmdText = Encoding.GetString(p.Buffer, 5, p.Length - 5); string normalized_query = null; if (cmdText.Length > 300) { QueryNormalizer normalizer = new QueryNormalizer(); normalized_query = normalizer.Normalize(cmdText); cmdText = cmdText.Substring(0, 300); } base.SendQuery(p); MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.QueryOpened, Resources.TraceQueryOpened, driverId, ThreadID, cmdText); if (normalized_query != null) MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.QueryNormalized, Resources.TraceQueryNormalized, driverId, ThreadID, normalized_query); } protected override int GetResult(int statementId, ref int affectedRows, ref int insertedId) { try { int fieldCount = base.GetResult(statementId, ref affectedRows, ref insertedId); MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.ResultOpened, Resources.TraceResult, driverId, fieldCount, affectedRows, insertedId); return fieldCount; } catch (MySqlException ex) { // we got an error so we report it MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.Error, Resources.TraceOpenResultError, driverId, ex.Number, ex.Message); throw ex; } } public override ResultSet NextResult(int statementId, bool force) { // first let's see if we already have a resultset on this statementId if (activeResult != null) { //oldRS = activeResults[statementId]; if (Settings.UseUsageAdvisor) ReportUsageAdvisorWarnings(statementId, activeResult); MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.ResultClosed, Resources.TraceResultClosed, driverId, activeResult.TotalRows, activeResult.SkippedRows, rowSizeInBytes); rowSizeInBytes = 0; activeResult = null; } activeResult = base.NextResult(statementId, force); return activeResult; } public override int PrepareStatement(string sql, ref MySqlField[] parameters) { int statementId = base.PrepareStatement(sql, ref parameters); MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.StatementPrepared, Resources.TraceStatementPrepared, driverId, sql, statementId); return statementId; } public override void CloseStatement(int id) { base.CloseStatement(id); MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.StatementClosed, Resources.TraceStatementClosed, driverId, id); } public override void SetDatabase(string dbName) { base.SetDatabase(dbName); MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.NonQuery, Resources.TraceSetDatabase, driverId, dbName); } public override void ExecuteStatement(MySqlPacket packetToExecute) { base.ExecuteStatement(packetToExecute); int pos = packetToExecute.Position; packetToExecute.Position = 1; int statementId = packetToExecute.ReadInteger(4); packetToExecute.Position = pos; MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.StatementExecuted, Resources.TraceStatementExecuted, driverId, statementId, ThreadID); } public override bool FetchDataRow(int statementId, int columns) { try { bool b = base.FetchDataRow(statementId, columns); if (b) rowSizeInBytes += (handler as NativeDriver).Packet.Length; return b; } catch (MySqlException ex) { MySqlTrace.TraceEvent(TraceEventType.Error, MySqlTraceEventType.Error, Resources.TraceFetchError, driverId, ex.Number, ex.Message); throw ex; } } public override void CloseQuery(MySqlConnection connection, int statementId) { base.CloseQuery(connection, statementId); MySqlTrace.TraceEvent(TraceEventType.Information, MySqlTraceEventType.QueryClosed, Resources.TraceQueryDone, driverId); } public override List ReportWarnings(MySqlConnection connection) { List warnings = base.ReportWarnings(connection); foreach (MySqlError warning in warnings) MySqlTrace.TraceEvent(TraceEventType.Warning, MySqlTraceEventType.Warning, Resources.TraceWarning, driverId, warning.Level, warning.Code, warning.Message); return warnings; } private bool AllFieldsAccessed(ResultSet rs) { if (rs.Fields == null || rs.Fields.Length == 0) return true; for (int i = 0; i < rs.Fields.Length; i++) if (!rs.FieldRead(i)) return false; return true; } private void ReportUsageAdvisorWarnings(int statementId, ResultSet rs) { if (!Settings.UseUsageAdvisor) return; if (HasStatus(ServerStatusFlags.NoIndex)) MySqlTrace.TraceEvent(TraceEventType.Warning, MySqlTraceEventType.UsageAdvisorWarning, Resources.TraceUAWarningNoIndex, driverId, UsageAdvisorWarningFlags.NoIndex); else if (HasStatus(ServerStatusFlags.BadIndex)) MySqlTrace.TraceEvent(TraceEventType.Warning, MySqlTraceEventType.UsageAdvisorWarning, Resources.TraceUAWarningBadIndex, driverId, UsageAdvisorWarningFlags.BadIndex); // report abandoned rows if (rs.SkippedRows > 0) MySqlTrace.TraceEvent(TraceEventType.Warning, MySqlTraceEventType.UsageAdvisorWarning, Resources.TraceUAWarningSkippedRows, driverId, UsageAdvisorWarningFlags.SkippedRows, rs.SkippedRows); // report not all fields accessed if (!AllFieldsAccessed(rs)) { StringBuilder notAccessed = new StringBuilder(""); string delimiter = ""; for (int i = 0; i < rs.Size; i++) if (!rs.FieldRead(i)) { notAccessed.AppendFormat("{0}{1}", delimiter, rs.Fields[i].ColumnName); delimiter = ","; } MySqlTrace.TraceEvent(TraceEventType.Warning, MySqlTraceEventType.UsageAdvisorWarning, Resources.TraceUAWarningSkippedColumns, driverId, UsageAdvisorWarningFlags.SkippedColumns, notAccessed.ToString()); } // report type conversions if any if (rs.Fields != null) { foreach (MySqlField f in rs.Fields) { StringBuilder s = new StringBuilder(); string delimiter = ""; foreach (Type t in f.TypeConversions) { s.AppendFormat("{0}{1}", delimiter, t.Name); delimiter = ","; } if (s.Length > 0) MySqlTrace.TraceEvent(TraceEventType.Warning, MySqlTraceEventType.UsageAdvisorWarning, Resources.TraceUAWarningFieldConversion, driverId, UsageAdvisorWarningFlags.FieldConversion, f.ColumnName, s.ToString()); } } } } } mysql-connector-net-6.4.3/Source/MySql.Data/Connection.cs0000644000175000017500000007442011127003600023765 0ustar directhexdirecthex// Copyright (c) 2004-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.ComponentModel; using System.Data; using System.Data.Common; #if !CF using System.Drawing; using System.Drawing.Design; using System.Transactions; #endif using System.Text; using IsolationLevel=System.Data.IsolationLevel; using MySql.Data.Common; using System.Diagnostics; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { /// #if !CF [ToolboxBitmap(typeof (MySqlConnection), "MySqlClient.resources.connection.bmp")] [DesignerCategory("Code")] [ToolboxItem(true)] #endif public sealed class MySqlConnection : DbConnection, ICloneable { internal ConnectionState connectionState; internal Driver driver; private MySqlConnectionStringBuilder settings; private bool hasBeenOpen; private SchemaProvider schemaProvider; private ProcedureCache procedureCache; private bool isInUse; #if !CF private PerformanceMonitor perfMonitor; #endif private bool isKillQueryConnection; private string database; private int commandTimeout; /// public event MySqlInfoMessageEventHandler InfoMessage; private static Cache connectionStringCache = new Cache(0, 25); /// public MySqlConnection() { //TODO: add event data to StateChange docs settings = new MySqlConnectionStringBuilder(); database = String.Empty; } /// public MySqlConnection(string connectionString) : this() { ConnectionString = connectionString; } #region Interal Methods & Properties #if !CF internal PerformanceMonitor PerfMonitor { get { return perfMonitor; } } #endif internal ProcedureCache ProcedureCache { get { return procedureCache; } } internal MySqlConnectionStringBuilder Settings { get { return settings; } } internal MySqlDataReader Reader { get { if (driver == null) return null; return driver.reader; } set { driver.reader = value; isInUse = driver.reader != null; } } internal void OnInfoMessage(MySqlInfoMessageEventArgs args) { if (InfoMessage != null) { InfoMessage(this, args); } } internal bool SoftClosed { get { #if !CF return (State == ConnectionState.Closed) && driver != null && driver.CurrentTransaction != null; #else return false; #endif } } internal bool IsInUse { get{ return isInUse; } set{ isInUse = value; } } #endregion #region Properties /// /// Returns the id of the server thread this connection is executing on /// #if !CF [Browsable(false)] #endif public int ServerThread { get { return driver.ThreadID; } } /// /// Gets the name of the MySQL server to which to connect. /// #if !CF [Browsable(true)] #endif public override string DataSource { get { return settings.Server; } } /// #if !CF [Browsable(true)] #endif public override int ConnectionTimeout { get { return (int) settings.ConnectionTimeout; } } /// #if !CF [Browsable(true)] #endif public override string Database { get { return database; } } /// /// Indicates if this connection should use compression when communicating with the server. /// #if !CF [Browsable(false)] #endif public bool UseCompression { get { return settings.UseCompression; } } /// #if !CF [Browsable(false)] #endif public override ConnectionState State { get { return connectionState; } } /// #if !CF [Browsable(false)] #endif public override string ServerVersion { get { return driver.Version.ToString(); } } /// #if !CF [Editor("MySql.Data.MySqlClient.Design.ConnectionStringTypeEditor,MySqlClient.Design", typeof (UITypeEditor))] [Browsable(true)] [Category("Data")] [Description( "Information used to connect to a DataSource, such as 'Server=xxx;UserId=yyy;Password=zzz;Database=dbdb'.")] #endif public override string ConnectionString { get { // Always return exactly what the user set. // Security-sensitive information may be removed. return settings.GetConnectionString(!hasBeenOpen || settings.PersistSecurityInfo); } set { if (State != ConnectionState.Closed) throw new MySqlException( "Not allowed to change the 'ConnectionString' property while the connection (state=" + State + ")."); MySqlConnectionStringBuilder newSettings; lock (connectionStringCache) { if (value == null) newSettings = new MySqlConnectionStringBuilder(); else { newSettings = (MySqlConnectionStringBuilder)connectionStringCache[value]; if (null == newSettings) { newSettings = new MySqlConnectionStringBuilder(value); connectionStringCache.Add(value, newSettings); } } } settings = newSettings; if (settings.Database != null && settings.Database.Length > 0) this.database = settings.Database; if (driver != null) driver.Settings = newSettings; } } #if !CF && !__MonoCS__ protected override DbProviderFactory DbProviderFactory { get { return MySqlClientFactory.Instance; } } #endif #endregion #region Transactions #if !MONO && !CF /// /// Enlists in the specified transaction. /// /// /// A reference to an existing in which to enlist. /// public override void EnlistTransaction(Transaction transaction) { // enlisting in the null transaction is a noop if (transaction == null) return; // guard against trying to enlist in more than one transaction if (driver.CurrentTransaction != null) { if (driver.CurrentTransaction.BaseTransaction == transaction) return; throw new MySqlException("Already enlisted"); } // now see if we need to swap out drivers. We would need to do this since // we have to make sure all ops for a given transaction are done on the // same physical connection. Driver existingDriver = DriverTransactionManager.GetDriverInTransaction(transaction); if (existingDriver != null) { // we can't allow more than one driver to contribute to the same connection if (existingDriver.IsInActiveUse) throw new NotSupportedException(Resources.MultipleConnectionsInTransactionNotSupported); // there is an existing driver and it's not being currently used. // now we need to see if it is using the same connection string string text1 = existingDriver.Settings.ConnectionString; string text2 = Settings.ConnectionString; if (String.Compare(text1, text2, true) != 0) throw new NotSupportedException(Resources.MultipleConnectionsInTransactionNotSupported); // close existing driver // set this new driver as our existing driver CloseFully(); driver = existingDriver; } if (driver.CurrentTransaction == null) { MySqlPromotableTransaction t = new MySqlPromotableTransaction(this, transaction); if (!transaction.EnlistPromotableSinglePhase(t)) throw new NotSupportedException(Resources.DistributedTxnNotSupported); driver.CurrentTransaction = t; DriverTransactionManager.SetDriverInTransaction(driver); driver.IsInActiveUse = true; } } #endif /// public new MySqlTransaction BeginTransaction() { return BeginTransaction(IsolationLevel.RepeatableRead); } /// public new MySqlTransaction BeginTransaction(IsolationLevel iso) { //TODO: check note in help if (State != ConnectionState.Open) throw new InvalidOperationException(Resources.ConnectionNotOpen); // First check to see if we are in a current transaction if (driver.HasStatus(ServerStatusFlags.InTransaction)) throw new InvalidOperationException(Resources.NoNestedTransactions); MySqlTransaction t = new MySqlTransaction(this, iso); MySqlCommand cmd = new MySqlCommand("", this); cmd.CommandText = "SET SESSION TRANSACTION ISOLATION LEVEL "; switch (iso) { case IsolationLevel.ReadCommitted: cmd.CommandText += "READ COMMITTED"; break; case IsolationLevel.ReadUncommitted: cmd.CommandText += "READ UNCOMMITTED"; break; case IsolationLevel.RepeatableRead: cmd.CommandText += "REPEATABLE READ"; break; case IsolationLevel.Serializable: cmd.CommandText += "SERIALIZABLE"; break; case IsolationLevel.Chaos: throw new NotSupportedException(Resources.ChaosNotSupported); case IsolationLevel.Snapshot: throw new NotSupportedException(Resources.SnapshotNotSupported); } cmd.ExecuteNonQuery(); cmd.CommandText = "BEGIN"; cmd.ExecuteNonQuery(); return t; } #endregion /// public override void ChangeDatabase(string databaseName) { if (databaseName == null || databaseName.Trim().Length == 0) throw new ArgumentException(Resources.ParameterIsInvalid, "databaseName"); if (State != ConnectionState.Open) throw new InvalidOperationException(Resources.ConnectionNotOpen); // This lock prevents promotable transaction rollback to run // in parallel lock (driver) { #if !CF if (Transaction.Current != null && Transaction.Current.TransactionInformation.Status == TransactionStatus.Aborted) { throw new TransactionAbortedException(); } #endif // We use default command timeout for SetDatabase using (new CommandTimer(this, (int)Settings.DefaultCommandTimeout)) { driver.SetDatabase(databaseName); } } this.database = databaseName; } internal void SetState(ConnectionState newConnectionState, bool broadcast) { if (newConnectionState == connectionState && !broadcast) return; ConnectionState oldConnectionState = connectionState; connectionState = newConnectionState; if (broadcast) OnStateChange(new StateChangeEventArgs(oldConnectionState, connectionState)); } /// /// Ping /// /// public bool Ping() { if(Reader != null) throw new MySqlException(Resources.DataReaderOpen); if (driver != null && driver.Ping()) return true; driver = null; SetState(ConnectionState.Closed, true); return false; } /// public override void Open() { if (State == ConnectionState.Open) throw new InvalidOperationException(Resources.ConnectionAlreadyOpen); SetState(ConnectionState.Connecting, true); #if !CF // if we are auto enlisting in a current transaction, then we will be // treating the connection as pooled if (settings.AutoEnlist && Transaction.Current != null) { driver = DriverTransactionManager.GetDriverInTransaction(Transaction.Current); if (driver != null && (driver.IsInActiveUse || !driver.Settings.EquivalentTo(this.Settings))) throw new NotSupportedException(Resources.MultipleConnectionsInTransactionNotSupported); } #endif try { if (settings.Pooling) { MySqlPool pool = MySqlPoolManager.GetPool(settings); if (driver == null || !driver.IsOpen) driver = pool.GetConnection(); procedureCache = pool.ProcedureCache; } else { if (driver == null || !driver.IsOpen) driver = Driver.Create(settings); procedureCache = new ProcedureCache((int) settings.ProcedureCacheSize); } } catch (Exception) { SetState(ConnectionState.Closed, true); throw; } // if the user is using old syntax, let them know if (driver.Settings.UseOldSyntax) MySqlTrace.LogWarning(ServerThread, "You are using old syntax that will be removed in future versions"); SetState(ConnectionState.Open, false); driver.Configure(this); if (settings.Database != null && settings.Database != String.Empty) ChangeDatabase(settings.Database); // setup our schema provider schemaProvider = new ISSchemaProvider(this); #if !CF perfMonitor = new PerformanceMonitor(this); #endif // if we are opening up inside a current transaction, then autoenlist // TODO: control this with a connection string option #if !MONO && !CF if (Transaction.Current != null && settings.AutoEnlist) EnlistTransaction(Transaction.Current); #endif hasBeenOpen = true; SetState(ConnectionState.Open, true); } /// public new MySqlCommand CreateCommand() { // Return a new instance of a command object. MySqlCommand c = new MySqlCommand(); c.Connection = this; return c; } #region ICloneable /// /// Creates a new MySqlConnection object with the exact same ConnectionString value /// /// A cloned MySqlConnection object public MySqlConnection Clone() { MySqlConnection clone = new MySqlConnection(); string connectionString = settings.ConnectionString; if (connectionString != null) clone.ConnectionString = connectionString; return clone; } object ICloneable.Clone() { return this.Clone(); } #endregion #region IDisposeable protected override void Dispose(bool disposing) { if (State == ConnectionState.Open) Close(); base.Dispose(disposing); } #endregion protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { if (isolationLevel == IsolationLevel.Unspecified) return BeginTransaction(); return BeginTransaction(isolationLevel); } protected override DbCommand CreateDbCommand() { return CreateCommand(); } internal void Abort() { try { driver.Close(); } catch (Exception ex) { MySqlTrace.LogWarning(ServerThread, String.Concat("Error occurred aborting the connection. Exception was: ", ex.Message)); } finally { this.isInUse = false; } SetState(ConnectionState.Closed, true); } internal void CloseFully() { if (settings.Pooling && driver.IsOpen) { // if we are in a transaction, roll it back if (driver.HasStatus(ServerStatusFlags.InTransaction)) { MySqlTransaction t = new MySqlTransaction(this, IsolationLevel.Unspecified); t.Rollback(); } MySqlPoolManager.ReleaseConnection(driver); } else driver.Close(); driver = null; } /// public override void Close() { if (State == ConnectionState.Closed) return; if (Reader != null) Reader.Close(); // if the reader was opened with CloseConnection then driver // will be null on the second time through if (driver != null) { #if !CF if (driver.CurrentTransaction == null) #endif CloseFully(); #if !CF else driver.IsInActiveUse = false; #endif } SetState(ConnectionState.Closed, true); } internal string CurrentDatabase() { if (Database != null && Database.Length > 0) return Database; MySqlCommand cmd = new MySqlCommand("SELECT database()", this); return cmd.ExecuteScalar().ToString(); } internal void HandleTimeoutOrThreadAbort(Exception ex) { bool isFatal = false; if (isKillQueryConnection) { // Special connection started to cancel a query. // Abort will prevent recursive connection spawning Abort(); if (ex is TimeoutException) { throw new MySqlException(Resources.Timeout, true, ex); } else { return; } } try { // Do a fast cancel.The reason behind small values for connection // and command timeout is that we do not want user to wait longer // after command has already expired. // Microsoft's SqlClient seems to be using 5 seconds timeouts // here as well. // Read the error packet with "interrupted" message. CancelQuery(5); driver.ResetTimeout(5000); if (Reader != null) { Reader.Close(); Reader = null; } } catch (Exception ex2) { MySqlTrace.LogWarning(ServerThread, "Could not kill query, " + " aborting connection. Exception was " + ex2.Message); Abort(); isFatal = true; } if (ex is TimeoutException) { throw new MySqlException(Resources.Timeout, isFatal, ex); } } public void CancelQuery(int timeout) { MySqlConnectionStringBuilder cb = new MySqlConnectionStringBuilder( Settings.ConnectionString); cb.Pooling = false; cb.AutoEnlist = false; cb.ConnectionTimeout = (uint) timeout; using(MySqlConnection c = new MySqlConnection(cb.ConnectionString)) { c.isKillQueryConnection = true; c.Open(); string commandText = "KILL QUERY " + ServerThread; MySqlCommand cmd = new MySqlCommand(commandText, c); cmd.CommandTimeout = timeout; cmd.ExecuteNonQuery(); } } #region Routines for timeout support. // Problem description: // Sometimes, ExecuteReader is called recursively. This is the case if // command behaviors are used and we issue "set sql_select_limit" // before and after command. This is also the case with prepared // statements , where we set session variables. In these situations, we // have to prevent recursive ExecuteReader calls from overwriting // timeouts set by the top level command. // To solve the problem, SetCommandTimeout() and ClearCommandTimeout() are // introduced . Query timeout here is "sticky", that is once set with // SetCommandTimeout, it only be overwritten after ClearCommandTimeout // (SetCommandTimeout would return false if it timeout has not been // cleared). // The proposed usage pattern of there routines is following: // When timed operations starts, issue SetCommandTimeout(). When it // finishes, issue ClearCommandTimeout(), but _only_ if call to // SetCommandTimeout() was successful. /// /// Sets query timeout. If timeout has been set prior and not /// yet cleared ClearCommandTimeout(), it has no effect. /// /// timeout in seconds /// true if internal bool SetCommandTimeout(int value) { if (!hasBeenOpen) // Connection timeout is handled by driver return false; if (commandTimeout != 0) // someone is trying to set a timeout while command is already // running. It could be for example recursive call to ExecuteReader // Ignore the request, as only top-level (non-recursive commands) // can set timeouts. return false; if (driver == null) return false; commandTimeout = value; driver.ResetTimeout(commandTimeout * 1000); return true; } /// /// Clears query timeout, allowing next SetCommandTimeout() to succeed. /// internal void ClearCommandTimeout() { if (!hasBeenOpen) return; commandTimeout = 0; if (driver != null) { driver.ResetTimeout(0); } } #endregion #region GetSchema Support /// /// Returns schema information for the data source of this . /// /// A that contains schema information. public override DataTable GetSchema() { return GetSchema(null); } /// /// Returns schema information for the data source of this /// using the specified string for the schema name. /// /// Specifies the name of the schema to return. /// A that contains schema information. public override DataTable GetSchema(string collectionName) { if (collectionName == null) collectionName = SchemaProvider.MetaCollection; return GetSchema(collectionName, null); } /// /// Returns schema information for the data source of this /// using the specified string for the schema name and the specified string array /// for the restriction values. /// /// Specifies the name of the schema to return. /// Specifies a set of restriction values for the requested schema. /// A that contains schema information. public override DataTable GetSchema(string collectionName, string[] restrictionValues) { if (collectionName == null) collectionName = SchemaProvider.MetaCollection; string[] restrictions = schemaProvider.CleanRestrictions(restrictionValues); DataTable dt = schemaProvider.GetSchema(collectionName, restrictions); return dt; } #endregion #region Pool Routines /// public static void ClearPool(MySqlConnection connection) { MySqlPoolManager.ClearPool(connection.Settings); } /// public static void ClearAllPools() { MySqlPoolManager.ClearAllPools(); } #endregion } /// /// Represents the method that will handle the event of a /// . /// public delegate void MySqlInfoMessageEventHandler(object sender, MySqlInfoMessageEventArgs args); /// /// Provides data for the InfoMessage event. This class cannot be inherited. /// public class MySqlInfoMessageEventArgs : EventArgs { /// /// /// public MySqlError[] errors; } /// /// IDisposable wrapper around SetCommandTimeout and ClearCommandTimeout /// functionality /// internal class CommandTimer:IDisposable { bool timeoutSet; MySqlConnection connection; public CommandTimer(MySqlConnection connection, int timeout) { this.connection = connection; if (connection != null) { timeoutSet = connection.SetCommandTimeout(timeout); } } #region IDisposable Members public void Dispose() { if (timeoutSet) { timeoutSet = false; connection.ClearCommandTimeout(); connection = null; } } #endregion } } mysql-connector-net-6.4.3/Source/MySql.Data/Runtime.cs0000644000175000017500000000101111127003600023273 0ustar directhexdirecthexusing System; namespace MySql.Web.Security { internal static class Runtime { private static bool inited; private static bool isMono; public static bool IsMono { get { if (!inited) Init(); return isMono; } } private static void Init() { Type t = Type.GetType("Mono.Runtime"); isMono = t != null; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/0000755000175000017500000000000011127003600023112 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.VisualStudio/MySql.VisualStudio.csproj0000644000175000017500000005430011127003600030035 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 Library Properties MySql.Data.VisualStudio MySql.VisualStudio false {DC3517FF-AC26-4755-9B7A-EF658FF69593} 3.5 v4.0 false publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false true true full false bin\Debug\ TRACE;DEBUG;CLR4 prompt 4 false AllRules.ruleset pdbonly true bin\Release\ TRACE;CLR4 prompt 4 AllRules.ruleset False ..\..\..\..\Program Files (x86)\Microsoft Visual Studio 2010 SDK\VisualStudioIntegration\Common\Assemblies\v4.0\Microsoft.Data.ConnectionUI.dll True False ..\..\..\..\Program Files (x86)\Microsoft Visual Studio 2010 SDK\VisualStudioIntegration\Common\Assemblies\v4.0\Microsoft.VisualStudio.Data.dll True c:\Program Files\Visual Studio 2005 SDK\2007.02\VisualStudioIntegration\Common\Assemblies\Microsoft.VisualStudio.OLE.Interop.dll False ..\..\..\..\Program Files (x86)\Microsoft Visual Studio 2010 SDK\VisualStudioIntegration\Common\Assemblies\v4.0\Microsoft.VisualStudio.Package.LanguageService.10.0.dll False ..\..\..\..\Program Files (x86)\Microsoft Visual Studio 2010 SDK\VisualStudioIntegration\Common\Assemblies\v2.0\Microsoft.VisualStudio.Shell.Interop.dll False True ..\..\..\..\Program Files (x86)\Microsoft Visual Studio 2010 SDK\VisualStudioIntegration\Common\Assemblies\v2.0\Microsoft.VisualStudio.Shell.Interop.10.0.dll False ..\..\..\..\Program Files (x86)\Microsoft Visual Studio 2010 SDK\VisualStudioIntegration\Common\Assemblies\v2.0\Microsoft.VisualStudio.Shell.Interop.8.0.dll False ..\..\..\..\Program Files (x86)\Microsoft Visual Studio 2010 SDK\VisualStudioIntegration\Common\Assemblies\v2.0\Microsoft.VisualStudio.Shell.Interop.9.0.dll False ..\..\..\..\Program Files (x86)\Microsoft Visual Studio 2010 SDK\VisualStudioIntegration\Common\Assemblies\v2.0\Microsoft.VisualStudio.TextManager.Interop.dll False True ..\..\..\..\Program Files (x86)\Microsoft Visual Studio 2010 SDK\VisualStudioIntegration\Common\Assemblies\v2.0\Microsoft.VisualStudio.TextManager.Interop.10.0.dll False ..\..\..\..\Program Files (x86)\Microsoft Visual Studio 2010 SDK\VisualStudioIntegration\Common\Assemblies\v2.0\Microsoft.VisualStudio.TextManager.Interop.8.0.dll False ..\..\..\..\Program Files (x86)\Microsoft Visual Studio 2010 SDK\VisualStudioIntegration\Common\Assemblies\v2.0\Microsoft.VisualStudio.TextManager.Interop.9.0.dll LanguageService\MySqlTokenizer.cs Properties\VersionInfo.cs UserControl UserControl MySqlConnectionUIControl.cs Form MySqlDataConnectionPromptDialog.cs UserControl Form ConnectDialog.cs Form ForeignKeyDialog.cs Form GenerateChangeScriptDialog.cs Form IndexColumnEditorDialog.cs Component Component UserControl SqlEditor.cs Form TableIndexDialog.cs Form TableNamePromptDialog.cs Form UDFEditor.cs Component Code UserControl Component True True Resources.resx Form ConnectionStringEditorDlg.cs Form MembershipOptionsDlg.cs Form WebConfigDlg.cs PublicResXFileCodeGenerator Resources.Designer.cs Designer true MySqlConnectionUIControl.cs Designer MySqlDataConnectionPromptDialog.cs ConnectDialog.cs ForeignKeyDialog.cs GenerateChangeScriptDialog.cs Designer IndexColumnEditorDialog.cs SqlEditor.cs Designer TableEditor.cs TableIndexDialog.cs Designer TableNamePromptDialog.cs UDFEditor.cs Designer ConnectionStringEditorDlg.cs MembershipOptionsDlg.cs WebConfigDlg.cs Always true Always Always 1000 False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 2.0 %28x86%29 true False .NET Framework 3.0 %28x86%29 false False .NET Framework 3.5 false False .NET Framework 3.5 SP1 false {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} MySql.Data false false true false mysql-connector-net-6.4.3/Source/MySql.VisualStudio/LanguageService/0000755000175000017500000000000011127003600026156 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.VisualStudio/LanguageService/Configuration.cs0000644000175000017500000001045011127003600031314 0ustar directhexdirecthexusing Microsoft.VisualStudio.Package; using System.Collections.Generic; namespace MySql.Data.VisualStudio { internal class Configuration { private static List keywords; static Configuration() { if (keywords != null) return; keywords = new List(); // procedures and functions keywords.Add("CREATE"); keywords.Add("ALTER"); keywords.Add("PROCEDURE"); keywords.Add("CALL"); keywords.Add("RETURN"); keywords.Add("FUNCTION"); keywords.Add("RETURNS"); keywords.Add("DECLARE"); keywords.Add("DEFINER"); keywords.Add("CURRENT_USER"); keywords.Add("OUT"); keywords.Add("INOUT"); keywords.Add("IN"); keywords.Add("BEGIN"); keywords.Add("END"); // update keywords.Add("UPDATE"); keywords.Add("TABLE"); // delete keywords.Add("DELETE"); // select keywords.Add("SELECT"); keywords.Add("FROM"); keywords.Add("WHERE"); keywords.Add("GROUP"); keywords.Add("BY"); keywords.Add("ASC"); keywords.Add("DESC"); keywords.Add("WITH"); keywords.Add("ROLLUP"); keywords.Add("HAVING"); keywords.Add("ORDER"); keywords.Add("LIMIT"); keywords.Add("OFFSET"); keywords.Add("INTO"); keywords.Add("OUTFILE"); keywords.Add("DUMPFILE"); keywords.Add("FOR"); keywords.Add("LOCK"); keywords.Add("SHARE"); keywords.Add("MODE"); keywords.Add("ALL"); keywords.Add("DISTINCT"); keywords.Add("DISTINCTROW"); keywords.Add("HIGH_PRIORITY"); keywords.Add("STRAIGHT_JOIN"); keywords.Add("SQL_SMALL_RESULT"); keywords.Add("SQL_BIG_RESULT"); keywords.Add("SQL_BUFFER_RESULT"); keywords.Add("SQL_CACHE"); keywords.Add("SQL_NO_CACHE"); keywords.Add("SQL_CALC_FOUND_ROWS"); // misc keywords.Add("SHOW"); keywords.Add("PROCESSLIST"); keywords.Add("KILL"); keywords.Add("STATUS"); // data types keywords.Add("INT"); keywords.Add("CHAR"); keywords.Add("VARCHAR"); // functions keywords.Add("COUNT"); keywords.Add("REPLACE"); } public static TokenInfo GetTokenInfo(string token, MySqlTokenizer tokenizer) { TokenInfo ti = new TokenInfo(); if (tokenizer.Quoted) { if (token.StartsWith("\'")) ti.Type = TokenType.Literal; else { if (token.StartsWith("\"") && !tokenizer.AnsiQuotes) ti.Type = TokenType.String; else ti.Type = TokenType.Identifier; } } else if (IsKeyword(token.ToUpperInvariant())) ti.Type = TokenType.Keyword; else if (tokenizer.IsComment) ti.Type = TokenType.Comment; else ti.Type = TokenType.Text; ti.Color = GetTokenColor(ti); return ti; } private static TokenColor GetTokenColor(TokenInfo ti) { switch (ti.Type) { case TokenType.String: case TokenType.Literal: return TokenColor.String; case TokenType.Identifier: return TokenColor.Identifier; case TokenType.Keyword: return TokenColor.Keyword; case TokenType.Comment: return TokenColor.Comment; default: return TokenColor.Text; } } private static bool IsKeyword(string token) { return keywords.Contains(token); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/LanguageService/Source.cs0000644000175000017500000000116511127003600027750 0ustar directhexdirecthexusing Microsoft.VisualStudio.Package; using Microsoft.VisualStudio.TextManager.Interop; namespace MySql.Data.VisualStudio { internal class MySqlSource : Source { public MySqlSource(LanguageService service, IVsTextLines textLines, Colorizer colorizer) : base(service, textLines, colorizer) { } public override CommentInfo GetCommentFormat() { CommentInfo ci = new CommentInfo(); ci.UseLineComments = true; ci.LineStart = "#"; ci.BlockStart = "/*"; ci.BlockEnd = "*/"; return ci; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/LanguageService/Tokenizer.cs0000644000175000017500000001471011127003600030462 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; namespace MySql.Data.VisualStudio { class Tokenizer { private string text; private int Pos; private string LastToken; private int _startIndex; private int _stopIndex; private bool _lineComment; private bool _quoted; public bool AnsiQuotes = false; public bool BackslashEscapes = true; public bool ReturnComments; public bool BlockComment; #region Properties public string Text { get { return text; } set { text = value; Pos = 0; } } public int StartIndex { get { return _startIndex; } private set { _startIndex = value; } } public int StopIndex { get { return _stopIndex; } private set { _stopIndex = value; } } public bool LineComment { get { return _lineComment; } private set { _lineComment = value; } } public bool Quoted { get { return _quoted; } private set { _quoted = value; } } #endregion public string NextToken() { if (LastToken == "*/" && BlockComment) BlockComment = false; LastToken = GetNextToken(); return LastToken; } private string GetNextToken() { if (Text == null) return null; StartIndex = StopIndex = 0; Quoted = false; LineComment = false; while (Pos < Text.Length) { if (BlockComment) return ExtractComment(); char c = Text[Pos++]; if (Char.IsWhiteSpace(c) && StartIndex == 0) continue; StartIndex = Pos - 1; if (IsQuoteCharacter(c) && !BlockComment) return ExtractQuotedToken(c); string comment = ReadComment(c); if (comment != null && ReturnComments) return comment; return ExtractUnquotedToken(); } return null; } #region Private methods private string ReadComment(char startingChar) { if (startingChar != '/' && startingChar != '#' && startingChar != '-') return null; if (startingChar == '-' && Text.Length == (Pos + 1)) return null; if (startingChar == '/' && Text.Length == Pos) return null; if ((startingChar == '-' && Text[Pos] == '-' && Text[Pos+1] == ' ') || startingChar == '#') { LineComment = true; return ExtractComment(); } if (startingChar == '/' && Text[Pos] == '*') { BlockComment = true; return ExtractComment(); } return null; } private string ExtractComment() { char lastChar = Char.MinValue; while (Pos < Text.Length) { char c = Text[Pos++]; if ((c == '\n' && LineComment) || (c == '/' && lastChar == '*' && BlockComment)) return ExtractToken(true); lastChar = c; } return ExtractToken(false); } private string ExtractUnquotedToken() { while (Pos < Text.Length) { char c = Text[Pos++]; if (IsTokenTerminator(c)) return ExtractToken(true); } return ExtractToken(false); } private string ExtractQuotedToken(char quoteChar) { bool escaped = false; while (Pos < Text.Length) { char c = Text[Pos++]; if (c == quoteChar && !escaped) { Quoted = true; return ExtractToken(true); } if (escaped) escaped = false; if (c == '\\' && BackslashEscapes) escaped = true; } return ExtractToken(false); } private bool IsQuoteCharacter(char c) { return c == '\'' || c == '`' || (c == '\"' && AnsiQuotes); } private bool IsTokenTerminator(char c) { if (c == '\n') return true; if (c == '#' || c == '-' || c == '/' || c == '\\') return true; if (c == '(' || c == ',') return true; if (Char.IsWhiteSpace(c)) return true; return false; } private string ExtractToken(bool preserveLast) { StopIndex = Math.Min(Text.Length-1, Pos - 1); if (preserveLast) Pos--; return Text.Substring(StartIndex, StopIndex - StartIndex+1); //if (Pos < Text.Length) // return Text.Substring(StartIndex, StopIndex - StartIndex + 1); //StopIndex = Pos; //return Text.Substring(StartIndex, StopIndex - StartIndex); } #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/LanguageService/MySqlColorizer.cs0000644000175000017500000001274411127003600031453 0ustar directhexdirecthexusing System; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.Package; using Microsoft.VisualStudio.TextManager.Interop; using MySql.Data.MySqlClient; namespace MySql.Data.VisualStudio { internal class MySqlColorizer : Colorizer { // private IScanner scanner; // private IVsTextLines buffer; // private List[] tokenList; // private string savedSqlText; public MySqlColorizer(LanguageService service, IVsTextLines buffer, IScanner scanner) : base(service, buffer, scanner) { (scanner as MySqlScanner).Colorizer = this; // this.scanner = scanner; // this.buffer = buffer; } // public override TokenInfo[] GetLineInfo(IVsTextLines buffer, int line, IVsTextColorState colorState) // { // LexBuffer(); // return tokenList[line].ToArray(); //} // public override int GetColorInfo(string line, int length, int state) // { // return 0; // } public int CurrentLine { get; set; } public override int ColorizeLine(int line, int length, System.IntPtr ptr, int state, uint[] attrs) { System.Diagnostics.Trace.WriteLine("colorizing line # " + line); CurrentLine = line; return base.ColorizeLine(line, length, ptr, state, attrs); /* int linepos = 0; // only relex if we need to LexBuffer(); if (scanner != null && tokenList.Length > line) { TokenInfo[] tokens = tokenList[line].ToArray(); foreach (TokenInfo ti in tokens) { for (; linepos < ti.StartIndex; linepos++) attrs[linepos] = (uint)TokenColor.Text; uint color = (uint)ti.Color; if (ti.Type == TokenType.Comment || ti.Type == TokenType.LineComment || ti.Type == TokenType.String || ti.Type == TokenType.Text) { color |= (uint)COLORIZER_ATTRIBUTE.HUMAN_TEXT_ATTR; } for (; linepos <= ti.EndIndex; linepos++) attrs[linepos] = (uint)ti.Color; } } else if (attrs != null) { // Must initialize the colors in all cases, otherwise you get // random color junk on the screen. for (; linepos < length; linepos++) attrs[linepos] = (uint)TokenColor.Text; } return 0;*/ } /// /// This method will "lex" the entire SQL buffer into an array /// of TokenInfo structs. It compares the buffer lines to a cached /// copy and only re-lexes if there are changes /// /* private void LexBuffer() { int lineCount; buffer.GetLineCount(out lineCount); StringBuilder sb = new StringBuilder(); string[] lines = new string[lineCount]; for (int line = 0; line < lineCount; line++) { int length; buffer.GetLengthOfLine(line, out length); buffer.GetLineText(line, 0, line, length, out lines[line]); //lines[line] = lines[line].Replace(@"\r\n", " ").Replace(@"\n", " "); } // now reformat the buffer to have new lines where VS wants them to be foreach (string line in lines) sb.AppendLine(line); string sqlText = sb.ToString(); if (sqlText == savedSqlText) return; savedSqlText = sqlText; // things have changed so we need to create an array // of TokenInfo arrays to hold our color info tokenList = new List[lineCount]; for (int i = 0; i < lineCount; i++) tokenList[i] = new List(); MySqlTokenizer tokenizer = new MySqlTokenizer(sqlText); tokenizer.ReturnComments = true; string token = tokenizer.NextToken(); while (token != null) { int startIndex = tokenizer.StartIndex; int stopIndex = tokenizer.StopIndex; int startLine = GetLineAndIndex(lines, ref startIndex); int endLine = GetLineAndIndex(lines, ref stopIndex); for (int line = startLine; line <= endLine; line++) { TokenInfo ti = Configuration.GetTokenInfo(token, tokenizer); ti.StartIndex = line == startLine ? startIndex : 0; ti.EndIndex = line == endLine ? stopIndex : lines[line].Length; tokenList[line].Add(ti); } token = tokenizer.NextToken(); } } private int GetLineAndIndex(string[] lines, ref int index) { if (lines == null || lines.Length == 0) return -1; int line = 0; int len = lines[line].Length; while (index > len) len += lines[++line].Length; index -= len; return line; }*/ } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/LanguageService/MySqlScanner.cs0000644000175000017500000001500511127003600031065 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using Microsoft.VisualStudio.Package; using System.Collections.Generic; namespace MySql.Data.VisualStudio { /// /// We don't actually need this class but we have to return a scanner object /// from our language service or the colorizing doesn't work. /// All the colorizing work happens in MySqlColorizer. /// class MySqlScanner : IScanner { List keywords; Tokenizer tokenizer = new Tokenizer(); List lines = new List(); public MySqlScanner() { tokenizer.ReturnComments = true; Initialize(); } #region IScanner Members bool IScanner.ScanTokenAndProvideInfoAboutIt(TokenInfo tokenInfo, ref int state) { tokenizer.BlockComment = state == 1 ? true : false; string token = tokenizer.NextToken(); if (token == null) return false; token = token.Trim(); tokenInfo.StartIndex = tokenizer.StartIndex; tokenInfo.EndIndex = tokenizer.StopIndex; tokenInfo.Type = GetTokenType(token); tokenInfo.Color = GetTokenColor(tokenInfo); state = (tokenizer.BlockComment && !token.EndsWith("*/")) ? 1 : 0; return true; } void IScanner.SetSource(string source, int offset) { tokenizer.Text = source; } #endregion #region Private methods private TokenColor GetTokenColor(TokenInfo ti) { switch (ti.Type) { case TokenType.Comment: case TokenType.LineComment: return TokenColor.Comment; case TokenType.Literal: return TokenColor.String; case TokenType.Keyword: return TokenColor.Keyword; default: return TokenColor.Text; } } private TokenType GetTokenType(string token) { if (tokenizer.LineComment) return TokenType.Comment; else if (tokenizer.BlockComment) return TokenType.Comment; else if (IsKeyword(token)) return TokenType.Keyword; else if (tokenizer.Quoted) return TokenType.Literal; return TokenType.Text; } private bool IsKeyword(string token) { return keywords.Contains(token.ToUpperInvariant()); } private void Initialize() { if (keywords != null) return; keywords = new List(); // procedures and functions keywords.Add("CREATE"); keywords.Add("ALTER"); keywords.Add("PROCEDURE"); keywords.Add("CALL"); keywords.Add("RETURN"); keywords.Add("FUNCTION"); keywords.Add("RETURNS"); keywords.Add("DECLARE"); keywords.Add("DEFINER"); keywords.Add("CURRENT_USER"); keywords.Add("OUT"); keywords.Add("INOUT"); keywords.Add("IN"); keywords.Add("BEGIN"); keywords.Add("END"); keywords.Add("VIEW"); keywords.Add("AS"); keywords.Add("TRIGGER"); // update keywords.Add("UPDATE"); keywords.Add("TABLE"); // delete keywords.Add("DELETE"); // select keywords.Add("SELECT"); keywords.Add("FROM"); keywords.Add("WHERE"); keywords.Add("GROUP"); keywords.Add("BY"); keywords.Add("ASC"); keywords.Add("DESC"); keywords.Add("WITH"); keywords.Add("ROLLUP"); keywords.Add("HAVING"); keywords.Add("ORDER"); keywords.Add("LIMIT"); keywords.Add("OFFSET"); keywords.Add("INTO"); keywords.Add("OUTFILE"); keywords.Add("DUMPFILE"); keywords.Add("FOR"); keywords.Add("LOCK"); keywords.Add("SHARE"); keywords.Add("MODE"); keywords.Add("ALL"); keywords.Add("DISTINCT"); keywords.Add("DISTINCTROW"); keywords.Add("HIGH_PRIORITY"); keywords.Add("STRAIGHT_JOIN"); keywords.Add("SQL_SMALL_RESULT"); keywords.Add("SQL_BIG_RESULT"); keywords.Add("SQL_BUFFER_RESULT"); keywords.Add("SQL_CACHE"); keywords.Add("SQL_NO_CACHE"); keywords.Add("SQL_CALC_FOUND_ROWS"); // misc keywords.Add("SHOW"); keywords.Add("PROCESSLIST"); keywords.Add("KILL"); keywords.Add("STATUS"); // data types keywords.Add("INT"); keywords.Add("CHAR"); keywords.Add("VARCHAR"); // functions keywords.Add("COUNT"); keywords.Add("REPLACE"); // trigger keywords keywords.Add("BEFORE"); keywords.Add("AFTER"); keywords.Add("INSERT"); keywords.Add("ON"); keywords.Add("EACH"); keywords.Add("ROW"); keywords.Add("SET"); } #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/LanguageService/MySqlLanguageService.cs0000644000175000017500000000471511127003600032546 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Runtime.InteropServices; using Microsoft.VisualStudio.Package; using Microsoft.VisualStudio.TextManager.Interop; using System; namespace MySql.Data.VisualStudio { /// /// This language service will provide language /// [ComVisible(true)] [Guid("FA498A2D-116A-4f25-9B55-7938E8E6DDA7")] class MySqlLanguageService : LanguageService { private LanguagePreferences preferences; public const string LanguageName = "MySQL"; public override AuthoringScope ParseSource(ParseRequest req) { return null; } public override string Name { get { return LanguageName; } } public override string GetFormatFilterList() { return String.Empty; } public override IScanner GetScanner(IVsTextLines buffer) { return new MySqlScanner(); } public override LanguagePreferences GetLanguagePreferences() { if (preferences == null) { preferences = new LanguagePreferences(this.Site, typeof(MySqlLanguageService).GUID, LanguageName); preferences.Init(); } return preferences; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/MySqlProviderObjectFactory.cs0000644000175000017500000000477111127003600030711 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Data.AdoDotNet; using Microsoft.VisualStudio.Data; using System.Data.Common; namespace MySql.Data.VisualStudio { [Guid("D949EA95-EDA1-4b65-8A9E-266949A99360")] class MySqlProviderObjectFactory : AdoDotNetProviderObjectFactory { private static DbProviderFactory factory; internal static DbProviderFactory Factory { get { if (factory== null) factory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient"); return factory; } } public override object CreateObject(Type objType) { if (objType == typeof(DataConnectionUIControl)) return new MySqlDataConnectionUI(); else if (objType == typeof(DataConnectionProperties)) return new MySqlConnectionProperties(); else if (objType == typeof(DataConnectionSupport)) return new MySqlConnectionSupport(); if (objType == typeof(DataSourceSpecializer)) return new MySqlDataSourceSpecializer(); else if (objType == typeof(DataConnectionPromptDialog)) return new MySqlDataConnectionPromptDialog(); else return base.CreateObject(objType); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/PkgCmdID.cs0000644000175000017500000000463211127003600025030 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // PkgCmdID.cs // MUST match PkgCmdID.h using System; namespace MySql.Data.VisualStudio { static class PkgCmdIDList { public const uint cmdidConfig = 0x800; public const uint cmdCreateTable = 0x100; public const uint cmdAlterTable = 0x101; public const uint cmdCreateView = 0x110; public const uint cmdAlterView = 0x111; public const uint cmdCreateProcedure = 0x120; public const uint cmdAlterProcedure = 0x121; public const uint cmdCreateFunction = 0x130; public const uint cmdCreateTrigger = 0x140; public const uint cmdAlterTrigger = 0x141; public const uint cmdCreateUDF = 0x150; public const uint cmdDelete = 0x160; //public const uint cmdidConfig = 0x170; public const uint cmdidGlobalCreateTable=500; public const uint cmdidGlobalCreateView=501; public const uint cmdidGlobalCreateProcedure=502; public const uint cmdidGlobalCreateFunction=503; public const uint cmdidGlobalCreateUDF=504; }; static class SharedCommands { public const int cmdidPrimaryKey = 109; public const int cmdidIndexesAndKeys = 675; public const int cmdidForeignKeys = 676; public const int cmdidGenerateChangeScript = 173; } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/PkgCmd.vsct0000644000175000017500000003740611127003600025172 0ustar directhexdirecthex &Add New mysql-connector-net-6.4.3/Source/MySql.VisualStudio/VsPkg.cs0000644000175000017500000002255511127003600024504 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.ComponentModel.Design; using Microsoft.Win32; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio; using MySql.Data.VisualStudio.Properties; using System.Reflection; using EnvDTE; using Microsoft.VisualStudio.CommandBars; using MySql.Data.VisualStudio.Editors; namespace MySql.Data.VisualStudio { /// /// This is the class that implements the package exposed by this assembly. /// /// The minimum requirement for a class to be considered a valid package for Visual Studio /// is to implement the IVsPackage interface and register itself with the shell. /// This package uses the helper classes defined inside the Managed Package Framework (MPF) /// to do it: it derives from the Package class that provides the implementation of the /// IVsPackage interface and uses the registration attributes defined in the framework to /// register itself and its components with the shell. /// [ComVisible(true)] // This attribute tells the registration utility (regpkg.exe) that this class needs // to be registered as package. [PackageRegistration(UseManagedResourcesOnly = true)] // A Visual Studio component can be registered under different regitry roots; for instance // when you debug your package you want to register it in the experimental hive. This // attribute specifies the registry root to use if no one is provided to regpkg.exe with // the /root switch. [DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\9.0Exp")] // This attribute is used to register the informations needed to show the this package // in the Help/About dialog of Visual Studio. [InstalledProductRegistration(true, null, null, null)] [ProvideEditorFactory(typeof(SqlEditorFactory), 200, TrustLevel = __VSEDITORTRUSTLEVEL.ETL_AlwaysTrusted)] [ProvideEditorExtension(typeof(SqlEditorFactory), ".mysql", 32, ProjectGuid = "{A2FE74E1-B743-11D0-AE1A-00A0C90FFFC3}", TemplateDir = @"..\..\Templates", NameResourceID = 105, DefaultName = "MySQL SQL Editor")] [ProvideEditorLogicalView(typeof(SqlEditorFactory), "{7651a703-06e5-11d1-8ebd-00a0c90f26ea}")] [ProvideService(typeof(MySqlProviderObjectFactory), ServiceName = "MySQL Provider Object Factory")] [ProvideService(typeof(MySqlLanguageService))] [ProvideLanguageService(typeof(MySqlLanguageService), MySqlLanguageService.LanguageName, 101, RequestStockColors = true)] // In order be loaded inside Visual Studio in a machine that has not the VS SDK installed, // package needs to have a valid load key (it can be requested at // http://msdn.microsoft.com/vstudio/extend/). This attributes tells the shell that this // package has a load key embedded in its resources. [ProvideLoadKey("Standard", "1.0", "MySQL Tools for Visual Studio", "MySQL AB c/o MySQL, Inc.", 100)] // This attribute is needed to let the shell know that this package exposes some menus. [ProvideMenuResource(1000, 1)] // This attribute registers a tool window exposed by this package. [Guid(GuidStrings.Package)] public sealed class MySqlDataProviderPackage : Package, IVsInstalledProduct { private MySqlLanguageService languageService; public static MySqlDataProviderPackage Instance; /// /// Default constructor of the package. /// Inside this method you can place any initialization code that does not require /// any Visual Studio service because at this point the package object is created but /// not sited yet inside Visual Studio environment. The place to do all the other /// initialization is the Initialize method. /// public MySqlDataProviderPackage() : base() { if (Instance != null) throw new Exception("Creating second instance of package"); Instance = this; Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString())); } ///////////////////////////////////////////////////////////////////////////// // Overriden Package Implementation #region Package Members /// /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initilaization code that rely on services provided by VisualStudio. /// protected override void Initialize() { Trace.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); MySqlProviderObjectFactory factory = new MySqlProviderObjectFactory(); ((IServiceContainer)this).AddService( typeof(MySqlProviderObjectFactory), factory, true); base.Initialize(); RegisterEditorFactory(new SqlEditorFactory()); // Add our command handlers for menu (commands must exist in the .vsct file) OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (null != mcs) { // Create the command for the menu item. CommandID menuCommandID = new CommandID(Guids.CmdSet, (int)PkgCmdIDList.cmdidConfig); OleMenuCommand menuItem = new OleMenuCommand(ConfigCallback, menuCommandID); menuItem.BeforeQueryStatus += new EventHandler(configWizard_BeforeQueryStatus); mcs.AddCommand(menuItem); } languageService = new MySqlLanguageService(); languageService.SetSite(this); IServiceContainer serviceContainer = (IServiceContainer)this; serviceContainer.AddService(typeof(MySqlLanguageService), languageService, true); } #endregion void configWizard_BeforeQueryStatus(object sender, EventArgs e) { OleMenuCommand configButton = sender as OleMenuCommand; configButton.Visible = false; DTE dte = GetService(typeof(DTE)) as DTE; Array a = (Array)dte.ActiveSolutionProjects; if (a.Length != 1) return; Project p = (Project)a.GetValue(0); configButton.Visible = false; foreach (Property prop in p.Properties) { if (prop.Name == "WebSiteType" || prop.Name.StartsWith("WebApplication")) { configButton.Visible = true; break; } } } private void ConfigCallback(object sender, EventArgs e) { WebConfig.WebConfigDlg w = new WebConfig.WebConfigDlg(); w.ShowDialog(); } #region IVsInstalledProduct Members int IVsInstalledProduct.IdBmpSplash(out uint pIdBmp) { pIdBmp = 400; return VSConstants.S_OK; } int IVsInstalledProduct.IdIcoLogoForAboutbox(out uint pIdIco) { pIdIco = 400; return VSConstants.S_OK; } int IVsInstalledProduct.OfficialName(out string pbstrName) { pbstrName = Resources.ProductName; return VSConstants.S_OK; } int IVsInstalledProduct.ProductDetails(out string pbstrProductDetails) { pbstrProductDetails = Resources.ProductDetails; return VSConstants.S_OK; } int IVsInstalledProduct.ProductID(out string pbstrPID) { string fullname = Assembly.GetExecutingAssembly().FullName; string[] parts = fullname.Split(new char[] { '=' }); string[] versionParts = parts[1].Split(new char[] { '.' }); pbstrPID = String.Format("{0}.{1}.{2}", versionParts[0], versionParts[1], versionParts[2]); return VSConstants.S_OK; } #endregion } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/source.extension.vsixmanifest0000644000175000017500000000233711127003600031074 0ustar directhexdirecthex MySQL Tools for Visual Studio Oracle, Inc. 6.4 Database design tools for MySQL 1033 false Ultimate Premium Pro VSTS VSTD Visual Studio MPF |%CurrentProject%;PkgdefProjectOutputGroup| MySql.VisualStudio.pkgdef mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/0000755000175000017500000000000011127003600025064 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/sql_editor_connect.png0000644000175000017500000000150111127003600031445 0ustar directhexdirecthexPNG  IHDRsO/sRGBgAMA a pHYsodtEXtSoftwarePaint.NET v3.5.5IIDAT8O}ILSQ0ܹr!q.P\HD4Q@X4 D j@(2DI)P9P P2 V '=;?Wx7mo6o녑-=htz]IENDB`mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/sql_editor_banner.bmp0000644000175000017500000034314611127003600031271 0ustar directhexdirecthexBMf6(Vu8lZlZlZlZlZlZlZlZlZlZlZp_x<|OsbaNaNaNaNaNaNaNaNaNaNaNaNaNaNp_ɱQcQaNaNlZvaNaNaNɱ{{{.ĽaNaNaNr{{{M{k*p_p_eQhV aNfT|Cp_p_td êvHr4q2r4r4r4r4r4r4td aNaNaN§.#Mf.##{{{GV0#[flwShV aNaNQbaNaNaNaNaNQnaNaNaNUaNaNaNaNaNaNaNaNaNaNaNaNaNaNaN§}{{{{{{{{{{{{{.w{{{{{{{{{{{{{{#{{{{{{{{{{{{{9iw|lZaNaNUfTaNaNaNaNaNbOnaNaNcQ\aNaNbOMUaNaNaN§|||||||||i0{{{.{{{{9w|c}{{{}{{{{{{Bl|||||||||lSMilZaNaNUvaNaNhV bOaNaNenaNaNcQsbaNaNu8ĽaNaNaN§B{{{r{{{S9{{}}{{{{{rwwfwlZaNaNUp_aNaNHr4aNaNjXnaNaNcQtd aNaNMaNaNaN§r{{{l{{{{{{{{{{S[cSlZaNaNUaNaNaNɱaNaNaNnaNaNcQtd aNaNHaNaNaN§r{{{l{{{{{{{{lZaNaNUyi&aNaN{k*sbaNaNsbnaNaNcQtd aNaNHaNaNaN§B{{{l{{{{{{{{lZaNaNU§aNaNaNaNaNaNnaNaNcQtd aNaNHaNaNaN§|iiiiiV#{{{9l{{{{{{{{v:ѽlZaNaNUx~o0aNhV {k*aNYihV aNy>ϺaNxaNm[aN{k*dRaNºdRhV ɲhV aNy>ϺaN_dRaN}EhV aNy>vlZaNaN\fTaNaNHMaNaNcQܮ|aNaNcQQu8u8qŬ{k*{k*{k*̶#{{Bl{{{{{{{{dRƭdRv:ra\dRraaNodRm[dRƭdRv:z@v:ѽv:HizdRƭz@raaNdR̶raxh&m[ιz@z@aNaNdRdR̶raxh&ibz@ƭralZaNaNe|aNaNaNɱ̶aNaNaNq|aNaNcQ#{{Gi{{{{{{{{ϥnɲv:tv:dRaNodRɲv:toιv:ѽv:aNOxh&\OU͸̶v:aNѽ~o0͸aNaNtOU͸̶v:흒bOm[lZaNaNxaNaNaNaNaNaNjXaNaNbOaNaNaNĽaNaNaNcQaNaNcQ[{{{.[llllllllll{{{{#V[[[[[[9{{{{{{̶|ChV ɲv:tv:dRi\ɲaNom[tɲv:toѽv:ѽdRaNɲr5xh&Oιv:aNѽaNaNtιv:raͷxh&ιaNyi&aNaNaNaNaNsbyi&aNaNaNaNaNsb9{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{ȋ|CaNlZdRƭdRv:m[\odRιdRaN\radRƭv:dRƭdRoѽv:ѽaNѽHv:dRƭdRraéιaNzoiz@aNѽſz@dRaNom[ѽzoiz@ºV|l,ѽz@obƄu8fTaNaN{k*ρr4aNaNcQr4̶S.###########G........0S###cQaNQ~o0aNm[ιv:ve"aN_q`aN{k*aNm[aN_m[aN{k*~o0aNm[ιoѽv:ѽ\t7aN{k*aNY~o0aNm[{k*aNYi웏_dRaNq`v:aNaNѽxhV aNm[aNdRhV 웏_dRaNq`_aNdRxhV aN_ѽѽaNsbŬoaNѽaNѽaNhV ove"ѽaNaNaNlZ|CvoaN˰|Ctd p_lZaNvԪv|Ctd o/̶td o/aNѽv:\aNtd p_vaNUaNѽv:aNHaNx<{k*Ľyi&cQaNѽv:cQaNvѽaNɱ\jXaN|CoaNohV aNy>aN|l,웏_dRdRxoaN{k*aNYiſm[aNq`oooxhV aN_hV aN~o0ve"aNaNdRm[ιxhV aN_ѽr5maN{k*{k*aNy>oom[aN{k*dRaNcQbOx<o/M\aNaNQѽoaNoz@ƭraraι\m[bbz@toaNraaNm[dRoooz@oz@īv:ɲ|l,aNaNom[z@oz@ѽaNdRoiraooz@z@aNaNMxoy>aNy>݇y>aNy>hV aN_dRaN_aNaNaNaNdRhV ſhV aN_ѽv:aNm[v:ѽooxhV aNm[aNaNr4hUaN̶oaNaNoOѽaNoqo/bOo/oaNaNom[dRo̶aNnaNoaNaNaNaNaNaNoaNaNoaNѽohV p_lZjXhaNhx0,K`&,5<PEKg_<|/c5uIENDB`mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/package.ico0000644000175000017500000000427611127003600027164 0ustar directhexdirecthex ( @ʦ """)))UUUMMMBBB999|PP3f3333f333ff3fffff3f3f̙f3333f3333333333f3333333f3f33ff3f3f3f3333f3333333f3̙33333f333ff3ffffff3f33f3ff3f3f3ffff3fffffffff3fffffff3f̙ffff3ff333f3ff33fff33f3ff̙3f3f3333f333ff3fffff̙̙3̙f̙̙̙3f̙3f3f3333f333ff3fffff3f3f̙3ffffffffff!___wwwCCCCmmmssssKKKssmmmssssKKKssmmmsyyzYY1111KKsyyzYY1111KKsYYzYY2211KKmmsYYzYY2211KKmmtYYzYY2211KKtYYzYY2211KKtYYzYY2211KKOOIIIzYY2211KKOOIIIzYY2211KKPPIIzYY2211KKPPIIzYY2211KKrrrrPPOOIIIIzYY2211KKrrrrPPOOIIIIzYY2211KKIIzzYYKKrrrrPPOOOOÚssrrrrPPOOOOÚssrrrrttsssttrrrrttsssttxxrrrxxrrrmysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/sql_editor_executionplan.png0000644000175000017500000000141411127003600032675 0ustar directhexdirecthexPNG  IHDRasRGBgAMA a pHYsodtEXtSoftwarePaint.NET v3.5.5I|IDAT8OKSaǭ..(D4H+щ,e4MT64s)F:iSƴr64miklMO>są̨ޗ/y2َxקS՞q'd etlέ94+E\ǒ/|ut퟊Xӛνg87MKC+.Q]!m}P DEs`H`; `_ Pp EiT1\ÜN3b[S'`栳=P%GDCx@}QD K ߎnZ?ڹz!Ex@UA,a#[@D@+*GcsD ͒5"D bZ ur)5/>>.[z1 lڶCIgS1< VX÷NQ܋q5q%J=D;;W*N5S4y؝,\/mA:Nv* .v]5i.mcbtʇehKI3$_Nd\{ {,m7+[(|L\hVrjHII¬9"Ÿ`ə+r4MKqҮa%AIENDB`mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/Key.bmp0000644000175000017500000000227211127003600026317 0ustar directhexdirecthexBM6( mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/sql_editor_validatesql.png0000644000175000017500000000145611127003600032336 0ustar directhexdirecthexPNG  IHDRasRGBgAMA a pHYsodtEXtSoftwarePaint.NET v3.5.5IIDAT8O}HSQogP(BNJ K7Mw##9WNkS7fZjΙkKHU%# p8Ϗ<̳a:֠my[?ј y/{K]3fӯpz0軋) TfSBZ5%n]=r p/ӚycC%K+h- Œ1B,hja&lT>4 )Ζ!>)7F0Wt@2MT؊UX/ *M y pFr<,|WHWr kBT(Bq<U>@FTL݀cjK "( \x; wH\Fsb!>T*.CeULֿV7`_IENDB`mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/icon.bmp0000644000175000017500000000206611127003600026520 0ustar directhexdirecthexBM66( 5dH/kdH/raE.h4=+CqK՘eۤnۤmۣlӗdpJ#:nIjҨrʶмͳuңf[lGzQۡkȫtqĵȶʙȕðtXOܟfxOI4#%ݠiedȸ̩Ôξög?ߠi Wƚ`OϮȢtŹֿѺ0ɔJTךf䫎JG±zΰβ`:,՘eڝf28BgǞǧеʪnªcI!ߟi`@ә`q3OYķv\_CܝdҖcܞgcn|,k{ͭӰٸİs-ߟjۜhȎjv}̺׶\SÔ̡ٷ:%ڜgٛg]Fr!z”ìiʴqȷÖðu-ɑLךfNۜho"xƸðv̸}м˹ȟָT)ܝhܝhCܝf{5`şȟʠʡǞT8ߟij3jޟiɑU9OfL:ΔWޟijjBjjjjjj<mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/bannrbmp.bmp0000644000175000017500000024760611127003600027402 0ustar directhexdirecthexBMO6(:׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yuspomkgecb^\ZWUSONMIHEC@?<;:642/-,}*|)|'z%z#y xwutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yuspomkgecb^\ZWUSONMIHEC@?<;:642/-,}*|)|'z%z#y xwutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusnnpniigb]\ZXVSMLLIGCCB?<<;:730-(},|+{*z'y$w wwutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusvplkgda_`\VPLIF}F|A}B~?~=;98:98442/-/}*|)z'z%z#y"yyutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusopphbba[ZTQ|MtGo@|k:ud1n^4n]2p]0t`0xc/{g.l2r5v+320111|,*~)|'{$z#z xwutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusunhgeb\WRsD{g8m]/_P)UJ*ME.C=*MB"NA!P?S@UCYG"]N'_S+n`&zh-l+x13}-//)~'}&|"|"{!wuutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusopojf_~R|pHe]5YR+MI&IB!J?^J'vY2`5|X4wZ5gT/MD9640 ;5C:?@VJ"kP${\'k+u*}+}'})~(}&|"{!{!y"w utsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusqnjbYqJm[6aN+cG)}Z8xRʓh۟qw|~߱߮~{ߣy֛sahAmM$C.C1G9SCgNz^!o'y*{+|+~(|"z y y w utsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusrjbUwd>iO*|]6ySԥmװy޿ə̞˝˝˝˓͔͔ʒő߾߱ۥvɒga9K>45?:WGoUe*q'w*{*{$z yxvutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yushbxMsb;~gA]Ϧy躋Ƞɟɞɜʛ˚ʙʙȚȚǘƖƓƎĊˆ׿}۲{њsfFH955G@eMdn$w'{%|"{!xvutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶ̲ɱ}zywmexGqe;xUҤtտʛ˖ə˛ĞşʑǏÕȔǏƍŒËȌÇ|ӽ{ԫlӢjj/B*@:WOq`!j w&z#y!v{utsrqppon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶŵű­y©wsapOwGןn۲˓ėݿ˚ÐŎŊxrr˷~ŠrµkuÊԿϻӴӵ~ֱyΤohJH4>8 ^Gw]!j v!zzsutsrqppon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶ˴ò~ĭ{ve|KxQ٢oܴɕʛՈďӻdz|ѬհcÂɶkŦɼϹܾطʸ{xз͹xͳqҭq̦lwBcH&D2 \It[o{ ys utsrqppon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶŶİĮ~|iUSؠoԽƗϿÄм{ĬvmóqӿxcÛomIJqϼq]λfnнrӹsʯoʬeΪ^ΞtjT+G6cNvamtw utsrqppon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶƵ±ƯqWY٤yӽ˾мԹλwhѱұf_^ܿƛku޼۹r̲pдtɳrǭk˫`͠\ӤnnQ%L<jNj#pxutsrqppon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶδxc\Ԟo޹ɻֽ׿˳}qӱԨrɳqʹpDzgƭgcɩPϝUӡlgHO=pZ hxutsrqppon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶ˳óm^Пmڳ|Ǹzݷ}˼wóqͰwkñ׵bҼtõibî]ì^ŪS¢O˚Vn9G7VI}cnutsrqppon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶųzfbͩsŸzuIJwëiX\ɰTNֽlbp̨RȠXXLIŸ_l=K; eVkutsrqppon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶĴ~bѥeƳoƵlȮxǡ`vKЮڼħNĨQ?C<ܝ`gG#XI|`mstsqqqon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶƴ}pџkȪi˱odêldϰN¡\JA7ƕEr=J@p\jrssqqpon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶɴtdѤkfūi^\L齪}¥JĢ\ˣK54+ͣ\]J^Meorsqppon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶʳpڠle`\ǨYPE\ЧZͰNL@:0"Ïfrspqonn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶԟly+u{wX™޿ïuȲp}ŇǍ̍ϑΚЛӞԟҝ͘Зϕ˵{Ҳͽ:/# }}ǍAv;httoppnn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶߤvy,o tw srw Ӹ¬k׾xۿʋʍ̓̕ЙʕϚ͕̓Ǎmݿɿn12#wǎIt9jttopqon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶήs1h ox'~ȼڷbǶevԸwČĉ̆ˉɐʖċ̈ȁɶyԿ˟QDG,|vҔXoprrtsqmn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶͭx@egBLOsܿпbʳh}غؾŇڿč…Ȅȶwwٺѿ_K~v מ`lprrsrqon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶ̯՜_cePV—۵ȺaηiԺnռtzٽv~ؾxyehΤkP}ΖUlpssrqqpn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶ˷ӟji fKaÞÎ]bʵqʴrѼxɳqűpixڨԲ߹xįkFq7Cpsssrppon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶóϪv|7b8dŲ۸ӬέٵȡȻʣϮٵųvñ|kͳg)wȓPt1tttrqqpon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶĶ˳}ŌX}^{Ƭjjmu{Ϯ̧DZκȶ{̺{϶fu rǛ\nutsqqsqon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǷŴ{٬sn!aWòyɳrǵv~ģͽκƵ|Ϻ}?s A?yvusqqqqpn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶİǹѯmŽL|a{+ѳ|Ǹyɻ۽͹ɰputݠ^q$wuutrpppon׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶøĴ̰zծpo}aSɶĸԴҺśż&mBBty"utsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶƵõdzʩwǝZa eɷv˻ƿҰğȞØΣśŕFj|&ƔRt){vutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶͶƭիv>~['͹ǜÛÝÚ̪ɟǚ͝ʚēħ\ss ͘U?v!y{utsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶ͵óϭҦiy*Z9ÔɡƗɠ˦ѱʪϦȡ̟Ĭpp kēEL{"ys {utsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶIJôǹ{vάwӧho&b@ɤΰɝЪռзϲͲб̨ʱsj h;Mx)|{!s xutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶöǵð}´zŶ~wˣrѡgtau.ŚӳͱѸԹ˭ѸֿӶӲеѺӳϟT~eo;Lz/{ z |'xvutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶŸ²Ŷ~sưũzǧrӧjx/bmйѰײԹӼԶڸڽչ׿ڽڸܵپӸ˘'kjʔGGz2y&{{$u |!tutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǹ~±{òywzsʤtҥh?_t_PȦٿۺٻ߿ٽ۽ݻճ[m fjҜ[ɎH#{,z.~&{{"v xutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusoçkΧiǗUt+|V|bJһھfpgj:֛iM+}*|)|'z%z#y xwutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yussokƥfˣbPl#V wb6Dz{ӷٸͼCea \/УZR:2(}*|)|'z%z#y xwutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusprqjȩi̝_ƑRv'byZzak1TRZQ=t b^fl4МUPA6()/}*|)|'z%z#y xwutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusĬxokmiedžbաeآeĐN~6u'ha~a~cdipz(B̖ZԛgSB81*.3{1}*|)|'z%z#y xwutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusmpnmhbcbcbaǚaϝc֟fۢkڡjghݠh՜eɗ]SG><;8367z+-}*|)|'z%z#y xwutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusnqkfhdb_[\WTXVPTTNHD>>><6678520-}*|)|'z%z#y xwutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusqomijfdb^XZYQSVRLIIGCB@>8855/.3{+}*|)|'z%z#y xwutsrqpppn׼ֻԹҶҴѳϯͭͫ˩ɧǣƢşÝÛ̼̾˼ʺȸƶǶŴò}°{yusrorjhfca^][YXRJGHGFGEC>;?9711.))}*|)|'z%z#y xwutsrqpppnmysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/messages_icon.png0000644000175000017500000000072111127003600030411 0ustar directhexdirecthexPNG  IHDRagAMA a pHYs(JtEXtSoftwarePaint.NET v3.5.5INIDAT8O=r0F3L$D;s8uPOEEǤ'PI[i}`뛸SO}ߚ"Ng]CP@T_jm)~$g^Op0MS1q5ppg d Aw6ˀgkÂG3R$ <ϸ^$.˒&~Vy٩4Iɨ%MeyL`-fj"w,V *` `OKu u0ټAk$G`8ƀM] L XHv*Pi @(7~g0ɎJBnIENDB`mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/ArrowKey.bmp0000644000175000017500000000227211127003600027332 0ustar directhexdirecthexBM6( mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/401.ico0000644000175000017500000002154611127003600026074 0ustar directhexdirecthex  F  hh( @ hVcI5cI5cI5cI5cI5cI5cI5cI5cI5cI5cI5cI5cI5cI5cI5cI5cI5cI5cI5cI5cI5cI5kYܾۼۻٹطص׳ְֱԭԫҪҨЦФϣϠ͟͞cI5n[Ͽͼ˹ɶǴ͠cI5p^ϾͼʹȷϡcI5saο̻˹ТcI5vdQxNtKqJnHkEiCgCgBd@c}@b}@b}@b}`uο̼ФcI5xgZ[^^^^]^^^^^YVSKV`ξѦcI5{i^Y<:eEawҩcI5}l_\YYYYYYYYYY@::Bd}ӫcI5oXGCC???E?c[oԬcI5qZ}faaZTNIDIbtծcI5spGBB??TGTXrֱcI5vr~vnnga[lPr׳cI5yuQ|MHBB?lbYw׵cI5{r~~xonٷcI5~UwR|MGCCx[ڹcI5_ۺcI5UwR|LGCCZua][ۼcI5[y{\ܾcI5knVp_cI5~{ywvvspllhx³cI5ĶcI5ǸcI5ɴxcI5vcI5cI5cI5cI5cI5yŽDZlR>|ży`Lĺ~p]ɿ¯nƾűï®( @cI5lR>y`LKV`EawIbt@b}Bd}[ohVkYn[p]savdxg{i}lnqsvyyx{|~BfEiHkJnKqNtPrXrZuYw[yUwQxZ}Q|`u?[Y[\^nuprLGH_B[ackhlxeqvwy{:2OZ<rYHHGEEDD@@?Atv{}p~y٨h h{zxvurqnlj(  ɻƶὬ๦ߵթ̻ߵ­bUSQPMJ๦űvttttfsi~}{w;+tjc][XWUSRymysql-connector-net-6.4.3/Source/MySql.VisualStudio/Resources/sql_editor_disconnect.png0000644000175000017500000000163111127003600032151 0ustar directhexdirecthexPNG  IHDRasRGBgAMA a pHYsodtEXtSoftwarePaint.NET v3.5.5I IDAT8OmkHa_ >OчQнe%]mD+2j)eH"UjW/dm:-sN,5[94$tyZ99sHz/8ֹyڄ".qCi}?xxhlQQd'PTZˎ^M0%=ׂц;~49I"C[~Z)wDMW[9H*l;hMy֦”Z  P`, Zǥ!y<Lv?1V<,;H~T*՗ch:{ ɫYI Dc06"(̬Bq0lDW4Ȳ$X-g Q0nkҼj46682Ok J7fV'jȩGBObn3^qQ/v(}ae8"jp351HbeVzr6gq1ÀJ'gi2"q, like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using MySql.Data.VisualStudio.DbObjects; using System.ComponentModel; using System.Collections.Generic; namespace MySql.Data.VisualStudio.DbObjects { internal class DataTypeConverter : StringConverter { private List dataTypes = new List(); public DataTypeConverter() { dataTypes.AddRange(Metadata.GetDataTypes(false)); } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { StandardValuesCollection coll = new StandardValuesCollection(dataTypes); return coll; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/Enums.cs0000644000175000017500000000265511127003600026377 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data; using System.ComponentModel; namespace MySql.Data.VisualStudio.DbObjects { internal enum RowFormat { Default, Dynamic, Fixed, Compact, Compressed } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/Column.cs0000644000175000017500000002362411127003600026544 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data; using System.ComponentModel; using MySql.Data.VisualStudio.Editors; using MySql.Data.VisualStudio.DbObjects; using System.Windows.Forms.Design; namespace MySql.Data.VisualStudio.DbObjects { internal class Column : Object, ITablePart { private string characterSet; internal Column OldColumn; private bool isNew; private Column() { AllowNull = true; } public Column(DataRow row) : this() { isNew = row == null; if (row != null) ParseColumnInfo(row); OldColumn = new Column(); ObjectHelper.Copy(this, OldColumn); } #region Properties [Browsable(false)] internal Table OwningTable; private string _columnName; [Category("General")] [Description("The name of this column")] public string ColumnName { get { return _columnName; } set { _columnName = value; } } private string _dataType; [Category("General")] [DisplayName("Data Type")] [TypeConverter(typeof(DataTypeConverter))] [RefreshProperties(RefreshProperties.All)] public string DataType { get { return _dataType; } set { _dataType = value; } } private bool _allowNull; [TypeConverter(typeof(YesNoTypeConverter))] [Category("Options")] [DisplayName("Allow Nulls")] public bool AllowNull { get { return _allowNull; } set { _allowNull = value; } } private bool _isUnsigned; [TypeConverter(typeof(YesNoTypeConverter))] [Category("Options")] [DisplayName("Is Unsigned")] public bool IsUnsigned { get { return _isUnsigned; } set { _isUnsigned = value; } } private bool _isZeroFill; [TypeConverter(typeof(YesNoTypeConverter))] [Category("Options")] [DisplayName("Is Zerofill")] public bool IsZerofill { get { return _isZeroFill; } set { _isZeroFill = value; } } private string _defaultValue; [Category("General")] [DisplayName("Default Value")] public string DefaultValue { get { return _defaultValue; } set { _defaultValue = value; } } private bool _autoIncrement; [TypeConverter(typeof(YesNoTypeConverter))] [Category("Options")] [DisplayName("Autoincrement")] public bool AutoIncrement { get { return _autoIncrement; } set { _autoIncrement = value; } } //[TypeConverter(typeof(YesNoTypeConverter))] //[Category("Options")] //[DisplayName("Primary Key")] //[RefreshProperties(RefreshProperties.All)] [Browsable(false)] public bool PrimaryKey; private int _precision; public int Precision { get { return _precision; } set { _precision = value; } } private int _scale; public int Scale { get { return _scale; } set { _scale = value; } } [Category("Encoding")] [DisplayName("Character Set")] [TypeConverter(typeof(CharacterSetTypeConverter))] public string CharacterSet { get { return characterSet; } set { if (value != characterSet) Collation = String.Empty; characterSet = value; } } private string _collation; [Category("Encoding")] [TypeConverter(typeof(CollationTypeConverter))] public string Collation { get { return _collation; } set { _collation = value; } } private string _comment; [Category("Miscellaneous")] public string Comment { get { return _comment; } set { _comment = value; } } #endregion private void ParseColumnInfo(DataRow row) { ColumnName = row["COLUMN_NAME"].ToString(); AllowNull = row["IS_NULLABLE"] != DBNull.Value && row["IS_NULLABLE"].ToString() == "YES"; Comment = row["COLUMN_COMMENT"].ToString(); Collation = row["COLLATION_NAME"].ToString(); CharacterSet = row["CHARACTER_SET_NAME"].ToString(); DefaultValue = row["COLUMN_DEFAULT"].ToString(); string columnType = row["COLUMN_TYPE"].ToString().ToLowerInvariant(); int index = columnType.IndexOf(' '); if (index == -1) index = columnType.Length; DataType = columnType.Substring(0, index); CleanDataType(); columnType = columnType.Substring(index); IsUnsigned = columnType.IndexOf("unsigned") != -1; IsZerofill = columnType.IndexOf("zerofill") != -1; PrimaryKey = row["COLUMN_KEY"].ToString() == "PRI"; Precision = DataRowHelpers.GetValueAsInt32(row, "NUMERIC_PRECISION"); Scale = DataRowHelpers.GetValueAsInt32(row, "NUMERIC_SCALE"); string extra = row["EXTRA"].ToString().ToLowerInvariant(); if (extra != null) AutoIncrement = extra.IndexOf("auto_increment") != -1; } private void CleanDataType() { if (DataType.Contains("char") || DataType.Contains("binary")) return; int index = DataType.IndexOf("("); if (index == -1) return; DataType = DataType.Substring(0, index); } #region Methods needed so PropertyGrid won't bold our values private bool ShouldSerializeColumnName() { return false; } private bool ShouldSerializeDataType() { return false; } private bool ShouldSerializeAllowNull() { return false; } private bool ShouldSerializeIsUnsigned() { return false; } private bool ShouldSerializeIsZerofill() { return false; } private bool ShouldSerializeDefaultValue() { return false; } private bool ShouldSerializeAutoIncrement() { return false; } private bool ShouldSerializePrimaryKey() { return false; } private bool ShouldSerializePrecision() { return false; } private bool ShouldSerializeScale() { return false; } private bool ShouldSerializeCharacterSet() { return false; } private bool ShouldSerializeCollation() { return false; } private bool ShouldSerializeComment() { return false; } #endregion #region ITablePart Members void ITablePart.Saved() { ObjectHelper.Copy(this, OldColumn); } bool ITablePart.HasChanges() { return !ObjectHelper.AreEqual(this, OldColumn); } bool ITablePart.IsNew() { return isNew; } string ITablePart.GetDropSql() { return String.Format("DROP `{0}`", ColumnName); } string ITablePart.GetSql(bool newTable) { if (OldColumn != null && OldColumn.ColumnName != null && ObjectHelper.AreEqual(this, OldColumn)) return null; if (String.IsNullOrEmpty(ColumnName)) return null; StringBuilder props = new StringBuilder(); props.AppendFormat(" {0}", DataType); if (!String.IsNullOrEmpty(CharacterSet)) props.AppendFormat(" CHARACTER SET '{0}'", CharacterSet); if (!String.IsNullOrEmpty(Collation)) props.AppendFormat(" COLLATE '{0}'", Collation); if (!String.IsNullOrEmpty(DefaultValue)) props.AppendFormat(" DEFAULT '{0}'", DefaultValue); if (!String.IsNullOrEmpty(Comment)) props.AppendFormat(" COMMENT '{0}'", Comment); if (!AllowNull) props.Append(" NOT NULL"); if (IsUnsigned) props.Append(" UNSIGNED"); if (IsZerofill) props.Append(" ZEROFILL"); if (AutoIncrement) props.Append(" AUTO_INCREMENT"); if (newTable) return String.Format("`{0}`{1}", ColumnName, props.ToString()); if (isNew) return String.Format("ADD `{0}`{1}", ColumnName, props.ToString()); return String.Format("CHANGE `{0}` `{1}` {2}", OldColumn.ColumnName, ColumnName, props.ToString()); } #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/ObjectComparer.cs0000644000175000017500000000532311127003600030202 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Diagnostics; namespace MySql.Data.VisualStudio.DbObjects { class ObjectHelper { public static bool AreEqual(object one, object two) { if (one == null && two != null) return false; if (one != null && two == null) return false; Type firstType = one.GetType(); Type secondType = two.GetType(); PropertyInfo[] properties = firstType.GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo property in properties) { object firstValue = property.GetValue(one, null); if (!(firstValue is IComparable)) continue; object secondValue = property.GetValue(two, null); if (!firstValue.Equals(secondValue)) return false; } return true; } public static void Copy(object from, object to) { Type firstType = from.GetType(); Type secondType = to.GetType(); PropertyInfo[] properties = firstType.GetProperties( BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.SetProperty); foreach (PropertyInfo property in properties) { if (!property.CanWrite) continue; object firstValue = property.GetValue(from, null); property.SetValue(to, firstValue, null); } } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/CollationTypeConverter.cs0000644000175000017500000000600711127003600031761 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data; using System.ComponentModel; using System.Collections; using System.Diagnostics; namespace MySql.Data.VisualStudio.DbObjects { internal class CollationTypeConverter : StringConverter { private DataTable collationData; public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { Table table = (context.Instance is Table) ? (context.Instance as Table) : (context.Instance as Column).OwningTable; if (collationData == null) PopulateList(table); StandardValuesCollection coll = new StandardValuesCollection(GetRelevantCollations(context.Instance)); return coll; } private List GetRelevantCollations(object instance) { List collations = new List(); string charset = String.Empty; if (instance is Table) charset = (instance as Table).CharacterSet; else charset = (instance as Column).CharacterSet; if (String.IsNullOrEmpty(charset)) return collations; foreach (DataRow row in collationData.Rows) if (row["charset"].Equals(charset)) collations.Add(row["collation"].ToString()); return collations; } private void PopulateList(Table table) { collationData = table.OwningNode.GetDataTable("SHOW COLLATION"); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/ForeignKey.cs0000644000175000017500000002031411127003600027342 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data; namespace MySql.Data.VisualStudio.DbObjects { class ForeignKey : Object, ITablePart { bool isNew; ForeignKey oldFk; Table Table; private ForeignKey(Table t) { Table = t; SetName(String.Format("FK_{0}_{0}", t.Name), true); Columns = new List(); } public ForeignKey(Table t, DataRow keyData) : this (t) { isNew = keyData == null; if (!isNew) { ParseFKInfo(keyData); (this as ITablePart).Saved(); } } private void ParseFKInfo(DataRow keyData) { Name = keyData["CONSTRAINT_NAME"].ToString(); ReferencedTable = keyData["REFERENCED_TABLE_NAME"].ToString(); if (keyData["MATCH_OPTION"] != DBNull.Value) Match = (MatchOption)Enum.Parse(typeof(MatchOption), keyData["MATCH_OPTION"].ToString(), true); if (keyData["UPDATE_RULE"] != DBNull.Value) UpdateAction = (ReferenceOption)Enum.Parse(typeof(ReferenceOption), keyData["UPDATE_RULE"].ToString(), true); if (keyData["DELETE_RULE"] != DBNull.Value) DeleteAction = (ReferenceOption)Enum.Parse(typeof(ReferenceOption), keyData["DELETE_RULE"].ToString(), true); string[] restrictions = new string[4] { null, Table.OwningNode.Database, Table.Name, Name }; DataTable cols = Table.OwningNode.GetSchema("Foreign Key Columns", restrictions); foreach (DataRow row in cols.Rows) { FKColumnPair colPair = new FKColumnPair(); colPair.Column = row["COLUMN_NAME"].ToString(); colPair.ReferencedColumn = row["REFERENCED_COLUMN_NAME"].ToString(); Columns.Add(colPair); } } private string _name; public string Name { get { return _name; } set { _name = value; } } private string _referencedTable; public string ReferencedTable { get { return _referencedTable; } set { _referencedTable = value; } } private MatchOption _match; public MatchOption Match { get { return _match; } set { _match = value; } } private ReferenceOption _updateAction; public ReferenceOption UpdateAction { get { return _updateAction; } set { _updateAction = value; } } private ReferenceOption _deleteAction; public ReferenceOption DeleteAction { get { return _deleteAction; } set { _deleteAction = value; } } private List _columns; public List Columns { get { return _columns; } set { _columns = value; } } public bool NameSet; public override string ToString() { return Name; } public void SetName(string name, bool makeUnique) { string proposedName = name; int uniqueIndex = 0; if (makeUnique) { while (true) { bool found = false; foreach (ForeignKey k in Table.ForeignKeys) if (k.Name == proposedName) { found = true; break; } if (!found) break; proposedName = String.Format("{0}_{1}", name, ++uniqueIndex); } } Name = proposedName; } #region ITablePart Members void ITablePart.Saved() { if (oldFk == null) oldFk = new ForeignKey(Table); // copy over the top level properties oldFk.DeleteAction = DeleteAction; oldFk.Match = Match; oldFk.Name = Name; oldFk.ReferencedTable = ReferencedTable; oldFk.Table = Table; oldFk.UpdateAction = UpdateAction; // now we need to copy the columns oldFk.Columns.Clear(); foreach (FKColumnPair fc in Columns) { FKColumnPair old = new FKColumnPair(); old.ReferencedColumn = fc.ReferencedColumn; old.Column = fc.Column; oldFk.Columns.Add(old); } } bool ITablePart.HasChanges() { if (!ObjectHelper.AreEqual(this, oldFk)) return true; if (Columns.Count != oldFk.Columns.Count) return true; foreach (FKColumnPair fc in Columns) { int i = 0; for (; i < oldFk.Columns.Count; i++) { FKColumnPair ofc = oldFk.Columns[i]; if (ofc.ReferencedColumn == fc.ReferencedColumn && ofc.Column == fc.Column) break; } if (i == oldFk.Columns.Count) return true; } return false; } string ITablePart.GetDropSql() { return String.Format("DROP FOREIGN KEY `{0}`", Name); } string ITablePart.GetSql(bool newTable) { // if we don't have any changes then just return null if (!(this as ITablePart).HasChanges()) return null; StringBuilder sql = new StringBuilder(); if (!newTable) { if (oldFk != null) sql.AppendFormat("DROP FOREIGN KEY `{0}`, ", oldFk.Name); sql.Append("ADD "); } sql.AppendFormat("FOREIGN KEY `{0}`", Name); sql.Append("("); string delimiter = ""; foreach (FKColumnPair c in Columns) { sql.AppendFormat("{0}{1}", delimiter, c.Column); delimiter = ", "; } sql.Append(")"); sql.AppendFormat(" REFERENCES `{0}`(", ReferencedTable); delimiter = ""; foreach (FKColumnPair c in Columns) { sql.AppendFormat("{0}{1}", delimiter, c.ReferencedColumn); delimiter = ", "; } sql.Append(")"); return sql.ToString(); } bool ITablePart.IsNew() { return isNew; } #endregion } enum MatchOption { Full, Partial, Simple, None } enum ReferenceOption : int { NoAction, Cascade, Restrict, SetNull } class FKColumnPair { public string ReferencedColumn; public string Column; } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/TableEngineTypeConverters.cs0000644000175000017500000000457411127003600032404 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data; using System.ComponentModel; using System.Collections; using System.Diagnostics; namespace MySql.Data.VisualStudio.DbObjects { internal class TableEngineTypeConverter : StringConverter { private List engineList; public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { Debug.Assert(context.Instance is Table); Table table = context.Instance as Table; if (engineList == null) PopulateList(table); StandardValuesCollection coll = new StandardValuesCollection(engineList); return coll; } private void PopulateList(Table table) { engineList = new List(); DataTable data = table.OwningNode.GetDataTable("SHOW ENGINES"); foreach (DataRow row in data.Rows) { if (!row[1].Equals("NO")) engineList.Add(row[0].ToString()); } } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/IndexColumnTypeConverter.cs0000644000175000017500000000427511127003600032267 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.ComponentModel; using System.Globalization; using System.Collections.Generic; using System.Text; namespace MySql.Data.VisualStudio.DbObjects { class IndexColumnTypeConverter : TypeConverter { public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(String)) { StringBuilder str = new StringBuilder(); List cols = (value as List); string separator = String.Empty; foreach (IndexColumn ic in cols) { str.AppendFormat("{2}{0} ({1})", ic.ColumnName, ic.SortOrder == IndexSortOrder.Ascending ? "ASC" : "DESC", separator); separator = ","; } return str.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/ColumnWithTypeDescriptor.cs0000644000175000017500000001044511127003600032276 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.ComponentModel; using System; using System.Collections.Generic; using MySql.Data.VisualStudio.DbObjects; using MySql.Data.VisualStudio.Editors; namespace MySql.Data.VisualStudio.DbObjects { class ColumnWithTypeDescriptor : Column, ICustomTypeDescriptor { public ColumnWithTypeDescriptor() : base(null) { } #region ICustomTypeDescriptor Members public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } EventDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } public string GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) { return this; } public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { PropertyDescriptorCollection coll = TypeDescriptor.GetProperties(this, attributes, true); List props = new List(); foreach (PropertyDescriptor pd in coll) { if (!pd.IsBrowsable) continue; if (pd.Name == "Precision" || pd.Name == "Scale") { if (DataType != null && DataType.ToLowerInvariant() == "decimal") props.Add(pd); } else if (pd.Name == "CharacterSet" || pd.Name == "Collation") { CustomPropertyDescriptor newPd = new CustomPropertyDescriptor(pd); newPd.SetReadOnly(DataType == null || !Metadata.IsStringType(DataType)); props.Add(newPd); } else props.Add(pd); } return new PropertyDescriptorCollection(props.ToArray()); } PropertyDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetProperties() { return TypeDescriptor.GetProperties(this, true); } public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } public string GetClassName() { return TypeDescriptor.GetClassName(this, true); } #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/Table.cs0000644000175000017500000005626611127003600026346 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data; using System.ComponentModel; using MySql.Data.VisualStudio.Properties; using System.Runtime.InteropServices; using Microsoft.VisualStudio.OLE.Interop; using MySql.Data.VisualStudio.Editors; using System.Windows.Forms; namespace MySql.Data.VisualStudio.DbObjects { public enum InsertMethod { No, First, Last } public enum PackKeysMethod { Default, None, Full } internal class Table : ICustomTypeDescriptor { private TableNode owningNode; internal Table OldTable; private string characterSet; private Table() { } public Table(TableNode node, DataRow row, DataTable columns) { owningNode = node; IsNew = row == null; Columns = new TablePartCollection(); Indexes = new TablePartCollection(); ForeignKeys = new TablePartCollection(); // set some defaults that may be overridden with actual table data Engine = node.DefaultStorageEngine; PackKeys = PackKeysMethod.Default; Schema = node.Database; if (row != null) ParseTableData(row); if (columns != null) ParseColumns(columns); if (!IsNew) { LoadIndexes(); LoadForeignKeys(); } // now save our current values as old OldTable = new Table(); ObjectHelper.Copy(this, OldTable); node.DataSaved += new EventHandler(node_DataSaved); } void node_DataSaved(object sender, EventArgs e) { ObjectHelper.Copy(this, OldTable); Columns.Saved(); Indexes.Saved(); ForeignKeys.Saved(); } private bool _isNew; [Browsable(false)] public bool IsNew { get { return _isNew; } private set { _isNew = value; } } private TablePartCollection _columns; [Browsable(false)] public TablePartCollection Columns { get { return _columns; } private set { _columns = value; } } private TablePartCollection _indexes; [Browsable(false)] public TablePartCollection Indexes { get { return _indexes; } private set { _indexes = value; } } private TablePartCollection _foreignKeys; [Browsable(false)] public TablePartCollection ForeignKeys { get { return _foreignKeys; } private set { _foreignKeys = value; } } internal TableNode OwningNode { get { return owningNode; } } internal bool SupportsFK { get { string engine = Engine.ToLowerInvariant(); return engine == "innodb" || engine == "falcon"; } } #region Table options private string _name; [Category("(Identity)")] [MyDescription("TableNameDesc")] public string Name { get { return _name; } set { _name = value; } } private string _schema; [Category("(Identity)")] [MyDescription("TableSchemaDesc")] public string Schema { get { return _schema; } private set { _schema = value; } } private string _comment; [MyDescription("TableCommentDesc")] public string Comment { get { return _comment; } set { _comment = value; } } [Category("Table Options")] [DisplayName("Character Set")] [TypeConverter(typeof(CharacterSetTypeConverter))] [RefreshProperties(RefreshProperties.All)] [MyDescription("TableCharSetDesc")] public string CharacterSet { get { return characterSet; } set { if (value != characterSet) Collation = String.Empty; characterSet = value; } } private string _collation; [Category("Table Options")] [DisplayName("Collation")] [TypeConverter(typeof(CollationTypeConverter))] [MyDescription("TableCollationDesc")] public string Collation { get { return _collation; } set { _collation = value; } } private ulong _autoInc; [Category("Table")] [DisplayName("Auto Increment")] [MyDescription("TableAutoIncStartDesc")] public ulong AutoInc { get { return _autoInc; } set { _autoInc = value; } } #endregion #region Storage options private string _engine; [Category("Storage")] [DisplayName("Storage Engine")] [MyDescription("TableEngineDescription")] [TypeConverter(typeof(TableEngineTypeConverter))] [RefreshProperties(RefreshProperties.All)] public string Engine { get { return _engine; } set { _engine = value; } } private string _dataDirectory; [Category("Storage")] [DisplayName("Data Directory")] [MyDescription("TableDataDirDesc")] public string DataDirectory { get { return _dataDirectory; } set { _dataDirectory = value; } } private string _indexDirectory; [Category("Storage")] [DisplayName("Index Directory")] [MyDescription("TableIndexDirDesc")] public string IndexDirectory { get { return _indexDirectory; } set { _indexDirectory = value; } } #endregion #region Row options private RowFormat _rowFormat; [Category("Row")] [DisplayName("Row Format")] [MyDescription("TableRowFormatDesc")] public RowFormat RowFormat { get { return _rowFormat; } set { _rowFormat = value; } } private bool _checkSum; [Category("Row")] [DisplayName("Compute Checksum")] [MyDescription("TableCheckSumDesc")] [DefaultValue(false)] [TypeConverter(typeof(YesNoTypeConverter))] public bool CheckSum { get { return _checkSum; } set { _checkSum = value; } } private ulong _avgRowLength; [Category("Row")] [DisplayName("Average Row Length")] [MyDescription("TableAvgRowLengthDesc")] [TypeConverter(typeof(NumericTypeConverter))] public ulong AvgRowLength { get { return _avgRowLength; } set { _avgRowLength = value; } } private ulong _minRows; [Category("Row")] [DisplayName("Minimum Rows")] [MyDescription("TableMinRowsDesc")] [TypeConverter(typeof(NumericTypeConverter))] public ulong MinRows { get { return _minRows; } set { _minRows = value; } } private UInt64 _maxRows; [Category("Row")] [DisplayName("Maximum Rows")] [MyDescription("TableMaxRowsDesc")] [TypeConverter(typeof(NumericTypeConverter))] public UInt64 MaxRows { get { return _maxRows; } set { _maxRows = value; } } private PackKeysMethod _packKeys; [Category("Row")] [DisplayName("Pack Keys")] [MyDescription("TablePackKeysDesc")] [DefaultValue(PackKeysMethod.Default)] public PackKeysMethod PackKeys { get { return _packKeys; } set { _packKeys = value; } } private InsertMethod _insertMethod; [Category("Row")] [DisplayName("Insert method")] [MyDescription("TableInsertMethodDesc")] [DefaultValue(InsertMethod.First)] public InsertMethod InsertMethod { get { return _insertMethod; } set { _insertMethod = value; } } private bool _delayKeyWrite; [Category("Row")] [DisplayName("Delay Key Write")] [MyDescription("DelayKeyWriteDesc")] public bool DelayKeyWrite { get { return _delayKeyWrite; } set { _delayKeyWrite = value; } } #endregion #region ShouldSerializeMethods bool ShouldSerializeName() { return false; } bool ShouldSerializeSchema() { return false; } bool ShouldSerializeComment() { return false; } bool ShouldSerializeCharacterSet() { return false; } bool ShouldSerializeCollation() { return false; } bool ShouldSerializeAutoInc() { return false; } bool ShouldSerializeEngine() { return false; } bool ShouldSerializeDataDirectory() { return false; } bool ShouldSerializeIndexDirectory() { return false; } bool ShouldSerializeRowFormat() { return false; } bool ShouldSerializeCheckSum() { return false; } bool ShouldSerializeAvgRowLength() { return false; } bool ShouldSerializeMinRows() { return false; } bool ShouldSerializeMaxRows() { return false; } bool ShouldSerializePackKeys() { return false; } bool ShouldSerializeInsertMethod() { return false; } #endregion public void NotifyUpdate() { OnDataUpdated(); } public void DeleteKey(string keyName) { for (int i = Indexes.Count - 1; i >= 0; i--) { if ((keyName != null && Indexes[i].Name == keyName) || (keyName == null && Indexes[i].IsPrimary)) { Indexes.Delete(i); break; } } } public Index CreateIndexWithUniqueName(bool primary) { Index newIndex = new Index(this, null); newIndex.IsPrimary = primary; string baseName = String.Format("{0}_{1}", primary ? "PK" : "IX", Name); string name = baseName; int uniqueIndex = 0; while (KeyExists(name)) name = String.Format("{0}_{1}", baseName, ++uniqueIndex); newIndex.Name = name; return newIndex; } public List GetColumnNames() { string sql = @"SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='{0}' AND TABLE_NAME='{1}'"; DataTable dt = owningNode.GetDataTable(String.Format(sql, owningNode.Database, Name)); List cols =new List(); foreach (DataRow row in dt.Rows) cols.Add(row[0].ToString()); return cols; } public string GetSql() { StringBuilder sql = new StringBuilder(); if (IsNew) sql.AppendFormat("CREATE TABLE `{0}` (", Name); else sql.AppendFormat("ALTER TABLE `{0}` ", OldTable.Name); string[] parts = new string[3]; parts[0] = Columns.GetSql(IsNew); parts[1] = Indexes.GetSql(IsNew); parts[2] = ForeignKeys.GetSql(IsNew); string delimiter = ""; foreach (string s in parts) { if (!String.IsNullOrEmpty(s)) { sql.AppendFormat("{0}{1}", delimiter, s); delimiter = ", "; } } if (IsNew) sql.Append(")"); sql.Append(GetTableOptionSql(IsNew)); return sql.ToString(); } public bool HasChanges() { // first compare our top level properties if (!ObjectHelper.AreEqual(this, OldTable)) return true; if (Columns.HasChanges()) return true; if (Indexes.HasChanges()) return true; if (ForeignKeys.HasChanges()) return true; return false; } #region Private methods private bool KeyExists(string keyName) { foreach (Index i in Indexes) if (String.Compare(i.Name, keyName, true) == 0) return true; return false; } private void ParseTableData(DataRow tableRow) { Schema = tableRow["TABLE_SCHEMA"].ToString(); Name = tableRow["TABLE_NAME"].ToString(); Engine = tableRow["ENGINE"].ToString(); RowFormat = (RowFormat)Enum.Parse(typeof(RowFormat), tableRow["ROW_FORMAT"].ToString()); AvgRowLength = DataRowHelpers.GetValueAsUInt64(tableRow, "AVG_ROW_LENGTH"); AutoInc = DataRowHelpers.GetValueAsUInt64(tableRow, "AUTO_INCREMENT"); Comment = tableRow["TABLE_COMMENT"].ToString(); Collation = tableRow["TABLE_COLLATION"].ToString(); if (Collation != null) { int index = Collation.IndexOf("_"); if (index != -1) CharacterSet = Collation.Substring(0, index); } string createOpt = (string)tableRow["CREATE_OPTIONS"]; if (String.IsNullOrEmpty(createOpt)) ParseCreateOptions(createOpt.ToLowerInvariant()); } private void ParseCreateOptions(string createOptions) { string[] options = createOptions.Split(' '); foreach (string option in options) { string[] parts = option.Split('='); if (parts.Length != 2) continue; switch (parts[0]) { case "min_rows": MinRows = UInt64.Parse(parts[1]); break; case "max_rows": MaxRows = UInt64.Parse(parts[1]); break; case "checksum": CheckSum = Boolean.Parse(parts[1]); break; case "pack_keys": PackKeys = parts[1] == "1" ? PackKeysMethod.Full : PackKeysMethod.None; break; case "delay_key_write": DelayKeyWrite = parts[1] == "1"; break; // data directory // index directory // insert method } } } private void ParseColumns(DataTable columnData) { foreach (DataRow row in columnData.Rows) { Column c = new Column(row); c.OwningTable = this; Columns.Add(c); } } private void LoadIndexes() { string[] restrictions = new string[4] { null, owningNode.Database, Name, null }; DataTable dt = owningNode.GetSchema("Indexes", restrictions); foreach (DataRow row in dt.Rows) { Index i = new Index(this, row); Indexes.Add(i); } } private void LoadForeignKeys() { string[] restrictions = new string[4] { null, owningNode.Database, Name, null }; DataTable dt = owningNode.GetSchema("Foreign Keys", restrictions); foreach (DataRow row in dt.Rows) { ForeignKey key = new ForeignKey(this, row); ForeignKeys.Add(key); } } private string GetTableOptionSql(bool newTable) { List options = new List(); StringBuilder sql = new StringBuilder(" "); if (!newTable) { if (Name != OldTable.Name) options.Add(String.Format("RENAME TO `{0}` ", Name)); } if (AutoInc != OldTable.AutoInc) options.Add(String.Format("AUTO_INCREMENT={0}", AutoInc)); if (AvgRowLength != OldTable.AvgRowLength) options.Add(String.Format("AVG_ROW_LENGTH={0}", AvgRowLength)); if (CheckSum != OldTable.CheckSum) options.Add(String.Format("CHECKSUM={0}", CheckSum ? 1 : 0)); if (Engine != OldTable.Engine) options.Add(String.Format("ENGINE={0}", Engine)); if (InsertMethod != OldTable.InsertMethod) options.Add(String.Format("INSERT_METHOD={0}", InsertMethod.ToString())); if (MaxRows != OldTable.MaxRows) options.Add(String.Format("MAX_ROWS={0}", MaxRows)); if (MinRows != OldTable.MinRows) options.Add(String.Format("MIN_ROWS={0}", MinRows)); if (PackKeys != OldTable.PackKeys) options.Add(String.Format("PACK_KEYS={0}", PackKeys.ToString())); if (RowFormat != OldTable.RowFormat) options.Add(String.Format("ROW_FORMAT={0}", RowFormat.ToString())); if (StringPropertyHasChanged(Comment, OldTable.Comment)) options.Add(String.Format("COMMENT='{0}'", Comment)); if (StringPropertyHasChanged(CharacterSet, OldTable.CharacterSet)) options.Add(String.IsNullOrEmpty(CharacterSet) ? "DEFAULT CHARACTER SET" : String.Format("CHARACTER SET='{0}'", CharacterSet)); if (StringPropertyHasChanged(Collation, OldTable.Collation)) options.Add(String.IsNullOrEmpty(Collation) ? "DEFAULT COLLATE" : String.Format("COLLATE='{0}'", Collation)); if (StringPropertyHasChanged(DataDirectory, OldTable.DataDirectory)) options.Add(String.Format("DATA DIRECTORY='{0}' ", DataDirectory)); if (StringPropertyHasChanged(IndexDirectory, OldTable.IndexDirectory)) options.Add(String.Format("INDEX DIRECTORY='{0}' ", IndexDirectory)); string delimiter = ""; foreach (string option in options) { sql.AppendFormat("{0}{1}", delimiter, option); delimiter = ",\r\n"; } return sql.ToString(); } private bool StringPropertyHasChanged(string newVal, string oldVal) { if (newVal == oldVal) return false; if (newVal != null && newVal.Length > 0) return true; if (oldVal != null && oldVal.Length > 0) return true; return false; } #endregion #region ICustomTypeDescriptor Members public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } EventDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } public string GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) { return this; } public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { PropertyDescriptorCollection coll = TypeDescriptor.GetProperties(this, attributes, true); List props = new List(); string engine = Engine.ToLowerInvariant(); bool engineIsMyIsam = engine == "myisam"; foreach (PropertyDescriptor pd in coll) { if (!pd.IsBrowsable) continue; if (pd.Name == "DataDirectory" || pd.Name == "IndexDirectory") { CustomPropertyDescriptor newPd = new CustomPropertyDescriptor(pd); newPd.SetReadOnly(!engineIsMyIsam); props.Add(newPd); } else if ((pd.Name == "DelayKeyWrite" || pd.Name == "CheckSum" || pd.Name=="PackKeys") && !engineIsMyIsam) { } else if (pd.Name == "InsertMethod" && engine != "mrg_myisam") { } else props.Add(pd); } return new PropertyDescriptorCollection(props.ToArray()); } PropertyDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetProperties() { return TypeDescriptor.GetProperties(this, true); } public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } public string GetClassName() { return TypeDescriptor.GetClassName(this, true); } #endregion #region Events public event EventHandler DataUpdated; private void OnDataUpdated() { if (DataUpdated != null) DataUpdated(this, null); } #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/Index.cs0000644000175000017500000003526011127003600026355 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.ComponentModel; using System.Collections.Generic; using MySql.Data.VisualStudio.Editors; using System.Data; using System.Text; namespace MySql.Data.VisualStudio.DbObjects { class Index : Object, ICustomTypeDescriptor, ITablePart { Table table; List indexColumns = new List(); bool isNew; Index oldIndex; private Index(Table t) { table = t; isNew = true; } public Index(Table t, DataRow indexData) : this(t) { isNew = indexData == null; oldIndex = new Index(t); if (!isNew) { ParseIndexInfo(indexData); (this as ITablePart).Saved(); } } private void ParseIndexInfo(DataRow indexData) { Name = indexData["INDEX_NAME"].ToString(); IsPrimary = (bool)indexData["PRIMARY"]; IsUnique = (bool)indexData["UNIQUE"] || IsPrimary; Comment = indexData["COMMENT"].ToString(); string type = indexData["TYPE"].ToString(); switch (type) { case "BTREE": IndexUsing = IndexUsingType.BTREE; break; case "RTREE": IndexUsing = IndexUsingType.RTREE; break; case "HASH": IndexUsing = IndexUsingType.HASH; break; } FullText = type == "FULLTEXT"; Spatial = type == "SPATIAL"; string[] restrictions = new string[5] { null, table.OwningNode.Database, table.Name, Name, null }; DataTable dt = table.OwningNode.GetSchema("IndexColumns", restrictions); foreach (DataRow row in dt.Rows) { IndexColumn col = new IndexColumn(); col.OwningIndex = this; col.ColumnName = row["COLUMN_NAME"].ToString(); string sortOrder = row["SORT_ORDER"].ToString(); // if (sortOrder == "D") // col.SortOrder = IndexSortOrder.Descending; // else if (sortOrder == null) // col.SortOrder = IndexSortOrder.Unsorted; // else col.SortOrder = IndexSortOrder.Ascending; Columns.Add(col); } if (IsPrimary) Type = IndexType.Key; //KeyBlockSize //Parser } #region Properties [Browsable(false)] public Table Table { get { return table; } } private string _name; [Category("Identity")] [DisplayName("(Name)")] [Description("The name of this index/key")] public string Name { get { return _name; } set { _name = value; } } private string _comment; [Category("Identity")] [Description("A description or comment about this index/key")] public string Comment { get { return _comment; } set { _comment = value; } } [Category("(General)")] [Description("The columns of this index/key and their associated sort order")] [TypeConverter(typeof(IndexColumnTypeConverter))] [Editor(typeof(IndexColumnEditor), typeof(System.Drawing.Design.UITypeEditor))] public List Columns { get { return indexColumns; } } private IndexType _indexType; [Category("(General)")] [Description("Specifies if this object is an index or key")] public IndexType Type { get { return _indexType; } set { _indexType = value; } } private bool _isUnique; [Category("(General)")] [DisplayName("Is Unique")] [Description("Specifies if this index/key uniquely identifies every row")] [TypeConverter(typeof(YesNoTypeConverter))] public bool IsUnique { get { return _isUnique; } set { _isUnique = value; } } private bool _isPrimary; [Browsable(false)] public bool IsPrimary { get { return _isPrimary; } set { _isPrimary = value; } } private IndexUsingType _indexUsing; [Category("Storage")] [DisplayName("Index Algorithm")] [Description("Specifies the algorithm that should be used for storing the index/key")] public IndexUsingType IndexUsing { get { return _indexUsing; } set { _indexUsing = value; } } private int _keyBlockSize; [Category("Storage")] [DisplayName("Key Block Size")] [Description("Suggested size in bytes to use for index key blocks. A zero value means to use the storage engine default.")] public int KeyBlockSize { get { return _keyBlockSize; } set { _keyBlockSize = value; } } private string _parser; [Description("Specifies a parser plugin to be used for this index/key. This is only valid for full-text indexes or keys.")] public string Parser { get { return _parser; } set { _parser = value; } } private bool _fullText; [DisplayName("Is Full-text Index/Key")] [Description("Specifies if this is a full-text index or key. This is only supported on MyISAM tables.")] [TypeConverter(typeof(YesNoTypeConverter))] [RefreshProperties(RefreshProperties.All)] public bool FullText { get { return _fullText; } set { _fullText = value; } } private bool _spatial; [DisplayName("Is Spatial Index/Key")] [Description("Specifies if this is a spatial index or key. This is only supported on MyISAM tables.")] [TypeConverter(typeof(YesNoTypeConverter))] [RefreshProperties(RefreshProperties.All)] public bool Spatial { get { return _spatial; } set { _spatial = value; } } #endregion #region ShouldSerialize bool ShouldSerializeName() { return false; } bool ShouldSerializeComment() { return false; } bool ShouldSerializeColumns() { return false; } bool ShouldSerializeType() { return false; } bool ShouldSerializeIsUnique() { return false; } bool ShouldSerializeIndexUsing() { return false; } bool ShouldSerializeKeyBlockSize() { return false; } bool ShouldSerializeParser() { return false; } bool ShouldSerializeFullText() { return false; } bool ShouldSerializeSpatial() { return false; } #endregion #region ICustomTypeDescriptor Members public TypeConverter GetConverter() { return TypeDescriptor.GetConverter(this, true); } public EventDescriptorCollection GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } EventDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } public string GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } public object GetPropertyOwner(PropertyDescriptor pd) { return this; } public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } public PropertyDescriptorCollection GetProperties(Attribute[] attributes) { PropertyDescriptorCollection coll = TypeDescriptor.GetProperties(this, attributes, true); List props = new List(); foreach (PropertyDescriptor pd in coll) { if (!pd.IsBrowsable) continue; if (pd.Name == "IsUnique" || pd.Name == "Name" || pd.Name == "Type") { if (IsPrimary) { CustomPropertyDescriptor newPd = new CustomPropertyDescriptor(pd); newPd.SetReadOnly(true); props.Add(newPd); } } else if (pd.Name == "FullText" && (Spatial || String.Compare(table.Engine, "myisam", true) != 0)) { CustomPropertyDescriptor newPd = new CustomPropertyDescriptor(pd); newPd.SetReadOnly(true); props.Add(newPd); } else if (pd.Name == "Spatial" && (FullText || String.Compare(table.Engine, "myisam", true) != 0)) { CustomPropertyDescriptor newPd = new CustomPropertyDescriptor(pd); newPd.SetReadOnly(true); props.Add(newPd); } else props.Add(pd); } return new PropertyDescriptorCollection(props.ToArray()); } PropertyDescriptorCollection System.ComponentModel.ICustomTypeDescriptor.GetProperties() { return TypeDescriptor.GetProperties(this, true); } public object GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(this, true); } public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } public string GetClassName() { return TypeDescriptor.GetClassName(this, true); } #endregion #region ITablePart Members void ITablePart.Saved() { oldIndex.Comment = Comment; oldIndex.FullText = FullText; oldIndex.IndexUsing = IndexUsing; oldIndex.IsPrimary = IsPrimary; oldIndex.IsUnique = IsUnique; oldIndex.KeyBlockSize = KeyBlockSize; oldIndex.Name = Name; oldIndex.Parser = Parser; oldIndex.Spatial = Spatial; oldIndex.Type = Type; // now we need to copy the columns oldIndex.Columns.Clear(); foreach (IndexColumn ic in Columns) { IndexColumn old = new IndexColumn(); old.ColumnName = ic.ColumnName; old.SortOrder = ic.SortOrder; old.OwningIndex = oldIndex; oldIndex.Columns.Add(old); } } bool ITablePart.HasChanges() { if (!ObjectHelper.AreEqual(this, oldIndex)) return true; if (Columns.Count != oldIndex.Columns.Count) return true; foreach (IndexColumn ic in Columns) { int i = 0; for (; i < oldIndex.Columns.Count; i++) { IndexColumn oic = oldIndex.Columns[i]; if (oic.ColumnName == ic.ColumnName && oic.SortOrder == ic.SortOrder) break; } if (i == oldIndex.Columns.Count) return true; } return false; } string ITablePart.GetDropSql() { if (IsPrimary) return "DROP PRIMARY KEY"; return String.Format("DROP KEY `{0}`", Name); } string ITablePart.GetSql(bool newTable) { StringBuilder sql = new StringBuilder(); // if we don't have any changes then just return null ITablePart part = this as ITablePart; if (!part.HasChanges()) return null; if (!newTable) { if (!String.IsNullOrEmpty(oldIndex.Name)) sql.AppendFormat("DROP INDEX `{0}`, ", oldIndex.Name); sql.Append("ADD "); } if (IsPrimary) sql.Append("PRIMARY KEY "); else if (IsUnique) sql.Append("UNIQUE "); else if (FullText) sql.Append("FULLTEXT "); else if (Spatial) sql.Append("SPATIAL "); if (!IsPrimary) sql.AppendFormat("{0} ", Type.ToString().ToUpperInvariant()); sql.AppendFormat("`{0}` (", Name); string delimiter = ""; foreach (IndexColumn c in Columns) { sql.AppendFormat("{0}{1}", delimiter, c.ColumnName); delimiter = ", "; } sql.Append(")"); return sql.ToString(); } bool ITablePart.IsNew() { return isNew; } #endregion } enum IndexType { Index, Key, Primary } enum IndexUsingType { BTREE, HASH, RTREE } public enum IndexSortOrder { Ascending } class IndexColumn { public Index OwningIndex; public string ColumnName; public IndexSortOrder SortOrder; } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/DataRowHelpers.cs0000644000175000017500000000333211127003600030165 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data; namespace MySql.Data.VisualStudio.DbObjects { internal static class DataRowHelpers { public static int GetValueAsInt32(DataRow row, string column) { if (row[column] == DBNull.Value) return 0; return Convert.ToInt32(row[column]); } public static ulong GetValueAsUInt64(DataRow row, string column) { if (row[column] == DBNull.Value) return 0; return Convert.ToUInt64(row[column]); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/TablePartCollection.cs0000644000175000017500000000741511127003600031201 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; namespace MySql.Data.VisualStudio.DbObjects { internal interface ITablePart { string GetDropSql(); string GetSql(bool isNew); bool HasChanges(); bool IsNew(); void Saved(); } internal class TablePartCollection : List { public TablePartCollection() { Deleted = new List(); } private List _deleted; public List Deleted { get { return _deleted; } private set { _deleted = value; } } public void Delete(T t) { Deleted.Add(t); } public void Delete(int index) { ITablePart part = (ITablePart)this[index]; RemoveAt(index); if (!part.IsNew()) Deleted.Add((T)part); } public bool HasChanges() { if (Deleted.Count > 0) return true; foreach (ITablePart part in this) if (part.HasChanges()) return true; return false; } public void Saved() { Deleted.Clear(); foreach (ITablePart part in this) part.Saved(); } public string GetSql(bool newTable) { List parts = new List(); if (!newTable) foreach (ITablePart part in Deleted) parts.Add(part.GetDropSql()); // process new columns for (int i = 0; i < Count; i++) { ITablePart part = (ITablePart)this[i]; string partSql = part.GetSql(newTable); if (!String.IsNullOrEmpty(partSql)) { if (part is Column && !newTable) { if (i == 0) partSql += " FIRST"; else if (i < Count - 1) { Column c = this[i - 1] as Column; partSql += String.Format(" AFTER {0}", c.ColumnName); } } parts.Add(partSql); } } string delimiter = ""; StringBuilder sql = new StringBuilder(); foreach (string s in parts) { sql.AppendFormat("{0}{1}", delimiter, s); delimiter = ", "; } return sql.ToString(); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/Metadata.cs0000644000175000017500000000634611127003600027031 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; namespace MySql.Data.VisualStudio.DbObjects { internal class Metadata { private static List DataTypes; public static bool IsStringType(string dataType) { dataType = dataType.ToLowerInvariant(); int index = dataType.IndexOf('('); if (index != -1) dataType = dataType.Substring(0, index); return dataType.IndexOf("char") != -1 || dataType.IndexOf("text") != -1; } public static string[] GetDataTypes(bool includeParens) { if (DataTypes == null) PopulateArray(); string[] dataTypes = DataTypes.ToArray(); if (!includeParens) { for (int i = 0; i < dataTypes.Length; i++) dataTypes[i] = RemoveParens(dataTypes[i]); } return dataTypes; } private static string RemoveParens(string dataType) { int index = dataType.IndexOf('('); if (index != -1) dataType = dataType.Substring(0, index); return dataType; } private static void PopulateArray() { DataTypes = new List(); DataTypes.AddRange(new string[] { "bit(10)", "tinyint", "boolean", "smallint", "mediumint", "int", "serial", "float", "double", "decimal", "date", "datetime", "timestamp", "time", "year", "char(10)", "varchar(10)", "binary(10)", "varbinary(10)", "tinyblob", "tinytext", "blob", "text", "mediumblob", "mediumtext", "longblob", "longtext", "enum(x,y,z)", "set(x,y,z)"}); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/NumericTypeConverter.cs0000644000175000017500000000504511127003600031440 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data; using System.ComponentModel; using System.Collections; using System.Diagnostics; namespace MySql.Data.VisualStudio.DbObjects { internal class NumericTypeConverter : TypeConverter { private bool isNull = true; public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(int)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { isNull = value.ToString() == ""; if (isNull) return (ulong)0; return Convert.ToUInt64(value); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (Convert.ToUInt64(value) == 0) return isNull ? "" : "0"; return value.ToString(); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DbObjects/CharacterSetTypeConverter.cs0000644000175000017500000000476311127003600032414 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data; using System.ComponentModel; using System.Collections; using System.Diagnostics; namespace MySql.Data.VisualStudio.DbObjects { internal class CharacterSetTypeConverter : StringConverter { private List charSets; public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return true; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (charSets == null) PopulateList(context.Instance); StandardValuesCollection coll = new StandardValuesCollection(charSets); return coll; } private void PopulateList(object instance) { Table table = (instance is Table) ? (instance as Table) : (instance as Column).OwningTable; DataTable data = table.OwningNode.GetDataTable("SHOW CHARSET"); charSets = new List(); charSets.Add(String.Empty); foreach (DataRow row in data.Rows) charSets.Add(row["charset"].ToString()); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/GlobalSuppressions.cs0000644000175000017500000000113211127003600027274 0ustar directhexdirecthex// This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. Project-level // suppressions either have no target or are given a specific target // and scoped to a namespace, type, member, etc. // // To add a suppression to this file, right-click the message in the // Error List, point to "Suppress Message(s)", and click "In Project // Suppression File". You do not need to add suppressions to this // file manually. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1017:MarkAssembliesWithComVisible")] mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Guids.cs0000644000175000017500000000512511127003600024517 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // Guids.cs // MUST match guids.h using System; namespace MySql.Data.VisualStudio { static class GuidStrings { public const string SqlEditorFactory = "CAA648E8-D6BD-465e-A1B3-2A0BF9DA5581"; //public const string SqlEditorCmdSet = "52C2F587-8E01-4333-BBD7-2BE0776207B8"; public const string Package = "79A115C9-B133-4891-9E7B-242509DAD272"; public const string CmdSet = "B87CB51F-8A01-4c5e-BF3E-5D0565D5397D"; public const string Provider = "C6882346-E592-4da5-80BA-D2EADCDA0359"; } static class Guids { public static readonly Guid Package = new Guid(GuidStrings.Package); public static readonly Guid Provider = new Guid(GuidStrings.Provider); public static readonly Guid CmdSet = new Guid(GuidStrings.CmdSet); public static readonly Guid SqlEditorFactory = new Guid(GuidStrings.SqlEditorFactory); //public static readonly Guid SqlEditorCmdSet = new Guid(GuidStrings.SqlEditorCmdSet); } static class GuidList { // TODO: This is wrong GUID, it must be CLSID of editor factory. public static readonly Guid EditorFactoryCLSID = new Guid( "D949EA95-EDA1-4b65-8A9E-266949A99360"); public static readonly Guid DavinciCommandSet = new Guid( "732ABE75-CD80-11D0-A2DB-00AA00A3EFFF"); public static readonly Guid StandardCommandSet = new Guid("{5efc7975-14bc-11cf-9b2b-00aa00573819}"); }; }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/0000755000175000017500000000000011127003600023636 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlConnectionProperties.cs0000644000175000017500000000624611127003600031337 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /* * This file contains implementation of customized connection properties. */ using System; using Microsoft.VisualStudio.Data.AdoDotNet; using System.Data.Common; namespace MySql.Data.VisualStudio { /// /// This class customize standard connection properties for /// MySql data base connection. /// public class MySqlConnectionProperties : AdoDotNetConnectionProperties { public static string InvariantName = "MySql.Data.MySqlClient"; /// /// Constructor fills base object with list of custom options and their description. /// public MySqlConnectionProperties() : base(InvariantName) { } /// /// Test connection for these properties. Uses MySqlConnection support for version validation. /// public override void Test() { // Create connection support MySqlConnectionSupport conn = new MySqlConnectionSupport(); try { // Initializes it with empty provider conn.Initialize(null); // Set connection string conn.ConnectionString = ToTestString(); // Try to open conn.Open(false); // Close after open conn.Close(); } finally { // In any case dispose connection support if (conn != null) conn.Dispose(); } } /// /// Connection properties are complete if server and database specified. /// public override bool IsComplete { get { DbConnectionStringBuilder cb = this.ConnectionStringBuilder; return !String.IsNullOrEmpty((string)cb["Server"]) && !String.IsNullOrEmpty((string)cb["Database"]); } } } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlDataObjectSupport.cs0000644000175000017500000000342411127003600030553 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /* * This file contains data object support entity implementation. */ using Microsoft.VisualStudio.Data; namespace MySql.Data.VisualStudio { /// /// Represents an implementation of data object support that returns /// the stream of XML containing the data object support elements. /// internal class MySqlDataObjectSupport : DataObjectSupport { /// /// Constructor just passes reference to XML to base constructor. /// public MySqlDataObjectSupport() : base("MySql.Data.VisualStudio.DDEX.MySqlDataObjectSupport", typeof(MySqlDataObjectSupport).Assembly) { } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlDataSourceInformation.cs0000644000175000017500000001071211127003600031414 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /* * This file contains class with data source specific information. */ using System; using Microsoft.VisualStudio.Data; using Microsoft.VisualStudio.Data.AdoDotNet; using System.Data; using System.Data.Common; namespace MySql.Data.VisualStudio { /// /// Represents a custom data source information class for MySQL /// public class MySqlDataSourceInformation : AdoDotNetDataSourceInformation { public const string DataSource = "DataSource"; private DataTable values; /// /// Constructors fills available properties information /// /// Reference to database connection object public MySqlDataSourceInformation(DataConnection connection) : base(connection) { AddProperty(DataSource); AddProperty(DataSourceVersion); AddProperty(DefaultSchema); AddProperty(SupportsAnsi92Sql, true); AddProperty(SupportsQuotedIdentifierParts, true); AddProperty(IdentifierOpenQuote, "`"); AddProperty(IdentifierCloseQuote, "`"); AddProperty(ServerSeparator, "."); AddProperty(CatalogSupported, false); AddProperty(CatalogSupportedInDml, false); AddProperty(SchemaSupported, true); AddProperty(SchemaSupportedInDml, true); AddProperty(SchemaSeparator, "."); AddProperty(ParameterPrefix, "@"); AddProperty(ParameterPrefixInName, true); AddProperty(DefaultCatalog, null); } internal void Refresh() { EnsureConnected(); DbConnection c = (DbConnection)Connection.GetLockedProviderObject(); values = c.GetSchema("DataSourceInformation"); Connection.UnlockProviderObject(); } #region Value retrieving public override object this[string propertyName] { get { // data source version can change so we need to // refresh it here if (propertyName == "DataSourceVersion") { if (values == null) Refresh(); return values.Rows[0]["DataSourceProductVersion"]; } else return base[propertyName]; } } /// /// Called to retrieve property value. Supports following custom properties: /// DataSource � MySQL server name. /// Database � default schema name. /// /// Name of property to retrieve. /// Property value protected override object RetrieveValue(string propertyName) { EnsureConnected(); if (propertyName.Equals(DataSource, StringComparison.InvariantCultureIgnoreCase)) { return (ProviderObject as DbConnection).DataSource; } else if (propertyName.Equals(DefaultSchema, StringComparison.InvariantCultureIgnoreCase)) { return (ProviderObject as DbConnection).Database; } object value = base.RetrieveValue(propertyName); return value; } #endregion private void EnsureConnected() { if (Connection.State != DataConnectionState.Open) Connection.Open(); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlDataObjectEnumerator.cs0000644000175000017500000001711011127003600031215 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /* * This file contains implementation of data object enumerator. */ using System; using System.Data; using System.Diagnostics; using Microsoft.VisualStudio.Data; using Microsoft.VisualStudio.Data.AdoDotNet; using System.Data.Common; namespace MySql.Data.VisualStudio { /// /// Implements custom database objects enumerator for MySQL databases. /// Uses information_schema database to enumerate objects. /// public class MySqlDataObjectEnumerator : AdoDotNetObjectEnumerator { /// /// Enumerates items for a set of data objects of the specified type /// with the specified restrictions and sort string, if supported. /// /// Name of the type of the object to enumerate. /// /// The set of items to enumerate, specified as strings where named items are available, /// otherwise as indexes. In cases in which a data provider does not support items /// filtering, this parameter is ignored. /// NOT SUPPORTED. /// /// /// A set of filtering restrictions to apply to the set of returned objects. /// /// /// A sort string, which follows syntax for the SQL Server ORDER BY clause. /// The actual sort order should be source-based; that is, if the client is /// English and the source is Chinese, the sort should be applied in Chinese. /// NOT SUPPORTED. /// /// /// An array whose contents are defined by the given implementation of /// EnumerateObjects, and which is specified by the Data Object Support /// XML file. Information supplied in this parameter can be used to provide /// extra data indicating how to perform the enumeration, allowing /// implementations of this method to be more data driven. /// NOT USED. /// /// /// Returns a DataReader object containing the results of the enumeration call. /// public override DataReader EnumerateObjects(string typeName, object[] items, object[] restrictions, string sort, object[] parameters) { if (typeName == null) throw new ArgumentNullException("typeName"); if (typeName == String.Empty) return EnumerateRoot(); else return EnumerateSchemaObjects(parameters[0] as string, restrictions); } private DataReader EnumerateRoot() { DbConnection conn = (DbConnection)Connection.GetLockedProviderObject(); try { DataTable table = new DataTable(); table.Columns.Add("SERVER_NAME"); table.Columns.Add("CATALOG_NAME"); table.Columns.Add("SCHEMA_NAME"); DataRow row = table.NewRow(); row["SERVER_NAME"] = conn.DataSource; row["SCHEMA_NAME"] = conn.Database; table.Rows.Add(row); return new AdoDotNetDataTableReader(table); } finally { Connection.UnlockProviderObject(); } } private DataReader EnumerateSchemaObjects(string typeName, object[] restrictions) { DbConnection conn = (DbConnection)Connection.GetLockedProviderObject(); try { string[] rest; DataTable tables = null; if (restrictions != null) { int i = 0; rest = new string[restrictions.Length]; foreach (object o in restrictions) rest[i++] = (string)o; tables = conn.GetSchema(typeName, rest); } else tables = conn.GetSchema(typeName); foreach (DataRow row in tables.Rows) row["TABLE_CATALOG"] = DBNull.Value; return new AdoDotNetDataTableReader(tables); } finally { Connection.UnlockProviderObject(); } } /* // Chose restricitions array object[] appliedRestrictions; if (typeName.Equals(RootDescriptor.TypeName, StringComparison.InvariantCultureIgnoreCase)) { appliedRestrictions = new object[] { ConnectionWrapper.ServerName, ConnectionWrapper.Schema }; } else { appliedRestrictions = restrictions; } DataTable table; try { // Enumerate objects into table table = ObjectDescriptor.EnumerateObjects(ConnectionWrapper, typeName, appliedRestrictions, sort); } catch (DbException e) { SqlErrorDialog.ShowError(e, ConnectionWrapper.GetFullStatus()); throw; } catch (Exception e) { UIHelper.ShowError(e); throw; } // Validate table if (table == null) { Debug.Fail("Failed to enumerate objects of type '" + typeName + "'!"); return null; } // Enumerete objects in to DataReader return new AdoDotNetDataTableReader(table);*/ #region Connection wrapper /// /// Returns wrapper for the underlying connection. Creates it at the first call. /// /* private DataConnectionWrapper ConnectionWrapper { get { if (connectionWrapperRef == null) connectionWrapperRef = new DataConnectionWrapper(Connection); return connectionWrapperRef; } } /// /// Used to stroe connection wrapper. /// private DataConnectionWrapper connectionWrapperRef;*/ #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlDataSourceSpecializer.cs0000644000175000017500000000416411127003600031405 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /* * This file contains stub for data connection specializer. */ using System; using Microsoft.VisualStudio.Data; using System.Reflection; namespace MySql.Data.VisualStudio { /// /// This class needed only as a stub to get prompt dialog to work. Its methods /// are never called. /// class MySqlDataSourceSpecializer: DataSourceSpecializer { public override object CreateObject(Guid dataSource, Type objType) { object result = base.CreateObject(dataSource, objType); return result; } public override Guid DeriveDataSource(string connectionString) { Guid result = base.DeriveDataSource(connectionString); return result; } public override Assembly GetAssembly(Guid dataSource, string assemblyString) { Assembly result = base.GetAssembly(dataSource, assemblyString); return result; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlDataObjectSupport.xml0000644000175000017500000012710011127003600030744 0ustar directhexdirecthex mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlConnectionSupport.cs0000644000175000017500000000764711127003600030665 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /* * This file contains implementation of custom connection support for MySQL. */ using System; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Reflection; using Microsoft.VisualStudio.Data; using Microsoft.VisualStudio.Data.AdoDotNet; using System.Globalization; using MySql.Data.VisualStudio.Properties; using System.Text; using System.Windows.Forms; namespace MySql.Data.VisualStudio { public class MySqlConnectionSupport : AdoDotNetConnectionSupport { private MySqlDataSourceInformation sourceInformation = null; public MySqlConnectionSupport() : base(MySqlConnectionProperties.InvariantName) { } /// /// Retrieves a service of the specified type. Following services are /// supported: /// DataViewSupport � information about view schema. /// DataObjectSupport � information about object model. /// /// A service type. /// /// Returns the service of the specified type, or returns a null reference /// if no service was found. /// protected override object GetServiceImpl(Type serviceType) { if (serviceType == typeof(DataViewSupport)) { return new MySqlDataViewSupport(); } else if (serviceType == typeof(DataObjectSupport)) { return new MySqlDataObjectSupport(); } else if (serviceType == typeof(DataSourceInformation)) { return new MySqlDataSourceInformation(Site as DataConnection); } else if (serviceType == typeof(DataObjectIdentifierConverter)) return new MySqlDataObjectIdentifierConverter(Site as DataConnection); else return base.GetServiceImpl(serviceType); } public override bool Open(bool doPromptCheck) { // Open connection try { // Call base method first if (!base.Open(doPromptCheck)) return false; } catch (DbException) { // If can't prompt user for new authentication data, re-throw exception if (!doPromptCheck) throw; // Else return false to display prompt dialog return false; } // TODO: check server version compatibility // Rreturn true if everything is ok if (sourceInformation != null) sourceInformation.Refresh(); return true; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlConnectionUIControl.cs0000644000175000017500000002230111127003600031047 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /* * This file contains implementation of custom connection dialog. */ using System; using System.Windows.Forms; using System.Diagnostics; using Microsoft.VisualStudio.Data.AdoDotNet; using MySql.Data.VisualStudio.Properties; using System.Data.Common; using Microsoft.VisualStudio.Data; namespace MySql.Data.VisualStudio { /// /// Represents a custom data connection UI control for entering /// connection information. /// internal partial class MySqlDataConnectionUI : DataConnectionUIControl //Stub { private bool dbListPopulated; public MySqlDataConnectionUI() { InitializeComponent(); } /// /// Initializes GUI elements with properties values. /// public override void LoadProperties() { if (ConnectionProperties == null) throw new Exception(Resources.ConnectionPropertiesNull); Button okButton = this.ParentForm.AcceptButton as Button; okButton.Click += new EventHandler(okButton_Click); AdoDotNetConnectionProperties prop = (ConnectionProperties as AdoDotNetConnectionProperties); DbConnectionStringBuilder cb = prop.ConnectionStringBuilder; loadingInProcess = true; try { serverNameTextBox.Text = (string)cb["Server"]; userNameTextBox.Text = (string)cb["User Id"]; passwordTextBox.Text = (string)cb["Password"]; dbList.Text = (string)cb["Database"]; savePasswordCheckBox.Checked = (bool)cb["Persist Security Info"]; } finally { loadingInProcess = false; } } /// /// We hook the ok button of our parent form so we can implement our /// 'create database' functionality /// /// /// void okButton_Click(object sender, EventArgs e) { bool exists = DatabaseExists(); if (exists) return; String prompt = String.Format(Resources.UnknownDbPromptCreate, dbList.Text); prompt = prompt.Replace(@"\n", @"\n"); DialogResult result = MessageBox.Show(prompt, null, MessageBoxButtons.YesNo, MessageBoxIcon.Question); this.ParentForm.DialogResult = DialogResult.None; if (result == DialogResult.Yes) { if (!AttemptToCreateDatabase()) MessageBox.Show(String.Format(Resources.ErrorAttemptingToCreateDB, dbList.Text)); else this.ParentForm.DialogResult = DialogResult.OK; } } /// /// Handles TextChanged event from all textboxes. /// /// Reference to sender object. /// Additional event data. Not used. private void SetProperty(object sender, EventArgs e) { // Only set properties if we are not currently loading them if (!loadingInProcess) { Control source = sender as Control; // if the user changes the host or user id then // we need to repopulate our db list if (source.Tag.Equals("Server") || source.Tag.Equals("User id")) dbListPopulated = false; // Tag is used to determine property name if (source != null && source.Tag is string) ConnectionProperties[source.Tag as string] = source.Text; } dbList.Enabled = serverNameTextBox.Text.Trim().Length > 0 && userNameTextBox.Text.Trim().Length > 0; } /// /// Handles Leave event and trims text. /// /// Reference to sender object. /// Additional event data. Not used. private void TrimControlText(object sender, EventArgs e) { Control c = sender as Control; c.Text = c.Text.Trim(); } /// /// Used to prevent OnChange event handling during initialization. /// private bool loadingInProcess = false; private void SavePasswordChanged(object sender, EventArgs e) { // Only set properties if we are not currently loading them if (!loadingInProcess) ConnectionProperties[savePasswordCheckBox.Tag as string] = savePasswordCheckBox.Checked; } private void dbList_DropDown(object sender, EventArgs e) { if (dbListPopulated) return; AdoDotNetConnectionProperties prop = (ConnectionProperties as AdoDotNetConnectionProperties); DbConnectionStringBuilder cb = prop.ConnectionStringBuilder; try { using (MySqlConnectionSupport conn = new MySqlConnectionSupport()) { conn.Initialize(null); conn.ConnectionString = cb.ConnectionString; conn.Open(false); dbList.Items.Clear(); using (DataReader reader = conn.Execute("SHOW DATABASES", 1, null, 0)) { while (reader.Read()) { string dbName = reader.GetItem(0).ToString().ToLowerInvariant(); if (dbName == "information_schema") continue; if (dbName == "mysql") continue; dbList.Items.Add(reader.GetItem(0)); } dbListPopulated = true; } } } catch (Exception) { MessageBox.Show(Resources.UnableToRetrieveDatabaseList); } } private bool DatabaseExists() { AdoDotNetConnectionProperties prop = (ConnectionProperties as AdoDotNetConnectionProperties); DbConnectionStringBuilder cb = prop.ConnectionStringBuilder; try { using (MySqlConnectionSupport conn = new MySqlConnectionSupport()) { conn.Initialize(null); conn.ConnectionString = cb.ConnectionString; conn.Open(false); } return true; } catch (DbException ex) { string msg = ex.Message.ToLowerInvariant(); if (msg.StartsWith("unknown database")) return false; throw; } } private bool AttemptToCreateDatabase() { AdoDotNetConnectionProperties prop = (ConnectionProperties as AdoDotNetConnectionProperties); DbConnectionStringBuilder cb = prop.ConnectionStringBuilder; string olddb = (string)cb["Database"]; cb["Database"] = ""; try { using (MySqlConnectionSupport conn = new MySqlConnectionSupport()) { conn.Initialize(null); conn.ConnectionString = cb.ConnectionString; conn.Open(false); conn.ExecuteWithoutResults("CREATE DATABASE `" + dbList.Text + "`", 1, null, 0); } return true; } catch (Exception) { MessageBox.Show(String.Format(Resources.ErrorAttemptingToCreateDB, dbList.Text)); return false; } finally { cb["Database"] = olddb; } } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlConnectionUIControl.designer.cs0000644000175000017500000001603411127003600032654 0ustar directhexdirecthexnamespace MySql.Data.VisualStudio { partial class MySqlDataConnectionUI { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MySqlDataConnectionUI)); this.loginTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.passwordLabel = new System.Windows.Forms.Label(); this.serverNameTextBox = new System.Windows.Forms.TextBox(); this.savePasswordCheckBox = new System.Windows.Forms.CheckBox(); this.databaseNameLabel = new System.Windows.Forms.Label(); this.userNameLabel = new System.Windows.Forms.Label(); this.serverNameLabel = new System.Windows.Forms.Label(); this.userNameTextBox = new System.Windows.Forms.TextBox(); this.passwordTextBox = new System.Windows.Forms.TextBox(); this.dbList = new System.Windows.Forms.ComboBox(); this.loginTableLayoutPanel.SuspendLayout(); this.SuspendLayout(); // // loginTableLayoutPanel // resources.ApplyResources(this.loginTableLayoutPanel, "loginTableLayoutPanel"); this.loginTableLayoutPanel.Controls.Add(this.passwordLabel, 0, 2); this.loginTableLayoutPanel.Controls.Add(this.serverNameTextBox, 1, 0); this.loginTableLayoutPanel.Controls.Add(this.savePasswordCheckBox, 1, 3); this.loginTableLayoutPanel.Controls.Add(this.databaseNameLabel, 0, 4); this.loginTableLayoutPanel.Controls.Add(this.userNameLabel, 0, 1); this.loginTableLayoutPanel.Controls.Add(this.serverNameLabel, 0, 0); this.loginTableLayoutPanel.Controls.Add(this.userNameTextBox, 1, 1); this.loginTableLayoutPanel.Controls.Add(this.passwordTextBox, 1, 2); this.loginTableLayoutPanel.Controls.Add(this.dbList, 1, 4); this.loginTableLayoutPanel.Name = "loginTableLayoutPanel"; // // passwordLabel // resources.ApplyResources(this.passwordLabel, "passwordLabel"); this.passwordLabel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.passwordLabel.Name = "passwordLabel"; // // serverNameTextBox // resources.ApplyResources(this.serverNameTextBox, "serverNameTextBox"); this.serverNameTextBox.Name = "serverNameTextBox"; this.serverNameTextBox.Tag = "Server"; this.serverNameTextBox.TextChanged += new System.EventHandler(this.SetProperty); this.serverNameTextBox.Leave += new System.EventHandler(this.TrimControlText); // // savePasswordCheckBox // resources.ApplyResources(this.savePasswordCheckBox, "savePasswordCheckBox"); this.savePasswordCheckBox.Name = "savePasswordCheckBox"; this.savePasswordCheckBox.Tag = "Persist Security Info"; this.savePasswordCheckBox.CheckedChanged += new System.EventHandler(this.SavePasswordChanged); // // databaseNameLabel // resources.ApplyResources(this.databaseNameLabel, "databaseNameLabel"); this.databaseNameLabel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.databaseNameLabel.Name = "databaseNameLabel"; // // userNameLabel // resources.ApplyResources(this.userNameLabel, "userNameLabel"); this.userNameLabel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.userNameLabel.Name = "userNameLabel"; // // serverNameLabel // resources.ApplyResources(this.serverNameLabel, "serverNameLabel"); this.serverNameLabel.FlatStyle = System.Windows.Forms.FlatStyle.System; this.serverNameLabel.Name = "serverNameLabel"; // // userNameTextBox // resources.ApplyResources(this.userNameTextBox, "userNameTextBox"); this.userNameTextBox.Name = "userNameTextBox"; this.userNameTextBox.Tag = "User id"; this.userNameTextBox.TextChanged += new System.EventHandler(this.SetProperty); this.userNameTextBox.Leave += new System.EventHandler(this.TrimControlText); // // passwordTextBox // resources.ApplyResources(this.passwordTextBox, "passwordTextBox"); this.passwordTextBox.Name = "passwordTextBox"; this.passwordTextBox.Tag = "Password"; this.passwordTextBox.UseSystemPasswordChar = true; this.passwordTextBox.TextChanged += new System.EventHandler(this.SetProperty); // // dbList // resources.ApplyResources(this.dbList, "dbList"); this.dbList.FormattingEnabled = true; this.dbList.Name = "dbList"; this.dbList.Tag = "Database"; this.dbList.DropDown += new System.EventHandler(this.dbList_DropDown); this.dbList.TextChanged += new System.EventHandler(this.SetProperty); // // MySqlDataConnectionUI // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.loginTableLayoutPanel); this.Name = "MySqlDataConnectionUI"; this.loginTableLayoutPanel.ResumeLayout(false); this.loginTableLayoutPanel.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TableLayoutPanel loginTableLayoutPanel; private System.Windows.Forms.Label userNameLabel; private System.Windows.Forms.TextBox userNameTextBox; private System.Windows.Forms.Label passwordLabel; private System.Windows.Forms.TextBox passwordTextBox; private System.Windows.Forms.CheckBox savePasswordCheckBox; private System.Windows.Forms.TextBox serverNameTextBox; private System.Windows.Forms.Label databaseNameLabel; private System.Windows.Forms.Label serverNameLabel; private System.Windows.Forms.ComboBox dbList; } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlDataViewSupport.xml0000644000175000017500000020424211127003600030453 0ustar directhexdirecthex Default {Root.Server}({Root.Schema}) {Name} mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlDataConnectionPromptDialog.cs0000644000175000017500000001066411127003600032375 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /* * This file contains an implemetation of prompt dialog. */ using System; using System.Diagnostics; using System.Globalization; using Microsoft.VisualStudio.Data; namespace MySql.Data.VisualStudio { /// /// Prompt dialog for user information retrieving in case of connection failure. /// public partial class MySqlDataConnectionPromptDialog : DataConnectionPromptDialog { /// /// Simple constructor to calls InitializeComponent /// public MySqlDataConnectionPromptDialog() { InitializeComponent(); } /// /// Extract connection options in this handler. /// /// Not used protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Check connection support if (ConnectionSupport == null) { Debug.Fail("No connection support!"); return; } // Create connection properties to parse connection string MySqlConnectionProperties prop = new MySqlConnectionProperties(); prop.ConnectionStringBuilder.ConnectionString = ConnectionSupport.ConnectionString; // Extract server name and port to build connection string string server = prop["Server"] as string; if (String.IsNullOrEmpty(server)) server = "localhost"; // Empty server name means local host Int64 port = 3306; // By default port is 3306 object givenPort = prop["Port"]; if (givenPort != null && typeof(Int64).IsAssignableFrom(givenPort.GetType())) port = (Int64)givenPort; // Format caption Text = String.Format(CultureInfo.CurrentCulture, Text, server, port); // Extract options login.Text = prop["User Id"] as string; password.Text = prop["Password"] as string; if (prop["Persist Security Info"] is bool) savePassword.Checked = (bool) prop["Persist Security Info"]; else savePassword.Checked = false; } /// /// Creates new connection string depending on user inpur. /// /// Not used. /// Not used. private void OkClick(object sender, EventArgs e) { // Check connection support if (ConnectionSupport == null) { Debug.Fail("No connection support!"); return; } // Create connection properties to parse connection string MySqlConnectionProperties prop = new MySqlConnectionProperties(); prop.ConnectionStringBuilder.ConnectionString = ConnectionSupport.ConnectionString; // Apply changed options prop["User Id"] = login.Text; prop["Password"] = password.Text; prop["Persist Security Info"] = savePassword.Checked; // Change connection string for connection support ConnectionSupport.ConnectionString = prop.ToFullString(); } } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/StoredProcedureColumnEnumerator.cs0000644000175000017500000001006511127003600032520 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System; using Microsoft.VisualStudio.Data; using System.Data.Common; using Microsoft.VisualStudio.Data.AdoDotNet; using System.Data; namespace MySql.Data.VisualStudio { class StoredProcedureColumnEnumerator : DataObjectEnumerator { public override DataReader EnumerateObjects(string typeName, object[] items, object[] restrictions, string sort, object[] parameters) { DbConnection conn = (DbConnection)Connection.GetLockedProviderObject(); try { string spName = String.Format("{0}.{1}", restrictions[1], restrictions[2]); if (conn.State != ConnectionState.Open) conn.Open(); string[] parmRest = new string[5]; parmRest[1] = (string)restrictions[1]; parmRest[2] = (string)restrictions[2]; parmRest[3] = (string)restrictions[3]; DataTable parmTable = conn.GetSchema("Procedure Parameters", parmRest); DbCommand cmd = conn.CreateCommand(); cmd.CommandText = spName; cmd.CommandType = CommandType.StoredProcedure; foreach (DataRow row in parmTable.Rows) { if (row["ORDINAL_POSITION"].Equals(0)) continue; DbParameter p = cmd.CreateParameter(); p.ParameterName = row["PARAMETER_NAME"].ToString(); p.Value = GetDefaultValue(row["DATA_TYPE"].ToString()); cmd.Parameters.Add(p); } using (IDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly)) { DataTable dt = reader.GetSchemaTable(); if (dt == null) dt = new DataTable(); else { dt.Columns.Add(new DataColumn("RoutineName", typeof(string))); foreach (DataRow row in dt.Rows) { row["RoutineName"] = restrictions[2]; string basedb = row["BaseSchemaName"] as string; if (String.IsNullOrEmpty(basedb) || row["BaseSchemaName"] == DBNull.Value) row["BaseSchemaName"] = cmd.Connection.Database; } } return new AdoDotNetDataTableReader(dt); } } finally { Connection.UnlockProviderObject(); } } private object GetDefaultValue(string dataType) { if (dataType == "VARCHAR" || dataType == "VARBINARY" || dataType == "ENUM" || dataType == "SET" || dataType == "CHAR") return ""; return 0; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlDataConnectionPromptDialog.resx0000644000175000017500000004507011127003600032750 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 False 80, 105 87, 27 4 OK buttonOK System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 $this 2 False True 2 False Left True NoControl 0, 36 0, 0, 3, 0 60, 15 2 &Password: label1 System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 tableLayoutPanel1 0 True System NoControl 72, 58 3, 0, 0, 0 129, 20 2 &Save my password savePassword System.Windows.Forms.CheckBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 tableLayoutPanel1 1 False Left True NoControl 0, 7 0, 0, 3, 0 66, 15 0 &User name: label3 System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 tableLayoutPanel1 2 Left, Right 72, 3 3, 3, 0, 3 357, 23 3 login System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 tableLayoutPanel1 3 Left, Right 72, 32 3, 3, 0, 3 357, 23 1 password System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 tableLayoutPanel1 4 20, 10 31, 0, 10, 10 3 429, 81 3 tableLayoutPanel1 System.Windows.Forms.TableLayoutPanel, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 $this 1 <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="label1" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="savePassword" Row="2" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="label3" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="login" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="password" Row="1" RowSpan="1" Column="1" ColumnSpan="1" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,Absolute,23" /></TableLayoutSettings> False 301, 105 87, 27 5 Cancel buttonCancel System.Windows.Forms.Button, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 $this 0 True 7, 15 469, 141 Segoe UI, 9pt CenterParent Input user name and password for {0}:{1} MySqlDataConnectionPromptDialog Microsoft.VisualStudio.Data.DataConnectionPromptDialog, Microsoft.VisualStudio.Data, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlDataViewCommandHandler.cs0000644000175000017500000002610611127003600031461 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /* * This file contains implementation of data view commands handler. */ using System; using Microsoft.VisualStudio.Data; using System.Diagnostics; using Microsoft.VisualStudio.Shell.Interop; using System.Windows.Forms; namespace MySql.Data.VisualStudio { /// /// Represents a custom data view command handler. /// public class MySqlDataViewCommandHandler : DataViewCommandHandler { // private NodeIdMapper nodeMapper; /* private NodeIdMapper NodeMapper { get { if (nodeMapper == null) nodeMapper = new NodeIdMapper(DataViewHierarchyAccessor); return nodeMapper; } }*/ /// /// This method supplies information about a command's status. At this point all /// commands are supported and visible. /// /// /// Array of identifiers for the items in the data view hierarchy on which this /// command should be invoked. /// /// /// The OleCommand object representing the command to invoke. /// /// /// The OleCommandTextType object instance for the specified command. /// /// /// The OleCommandStatus object instance for the specified command. /// /// /// Returns an OleCommandStatus object instance representing the status returned by the specified commands. /// /// public override OleCommandStatus GetCommandStatus(int[] itemIds, OleCommand command, OleCommandTextType textType, OleCommandStatus status) { if (command == null) throw new ArgumentNullException("command"); if (status == null) throw new ArgumentNullException("status"); OleCommandStatus result = new OleCommandStatus(); /* string[] selTypes = DataViewHierarchyAccessor.GetChildSelectionTypes(itemIds[0]); string type = DataViewHierarchyAccessor.GetObjectType(itemIds[0]); string[] staticNodes = DataViewHierarchyAccessor.GetChildStaticNodeIds(itemIds[0]); string path = DataViewHierarchyAccessor.GetNodePath(itemIds[0]); object[] identifier = DataViewHierarchyAccessor.GetObjectIdentifier(itemIds[0]); object v1 = DataViewHierarchyAccessor.GetProperty(itemIds[0], (int)__VSHPROPID.VSHPROPID_IsHiddenItem); object v2 = DataViewHierarchyAccessor.GetProperty(itemIds[0], (int)__VSHPROPID.VSHPROPID_Parent); */ //BaseNode node = NodeMapper[itemIds[0]]; result.Enabled = true; result.Visible = true; result.Supported = true; return result; /* // Get command handler instance ICommand commandHandler = CommandFactory.Instance.CreateCommandHandler(command.GroupGuid, command.CommandId); if (commandHandler == null) return base.GetCommandStatus(itemIds, command, textType, status); result.Supported = true; // Determine visibility if (!commandHandler.GetIsVisible(Hierarchy, itemIds)) { result.Visible = false; return result; } result.Visible = true; result.Enabled = true; // TODO: Find out why this doesn't work at all! // Localize text if possible string localizedText = commandHandler.GetText(Hierarchy, itemIds); if (!String.IsNullOrEmpty(localizedText)) result.Text = localizedText; return result;*/ } /// /// Executes a specified command, potentially based on parameters passed in /// from the data view support XML. /// /// /// Array of identifiers for the items in the data view hierarchy on which this /// command should be invoked. /// /// /// The OleCommand object representing the command to invoke. /// /// /// Any OleCommandExecutionOption object instance representing options on the /// invoked command. /// NOT USED. /// /// /// An object representing arguments to the command. /// NOT USED. /// /// /// Returns an object instance representing the value returned by the specified /// command, which is typically nothing. /// public override object[] ExecuteCommand(int[] itemIds, OleCommand command, OleCommandExecutionOption executionOption, object arguments) { if (command == null) throw new ArgumentNullException("command"); if (!HandleStaticCommand(command.CommandId)) { BaseNode node = MakeNewNode(itemIds[0]); node.ExecuteCommand(command.CommandId); } return null; } /// /// Handle any of the static commands /// /// /// private bool HandleStaticCommand(int commandId) { switch ((uint)commandId) { case PkgCmdIDList.cmdCreateTable: case PkgCmdIDList.cmdidGlobalCreateTable: TableNode.CreateNew(DataViewHierarchyAccessor); return true; case PkgCmdIDList.cmdCreateProcedure: case PkgCmdIDList.cmdidGlobalCreateProcedure: StoredProcedureNode.CreateNew(DataViewHierarchyAccessor, false); return true; case PkgCmdIDList.cmdCreateFunction: case PkgCmdIDList.cmdidGlobalCreateFunction: StoredProcedureNode.CreateNew(DataViewHierarchyAccessor, true); return true; case PkgCmdIDList.cmdCreateView: case PkgCmdIDList.cmdidGlobalCreateView: ViewNode.CreateNew(DataViewHierarchyAccessor); return true; case PkgCmdIDList.cmdCreateUDF: case PkgCmdIDList.cmdidGlobalCreateUDF: UDFNode.CreateNew(DataViewHierarchyAccessor); return true; } return false; } /// /// Executes a specified command, potentially based on parameters passed in /// from the data view support XML. /// /// /// Identifier of hierarchy item for which command should be executed. /// /// /// The OleCommand object representing the command to invoke. /// /// /// Any OleCommandExecutionOption object instance representing options on the /// invoked command. /// NOT USED. /// /// /// An object representing arguments to the command. /// NOT USED. /// /// /// Returns an object instance representing the value returned by the specified /// command, which is typically nothing. /// public override object ExecuteCommand(int itemId, OleCommand command, OleCommandExecutionOption executionOption, object arguments) { return ExecuteCommand(new int[] { itemId }, command, executionOption, arguments); } private BaseNode MakeNewNode(int id) { string nodeId = DataViewHierarchyAccessor.GetNodeId(id); nodeId = nodeId.ToLowerInvariant(); BaseNode newNode = null; switch (nodeId) { case "table": newNode = new TableNode(DataViewHierarchyAccessor, id); break; case "storedprocedure": newNode = new StoredProcedureNode(DataViewHierarchyAccessor, id, false); break; case "storedfunction": newNode = new StoredProcedureNode(DataViewHierarchyAccessor, id, true); break; case "view": newNode = new ViewNode(DataViewHierarchyAccessor, id); break; case "udf": newNode = new UDFNode(DataViewHierarchyAccessor, id); break; case "trigger": newNode = new TriggerNode(DataViewHierarchyAccessor, id); break; default: throw new NotSupportedException("Node type not supported"); } Debug.Assert(newNode != null); return newNode; } /* #region Hierarchy accessor mediator /// /// Returns hierarchy accessor mediator instance. Create instance at the first call. /// protected ServerExplorerFacade Hierarchy { get { // Check if not created yet if (hierarchyRef == null) { Debug.Assert(DataViewHierarchyAccessor != null, "Hierarchy accessor is not initialized!"); hierarchyRef = new ServerExplorerFacade(DataViewHierarchyAccessor); } // Here must be already created Debug.Assert(hierarchyRef != null, "Failed to initialize hierarchy accessor mediator!"); return hierarchyRef; } } /// /// Used to store hierarchy accessor mediator instance /// private ServerExplorerFacade hierarchyRef; #endregion*/ } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlDataViewSupport.cs0000644000175000017500000000564011127003600030261 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /* * This file contains data view support entity implementation. */ using System; using System.IO; using System.Reflection; using System.Xml; using Microsoft.VisualStudio.Data; using Microsoft.VisualStudio.Shell; using EnvDTE; namespace MySql.Data.VisualStudio { /// /// Represents an implementation of data view support that returns /// the stream of XML containing the data view support elements. /// internal class MySqlDataViewSupport : DataViewSupport { /// /// Constructor does nothing. All the work happens in GetDataViews /// public MySqlDataViewSupport() : base() { } public override Stream GetDataViews() { string xmlName = "MySql.Data.VisualStudio.DDEX.MySqlDataViewSupport.xml"; Assembly executingAssembly = Assembly.GetExecutingAssembly(); Stream stream = executingAssembly.GetManifestResourceStream(xmlName); StreamReader reader = new StreamReader(stream); string xml = reader.ReadToEnd(); reader.Close(); // if we are running under VS 2008 then we need to switch out a couple // of command handlers DTE dte = Package.GetGlobalService(typeof(DTE)) as DTE; if (dte != null && dte.Version.StartsWith("9")) xml = xml.Replace("Microsoft.VisualStudio.DataTools.DBPackage.VDT_OLEDB_CommandHandler_TableTools", "884DD964-5327-461f-9F06-6484DD540F8F"); MemoryStream ms = new MemoryStream(xml.Length); StreamWriter writer = new StreamWriter(ms); writer.Write(xml); writer.Flush(); ms.Position = 0; return ms; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlConnectionUIControl.resx0000644000175000017500000005377411127003600031445 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 True GrowAndShrink 2 Left True NoControl 0, 58 0, 0, 3, 0 56, 13 2 &Password: passwordLabel System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 loginTableLayoutPanel 0 Fill 88, 3 3, 3, 0, 3 212, 20 1 serverNameTextBox System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 loginTableLayoutPanel 1 True System NoControl 88, 78 3, 0, 0, 0 121, 18 4 &Save my password savePasswordCheckBox System.Windows.Forms.CheckBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 loginTableLayoutPanel 2 Left True NoControl 0, 105 0, 3, 0, 0 85, 13 3 &Database name: BottomLeft databaseNameLabel System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 loginTableLayoutPanel 3 Left True NoControl 0, 32 0, 0, 3, 0 61, 13 0 &User name: userNameLabel System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 loginTableLayoutPanel 4 Left True NoControl 0, 6 0, 0, 0, 0 70, 13 0 S&erver name: serverNameLabel System.Windows.Forms.Label, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 loginTableLayoutPanel 5 Left, Right 88, 29 3, 3, 0, 3 212, 20 1 userNameTextBox System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 loginTableLayoutPanel 6 Left, Right 88, 55 3, 3, 0, 3 212, 20 3 passwordTextBox System.Windows.Forms.TextBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 loginTableLayoutPanel 7 False 88, 99 209, 21 6 dbList System.Windows.Forms.ComboBox, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 loginTableLayoutPanel 8 Fill 0, 0 27, 0, 9, 9 5 300, 124 2 loginTableLayoutPanel System.Windows.Forms.TableLayoutPanel, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 $this 0 <?xml version="1.0" encoding="utf-16"?><TableLayoutSettings><Controls><Control Name="passwordLabel" Row="2" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="serverNameTextBox" Row="0" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="savePasswordCheckBox" Row="3" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="databaseNameLabel" Row="4" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="userNameLabel" Row="1" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="serverNameLabel" Row="0" RowSpan="1" Column="0" ColumnSpan="1" /><Control Name="userNameTextBox" Row="1" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="passwordTextBox" Row="2" RowSpan="1" Column="1" ColumnSpan="1" /><Control Name="dbList" Row="4" RowSpan="1" Column="1" ColumnSpan="1" /></Controls><Columns Styles="AutoSize,0,Percent,100" /><Rows Styles="AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,0,AutoSize,59,Absolute,20" /></TableLayoutSettings> True 6, 13 0, 0, 0, 0 300, 124 MySqlDataConnectionUI Microsoft.VisualStudio.Data.DataConnectionUIControl, Microsoft.VisualStudio.Data, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlDataConnectionPromptDialog.Designer.cs0000644000175000017500000001252211127003600034127 0ustar directhexdirecthexnamespace MySql.Data.VisualStudio { partial class MySqlDataConnectionPromptDialog { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.Windows.Forms.Button buttonOK; System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MySqlDataConnectionPromptDialog)); System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; System.Windows.Forms.Label label1; System.Windows.Forms.Label label3; System.Windows.Forms.Button buttonCancel; this.savePassword = new System.Windows.Forms.CheckBox(); this.login = new System.Windows.Forms.TextBox(); this.password = new System.Windows.Forms.TextBox(); buttonOK = new System.Windows.Forms.Button(); tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); label1 = new System.Windows.Forms.Label(); label3 = new System.Windows.Forms.Label(); buttonCancel = new System.Windows.Forms.Button(); tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // buttonOK // buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK; resources.ApplyResources(buttonOK, "buttonOK"); buttonOK.Name = "buttonOK"; buttonOK.UseVisualStyleBackColor = true; buttonOK.Click += new System.EventHandler(this.OkClick); // // tableLayoutPanel1 // resources.ApplyResources(tableLayoutPanel1, "tableLayoutPanel1"); tableLayoutPanel1.Controls.Add(label1, 0, 1); tableLayoutPanel1.Controls.Add(this.savePassword, 1, 2); tableLayoutPanel1.Controls.Add(label3, 0, 0); tableLayoutPanel1.Controls.Add(this.login, 1, 0); tableLayoutPanel1.Controls.Add(this.password, 1, 1); tableLayoutPanel1.Name = "tableLayoutPanel1"; // // label1 // resources.ApplyResources(label1, "label1"); label1.FlatStyle = System.Windows.Forms.FlatStyle.System; label1.Name = "label1"; // // savePassword // resources.ApplyResources(this.savePassword, "savePassword"); this.savePassword.Name = "savePassword"; // // label3 // resources.ApplyResources(label3, "label3"); label3.FlatStyle = System.Windows.Forms.FlatStyle.System; label3.Name = "label3"; // // login // resources.ApplyResources(this.login, "login"); this.login.Name = "login"; this.login.Tag = "User id"; // // password // resources.ApplyResources(this.password, "password"); this.password.Name = "password"; this.password.Tag = "Password"; this.password.UseSystemPasswordChar = true; // // buttonCancel // buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(buttonCancel, "buttonCancel"); buttonCancel.Name = "buttonCancel"; buttonCancel.UseVisualStyleBackColor = true; // // MySqlDataConnectionPromptDialog // this.AcceptButton = buttonOK; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = buttonCancel; this.Controls.Add(buttonCancel); this.Controls.Add(tableLayoutPanel1); this.Controls.Add(buttonOK); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "MySqlDataConnectionPromptDialog"; this.ShowIcon = false; this.ShowInTaskbar = false; tableLayoutPanel1.ResumeLayout(false); tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.CheckBox savePassword; private System.Windows.Forms.TextBox login; private System.Windows.Forms.TextBox password; } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/DDEX/MySqlDataObjectIdentifierConverter.cs0000644000175000017500000000502611127003600033051 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Data.AdoDotNet; using Microsoft.VisualStudio.Data; using System.Data.Common; namespace MySql.Data.VisualStudio { public class MySqlDataObjectIdentifierConverter : AdoDotNetObjectIdentifierConverter { private DataConnection connection; public MySqlDataObjectIdentifierConverter(DataConnection c) : base(c) { connection = c; } protected override string BuildString(string typeName, string[] identifierParts, bool forDisplay) { string id = String.Empty; if (typeName == "Table") { DbConnection c = connection.ConnectionSupport.ProviderObject as DbConnection; string dbName = FormatPart("Table", c.Database, true); if (identifierParts.Length == 1) id = identifierParts[0]; if (identifierParts.Length == 2 && identifierParts[0] == dbName) id = identifierParts[1]; if (identifierParts.Length == 3 && identifierParts[1] == dbName) id = identifierParts[2]; } if (id == String.Empty || forDisplay) id = base.BuildString(typeName, identifierParts, forDisplay); return id; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/MyInstaller.cs0000644000175000017500000004036011127003600025707 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration.Install; using Microsoft.Win32; using System.Reflection; namespace MySql.Data.VisualStudio { [RunInstaller(true)] public class MyInstaller : Installer { private string GetRoot() { string root = String.Empty; bool ranu = false; if (Context.Parameters["RANU"] == "true") ranu = true; if (Context.Parameters["version"] == "VS2005") { if (ranu) throw new NotSupportedException("RANU not supported for Visual Studio 2005"); root = "8.0"; } else if (Context.Parameters["version"] == "VS2008") root = "9.0"; else if (Context.Parameters["version"] == "VS2010") root = "10.0"; else throw new NotSupportedException(); if (Context.Parameters["debug"] == "true") root += "Exp"; if (ranu) root += @"\Configuration"; return root; } public override void Install(IDictionary stateSaver) { string root = GetRoot(); Console.WriteLine("Installing to root " + root); InstallInternal(root); } public override void Uninstall(IDictionary savedState) { string root = GetRoot(); Console.WriteLine("Removing from root " + root); UnInstallInternal(root); } private RegistryKey GetRootKey() { if (Context.Parameters["RANU"] == "true") return Registry.CurrentUser; return Registry.LocalMachine; } private void InstallInternal(string version) { RegistryKey rootKey = GetRootKey(); // Data Source string keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\DataSources\{1}", version, "{98FBE4D8-5583-4233-B219-70FF8C7FBBBD}"); RegistryKey dsKey = rootKey.CreateSubKey(keyPath); dsKey.SetValue(null, "MySQL Server"); RegistryKey dsSubKey = dsKey.CreateSubKey("SupportingProviders").CreateSubKey( Guids.Provider.ToString("B")); dsSubKey.SetValue("Description", "Provider_Description, MySql.Data.VisualStudio.Properties.Resources"); dsSubKey.SetValue("DisplayName", "Datasource_Displayname, MySql.Data.VisualStudio.Properties.Resources"); //"AssociatedSource"="{067EA0D9-BA62-43f7-9106-34930C60C528}" //"PlatformVersion"="2.0" // Data Provider keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\DataProviders\{1}", version, Guids.Provider.ToString("B")); RegistryKey dpKey = rootKey.CreateSubKey(keyPath); dpKey.SetValue(null, ".NET Framework Data Provider for MySQL"); dpKey.SetValue("DisplayName", "Provider_DisplayName, MySql.Data.VisualStudio.Properties.Resources"); dpKey.SetValue("ShortDisplayName", "Provider_ShortDisplayName, MySql.Data.VisualStudio.Properties.Resources"); dpKey.SetValue("Description", "Provider_Description, MySql.Data.VisualStudio.Properties.Resources"); dpKey.SetValue("Technology", "{77AB9A9D-78B9-4ba7-91AC-873F5338F1D2}"); dpKey.SetValue("FactoryService", GuidList.EditorFactoryCLSID.ToString("B")); dpKey.SetValue("InvariantName", "MySql.Data.MySqlClient"); RegistryKey dpKeySO = dpKey.CreateSubKey("SupportedObjects"); dpKeySO.CreateSubKey("DataConnectionPromptDialog"); dpKeySO.CreateSubKey("DataConnectionProperties"); dpKeySO.CreateSubKey("DataConnectionSupport"); dpKeySO.CreateSubKey("DataConnectionUIControl"); dpKeySO.CreateSubKey("DataObjectSupport"); dpKeySO.CreateSubKey("DataSourceInformation"); dpKeySO.CreateSubKey("DataViewSupport"); // Data Provider for the Compact Framework string cfVersion = null; if (version.Equals("8.0")) cfVersion = "v2.0.3600"; if (version.Equals("9.0")) cfVersion = "v3.5.0.0"; if (version.Equals("8.0") || version.Equals("9.0")) { CreateCompactFrameworkKey(rootKey, cfVersion, "PocketPC", Guids.Package.ToString("B")); CreateCompactFrameworkKey(rootKey, cfVersion, "SmartPhone", Guids.Package.ToString("B")); CreateCompactFrameworkKey(rootKey, cfVersion, "WindowsCE", Guids.Package.ToString("B")); } // Menus keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\Menus", version); RegistryKey menuKey = rootKey.OpenSubKey(keyPath, true); menuKey.SetValue(Guids.Package.ToString("B"), ",1000,1"); // Templates keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\Projects\{{a2fe74e1-b743-11d0-ae1a-00a0c90fffc3}}\AddItemTemplates\TemplateDirs\{1}", version, Guids.Package.ToString("B")); RegistryKey templateKey = rootKey.CreateSubKey(keyPath); RegistryKey templateSubKey = templateKey.CreateSubKey("/1"); templateSubKey.SetValue(null, "#105"); string path = Assembly.GetExecutingAssembly().CodeBase; path = path.Substring(8); string root = System.IO.Path.GetDirectoryName(path); templateSubKey.SetValue("Package", Guids.Package.ToString("B")); templateSubKey.SetValue("TemplatesDir", root); templateSubKey.SetValue("SortPriority", 32); // Editor keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\Editors\{1}", version, Guids.SqlEditorFactory.ToString("B")); RegistryKey editorKey = rootKey.CreateSubKey(keyPath); editorKey.SetValue(null, "Package name"); editorKey.SetValue("DisplayName", "#105"); editorKey.SetValue("Package", Guids.Package.ToString("B")); RegistryKey extensionsKey = editorKey.CreateSubKey("Extensions"); extensionsKey.SetValue("mysql", 32); RegistryKey logicalViewsKey = editorKey.CreateSubKey("LogicalViews"); logicalViewsKey.SetValue("{7651a703-06e5-11d1-8ebd-00a0c90f26ea}", ""); // Service keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\Services\{1}", version, GuidList.EditorFactoryCLSID.ToString("B")); RegistryKey srvKey = rootKey.CreateSubKey(keyPath); srvKey.SetValue(null, Guids.Package.ToString("B")); srvKey.SetValue("Name", "MySQL Provider Object Factory"); Assembly a = Assembly.GetExecutingAssembly(); Version v = a.GetName().Version; string assemblyVersion = String.Format("{0}.{1}.{2}", v.Major, v.Minor, v.Build); // Installed products keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\InstalledProducts\MySQL Connector Net {1}", version, assemblyVersion); RegistryKey ipKey = rootKey.CreateSubKey(keyPath); ipKey.SetValue(null, String.Format("MySQL Connector Net {0}", assemblyVersion)); ipKey.SetValue("Package", Guids.Package.ToString("B")); ipKey.SetValue("UseInterface", 1); keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\Languages\Language Services\MySQL", version); RegistryKey langKey = rootKey.CreateSubKey(keyPath); langKey.SetValue(null, "{fa498a2d-116a-4f25-9b55-7938e8e6dda7}"); langKey.SetValue("Package", "{79a115c9-b133-4891-9e7b-242509dad272}"); langKey.SetValue("LangResID", 101); langKey.SetValue("RequestStockColors", 1); // Package keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\Packages\{1}", version, Guids.Package.ToString("B")); RegistryKey packageKey = rootKey.CreateSubKey(keyPath); packageKey.SetValue(null, String.Format("MySQL Connector Net {0}", assemblyVersion)); packageKey.SetValue("InprocServer32", String.Format(@"{0}\system32\mscoree.dll", Environment.GetEnvironmentVariable("windir"))); packageKey.SetValue("Class", typeof(MySqlDataProviderPackage).ToString()); string codeBase = Assembly.GetExecutingAssembly().CodeBase; if (codeBase.StartsWith("file:///")) codeBase = codeBase.Substring(8); packageKey.SetValue("CodeBase", codeBase); packageKey.SetValue("ProductName", "MySQL Tools for Visual Studio"); packageKey.SetValue("ProductVersion", "1.1"); packageKey.SetValue("CompanyName", "MySQL AB c/o MySQL, Inc."); packageKey.SetValue("MinEdition", "standard"); packageKey.SetValue("ID", 100); // our package should autoload if a solution exists keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\AutoLoadPackages\{{F1536EF8-92EC-443C-9ED7-FDADF150DA82}}", version); RegistryKey autoLoadKey = rootKey.OpenSubKey(keyPath, true); autoLoadKey.SetValue(Guids.Package.ToString("B"), 0); } private static void CreateCompactFrameworkKey(RegistryKey rootKey, string version, string platform, string providerGuid) { string keyPath = String.Format(@"Software\Microsoft\.NETCompactFramework\{0}\{1}\DataProviders\{2}", version, platform, providerGuid); RegistryKey dpKey = rootKey.CreateSubKey(keyPath); dpKey.SetValue(null, ".NET Framework Data Provider for MySQL"); dpKey.SetValue("InvariantName", "MySql.Data.MySqlClient"); dpKey.SetValue("RuntimeAssembly", "MySql.Data.CF.dll"); } private void UnInstallInternal(string version) { RegistryKey rootKey = GetRootKey(); // Data Source string keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\DataSources\{1}", version, "{98FBE4D8-5583-4233-B219-70FF8C7FBBBD}"); RegistryKey key = rootKey.OpenSubKey(keyPath); if (key != null) { key.Close(); rootKey.DeleteSubKeyTree(keyPath); } // Data Provider keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\DataProviders\{1}", version, Guids.Provider.ToString("B")); key = rootKey.OpenSubKey(keyPath); if (key != null) { key.Close(); rootKey.DeleteSubKeyTree(keyPath); } // Data Provider for the Compact Framework string cfVersion = null; if (version.Equals("8.0")) cfVersion = "v2.0.3600"; if (version.Equals("9.0")) cfVersion = "v3.5.0.0"; if (!string.IsNullOrEmpty(cfVersion)) { RemoveCompactFrameworkKey(rootKey, cfVersion, "PocketPC", Guids.Package.ToString("B")); RemoveCompactFrameworkKey(rootKey, cfVersion, "SmartPhone", Guids.Package.ToString("B")); RemoveCompactFrameworkKey(rootKey, cfVersion, "WindowsCE", Guids.Package.ToString("B")); } // Menus keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\Menus", version); RegistryKey menuKey = rootKey.OpenSubKey(keyPath, true); menuKey.DeleteValue(Guids.Package.ToString("B"), false); // Templates keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\Projects\{{a2fe74e1-b743-11d0-ae1a-00a0c90fffc3}}\AddItemTemplates\TemplateDirs\{1}", version, Guids.Package.ToString("B")); key = rootKey.OpenSubKey(keyPath); if (key != null) { key.Close(); rootKey.DeleteSubKeyTree(keyPath); } // Editor keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\Editors\{1}", version, Guids.SqlEditorFactory.ToString("B")); key = rootKey.OpenSubKey(keyPath); if (key != null) { key.Close(); rootKey.DeleteSubKeyTree(keyPath); } // Service keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\Services\{1}", version, GuidList.EditorFactoryCLSID.ToString("B")); key = rootKey.OpenSubKey(keyPath); if (key != null) { key.Close(); rootKey.DeleteSubKeyTree(keyPath); } Assembly a = Assembly.GetExecutingAssembly(); string assemblyVersion = a.GetName().Version.ToString(); // Installed products keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\InstalledProducts\MySQL Connector/Net {1}", version, assemblyVersion); key = rootKey.OpenSubKey(keyPath); if (key != null) { key.Close(); rootKey.DeleteSubKeyTree(keyPath); } keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\Languages\Language Services\MySQL", assemblyVersion); key = rootKey.OpenSubKey(keyPath); if (key != null) { key.Close(); rootKey.DeleteSubKey(keyPath); } // Package keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\Packages\{1}", version, Guids.Package.ToString("B")); key = rootKey.OpenSubKey(keyPath); if (key != null) { key.Close(); rootKey.DeleteSubKeyTree(keyPath); } // Autoload keyPath = String.Format(@"Software\Microsoft\VisualStudio\{0}\AutoLoadPackages\{{F1536EF8-92EC-443C-9ED7-FDADF150DA82}}", version); RegistryKey autoLoadKey = rootKey.OpenSubKey(keyPath, true); autoLoadKey.DeleteValue(Guids.Package.ToString("B"), false); } private static void RemoveCompactFrameworkKey(RegistryKey rootKey, string version, string platform, string providerGuid) { string keyPath = String.Format(@"Software\Microsoft\.NETCompactFramework\{0}\{1}\DataProviders\{2}", version, platform, providerGuid); RegistryKey key = rootKey.OpenSubKey(keyPath); if (key != null) { key.Close(); rootKey.DeleteSubKeyTree(keyPath); } } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/MySql.VisualStudio.pkgdef0000644000175000017500000001464011127003600030000 0ustar directhexdirecthex[$RootKey$\DataProviders\{c6882346-e592-4da5-80ba-d2eadcda0359}] @=".NET Framework Data Provider for MySQL" "DisplayName"="Provider_DisplayName, MySql.Data.VisualStudio.Properties.Resources" "ShortDisplayName"="Provider_ShortDisplayName, MySql.Data.VisualStudio.Properties.Resources" "Description"="Provider_Description, MySql.Data.VisualStudio.Properties.Resources" "Technology"="{77AB9A9D-78B9-4ba7-91AC-873F5338F1D2}" "FactoryService"="{D949EA95-EDA1-4b65-8A9E-266949A99360}" [$RootKey$\DataProviders\{c6882346-e592-4da5-80ba-d2eadcda0359}\SupportedObjects] [$RootKey$\DataProviders\{c6882346-e592-4da5-80ba-d2eadcda0359}\SupportedObjects\DataConnectionPromptDialog] [$RootKey$\DataProviders\{c6882346-e592-4da5-80ba-d2eadcda0359}\SupportedObjects\DataConnectionProperties] [$RootKey$\DataProviders\{c6882346-e592-4da5-80ba-d2eadcda0359}\SupportedObjects\DataConnectionSupport] [$RootKey$\DataProviders\{c6882346-e592-4da5-80ba-d2eadcda0359}\SupportedObjects\DataConnectionUIControl] [$RootKey$\DataProviders\{c6882346-e592-4da5-80ba-d2eadcda0359}\SupportedObjects\DataObjectSupport] [$RootKey$\DataProviders\{c6882346-e592-4da5-80ba-d2eadcda0359}\SupportedObjects\DataSourceInformation] [$RootKey$\DataProviders\{c6882346-e592-4da5-80ba-d2eadcda0359}\SupportedObjects\DataViewSupport] [$RootKey$\DataSources\{98FBE4D8-5583-4233-B219-70FF8C7FBBBD}] @="MySQL Database" [$RootKey$\DataSources\{98FBE4D8-5583-4233-B219-70FF8C7FBBBD}\SupportingProviders] [$RootKey$\DataSources\{98FBE4D8-5583-4233-B219-70FF8C7FBBBD}\SupportingProviders\{c6882346-e592-4da5-80ba-d2eadcda0359}] "Description"="Provider_Description, MySql.Data.VisualStudio.Properties.Resources" "DisplayName"="Datasource_Displayname, MySql.Data.VisualStudio.Properties.Resources" [$RootKey$\InstalledProducts\MySqlDataProviderPackage] "Package"="{79a115c9-b133-4891-9e7b-242509dad272}" "UseInterface"=dword:00000001 [$RootKey$\Packages\{79a115c9-b133-4891-9e7b-242509dad272}] @="MySQL Connector Net 6.4.0" "InprocServer32"="$WinDir$\SYSTEM32\MSCOREE.DLL" "Class"="MySql.Data.VisualStudio.MySqlDataProviderPackage" "CodeBase"= "$PackageFolder$\mysql.visualstudio.dll" "ID"=dword:00000064 "MinEdition"="Standard" "ProductVersion"="1.1" "ProductName"="MySQL Tools for Visual Studio" "CompanyName"="MySQL AB c/o Oracle, Inc." [$RootKey$\Menus] "{79a115c9-b133-4891-9e7b-242509dad272}"=", 1000, 1" [$RootKey$\Languages\Language Services\MySQL] @="{fa498a2d-116a-4f25-9b55-7938e8e6dda7}" "Package"="{79a115c9-b133-4891-9e7b-242509dad272}" "LangResID"=dword:00000065 "RequestStockColors"=dword:00000001 [$RootKey$\Services\{d949ea95-eda1-4b65-8a9e-266949a99360}] @="{79a115c9-b133-4891-9e7b-242509dad272}" "Name"="MySQL Provider Object Factory" [$RootKey$\Services\{fa498a2d-116a-4f25-9b55-7938e8e6dda7}] @="{79a115c9-b133-4891-9e7b-242509dad272}" "Name"="MySqlLanguageService" [$RootKey$\Editors\{CAA648E8-D6BD-465e-A1B3-2A0BF9DA5581}] @="MySql Tools for Visual Studio" "DisplayName"="#105" "Package"= "{79A115C9-B133-4891-9E7B-242509DAD272}" [$RootKey$\Editors\{CAA648E8-D6BD-465e-A1B3-2A0BF9DA5581}\Extensions] "mysql"="32" [$RootKey$\Editors\{CAA648E8-D6BD-465e-A1B3-2A0BF9DA5581}\LogicalViews] "{7651a703-06e5-11d1-8ebd-00a0c90f26ea}"="" mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/0000755000175000017500000000000011127003600024755 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/ProfileConfig.cs0000644000175000017500000000364311127003600030040 0ustar directhexdirecthex// Copyright © 2009, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Configuration; using System.Web.Configuration; namespace MySql.Data.VisualStudio.WebConfig { internal class ProfileConfig : GenericConfig { public ProfileConfig() : base() { typeName = "MySQLProfileProvider"; sectionName = "profile"; } protected override ProviderSettings GetMachineSettings() { Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration(); ProfileSection section = (ProfileSection)machineConfig.SectionGroups["system.web"].Sections[sectionName]; foreach (ProviderSettings p in section.Providers) if (p.Type.Contains(typeName)) return p; return null; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/WebConfig.cs0000644000175000017500000002272311127003600027155 0ustar directhexdirecthex// Copyright © 2009, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Xml; using System.Configuration; using System.Web.Configuration; using System.Web.Security; using System.Diagnostics; using System.Web.Profile; using System.Collections.Generic; namespace MySql.Data.VisualStudio.WebConfig { internal class WebConfig { private string webConfigFile; private XmlDocument webDoc; public WebConfig(string filename) { webConfigFile = filename; Initialize(); } private void Initialize() { if (webDoc == null && System.IO.File.Exists(webConfigFile)) { webDoc = new XmlDocument(); webDoc.Load(webConfigFile); } } public void Save() { webDoc.Save(webConfigFile); } public XmlElement GetProviderSection(string type) { if (webDoc == null) return null; XmlNodeList nodes = webDoc.GetElementsByTagName(type); if (nodes.Count == 0) return null; return nodes[0] as XmlElement; } public XmlElement GetProviderElement(string type) { XmlNode el = GetSystemWebNode(type, false, false); if (el == null || el.FirstChild == null) return null; el = el.FirstChild; // move to the element if (el.ChildNodes.Count == 0) return null; foreach (XmlNode node in el.ChildNodes) { if (String.Compare(node.Name, "remove", true) == 0 || String.Compare(node.Name, "clear", true) == 0) continue; string typeName = node.Attributes["type"].Value; if (typeName.StartsWith("MySql.Web.")) return node as XmlElement; } return null; } public XmlElement GetListItem(string topNode, string nodeName, string itemName) { Debug.Assert(webDoc != null); XmlNodeList nodes = webDoc.GetElementsByTagName(topNode); if (nodes.Count == 0) return null; // nodeName == null just means return the top node XmlNode node = nodes[0]; if (nodeName == null) return node as XmlElement; // we are looking for something lower but there is nothing here if (node.ChildNodes.Count == 0) return null; // if we are looking in a provider list, then step over the providers element if (node.FirstChild.Name == "providers") node = node.FirstChild; foreach (XmlNode child in node.ChildNodes) { if (child.Name != nodeName) continue; if (String.Compare(child.Attributes["name"].Value, itemName, true) == 0) return child as XmlElement; } return null; } public string GetConnectionString(string name) { XmlElement el = GetListItem("connectionStrings", "add", name); if (el == null) return null; return el.Attributes["connectionString"].Value; } public void SaveConnectionString(string defaultName, string name, string connectionString) { Debug.Assert(webDoc != null); XmlNode connStrNode = null; XmlNodeList nodes = webDoc.GetElementsByTagName("connectionStrings"); if (nodes.Count == 0) { XmlNode topNode = webDoc.GetElementsByTagName("configuration")[0]; connStrNode = webDoc.CreateElement("connectionStrings"); XmlNode syswebElement = webDoc.GetElementsByTagName("system.web")[0]; topNode.InsertBefore(connStrNode, syswebElement); } else connStrNode = nodes[0]; // remove all traces of the old connection strings RemoveConnectionString(connStrNode, name); if (defaultName == name) { XmlElement remove = webDoc.CreateElement("remove"); remove.SetAttribute("name", defaultName); connStrNode.AppendChild(remove); } XmlElement add = webDoc.CreateElement("add"); add.SetAttribute("name", name); add.SetAttribute("connectionString", connectionString); add.SetAttribute("providerName", "MySql.Data.MySqlClient"); connStrNode.AppendChild(add); } private void RemoveConnectionString(XmlNode parentNode, string name) { List toBeDeleted = new List(); foreach (XmlNode node in parentNode.ChildNodes) { if (String.Compare(node.Attributes["name"].Value, name, true) == 0) toBeDeleted.Add(node); } foreach (XmlNode node in toBeDeleted) parentNode.RemoveChild(node); } public void SetDefaultProvider(string sectionName, string providerName) { XmlElement e = GetSystemWebNode(sectionName, true, false) as XmlElement; e.SetAttribute("defaultProvider", providerName); } public void RemoveProvider(string sectionName, string defaultName, string name) { XmlElement section = GetProviderSection(sectionName); if (section == null) return; section.RemoveAttribute("defaultProvider"); if (section.FirstChild == null) return; XmlElement providers = section.FirstChild as XmlElement; List toBeDeleted = new List(); foreach (XmlNode node in providers.ChildNodes) { if (String.Compare("clear", node.Name, true) == 0) continue; string nodeName = node.Attributes["name"].Value; if ((node.Name == "remove" && String.Compare(nodeName, defaultName, true) == 0) || String.Compare(nodeName, name, true) == 0) toBeDeleted.Add(node); } foreach (XmlNode node in toBeDeleted) providers.RemoveChild(node); if (providers.ChildNodes.Count == 0) section.ParentNode.RemoveChild(section); } public XmlNode GetSystemWebNode(string name, bool createTopNode, bool createProvidersNode) { XmlNode webNode = null; XmlNode systemWebNode = webDoc.GetElementsByTagName("system.web")[0]; foreach (XmlNode node in systemWebNode.ChildNodes) if (node.Name == name) { webNode = node; break; } if (webNode == null && createTopNode) { webNode = (XmlNode)webDoc.CreateElement(name); systemWebNode.InsertBefore(webNode, systemWebNode.FirstChild); } if (createProvidersNode) { if (webNode.ChildNodes.Count == 0) webNode.AppendChild(webDoc.CreateElement("providers")); } return webNode; } private string GetDefaultRoleProvider() { XmlElement el = (XmlElement)GetSystemWebNode("roleManager", false, false); if (el == null) return null; if (!el.HasAttribute("defaultProvider")) return null; return el.Attributes["defaultProvider"].Value; } public XmlElement AddProvider(string sectionName, string defaultName, string name) { XmlElement e = (XmlElement)GetSystemWebNode(sectionName, true, true); e = e.FirstChild as XmlElement; // if we are adding a provider def with the same name as default then we // need to remove the default if (String.Compare(defaultName, name, true) == 0) { XmlElement remove = webDoc.CreateElement("remove"); remove.SetAttribute("name", defaultName); e.AppendChild(remove); } XmlElement add = webDoc.CreateElement("add"); add.SetAttribute("name", name); e.AppendChild(add); return add; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/MembershipConfig.cs0000644000175000017500000001605711127003600030536 0ustar directhexdirecthex// Copyright © 2009, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Configuration; using System.Web.Configuration; using System.Web.Security; using System.Diagnostics; using System.Xml; namespace MySql.Data.VisualStudio.WebConfig { internal struct MembershipOptions { public bool EnablePasswordRetrieval; public bool EnablePasswordReset; public bool RequiresQA; public bool RequiresUniqueEmail; public MembershipPasswordFormat PasswordFormat; public int MaxInvalidPasswordAttempts; public int MinRequiredPasswordLength; public int MinRequiredNonAlphaNumericCharacters; public int PasswordAttemptWindow; public string PasswordStrengthRegEx; } internal class MembershipConfig : GenericConfig { private new MembershipOptions defaults = new MembershipOptions(); private MembershipOptions values; public MembershipConfig() : base() { typeName = "MySQLMembershipProvider"; sectionName = "membership"; } public MembershipOptions MemberOptions { get { return values; } set { values = value; } } protected override ProviderSettings GetMachineSettings() { Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration(); MembershipSection section = (MembershipSection)machineConfig.SectionGroups["system.web"].Sections[sectionName]; foreach (ProviderSettings p in section.Providers) if (p.Type.Contains(typeName)) return p; return null; } public override void Initialize(WebConfig wc) { base.Initialize(wc); values = defaults; XmlElement e = wc.GetProviderElement(sectionName); if (e == null) return; //GetOptionalParameter(e, "description"); if (e.HasAttribute("enablePasswordRetrieval")) values.EnablePasswordRetrieval = Convert.ToBoolean(e.GetAttribute("enablePasswordRetrieval")); if (e.HasAttribute("enablePasswordReset")) values.EnablePasswordReset = Convert.ToBoolean(e.GetAttribute("enablePasswordReset")); if (e.HasAttribute("requiresQuestionAndAnswer")) values.RequiresQA = Convert.ToBoolean(e.GetAttribute("requiresQuestionAndAnswer")); if (e.HasAttribute("requiresUniqueEmail")) values.RequiresUniqueEmail = Convert.ToBoolean(e.GetAttribute("requiresUniqueEmail")); if (e.HasAttribute("passwordFormat")) values.PasswordFormat = (MembershipPasswordFormat)Enum.Parse(typeof(MembershipPasswordFormat), e.GetAttribute("passwordFormat")); if (e.HasAttribute("passwordStrengthRegularExpression")) values.PasswordStrengthRegEx = e.GetAttribute("passwordStrengthRegularExpression"); if (e.HasAttribute("maxInvalidPasswordAttempts")) values.MaxInvalidPasswordAttempts = Convert.ToInt32(e.GetAttribute("maxInvalidPasswordAttempts")); if (e.HasAttribute("minRequiredPasswordLength")) values.MinRequiredPasswordLength = Convert.ToInt32(e.GetAttribute("minRequiredPasswordLength")); if (e.HasAttribute("minRequiredNonalphanumericCharacters")) values.MinRequiredNonAlphaNumericCharacters = Convert.ToInt32(e.GetAttribute("minRequiredNonalphanumericCharacters")); if (e.HasAttribute("passwordAttemptWindow")) values.PasswordAttemptWindow = Convert.ToInt32(e.GetAttribute("passwordAttemptWindow")); } override public void GetDefaults() { base.GetDefaults(); foreach (MembershipProvider p in Membership.Providers) { if (!p.GetType().ToString().Contains("MySQL")) continue; base.defaults.AppDescription = p.Description; defaults.EnablePasswordReset = p.EnablePasswordReset; defaults.EnablePasswordRetrieval = p.EnablePasswordRetrieval; defaults.RequiresQA = p.RequiresQuestionAndAnswer; defaults.RequiresUniqueEmail = p.RequiresUniqueEmail; defaults.PasswordFormat = p.PasswordFormat; defaults.MaxInvalidPasswordAttempts = p.MaxInvalidPasswordAttempts; defaults.MinRequiredPasswordLength = p.MinRequiredPasswordLength; defaults.MinRequiredNonAlphaNumericCharacters = p.MinRequiredNonAlphanumericCharacters; defaults.PasswordAttemptWindow = p.PasswordAttemptWindow; defaults.PasswordStrengthRegEx = p.PasswordStrengthRegularExpression; break; } } protected override void SaveProvider(XmlElement provider) { base.SaveProvider(provider); provider.SetAttribute("enablePasswordRetrieval", values.EnablePasswordRetrieval.ToString()); provider.SetAttribute("enablePasswordReset", values.EnablePasswordReset.ToString()); provider.SetAttribute("requiresQuestionAndAnswer", values.RequiresQA.ToString()); provider.SetAttribute("requiresUniqueEmail", values.RequiresUniqueEmail.ToString()); provider.SetAttribute("passwordFormat", values.PasswordFormat.ToString()); provider.SetAttribute("maxInvalidPasswordAttempts", values.MaxInvalidPasswordAttempts.ToString()); provider.SetAttribute("minRequiredPasswordLength", values.MinRequiredPasswordLength.ToString()); provider.SetAttribute("minRequiredNonalphanumericCharacters", values.MinRequiredNonAlphaNumericCharacters.ToString()); provider.SetAttribute("passwordAttemptWindow", values.PasswordAttemptWindow.ToString()); provider.SetAttribute("passwordStrengthRegularExpression", values.PasswordStrengthRegEx); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/MembershipOptionsDlg.cs0000644000175000017500000000655311127003600031413 0ustar directhexdirecthex// Copyright © 2009, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Windows.Forms; using System.Web.Security; namespace MySql.Data.VisualStudio.WebConfig { public partial class MembershipOptionsDlg : Form { public MembershipOptionsDlg() { InitializeComponent(); passwordFormat.DataSource = Enum.GetValues(typeof(MembershipPasswordFormat)); } internal MembershipOptions Options { get { MembershipOptions options = new MembershipOptions(); options.EnablePasswordReset = enablePasswordReset.Checked; options.EnablePasswordRetrieval = enablePasswordRetrieval.Checked; options.MaxInvalidPasswordAttempts = (int)maxInvalidPassAttempts.Value; options.MinRequiredNonAlphaNumericCharacters = (int)minRequiredNonAlpha.Value; options.MinRequiredPasswordLength = (int)minPassLength.Value; options.PasswordAttemptWindow = (int)passwordAttemptWindow.Value; options.PasswordFormat = (MembershipPasswordFormat)passwordFormat.SelectedItem; options.PasswordStrengthRegEx = passwordRegex.Text.Trim(); options.RequiresQA = requireQA.Checked; options.RequiresUniqueEmail = requireUniqueEmail.Checked; return options; } set { enablePasswordReset.Checked = value.EnablePasswordReset; enablePasswordRetrieval.Checked = value.EnablePasswordRetrieval; maxInvalidPassAttempts.Value = value.MaxInvalidPasswordAttempts; minRequiredNonAlpha.Value = value.MinRequiredNonAlphaNumericCharacters; minPassLength.Value = value.MinRequiredPasswordLength; passwordAttemptWindow.Value = value.PasswordAttemptWindow; passwordFormat.SelectedItem = value.PasswordFormat; passwordRegex.Text = value.PasswordStrengthRegEx; requireQA.Checked = value.RequiresQA; requireUniqueEmail.Checked = value.RequiresUniqueEmail; } } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/RoleConfig.cs0000644000175000017500000000364611127003600027344 0ustar directhexdirecthex// Copyright © 2009, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Configuration; using System.Web.Configuration; namespace MySql.Data.VisualStudio.WebConfig { internal class RoleConfig : GenericConfig { public RoleConfig() : base() { typeName = "MySQLRoleProvider"; sectionName = "roleManager"; } protected override ProviderSettings GetMachineSettings() { Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration(); RoleManagerSection section = (RoleManagerSection)machineConfig.SectionGroups["system.web"].Sections[sectionName]; foreach (ProviderSettings p in section.Providers) if (p.Type.Contains(typeName)) return p; return null; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/ConnectionStringEditorDlg.Designer.cs0000644000175000017500000001240111127003600034125 0ustar directhexdirecthexusing MySql.Data.VisualStudio.Editors; namespace MySql.Data.VisualStudio.WebConfig { partial class ConnectionStringEditorDlg { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.connStrProps = new VS2005PropertyGrid(); this.connectionString = new System.Windows.Forms.TextBox(); this.cancelButton = new System.Windows.Forms.Button(); this.okButton = new System.Windows.Forms.Button(); this.SuspendLayout(); // // connStrProps // this.connStrProps.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.connStrProps.Location = new System.Drawing.Point(10, 10); this.connStrProps.Name = "connStrProps"; this.connStrProps.Size = new System.Drawing.Size(359, 320); this.connStrProps.TabIndex = 0; this.connStrProps.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.connStrProps_PropertyValueChanged); // // connectionString // this.connectionString.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.connectionString.Location = new System.Drawing.Point(10, 342); this.connectionString.Name = "connectionString"; this.connectionString.ReadOnly = true; this.connectionString.Size = new System.Drawing.Size(359, 20); this.connectionString.TabIndex = 1; // // cancelButton // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(294, 368); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 2; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; // // okButton // this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.Location = new System.Drawing.Point(210, 368); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 3; this.okButton.Text = "OK"; this.okButton.UseVisualStyleBackColor = true; // // ConnectionStringEditorDlg // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(379, 398); this.Controls.Add(this.okButton); this.Controls.Add(this.cancelButton); this.Controls.Add(this.connectionString); this.Controls.Add(this.connStrProps); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(285, 314); this.Name = "ConnectionStringEditorDlg"; this.Padding = new System.Windows.Forms.Padding(10); this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "MySql Connection String Editor"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private VS2005PropertyGrid connStrProps; private System.Windows.Forms.TextBox connectionString; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button okButton; } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/ConnectionStringEditorDlg.resx0000644000175000017500000001326611127003600032754 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/WebConfigDlg.Designer.cs0000644000175000017500000003423111127003600031340 0ustar directhexdirecthexnamespace MySql.Data.VisualStudio.WebConfig { partial class WebConfigDlg { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.connectionString = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.writeExToLog = new System.Windows.Forms.CheckBox(); this.appName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.autogenSchema = new System.Windows.Forms.CheckBox(); this.appDescription = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.editConnString = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.nextButton = new System.Windows.Forms.Button(); this.configPanel = new System.Windows.Forms.Panel(); this.controlPanel = new System.Windows.Forms.Panel(); this.advancedBtn = new System.Windows.Forms.Button(); this.useProvider = new System.Windows.Forms.CheckBox(); this.pageLabel = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pageDesc = new System.Windows.Forms.Label(); this.backButton = new System.Windows.Forms.Button(); this.configPanel.SuspendLayout(); this.controlPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // connectionString // this.connectionString.Location = new System.Drawing.Point(114, 63); this.connectionString.Multiline = true; this.connectionString.Name = "connectionString"; this.connectionString.Size = new System.Drawing.Size(276, 40); this.connectionString.TabIndex = 2; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(4, 65); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(94, 13); this.label2.TabIndex = 3; this.label2.Text = "Connection String:"; // // writeExToLog // this.writeExToLog.AutoSize = true; this.writeExToLog.Location = new System.Drawing.Point(114, 134); this.writeExToLog.Name = "writeExToLog"; this.writeExToLog.Size = new System.Drawing.Size(164, 17); this.writeExToLog.TabIndex = 5; this.writeExToLog.Text = "Write exceptions to event log"; this.writeExToLog.UseVisualStyleBackColor = true; // // appName // this.appName.Location = new System.Drawing.Point(114, 9); this.appName.Name = "appName"; this.appName.Size = new System.Drawing.Size(363, 20); this.appName.TabIndex = 0; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(60, 12); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(38, 13); this.label1.TabIndex = 0; this.label1.Text = "Name:"; // // autogenSchema // this.autogenSchema.AutoSize = true; this.autogenSchema.Location = new System.Drawing.Point(114, 111); this.autogenSchema.Name = "autogenSchema"; this.autogenSchema.Size = new System.Drawing.Size(132, 17); this.autogenSchema.TabIndex = 4; this.autogenSchema.Text = "Autogenerate Schema"; this.autogenSchema.UseVisualStyleBackColor = true; // // appDescription // this.appDescription.Location = new System.Drawing.Point(114, 36); this.appDescription.Name = "appDescription"; this.appDescription.Size = new System.Drawing.Size(363, 20); this.appDescription.TabIndex = 1; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(35, 38); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(63, 13); this.label3.TabIndex = 6; this.label3.Text = "Description:"; // // editConnString // this.editConnString.Location = new System.Drawing.Point(396, 63); this.editConnString.Name = "editConnString"; this.editConnString.Size = new System.Drawing.Size(81, 25); this.editConnString.TabIndex = 3; this.editConnString.Text = "Edit..."; this.editConnString.UseVisualStyleBackColor = true; this.editConnString.Click += new System.EventHandler(this.editConnString_Click); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(400, 291); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(81, 25); this.cancelButton.TabIndex = 2; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; // // nextButton // this.nextButton.Location = new System.Drawing.Point(313, 291); this.nextButton.Name = "nextButton"; this.nextButton.Size = new System.Drawing.Size(81, 25); this.nextButton.TabIndex = 1; this.nextButton.Text = "Next"; this.nextButton.UseVisualStyleBackColor = true; this.nextButton.Click += new System.EventHandler(this.nextButton_Click); // // configPanel // this.configPanel.Controls.Add(this.controlPanel); this.configPanel.Controls.Add(this.useProvider); this.configPanel.Location = new System.Drawing.Point(2, 58); this.configPanel.Name = "configPanel"; this.configPanel.Size = new System.Drawing.Size(492, 223); this.configPanel.TabIndex = 8; this.configPanel.Paint += new System.Windows.Forms.PaintEventHandler(this.configPanel_Paint); // // controlPanel // this.controlPanel.Controls.Add(this.label1); this.controlPanel.Controls.Add(this.advancedBtn); this.controlPanel.Controls.Add(this.connectionString); this.controlPanel.Controls.Add(this.autogenSchema); this.controlPanel.Controls.Add(this.appDescription); this.controlPanel.Controls.Add(this.appName); this.controlPanel.Controls.Add(this.label2); this.controlPanel.Controls.Add(this.editConnString); this.controlPanel.Controls.Add(this.writeExToLog); this.controlPanel.Controls.Add(this.label3); this.controlPanel.Location = new System.Drawing.Point(3, 31); this.controlPanel.Name = "controlPanel"; this.controlPanel.Size = new System.Drawing.Size(486, 169); this.controlPanel.TabIndex = 11; // // advancedBtn // this.advancedBtn.Location = new System.Drawing.Point(309, 129); this.advancedBtn.Name = "advancedBtn"; this.advancedBtn.Size = new System.Drawing.Size(81, 25); this.advancedBtn.TabIndex = 6; this.advancedBtn.Text = "Advanced..."; this.advancedBtn.UseVisualStyleBackColor = true; this.advancedBtn.Click += new System.EventHandler(this.advancedBtn_Click); // // useProvider // this.useProvider.AutoSize = true; this.useProvider.Location = new System.Drawing.Point(118, 14); this.useProvider.Name = "useProvider"; this.useProvider.Size = new System.Drawing.Size(80, 17); this.useProvider.TabIndex = 10; this.useProvider.Text = "checkBox1"; this.useProvider.UseVisualStyleBackColor = true; this.useProvider.CheckStateChanged += new System.EventHandler(this.useProvider_CheckStateChanged); // // pageLabel // this.pageLabel.AutoSize = true; this.pageLabel.BackColor = System.Drawing.Color.White; this.pageLabel.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.pageLabel.Location = new System.Drawing.Point(12, 9); this.pageLabel.Name = "pageLabel"; this.pageLabel.Size = new System.Drawing.Size(124, 13); this.pageLabel.TabIndex = 9; this.pageLabel.Text = "Page Title Goes Here"; // // pictureBox1 // this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Top; this.pictureBox1.Image = global::MySql.Data.VisualStudio.Properties.Resources.bannrbmp; this.pictureBox1.Location = new System.Drawing.Point(0, 0); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(493, 58); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox1.TabIndex = 10; this.pictureBox1.TabStop = false; // // pageDesc // this.pageDesc.AutoSize = true; this.pageDesc.BackColor = System.Drawing.Color.White; this.pageDesc.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.pageDesc.Location = new System.Drawing.Point(38, 31); this.pageDesc.Name = "pageDesc"; this.pageDesc.Size = new System.Drawing.Size(140, 13); this.pageDesc.TabIndex = 11; this.pageDesc.Text = "Page Description Goes Here"; // // backButton // this.backButton.Location = new System.Drawing.Point(226, 291); this.backButton.Name = "backButton"; this.backButton.Size = new System.Drawing.Size(81, 25); this.backButton.TabIndex = 0; this.backButton.Text = "Back"; this.backButton.UseVisualStyleBackColor = true; this.backButton.Click += new System.EventHandler(this.backButton_Click); // // WebConfigDlg // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(493, 331); this.Controls.Add(this.backButton); this.Controls.Add(this.pageDesc); this.Controls.Add(this.pageLabel); this.Controls.Add(this.configPanel); this.Controls.Add(this.cancelButton); this.Controls.Add(this.nextButton); this.Controls.Add(this.pictureBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "WebConfigDlg"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "MySQL Website Configuration"; this.configPanel.ResumeLayout(false); this.configPanel.PerformLayout(); this.controlPanel.ResumeLayout(false); this.controlPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox connectionString; private System.Windows.Forms.Label label2; private System.Windows.Forms.CheckBox writeExToLog; private System.Windows.Forms.TextBox appName; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button editConnString; private System.Windows.Forms.TextBox appDescription; private System.Windows.Forms.Label label3; private System.Windows.Forms.CheckBox autogenSchema; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button nextButton; private System.Windows.Forms.Panel configPanel; private System.Windows.Forms.Label pageLabel; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Button advancedBtn; private System.Windows.Forms.Label pageDesc; private System.Windows.Forms.CheckBox useProvider; private System.Windows.Forms.Button backButton; private System.Windows.Forms.Panel controlPanel; } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/MembershipOptionsDlg.Designer.cs0000644000175000017500000003670211127003600033151 0ustar directhexdirecthexnamespace MySql.Data.VisualStudio.WebConfig { partial class MembershipOptionsDlg { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label6 = new System.Windows.Forms.Label(); this.passwordAttemptWindow = new System.Windows.Forms.NumericUpDown(); this.passwordRegex = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.minPassLength = new System.Windows.Forms.NumericUpDown(); this.requireUniqueEmail = new System.Windows.Forms.CheckBox(); this.requireQA = new System.Windows.Forms.CheckBox(); this.enablePasswordRetrieval = new System.Windows.Forms.CheckBox(); this.enablePasswordReset = new System.Windows.Forms.CheckBox(); this.label9 = new System.Windows.Forms.Label(); this.minRequiredNonAlpha = new System.Windows.Forms.NumericUpDown(); this.label10 = new System.Windows.Forms.Label(); this.maxInvalidPassAttempts = new System.Windows.Forms.NumericUpDown(); this.cancelButton = new System.Windows.Forms.Button(); this.okButton = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.passwordFormat = new System.Windows.Forms.ComboBox(); ((System.ComponentModel.ISupportInitialize)(this.passwordAttemptWindow)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.minPassLength)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.minRequiredNonAlpha)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.maxInvalidPassAttempts)).BeginInit(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.SuspendLayout(); // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(20, 54); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(134, 13); this.label6.TabIndex = 28; this.label6.Text = "Password Attempt Window"; // // passwordAttemptWindow // this.passwordAttemptWindow.Location = new System.Drawing.Point(229, 48); this.passwordAttemptWindow.Name = "passwordAttemptWindow"; this.passwordAttemptWindow.Size = new System.Drawing.Size(40, 20); this.passwordAttemptWindow.TabIndex = 27; // // passwordRegex // this.passwordRegex.Location = new System.Drawing.Point(20, 102); this.passwordRegex.Name = "passwordRegex"; this.passwordRegex.Size = new System.Drawing.Size(254, 20); this.passwordRegex.TabIndex = 26; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(20, 86); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(182, 13); this.label7.TabIndex = 25; this.label7.Text = "Password strength regular expression"; // // label8 // this.label8.AutoSize = true; this.label8.Location = new System.Drawing.Point(20, 32); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(179, 13); this.label8.TabIndex = 24; this.label8.Text = "Minimum Required Password Length"; // // minPassLength // this.minPassLength.Location = new System.Drawing.Point(234, 29); this.minPassLength.Name = "minPassLength"; this.minPassLength.Size = new System.Drawing.Size(40, 20); this.minPassLength.TabIndex = 23; // // requireUniqueEmail // this.requireUniqueEmail.AutoSize = true; this.requireUniqueEmail.Location = new System.Drawing.Point(15, 53); this.requireUniqueEmail.Name = "requireUniqueEmail"; this.requireUniqueEmail.Size = new System.Drawing.Size(133, 17); this.requireUniqueEmail.TabIndex = 22; this.requireUniqueEmail.Text = "Requires Unique Email"; this.requireUniqueEmail.UseVisualStyleBackColor = true; // // requireQA // this.requireQA.AutoSize = true; this.requireQA.Location = new System.Drawing.Point(15, 30); this.requireQA.Name = "requireQA"; this.requireQA.Size = new System.Drawing.Size(148, 17); this.requireQA.TabIndex = 21; this.requireQA.Text = "Require Question/Answer"; this.requireQA.UseVisualStyleBackColor = true; // // enablePasswordRetrieval // this.enablePasswordRetrieval.AutoSize = true; this.enablePasswordRetrieval.Location = new System.Drawing.Point(169, 53); this.enablePasswordRetrieval.Name = "enablePasswordRetrieval"; this.enablePasswordRetrieval.Size = new System.Drawing.Size(153, 17); this.enablePasswordRetrieval.TabIndex = 20; this.enablePasswordRetrieval.Text = "Enable Password Retrieval"; this.enablePasswordRetrieval.UseVisualStyleBackColor = true; // // enablePasswordReset // this.enablePasswordReset.AutoSize = true; this.enablePasswordReset.Location = new System.Drawing.Point(169, 30); this.enablePasswordReset.Name = "enablePasswordReset"; this.enablePasswordReset.Size = new System.Drawing.Size(139, 17); this.enablePasswordReset.TabIndex = 19; this.enablePasswordReset.Text = "Enable Password Reset"; this.enablePasswordReset.UseVisualStyleBackColor = true; // // label9 // this.label9.AutoSize = true; this.label9.Location = new System.Drawing.Point(20, 60); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(213, 13); this.label9.TabIndex = 18; this.label9.Text = "Min Required Non-alphanumeric Characters"; // // minRequiredNonAlpha // this.minRequiredNonAlpha.Location = new System.Drawing.Point(234, 58); this.minRequiredNonAlpha.Name = "minRequiredNonAlpha"; this.minRequiredNonAlpha.Size = new System.Drawing.Size(40, 20); this.minRequiredNonAlpha.TabIndex = 17; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(20, 26); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(178, 13); this.label10.TabIndex = 16; this.label10.Text = "Maximum Invalid Password Attempts"; // // maxInvalidPassAttempts // this.maxInvalidPassAttempts.Location = new System.Drawing.Point(231, 19); this.maxInvalidPassAttempts.Name = "maxInvalidPassAttempts"; this.maxInvalidPassAttempts.Size = new System.Drawing.Size(40, 20); this.maxInvalidPassAttempts.TabIndex = 15; // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(259, 418); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(81, 25); this.cancelButton.TabIndex = 31; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; // // okButton // this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.Location = new System.Drawing.Point(172, 418); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(81, 25); this.okButton.TabIndex = 30; this.okButton.Text = "OK"; this.okButton.UseVisualStyleBackColor = true; // // groupBox1 // this.groupBox1.Controls.Add(this.passwordFormat); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.minPassLength); this.groupBox1.Controls.Add(this.minRequiredNonAlpha); this.groupBox1.Controls.Add(this.label9); this.groupBox1.Controls.Add(this.label8); this.groupBox1.Controls.Add(this.label7); this.groupBox1.Controls.Add(this.passwordRegex); this.groupBox1.Location = new System.Drawing.Point(12, 12); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(328, 194); this.groupBox1.TabIndex = 32; this.groupBox1.TabStop = false; this.groupBox1.Text = "Password Options"; // // groupBox2 // this.groupBox2.Controls.Add(this.requireQA); this.groupBox2.Controls.Add(this.requireUniqueEmail); this.groupBox2.Controls.Add(this.enablePasswordReset); this.groupBox2.Controls.Add(this.enablePasswordRetrieval); this.groupBox2.Location = new System.Drawing.Point(12, 219); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(328, 86); this.groupBox2.TabIndex = 33; this.groupBox2.TabStop = false; this.groupBox2.Text = "User Options"; // // groupBox3 // this.groupBox3.Controls.Add(this.passwordAttemptWindow); this.groupBox3.Controls.Add(this.maxInvalidPassAttempts); this.groupBox3.Controls.Add(this.label10); this.groupBox3.Controls.Add(this.label6); this.groupBox3.Location = new System.Drawing.Point(12, 318); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(328, 83); this.groupBox3.TabIndex = 34; this.groupBox3.TabStop = false; this.groupBox3.Text = "Access Options"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(20, 134); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(88, 13); this.label1.TabIndex = 27; this.label1.Text = "Password Format"; // // passwordFormat // this.passwordFormat.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.passwordFormat.FormattingEnabled = true; this.passwordFormat.Location = new System.Drawing.Point(20, 150); this.passwordFormat.Name = "passwordFormat"; this.passwordFormat.Size = new System.Drawing.Size(254, 21); this.passwordFormat.TabIndex = 28; // // MembershipOptionsDlg // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(359, 458); this.Controls.Add(this.groupBox3); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "MembershipOptionsDlg"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Membership Options"; ((System.ComponentModel.ISupportInitialize)(this.passwordAttemptWindow)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.minPassLength)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.minRequiredNonAlpha)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.maxInvalidPassAttempts)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox3.ResumeLayout(false); this.groupBox3.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label6; private System.Windows.Forms.NumericUpDown passwordAttemptWindow; private System.Windows.Forms.TextBox passwordRegex; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label8; private System.Windows.Forms.NumericUpDown minPassLength; private System.Windows.Forms.CheckBox requireUniqueEmail; private System.Windows.Forms.CheckBox requireQA; private System.Windows.Forms.CheckBox enablePasswordRetrieval; private System.Windows.Forms.CheckBox enablePasswordReset; private System.Windows.Forms.Label label9; private System.Windows.Forms.NumericUpDown minRequiredNonAlpha; private System.Windows.Forms.Label label10; private System.Windows.Forms.NumericUpDown maxInvalidPassAttempts; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button okButton; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.ComboBox passwordFormat; private System.Windows.Forms.Label label1; } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/GenericConfig.cs0000644000175000017500000001502511127003600030011 0ustar directhexdirecthex// Copyright © 2009, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Configuration; using System.Web.Configuration; using System.Collections; using System.Xml; namespace MySql.Data.VisualStudio.WebConfig { internal struct Options { public string ProviderName; public string AppName; public string AppDescription; public bool WriteExceptionToLog; public bool AutoGenSchema; public string ConnectionStringName; public string ConnectionString; } internal abstract class GenericConfig { protected bool OriginallyEnabled; protected string sectionName; protected string typeName; protected abstract ProviderSettings GetMachineSettings(); public bool Enabled; public string DefaultProvider; public string ProviderType; protected Options defaults = new Options(); protected Options values; public Options GenericOptions { get { return values; } set { values = value; } } public virtual void GetDefaults() { ProviderSettings p = GetMachineSettings(); ProviderType = p.Type; defaults.ProviderName = p.Name; defaults.ConnectionStringName = GetStringValue(p.Parameters["connectionStringName"]); defaults.AppName = GetStringValue(p.Parameters["applicationName"]); defaults.AppDescription = GetStringValue(p.Parameters["description"]); defaults.AutoGenSchema = GetBoolValue(p.Parameters["autogenerateschema"], false); defaults.WriteExceptionToLog = GetBoolValue(p.Parameters["writeExceptionsToEventLog"], false); } protected string GetStringValue(string s) { if (String.IsNullOrEmpty(s)) return ""; return s; } protected bool GetBoolValue(string s, bool defaultValue) { if (!String.IsNullOrEmpty(s)) { string lower = s.ToLowerInvariant(); if (lower == "true" || lower == "false") return Convert.ToBoolean(lower); } return defaultValue; } public virtual void Initialize(WebConfig wc) { // first load up the defaults GetDefaults(); values = defaults; // get the default provider XmlElement e = wc.GetProviderSection(sectionName); if (e != null) DefaultProvider = e.GetAttribute("defaultProvider"); e = wc.GetProviderElement(sectionName); if (e != null) { values.ProviderName = e.GetAttribute("name"); if (e.HasAttribute("connectionStringName")) values.ConnectionStringName = e.GetAttribute("connectionStringName"); if (e.HasAttribute("description")) values.AppDescription = e.GetAttribute("description"); if (e.HasAttribute("applicationName")) values.AppName = e.GetAttribute("applicationName"); if (e.HasAttribute("writeExceptionsToEventLog")) values.WriteExceptionToLog = GetBoolValue(e.GetAttribute("writeExceptionsToEventLog"), false); if (e.HasAttribute("autogenerateschema")) values.AutoGenSchema = GetBoolValue(e.GetAttribute("autogenerateschema"), false); } values.ConnectionString = wc.GetConnectionString(values.ConnectionStringName); Enabled = OriginallyEnabled = DefaultProvider != null && (DefaultProvider == values.ProviderName || DefaultProvider == defaults.ProviderName); } protected virtual void SaveProvider(XmlElement provider) { provider.SetAttribute("type", ProviderType); provider.SetAttribute("applicationName", values.AppName); provider.SetAttribute("description", values.AppDescription); provider.SetAttribute("connectionStringName", values.ConnectionStringName); provider.SetAttribute("writeExceptionsToEventLog", values.WriteExceptionToLog.ToString()); provider.SetAttribute("autogenerateschema", values.AutoGenSchema.ToString()); } public virtual void Save(WebConfig wc) { if (OriginallyEnabled) wc.RemoveProvider(sectionName, defaults.ProviderName, values.ProviderName); if (!Enabled) return; // we need to save our connection strings even if we are using the default // provider definition wc.SaveConnectionString(defaults.ConnectionStringName, values.ConnectionStringName, values.ConnectionString); // we do this so our equality comparison that follows can work defaults.ConnectionString = values.ConnectionString; // we are enabled so we want to set our defaultProvider attribute wc.SetDefaultProvider(sectionName, values.ProviderName); if (defaults.Equals(values)) return; // our defaults do not equal our new values so we need to redefine our provider XmlElement provider = wc.AddProvider(sectionName, defaults.ProviderName, values.ProviderName); SaveProvider(provider); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/MembershipOptionsDlg.resx0000644000175000017500000001326611127003600031766 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/ConnectionStringEditorDlg.cs0000644000175000017500000000413311127003600032371 0ustar directhexdirecthex// Copyright © 2009, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data.Common; using System.Windows.Forms; using System.Reflection; namespace MySql.Data.VisualStudio.WebConfig { public partial class ConnectionStringEditorDlg : Form { private DbConnectionStringBuilder builder; public ConnectionStringEditorDlg() { InitializeComponent(); DbProviderFactory factory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient"); builder = factory.CreateConnectionStringBuilder (); connStrProps.SelectedObject = builder; } public string ConnectionString { get { return builder.ConnectionString; } set { builder.ConnectionString = value; connectionString.Text = value; } } private void connStrProps_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { connectionString.Text = builder.ConnectionString; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/SessionStateConfig.cs0000644000175000017500000001333111127003600031057 0ustar directhexdirecthex// Copyright © 2009, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Configuration; using System.Web.Configuration; using System.Xml; namespace MySql.Data.VisualStudio.WebConfig { internal class SessionStateConfig : GenericConfig { public SessionStateConfig() : base() { typeName = "MySqlSessionStateStoreProvider"; sectionName = "sessionState"; Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration(); MembershipSection section = (MembershipSection)machineConfig.SectionGroups["system.web"].Sections["membership"]; foreach (ProviderSettings p in section.Providers) if (p.Type.Contains("MySql")) ProviderType = p.Type; ProviderType = ProviderType.Replace("MySql.Web.Security.MySQLMembershipProvider", "MySql.Web.SessionState.MySqlSessionStateStore"); } public override void GetDefaults() { defaults.ProviderName = "MySqlSessionStateProvider"; defaults.WriteExceptionToLog = false; defaults.ConnectionStringName = "LocalMySqlServer"; defaults.AutoGenSchema = false; defaults.AppName = "/"; } protected override ProviderSettings GetMachineSettings() { Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration(); SessionStateSection section = (SessionStateSection)machineConfig.SectionGroups["system.web"].Sections[sectionName]; foreach (ProviderSettings p in section.Providers) if (p.Type.Contains(typeName)) return p; return null; } public override void Initialize(WebConfig wc) { GetDefaults(); values = defaults; // get the default provider XmlElement e = wc.GetProviderSection(sectionName); if (e != null) { string mode = e.GetAttribute("mode"); if (String.Compare(mode, "custom", true) == 0) DefaultProvider = e.GetAttribute("customProvider"); } e = wc.GetProviderElement(sectionName); if (e != null) { values.ProviderName = e.GetAttribute("name"); if (e.HasAttribute("connectionStringName")) values.ConnectionStringName = e.GetAttribute("connectionStringName"); if (e.HasAttribute("description")) values.AppDescription = e.GetAttribute("description"); if (e.HasAttribute("applicationName")) values.AppName = e.GetAttribute("applicationName"); if (e.HasAttribute("writeExceptionsToEventLog")) values.WriteExceptionToLog = GetBoolValue(e.GetAttribute("writeExceptionsToEventLog"), false); if (e.HasAttribute("autogenerateschema")) values.AutoGenSchema = GetBoolValue(e.GetAttribute("autogenerateschema"), false); } values.ConnectionString = wc.GetConnectionString(values.ConnectionStringName); Enabled = OriginallyEnabled = DefaultProvider != null && (DefaultProvider == values.ProviderName || DefaultProvider == defaults.ProviderName); } public override void Save(WebConfig wc) { if (OriginallyEnabled) { XmlElement e = wc.GetProviderSection(sectionName); e.ParentNode.RemoveChild(e); } if (!Enabled) return; // we need to save our connection strings even if we are using the default // provider definition wc.SaveConnectionString(defaults.ConnectionStringName, values.ConnectionStringName, values.ConnectionString); // we do this so our equality comparison that follows can work defaults.ConnectionString = values.ConnectionString; XmlElement provider = wc.AddProvider(sectionName, null, values.ProviderName); SaveProvider(provider); // we are enabled so we want to set our defaultProvider attribute XmlElement sessionNode = (XmlElement)provider.ParentNode.ParentNode; sessionNode.SetAttribute("mode", "Custom"); sessionNode.SetAttribute("cookieless", "true"); sessionNode.SetAttribute("regenerateExpiredSessionId", "true"); sessionNode.SetAttribute("customProvider", values.ProviderName); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/WebConfigDlg.cs0000644000175000017500000002306411127003600027603 0ustar directhexdirecthex// Copyright © 2009, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using EnvDTE80; using EnvDTE; using MySql.Data.VisualStudio.Properties; using System.Web.Security; using System.Configuration.Provider; using System.Web.Profile; using System.Reflection; using System.Diagnostics; using System.Configuration; using System.Data.Common; namespace MySql.Data.VisualStudio.WebConfig { public partial class WebConfigDlg : Form { private string webConfigFileName; private DTE2 dte; private Solution2 solution; private Project project; private int page; private WizardPage[] pages = new WizardPage[4]; public WebConfigDlg() { InitializeComponent(); dte = MySqlDataProviderPackage.GetGlobalService( typeof(EnvDTE.DTE)) as EnvDTE80.DTE2; solution = (Solution2)dte.Solution; FindCurrentWebProject(); EnsureWebConfig(); LoadInitialState(); PageChanged(); } private void FindCurrentWebProject() { project = (Project)solution.Projects.Item(1); } private void EnsureWebConfig() { foreach (ProjectItem items in project.ProjectItems) { if (!String.Equals(items.Name, "web.config", StringComparison.InvariantCultureIgnoreCase)) continue; webConfigFileName = items.get_FileNames(1); break; } if (webConfigFileName == null) { string template = solution.GetProjectItemTemplate("WebConfig.zip", "Web/CSharp"); ProjectItem item = project.ProjectItems.AddFromTemplate(template, "web.config"); webConfigFileName = item.get_FileNames(1); } } private void LoadInitialState() { WebConfig wc = new WebConfig(webConfigFileName); LoadInitialMembershipState(); LoadInitialRoleState(); LoadInitialProfileState(); LoadInitialSessionState(); foreach (WizardPage page in pages) page.ProviderConfig.Initialize(wc); } private void LoadInitialMembershipState() { pages[0].Title = "Membership"; pages[0].Description = "Set options for use with the membership provider"; pages[0].EnabledString = "Use MySQL to manage my membership records"; pages[0].ProviderConfig = new MembershipConfig(); } private void LoadInitialRoleState() { pages[1].Title = "Roles"; pages[1].Description = "Set options for use with the role provider"; pages[1].EnabledString = "Use MySQL to manage my roles"; pages[1].ProviderConfig = new RoleConfig(); } private void LoadInitialProfileState() { pages[2].Title = "Profiles"; pages[2].Description = "Set options for use with the profile provider"; pages[2].EnabledString = "Use MySQL to manage my profiles"; pages[2].ProviderConfig = new ProfileConfig(); } private void LoadInitialSessionState() { pages[3].Title = "Session State"; pages[3].Description = "Set options for use with the session state provider"; pages[3].EnabledString = "Use MySQL to manage my ASP.Net session state"; pages[3].ProviderConfig = new SessionStateConfig(); } private void advancedBtn_Click(object sender, EventArgs e) { MembershipOptionsDlg dlg = new MembershipOptionsDlg(); MembershipConfig config = pages[0].ProviderConfig as MembershipConfig; dlg.Options = config.MemberOptions; DialogResult r = dlg.ShowDialog(); if (DialogResult.Cancel == r) return; config.MemberOptions = dlg.Options; } private void editConnString_Click(object sender, EventArgs e) { ConnectionStringEditorDlg dlg = new ConnectionStringEditorDlg(); try { dlg.ConnectionString = connectionString.Text; if (DialogResult.Cancel == dlg.ShowDialog(this)) return; connectionString.Text = dlg.ConnectionString; } catch (ArgumentException) { MessageBox.Show(this, Resources.ConnectionStringInvalid, Resources.ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void nextButton_Click(object sender, EventArgs e) { if (!SavePageData()) return; if (page == pages.Length - 1) Finish(); else { page++; PageChanged(); } } private void backButton_Click(object sender, EventArgs e) { SavePageData(); page--; PageChanged(); } private bool SavePageData() { if (useProvider.Checked && connectionString.Text.Trim().Length == 0) { MessageBox.Show(this, Resources.WebConfigConnStrNoEmpty, Resources.ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } GenericConfig config = pages[page].ProviderConfig; Options o = config.GenericOptions; o.AppName = appName.Text; o.AppDescription = appDescription.Text.Trim(); o.WriteExceptionToLog = writeExToLog.Checked; o.AutoGenSchema = autogenSchema.Checked; o.ConnectionString = connectionString.Text.Trim(); config.GenericOptions = o; return true; } private void PageChanged() { pageLabel.Text = pages[page].Title; pageDesc.Text = pages[page].Description; useProvider.Text = pages[page].EnabledString; GenericConfig config = pages[page].ProviderConfig; useProvider.Checked = config.Enabled; Options o = config.GenericOptions; appName.Text = o.AppName; appDescription.Text = o.AppDescription; writeExToLog.Checked = o.WriteExceptionToLog; autogenSchema.Checked = o.AutoGenSchema; controlPanel.Enabled = config.Enabled; connectionString.Text = o.ConnectionString; advancedBtn.Visible = page == 0; writeExToLog.Visible = page != 2; nextButton.Text = (page == pages.Length - 1) ? "Finish" : "Next"; backButton.Enabled = page > 0; } private void Finish() { WebConfig w = new WebConfig(webConfigFileName); pages[0].ProviderConfig.Save(w); pages[1].ProviderConfig.Save(w); pages[2].ProviderConfig.Save(w); pages[3].ProviderConfig.Save(w); w.Save(); Close(); } private void configPanel_Paint(object sender, PaintEventArgs e) { Pen darkPen = new Pen(SystemColors.ControlDark); Pen lightPen = new Pen(SystemColors.ControlLightLight); int left = configPanel.ClientRectangle.Left; int right = configPanel.ClientRectangle.Right; int top = configPanel.ClientRectangle.Top; int bottom = configPanel.ClientRectangle.Bottom - 2; e.Graphics.DrawLine(darkPen, left, top, right, top); e.Graphics.DrawLine(lightPen, left, top + 1, right, top + 1); e.Graphics.DrawLine(darkPen, left, bottom, right, bottom); e.Graphics.DrawLine(lightPen, left, bottom + 1, right, bottom + 1); } private void useProvider_CheckStateChanged(object sender, EventArgs e) { GenericConfig config = pages[page].ProviderConfig; config.Enabled = useProvider.Checked; controlPanel.Enabled = config.Enabled; } } internal struct WizardPage { public string Title; public string Description; public string EnabledString; public GenericConfig ProviderConfig; } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/WebConfig/WebConfigDlg.resx0000644000175000017500000001326611127003600030162 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Properties/0000755000175000017500000000000011127003600025246 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.VisualStudio/Properties/Resources.Designer.cs0000644000175000017500000034262111127003600031316 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.5444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace MySql.Data.VisualStudio.Properties { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MySql.Data.VisualStudio.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// /// Looks up a localized string similar to H1PZDDC3CDP8CDKAH1HRAPE2ZQZECRQER1PEIKDCEKD9CMKPDKJZMKPZZIRHEIE2EQZHH9JTJED0ZDPTQ2I8RHJMCQRIZ1MDM9Q9Z1MZE8M2JQHTI1MCA2M3ZDRTEZAR. /// public static string _100 { get { return ResourceManager.GetString("100", resourceCulture); } } /// /// Looks up a localized string similar to MySQL. /// public static string _105 { get { return ResourceManager.GetString("105", resourceCulture); } } /// /// Looks up a localized string similar to MySQL SQL Script. /// public static string _106 { get { return ResourceManager.GetString("106", resourceCulture); } } /// /// Looks up a localized string similar to MySQL Script. /// public static string _107 { get { return ResourceManager.GetString("107", resourceCulture); } } /// /// Looks up a localized string similar to MySQL SQL Script File (.mysql). /// public static string _109 { get { return ResourceManager.GetString("109", resourceCulture); } } public static System.Drawing.Icon _400 { get { object obj = ResourceManager.GetObject("400", resourceCulture); return ((System.Drawing.Icon)(obj)); } } public static System.Drawing.Icon _401 { get { object obj = ResourceManager.GetObject("401", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// /// Looks up a localized string similar to Cannot alter trigger '{0}' on '{1}' because this trigger does not belong to this object. Specify the correct trigger name or the correct target object name.. /// public static string AlterTriggerOnWrongTable { get { return ResourceManager.GetString("AlterTriggerOnWrongTable", resourceCulture); } } public static System.Drawing.Bitmap ArrowKey { get { object obj = ResourceManager.GetObject("ArrowKey", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } public static System.Drawing.Bitmap bannrbmp { get { object obj = ResourceManager.GetObject("bannrbmp", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized string similar to Advanced. /// public static string Category_Advanced { get { return ResourceManager.GetString("Category_Advanced", resourceCulture); } } /// /// Looks up a localized string similar to Authentication. /// public static string Category_Authentication { get { return ResourceManager.GetString("Category_Authentication", resourceCulture); } } /// /// Looks up a localized string similar to Base. /// public static string Category_Base { get { return ResourceManager.GetString("Category_Base", resourceCulture); } } /// /// Looks up a localized string similar to Connection. /// public static string Category_Connection { get { return ResourceManager.GetString("Category_Connection", resourceCulture); } } /// /// Looks up a localized string similar to Data Type. /// public static string Category_DataType { get { return ResourceManager.GetString("Category_DataType", resourceCulture); } } /// /// Looks up a localized string similar to (Identifier). /// public static string Category_Identifier { get { return ResourceManager.GetString("Category_Identifier", resourceCulture); } } /// /// Looks up a localized string similar to Pooling. /// public static string Category_Pooling { get { return ResourceManager.GetString("Category_Pooling", resourceCulture); } } /// /// Looks up a localized string similar to Security. /// public static string Category_Security { get { return ResourceManager.GetString("Category_Security", resourceCulture); } } /// /// Looks up a localized string similar to Statistic. /// public static string Category_Statistic { get { return ResourceManager.GetString("Category_Statistic", resourceCulture); } } /// /// Looks up a localized string similar to Column name missing for column definition. Column will be deleted. To correct, choose cancel and specify the name of the column.. /// public static string ColumnWillBeDeleted { get { return ResourceManager.GetString("ColumnWillBeDeleted", resourceCulture); } } /// /// Looks up a localized string similar to An error occurred that is normally caused by not having Connector/Net properly installed.. /// public static string ConnectionPropertiesNull { get { return ResourceManager.GetString("ConnectionPropertiesNull", resourceCulture); } } /// /// Looks up a localized string similar to The specified connection string is invalid.. /// public static string ConnectionStringInvalid { get { return ResourceManager.GetString("ConnectionStringInvalid", resourceCulture); } } /// /// Looks up a localized string similar to MySQL Database. /// public static string DataSource_DisplayName { get { return ResourceManager.GetString("DataSource_DisplayName", resourceCulture); } } /// /// Looks up a localized string similar to Default View. /// public static string DataView_Default { get { return ResourceManager.GetString("DataView_Default", resourceCulture); } } /// /// Looks up a localized string similar to True if you want to delay key updates until the table is closed. (MyISAM only). /// public static string DelayKeyWriteDesc { get { return ResourceManager.GetString("DelayKeyWriteDesc", resourceCulture); } } /// /// Looks up a localized string similar to Allows execution of multiple SQL commands in a single statement. /// public static string Description_AllowBatch { get { return ResourceManager.GetString("Description_AllowBatch", resourceCulture); } } /// /// Looks up a localized string similar to Should zero datetimes be supported. /// public static string Description_AllowZero { get { return ResourceManager.GetString("Description_AllowZero", resourceCulture); } } /// /// Looks up a localized string similar to Indicates how many stored procedures can be cached at one time. A value of 0 effectively disables the procedure cache. /// public static string Description_CacheSize { get { return ResourceManager.GetString("Description_CacheSize", resourceCulture); } } /// /// Looks up a localized string similar to Character set this connection should use. /// public static string Description_CharacterSet { get { return ResourceManager.GetString("Description_CharacterSet", resourceCulture); } } /// /// Looks up a localized string similar to The way this column participate table keys and indices.. /// public static string Description_Column_ColumnKey { get { return ResourceManager.GetString("Description_Column_ColumnKey", resourceCulture); } } /// /// Looks up a localized string similar to The default value used to initialize new row values for this column.. /// public static string Description_Column_Default { get { return ResourceManager.GetString("Description_Column_Default", resourceCulture); } } /// /// Looks up a localized string similar to The advanced options for the column.. /// public static string Description_Column_Extra { get { return ResourceManager.GetString("Description_Column_Extra", resourceCulture); } } /// /// Looks up a localized string similar to Indicates if null values are allowed in this database object.. /// public static string Description_Column_Nullable { get { return ResourceManager.GetString("Description_Column_Nullable", resourceCulture); } } /// /// Looks up a localized string similar to The maximum length (in bytes) that can be stored in the column. Should be the same as Length, except for multi-byte character sets.. /// public static string Description_Column_OctetLength { get { return ResourceManager.GetString("Description_Column_OctetLength", resourceCulture); } } /// /// Looks up a localized string similar to The position of this object in the parent database object definition.. /// public static string Description_Column_Ordinal { get { return ResourceManager.GetString("Description_Column_Ordinal", resourceCulture); } } /// /// Looks up a localized string similar to The privileges for the column.. /// public static string Description_Column_Privileges { get { return ResourceManager.GetString("Description_Column_Privileges", resourceCulture); } } /// /// Looks up a localized string similar to The ANSI SQL type definition for the column.. /// public static string Description_Column_SqlType { get { return ResourceManager.GetString("Description_Column_SqlType", resourceCulture); } } /// /// Looks up a localized string similar to Should the connection ues compression. /// public static string Description_Compression { get { return ResourceManager.GetString("Description_Compression", resourceCulture); } } /// /// Looks up a localized string similar to When true, indicates the connection state is reset when removed from the pool. /// public static string Description_ConnReset { get { return ResourceManager.GetString("Description_ConnReset", resourceCulture); } } /// /// Looks up a localized string similar to Should illegal datetime values be converted to DateTime.MinValue. /// public static string Description_ConvertZero { get { return ResourceManager.GetString("Description_ConvertZero", resourceCulture); } } /// /// Looks up a localized string similar to The default schema name. Can be empty, but it is not recommended.. /// public static string Description_Database { get { return ResourceManager.GetString("Description_Database", resourceCulture); } } /// /// Looks up a localized string similar to Specifies the type of driver to use for this connection. /// public static string Description_DriverType { get { return ResourceManager.GetString("Description_DriverType", resourceCulture); } } /// /// Looks up a localized string similar to The minimum amount of time (in seconds) for this connection to live in the pool before being destroyed. /// public static string Description_LifeTime { get { return ResourceManager.GetString("Description_LifeTime", resourceCulture); } } /// /// Looks up a localized string similar to Enables output of diagnostic messages. /// public static string Description_Logging { get { return ResourceManager.GetString("Description_Logging", resourceCulture); } } /// /// Looks up a localized string similar to The maximum number of connections allowed in the pool. /// public static string Description_MaxPoolSize { get { return ResourceManager.GetString("Description_MaxPoolSize", resourceCulture); } } /// /// Looks up a localized string similar to The minimum number of connections allowed in the pool. /// public static string Description_MinPoolSize { get { return ResourceManager.GetString("Description_MinPoolSize", resourceCulture); } } /// /// Looks up a localized string similar to The default character set that is used for the database object.. /// public static string Description_Object_CharacterSet { get { return ResourceManager.GetString("Description_Object_CharacterSet", resourceCulture); } } /// /// Looks up a localized string similar to The collation that is used to compare text for the database object.. /// public static string Description_Object_Collation { get { return ResourceManager.GetString("Description_Object_Collation", resourceCulture); } } /// /// Looks up a localized string similar to The brief description of the database object.. /// public static string Description_Object_Comment { get { return ResourceManager.GetString("Description_Object_Comment", resourceCulture); } } /// /// Looks up a localized string similar to The date and time when the database object was created.. /// public static string Description_Object_CreationTime { get { return ResourceManager.GetString("Description_Object_CreationTime", resourceCulture); } } /// /// Looks up a localized string similar to The database catalog which owns the database object.. /// public static string Description_Object_Database { get { return ResourceManager.GetString("Description_Object_Database", resourceCulture); } } /// /// Looks up a localized string similar to Creator of the object. /// public static string Description_Object_Definer { get { return ResourceManager.GetString("Description_Object_Definer", resourceCulture); } } /// /// Looks up a localized string similar to The flags used to modify data type of this database object.. /// public static string Description_Object_Flags { get { return ResourceManager.GetString("Description_Object_Flags", resourceCulture); } } /// /// Looks up a localized string similar to The maximum length (in characters) that can be stored in this database object.. /// public static string Description_Object_Length { get { return ResourceManager.GetString("Description_Object_Length", resourceCulture); } } /// /// Looks up a localized string similar to SQL Mode of the object. /// public static string Description_Object_Mode { get { return ResourceManager.GetString("Description_Object_Mode", resourceCulture); } } /// /// Looks up a localized string similar to The native MySQL type for the database object.. /// public static string Description_Object_MySqlType { get { return ResourceManager.GetString("Description_Object_MySqlType", resourceCulture); } } /// /// Looks up a localized string similar to The name of the database object.. /// public static string Description_Object_Name { get { return ResourceManager.GetString("Description_Object_Name", resourceCulture); } } /// /// Looks up a localized string similar to For numeric data, the maximum number of decimal digits that can be stored in this database object.. /// public static string Description_Object_Precision { get { return ResourceManager.GetString("Description_Object_Precision", resourceCulture); } } /// /// Looks up a localized string similar to For numeric data, the maximum number of decimal digits that can be stored in this database object to the right of a decimal point.. /// public static string Description_Object_Scale { get { return ResourceManager.GetString("Description_Object_Scale", resourceCulture); } } /// /// Looks up a localized string similar to The schema which owns the database object.. /// public static string Description_Object_Schema { get { return ResourceManager.GetString("Description_Object_Schema", resourceCulture); } } /// /// Looks up a localized string similar to Security type of the object. /// public static string Description_Object_SecurityType { get { return ResourceManager.GetString("Description_Object_SecurityType", resourceCulture); } } /// /// Looks up a localized string similar to The host name of the MySQL server which runs underlying database.. /// public static string Description_Object_Server { get { return ResourceManager.GetString("Description_Object_Server", resourceCulture); } } /// /// Looks up a localized string similar to The table which owns the database object.. /// public static string Description_Object_Table { get { return ResourceManager.GetString("Description_Object_Table", resourceCulture); } } /// /// Looks up a localized string similar to A view owning this object. /// public static string Description_Object_View { get { return ResourceManager.GetString("Description_Object_View", resourceCulture); } } /// /// Looks up a localized string similar to Name of the file with startup options. /// public static string Description_OptionFile { get { return ResourceManager.GetString("Description_OptionFile", resourceCulture); } } /// /// Looks up a localized string similar to Shows if this parameter is the return value for the routine.. /// public static string Description_Parameter_IsResult { get { return ResourceManager.GetString("Description_Parameter_IsResult", resourceCulture); } } /// /// Looks up a localized string similar to The direction of this parameter.. /// public static string Description_Parameter_Mode { get { return ResourceManager.GetString("Description_Parameter_Mode", resourceCulture); } } /// /// Looks up a localized string similar to The position of this object in the parent database object definition.. /// public static string Description_Parameter_Ordinal { get { return ResourceManager.GetString("Description_Parameter_Ordinal", resourceCulture); } } /// /// Looks up a localized string similar to The stored procedure that owns this database object.. /// public static string Description_Parameter_StoredProcedure { get { return ResourceManager.GetString("Description_Parameter_StoredProcedure", resourceCulture); } } /// /// Looks up a localized string similar to The database user password.. /// public static string Description_Password { get { return ResourceManager.GetString("Description_Password", resourceCulture); } } /// /// Looks up a localized string similar to Indicates that performance counters should be updated during execution. /// public static string Description_PerfMonitor { get { return ResourceManager.GetString("Description_PerfMonitor", resourceCulture); } } /// /// Looks up a localized string similar to When false, security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. /// public static string Description_Persist { get { return ResourceManager.GetString("Description_Persist", resourceCulture); } } /// /// Looks up a localized string similar to Name of pipe to use when connecting with named pipes (Win32 only). /// public static string Description_PipeName { get { return ResourceManager.GetString("Description_PipeName", resourceCulture); } } /// /// Looks up a localized string similar to When true, the connection object is drawn from the appropriate pool, or if necessary, is created and added to the appropriate pool. /// public static string Description_Pooling { get { return ResourceManager.GetString("Description_Pooling", resourceCulture); } } /// /// Looks up a localized string similar to The port to use when connecting with sockets. /// public static string Description_Port { get { return ResourceManager.GetString("Description_Port", resourceCulture); } } /// /// Looks up a localized string similar to Protocol to use for connection to MySQL. /// public static string Description_Protocol { get { return ResourceManager.GetString("Description_Protocol", resourceCulture); } } /// /// Looks up a localized string similar to Return type of the routine. /// public static string Description_Routine_Returns { get { return ResourceManager.GetString("Description_Routine_Returns", resourceCulture); } } /// /// Looks up a localized string similar to The schema that owns the database object.. /// public static string Description_Schema { get { return ResourceManager.GetString("Description_Schema", resourceCulture); } } /// /// Looks up a localized string similar to The MySQL server IP or hostname.. /// public static string Description_Server { get { return ResourceManager.GetString("Description_Server", resourceCulture); } } /// /// Looks up a localized string similar to Name of the shared memory object to use. /// public static string Description_SharedMemory { get { return ResourceManager.GetString("Description_SharedMemory", resourceCulture); } } /// /// Looks up a localized string similar to Language of the body of the routine. /// public static string Description_StoredProcedure_Body { get { return ResourceManager.GetString("Description_StoredProcedure_Body", resourceCulture); } } /// /// Looks up a localized string similar to Comments. /// public static string Description_StoredProcedure_Comment { get { return ResourceManager.GetString("Description_StoredProcedure_Comment", resourceCulture); } } /// /// Looks up a localized string similar to Type of data access of the routine. /// public static string Description_StoredProcedure_DataAccess { get { return ResourceManager.GetString("Description_StoredProcedure_DataAccess", resourceCulture); } } /// /// Looks up a localized string similar to Body of the routine. /// public static string Description_StoredProcedure_Definition { get { return ResourceManager.GetString("Description_StoredProcedure_Definition", resourceCulture); } } /// /// Looks up a localized string similar to External language used to write the routine. /// public static string Description_StoredProcedure_ExternalLanguage { get { return ResourceManager.GetString("Description_StoredProcedure_ExternalLanguage", resourceCulture); } } /// /// Looks up a localized string similar to External name of the routine. /// public static string Description_StoredProcedure_ExternalName { get { return ResourceManager.GetString("Description_StoredProcedure_ExternalName", resourceCulture); } } /// /// Looks up a localized string similar to Defines if the routine is deterministic. /// public static string Description_StoredProcedure_IsDeterministic { get { return ResourceManager.GetString("Description_StoredProcedure_IsDeterministic", resourceCulture); } } /// /// Looks up a localized string similar to Time of the last modification of the routine. /// public static string Description_StoredProcedure_LastModified { get { return ResourceManager.GetString("Description_StoredProcedure_LastModified", resourceCulture); } } /// /// Looks up a localized string similar to List of parameters of the routine. /// public static string Description_StoredProcedure_ParameterList { get { return ResourceManager.GetString("Description_StoredProcedure_ParameterList", resourceCulture); } } /// /// Looks up a localized string similar to Parameter style of the routine. /// public static string Description_StoredProcedure_ParameterStyle { get { return ResourceManager.GetString("Description_StoredProcedure_ParameterStyle", resourceCulture); } } /// /// Looks up a localized string similar to Specific name of the routine. /// public static string Description_StoredProcedure_SpecificName { get { return ResourceManager.GetString("Description_StoredProcedure_SpecificName", resourceCulture); } } /// /// Looks up a localized string similar to SQL path to the routine. /// public static string Description_StoredProcedure_SqlPath { get { return ResourceManager.GetString("Description_StoredProcedure_SqlPath", resourceCulture); } } /// /// Looks up a localized string similar to Type of the routine (procedure or function). /// public static string Description_StoredProcedure_Type { get { return ResourceManager.GetString("Description_StoredProcedure_Type", resourceCulture); } } /// /// Looks up a localized string similar to The initial AUTO_INCREMENT value for the table. Only for MyISAM tables with a least one AUTO_INCREMENT column.. /// public static string Description_Table_AutoIncrement { get { return ResourceManager.GetString("Description_Table_AutoIncrement", resourceCulture); } } /// /// Looks up a localized string similar to The average length for the rows in the table.. /// public static string Description_Table_AverageRowLength { get { return ResourceManager.GetString("Description_Table_AverageRowLength", resourceCulture); } } /// /// Looks up a localized string similar to An approximation of the average row length for the table. Set this value only for large tables with variable-size records.. /// public static string Description_Table_AverageRowLength_Option { get { return ResourceManager.GetString("Description_Table_AverageRowLength_Option", resourceCulture); } } /// /// Looks up a localized string similar to The date and time when the table was checked last time.. /// public static string Description_Table_CheckDateTime { get { return ResourceManager.GetString("Description_Table_CheckDateTime", resourceCulture); } } /// /// Looks up a localized string similar to The checksum for the table.. /// public static string Description_Table_Checksum { get { return ResourceManager.GetString("Description_Table_Checksum", resourceCulture); } } /// /// Looks up a localized string similar to Set this option if you want MySQL to maintain a live checksum for all rows (that is, a checksum that MySQL updates automatically as the table changes). This makes the table a little slower to update, but also makes it easier to find corrupted tables. The CHECKSUM TABLE statement reports the checksum. (MyISAM only.). /// public static string Description_Table_Checksum_Option { get { return ResourceManager.GetString("Description_Table_Checksum_Option", resourceCulture); } } /// /// Looks up a localized string similar to The connection string for a FEDERATED table. This option is available as of MySQL 5.0.13; before that, use a COMMENT option for the connection string.. /// public static string Description_Table_Connection_Option { get { return ResourceManager.GetString("Description_Table_Connection_Option", resourceCulture); } } /// /// Looks up a localized string similar to The options, used to create the table.. /// public static string Description_Table_CreateOptions { get { return ResourceManager.GetString("Description_Table_CreateOptions", resourceCulture); } } /// /// Looks up a localized string similar to By using this option you can specify where the MyISAM storage engine should put a table's data file. The directory must be the full pathname to the directory, not a relative path.. /// public static string Description_Table_DataDirectory_Option { get { return ResourceManager.GetString("Description_Table_DataDirectory_Option", resourceCulture); } } /// /// Looks up a localized string similar to . /// public static string Description_Table_DataFree { get { return ResourceManager.GetString("Description_Table_DataFree", resourceCulture); } } /// /// Looks up a localized string similar to The data length for the table.. /// public static string Description_Table_DataLength { get { return ResourceManager.GetString("Description_Table_DataLength", resourceCulture); } } /// /// Looks up a localized string similar to Set this option if you want to delay key updates for the table until the table is closed. (MyISAM only.). /// public static string Description_Table_DelayKeyWrite { get { return ResourceManager.GetString("Description_Table_DelayKeyWrite", resourceCulture); } } /// /// Looks up a localized string similar to The storage engine used for the table.. /// public static string Description_Table_Engine { get { return ResourceManager.GetString("Description_Table_Engine", resourceCulture); } } /// /// Looks up a localized string similar to By using this option you can specify where the MyISAM storage engine should put a table's index file. The directory must be the full pathname to the directory, not a relative path.. /// public static string Description_Table_IndexDirectory_Option { get { return ResourceManager.GetString("Description_Table_IndexDirectory_Option", resourceCulture); } } /// /// Looks up a localized string similar to The index length for the table.. /// public static string Description_Table_IndexLength { get { return ResourceManager.GetString("Description_Table_IndexLength", resourceCulture); } } /// /// Looks up a localized string similar to If you want to insert data into a MERGE table, you must specify with INSERT_METHOD the table into which the row should be inserted. INSERT_METHOD is an option useful for MERGE tables only. Use a value of FIRST or LAST to have inserts go to the first or last table, or a value of NO to prevent inserts.. /// public static string Description_Table_InsertMethod { get { return ResourceManager.GetString("Description_Table_InsertMethod", resourceCulture); } } /// /// Looks up a localized string similar to The maximum data length for the table.. /// public static string Description_Table_MaxDataLength { get { return ResourceManager.GetString("Description_Table_MaxDataLength", resourceCulture); } } /// /// Looks up a localized string similar to The maximum number of rows you plan to store in the table. This is not a hard limit, but rather a hint to the storage engine that the table must be able to store at least this many rows.. /// public static string Description_Table_MaxRows_Option { get { return ResourceManager.GetString("Description_Table_MaxRows_Option", resourceCulture); } } /// /// Looks up a localized string similar to The minimum number of rows you plan to store in the table.. /// public static string Description_Table_MinRows_Option { get { return ResourceManager.GetString("Description_Table_MinRows_Option", resourceCulture); } } /// /// Looks up a localized string similar to Use this option to generate smaller indices. This usually makes updates slower and reads faster. Setting it to DEFAULT tells the storage engine to only pack long CHAR/VARCHAR columns.. /// public static string Description_Table_PackKeys { get { return ResourceManager.GetString("Description_Table_PackKeys", resourceCulture); } } /// /// Looks up a localized string similar to Use this option to encrypt the .frm file with a password. This option does nothing in the standard MySQL version.. /// public static string Description_Table_Password { get { return ResourceManager.GetString("Description_Table_Password", resourceCulture); } } /// /// Looks up a localized string similar to The row format used for the table.. /// public static string Description_Table_RowFormat { get { return ResourceManager.GetString("Description_Table_RowFormat", resourceCulture); } } /// /// Looks up a localized string similar to Defines how the rows should be stored. For MyISAM tables, the option value can be FIXED or DYNAMIC for static or variable-length row format. myisampack sets the type to COMPRESSED.. /// public static string Description_Table_RowFormat_Option { get { return ResourceManager.GetString("Description_Table_RowFormat_Option", resourceCulture); } } /// /// Looks up a localized string similar to The amount of rows in the table.. /// public static string Description_Table_TableRows { get { return ResourceManager.GetString("Description_Table_TableRows", resourceCulture); } } /// /// Looks up a localized string similar to The type of the table.. /// public static string Description_Table_Type { get { return ResourceManager.GetString("Description_Table_Type", resourceCulture); } } /// /// Looks up a localized string similar to List of MyISAM tables that should be used by the MERGE table.. /// public static string Description_Table_Union { get { return ResourceManager.GetString("Description_Table_Union", resourceCulture); } } /// /// Looks up a localized string similar to The date and time when the table was updated last time.. /// public static string Description_Table_UpdateDateTime { get { return ResourceManager.GetString("Description_Table_UpdateDateTime", resourceCulture); } } /// /// Looks up a localized string similar to The storage engine version.. /// public static string Description_Table_Version { get { return ResourceManager.GetString("Description_Table_Version", resourceCulture); } } /// /// Looks up a localized string similar to The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error. /// public static string Description_Timeout { get { return ResourceManager.GetString("Description_Timeout", resourceCulture); } } /// /// Looks up a localized string similar to Condition of the trigger. /// public static string Description_Trigger_Condition { get { return ResourceManager.GetString("Description_Trigger_Condition", resourceCulture); } } /// /// Looks up a localized string similar to A catalog on which an action is performed. /// public static string Description_Trigger_EventCatalog { get { return ResourceManager.GetString("Description_Trigger_EventCatalog", resourceCulture); } } /// /// Looks up a localized string similar to An event on which the trigger is switched on. /// public static string Description_Trigger_EventManipulation { get { return ResourceManager.GetString("Description_Trigger_EventManipulation", resourceCulture); } } /// /// Looks up a localized string similar to A schema on which an action is performed. /// public static string Description_Trigger_EventSchema { get { return ResourceManager.GetString("Description_Trigger_EventSchema", resourceCulture); } } /// /// Looks up a localized string similar to A table on which an action is performed. /// public static string Description_Trigger_EventTable { get { return ResourceManager.GetString("Description_Trigger_EventTable", resourceCulture); } } /// /// Looks up a localized string similar to The order number of the action. /// public static string Description_Trigger_Order { get { return ResourceManager.GetString("Description_Trigger_Order", resourceCulture); } } /// /// Looks up a localized string similar to An atomic object of a trigger action. /// public static string Description_Trigger_Orientation { get { return ResourceManager.GetString("Description_Trigger_Orientation", resourceCulture); } } /// /// Looks up a localized string similar to An action reference to a new row. /// public static string Description_Trigger_RefToNewRow { get { return ResourceManager.GetString("Description_Trigger_RefToNewRow", resourceCulture); } } /// /// Looks up a localized string similar to An action reference to a new table. /// public static string Description_Trigger_RefToNewTable { get { return ResourceManager.GetString("Description_Trigger_RefToNewTable", resourceCulture); } } /// /// Looks up a localized string similar to An action reference to an old row. /// public static string Description_Trigger_RefToOldRow { get { return ResourceManager.GetString("Description_Trigger_RefToOldRow", resourceCulture); } } /// /// Looks up a localized string similar to An action reference to an old table. /// public static string Description_Trigger_RefToOldTable { get { return ResourceManager.GetString("Description_Trigger_RefToOldTable", resourceCulture); } } /// /// Looks up a localized string similar to A statement executed by the trigger. /// public static string Description_Trigger_Statement { get { return ResourceManager.GetString("Description_Trigger_Statement", resourceCulture); } } /// /// Looks up a localized string similar to The trigger action time. /// public static string Description_Trigger_Timing { get { return ResourceManager.GetString("Description_Trigger_Timing", resourceCulture); } } /// /// Looks up a localized string similar to The basename of the file containing the implementation of the function.. /// public static string Description_UDF_Dll { get { return ResourceManager.GetString("Description_UDF_Dll", resourceCulture); } } /// /// Looks up a localized string similar to Indicates if the function is aggregate function.. /// public static string Description_UDF_IsAgregate { get { return ResourceManager.GetString("Description_UDF_IsAgregate", resourceCulture); } } /// /// Looks up a localized string similar to The type of the function.. /// public static string Description_UDF_Type { get { return ResourceManager.GetString("Description_UDF_Type", resourceCulture); } } /// /// Looks up a localized string similar to Allows the use of old style @ syntax for parameters. /// public static string Description_UseOldSyntax { get { return ResourceManager.GetString("Description_UseOldSyntax", resourceCulture); } } /// /// Looks up a localized string similar to The database user login name.. /// public static string Description_UserID { get { return ResourceManager.GetString("Description_UserID", resourceCulture); } } /// /// Looks up a localized string similar to Should the connection use SSL. This currently has no effect. /// public static string Description_UseSSL { get { return ResourceManager.GetString("Description_UseSSL", resourceCulture); } } /// /// Looks up a localized string similar to Logs inefficient database operations. /// public static string Description_UseUsage { get { return ResourceManager.GetString("Description_UseUsage", resourceCulture); } } /// /// Looks up a localized string similar to Indicates how to treat a view in SQL statements. /// public static string Description_View_Algorithm { get { return ResourceManager.GetString("Description_View_Algorithm", resourceCulture); } } /// /// Looks up a localized string similar to Check option. /// public static string Description_View_CheckOption { get { return ResourceManager.GetString("Description_View_CheckOption", resourceCulture); } } /// /// Looks up a localized string similar to Definition of the view. /// public static string Description_View_Definition { get { return ResourceManager.GetString("Description_View_Definition", resourceCulture); } } /// /// Looks up a localized string similar to Indicates if the table or view is updatable. /// public static string Description_View_IsUpdatable { get { return ResourceManager.GetString("Description_View_IsUpdatable", resourceCulture); } } /// /// Looks up a localized string similar to Allow Batch. /// public static string DisplayName_AllowBatch { get { return ResourceManager.GetString("DisplayName_AllowBatch", resourceCulture); } } /// /// Looks up a localized string similar to Allow Zero DateTime. /// public static string DisplayName_AllowZero { get { return ResourceManager.GetString("DisplayName_AllowZero", resourceCulture); } } /// /// Looks up a localized string similar to Procedure Cache Size. /// public static string DisplayName_CacheSize { get { return ResourceManager.GetString("DisplayName_CacheSize", resourceCulture); } } /// /// Looks up a localized string similar to Character Set. /// public static string DisplayName_CharacterSet { get { return ResourceManager.GetString("DisplayName_CharacterSet", resourceCulture); } } /// /// Looks up a localized string similar to Column Key. /// public static string DisplayName_Column_ColumnKey { get { return ResourceManager.GetString("DisplayName_Column_ColumnKey", resourceCulture); } } /// /// Looks up a localized string similar to Default Value. /// public static string DisplayName_Column_Default { get { return ResourceManager.GetString("DisplayName_Column_Default", resourceCulture); } } /// /// Looks up a localized string similar to Extra. /// public static string DisplayName_Column_Extra { get { return ResourceManager.GetString("DisplayName_Column_Extra", resourceCulture); } } /// /// Looks up a localized string similar to Is Nullable. /// public static string DisplayName_Column_Nullable { get { return ResourceManager.GetString("DisplayName_Column_Nullable", resourceCulture); } } /// /// Looks up a localized string similar to Octet Length. /// public static string DisplayName_Column_OctetLength { get { return ResourceManager.GetString("DisplayName_Column_OctetLength", resourceCulture); } } /// /// Looks up a localized string similar to Ordinal. /// public static string DisplayName_Column_Ordinal { get { return ResourceManager.GetString("DisplayName_Column_Ordinal", resourceCulture); } } /// /// Looks up a localized string similar to Privileges. /// public static string DisplayName_Column_Privileges { get { return ResourceManager.GetString("DisplayName_Column_Privileges", resourceCulture); } } /// /// Looks up a localized string similar to SQL Type. /// public static string DisplayName_Column_SqlType { get { return ResourceManager.GetString("DisplayName_Column_SqlType", resourceCulture); } } /// /// Looks up a localized string similar to Use Compression. /// public static string DisplayName_Compression { get { return ResourceManager.GetString("DisplayName_Compression", resourceCulture); } } /// /// Looks up a localized string similar to Connection Reset. /// public static string DisplayName_ConnReset { get { return ResourceManager.GetString("DisplayName_ConnReset", resourceCulture); } } /// /// Looks up a localized string similar to Convert Zero Datetime. /// public static string DisplayName_ConvertZero { get { return ResourceManager.GetString("DisplayName_ConvertZero", resourceCulture); } } /// /// Looks up a localized string similar to Default Schema. /// public static string DisplayName_Database { get { return ResourceManager.GetString("DisplayName_Database", resourceCulture); } } /// /// Looks up a localized string similar to Driver Type. /// public static string DisplayName_DriverType { get { return ResourceManager.GetString("DisplayName_DriverType", resourceCulture); } } /// /// Looks up a localized string similar to Load Balance Timeout. /// public static string DisplayName_LifeTime { get { return ResourceManager.GetString("DisplayName_LifeTime", resourceCulture); } } /// /// Looks up a localized string similar to Logging. /// public static string DisplayName_Logging { get { return ResourceManager.GetString("DisplayName_Logging", resourceCulture); } } /// /// Looks up a localized string similar to Max Pool Size. /// public static string DisplayName_MaxPoolSize { get { return ResourceManager.GetString("DisplayName_MaxPoolSize", resourceCulture); } } /// /// Looks up a localized string similar to Min Pool Size. /// public static string DisplayName_MinPoolSize { get { return ResourceManager.GetString("DisplayName_MinPoolSize", resourceCulture); } } /// /// Looks up a localized string similar to Character Set. /// public static string DisplayName_Object_CharacterSet { get { return ResourceManager.GetString("DisplayName_Object_CharacterSet", resourceCulture); } } /// /// Looks up a localized string similar to Collation. /// public static string DisplayName_Object_Collation { get { return ResourceManager.GetString("DisplayName_Object_Collation", resourceCulture); } } /// /// Looks up a localized string similar to Comment. /// public static string DisplayName_Object_Comment { get { return ResourceManager.GetString("DisplayName_Object_Comment", resourceCulture); } } /// /// Looks up a localized string similar to Creation date. /// public static string DisplayName_Object_CreateDateTime { get { return ResourceManager.GetString("DisplayName_Object_CreateDateTime", resourceCulture); } } /// /// Looks up a localized string similar to Creation Time. /// public static string DisplayName_Object_CreationTime { get { return ResourceManager.GetString("DisplayName_Object_CreationTime", resourceCulture); } } /// /// Looks up a localized string similar to Catalog. /// public static string DisplayName_Object_Database { get { return ResourceManager.GetString("DisplayName_Object_Database", resourceCulture); } } /// /// Looks up a localized string similar to Definer. /// public static string DisplayName_Object_Definer { get { return ResourceManager.GetString("DisplayName_Object_Definer", resourceCulture); } } /// /// Looks up a localized string similar to Flags. /// public static string DisplayName_Object_Flags { get { return ResourceManager.GetString("DisplayName_Object_Flags", resourceCulture); } } /// /// Looks up a localized string similar to Length. /// public static string DisplayName_Object_Length { get { return ResourceManager.GetString("DisplayName_Object_Length", resourceCulture); } } /// /// Looks up a localized string similar to SQL Mode. /// public static string DisplayName_Object_Mode { get { return ResourceManager.GetString("DisplayName_Object_Mode", resourceCulture); } } /// /// Looks up a localized string similar to Native Type. /// public static string DisplayName_Object_MySqlType { get { return ResourceManager.GetString("DisplayName_Object_MySqlType", resourceCulture); } } /// /// Looks up a localized string similar to Name. /// public static string DisplayName_Object_Name { get { return ResourceManager.GetString("DisplayName_Object_Name", resourceCulture); } } /// /// Looks up a localized string similar to Precision. /// public static string DisplayName_Object_Precision { get { return ResourceManager.GetString("DisplayName_Object_Precision", resourceCulture); } } /// /// Looks up a localized string similar to Scale. /// public static string DisplayName_Object_Scale { get { return ResourceManager.GetString("DisplayName_Object_Scale", resourceCulture); } } /// /// Looks up a localized string similar to Schema. /// public static string DisplayName_Object_Schema { get { return ResourceManager.GetString("DisplayName_Object_Schema", resourceCulture); } } /// /// Looks up a localized string similar to Security Type. /// public static string DisplayName_Object_SecurityType { get { return ResourceManager.GetString("DisplayName_Object_SecurityType", resourceCulture); } } /// /// Looks up a localized string similar to Server. /// public static string DisplayName_Object_Server { get { return ResourceManager.GetString("DisplayName_Object_Server", resourceCulture); } } /// /// Looks up a localized string similar to Table. /// public static string DisplayName_Object_Table { get { return ResourceManager.GetString("DisplayName_Object_Table", resourceCulture); } } /// /// Looks up a localized string similar to View. /// public static string DisplayName_Object_View { get { return ResourceManager.GetString("DisplayName_Object_View", resourceCulture); } } /// /// Looks up a localized string similar to Option File. /// public static string DisplayName_OptionFile { get { return ResourceManager.GetString("DisplayName_OptionFile", resourceCulture); } } /// /// Looks up a localized string similar to Is Return Value. /// public static string DisplayName_Parameter_IsResult { get { return ResourceManager.GetString("DisplayName_Parameter_IsResult", resourceCulture); } } /// /// Looks up a localized string similar to Direction. /// public static string DisplayName_Parameter_Mode { get { return ResourceManager.GetString("DisplayName_Parameter_Mode", resourceCulture); } } /// /// Looks up a localized string similar to Ordinal. /// public static string DisplayName_Parameter_Ordinal { get { return ResourceManager.GetString("DisplayName_Parameter_Ordinal", resourceCulture); } } /// /// Looks up a localized string similar to Stored Procedure. /// public static string DisplayName_Parameter_StoredProcedure { get { return ResourceManager.GetString("DisplayName_Parameter_StoredProcedure", resourceCulture); } } /// /// Looks up a localized string similar to Password. /// public static string DisplayName_Password { get { return ResourceManager.GetString("DisplayName_Password", resourceCulture); } } /// /// Looks up a localized string similar to Use Performance Monitor. /// public static string DisplayName_PerfMonitor { get { return ResourceManager.GetString("DisplayName_PerfMonitor", resourceCulture); } } /// /// Looks up a localized string similar to Persist Security Info. /// public static string DisplayName_Persist { get { return ResourceManager.GetString("DisplayName_Persist", resourceCulture); } } /// /// Looks up a localized string similar to Pipe Name. /// public static string DisplayName_PipeName { get { return ResourceManager.GetString("DisplayName_PipeName", resourceCulture); } } /// /// Looks up a localized string similar to Pooling. /// public static string DisplayName_Pooling { get { return ResourceManager.GetString("DisplayName_Pooling", resourceCulture); } } /// /// Looks up a localized string similar to Port. /// public static string DisplayName_Port { get { return ResourceManager.GetString("DisplayName_Port", resourceCulture); } } /// /// Looks up a localized string similar to Connection Protocol. /// public static string DisplayName_Protocol { get { return ResourceManager.GetString("DisplayName_Protocol", resourceCulture); } } /// /// Looks up a localized string similar to Returns. /// public static string DisplayName_Routine_Returns { get { return ResourceManager.GetString("DisplayName_Routine_Returns", resourceCulture); } } /// /// Looks up a localized string similar to Server Host. /// public static string DisplayName_Server { get { return ResourceManager.GetString("DisplayName_Server", resourceCulture); } } /// /// Looks up a localized string similar to Shared Memory Name. /// public static string DisplayName_SharedMemory { get { return ResourceManager.GetString("DisplayName_SharedMemory", resourceCulture); } } /// /// Looks up a localized string similar to Body. /// public static string DisplayName_StoredProcedure_Body { get { return ResourceManager.GetString("DisplayName_StoredProcedure_Body", resourceCulture); } } /// /// Looks up a localized string similar to Comment. /// public static string DisplayName_StoredProcedure_Comment { get { return ResourceManager.GetString("DisplayName_StoredProcedure_Comment", resourceCulture); } } /// /// Looks up a localized string similar to Data Access. /// public static string DisplayName_StoredProcedure_DataAccess { get { return ResourceManager.GetString("DisplayName_StoredProcedure_DataAccess", resourceCulture); } } /// /// Looks up a localized string similar to Definition. /// public static string DisplayName_StoredProcedure_Definition { get { return ResourceManager.GetString("DisplayName_StoredProcedure_Definition", resourceCulture); } } /// /// Looks up a localized string similar to ExternalLanguage. /// public static string DisplayName_StoredProcedure_ExternalLanguage { get { return ResourceManager.GetString("DisplayName_StoredProcedure_ExternalLanguage", resourceCulture); } } /// /// Looks up a localized string similar to External Name. /// public static string DisplayName_StoredProcedure_ExternalName { get { return ResourceManager.GetString("DisplayName_StoredProcedure_ExternalName", resourceCulture); } } /// /// Looks up a localized string similar to Is Deterministic. /// public static string DisplayName_StoredProcedure_IsDeterministic { get { return ResourceManager.GetString("DisplayName_StoredProcedure_IsDeterministic", resourceCulture); } } /// /// Looks up a localized string similar to Last Modified. /// public static string DisplayName_StoredProcedure_LastModified { get { return ResourceManager.GetString("DisplayName_StoredProcedure_LastModified", resourceCulture); } } /// /// Looks up a localized string similar to Parameter List. /// public static string DisplayName_StoredProcedure_ParameterList { get { return ResourceManager.GetString("DisplayName_StoredProcedure_ParameterList", resourceCulture); } } /// /// Looks up a localized string similar to Parameter Style. /// public static string DisplayName_StoredProcedure_ParameterStyle { get { return ResourceManager.GetString("DisplayName_StoredProcedure_ParameterStyle", resourceCulture); } } /// /// Looks up a localized string similar to Specific Name. /// public static string DisplayName_StoredProcedure_SpecificName { get { return ResourceManager.GetString("DisplayName_StoredProcedure_SpecificName", resourceCulture); } } /// /// Looks up a localized string similar to SQL path. /// public static string DisplayName_StoredProcedure_SqlPath { get { return ResourceManager.GetString("DisplayName_StoredProcedure_SqlPath", resourceCulture); } } /// /// Looks up a localized string similar to Type. /// public static string DisplayName_StoredProcedure_Type { get { return ResourceManager.GetString("DisplayName_StoredProcedure_Type", resourceCulture); } } /// /// Looks up a localized string similar to Auto Increment. /// public static string DisplayName_Table_AutoIncrement { get { return ResourceManager.GetString("DisplayName_Table_AutoIncrement", resourceCulture); } } /// /// Looks up a localized string similar to Average Row Length. /// public static string DisplayName_Table_AverageRowLength { get { return ResourceManager.GetString("DisplayName_Table_AverageRowLength", resourceCulture); } } /// /// Looks up a localized string similar to Average Row Length. /// public static string DisplayName_Table_AverageRowLength_Option { get { return ResourceManager.GetString("DisplayName_Table_AverageRowLength_Option", resourceCulture); } } /// /// Looks up a localized string similar to Check date. /// public static string DisplayName_Table_CheckDateTime { get { return ResourceManager.GetString("DisplayName_Table_CheckDateTime", resourceCulture); } } /// /// Looks up a localized string similar to Checksum. /// public static string DisplayName_Table_Checksum { get { return ResourceManager.GetString("DisplayName_Table_Checksum", resourceCulture); } } /// /// Looks up a localized string similar to Checksum for Rows. /// public static string DisplayName_Table_Checksum_Option { get { return ResourceManager.GetString("DisplayName_Table_Checksum_Option", resourceCulture); } } /// /// Looks up a localized string similar to Connection. /// public static string DisplayName_Table_Connection_Option { get { return ResourceManager.GetString("DisplayName_Table_Connection_Option", resourceCulture); } } /// /// Looks up a localized string similar to Create Options. /// public static string DisplayName_Table_CreateOptions { get { return ResourceManager.GetString("DisplayName_Table_CreateOptions", resourceCulture); } } /// /// Looks up a localized string similar to Data Directory. /// public static string DisplayName_Table_DataDirectory_Option { get { return ResourceManager.GetString("DisplayName_Table_DataDirectory_Option", resourceCulture); } } /// /// Looks up a localized string similar to Data Free. /// public static string DisplayName_Table_DataFree { get { return ResourceManager.GetString("DisplayName_Table_DataFree", resourceCulture); } } /// /// Looks up a localized string similar to Data Length. /// public static string DisplayName_Table_DataLength { get { return ResourceManager.GetString("DisplayName_Table_DataLength", resourceCulture); } } /// /// Looks up a localized string similar to Delay Key Updates. /// public static string DisplayName_Table_DelayKeyWrite { get { return ResourceManager.GetString("DisplayName_Table_DelayKeyWrite", resourceCulture); } } /// /// Looks up a localized string similar to Engine. /// public static string DisplayName_Table_Engine { get { return ResourceManager.GetString("DisplayName_Table_Engine", resourceCulture); } } /// /// Looks up a localized string similar to Index Directory. /// public static string DisplayName_Table_IndexDirectory_Option { get { return ResourceManager.GetString("DisplayName_Table_IndexDirectory_Option", resourceCulture); } } /// /// Looks up a localized string similar to Index Length. /// public static string DisplayName_Table_IndexLength { get { return ResourceManager.GetString("DisplayName_Table_IndexLength", resourceCulture); } } /// /// Looks up a localized string similar to Insert Method. /// public static string DisplayName_Table_InsertMethod { get { return ResourceManager.GetString("DisplayName_Table_InsertMethod", resourceCulture); } } /// /// Looks up a localized string similar to Max Data Length. /// public static string DisplayName_Table_MaxDataLength { get { return ResourceManager.GetString("DisplayName_Table_MaxDataLength", resourceCulture); } } /// /// Looks up a localized string similar to Maximum Rows. /// public static string DisplayName_Table_MaxRows_Option { get { return ResourceManager.GetString("DisplayName_Table_MaxRows_Option", resourceCulture); } } /// /// Looks up a localized string similar to Minimum Rows. /// public static string DisplayName_Table_MinRows_Option { get { return ResourceManager.GetString("DisplayName_Table_MinRows_Option", resourceCulture); } } /// /// Looks up a localized string similar to Pack Keys. /// public static string DisplayName_Table_PackKeys { get { return ResourceManager.GetString("DisplayName_Table_PackKeys", resourceCulture); } } /// /// Looks up a localized string similar to Password. /// public static string DisplayName_Table_Password { get { return ResourceManager.GetString("DisplayName_Table_Password", resourceCulture); } } /// /// Looks up a localized string similar to Row Format. /// public static string DisplayName_Table_RowFormat { get { return ResourceManager.GetString("DisplayName_Table_RowFormat", resourceCulture); } } /// /// Looks up a localized string similar to Row Format. /// public static string DisplayName_Table_RowFormat_Option { get { return ResourceManager.GetString("DisplayName_Table_RowFormat_Option", resourceCulture); } } /// /// Looks up a localized string similar to Table rows. /// public static string DisplayName_Table_TableRows { get { return ResourceManager.GetString("DisplayName_Table_TableRows", resourceCulture); } } /// /// Looks up a localized string similar to Table type. /// public static string DisplayName_Table_Type { get { return ResourceManager.GetString("DisplayName_Table_Type", resourceCulture); } } /// /// Looks up a localized string similar to Union. /// public static string DisplayName_Table_Union { get { return ResourceManager.GetString("DisplayName_Table_Union", resourceCulture); } } /// /// Looks up a localized string similar to Update date. /// public static string DisplayName_Table_UpdateDateTime { get { return ResourceManager.GetString("DisplayName_Table_UpdateDateTime", resourceCulture); } } /// /// Looks up a localized string similar to Version. /// public static string DisplayName_Table_Version { get { return ResourceManager.GetString("DisplayName_Table_Version", resourceCulture); } } /// /// Looks up a localized string similar to Connect Timeout. /// public static string DisplayName_Timeout { get { return ResourceManager.GetString("DisplayName_Timeout", resourceCulture); } } /// /// Looks up a localized string similar to Condition. /// public static string DisplayName_Trigger_Condition { get { return ResourceManager.GetString("DisplayName_Trigger_Condition", resourceCulture); } } /// /// Looks up a localized string similar to Event Catalog. /// public static string DisplayName_Trigger_EventCatalog { get { return ResourceManager.GetString("DisplayName_Trigger_EventCatalog", resourceCulture); } } /// /// Looks up a localized string similar to Event Manipulation. /// public static string DisplayName_Trigger_EventManipulation { get { return ResourceManager.GetString("DisplayName_Trigger_EventManipulation", resourceCulture); } } /// /// Looks up a localized string similar to Event Schema. /// public static string DisplayName_Trigger_EventSchema { get { return ResourceManager.GetString("DisplayName_Trigger_EventSchema", resourceCulture); } } /// /// Looks up a localized string similar to Event Table. /// public static string DisplayName_Trigger_EventTable { get { return ResourceManager.GetString("DisplayName_Trigger_EventTable", resourceCulture); } } /// /// Looks up a localized string similar to Order. /// public static string DisplayName_Trigger_Order { get { return ResourceManager.GetString("DisplayName_Trigger_Order", resourceCulture); } } /// /// Looks up a localized string similar to Orientation. /// public static string DisplayName_Trigger_Orientation { get { return ResourceManager.GetString("DisplayName_Trigger_Orientation", resourceCulture); } } /// /// Looks up a localized string similar to Ref to New Row. /// public static string DisplayName_Trigger_RefToNewRow { get { return ResourceManager.GetString("DisplayName_Trigger_RefToNewRow", resourceCulture); } } /// /// Looks up a localized string similar to Ref to New Table. /// public static string DisplayName_Trigger_RefToNewTable { get { return ResourceManager.GetString("DisplayName_Trigger_RefToNewTable", resourceCulture); } } /// /// Looks up a localized string similar to Ref to Old Row. /// public static string DisplayName_Trigger_RefToOldRow { get { return ResourceManager.GetString("DisplayName_Trigger_RefToOldRow", resourceCulture); } } /// /// Looks up a localized string similar to Ref to Old Table. /// public static string DisplayName_Trigger_RefToOldTable { get { return ResourceManager.GetString("DisplayName_Trigger_RefToOldTable", resourceCulture); } } /// /// Looks up a localized string similar to Statement. /// public static string DisplayName_Trigger_Statement { get { return ResourceManager.GetString("DisplayName_Trigger_Statement", resourceCulture); } } /// /// Looks up a localized string similar to Timing. /// public static string DisplayName_Trigger_Timing { get { return ResourceManager.GetString("DisplayName_Trigger_Timing", resourceCulture); } } /// /// Looks up a localized string similar to Library. /// public static string DisplayName_UDF_Dll { get { return ResourceManager.GetString("DisplayName_UDF_Dll", resourceCulture); } } /// /// Looks up a localized string similar to Is Agregate. /// public static string DisplayName_UDF_IsAgregate { get { return ResourceManager.GetString("DisplayName_UDF_IsAgregate", resourceCulture); } } /// /// Looks up a localized string similar to Type. /// public static string DisplayName_UDF_Type { get { return ResourceManager.GetString("DisplayName_UDF_Type", resourceCulture); } } /// /// Looks up a localized string similar to Use Old Syntax. /// public static string DisplayName_UseOldSyntax { get { return ResourceManager.GetString("DisplayName_UseOldSyntax", resourceCulture); } } /// /// Looks up a localized string similar to Username. /// public static string DisplayName_UserID { get { return ResourceManager.GetString("DisplayName_UserID", resourceCulture); } } /// /// Looks up a localized string similar to Use SSL. /// public static string DisplayName_UseSSL { get { return ResourceManager.GetString("DisplayName_UseSSL", resourceCulture); } } /// /// Looks up a localized string similar to Use Usage Advisor. /// public static string DisplayName_UseUsage { get { return ResourceManager.GetString("DisplayName_UseUsage", resourceCulture); } } /// /// Looks up a localized string similar to Algorithm. /// public static string DisplayName_View_Algorithm { get { return ResourceManager.GetString("DisplayName_View_Algorithm", resourceCulture); } } /// /// Looks up a localized string similar to Check Option. /// public static string DisplayName_View_CheckOption { get { return ResourceManager.GetString("DisplayName_View_CheckOption", resourceCulture); } } /// /// Looks up a localized string similar to Definition. /// public static string DisplayName_View_Definition { get { return ResourceManager.GetString("DisplayName_View_Definition", resourceCulture); } } /// /// Looks up a localized string similar to Is Updatable. /// public static string DisplayName_View_IsUpdatable { get { return ResourceManager.GetString("DisplayName_View_IsUpdatable", resourceCulture); } } /// /// Looks up a localized string similar to Are you sure you want to drop the {0} '{1}'?. /// public static string DropConfirmation { get { return ResourceManager.GetString("DropConfirmation", resourceCulture); } } /// /// Looks up a localized string similar to Drop {0}?. /// public static string DropConfirmationCaption { get { return ResourceManager.GetString("DropConfirmationCaption", resourceCulture); } } /// /// Looks up a localized string similar to There was an error attempting to create the database '{0}'. /// public static string ErrorAttemptingToCreateDB { get { return ResourceManager.GetString("ErrorAttemptingToCreateDB", resourceCulture); } } /// /// Looks up a localized string similar to The following error occured while attempting to drop the {0} '{1}': {2}. /// public static string ErrorAttemptingToDrop { get { return ResourceManager.GetString("ErrorAttemptingToDrop", resourceCulture); } } /// /// Looks up a localized string similar to An error was encountered during loading.. /// public static string ErrorDuringLoad { get { return ResourceManager.GetString("ErrorDuringLoad", resourceCulture); } } /// /// Looks up a localized string similar to Error. /// public static string ErrorTitle { get { return ResourceManager.GetString("ErrorTitle", resourceCulture); } } /// /// Looks up a localized string similar to Both sides of a relationship must have the same number of columns.. /// public static string FKColumnsNotMatched { get { return ResourceManager.GetString("FKColumnsNotMatched", resourceCulture); } } /// /// Looks up a localized string similar to Expected column name.. /// public static string FKNeedColumn { get { return ResourceManager.GetString("FKNeedColumn", resourceCulture); } } public static System.Drawing.Bitmap Key { get { object obj = ResourceManager.GetObject("Key", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized string similar to Stored Functions. /// public static string Node_Functions { get { return ResourceManager.GetString("Node_Functions", resourceCulture); } } /// /// Looks up a localized string similar to Stored Procedures. /// public static string Node_StoredProcedures { get { return ResourceManager.GetString("Node_StoredProcedures", resourceCulture); } } /// /// Looks up a localized string similar to Tables. /// public static string Node_Tables { get { return ResourceManager.GetString("Node_Tables", resourceCulture); } } /// /// Looks up a localized string similar to Triggers. /// public static string Node_Triggers { get { return ResourceManager.GetString("Node_Triggers", resourceCulture); } } /// /// Looks up a localized string similar to UDFs. /// public static string Node_UDFs { get { return ResourceManager.GetString("Node_UDFs", resourceCulture); } } /// /// Looks up a localized string similar to Views. /// public static string Node_Views { get { return ResourceManager.GetString("Node_Views", resourceCulture); } } /// /// Looks up a localized string similar to Data design and management tools for MySQL. Copyright © 2007-2009 MySQL AB. /// public static string ProductDetails { get { return ResourceManager.GetString("ProductDetails", resourceCulture); } } /// /// Looks up a localized string similar to MySQL Connector/Net. /// public static string ProductName { get { return ResourceManager.GetString("ProductName", resourceCulture); } } /// /// Looks up a localized string similar to Use this selection to connect to MySQL Server using the .NET Framework Data Provider for MySQL. /// public static string Provider_Description { get { return ResourceManager.GetString("Provider_Description", resourceCulture); } } /// /// Looks up a localized string similar to .NET Framework Data Provider for MySQL. /// public static string Provider_DisplayName { get { return ResourceManager.GetString("Provider_DisplayName", resourceCulture); } } /// /// Looks up a localized string similar to MySQL Data Provider. /// public static string Provider_ShortDisplayName { get { return ResourceManager.GetString("Provider_ShortDisplayName", resourceCulture); } } public static System.Drawing.Bitmap sql_editor_banner { get { object obj = ResourceManager.GetObject("sql_editor_banner", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } public static System.Drawing.Bitmap sql_editor_connect { get { object obj = ResourceManager.GetObject("sql_editor_connect", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } public static System.Drawing.Bitmap sql_editor_disconnect { get { object obj = ResourceManager.GetObject("sql_editor_disconnect", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } public static System.Drawing.Bitmap sql_editor_executionplan { get { object obj = ResourceManager.GetObject("sql_editor_executionplan", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } public static System.Drawing.Bitmap sql_editor_runsql { get { object obj = ResourceManager.GetObject("sql_editor_runsql", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } public static System.Drawing.Bitmap sql_editor_validatesql { get { object obj = ResourceManager.GetObject("sql_editor_validatesql", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// /// Looks up a localized string similar to The starting auto-increment value for this table.. /// public static string TableAutoIncStartDesc { get { return ResourceManager.GetString("TableAutoIncStartDesc", resourceCulture); } } /// /// Looks up a localized string similar to The average row length for this table. Set this only for large tables with variable-size rows.. /// public static string TableAvgRowLengthDesc { get { return ResourceManager.GetString("TableAvgRowLengthDesc", resourceCulture); } } /// /// Looks up a localized string similar to The default character set to use for this table.. /// public static string TableCharSetDesc { get { return ResourceManager.GetString("TableCharSetDesc", resourceCulture); } } /// /// Looks up a localized string similar to Set to true if you want a live checksum maintained for this table.. /// public static string TableCheckSumDesc { get { return ResourceManager.GetString("TableCheckSumDesc", resourceCulture); } } /// /// Looks up a localized string similar to The default collation to use for this table.. /// public static string TableCollationDesc { get { return ResourceManager.GetString("TableCollationDesc", resourceCulture); } } /// /// Looks up a localized string similar to A comment for this table.. /// public static string TableCommentDesc { get { return ResourceManager.GetString("TableCommentDesc", resourceCulture); } } /// /// Looks up a localized string similar to The directory used to store the data files for this table.. /// public static string TableDataDirDesc { get { return ResourceManager.GetString("TableDataDirDesc", resourceCulture); } } /// /// Looks up a localized string similar to The storage engine to use.. /// public static string TableEngineDescription { get { return ResourceManager.GetString("TableEngineDescription", resourceCulture); } } /// /// Looks up a localized string similar to The directory used to store the index files for this table.. /// public static string TableIndexDirDesc { get { return ResourceManager.GetString("TableIndexDirDesc", resourceCulture); } } /// /// Looks up a localized string similar to Determines which table in a merge table receives updates.. /// public static string TableInsertMethodDesc { get { return ResourceManager.GetString("TableInsertMethodDesc", resourceCulture); } } /// /// Looks up a localized string similar to Provides a hint to the storage engine as to how many rows you plan to store in the table.. /// public static string TableMaxRowsDesc { get { return ResourceManager.GetString("TableMaxRowsDesc", resourceCulture); } } /// /// Looks up a localized string similar to The minimum number of rows you plan to store in the table.. /// public static string TableMinRowsDesc { get { return ResourceManager.GetString("TableMinRowsDesc", resourceCulture); } } /// /// Looks up a localized string similar to The name of this table.. /// public static string TableNameDesc { get { return ResourceManager.GetString("TableNameDesc", resourceCulture); } } /// /// Looks up a localized string similar to Determines if indexes are packed. This will slow down updates and inserts.. /// public static string TablePackKeysDesc { get { return ResourceManager.GetString("TablePackKeysDesc", resourceCulture); } } /// /// Looks up a localized string similar to Defines how the rows should be stored.. /// public static string TableRowFormatDesc { get { return ResourceManager.GetString("TableRowFormatDesc", resourceCulture); } } /// /// Looks up a localized string similar to The schema this table belongs to.. /// public static string TableSchemaDesc { get { return ResourceManager.GetString("TableSchemaDesc", resourceCulture); } } /// /// Looks up a localized string similar to Column. /// public static string Type_Column { get { return ResourceManager.GetString("Type_Column", resourceCulture); } } /// /// Looks up a localized string similar to Stored Function. /// public static string Type_StoredFunction { get { return ResourceManager.GetString("Type_StoredFunction", resourceCulture); } } /// /// Looks up a localized string similar to Stored Procedure. /// public static string Type_StoredProcedure { get { return ResourceManager.GetString("Type_StoredProcedure", resourceCulture); } } /// /// Looks up a localized string similar to Stored Procedure Parameter. /// public static string Type_StoredProcedureParameter { get { return ResourceManager.GetString("Type_StoredProcedureParameter", resourceCulture); } } /// /// Looks up a localized string similar to Table. /// public static string Type_Table { get { return ResourceManager.GetString("Type_Table", resourceCulture); } } /// /// Looks up a localized string similar to Trigger. /// public static string Type_Trigger { get { return ResourceManager.GetString("Type_Trigger", resourceCulture); } } /// /// Looks up a localized string similar to User-defined Function. /// public static string Type_UDF { get { return ResourceManager.GetString("Type_UDF", resourceCulture); } } /// /// Looks up a localized string similar to View. /// public static string Type_View { get { return ResourceManager.GetString("Type_View", resourceCulture); } } /// /// Looks up a localized string similar to Column. /// public static string Type_ViewColumn { get { return ResourceManager.GetString("Type_ViewColumn", resourceCulture); } } /// /// Looks up a localized string similar to Unable to execute the create script. SQL batch must begin with CREATE or ALTER.. /// public static string UnableToExecuteProcScript { get { return ResourceManager.GetString("UnableToExecuteProcScript", resourceCulture); } } /// /// Looks up a localized string similar to Unable to retrieve the list of databases. /// public static string UnableToRetrieveDatabaseList { get { return ResourceManager.GetString("UnableToRetrieveDatabaseList", resourceCulture); } } /// /// Looks up a localized string similar to The database '{0}' does not exist or you do not have permission to see it. /// ///Would you like to create it?. /// public static string UnknownDbPromptCreate { get { return ResourceManager.GetString("UnknownDbPromptCreate", resourceCulture); } } /// /// Looks up a localized string similar to decimal. /// public static string Value_Decimal { get { return ResourceManager.GetString("Value_Decimal", resourceCulture); } } /// /// Looks up a localized string similar to int. /// public static string Value_Int { get { return ResourceManager.GetString("Value_Int", resourceCulture); } } /// /// Looks up a localized string similar to real. /// public static string Value_Real { get { return ResourceManager.GetString("Value_Real", resourceCulture); } } /// /// Looks up a localized string similar to row. /// public static string Value_Row { get { return ResourceManager.GetString("Value_Row", resourceCulture); } } /// /// Looks up a localized string similar to string. /// public static string Value_String { get { return ResourceManager.GetString("Value_String", resourceCulture); } } /// /// Looks up a localized string similar to The connection string must not be empty.. /// public static string WebConfigConnStrNoEmpty { get { return ResourceManager.GetString("WebConfigConnStrNoEmpty", resourceCulture); } } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Properties/Resources.resx0000644000175000017500000014242111127003600030127 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Convert Zero Datetime SQL path to the routine For numeric data, the maximum number of decimal digits that can be stored in this database object. Pooling The position of this object in the parent database object definition. User-defined Function Connection Index Length Name of the shared memory object to use Ref to New Row Direction Column Key row The MySQL server IP or hostname. Body The default character set to use for this table. Indicates if the function is aggregate function. A comment for this table. Authentication The database user password. real The default schema name. Can be empty, but it is not recommended. An approximation of the average row length for the table. Set this value only for large tables with variable-size records. Catalog The database '{0}' does not exist or you do not have permission to see it. Would you like to create it? Schema Body of the routine Definer The minimum number of rows you plan to store in the table. An event on which the trigger is switched on External Name Should the connection ues compression The minimum number of connections allowed in the pool Ordinal SQL Mode The host name of the MySQL server which runs underlying database. Insert Method Option File Returns Row Format Condition of the trigger Unable to execute the create script. SQL batch must begin with CREATE or ALTER. The schema which owns the database object. Table If you want to insert data into a MERGE table, you must specify with INSERT_METHOD the table into which the row should be inserted. INSERT_METHOD is an option useful for MERGE tables only. Use a value of FIRST or LAST to have inserts go to the first or last table, or a value of NO to prevent inserts. Stored Functions Data Directory Are you sure you want to drop the {0} '{1}'? Driver Type The maximum length (in characters) that can be stored in this database object. Language of the body of the routine An action reference to an old row Should the connection use SSL. This currently has no effect Precision The collation that is used to compare text for the database object. Flags Base Library The row format used for the table. Ref to New Table The initial AUTO_INCREMENT value for the table. Only for MyISAM tables with a least one AUTO_INCREMENT column. The basename of the file containing the implementation of the function. Expected column name. By using this option you can specify where the MyISAM storage engine should put a table's index file. The directory must be the full pathname to the directory, not a relative path. Set this option if you want to delay key updates for the table until the table is closed. (MyISAM only.) Table rows Views The ANSI SQL type definition for the column. Indicates if the table or view is updatable Defines if the routine is deterministic Set to true if you want a live checksum maintained for this table. When true, the connection object is drawn from the appropriate pool, or if necessary, is created and added to the appropriate pool The database catalog which owns the database object. The starting auto-increment value for this table. The database user login name. Stored Function Version A table on which an action is performed Name Protocol to use for connection to MySQL A schema on which an action is performed Use this option to encrypt the .frm file with a password. This option does nothing in the standard MySQL version. Indicates if null values are allowed in this database object. Provides a hint to the storage engine as to how many rows you plan to store in the table. Parameter List The amount of rows in the table. True if you want to delay key updates until the table is closed. (MyISAM only) Definition Password The advanced options for the column. The directory used to store the data files for this table. H1PZDDC3CDP8CDKAH1HRAPE2ZQZECRQER1PEIKDCEKD9CMKPDKJZMKPZZIRHEIE2EQZHH9JTJED0ZDPTQ2I8RHJMCQRIZ1MDM9Q9Z1MZE8M2JQHTI1MCA2M3ZDRTEZAR By using this option you can specify where the MyISAM storage engine should put a table's data file. The directory must be the full pathname to the directory, not a relative path. Username Server The following error occured while attempting to drop the {0} '{1}': {2} UDFs Table type Use this selection to connect to MySQL Server using the .NET Framework Data Provider for MySQL Indicates how to treat a view in SQL statements Parameter Style Load Balance Timeout Checksum for Rows The average row length for this table. Set this only for large tables with variable-size rows. Event Table Triggers An error occurred that is normally caused by not having Connector/Net properly installed. SQL Type The schema this table belongs to. Column name missing for column definition. Column will be deleted. To correct, choose cancel and specify the name of the column. Indicates that performance counters should be updated during execution (Identifier) Minimum Rows Statement MySQL Data Provider Event Catalog decimal The average length for the rows in the table. Type of the routine (procedure or function) Comments ..\Resources\Key.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a Default Value Engine Allows the use of old style @ syntax for parameters The date and time when the database object was created. Error Checksum Native Type The data length for the table. Data design and management tools for MySQL. Copyright © 2007-2011 Oracle, Inc. Is Updatable Defines how the rows should be stored. For MyISAM tables, the option value can be FIXED or DYNAMIC for static or variable-length row format. myisampack sets the type to COMPRESSED. The maximum number of rows you plan to store in the table. This is not a hard limit, but rather a hint to the storage engine that the table must be able to store at least this many rows. The default character set that is used for the database object. Cannot alter trigger '{0}' on '{1}' because this trigger does not belong to this object. Specify the correct trigger name or the correct target object name. Ref to Old Table Row Format Determines which table in a merge table receives updates. The trigger action time Extra When true, indicates the connection state is reset when removed from the pool Use this option to generate smaller indices. This usually makes updates slower and reads faster. Setting it to DEFAULT tells the storage engine to only pack long CHAR/VARCHAR columns. Set this option if you want MySQL to maintain a live checksum for all rows (that is, a checksum that MySQL updates automatically as the table changes). This makes the table a little slower to update, but also makes it easier to find corrupted tables. The CHECKSUM TABLE statement reports the checksum. (MyISAM only.) Comment The brief description of the database object. Connection Protocol Union Parameter style of the routine Condition Shows if this parameter is the return value for the routine. Data Access Max Pool Size Event Schema An error was encountered during loading. The way this column participate table keys and indices. Security Allow Batch Trigger Enables output of diagnostic messages Return type of the routine Password Timing Should illegal datetime values be converted to DateTime.MinValue Security type of the object Determines if indexes are packed. This will slow down updates and inserts. Is Deterministic Definition of the view List of MyISAM tables that should be used by the MERGE table. Allows execution of multiple SQL commands in a single statement An action reference to an old table The default value used to initialize new row values for this column. The privileges for the column. Name of the file with startup options Allow Zero DateTime The stored procedure that owns this database object. Connection Reset Check option Privileges Both sides of a relationship must have the same number of columns. External name of the routine Default View The native MySQL type for the database object. List of parameters of the routine Octet Length Use SSL The minimum amount of time (in seconds) for this connection to live in the pool before being destroyed Update date Unable to retrieve the list of databases Data Type Data Free Pack Keys Last Modified Average Row Length Ref to Old Row A view owning this object Drop {0}? Connection Statistic A statement executed by the trigger The storage engine to use. Create Options Table ExternalLanguage MySQL Database An action reference to a new row The directory used to store the index files for this table. Character set this connection should use The flags used to modify data type of this database object. Orientation Port The table which owns the database object. Use Compression string Is Agregate There was an error attempting to create the database '{0}' Length Min Pool Size The type of the function. Server Host Procedure Cache Size The order number of the action Definition The checksum for the table. Scale Name of pipe to use when connecting with named pipes (Win32 only) The default collation to use for this table. Is Return Value Specific name of the routine The type of the table. Check date Pooling Comment Stored Procedure Use Performance Monitor The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error Character Set MySQL Connector/Net The name of this table. Collation The minimum number of rows you plan to store in the table. The storage engine version. Max Data Length A catalog on which an action is performed Delay Key Updates The date and time when the table was updated last time. Connect Timeout Auto Increment For numeric data, the maximum number of decimal digits that can be stored in this database object to the right of a decimal point. Logging Persist Security Info Column View Index Directory Average Row Length Creator of the object Type ..\Resources\package.ico;System.Drawing.Icon, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a An atomic object of a trigger action Is Nullable Advanced Creation Time The maximum length (in bytes) that can be stored in the column. Should be the same as Length, except for multi-byte character sets. Logs inefficient database operations The position of this object in the parent database object definition. View The maximum data length for the table. An action reference to a new table Should zero datetimes be supported Stored Procedures Indicates how many stored procedures can be cached at one time. A value of 0 effectively disables the procedure cache SQL path .NET Framework Data Provider for MySQL Ordinal Tables Data Length Specific Name Event Manipulation Pipe Name Use Old Syntax The options, used to create the table. The maximum number of connections allowed in the pool The direction of this parameter. The storage engine used for the table. The schema that owns the database object. Defines how the rows should be stored. The port to use when connecting with sockets Specifies the type of driver to use for this connection When false, security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state The connection string for a FEDERATED table. This option is available as of MySQL 5.0.13; before that, use a COMMENT option for the connection string. Creation date Character Set External language used to write the routine The date and time when the table was checked last time. Type Type of data access of the routine Stored Procedure Parameter Check Option The specified connection string is invalid. ..\Resources\ArrowKey.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a Time of the last modification of the routine The name of the database object. Stored Procedure Shared Memory Name Default Schema SQL Mode of the object Order Column The index length for the table. Maximum Rows Use Usage Advisor int Security Type Algorithm ..\Resources\bannrbmp.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a The connection string must not be empty. MySQL MySQL SQL Script MySQL Script MySQL SQL Script File (.mysql) ..\Resources\401.ico;System.Drawing.Icon, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a ..\Resources\sql_editor_banner.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a ..\Resources\sql_editor_connect.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a ..\Resources\sql_editor_disconnect.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a ..\Resources\sql_editor_runsql.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a ..\Resources\sql_editor_validatesql.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a ..\Resources\sql_editor_executionplan.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Properties/DataSources/0000755000175000017500000000000011127003600027463 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.VisualStudio/Properties/DataSources/TableNode.datasource0000644000175000017500000000114211127003600033372 0ustar directhexdirecthex MySql.Data.VisualStudio.TableNode, MySql.VisualStudio, Version=5.1.3.0, Culture=neutral, PublicKeyToken=null mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Properties/AssemblyInfo.cs0000644000175000017500000000404611127003600030174 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MySQL Tools for Visual Studio")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Oracle")] [assembly: AssemblyProduct("MySQL Tools for Visual Studio")] [assembly: AssemblyCopyright("Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5860AC5F-9DE5-4e2b-9FDA-D2AC4B1D6FA5")] [assembly: AssemblyKeyName("ConnectorNet")] mysql-connector-net-6.4.3/Source/MySql.VisualStudio/VSCTComponents/0000755000175000017500000000000011127003600025737 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.VisualStudio/VSCTComponents/pkgcmd.h0000644000175000017500000000457311127003600027366 0ustar directhexdirecthex////////////////////////////////////////////////////////////////////////// // // ////////////////////////////////////////////////////////////////////////// // pkgcmd.h : Menu commands defined for this Environment package // do not use #pragma once - it is used by ctc compiler #ifndef __PKGCMD_H_ #define __PKGCMD_H_ #define guidMySqlProviderPkg {79a115c9-b133-4891-9e7b-242509dad272} #define Group_Undefined {83285929-227c-11d3-b870-00c04f79f802} #define Pkg_Undefined {8328592a-227c-11d3-b870-00c04f79f802} #define guidVSData {4614107f-217d-4bbf-9dfe-b9e165c65572} #define IDG_DV_CONNECTION 0x4101 #define IDG_DV_GLOBAL1 0x4001 #define IDG_DV_OBJECT 0x4301 #define IDG_DV_STATIC 0x4401 #define guidMySqlProviderCmdSet {b87cb51f-8a01-4c5e-bf3e-5d0565d5397d} #define cmdidAddNewFunctionGlobal 0x01F7 #define cmdidAddNewProcedureGlobal 0x01F6 #define cmdidAddNewTableGlobal 0x01F4 #define cmdidAddNewUDFGlobal 0x01F8 #define cmdidAddNewViewGlobal 0x01F5 #define cmdidAlterProcedure 0x0121 #define cmdidAlterTrigger 0x0141 #define cmdidAlterView 0x0111 #define cmdidCreateFunction 0x0130 #define cmdidCreateProcedure 0x0120 #define cmdidCreateTable 0x0100 #define cmdidCreateTrigger 0x0140 #define cmdidCreateUDF 0x0150 #define cmdidCreateView 0x0110 #define cmdidDelete 0x0151 #define groupAddNew2005 0x03EA #define groupAddNew2008 0x03EB #define menuAddNew2005 0x03E8 #define menuAddNew2008 0x03E9 #define guidOfficeIcon {d309f794-903f-11d0-9efc-00a0c911004f} #define msotcidNoIcon 0x02EA #endif // __PKGCMD_H_ mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Nodes/0000755000175000017500000000000011127003600024162 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.VisualStudio/Nodes/StoredProcedureNode.cs0000644000175000017500000002234211127003600030433 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data.Common; using Microsoft.VisualStudio.Data; using System.Windows.Forms; using Microsoft.VisualStudio.TextManager.Interop; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Package; using Microsoft.VisualStudio.Shell.Interop; using System.Diagnostics; using OleInterop = Microsoft.VisualStudio.OLE.Interop; using System.Data; using MySql.Data.VisualStudio.Editors; using MySql.Data.VisualStudio.Properties; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace MySql.Data.VisualStudio { class StoredProcedureNode : DocumentNode, IVsTextBufferProvider { private string sql_mode; private bool isFunction; private VSCodeEditor editor; public StoredProcedureNode(DataViewHierarchyAccessor hierarchyAccessor, int id, bool isFunc) : base(hierarchyAccessor, id) { NodeId = isFunc ? "StoredFunction" : "StoredProcedure"; isFunction = isFunc; NameIndex = 3; editor = new VSCodeEditor((IOleServiceProvider)hierarchyAccessor.ServiceProvider); } #region Properties public override string SchemaCollection { get { return "procedures"; } } public override bool Dirty { get { return editor.Dirty; } protected set { editor.Dirty = value; } } private bool IsFunction { get { return NodeId.ToLowerInvariant() == "storedfunction"; } } #endregion public static void CreateNew(DataViewHierarchyAccessor HierarchyAccessor, bool isFunc) { StoredProcedureNode node = new StoredProcedureNode(HierarchyAccessor, 0, isFunc); node.Edit(); } public override object GetEditor() { return editor; } public override string GetDropSQL() { return GetDropSQL(Name); } public override string GetSaveSql() { return editor.Text; } private string GetDropSQL(string procName) { procName = procName.Trim('`'); return String.Format("DROP {0} `{1}`.`{2}`", IsFunction ? "FUNCTION" : "PROCEDURE", Database, procName); } private string GetNewRoutineText() { StringBuilder sb = new StringBuilder("CREATE "); sb.AppendFormat("{0} {1}\r\n", isFunction ? "FUNCTION" : "PROCEDURE", Name); sb.Append("/*\r\n(\r\n"); sb.Append("parameter1 INT\r\nOUT parameter2 datatype\r\n"); sb.Append(")\r\n*/\r\n"); if (isFunction) sb.Append("RETURNS /* datatype */\r\n"); sb.Append("BEGIN\r\n"); if (isFunction) sb.Append("RETURN /* return value */\r\n"); sb.Append("END"); return sb.ToString(); } protected override void Load() { if (IsNew) editor.Text = GetNewRoutineText(); else { try { string sql = GetStoredProcedureBody(String.Format( "SHOW CREATE {0} `{1}`.`{2}`", IsFunction ? "FUNCTION" : "PROCEDURE", Database, Name), out sql_mode); editor.Text = ChangeSqlTypeTo(sql, "ALTER"); Dirty = false; } catch (Exception ex) { MessageBox.Show("Unable to load the stored procedure for editing"); } } } private string GetStoredProcedureBody(string sql, out string sql_mode) { string body = null; DbConnection conn = (DbConnection)HierarchyAccessor.Connection.GetLockedProviderObject(); try { DbCommand cmd = MySqlProviderObjectFactory.Factory.CreateCommand(); cmd.Connection = conn; cmd.CommandText = sql; using (DbDataReader reader = cmd.ExecuteReader()) { reader.Read(); sql_mode = reader.GetString(1); body = reader.GetString(2); } return body; } finally { HierarchyAccessor.Connection.UnlockProviderObject(); } } /// /// We override save here so we can change the sql from create to alter on /// first save /// /// protected override bool Save() { // since MySQL doesn't support altering the body of a proc we have // to do some "magic" try { string sql = editor.Text.Trim(); if (!IsNew) { // first we need to check the syntax of our changes. THis will throw // an exception if the syntax is bad CheckSyntax(); sql = ChangeSqlTypeTo(editor.Text.Trim(), "CREATE"); ExecuteSQL(GetDropSQL(Name)); } ExecuteSQL(sql); return true; } catch (Exception ex) { MessageBox.Show(ex.Message, "MySQL", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } } private void CheckSyntax() { string sql = editor.Text.Trim(); sql = ChangeSqlTypeTo(sql, "CREATE"); try { ExecuteSQL(sql); sql = GetDropSQL(GetCurrentName()); ExecuteSQL(sql); } catch (Exception ex) { if (ex.Message.Contains("syntax")) throw; } } private string ChangeSqlTypeTo(string sql, string type) { int index = sql.IndexOf(' '); string startingCommand = sql.Substring(0, index).ToUpperInvariant(); if (startingCommand != "CREATE" && startingCommand != "ALTER") throw new Exception(Resources.UnableToExecuteProcScript); return type + sql.Substring(index); } protected override string GetCurrentName() { string sql = editor.Text.Trim(); string lowerSql = sql.ToLowerInvariant(); int pos = lowerSql.IndexOf("procedure") + 9; if (IsFunction) pos = lowerSql.IndexOf("function") + 8; int end = pos; while (++end < sql.Length) { if (lowerSql[end] == '(') break; if (Char.IsWhiteSpace(lowerSql[end])) break; } string procName = sql.Substring(pos, end - pos).Trim(); return procName.Trim('`'); } #region IVsTextBufferProvider Members private IVsTextLines buffer; int IVsTextBufferProvider.GetTextBuffer(out IVsTextLines ppTextBuffer) { if (buffer == null) { Type bufferType = typeof(IVsTextLines); Guid riid = bufferType.GUID; Guid clsid = typeof(VsTextBufferClass).GUID; buffer = (IVsTextLines)MySqlDataProviderPackage.Instance.CreateInstance( ref clsid, ref riid, typeof(object)); } ppTextBuffer = buffer; return VSConstants.S_OK; } int IVsTextBufferProvider.LockTextBuffer(int fLock) { return VSConstants.S_OK; } int IVsTextBufferProvider.SetTextBuffer(IVsTextLines pTextBuffer) { return VSConstants.S_OK; } #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Nodes/TriggerNode.cs0000644000175000017500000002346311127003600026732 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data.Common; using Microsoft.VisualStudio.Data; using System.Windows.Forms; using Microsoft.VisualStudio.TextManager.Interop; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Package; using Microsoft.VisualStudio.Shell.Interop; using System.Diagnostics; using OleInterop = Microsoft.VisualStudio.OLE.Interop; using System.Data; using MySql.Data.VisualStudio.Editors; using MySql.Data.VisualStudio.Properties; using MySql.Data.MySqlClient; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace MySql.Data.VisualStudio { class TriggerNode : DocumentNode, IVsTextBufferProvider { private string sql_mode; private VSCodeEditor editor; string table; public TriggerNode(DataViewHierarchyAccessor hierarchyAccessor, int id) : base(hierarchyAccessor, id) { NodeId = "Trigger"; NameIndex = 2; editor = new VSCodeEditor((IOleServiceProvider)hierarchyAccessor.ServiceProvider); } #region Properties public TableNode ParentTable; public override string SchemaCollection { get { return "triggers"; } } public override bool Dirty { get { return editor.Dirty; } protected set { editor.Dirty = value; } } #endregion public static void CreateNew(DataViewHierarchyAccessor HierarchyAccessor, TableNode parent) { TriggerNode node = new TriggerNode(HierarchyAccessor, 0); node.ParentTable = parent; node.Edit(); } public override object GetEditor() { return editor; } public override string GetDropSQL() { return GetDropSQL(Name); } public override string GetSaveSql() { return editor.Text; } private string GetDropSQL(string triggerName) { triggerName = triggerName.Trim('`'); return String.Format("DROP TRIGGER `{0}`.`{1}`", Database, triggerName); } private string GetNewTriggerText() { StringBuilder sb = new StringBuilder("CREATE TRIGGER "); sb.AppendFormat("{0}\r\n", Name); sb.AppendFormat("/* [BEFORE|AFTER] [INSERT|UPDATE|DELETE] */\r\n"); sb.AppendFormat("ON {0}\r\n", ParentTable.Name); sb.Append("FOR EACH ROW\r\n"); sb.Append("BEGIN\r\n"); sb.Append("/* sql commands go here */\r\n"); sb.Append("END"); return sb.ToString(); } protected override void Load() { if (IsNew) editor.Text = GetNewTriggerText(); else { try { DataTable dt = GetDataTable(String.Format("SHOW CREATE TRIGGER `{0}`.`{1}`", Database, Name)); sql_mode = dt.Rows[0][1] as string; string sql = dt.Rows[0][2] as string; byte[] bytes = UTF8Encoding.UTF8.GetBytes(sql); editor.Text = ChangeSqlTypeTo(sql, "ALTER"); Dirty = false; } catch (Exception ex) { MessageBox.Show("Unable to load object with error: " + ex.Message); } } table = GetTargetedTable(editor.Text); } /// /// We override save here so we can change the sql from create to alter on /// first save /// /// protected override bool Save() { try { string sql = editor.Text.Trim(); if (!IsNew) { MakeSureWeAreNotChangingTables(sql); // first we need to check the syntax of our changes. THis will throw // an exception if the syntax is bad CheckSyntax(); sql = ChangeSqlTypeTo(editor.Text.Trim(), "CREATE"); ExecuteSQL(GetDropSQL(Name)); } ExecuteSQL(sql); return true; } catch (Exception ex) { MessageBox.Show(ex.Message, "MySQL", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } } /// /// This method will attempt to extract the table this trigger script is targeting /// and make sure it matches the table the trigger was originally created for. We do /// this because we don't want the user using an 'ALTER' script to move a trigger to a /// different table /// private void MakeSureWeAreNotChangingTables(string sql) { string newTable = GetTargetedTable(sql); if (table != null && newTable != null && newTable.ToLowerInvariant() != table.ToLowerInvariant()) throw new InvalidOperationException( String.Format(Resources.AlterTriggerOnWrongTable, Name, newTable)); } private string GetTargetedTable(string sql) { MySqlTokenizer tokenizer = new MySqlTokenizer(sql); tokenizer.ReturnComments = false; tokenizer.AnsiQuotes = sql_mode.ToLowerInvariant().Contains("ansi_quotes"); tokenizer.BackslashEscapes = !sql_mode.ToLowerInvariant().Contains("no_backslash_escapes"); string token = null; while (token != "ON" || tokenizer.Quoted) token = tokenizer.NextToken(); string tableName = tokenizer.NextToken(); if (tokenizer.NextToken() == ".") tableName = tokenizer.NextToken(); if (tableName.StartsWith("`")) return tableName.Trim('`'); if (tableName.StartsWith("\"") && tokenizer.AnsiQuotes) return tableName.Trim('"'); return tableName; } private void CheckSyntax() { string sql = editor.Text.Trim(); sql = ChangeSqlTypeTo(sql, "CREATE"); try { ExecuteSQL(sql); sql = GetDropSQL(GetCurrentName()); ExecuteSQL(sql); } catch (Exception ex) { if (ex.Message.Contains("syntax")) throw; } } private string ChangeSqlTypeTo(string sql, string type) { int index = sql.IndexOf(' '); string startingCommand = sql.Substring(0, index).ToUpperInvariant(); if (startingCommand != "CREATE" && startingCommand != "ALTER") throw new Exception(Resources.UnableToExecuteProcScript); return type + sql.Substring(index); } protected override string GetCurrentName() { string sql = editor.Text.Trim(); string lowerSql = sql.ToLowerInvariant(); int pos = lowerSql.IndexOf("trigger") + 7; int end = pos; while (++end < sql.Length) { if (lowerSql[end] == '(') break; if (Char.IsWhiteSpace(lowerSql[end])) break; } string triggerName = sql.Substring(pos, end - pos).Trim(); return triggerName.Trim('`'); } #region IVsTextBufferProvider Members private IVsTextLines buffer; int IVsTextBufferProvider.GetTextBuffer(out IVsTextLines ppTextBuffer) { if (buffer == null) { Type bufferType = typeof(IVsTextLines); Guid riid = bufferType.GUID; Guid clsid = typeof(VsTextBufferClass).GUID; buffer = (IVsTextLines)MySqlDataProviderPackage.Instance.CreateInstance( ref clsid, ref riid, typeof(object)); } ppTextBuffer = buffer; return VSConstants.S_OK; } int IVsTextBufferProvider.LockTextBuffer(int fLock) { return VSConstants.S_OK; } int IVsTextBufferProvider.SetTextBuffer(IVsTextLines pTextBuffer) { return VSConstants.S_OK; } #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Nodes/BaseNode.cs0000644000175000017500000003466411127003600026206 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using MySql.Data.VisualStudio.Properties; using Microsoft.VisualStudio.Shell.Interop; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Data; using System.Diagnostics; using Microsoft.VisualStudio; using System.Data.Common; using System.Resources; using System.Globalization; using System.Data; using Microsoft.VisualStudio.Data.AdoDotNet; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.OLE.Interop; using MySql.Data.VisualStudio.Editors; using Microsoft.VisualStudio.Shell; namespace MySql.Data.VisualStudio { abstract class BaseNode { protected Guid editorGuid; protected Guid commandGroupGuid; protected string name; private static string defaultStorageEngine; public DataViewHierarchyAccessor HierarchyAccessor; public bool IsNew; public BaseNode(DataViewHierarchyAccessor hierarchyAccessor, int id) { HierarchyAccessor = hierarchyAccessor; ItemId = id; IsNew = ItemId == 0; // set the server and database from our active connection DbConnection conn = (DbConnection)HierarchyAccessor.Connection.GetLockedProviderObject(); Server = conn.DataSource; Database = conn.Database; HierarchyAccessor.Connection.UnlockProviderObject(); if (!IsNew) Name = hierarchyAccessor.GetNodeName(id); else ItemId = hierarchyAccessor.CreateObjectNode(); NameIndex = 2; commandGroupGuid = VSConstants.GUID_TextEditorFactory; editorGuid = Guid.Empty; } #region Properties public string Name { get { if (name == null) Name = GenerateUniqueName(); return name; } protected set { name = value; } } private int _itemId; public int ItemId { get { return _itemId; } protected set { _itemId = value; } } private string _nodeId; public string NodeId { get { return _nodeId; } protected set { _nodeId = value; } } private string _server; public string Server { get { return _server; } private set { _server = value; } } private string _database; public string Database { get { return _database; } private set { _database = value; } } private bool _dirty; public virtual bool Dirty { get { return _dirty; } protected set { _dirty = value; } } protected string Moniker { get { return String.Format("mysql://{0}/{1}/{2}", Server, Database, Name); } } private int _nameIndex; public int NameIndex { get { return _nameIndex; } protected set { _nameIndex = value; } } public virtual string SchemaCollection { get { return NodeId + "s"; } } public virtual string LocalizedTypeString { get { return Resources.ResourceManager.GetString("Type_" + NodeId); } } public string DefaultStorageEngine { get { if (defaultStorageEngine == null) { DataTable dt = GetDataTable("SHOW VARIABLES LIKE 'storage_engine'"); defaultStorageEngine = "MyISAM"; if (dt != null && dt.Rows.Count == 1) defaultStorageEngine = (string)dt.Rows[0][1]; } return defaultStorageEngine; } } #endregion #region Virtuals public virtual void ExecuteCommand(int command) { switch ((uint)command) { case 12291: // design case PkgCmdIDList.cmdAlterTable: case PkgCmdIDList.cmdAlterTrigger: case PkgCmdIDList.cmdAlterProcedure: case PkgCmdIDList.cmdAlterView: Alter(); break; case (uint)VSConstants.VSStd97CmdID.Delete: Drop(); break; } } public virtual void Edit() { if (!HierarchyAccessor.ActivateDocumentIfOpen(Moniker)) OpenEditor(); } public virtual object GetEditor() { throw new NotImplementedException(); } public virtual void Alter() { Edit(); } public virtual string GetDropSQL() { return String.Format("DROP {0} `{1}`.`{2}`", NodeId, Database, Name); } private void Drop() { string typeString = LocalizedTypeString.ToLower(CultureInfo.CurrentCulture); DialogResult result = MessageBox.Show(String.Format( Resources.DropConfirmation, typeString, Name), String.Format(Resources.DropConfirmationCaption, typeString), MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) throw new OperationCanceledException(); string sql = GetDropSQL(); try { ExecuteSQL(sql); // now we drop the node from the hierarchy HierarchyAccessor.DropObjectNode(ItemId); } catch (Exception ex) { MessageBox.Show( String.Format(Resources.ErrorAttemptingToDrop, LocalizedTypeString, Name, ex.Message), Resources.ErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error); } } protected virtual string GenerateUniqueName() { DbConnection conn = (DbConnection)HierarchyAccessor.Connection.GetLockedProviderObject(); string[] restrictions = new string[2] { null, Database }; try { DataTable dt = conn.GetSchema(SchemaCollection, restrictions); int uniqueIndex = 1; string objectName = String.Empty; foreach (DataRow row in dt.Rows) { objectName = String.Format("{0}{1}", NodeId, uniqueIndex).Replace(" ", ""); if (row[NameIndex].ToString().ToLowerInvariant() == objectName.ToLowerInvariant()) uniqueIndex++; } Name = String.Format("{0}{1}", NodeId, uniqueIndex).Replace(" ", ""); HierarchyAccessor.SetProperty(ItemId, (int)__VSHPROPID.VSHPROPID_Name, Name); return Name; } finally { HierarchyAccessor.Connection.UnlockProviderObject(); } } #endregion #region Private Methods private void OpenEditor() { IVsUIShellOpenDocument shell = MySqlDataProviderPackage.GetGlobalService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; IVsWindowFrame winFrame = null; object editor = GetEditor(); object coreEditor = editor; editorGuid = editor.GetType().GUID; if (editor is VSCodeEditor) coreEditor = (editor as VSCodeEditor).CodeWindow; IntPtr viewPunk = Marshal.GetIUnknownForObject(coreEditor); IntPtr dataPunk = Marshal.GetIUnknownForObject(this); Guid viewGuid = VSConstants.LOGVIEWID_TextView; // Initialize IDE editor infrastracture int result = shell.InitializeEditorInstance( (uint)0, // Initialization flags. We need default behavior here viewPunk, // View object reference (should implement IVsWindowPane) dataPunk, // Docuemnt object reference (should implement IVsPersistDocData) Moniker, // Document moniker ref editorGuid, // GUID of the editor type null, // Name of the physical view. We use default ref viewGuid, // GUID identifying the logical view. null, // Initial caption defined by the document owner. Will be initialized by the editor later null, // Initial caption defined by the document editor. Will be initialized by the editor later // Pointer to the IVsUIHierarchy interface of the project that contains the document HierarchyAccessor.Hierarchy, (uint)ItemId, // UI hierarchy item identifier of the document in the project system IntPtr.Zero, // Pointer to the IUnknown interface of the document data object if the document data object already exists in the running document table // Project-specific service provider. HierarchyAccessor.ServiceProvider as Microsoft.VisualStudio.OLE.Interop.IServiceProvider, ref commandGroupGuid, // Command UI GUID of the commands to display for this editor. out winFrame // The window frame that contains the editor ); Debug.Assert(winFrame != null && ErrorHandler.Succeeded(result), "Failed to initialize editor"); // if our editor is a text buffer then hook up our language service //if (editor is TextBufferEditor) //{ // // now we tell our text buffer what language service to use // Guid langSvcGuid = typeof(MySqlLanguageService).GUID; // (editor as TextBufferEditor).TextBuffer.SetLanguageServiceID(ref langSvcGuid); //} winFrame.Show(); } protected void SaveNode() { string nodePath = String.Format("/Connection/{0}s/{1}", NodeId, Name); HierarchyAccessor.SetNodePath(ItemId, nodePath); } protected void ExecuteSQL(string sql) { DbConnection conn = (DbConnection)HierarchyAccessor.Connection.GetLockedProviderObject(); try { DbCommand cmd = conn.CreateCommand(); cmd.CommandText = sql; cmd.ExecuteNonQuery(); } finally { HierarchyAccessor.Connection.UnlockProviderObject(); } } public DataTable GetSchema(string schemaName, string[] restrictions) { DbConnection conn = (DbConnection)HierarchyAccessor.Connection.GetLockedProviderObject(); try { return conn.GetSchema(schemaName, restrictions); } finally { HierarchyAccessor.Connection.UnlockProviderObject(); } } public DataTable GetDataTable(string sql) { DbConnection conn = (DbConnection)HierarchyAccessor.Connection.GetLockedProviderObject(); try { DbDataAdapter da = MySqlProviderObjectFactory.Factory.CreateDataAdapter(); DbCommand cmd = MySqlProviderObjectFactory.Factory.CreateCommand(); cmd.Connection = conn; cmd.CommandText = sql; da.SelectCommand = cmd; DataTable dt = new DataTable(); da.Fill(dt); return dt; } finally { HierarchyAccessor.Connection.UnlockProviderObject(); } } /// /// Selects connection node in the Server Explorer window. /// private void SelectConnectionNode() { //MySqlDataProviderPackage package = MySqlDataProviderPackage.Instance; // Extracts connection mamanger global service DataExplorerConnectionManager manager = Package.GetGlobalService(typeof(DataExplorerConnectionManager)) as DataExplorerConnectionManager; if (manager == null) { Debug.Fail("Failed to get connection manager!"); return; } // Searches for connection using connection string for current connection DataExplorerConnection connection = manager.FindConnection( Guids.Provider, HierarchyAccessor.Connection.EncryptedConnectionString, true); if (connection == null) { Debug.Fail("Failed to find proper connection node!"); return; } // Select connection node manager.SelectConnection(connection); } #endregion /// /// Refresh database node in server explorer /// public void Refresh() { SelectConnectionNode(); IVsUIHierarchy hier = HierarchyAccessor.Hierarchy as IVsUIHierarchy; Guid g = VSConstants.GUID_VSStandardCommandSet97; hier.ExecCommand(VSConstants.VSITEMID_ROOT, ref g, (uint)VSConstants.VSStd97CmdID.Refresh, (uint)OleCommandExecutionOption.DoDefault, IntPtr.Zero, IntPtr.Zero); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Nodes/DocumentNode.cs0000644000175000017500000001344111127003600027100 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Shell.Interop; using System.Diagnostics; using Microsoft.VisualStudio; using System.Data.Common; using System.Data; using Microsoft.VisualStudio.Data; using Microsoft.VisualStudio.TextManager.Interop; using System.Windows.Forms; using MySql.Data.VisualStudio.Properties; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Package; using MySql.Data.VisualStudio.Editors; using Microsoft.VisualStudio.Shell; namespace MySql.Data.VisualStudio { abstract class DocumentNode : BaseNode, IVsPersistDocData { public DocumentNode(DataViewHierarchyAccessor hierarchyAccessor, int id) : base(hierarchyAccessor, id) { } private uint DocumentCookie; protected abstract void Load(); public abstract string GetSaveSql(); protected abstract string GetCurrentName(); protected virtual bool Save() { ExecuteSQL(GetSaveSql()); return true; } #region IVsPersistDocData Members public int Close() { //throw new Exception("The method or operation is not implemented."); return VSConstants.S_OK; } public int GetGuidEditorType(out Guid pClassID) { throw new Exception("The method or operation is not implemented."); } public int IsDocDataDirty(out int pfDirty) { pfDirty = Dirty ? 1 : 0; return VSConstants.S_OK; } public int IsDocDataReloadable(out int pfReloadable) { throw new Exception("The method or operation is not implemented."); } public int LoadDocData(string pszMkDocument) { Debug.Assert(pszMkDocument == Moniker); Load(); OnDataLoaded(); return VSConstants.S_OK; } public int OnRegisterDocData(uint docCookie, IVsHierarchy pHierNew, uint itemidNew) { DocumentCookie = docCookie; Debug.Assert(HierarchyAccessor.Hierarchy == pHierNew, "Registration in wrong hierarchy"); return VSConstants.S_OK; } public int ReloadDocData(uint grfFlags) { throw new Exception("The method or operation is not implemented."); } public int RenameDocData(uint grfAttribs, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew) { return VSConstants.S_OK; } public int SaveDocData(VSSAVEFLAGS dwSave, out string pbstrMkDocumentNew, out int pfSaveCanceled) { string oldMoniker = Moniker; pfSaveCanceled = 1; pbstrMkDocumentNew = null; try { // Call out to the derived nodes to do the save work if (Save()) pfSaveCanceled = 0; } catch (Exception ex) { MessageBox.Show("Unable to save object with error: " + ex.Message); return VSConstants.S_OK; } if (pfSaveCanceled == 0) { // then mark the document has clean and unchanged Dirty = false; IsNew = false; //notify any listeners that our save is done OnDataSaved(); Name = GetCurrentName(); pbstrMkDocumentNew = String.Format("/Connection/{0}s/{1}", NodeId, Name); VsShellUtilities.RenameDocument(MySqlDataProviderPackage.Instance, oldMoniker, Moniker); // update server explorer Refresh(); Load(); } return VSConstants.S_OK; } public int SetUntitledDocPath(string pszDocDataPath) { throw new Exception("The method or operation is not implemented."); } #endregion #region Events public event EventHandler DataLoaded; public event EventHandler DataChanged; public event EventHandler DataSaved; private void OnDataLoaded() { if (DataLoaded != null) DataLoaded(this, null); } private void OnDataChanged() { if (DataChanged != null) DataChanged(this, null); } private void OnDataSaved() { if (DataSaved != null) DataSaved(this, null); } #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Nodes/UDFNode.cs0000644000175000017500000000464411127003600025745 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data.Common; using System.Data; using System.Collections.Generic; using Microsoft.VisualStudio.Data; using MySql.Data.VisualStudio.Editors; using System.Windows.Forms; namespace MySql.Data.VisualStudio { class UDFNode : BaseNode { public UDFNode(DataViewHierarchyAccessor hierarchyAccessor, int itemId) : base(hierarchyAccessor, itemId) { NodeId = "UDF"; } public override string GetDropSQL() { return String.Format("DROP FUNCTION `{0}`.`{1}`", Database, Name); } public static void CreateNew(DataViewHierarchyAccessor HierarchyAccessor) { UDFNode node = new UDFNode(HierarchyAccessor, 0); node.Edit(); } public override void Edit() { UDFEditor editor = new UDFEditor(); DialogResult result = editor.ShowDialog(); if (result == DialogResult.Cancel) return; string sql = "CREATE {0} FUNCTION {1} RETURNS {2} SONAME '{3}'"; sql = String.Format(sql, editor.Aggregate ? "AGGREGATE" : "", editor.FunctionName, editor.ReturnTypeByName, editor.LibraryName); Name = editor.FunctionName; ExecuteSQL(sql); SaveNode(); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Nodes/ViewNode.cs0000644000175000017500000001260211127003600026232 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Data; using MySql.Data.VisualStudio.Editors; using System.Data; using System.Windows.Forms; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace MySql.Data.VisualStudio { class ViewNode : DocumentNode, IVsTextBufferProvider { private VSCodeEditor editor = null; public ViewNode(DataViewHierarchyAccessor hierarchyAccessor, int id) : base(hierarchyAccessor, id) { NodeId = "View"; editor = new VSCodeEditor((IOleServiceProvider)hierarchyAccessor.ServiceProvider); } public static void CreateNew(DataViewHierarchyAccessor HierarchyAccessor) { ViewNode node = new ViewNode(HierarchyAccessor, 0); node.Edit(); } #region Properties public override string SchemaCollection { get { return "views"; } } public override bool Dirty { get { return editor.Dirty; } protected set { editor.Dirty = value; } } #endregion public override object GetEditor() { return editor; } private string GetNewViewText() { StringBuilder sb = new StringBuilder("CREATE VIEW "); sb.AppendFormat("{0}\r\n", Name); sb.Append("/*\r\n(column1, column2)\r\n*/\r\n"); sb.Append("AS /* select statement */\r\n"); return sb.ToString(); } protected override string GetCurrentName() { string sql = editor.Text.Trim(); string lowerSql = sql.ToLowerInvariant(); int pos = lowerSql.IndexOf("view") + 4; int end = pos; while (++end < sql.Length) { if (lowerSql[end] == '(') break; if (Char.IsWhiteSpace(lowerSql[end])) break; } string procName = sql.Substring(pos, end - pos).Trim(); return procName.Trim('`'); } protected override void Load() { if (IsNew) editor.Text = GetNewViewText(); else { try { string[] restrictions = new string[3]; restrictions[1] = Database; restrictions[2] = Name; DataTable views = this.GetSchema("Views", restrictions); if (views.Rows.Count != 1) throw new Exception(String.Format("There is no view with the name '{0}'", Name)); editor.Text = String.Format("ALTER VIEW `{0}` AS \r\n{1}", Name, views.Rows[0]["VIEW_DEFINITION"].ToString()); Dirty = false; } catch (Exception ex) { MessageBox.Show("Unable to load view with error: " + ex.Message); } } } public override string GetSaveSql() { return editor.Text; } #region IVsTextBufferProvider Members private IVsTextLines buffer; int IVsTextBufferProvider.GetTextBuffer(out IVsTextLines ppTextBuffer) { if (buffer == null) { Type bufferType = typeof(IVsTextLines); Guid riid = bufferType.GUID; Guid clsid = typeof(VsTextBufferClass).GUID; buffer = (IVsTextLines)MySqlDataProviderPackage.Instance.CreateInstance( ref clsid, ref riid, typeof(object)); } ppTextBuffer = buffer; return VSConstants.S_OK; } int IVsTextBufferProvider.LockTextBuffer(int fLock) { return VSConstants.S_OK; } int IVsTextBufferProvider.SetTextBuffer(IVsTextLines pTextBuffer) { return VSConstants.S_OK; } #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Nodes/TableNode.cs0000644000175000017500000001045211127003600026350 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data.Common; using System.Data; using System.Collections.Generic; using Microsoft.VisualStudio.Data; using MySql.Data.VisualStudio.DbObjects; using System.Text; using System.Windows.Forms; using MySql.Data.VisualStudio.Editors; using System.Diagnostics; using Microsoft.VisualStudio.Shell.Interop; namespace MySql.Data.VisualStudio { class TableNode : DocumentNode { private Table table; public TableNode(DataViewHierarchyAccessor hierarchyAccessor, int id) : base(hierarchyAccessor, id) { NodeId = "Table"; //commandGroupGuid = GuidList.DavinciCommandSet; } #region Properties public Table Table { get { return table; } } public override bool Dirty { get { if (table == null) return false; return table.HasChanges(); } } #endregion protected override string GetCurrentName() { return table.Name; } /// /// We override Save here because we want to prompt for a new name if this table is new and the user has /// not changed the default name /// /// protected override bool Save() { if (table.IsNew && table.Name == Name) { TableNamePromptDialog dlg = new TableNamePromptDialog(); dlg.TableName = table.Name; if (DialogResult.Cancel == dlg.ShowDialog()) return false; table.Name = dlg.TableName; } return base.Save(); } public static void CreateNew(DataViewHierarchyAccessor HierarchyAccessor) { TableNode node = new TableNode(HierarchyAccessor, 0); node.Edit(); } protected override void Load() { if (IsNew) { table = new Table(this, null, null); table.Name = Name; } else { DbConnection connection = (DbConnection)HierarchyAccessor.Connection.GetLockedProviderObject(); string[] restrictions = new string[4] { null, connection.Database, Name, null }; DataTable columnsTable = connection.GetSchema("Columns", restrictions); DataTable dt = connection.GetSchema("Tables", restrictions); table = new Table(this, dt.Rows[0], columnsTable); HierarchyAccessor.Connection.UnlockProviderObject(); } } public override string GetSaveSql() { return Table.GetSql(); } public override object GetEditor() { return new TableEditorPane(this); } public override void ExecuteCommand(int command) { if (command == PkgCmdIDList.cmdCreateTrigger) { TriggerNode.CreateNew(HierarchyAccessor, this); } else base.ExecuteCommand(command); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/0000755000175000017500000000000011127003600024523 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/UDFEditor.Designer.cs0000644000175000017500000001676011127003600030410 0ustar directhexdirecthexnamespace MySql.Data.VisualStudio.Editors { partial class UDFEditor { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.functionName = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.returnType = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.libraryName = new System.Windows.Forms.TextBox(); this.aggregate = new System.Windows.Forms.CheckBox(); this.SuspendLayout(); // // okButton // this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.Enabled = false; this.okButton.Location = new System.Drawing.Point(178, 116); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 4; this.okButton.Text = "OK"; this.okButton.UseVisualStyleBackColor = true; // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(259, 116); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 5; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(17, 15); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(38, 13); this.label1.TabIndex = 2; this.label1.Text = "Name:"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // functionName // this.functionName.Location = new System.Drawing.Point(61, 12); this.functionName.Name = "functionName"; this.functionName.Size = new System.Drawing.Size(273, 20); this.functionName.TabIndex = 0; this.functionName.TextChanged += new System.EventHandler(this.functionName_TextChanged); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(9, 43); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(47, 13); this.label2.TabIndex = 4; this.label2.Text = "Returns:"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // returnType // this.returnType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.returnType.FormattingEnabled = true; this.returnType.Items.AddRange(new object[] { "String", "Integer", "Real", "Decimal"}); this.returnType.Location = new System.Drawing.Point(62, 38); this.returnType.Name = "returnType"; this.returnType.Size = new System.Drawing.Size(123, 21); this.returnType.TabIndex = 1; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(14, 68); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(41, 13); this.label3.TabIndex = 6; this.label3.Text = "Library:"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // libraryName // this.libraryName.Location = new System.Drawing.Point(62, 65); this.libraryName.Name = "libraryName"; this.libraryName.Size = new System.Drawing.Size(272, 20); this.libraryName.TabIndex = 3; this.libraryName.TextChanged += new System.EventHandler(this.libraryName_TextChanged); // // aggregate // this.aggregate.AutoSize = true; this.aggregate.Location = new System.Drawing.Point(220, 42); this.aggregate.Name = "aggregate"; this.aggregate.Size = new System.Drawing.Size(75, 17); this.aggregate.TabIndex = 2; this.aggregate.Text = "Aggregate"; this.aggregate.UseVisualStyleBackColor = true; // // UDFEditor // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(342, 147); this.ControlBox = false; this.Controls.Add(this.aggregate); this.Controls.Add(this.libraryName); this.Controls.Add(this.label3); this.Controls.Add(this.returnType); this.Controls.Add(this.label2); this.Controls.Add(this.functionName); this.Controls.Add(this.label1); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "UDFEditor"; this.Padding = new System.Windows.Forms.Padding(5); this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Create New UDF"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox functionName; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox returnType; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox libraryName; private System.Windows.Forms.CheckBox aggregate; } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/IEditor.cs0000644000175000017500000000247211127003600026416 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; namespace MySql.Data.VisualStudio.Editors { interface IEditor { object GetObject(); } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/SqlEditorPane.cs0000644000175000017500000000433511127003600027571 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio; using System.Windows.Forms; namespace MySql.Data.VisualStudio.Editors { class SqlEditorPane : WindowPane//, IOleCommandTarget { private SqlEditor editor; public SqlEditorPane(ServiceProvider sp) : base(sp) { editor = new SqlEditor(sp); } public override IWin32Window Window { get { return editor; } } //#region IOleCommandTarget Members //int IOleCommandTarget.Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, // IntPtr pvaIn, IntPtr pvaOut) //{ // return base.Ex // return VSConstants.S_OK; //} //int IOleCommandTarget.QueryStatus(ref Guid pguidCmdGroup, uint cCmds, // OLECMD[] prgCmds, IntPtr pCmdText) //{ // return VSConstants.S_OK; //} //#endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/ServiceBroker.cs0000644000175000017500000001150611127003600027622 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio; using System.Runtime.InteropServices; using Microsoft.VisualStudio.OLE.Interop; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace MySql.Data.VisualStudio.Editors { internal class ServiceBroker { private IOleServiceProvider psp; private ServiceProvider site; public ServiceBroker(ServiceProvider site) { this.site = site; psp = (IOleServiceProvider)site.GetService(typeof(IOleServiceProvider).GUID); } public ServiceBroker(IOleServiceProvider psp) { site = null; this.psp = psp; } #region Common Interfaces public IOleServiceProvider IOleServiceProvider { get { return psp; } } public ILocalRegistry LocalRegistry { get { return OleService(typeof(SLocalRegistry)); } } public IVsRegisterPriorityCommandTarget VsRegisterPriorityCommandTarget { get { return OleService(typeof(SVsRegisterPriorityCommandTarget)); } } public IVsFilterKeys2 VsFilterKeys2 { get { return OleService(typeof(SVsFilterKeys)); } } #endregion /// /// Creates an object /// /// Establishes a locally-registered COM object relative to the local Visual Studio registry hive /// GUID if object to be created /// GUID assotiated with specified System.Type /// An object public object CreateObject(ILocalRegistry localRegistry, Guid clsid, Guid iid) { object objectInstance; IntPtr unknown = IntPtr.Zero; int hr = localRegistry.CreateInstance(clsid, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out unknown); if (hr != VSConstants.S_OK) { Marshal.ThrowExceptionForHR(hr); } try { objectInstance = Marshal.GetObjectForIUnknown(unknown); } finally { if (unknown != IntPtr.Zero) { Marshal.Release(unknown); } } // Try to site object instance IObjectWithSite objectWithSite = objectInstance as IObjectWithSite; if (objectWithSite != null) objectWithSite.SetSite(psp); return objectInstance; } private InterfaceType OleService(Type serviceType) where InterfaceType : class { Guid serviceGuid = serviceType.GUID; Guid interfaceGuid = typeof(InterfaceType).GUID; IntPtr unknown = IntPtr.Zero; InterfaceType service = null; int hr = psp.QueryService(ref serviceGuid, ref interfaceGuid, out unknown); if (hr != VSConstants.S_OK) Marshal.ThrowExceptionForHR(hr); try { service = (InterfaceType)Marshal.GetObjectForIUnknown(unknown); } finally { if (unknown != IntPtr.Zero) Marshal.Release(unknown); } return service; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/BaseEditorControl.cs0000644000175000017500000002421311127003600030436 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using System.IO; using System.Globalization; namespace MySql.Data.VisualStudio.Editors { public class BaseEditorControl : UserControl, IVsPersistDocData, IPersistFileFormat { private bool savingFile; private bool loadingFile; protected ServiceProvider serviceProvider; protected string fileName; #region IVsPersistDocData Members int IVsPersistDocData.Close() { return VSConstants.S_OK; } int IVsPersistDocData.GetGuidEditorType(out Guid pClassID) { throw new NotImplementedException(); } int IVsPersistDocData.IsDocDataDirty(out int pfDirty) { return ((IPersistFileFormat)this).IsDirty(out pfDirty); } int IVsPersistDocData.IsDocDataReloadable(out int pfReloadable) { pfReloadable = 1; return VSConstants.S_OK; } int IVsPersistDocData.LoadDocData(string pszMkDocument) { return ((IPersistFileFormat)this).Load(pszMkDocument, 0, 0); } int IVsPersistDocData.OnRegisterDocData(uint docCookie, IVsHierarchy pHierNew, uint itemidNew) { return VSConstants.S_OK; } int IVsPersistDocData.ReloadDocData(uint grfFlags) { return ((IPersistFileFormat)this).Load(null, grfFlags, 0); } int IVsPersistDocData.RenameDocData(uint grfAttribs, IVsHierarchy pHierNew, uint itemidNew, string pszMkDocumentNew) { fileName = pszMkDocumentNew; return VSConstants.S_OK; } private int QuerySave(out tagVSQuerySaveResult qsResult) { uint result; IVsQueryEditQuerySave2 querySave = (IVsQueryEditQuerySave2)serviceProvider.GetService(typeof(SVsQueryEditQuerySave)); int hr = querySave.QuerySaveFile(fileName, 0, null, out result); qsResult = (tagVSQuerySaveResult)result; return hr; } int IVsPersistDocData.SaveDocData(VSSAVEFLAGS dwSave, out string pbstrMkDocumentNew, out int pfSaveCanceled) { pbstrMkDocumentNew = null; pfSaveCanceled = 0; int hr; IVsUIShell uiShell = (IVsUIShell)serviceProvider.GetService(typeof(IVsUIShell)); switch (dwSave) { case VSSAVEFLAGS.VSSAVE_Save: case VSSAVEFLAGS.VSSAVE_SilentSave: { tagVSQuerySaveResult qsResult; hr = QuerySave(out qsResult); if (ErrorHandler.Failed(hr)) return hr; if (qsResult == tagVSQuerySaveResult.QSR_NoSave_Cancel) pfSaveCanceled = ~0; else if (qsResult == tagVSQuerySaveResult.QSR_SaveOK) { hr = uiShell.SaveDocDataToFile(dwSave, this, fileName, out pbstrMkDocumentNew, out pfSaveCanceled); if (ErrorHandler.Failed(hr)) return hr; } else if (qsResult == tagVSQuerySaveResult.QSR_ForceSaveAs) { hr = uiShell.SaveDocDataToFile(VSSAVEFLAGS.VSSAVE_SaveAs, this, fileName, out pbstrMkDocumentNew, out pfSaveCanceled); if (ErrorHandler.Failed(hr)) return hr; } break; } case VSSAVEFLAGS.VSSAVE_SaveAs: case VSSAVEFLAGS.VSSAVE_SaveCopyAs: { // --- Make sure the file name as the right extension if (String.Compare(".mysql", Path.GetExtension(fileName), true, CultureInfo.CurrentCulture) != 0) fileName += ".mysql"; // --- Call the shell to do the save for us hr = uiShell.SaveDocDataToFile(dwSave, this, fileName, out pbstrMkDocumentNew, out pfSaveCanceled); if (ErrorHandler.Failed(hr)) return hr; break; } default: throw new ArgumentException("Unable to save file"); } return VSConstants.S_OK; } int IVsPersistDocData.SetUntitledDocPath(string pszDocDataPath) { fileName = pszDocDataPath; return VSConstants.S_OK; } #endregion #region IPersistFileFormat Members int IPersistFileFormat.GetClassID(out Guid pClassID) { throw new NotImplementedException(); } int IPersistFileFormat.GetCurFile(out string ppszFilename, out uint pnFormatIndex) { ppszFilename = fileName; pnFormatIndex = 0; return VSConstants.S_OK; } int IPersistFileFormat.GetFormatList(out string ppszFormatList) { ppszFormatList = GetFileFormatList(); return VSConstants.S_OK; } int IPersistFileFormat.InitNew(uint nFormatIndex) { return VSConstants.S_OK; } int IPersistFileFormat.IsDirty(out int pfIsDirty) { pfIsDirty = IsDirty ? 1 : 0; return VSConstants.S_OK; } int IPersistFileFormat.Load(string pszFilename, uint grfMode, int fReadOnly) { // --- A valid file name is required. if ((pszFilename == null) && ((fileName == null) || (fileName.Length == 0))) throw new ArgumentNullException("pszFilename"); loadingFile = true; int hr = VSConstants.S_OK; try { // --- If the new file name is null, then this operation is a reload bool isReload = false; if (pszFilename == null) { isReload = true; } // --- Set the new file name if (!isReload) { fileName = pszFilename; } // --- Load the file LoadFile(fileName); IsDirty = false; // --- Notify the load or reload //NotifyDocChanged(); } finally { loadingFile = false; } return hr; } int IPersistFileFormat.Save(string pszFilename, int fRemember, uint nFormatIndex) { // --- switch into the NoScribble mode savingFile = true; try { // --- If file is null or same --> SAVE if (pszFilename == null || pszFilename == fileName) { SaveFile(fileName); IsDirty = false; } else { // --- If remember --> SaveAs if (fRemember != 0) { fileName = pszFilename; SaveFile(fileName); IsDirty = false; } else // --- Else, Save a Copy As { SaveFile(pszFilename); } } } finally { // --- Switch into the Normal mode savingFile = false; } return VSConstants.S_OK; } int IPersistFileFormat.SaveCompleted(string pszFilename) { if (savingFile) return VSConstants.S_FALSE; return VSConstants.S_OK; } #endregion #region IPersist Members public int GetClassID(out Guid pClassID) { throw new NotImplementedException(); } #endregion protected override void Dispose(bool disposing) { base.Dispose(disposing); } #region Virtuals protected virtual string GetFileFormatList() { return null; } protected virtual void SaveFile(string fileName) { } protected virtual void LoadFile(string fileName) { } protected virtual bool IsDirty { get { return true; } set {} } #endregion #region IPersist Members int IPersist.GetClassID(out Guid pClassID) { throw new NotImplementedException(); } #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/CustomPropertyDescriptor.cs0000644000175000017500000000504411127003600032133 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.ComponentModel; using System; using MySql.Data.VisualStudio.DbObjects; namespace MySql.Data.VisualStudio.Editors { class CustomPropertyDescriptor : PropertyDescriptor { private PropertyDescriptor myProp; private bool readOnly; public CustomPropertyDescriptor(PropertyDescriptor pd) : base(pd) { myProp = pd; } public override bool IsReadOnly { get { return readOnly; } } public void SetReadOnly(bool value) { readOnly = value; } public override bool CanResetValue(object component) { return true; } public override Type ComponentType { get { return typeof(Table); } } public override object GetValue(object component) { return myProp.GetValue(component); } public override System.Type PropertyType { get { return typeof(string); } } public override void ResetValue(object component) { } public override void SetValue(object component, object value) { myProp.SetValue(component, value); } public override bool ShouldSerializeValue(object component) { return false; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/TableEditor.resx0000644000175000017500000001435511127003600027634 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 True 17, 17 52 mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/VSCodeEditor.cs0000644000175000017500000001652411127003600027354 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell.Interop; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace MySql.Data.VisualStudio.Editors { internal class VSCodeEditor { private ServiceBroker services; private IVsCodeWindow codeWindow; private IntPtr parentHandle; private IntPtr hwnd; private bool noContent; private IVsTextBuffer textBuffer; public VSCodeEditor() { hwnd = IntPtr.Zero; parentHandle = IntPtr.Zero; } public VSCodeEditor(IntPtr parent, ServiceBroker services) : this() { parentHandle = parent; this.services = services; CreateCodeWindow(); } public VSCodeEditor(IOleServiceProvider psp) : this() { services = new ServiceBroker(psp); CreateCodeWindow(); } public IntPtr Hwnd { get { return hwnd; } } public IVsCodeWindow CodeWindow { get { return codeWindow; } } public bool Dirty { get { uint flags; textBuffer.GetStateFlags(out flags); return (flags & (uint)BUFFERSTATEFLAGS.BSF_MODIFIED) != 0; } set { uint flags; textBuffer.GetStateFlags(out flags); if (value) flags |= (uint)BUFFERSTATEFLAGS.BSF_MODIFIED; else flags &= ~(uint)BUFFERSTATEFLAGS.BSF_MODIFIED; textBuffer.SetStateFlags(flags); } } public string Text { get { IVsTextLines lines = (IVsTextLines)textBuffer; int lineCount, lineLength; string text; lines.GetLineCount(out lineCount); lines.GetLengthOfLine(lineCount - 1, out lineLength); lines.GetLineText(0, 0, lineCount - 1, lineLength, out text); return text; } set { if (noContent) Initialize(value); else Replace(value); noContent = false; } } private void Initialize(string value) { IVsTextLines lines = (IVsTextLines)textBuffer; lines.InitializeContent(value, value.Length); } private void Replace(string value) { int endLine, endCol; IVsTextLines lines = (IVsTextLines)textBuffer; lines.GetLastLineIndex(out endLine, out endCol); IntPtr pText = Marshal.StringToCoTaskMemAuto(value); try { lines.ReplaceLines(0, 0, endLine, endCol, pText, value.Length, null); } finally { Marshal.FreeCoTaskMem(pText); } } private void CreateCodeWindow() { // create code window Guid guidVsCodeWindow = typeof(VsCodeWindowClass).GUID; codeWindow = services.CreateObject(services.LocalRegistry, guidVsCodeWindow, typeof(IVsCodeWindow).GUID) as IVsCodeWindow; CustomizeCodeWindow(); // set buffer Guid guidVsTextBuffer = typeof(VsTextBufferClass).GUID; textBuffer = services.CreateObject(services.LocalRegistry, guidVsTextBuffer, typeof(IVsTextBuffer).GUID) as IVsTextBuffer; textBuffer.InitializeContent("ed", 2); Guid langSvc = new Guid("{fa498a2d-116a-4f25-9b55-7938e8e6dda7}"); int hr = textBuffer.SetLanguageServiceID(ref langSvc); if (hr != VSConstants.S_OK) Marshal.ThrowExceptionForHR(hr); hr = codeWindow.SetBuffer(textBuffer as IVsTextLines); if (hr != VSConstants.S_OK) Marshal.ThrowExceptionForHR(hr); // this is necessary for the adapters to work in VS2010 Initialize(String.Empty); // create pane window IVsWindowPane windowPane = codeWindow as IVsWindowPane; hr = windowPane.SetSite(services.IOleServiceProvider); if (hr != VSConstants.S_OK) Marshal.ThrowExceptionForHR(hr); if (parentHandle != IntPtr.Zero) { hr = windowPane.CreatePaneWindow(parentHandle, 0, 0, 100, 100, out hwnd); if (hr != VSConstants.S_OK) Marshal.ThrowExceptionForHR(hr); } } private void CustomizeCodeWindow() { //// initialize code window //INITVIEW[] initView = new INITVIEW[1]; //initView[0].fSelectionMargin = 0; //initView[0].IndentStyle = vsIndentStyle.vsIndentStyleSmart; //initView[0].fWidgetMargin = 0; //initView[0].fVirtualSpace = 0; //initView[0].fDragDropMove = 1; //initView[0].fVisibleWhitespace = 0; //IVsCodeWindowEx codeWindowEx = codeWindow as IVsCodeWindowEx; //int hr = codeWindowEx.Initialize((uint)_codewindowbehaviorflags.CWB_DISABLEDROPDOWNBAR, // //(uint)_codewindowbehaviorflags.CWB_DISABLESPLITTER, // 0, null, null, // (int)TextViewInitFlags.VIF_SET_WIDGET_MARGIN | // (int)TextViewInitFlags.VIF_SET_SELECTION_MARGIN | // (int)TextViewInitFlags2.VIF_ACTIVEINMODALSTATE | // (int)TextViewInitFlags2.VIF_SUPPRESSBORDER | // (int)TextViewInitFlags2.VIF_SUPPRESS_STATUS_BAR_UPDATE | // (int)TextViewInitFlags2.VIF_SUPPRESSTRACKCHANGES, // initView); //if (hr != VSConstants.S_OK) // Marshal.ThrowExceptionForHR(hr); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/TableIndexDialog.Designer.cs0000644000175000017500000001313011127003600031746 0ustar directhexdirecthexnamespace MySql.Data.VisualStudio.Editors { partial class TableIndexDialog { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.indexList = new System.Windows.Forms.ListBox(); this.addButton = new System.Windows.Forms.Button(); this.deleteButton = new System.Windows.Forms.Button(); this.closeButton = new System.Windows.Forms.Button(); this.indexProps = new System.Windows.Forms.PropertyGrid(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(14, 10); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(208, 15); this.label1.TabIndex = 0; this.label1.Text = "Selected Primary/Unique Key or Index:"; // // indexList // this.indexList.FormattingEnabled = true; this.indexList.ItemHeight = 15; this.indexList.Location = new System.Drawing.Point(14, 36); this.indexList.Name = "indexList"; this.indexList.Size = new System.Drawing.Size(205, 304); this.indexList.TabIndex = 0; this.indexList.SelectedIndexChanged += new System.EventHandler(this.indexList_SelectedIndexChanged); // // addButton // this.addButton.Location = new System.Drawing.Point(14, 348); this.addButton.Name = "addButton"; this.addButton.Size = new System.Drawing.Size(99, 27); this.addButton.TabIndex = 5; this.addButton.Text = "Add"; this.addButton.UseVisualStyleBackColor = true; this.addButton.Click += new System.EventHandler(this.addButton_Click); // // deleteButton // this.deleteButton.Location = new System.Drawing.Point(120, 348); this.deleteButton.Name = "deleteButton"; this.deleteButton.Size = new System.Drawing.Size(99, 27); this.deleteButton.TabIndex = 6; this.deleteButton.Text = "Delete"; this.deleteButton.UseVisualStyleBackColor = true; this.deleteButton.Click += new System.EventHandler(this.deleteButton_Click); // // closeButton // this.closeButton.Location = new System.Drawing.Point(465, 348); this.closeButton.Name = "closeButton"; this.closeButton.Size = new System.Drawing.Size(99, 27); this.closeButton.TabIndex = 7; this.closeButton.Text = "Close"; this.closeButton.UseVisualStyleBackColor = true; this.closeButton.Click += new System.EventHandler(this.closeButton_Click); // // indexProps // this.indexProps.Location = new System.Drawing.Point(247, 36); this.indexProps.Name = "indexProps"; this.indexProps.Size = new System.Drawing.Size(317, 304); this.indexProps.TabIndex = 10; this.indexProps.ToolbarVisible = false; // // TableIndexDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(577, 387); this.Controls.Add(this.indexProps); this.Controls.Add(this.closeButton); this.Controls.Add(this.deleteButton); this.Controls.Add(this.addButton); this.Controls.Add(this.indexList); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "TableIndexDialog"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Indexes/Keys"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.ListBox indexList; private System.Windows.Forms.Button addButton; private System.Windows.Forms.Button deleteButton; private System.Windows.Forms.Button closeButton; private System.Windows.Forms.PropertyGrid indexProps; } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/VSCodeEditorUserControl.cs0000644000175000017500000000614711127003600031554 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Shell.Interop; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using Microsoft.VisualStudio.Shell; namespace MySql.Data.VisualStudio.Editors { internal class VSCodeEditorUserControl : UserControl { private VSCodeEditorWindow nativeWindow; public void Init(ServiceProvider serviceProvider) { ServiceBroker sb = new ServiceBroker(serviceProvider); nativeWindow = new VSCodeEditorWindow(sb, this); } protected override void Dispose(bool disposing) { try { if (!disposing) return; if (nativeWindow == null) return; nativeWindow.Dispose(); } finally { base.Dispose(disposing); } } public string Text { get { return nativeWindow.CoreEditor.Text; } set { nativeWindow.CoreEditor.Text = value; } } public bool IsDirty { get { return nativeWindow.CoreEditor.Dirty; } set { nativeWindow.CoreEditor.Dirty = value; } } protected override bool IsInputKey(Keys keyData) { // Since we process each pressed keystroke, the return value is always true. return true; } protected override void OnGotFocus(EventArgs e) { if (nativeWindow == null) return; nativeWindow.SetFocus(); } protected override void OnSizeChanged(EventArgs e) { if (nativeWindow == null) return; nativeWindow.SetWindowPos(ClientRectangle); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/IndexColumnEditorDialog.Designer.cs0000644000175000017500000001772511127003600033341 0ustar directhexdirecthexusing MySql.Data.VisualStudio.DbObjects; namespace MySql.Data.VisualStudio.Editors { partial class IndexColumnEditorDialog { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.label1 = new System.Windows.Forms.Label(); this.indexGrid = new System.Windows.Forms.DataGridView(); this.cancelButton = new System.Windows.Forms.Button(); this.okButton = new System.Windows.Forms.Button(); this.columnName = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.sortOrder = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.indexColumnBindingSource = new System.Windows.Forms.BindingSource(this.components); ((System.ComponentModel.ISupportInitialize)(this.indexGrid)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.indexColumnBindingSource)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(265, 15); this.label1.TabIndex = 0; this.label1.Text = "Specify the columns and sort order for this Index:"; // // indexGrid // this.indexGrid.AllowUserToResizeColumns = false; this.indexGrid.AllowUserToResizeRows = false; this.indexGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.indexGrid.AutoGenerateColumns = false; this.indexGrid.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.indexGrid.BackgroundColor = System.Drawing.SystemColors.Window; this.indexGrid.BorderStyle = System.Windows.Forms.BorderStyle.None; this.indexGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.indexGrid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.columnName, this.sortOrder}); this.indexGrid.DataSource = this.indexColumnBindingSource; this.indexGrid.GridColor = System.Drawing.SystemColors.ControlLight; this.indexGrid.Location = new System.Drawing.Point(12, 38); this.indexGrid.Name = "indexGrid"; this.indexGrid.RowHeadersVisible = false; this.indexGrid.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.indexGrid.Size = new System.Drawing.Size(515, 260); this.indexGrid.TabIndex = 1; this.indexGrid.CellValidating += new System.Windows.Forms.DataGridViewCellValidatingEventHandler(this.indexGrid_CellValidating); this.indexGrid.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.indexGrid_EditingControlShowing); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(440, 304); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(87, 28); this.cancelButton.TabIndex = 2; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; // // okButton // this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.Location = new System.Drawing.Point(347, 304); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(87, 28); this.okButton.TabIndex = 3; this.okButton.Text = "OK"; this.okButton.UseVisualStyleBackColor = true; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // columnName // this.columnName.DataPropertyName = "ColumnName"; this.columnName.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.ComboBox; this.columnName.DisplayStyleForCurrentCellOnly = true; this.columnName.HeaderText = "Column Name"; this.columnName.Name = "columnName"; // // sortOrder // this.sortOrder.DataPropertyName = "SortOrder"; this.sortOrder.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.ComboBox; this.sortOrder.DisplayStyleForCurrentCellOnly = true; this.sortOrder.HeaderText = "Sort Order"; this.sortOrder.Name = "sortOrder"; // // indexColumnBindingSource // this.indexColumnBindingSource.DataSource = typeof(MySql.Data.VisualStudio.Editors.IndexColumnGridRow); // // IndexColumnEditorDialog // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(539, 344); this.Controls.Add(this.okButton); this.Controls.Add(this.cancelButton); this.Controls.Add(this.indexGrid); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "IndexColumnEditorDialog"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Index Columns"; ((System.ComponentModel.ISupportInitialize)(this.indexGrid)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.indexColumnBindingSource)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.DataGridView indexGrid; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button okButton; private System.Windows.Forms.BindingSource indexColumnBindingSource; private System.Windows.Forms.DataGridViewComboBoxColumn columnName; private System.Windows.Forms.DataGridViewComboBoxColumn sortOrder; } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/TableNamePromptDialog.cs0000644000175000017500000001042211127003600031223 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Reflection; using System.Windows.Forms; namespace MySql.Data.VisualStudio.Editors { partial class TableNamePromptDialog : Form { public TableNamePromptDialog() { InitializeComponent(); } public string TableName { get { return tableName.Text; } set { tableName.Text = value; } } #region Assembly Attribute Accessors public string AssemblyTitle { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false); if (attributes.Length > 0) { AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0]; if (titleAttribute.Title != "") { return titleAttribute.Title; } } return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase); } } public string AssemblyVersion { get { return Assembly.GetExecutingAssembly().GetName().Version.ToString(); } } public string AssemblyDescription { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyDescriptionAttribute)attributes[0]).Description; } } public string AssemblyProduct { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyProductAttribute)attributes[0]).Product; } } public string AssemblyCopyright { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyCopyrightAttribute)attributes[0]).Copyright; } } public string AssemblyCompany { get { object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false); if (attributes.Length == 0) { return ""; } return ((AssemblyCompanyAttribute)attributes[0]).Company; } } #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/YesNoTypeConverter.cs0000644000175000017500000000637311127003600030652 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.ComponentModel; namespace MySql.Data.VisualStudio.Editors { public class YesNoTypeConverter : TypeConverter { public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value.GetType() == typeof(string)) { if (((string)value).ToLower() == "yes") return true; if (((string)value).ToLower() == "no") return false; throw new Exception("Values must be \"Yes\" or \"No\""); } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { return (((bool)value) ? "Yes" : "No"); } return base.ConvertTo(context, culture, value, destinationType); } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { bool[] bools = new bool[] { true, false }; System.ComponentModel.TypeConverter.StandardValuesCollection svc = new System.ComponentModel.TypeConverter.StandardValuesCollection(bools); return svc; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/UDFEditor.cs0000644000175000017500000000501211127003600026635 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace MySql.Data.VisualStudio.Editors { public partial class UDFEditor : Form { public UDFEditor() { InitializeComponent(); returnType.SelectedIndex = 0; } public bool Aggregate { get { return aggregate.Checked; } } public string FunctionName { get { return functionName.Text.Trim(); } } public string LibraryName { get { return libraryName.Text.Trim(); } } public int ReturnType { get { return returnType.SelectedIndex; } } public string ReturnTypeByName { get { return returnType.SelectedItem as string; } } private void functionName_TextChanged(object sender, EventArgs e) { UpdateOkButton(); } private void libraryName_TextChanged(object sender, EventArgs e) { UpdateOkButton(); } private void UpdateOkButton() { okButton.Enabled = functionName.Text.Trim().Length > 0 && libraryName.Text.Trim().Length > 0; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/ForeignKeyDialog.cs0000644000175000017500000002521111127003600030235 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using MySql.Data.VisualStudio.DbObjects; using System.Collections; using MySql.Data.VisualStudio.Properties; namespace MySql.Data.VisualStudio.Editors { partial class ForeignKeyDialog : Form { TableNode tableNode; List columnNames = new List(); List fkColumnNames = new List(); const string None = ""; public ForeignKeyDialog(TableNode node) { tableNode = node; Application.EnableVisualStyles(); InitializeComponent(); // create a list of all tables in this database DataTable dt = tableNode.GetDataTable( String.Format(@"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{0}' AND TABLE_NAME <> '{1}'", tableNode.Database, tableNode.Table.Name)); List tables = new List(); foreach (DataRow row in dt.Rows) tables.Add(row[0].ToString()); refTable.DataSource = tables; colGridColumn.HeaderText = tableNode.Table.Name; colGridColumn.Items.Add(None); foreach (Column c in tableNode.Table.Columns) { if (c.ColumnName == null) continue; columnNames.Add(c.ColumnName); colGridColumn.Items.Add(c.ColumnName); } foreignKeyBindingSource.DataSource = tableNode.Table.ForeignKeys; fkList.DataSource = foreignKeyBindingSource; } private void closeButton_Click(object sender, EventArgs e) { Close(); } private void addButton_Click(object sender, EventArgs e) { ForeignKey key = new ForeignKey(tableNode.Table, null); if (refTable.SelectedValue != null) { key.SetName(String.Format("FK_{0}_{1}", tableNode.Table.Name, refTable.SelectedValue), true); key.ReferencedTable = refTable.SelectedValue.ToString(); } foreignKeyBindingSource.Add(key); } private void deleteButton_Click(object sender, EventArgs e) { foreignKeyBindingSource.RemoveCurrent(); } private void refTable_SelectedIndexChanged(object sender, EventArgs e) { string refTableName = refTable.Items[refTable.SelectedIndex].ToString(); fkGridColumn.HeaderText = refTableName; //reset the items list for the fk column string sql = @"SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='{0}' AND TABLE_NAME='{1}'"; DataTable dt = tableNode.GetDataTable(String.Format(sql, tableNode.Database, refTableName)); fkColumnNames.Clear(); foreach (DataRow row in dt.Rows) fkColumnNames.Add(row[0].ToString()); fkGridColumn.Items.Clear(); fkGridColumn.Items.Add(None); foreach (string col in fkColumnNames) fkGridColumn.Items.Add(col); if (foreignKeyBindingSource.Current == null) return; // update the key name if it is not already finalized ForeignKey key = foreignKeyBindingSource.Current as ForeignKey; if (!key.NameSet) { string name = String.Format("FK_{0}_{1}", tableNode.Table.Name, refTableName); key.SetName(name, true); } } private void fkName_KeyPress(object sender, KeyPressEventArgs e) { ForeignKey key = foreignKeyBindingSource.Current as ForeignKey; key.NameSet = true; } private void columnGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { Type t = e.Control.GetType(); if (t != typeof(DataGridViewComboBoxEditingControl)) return; DataGridViewComboBoxEditingControl ec = e.Control as DataGridViewComboBoxEditingControl; ec.DrawMode = DrawMode.OwnerDrawFixed; ec.DrawItem += new DrawItemEventHandler(dropdown_DrawItem); // now update the items that should be seen in this control ec.Items.Clear(); ec.Items.Add(None); int index = columnGrid.CurrentCell.ColumnIndex; List cols = index == 0 ? columnNames : fkColumnNames; ForeignKey key = foreignKeyBindingSource.Current as ForeignKey; foreach (string s in cols) { bool alreadyUsed = false; if (s != (string)columnGrid.CurrentCell.Value) foreach (FKColumnPair pair in key.Columns) if ((index == 0 && pair.ReferencedColumn == s) || (index == 1 && pair.Column == s)) { alreadyUsed = true; break; } if (!alreadyUsed) ec.Items.Add(s); } int selIndex = ec.FindStringExact(columnGrid.CurrentCell.Value as string); if (selIndex > 0) ec.SelectedIndex = selIndex; } void dropdown_DrawItem(object sender, DrawItemEventArgs e) { MyComboBox.DrawComboBox(sender as ComboBox, e); } private void foreignKeyBindingSource_CurrentChanged(object sender, EventArgs e) { if (foreignKeyBindingSource.Current == null) { columnGrid.Rows.Clear(); return; } ForeignKey key = foreignKeyBindingSource.Current as ForeignKey; fkColumnsBindingSource.DataSource = key.Columns; } private void columnGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { int index = e.ColumnIndex; DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)columnGrid.Rows[e.RowIndex].Cells[e.ColumnIndex]; FKColumnPair pair = fkColumnsBindingSource.Current as FKColumnPair; string value = e.FormattedValue as string; if (value == None) { cell.Value = null; if (index == 0) pair.ReferencedColumn = null; else pair.Column = null; } else cell.Value = e.FormattedValue as string; } private void columnGrid_RowValidating(object sender, DataGridViewCellCancelEventArgs e) { int index = e.RowIndex; DataGridViewCell parentCell = columnGrid.Rows[e.RowIndex].Cells[0]; DataGridViewCell childCell = columnGrid.Rows[e.RowIndex].Cells[1]; string parent = parentCell.Value as string; string child = childCell.Value as string; bool bad = false; parentCell.ErrorText = childCell.ErrorText = null; if ((String.IsNullOrEmpty(parent) || parent == None) && (!String.IsNullOrEmpty(child) && child != None)) { parentCell.ErrorText = Resources.FKNeedColumn; bad = true; } else if ((String.IsNullOrEmpty(child) || child == None) && (!String.IsNullOrEmpty(parent) && parent != None)) { childCell.ErrorText = Resources.FKNeedColumn; bad = true; } if (bad) { MessageBox.Show(Resources.FKColumnsNotMatched, null, MessageBoxButtons.OK, MessageBoxIcon.Information); e.Cancel = true; return; } FKColumnPair pair = fkColumnsBindingSource.Current as FKColumnPair; pair.Column = parent; pair.ReferencedColumn = child; fkColumnsBindingSource.EndEdit(); } private void columnGrid_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) { FKColumnPair pair = fkColumnsBindingSource[ e.RowIndex ] as FKColumnPair; switch( e.ColumnIndex ) { case 0: e.Value = pair.Column; break; case 1: e.Value = pair.ReferencedColumn; break; } } private void columnGrid_CellValuePushed(object sender, DataGridViewCellValueEventArgs e) { FKColumnPair fk; if ((e.RowIndex == columnGrid.Rows.Count - 1) && (columnGrid.Rows.Count > fkColumnsBindingSource.Count)) { fk = new FKColumnPair() { Column = "", ReferencedColumn = "" }; fkColumnsBindingSource.Add( fk ); } else { fk = (fkColumnsBindingSource[e.RowIndex] as FKColumnPair); } switch (e.ColumnIndex) { case 0: fk.Column = (string)e.Value; break; case 1: fk.ReferencedColumn = (string)e.Value; break; } } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/IndexColumnEditorDialog.cs0000644000175000017500000001670111127003600031573 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Windows.Forms; using System.Drawing.Design; using MySql.Data.VisualStudio.DbObjects; using System.Collections.Generic; using System.ComponentModel; namespace MySql.Data.VisualStudio.Editors { internal partial class IndexColumnEditorDialog : Form { private Table table; private List indexColumns; private List gridRows = new List(); private List columnNames = new List(); public IndexColumnEditorDialog(List ic) { table = ic[0].OwningIndex.Table; indexColumns = ic; InitializeComponent(); foreach (Column c in table.Columns) { if (!String.IsNullOrEmpty(c.ColumnName)) columnNames.Add(c.ColumnName); } for (int i=0; i < indexColumns.Count; i++) { IndexColumnGridRow row = new IndexColumnGridRow(); row.ColumnName = indexColumns[i].ColumnName; row.SortOrder = indexColumns[i].SortOrder.ToString(); gridRows.Add(row); } columnName.Items.Add(""); columnName.Items.AddRange((object[])columnNames.ToArray()); sortOrder.Items.Add("Ascending"); sortOrder.Items.Add("Descending"); indexColumnBindingSource.DataSource = gridRows; } private void indexGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { Type t = e.Control.GetType(); if (t != typeof(DataGridViewComboBoxEditingControl)) return; DataGridViewComboBoxEditingControl ec = e.Control as DataGridViewComboBoxEditingControl; ec.DrawMode = DrawMode.OwnerDrawFixed; ec.DrawItem += new DrawItemEventHandler(dropdown_DrawItem); if (indexGrid.CurrentCell.ColumnIndex == 0) { // now we need to set the item list to all non used columns and the option of // NONE ec.Items.Clear(); ec.Items.Add(""); foreach (string s in columnNames) { bool alreadyUsed = false; if (s != (string)indexGrid.CurrentRow.Cells[0].Value) foreach (IndexColumnGridRow row in gridRows) if (row.ColumnName == s) { alreadyUsed = true; break; } if (!alreadyUsed) ec.Items.Add(s); } int index = ec.FindStringExact(indexGrid.CurrentRow.Cells[0].Value as string); if (index > 0) ec.SelectedIndex = index; } } void dropdown_DrawItem(object sender, DrawItemEventArgs e) { MyComboBox.DrawComboBox(sender as ComboBox, e); } private void okButton_Click(object sender, EventArgs e) { indexColumns.Clear(); foreach (IndexColumnGridRow row in gridRows) { if (String.IsNullOrEmpty(row.ColumnName)) continue; IndexColumn ic = new IndexColumn(); ic.ColumnName = row.ColumnName; ic.SortOrder = (IndexSortOrder)Enum.Parse(typeof(IndexSortOrder), row.SortOrder); indexColumns.Add(ic); } } private void indexGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex != 0) return; System.Diagnostics.Trace.WriteLine("Validate starting"); DataGridViewComboBoxCell colCell = (DataGridViewComboBoxCell)indexGrid.Rows[e.RowIndex].Cells[0]; DataGridViewComboBoxCell sortCell = (DataGridViewComboBoxCell)indexGrid.Rows[e.RowIndex].Cells[1]; IndexColumnGridRow gr = indexColumnBindingSource.Current as IndexColumnGridRow; string value = e.FormattedValue as string; if (value == "") { colCell.Value = null; sortCell.Value = null; gr.ColumnName = null; gr.SortOrder = null; } else { colCell.Value = e.FormattedValue; if (!String.IsNullOrEmpty(colCell.Value as string) && String.IsNullOrEmpty(sortCell.Value as string)) gr.SortOrder = "Ascending"; sortCell.Value = gr.SortOrder; } } } public class IndexColumnEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { List ic = value as List; Index index = ic[0].OwningIndex; Table t = index.Table; IndexColumnEditorDialog dlg = new IndexColumnEditorDialog(ic); DialogResult result = dlg.ShowDialog(); if (index.Type != IndexType.Primary) return value; foreach (Column c in t.Columns) c.PrimaryKey = false; foreach (IndexColumn i in ic) { i.OwningIndex = index; foreach (Column c in t.Columns) if (c.ColumnName == i.ColumnName) c.PrimaryKey = true; } t.NotifyUpdate(); return value; } } public class IndexColumnGridRow { private string _columnName; public string ColumnName { get { return _columnName; } set { _columnName = value; } } private string _sortOrder; public string SortOrder { get { return _sortOrder; } set { _sortOrder = value; } } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/TableNamePromptDialog.Designer.cs0000644000175000017500000000761611127003600032775 0ustar directhexdirecthexnamespace MySql.Data.VisualStudio.Editors { partial class TableNamePromptDialog { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.tableName = new System.Windows.Forms.TextBox(); this.Cancel = new System.Windows.Forms.Button(); this.Ok = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(132, 13); this.label1.TabIndex = 0; this.label1.Text = "&Enter a name for the table:"; // // tableName // this.tableName.Location = new System.Drawing.Point(15, 30); this.tableName.Name = "tableName"; this.tableName.Size = new System.Drawing.Size(354, 20); this.tableName.TabIndex = 1; // // Cancel // this.Cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.Cancel.Location = new System.Drawing.Point(294, 59); this.Cancel.Name = "Cancel"; this.Cancel.Size = new System.Drawing.Size(75, 23); this.Cancel.TabIndex = 2; this.Cancel.Text = "Cancel"; this.Cancel.UseVisualStyleBackColor = true; // // Ok // this.Ok.DialogResult = System.Windows.Forms.DialogResult.OK; this.Ok.Location = new System.Drawing.Point(213, 59); this.Ok.Name = "Ok"; this.Ok.Size = new System.Drawing.Size(75, 23); this.Ok.TabIndex = 3; this.Ok.Text = "OK"; this.Ok.UseVisualStyleBackColor = true; // // TableNamePromptDialog // this.AcceptButton = this.Ok; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.Cancel; this.ClientSize = new System.Drawing.Size(381, 93); this.Controls.Add(this.Ok); this.Controls.Add(this.Cancel); this.Controls.Add(this.tableName); this.Controls.Add(this.label1); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "TableNamePromptDialog"; this.Padding = new System.Windows.Forms.Padding(9); this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Choose Name"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox tableName; private System.Windows.Forms.Button Cancel; private System.Windows.Forms.Button Ok; } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/ForeignKeyDialog.Designer.cs0000644000175000017500000004764711127003600032015 0ustar directhexdirecthexusing System; using MySql.Data.VisualStudio.DbObjects; using System.Windows.Forms; namespace MySql.Data.VisualStudio.Editors { partial class ForeignKeyDialog { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.fkList = new System.Windows.Forms.ListBox(); this.foreignKeyBindingSource = new System.Windows.Forms.BindingSource(this.components); this.label1 = new System.Windows.Forms.Label(); this.addButton = new System.Windows.Forms.Button(); this.deleteButton = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.columnGrid = new System.Windows.Forms.DataGridView(); this.colGridColumn = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.fkGridColumn = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.fkColumnsBindingSource = new System.Windows.Forms.BindingSource(this.components); this.closeButton = new System.Windows.Forms.Button(); this.label5 = new System.Windows.Forms.Label(); this.fkName = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.dataGridViewComboBoxColumn1 = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.dataGridViewComboBoxColumn2 = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.label6 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.matchType = new MySql.Data.VisualStudio.Editors.MyComboBox(); this.deleteAction = new MySql.Data.VisualStudio.Editors.MyComboBox(); this.updateAction = new MySql.Data.VisualStudio.Editors.MyComboBox(); this.refTable = new MySql.Data.VisualStudio.Editors.MyComboBox(); ((System.ComponentModel.ISupportInitialize)(this.foreignKeyBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.columnGrid)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.fkColumnsBindingSource)).BeginInit(); this.SuspendLayout(); // // fkList // this.fkList.FormattingEnabled = true; this.fkList.ItemHeight = 15; this.fkList.Location = new System.Drawing.Point(14, 36); this.fkList.Name = "fkList"; this.fkList.Size = new System.Drawing.Size(181, 304); this.fkList.TabIndex = 0; // // foreignKeyBindingSource // this.foreignKeyBindingSource.AllowNew = false; this.foreignKeyBindingSource.CurrentChanged += new System.EventHandler(this.foreignKeyBindingSource_CurrentChanged); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(10, 9); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(122, 15); this.label1.TabIndex = 1; this.label1.Text = "Selected Relationship:"; // // addButton // this.addButton.Location = new System.Drawing.Point(14, 347); this.addButton.Name = "addButton"; this.addButton.Size = new System.Drawing.Size(87, 27); this.addButton.TabIndex = 2; this.addButton.Text = "Add"; this.addButton.UseVisualStyleBackColor = true; this.addButton.Click += new System.EventHandler(this.addButton_Click); // // deleteButton // this.deleteButton.Location = new System.Drawing.Point(108, 347); this.deleteButton.Name = "deleteButton"; this.deleteButton.Size = new System.Drawing.Size(87, 27); this.deleteButton.TabIndex = 3; this.deleteButton.Text = "Delete"; this.deleteButton.UseVisualStyleBackColor = true; this.deleteButton.Click += new System.EventHandler(this.deleteButton_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(235, 75); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(101, 15); this.label2.TabIndex = 5; this.label2.Text = "Referenced Table:"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(288, 104); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(48, 15); this.label3.TabIndex = 6; this.label3.Text = "Update:"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // columnGrid // this.columnGrid.AllowUserToResizeRows = false; this.columnGrid.AutoGenerateColumns = false; this.columnGrid.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; this.columnGrid.BackgroundColor = System.Drawing.SystemColors.Window; this.columnGrid.BorderStyle = System.Windows.Forms.BorderStyle.None; this.columnGrid.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; this.columnGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.columnGrid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colGridColumn, this.fkGridColumn}); this.columnGrid.DataSource = this.fkColumnsBindingSource; this.columnGrid.GridColor = System.Drawing.SystemColors.ControlLight; this.columnGrid.Location = new System.Drawing.Point(218, 163); this.columnGrid.MultiSelect = false; this.columnGrid.Name = "columnGrid"; this.columnGrid.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; this.columnGrid.RowHeadersVisible = false; this.columnGrid.ShowEditingIcon = false; this.columnGrid.Size = new System.Drawing.Size(425, 177); this.columnGrid.TabIndex = 10; this.columnGrid.VirtualMode = true; this.columnGrid.RowValidating += new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.columnGrid_RowValidating); this.columnGrid.CellValueNeeded += new System.Windows.Forms.DataGridViewCellValueEventHandler(this.columnGrid_CellValueNeeded); this.columnGrid.CellValidating += new System.Windows.Forms.DataGridViewCellValidatingEventHandler(this.columnGrid_CellValidating); this.columnGrid.CellValuePushed += new System.Windows.Forms.DataGridViewCellValueEventHandler(this.columnGrid_CellValuePushed); this.columnGrid.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.columnGrid_EditingControlShowing); // // colGridColumn // this.colGridColumn.DataPropertyName = "Column"; this.colGridColumn.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.Nothing; this.colGridColumn.DisplayStyleForCurrentCellOnly = true; this.colGridColumn.HeaderText = "Column"; this.colGridColumn.Name = "colGridColumn"; // // fkGridColumn // this.fkGridColumn.DataPropertyName = "ReferencedColumn"; this.fkGridColumn.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.ComboBox; this.fkGridColumn.DisplayStyleForCurrentCellOnly = true; this.fkGridColumn.HeaderText = "Foreign Column"; this.fkGridColumn.Name = "fkGridColumn"; // // fkColumnsBindingSource // this.fkColumnsBindingSource.AllowNew = true; this.fkColumnsBindingSource.DataSource = typeof(MySql.Data.VisualStudio.DbObjects.FKColumnPair); // // closeButton // this.closeButton.Location = new System.Drawing.Point(556, 347); this.closeButton.Name = "closeButton"; this.closeButton.Size = new System.Drawing.Size(87, 27); this.closeButton.TabIndex = 12; this.closeButton.Text = "Close"; this.closeButton.UseVisualStyleBackColor = true; this.closeButton.Click += new System.EventHandler(this.closeButton_Click); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(488, 104); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(43, 15); this.label5.TabIndex = 13; this.label5.Text = "Delete:"; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // fkName // this.fkName.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.foreignKeyBindingSource, "Name", true)); this.fkName.Location = new System.Drawing.Point(342, 36); this.fkName.Name = "fkName"; this.fkName.Size = new System.Drawing.Size(301, 23); this.fkName.TabIndex = 14; this.fkName.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.fkName_KeyPress); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(294, 44); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(42, 15); this.label4.TabIndex = 15; this.label4.Text = "Name:"; // // dataGridViewComboBoxColumn1 // this.dataGridViewComboBoxColumn1.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.Nothing; this.dataGridViewComboBoxColumn1.DisplayStyleForCurrentCellOnly = true; this.dataGridViewComboBoxColumn1.HeaderText = "Column"; this.dataGridViewComboBoxColumn1.Name = "dataGridViewComboBoxColumn1"; this.dataGridViewComboBoxColumn1.Width = 159; // // dataGridViewComboBoxColumn2 // this.dataGridViewComboBoxColumn2.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.ComboBox; this.dataGridViewComboBoxColumn2.DisplayStyleForCurrentCellOnly = true; this.dataGridViewComboBoxColumn2.HeaderText = "Foreign Column"; this.dataGridViewComboBoxColumn2.Name = "dataGridViewComboBoxColumn2"; this.dataGridViewComboBoxColumn2.Width = 159; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(488, 134); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(44, 15); this.label6.TabIndex = 17; this.label6.Text = "Match:"; this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(215, 145); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(55, 15); this.label7.TabIndex = 18; this.label7.Text = "Columns"; // // matchType // this.matchType.DataBindings.Add(new System.Windows.Forms.Binding("SelectedItem", this.foreignKeyBindingSource, "Match", true)); this.matchType.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.matchType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.matchType.Items.AddRange(new object[] { MySql.Data.VisualStudio.DbObjects.MatchOption.Full, MySql.Data.VisualStudio.DbObjects.MatchOption.Partial, MySql.Data.VisualStudio.DbObjects.MatchOption.Simple}); this.matchType.Location = new System.Drawing.Point(536, 125); this.matchType.MinimumSize = new System.Drawing.Size(4, 10); this.matchType.Name = "matchType"; this.matchType.Size = new System.Drawing.Size(107, 24); this.matchType.TabIndex = 16; // // deleteAction // this.deleteAction.DataBindings.Add(new System.Windows.Forms.Binding("SelectedItem", this.foreignKeyBindingSource, "DeleteAction", true)); this.deleteAction.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.deleteAction.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.deleteAction.Items.AddRange(new object[] { MySql.Data.VisualStudio.DbObjects.ReferenceOption.NoAction, MySql.Data.VisualStudio.DbObjects.ReferenceOption.Cascade, MySql.Data.VisualStudio.DbObjects.ReferenceOption.Restrict, MySql.Data.VisualStudio.DbObjects.ReferenceOption.SetNull}); this.deleteAction.Location = new System.Drawing.Point(536, 95); this.deleteAction.MinimumSize = new System.Drawing.Size(4, 10); this.deleteAction.Name = "deleteAction"; this.deleteAction.Size = new System.Drawing.Size(107, 24); this.deleteAction.TabIndex = 9; // // updateAction // this.updateAction.DataBindings.Add(new System.Windows.Forms.Binding("SelectedItem", this.foreignKeyBindingSource, "UpdateAction", true)); this.updateAction.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.updateAction.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.updateAction.FormattingEnabled = true; this.updateAction.Items.AddRange(new object[] { MySql.Data.VisualStudio.DbObjects.ReferenceOption.NoAction, MySql.Data.VisualStudio.DbObjects.ReferenceOption.Cascade, MySql.Data.VisualStudio.DbObjects.ReferenceOption.Restrict, MySql.Data.VisualStudio.DbObjects.ReferenceOption.SetNull}); this.updateAction.Location = new System.Drawing.Point(342, 95); this.updateAction.MinimumSize = new System.Drawing.Size(4, 10); this.updateAction.Name = "updateAction"; this.updateAction.Size = new System.Drawing.Size(107, 24); this.updateAction.TabIndex = 8; // // refTable // this.refTable.DataBindings.Add(new System.Windows.Forms.Binding("SelectedItem", this.foreignKeyBindingSource, "ReferencedTable", true)); this.refTable.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.refTable.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.refTable.FormattingEnabled = true; this.refTable.Location = new System.Drawing.Point(342, 66); this.refTable.MinimumSize = new System.Drawing.Size(4, 10); this.refTable.Name = "refTable"; this.refTable.Size = new System.Drawing.Size(301, 24); this.refTable.TabIndex = 4; this.refTable.SelectedIndexChanged += new System.EventHandler(this.refTable_SelectedIndexChanged); // // ForeignKeyDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(655, 386); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.matchType); this.Controls.Add(this.label4); this.Controls.Add(this.fkName); this.Controls.Add(this.label5); this.Controls.Add(this.closeButton); this.Controls.Add(this.columnGrid); this.Controls.Add(this.deleteAction); this.Controls.Add(this.updateAction); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.refTable); this.Controls.Add(this.deleteButton); this.Controls.Add(this.addButton); this.Controls.Add(this.label1); this.Controls.Add(this.fkList); this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ForeignKeyDialog"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Foreign Key Relationships"; ((System.ComponentModel.ISupportInitialize)(this.foreignKeyBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.columnGrid)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.fkColumnsBindingSource)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ListBox fkList; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button addButton; private System.Windows.Forms.Button deleteButton; private MyComboBox refTable; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private MyComboBox updateAction; private MyComboBox deleteAction; private System.Windows.Forms.DataGridView columnGrid; private System.Windows.Forms.Button closeButton; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox fkName; private System.Windows.Forms.Label label4; private System.Windows.Forms.DataGridViewComboBoxColumn dataGridViewComboBoxColumn1; private System.Windows.Forms.DataGridViewComboBoxColumn dataGridViewComboBoxColumn2; private System.Windows.Forms.Label label6; private MyComboBox matchType; private System.Windows.Forms.Label label7; private System.Windows.Forms.BindingSource foreignKeyBindingSource; private BindingSource fkColumnsBindingSource; private DataGridViewComboBoxColumn colGridColumn; private DataGridViewComboBoxColumn fkGridColumn; } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/TextBufferEditor.cs0000644000175000017500000001363711127003600030311 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.OLE.Interop; using System; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Package; using System.Runtime.InteropServices; namespace MySql.Data.VisualStudio.Editors { internal class TextBufferEditor { private bool noContent; private Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp; public TextBufferEditor(System.IServiceProvider sp) { psp = sp as Microsoft.VisualStudio.OLE.Interop.IServiceProvider; noContent = true; CreateCodeEditor(); } private IVsCodeWindow _codeWindow; public IVsCodeWindow CodeWindow { get { return _codeWindow; } private set { _codeWindow = value; } } private IVsTextBuffer _textBuffer; public IVsTextBuffer TextBuffer { get { return _textBuffer; } private set { _textBuffer = value; } } private void CreateCodeEditor() { Guid clsidTextBuffer = typeof(VsTextBufferClass).GUID; Guid iidTextBuffer = VSConstants.IID_IUnknown; TextBuffer = (IVsTextBuffer)MySqlDataProviderPackage.Instance.CreateInstance( ref clsidTextBuffer, ref iidTextBuffer, typeof(object)); if (TextBuffer == null) throw new Exception("Failed to create core editor"); // first we need to site our buffer IObjectWithSite textBufferSite = TextBuffer as IObjectWithSite; if (textBufferSite != null) { textBufferSite.SetSite(psp); } // then we need to tell our buffer not to attempt to autodetect the // language settings IVsUserData userData = TextBuffer as IVsUserData; Guid g = EditorFactory.GuidVSBufferDetectLangSid; int result = userData.SetData(ref g, false); Guid clsidCodeWindow = typeof(VsCodeWindowClass).GUID; Guid iidCodeWindow = typeof(IVsCodeWindow).GUID; IVsCodeWindow pCodeWindow = (IVsCodeWindow)MySqlDataProviderPackage.Instance.CreateInstance( ref clsidCodeWindow, ref iidCodeWindow, typeof(IVsCodeWindow)); if (pCodeWindow == null) throw new Exception("Failed to create core editor"); // Give the text buffer to the code window. // We are giving up ownership of the text buffer! pCodeWindow.SetBuffer((IVsTextLines)TextBuffer); CodeWindow = pCodeWindow; } public bool Dirty { get { uint flags; TextBuffer.GetStateFlags(out flags); return (flags & (uint)BUFFERSTATEFLAGS.BSF_MODIFIED) != 0; } set { uint flags; TextBuffer.GetStateFlags(out flags); if (value) flags |= (uint)BUFFERSTATEFLAGS.BSF_MODIFIED; else flags &= ~(uint)BUFFERSTATEFLAGS.BSF_MODIFIED; TextBuffer.SetStateFlags(flags); } } public string Text { get { IVsTextLines lines = (IVsTextLines)TextBuffer; int lineCount, lineLength; string text; lines.GetLineCount(out lineCount); lines.GetLengthOfLine(lineCount - 1, out lineLength); lines.GetLineText(0, 0, lineCount - 1, lineLength, out text); return text; } set { if (noContent) Initialize(value); else Replace(value); noContent = false; } } private void Initialize(string value) { IVsTextLines lines = (IVsTextLines)TextBuffer; lines.InitializeContent(value, value.Length); } private void Replace(string value) { int endLine, endCol; IVsTextLines lines = (IVsTextLines)TextBuffer; lines.GetLastLineIndex(out endLine, out endCol); IntPtr pText = Marshal.StringToCoTaskMemAuto(value); try { lines.ReplaceLines(0, 0, endLine, endCol, pText, value.Length, null); } finally { Marshal.FreeCoTaskMem(pText); } } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/TableIndexDialog.resx0000644000175000017500000001326611127003600030575 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/TableEditorPane.cs0000644000175000017500000000611311127003600030055 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.VisualStudio.Shell; using System.ComponentModel.Design; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using System.Collections.Generic; namespace MySql.Data.VisualStudio { [Guid("7363513B-298D-49eb-B9D9-264CE6C47540")] class TableEditorPane : WindowPane { TableEditor tableEditor; List objectsForInspection = new List(); public TableEditorPane(TableNode table) : base(null) { tableEditor = new TableEditor(this, table); } public override IWin32Window Window { get { return tableEditor; } } protected override void OnCreate() { base.OnCreate(); // set up our property window tracking SelectionContainer selContainer = new SelectionContainer(); selContainer.SelectableObjects = objectsForInspection; selContainer.SelectedObjects = objectsForInspection; ITrackSelection trackSelectionRef = GetService(typeof(STrackSelection)) as ITrackSelection; trackSelectionRef.OnSelectChange(selContainer); } internal void SelectObject(object objectToInspect) { objectsForInspection.Clear(); objectsForInspection.Add(objectToInspect); } internal void AddCommand(Guid group, int commandId, EventHandler doCmd, EventHandler queryCmd) { IMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as IMenuCommandService; if (mcs == null) return; CommandID cmd = new CommandID(group, commandId); OleMenuCommand mc = new OleMenuCommand(doCmd, cmd); if (queryCmd != null) mc.BeforeQueryStatus += queryCmd; mcs.AddCommand(mc); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/TableEditor.cs0000644000175000017500000005754611127003600027271 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using MySql.Data.VisualStudio.Editors; using System.Drawing; using System.Collections; using MySql.Data.VisualStudio.Properties; using System.ComponentModel; using Microsoft.VisualStudio.OLE.Interop; using MySql.Data.VisualStudio.DbObjects; using System.Runtime.InteropServices; using System.ComponentModel.Design; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio; namespace MySql.Data.VisualStudio { class TableEditor : UserControl { private TableNode tableNode; private System.ComponentModel.IContainer components; private DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; private DataGridViewComboBoxColumn dataGridViewComboBoxColumn1; private TabControl tabControl1; private TabPage tabPage1; private VS2005PropertyGrid columnProperties; private Panel panel1; private DataGridView columnGrid; private TableEditorPane pane; private MySplitter splitter1; private DataGridViewTextBoxColumn NameColumn; private DataGridViewComboBoxColumn TypeColumn; private DataGridViewCheckBoxColumn AllowNullColumn; private BindingSource columnBindingSource; private string[] dataTypes; public TableEditor(TableEditorPane pane, TableNode node) { this.pane = pane; tableNode = node; InitializeComponent(); dataTypes = Metadata.GetDataTypes(true); TypeColumn.Items.AddRange((object[])dataTypes); tableNode.DataLoaded += new EventHandler(OnDataLoaded); columnGrid.RowTemplate.HeaderCell = new MyDataGridViewRowHeaderCell(); SetupCommands(); } #region Properties List Indexes { get { return tableNode.Table.Indexes; } } List Columns { get { return tableNode.Table.Columns; } } #endregion void OnDataLoaded(object sender, EventArgs e) { columnBindingSource.DataSource = tableNode.Table.Columns; // if our type column doesn't already contain our data types then we add // them so our grid won't complain about unsupported values foreach (Column c in tableNode.Table.Columns) if (!TypeColumn.Items.Contains(c.DataType)) TypeColumn.Items.Add(c.DataType); columnBindingSource.AddingNew += new AddingNewEventHandler(columnBindingSource_AddingNew); pane.SelectObject(tableNode.Table); tableNode.Table.DataUpdated += new EventHandler(Table_DataUpdated); } void Table_DataUpdated(object sender, EventArgs e) { columnGrid.Refresh(); } void columnBindingSource_AddingNew(object sender, AddingNewEventArgs e) { //Column c = new Column(null); ColumnWithTypeDescriptor c = new ColumnWithTypeDescriptor(); c.OwningTable = tableNode.Table; e.NewObject = c; } private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.columnProperties = new MySql.Data.VisualStudio.Editors.VS2005PropertyGrid(); this.panel1 = new System.Windows.Forms.Panel(); this.columnGrid = new System.Windows.Forms.DataGridView(); this.NameColumn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.TypeColumn = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.AllowNullColumn = new System.Windows.Forms.DataGridViewCheckBoxColumn(); this.columnBindingSource = new System.Windows.Forms.BindingSource(this.components); this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewComboBoxColumn1 = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.splitter1 = new MySql.Data.VisualStudio.Editors.MySplitter(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.columnGrid)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.columnBindingSource)).BeginInit(); this.SuspendLayout(); // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl1.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tabControl1.Location = new System.Drawing.Point(6, 10); this.tabControl1.Name = "tabControl1"; this.tabControl1.Padding = new System.Drawing.Point(6, 6); this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(612, 308); this.tabControl1.TabIndex = 1; // // tabPage1 // this.tabPage1.BackColor = System.Drawing.SystemColors.Control; this.tabPage1.Controls.Add(this.columnProperties); this.tabPage1.Location = new System.Drawing.Point(4, 30); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(604, 274); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Column Properties"; // // columnProperties // this.columnProperties.Dock = System.Windows.Forms.DockStyle.Fill; this.columnProperties.Location = new System.Drawing.Point(3, 3); this.columnProperties.Name = "columnProperties"; this.columnProperties.Size = new System.Drawing.Size(598, 268); this.columnProperties.TabIndex = 0; this.columnProperties.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.columnProperties_PropertyValueChanged); // // panel1 // this.panel1.BackColor = System.Drawing.SystemColors.Control; this.panel1.Controls.Add(this.tabControl1); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(0, 103); this.panel1.Name = "panel1"; this.panel1.Padding = new System.Windows.Forms.Padding(6, 10, 6, 6); this.panel1.Size = new System.Drawing.Size(624, 324); this.panel1.TabIndex = 9; // // columnGrid // this.columnGrid.AllowUserToResizeRows = false; this.columnGrid.AutoGenerateColumns = false; this.columnGrid.BackgroundColor = System.Drawing.SystemColors.Window; this.columnGrid.BorderStyle = System.Windows.Forms.BorderStyle.None; this.columnGrid.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter; dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle1.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.columnGrid.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1; this.columnGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.columnGrid.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.NameColumn, this.TypeColumn, this.AllowNullColumn}); this.columnGrid.DataSource = this.columnBindingSource; dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle2.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.GradientActiveCaption; dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.columnGrid.DefaultCellStyle = dataGridViewCellStyle2; this.columnGrid.Dock = System.Windows.Forms.DockStyle.Top; this.columnGrid.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically; this.columnGrid.GridColor = System.Drawing.SystemColors.ControlLight; this.columnGrid.Location = new System.Drawing.Point(0, 0); this.columnGrid.Name = "columnGrid"; this.columnGrid.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.None; this.columnGrid.RowHeadersWidth = 25; this.columnGrid.ShowCellErrors = false; this.columnGrid.ShowEditingIcon = false; this.columnGrid.ShowRowErrors = false; this.columnGrid.Size = new System.Drawing.Size(624, 103); this.columnGrid.TabIndex = 2; this.columnGrid.UserDeletingRow += new System.Windows.Forms.DataGridViewRowCancelEventHandler(this.columnGrid_UserDeletingRow); this.columnGrid.CellLeave += new System.Windows.Forms.DataGridViewCellEventHandler(this.columnGrid_CellLeave); this.columnGrid.CellValidating += new System.Windows.Forms.DataGridViewCellValidatingEventHandler(this.columnGrid_CellValidating); this.columnGrid.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.columnGrid_CellClick); this.columnGrid.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(this.columnGrid_EditingControlShowing); this.columnGrid.CellEnter += new System.Windows.Forms.DataGridViewCellEventHandler(this.columnGrid_CellEnter); this.columnGrid.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.columnGrid_CellContentClick); // // NameColumn // this.NameColumn.DataPropertyName = "ColumnName"; this.NameColumn.HeaderText = "Column Name"; this.NameColumn.MinimumWidth = 200; this.NameColumn.Name = "NameColumn"; this.NameColumn.Width = 200; // // TypeColumn // this.TypeColumn.DataPropertyName = "DataType"; this.TypeColumn.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.ComboBox; this.TypeColumn.DisplayStyleForCurrentCellOnly = true; this.TypeColumn.HeaderText = "Data Type"; this.TypeColumn.Name = "TypeColumn"; // // AllowNullColumn // this.AllowNullColumn.DataPropertyName = "AllowNull"; this.AllowNullColumn.HeaderText = "Allow Nulls"; this.AllowNullColumn.Name = "AllowNullColumn"; // // columnBindingSource // this.columnBindingSource.AllowNew = true; this.columnBindingSource.DataSource = typeof(MySql.Data.VisualStudio.DbObjects.Column); this.columnBindingSource.CurrentChanged += new System.EventHandler(this.columnBindingSource_CurrentChanged); // // dataGridViewTextBoxColumn1 // this.dataGridViewTextBoxColumn1.DataPropertyName = "ColumnName"; this.dataGridViewTextBoxColumn1.HeaderText = "Column Name"; this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; this.dataGridViewTextBoxColumn1.Width = 150; // // dataGridViewComboBoxColumn1 // this.dataGridViewComboBoxColumn1.DataPropertyName = "DataType"; this.dataGridViewComboBoxColumn1.DisplayStyle = System.Windows.Forms.DataGridViewComboBoxDisplayStyle.ComboBox; this.dataGridViewComboBoxColumn1.DisplayStyleForCurrentCellOnly = true; this.dataGridViewComboBoxColumn1.HeaderText = "Data Type"; this.dataGridViewComboBoxColumn1.Name = "dataGridViewComboBoxColumn1"; // // splitter1 // this.splitter1.Dock = System.Windows.Forms.DockStyle.Top; this.splitter1.Location = new System.Drawing.Point(0, 103); this.splitter1.Name = "splitter1"; this.splitter1.Size = new System.Drawing.Size(624, 6); this.splitter1.TabIndex = 10; this.splitter1.TabStop = false; // // TableEditor // this.BackColor = System.Drawing.SystemColors.Window; this.Controls.Add(this.splitter1); this.Controls.Add(this.panel1); this.Controls.Add(this.columnGrid); this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Margin = new System.Windows.Forms.Padding(0); this.Name = "TableEditor"; this.Size = new System.Drawing.Size(624, 427); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.columnGrid)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.columnBindingSource)).EndInit(); this.ResumeLayout(false); } #region Command Handling private void SetupCommands() { pane.AddCommand(GuidList.DavinciCommandSet, SharedCommands.cmdidIndexesAndKeys, new EventHandler(OnIndexesAndKeys), null); pane.AddCommand(GuidList.DavinciCommandSet, SharedCommands.cmdidForeignKeys, new EventHandler(OnForeignKeys), new EventHandler(OnQueryForeignKeys)); pane.AddCommand(VSConstants.GUID_VSStandardCommandSet97, (int)VSConstants.VSStd97CmdID.PrimaryKey, new EventHandler(OnPrimaryKey), new EventHandler(OnQueryPrimaryKey)); pane.AddCommand(VSConstants.GUID_VSStandardCommandSet97, (int)VSConstants.VSStd97CmdID.GenerateChangeScript, new EventHandler(OnGenerateChangeScript), new EventHandler(OnQueryGenerateChangeScript)); } private void OnQueryPrimaryKey(object sender, EventArgs e) { bool allKeys = columnGrid.SelectedRows.Count == 0 ? false : true; foreach (DataGridViewRow row in columnGrid.SelectedRows) if (!tableNode.Table.Columns[row.Index].PrimaryKey) { allKeys = false; break; } OleMenuCommand primaryKey = sender as OleMenuCommand; primaryKey.Checked = allKeys; } private void OnPrimaryKey(object sender, EventArgs e) { OleMenuCommand primaryKey = sender as OleMenuCommand; foreach (Column c in Columns) c.PrimaryKey = false; tableNode.Table.DeleteKey(null); // if not checked then we are setting the key columns if (!primaryKey.Checked) { Index index = tableNode.Table.CreateIndexWithUniqueName(true); List rows = new List(); foreach (DataGridViewRow row in columnGrid.SelectedRows) rows.Add(row.Index); if (columnGrid.SelectedRows.Count == 0) rows.Add(columnGrid.CurrentCell.RowIndex); foreach (int row in rows) { Columns[row].PrimaryKey = true; IndexColumn ic = new IndexColumn(); ic.OwningIndex = index; ic.ColumnName = Columns[row].ColumnName; ic.SortOrder = IndexSortOrder.Ascending; index.Columns.Add(ic); } if (index.Columns.Count > 0) Indexes.Add(index); } columnGrid.Refresh(); } private void OnIndexesAndKeys(object sender, EventArgs e) { TableIndexDialog dlg = new TableIndexDialog(tableNode); dlg.ShowDialog(); } private void OnQueryForeignKeys(object sender, EventArgs e) { OleMenuCommand foreignKey = sender as OleMenuCommand; foreignKey.Enabled = tableNode.Table.SupportsFK; } private void OnForeignKeys(object sender, EventArgs e) { ForeignKeyDialog dlg = new ForeignKeyDialog(tableNode); dlg.ShowDialog(); } private void OnQueryGenerateChangeScript(object sender, EventArgs e) { bool hasChanges = tableNode.Table.HasChanges(); OleMenuCommand gcsKey = sender as OleMenuCommand; gcsKey.Enabled = hasChanges; } private void OnGenerateChangeScript(object sender, EventArgs e) { GenerateChangeScriptDialog dlg = new GenerateChangeScriptDialog(tableNode); dlg.ShowDialog(); } #endregion private void columnGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { Type t = e.Control.GetType(); if (t == typeof(DataGridViewComboBoxEditingControl)) { DataGridViewComboBoxEditingControl ec = e.Control as DataGridViewComboBoxEditingControl; ec.DropDownStyle = ComboBoxStyle.DropDown; columnGrid.NotifyCurrentCellDirty(true); ec.Items.Clear(); foreach (string s in dataTypes) ec.Items.Add(s); if (tableNode.Table.Columns.Count > columnGrid.CurrentRow.Index) { Column c = tableNode.Table.Columns[columnGrid.CurrentRow.Index]; AdjustComboBox(ec, c.DataType); } } else if (t == typeof(DataGridViewTextBoxEditingControl)) { DataGridViewTextBoxEditingControl tec = e.Control as DataGridViewTextBoxEditingControl; tec.Multiline = true; tec.Dock = DockStyle.Fill; tec.BorderStyle = BorderStyle.Fixed3D; } } private void columnBindingSource_CurrentChanged(object sender, EventArgs e) { Column currentObject = columnBindingSource.Current as Column; columnProperties.SelectedObject = currentObject; } private void AdjustComboBox(ComboBox cb, string type) { if (String.IsNullOrEmpty(type)) return; int index = type.IndexOf("("); if (index == -1) cb.Items.Add(type); else { string baseType = type.Substring(0, index); for (int i = 0; i < cb.Items.Count; i++) { string item = cb.Items[i] as string; if (item.StartsWith(baseType)) { cb.Items[i] = type; break; } } } } private void columnGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex != 1) return; string type = e.FormattedValue as string; if (String.IsNullOrEmpty(type)) return; if (!TypeColumn.Items.Contains(type)) TypeColumn.Items.Add(type); columnGrid.CurrentCell.Value = e.FormattedValue; } private void columnGrid_CellEnter(object sender, DataGridViewCellEventArgs e) { if (columnGrid.SelectedCells.Count == 1) columnGrid.BeginEdit(true); } private void columnGrid_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == -1) columnGrid.EndEdit(); else columnGrid.BeginEdit(true); } private void columnGrid_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e) { Column c = Columns[e.Row.Index]; if (c.OldColumn != null) tableNode.Table.Columns.Delete(c); } private void columnGrid_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex != 2) return; DataGridViewCheckBoxCell cell = columnGrid[e.ColumnIndex, e.RowIndex] as DataGridViewCheckBoxCell; Column c = Columns[e.RowIndex]; c.AllowNull = (bool)cell.EditingCellFormattedValue; } private void columnProperties_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { if (e.ChangedItem.PropertyDescriptor.Name == "PrimaryKey") columnGrid.Refresh(); } private void columnGrid_CellLeave(object sender, DataGridViewCellEventArgs e) { int index = columnGrid.CurrentRow.Index; if (index >= 0 && index < tableNode.Table.Columns.Count) columnProperties.SelectedObject = tableNode.Table.Columns[index]; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/ForeignKeyDialog.resx0000644000175000017500000001472711127003600030623 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 True True 206, 17 mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/VS2005PropertyGrid.cs0000644000175000017500000000306411127003600030267 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Windows.Forms.Design; namespace MySql.Data.VisualStudio.Editors { public class VS2005PropertyGrid : PropertyGrid { public VS2005PropertyGrid() { this.ToolStripRenderer = new ToolStripProfessionalRenderer(new VS2005ColorTable()); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/MyDescriptionAttribute.cs0000644000175000017500000000322511127003600031531 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.ComponentModel; using MySql.Data.VisualStudio.Properties; namespace MySql.Data.VisualStudio.Editors { class MyDescriptionAttribute : DescriptionAttribute { private string rezName; public MyDescriptionAttribute(string resourceName) { rezName = resourceName; } public override string Description { get { return Resources.ResourceManager.GetString(rezName); } } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/VS2005ColorTable.cs0000644000175000017500000002651511127003600027671 0ustar directhexdirecthex// Copyright 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Windows.Forms; namespace MySql.Data.VisualStudio.Editors { class VS2005ColorTable : ProfessionalColorTable { public override Color ButtonCheckedGradientBegin { get { return Color.FromArgb(0xe1, 230, 0xe8); } } public override Color ButtonCheckedGradientEnd { get { return Color.FromArgb(0xe1, 230, 0xe8); } } public override Color ButtonCheckedGradientMiddle { get { return Color.FromArgb(0xe1, 230, 0xe8); } } public override Color ButtonCheckedHighlight { get { return base.ButtonCheckedHighlight; } } public override Color ButtonCheckedHighlightBorder { get { return base.ButtonCheckedHighlightBorder; } } public override Color ButtonPressedBorder { get { return base.ButtonPressedBorder; } } public override Color ButtonPressedGradientBegin { get { return Color.FromArgb(0x98, 0xb5, 0xe2); } } public override Color ButtonPressedGradientEnd { get { return Color.FromArgb(0x98, 0xb5, 0xe2); } } public override Color ButtonPressedGradientMiddle { get { return Color.FromArgb(0x98, 0xb5, 0xe2); } } public override Color ButtonSelectedGradientBegin { get { return Color.FromArgb(0xc1, 210, 0xee); } } public override Color ButtonSelectedGradientEnd { get { return Color.FromArgb(0xc1, 210, 0xee); } } public override Color ButtonSelectedGradientMiddle { get { return Color.FromArgb(0xc1, 210, 0xee); } } public override Color CheckBackground { get { return Color.FromArgb(0xe1, 230, 0xe8); } } public override Color CheckPressedBackground { get { return base.CheckPressedBackground; } } public override Color ButtonPressedHighlight { get { return base.ButtonPressedHighlight; } } public override Color ButtonPressedHighlightBorder { get { return base.ButtonPressedHighlightBorder; } } public override Color ButtonSelectedBorder { get { return base.ButtonSelectedBorder; } } public override Color ButtonSelectedHighlight { get { return base.ButtonSelectedHighlight; } } public override Color ButtonSelectedHighlightBorder { get { return base.ButtonSelectedHighlightBorder; } } public override Color CheckSelectedBackground { get { return base.CheckSelectedBackground; } } public override Color GripDark { get { return base.GripDark; } } public override Color GripLight { get { return Color.FromArgb(0xff, 0xff, 0xff); } } public override Color ImageMarginGradientBegin { get { return Color.FromArgb(0xfe, 0xfe, 0xfb); } } public override Color ImageMarginGradientEnd { get { return Color.FromArgb(0xbd, 0xbd, 0xa3); } } public override Color ImageMarginGradientMiddle { get { return Color.FromArgb(0xec, 0xe7, 0xe0); } } public override Color ImageMarginRevealedGradientBegin { get { return Color.FromArgb(0xf7, 0xf6, 0xef); } } public override Color ImageMarginRevealedGradientEnd { get { return Color.FromArgb(230, 0xe3, 210); } } public override Color ImageMarginRevealedGradientMiddle { get { return Color.FromArgb(0xf2, 240, 0xe4); } } public override Color MenuBorder { get { return Color.FromArgb(0x8a, 0x86, 0x7a); } } public override Color MenuItemBorder { get { return Color.FromArgb(0x31, 0x6a, 0xc5); } } public override Color MenuItemPressedGradientBegin { get { return Color.FromArgb(0xfc, 0xfc, 0xf9); } } public override Color MenuItemPressedGradientEnd { get { return Color.FromArgb(0xf6, 0xf4, 0xec); } } public override Color MenuItemPressedGradientMiddle { get { return base.MenuItemPressedGradientMiddle; } } public override Color MenuItemSelected { get { return Color.FromArgb(0xc1, 210, 0xee); } } public override Color MenuItemSelectedGradientBegin { get { return base.MenuItemSelectedGradientBegin; } } public override Color MenuItemSelectedGradientEnd { get { return base.MenuItemSelectedGradientEnd; } } public override Color MenuStripGradientBegin { get { return Color.FromArgb(0xe5, 0xe5, 0xd7); } } public override Color MenuStripGradientEnd { get { return Color.FromArgb(0xf4, 0xf2, 0xe8); } } public override Color OverflowButtonGradientBegin { get { return Color.FromArgb(0xf3, 0xf2, 240); } } public override Color OverflowButtonGradientEnd { get { return Color.FromArgb(0x92, 0x92, 0x76); } } public override Color OverflowButtonGradientMiddle { get { return Color.FromArgb(0xe2, 0xe1, 0xdb); } } public override Color RaftingContainerGradientBegin { get { return base.RaftingContainerGradientBegin; } } public override Color RaftingContainerGradientEnd { get { return base.RaftingContainerGradientEnd; } } public override Color SeparatorDark { get { return Color.FromArgb(0xc5, 0xc2, 0xb8); } } public override Color SeparatorLight { get { return Color.FromArgb(0xff, 0xff, 0xff); } } public override Color StatusStripGradientBegin { get { return base.StatusStripGradientBegin; } } public override Color StatusStripGradientEnd { get { return base.StatusStripGradientEnd; } } public override Color ToolStripBorder { get { return Color.FromArgb(0xa3, 0xa3, 0x7c); } } public override Color ToolStripContentPanelGradientBegin { get { return Color.FromArgb(250, 249, 245); } } public override Color ToolStripContentPanelGradientEnd { get { return Color.FromArgb(192, 192, 168); } } public override Color ToolStripDropDownBackground { get { return Color.FromArgb(0xfc, 0xfc, 0xf9); } } public override Color ToolStripGradientBegin { get { return Color.FromArgb(250, 249, 245); } } public override Color ToolStripGradientEnd { get { return Color.FromArgb(192, 192, 168); } } public override Color ToolStripGradientMiddle { get { return Color.FromArgb(235, 231, 224); } } public override Color ToolStripPanelGradientBegin { get { return base.ToolStripPanelGradientBegin; } } public override Color ToolStripPanelGradientEnd { get { return base.ToolStripPanelGradientEnd; } } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/MyDataGridViewRowHeaderCell.cs0000644000175000017500000000614711127003600032303 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Windows.Forms; using System.Drawing; using System.Collections.Generic; using MySql.Data.VisualStudio.Properties; using MySql.Data.VisualStudio.DbObjects; namespace MySql.Data.VisualStudio.Editors { class MyDataGridViewRowHeaderCell : DataGridViewRowHeaderCell { private List Columns { get { return (DataGridView.DataSource as BindingSource).DataSource as List; } } protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { if (Columns.Count > rowIndex) { Column c = Columns[rowIndex]; if (c.PrimaryKey) { Bitmap bmp = rowIndex == DataGridView.CurrentRow.Index ? Resources.ArrowKey : Resources.Key; bmp.MakeTransparent(); paintParts &= ~DataGridViewPaintParts.ContentBackground; base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts); Rectangle r = cellBounds; r.Offset(bmp.Width / 2, bmp.Height / 2); r.Width = bmp.Width; r.Height = bmp.Height; graphics.DrawImage(bmp, r); return; } } base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/TableIndexDialog.cs0000644000175000017500000000676511127003600030227 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using MySql.Data.VisualStudio.DbObjects; namespace MySql.Data.VisualStudio.Editors { partial class TableIndexDialog : Form { private TableNode tableNode; private Table table; public TableIndexDialog(TableNode node) { tableNode = node; table = tableNode.Table; InitializeComponent(); foreach (Index i in tableNode.Table.Indexes) indexList.Items.Add(i.Name); bool isOk = tableNode.Table.Columns.Count > 0 && !String.IsNullOrEmpty(tableNode.Table.Columns[0].ColumnName) && !String.IsNullOrEmpty(tableNode.Table.Columns[0].DataType); addButton.Enabled = isOk; deleteButton.Enabled = false; indexList.Enabled = isOk; } private void indexList_SelectedIndexChanged(object sender, EventArgs e) { if (indexList.SelectedIndex == -1) indexProps.SelectedObject = null; else indexProps.SelectedObject = tableNode.Table.Indexes[indexList.SelectedIndex]; deleteButton.Enabled = indexList.SelectedIndex != -1; } private void closeButton_Click(object sender, EventArgs e) { Close(); } private void addButton_Click(object sender, EventArgs e) { Index index = table.CreateIndexWithUniqueName(false); IndexColumn ic = new IndexColumn(); ic.OwningIndex = index; ic.ColumnName = table.Columns[0].ColumnName; ic.SortOrder = IndexSortOrder.Ascending; index.Columns.Add(ic); table.Indexes.Add(index); indexList.SelectedIndex = indexList.Items.Add(index.Name); } private void deleteButton_Click(object sender, EventArgs e) { int index = indexList.SelectedIndex; table.Indexes.RemoveAt(index); indexList.Items.RemoveAt(index); index --; if (index == -1 && indexList.Items.Count > 0) index = 0; indexList.SelectedIndex = index; } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/IndexColumnEditorDialog.resx0000644000175000017500000001361211127003600032145 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/ConnectDialog.resx0000644000175000017500000001326611127003600030147 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/SqlEditor.Designer.cs0000644000175000017500000003317011127003600030523 0ustar directhexdirecthexnamespace MySql.Data.VisualStudio.Editors { partial class SqlEditor { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SqlEditor)); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.connectButton = new System.Windows.Forms.ToolStripButton(); this.disconnectButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.runSqlButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.serverLabel = new System.Windows.Forms.ToolStripLabel(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.userLabel = new System.Windows.Forms.ToolStripLabel(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.dbLabel = new System.Windows.Forms.ToolStripLabel(); this.splitter1 = new System.Windows.Forms.Splitter(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.resultsPage = new System.Windows.Forms.TabPage(); this.resultsGrid = new System.Windows.Forms.DataGridView(); this.messagesPage = new System.Windows.Forms.TabPage(); this.messages = new System.Windows.Forms.Label(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.codeEditor = new MySql.Data.VisualStudio.Editors.VSCodeEditorUserControl(); this.toolStrip1.SuspendLayout(); this.tabControl1.SuspendLayout(); this.resultsPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.resultsGrid)).BeginInit(); this.messagesPage.SuspendLayout(); this.SuspendLayout(); // // toolStrip1 // this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.connectButton, this.disconnectButton, this.toolStripSeparator1, this.runSqlButton, this.toolStripSeparator2, this.serverLabel, this.toolStripSeparator3, this.userLabel, this.toolStripSeparator4, this.dbLabel}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(604, 25); this.toolStrip1.TabIndex = 1; this.toolStrip1.Text = "toolStrip1"; // // connectButton // this.connectButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.connectButton.Image = global::MySql.Data.VisualStudio.Properties.Resources.sql_editor_connect; this.connectButton.ImageTransparentColor = System.Drawing.Color.Transparent; this.connectButton.Name = "connectButton"; this.connectButton.Size = new System.Drawing.Size(23, 22); this.connectButton.Text = "connectButton"; this.connectButton.ToolTipText = "Connect to MySQL..."; this.connectButton.Click += new System.EventHandler(this.connectButton_Click); // // disconnectButton // this.disconnectButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.disconnectButton.Enabled = false; this.disconnectButton.Image = global::MySql.Data.VisualStudio.Properties.Resources.sql_editor_disconnect; this.disconnectButton.ImageTransparentColor = System.Drawing.Color.Transparent; this.disconnectButton.Name = "disconnectButton"; this.disconnectButton.Size = new System.Drawing.Size(23, 22); this.disconnectButton.Text = "Disconnect from MySQL"; this.disconnectButton.Click += new System.EventHandler(this.disconnectButton_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // runSqlButton // this.runSqlButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.runSqlButton.Enabled = false; this.runSqlButton.Image = global::MySql.Data.VisualStudio.Properties.Resources.sql_editor_runsql; this.runSqlButton.ImageTransparentColor = System.Drawing.Color.Transparent; this.runSqlButton.Name = "runSqlButton"; this.runSqlButton.Size = new System.Drawing.Size(23, 22); this.runSqlButton.Text = "runSqlButton"; this.runSqlButton.ToolTipText = "Run SQL"; this.runSqlButton.Click += new System.EventHandler(this.runSqlButton_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25); // // serverLabel // this.serverLabel.Name = "serverLabel"; this.serverLabel.Size = new System.Drawing.Size(88, 22); this.serverLabel.Text = "Server: "; // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25); // // userLabel // this.userLabel.Name = "userLabel"; this.userLabel.Size = new System.Drawing.Size(79, 22); this.userLabel.Text = "User: "; // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(6, 25); // // dbLabel // this.dbLabel.Name = "dbLabel"; this.dbLabel.Size = new System.Drawing.Size(104, 22); this.dbLabel.Text = "Database: "; // // splitter1 // this.splitter1.Dock = System.Windows.Forms.DockStyle.Top; this.splitter1.Location = new System.Drawing.Point(0, 271); this.splitter1.Name = "splitter1"; this.splitter1.Size = new System.Drawing.Size(604, 10); this.splitter1.TabIndex = 3; this.splitter1.TabStop = false; // // tabControl1 // this.tabControl1.Controls.Add(this.resultsPage); this.tabControl1.Controls.Add(this.messagesPage); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl1.ImageList = this.imageList1; this.tabControl1.Location = new System.Drawing.Point(0, 281); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(604, 185); this.tabControl1.TabIndex = 4; // // resultsPage // this.resultsPage.Controls.Add(this.resultsGrid); this.resultsPage.ImageIndex = 1; this.resultsPage.Location = new System.Drawing.Point(4, 23); this.resultsPage.Name = "resultsPage"; this.resultsPage.Padding = new System.Windows.Forms.Padding(3); this.resultsPage.Size = new System.Drawing.Size(596, 158); this.resultsPage.TabIndex = 0; this.resultsPage.Text = "Results"; this.resultsPage.UseVisualStyleBackColor = true; // // resultsGrid // this.resultsGrid.AllowUserToAddRows = false; this.resultsGrid.AllowUserToDeleteRows = false; this.resultsGrid.BackgroundColor = System.Drawing.SystemColors.Window; this.resultsGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.resultsGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.resultsGrid.Location = new System.Drawing.Point(3, 3); this.resultsGrid.Name = "resultsGrid"; this.resultsGrid.Size = new System.Drawing.Size(590, 152); this.resultsGrid.TabIndex = 0; // // messagesPage // this.messagesPage.Controls.Add(this.messages); this.messagesPage.ImageIndex = 0; this.messagesPage.Location = new System.Drawing.Point(4, 23); this.messagesPage.Name = "messagesPage"; this.messagesPage.Padding = new System.Windows.Forms.Padding(3); this.messagesPage.Size = new System.Drawing.Size(596, 158); this.messagesPage.TabIndex = 1; this.messagesPage.Text = "Messages"; this.messagesPage.UseVisualStyleBackColor = true; // // messages // this.messages.Dock = System.Windows.Forms.DockStyle.Fill; this.messages.Location = new System.Drawing.Point(3, 3); this.messages.Name = "messages"; this.messages.Size = new System.Drawing.Size(590, 152); this.messages.TabIndex = 0; // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "messages_icon.png"); this.imageList1.Images.SetKeyName(1, "results_icon.png"); // // codeEditor // this.codeEditor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.codeEditor.Dock = System.Windows.Forms.DockStyle.Top; this.codeEditor.Location = new System.Drawing.Point(0, 25); this.codeEditor.Name = "codeEditor"; this.codeEditor.Size = new System.Drawing.Size(604, 246); this.codeEditor.TabIndex = 2; // // SqlEditor // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.tabControl1); this.Controls.Add(this.splitter1); this.Controls.Add(this.codeEditor); this.Controls.Add(this.toolStrip1); this.Name = "SqlEditor"; this.Size = new System.Drawing.Size(604, 466); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.tabControl1.ResumeLayout(false); this.resultsPage.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.resultsGrid)).EndInit(); this.messagesPage.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStrip toolStrip1; private VSCodeEditorUserControl codeEditor; private System.Windows.Forms.Splitter splitter1; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage resultsPage; private System.Windows.Forms.TabPage messagesPage; private System.Windows.Forms.ToolStripButton connectButton; private System.Windows.Forms.ToolStripLabel serverLabel; private System.Windows.Forms.ToolStripButton runSqlButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripButton disconnectButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripLabel userLabel; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripLabel dbLabel; private System.Windows.Forms.DataGridView resultsGrid; private System.Windows.Forms.Label messages; private System.Windows.Forms.ImageList imageList1; } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/MyComboBox.cs0000644000175000017500000000774111127003600027101 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Windows.Forms; using System.Drawing; namespace MySql.Data.VisualStudio.Editors { class MyComboBox : ComboBox { public MyComboBox() : base() { DrawMode = DrawMode.OwnerDrawFixed; DrawItem += new DrawItemEventHandler(DrawListItem); } private void DrawListItem(object sender, DrawItemEventArgs e) { DrawComboBox(this, e); } public override Size MinimumSize { get { Size sz = base.MinimumSize; sz.Height += 10; return sz; } set { base.MinimumSize = value; } } public static void DrawComboBox(ComboBox cb, DrawItemEventArgs e) { if (e.Index == -1) return; object comboBoxItem = cb.Items[e.Index]; e.DrawBackground(); e.DrawFocusRectangle(); // bool isSeparatorItem = (comboBoxItem is SeparatorItem); // draw the text using (Brush textBrush = new SolidBrush(e.ForeColor)) { Rectangle bounds = e.Bounds; // adjust the bounds so that the text is centered properly. // if we're a separator, remove the separator height // if (isSeparatorItem && (e.State & DrawItemState.ComboBoxEdit) != DrawItemState.ComboBoxEdit) // { // bounds.Height -= separatorHeight; // } // Draw the string vertically centered but on the left using (StringFormat format = new StringFormat()) { format.LineAlignment = StringAlignment.Center; format.Alignment = StringAlignment.Near; // in Whidbey consider using TextRenderer.DrawText instead e.Graphics.DrawString(comboBoxItem.ToString(), cb.Font, textBrush, bounds, format); } } // draw the separator line /* if (isSeparatorItem && ((e.State & DrawItemState.ComboBoxEdit) != DrawItemState.ComboBoxEdit)) { Rectangle separatorRect = new Rectangle(e.Bounds.Left, e.Bounds.Bottom - separatorHeight, e.Bounds.Width, separatorHeight); // fill the background behind the separator using (Brush b = new SolidBrush(comboBox1.BackColor)) { e.Graphics.FillRectangle(b, separatorRect); } e.Graphics.DrawLine(SystemPens.ControlText, separatorRect.Left + 2, separatorRect.Top + 1, separatorRect.Right - 2, separatorRect.Top + 1); }*/ } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/SqlEditor.resx0000644000175000017500000002422311127003600027337 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 122, 17 AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj00LjAuMC4w LCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAACZTeXN0 ZW0uV2luZG93cy5Gb3Jtcy5JbWFnZUxpc3RTdHJlYW1lcgEAAAAERGF0YQcCAgAAAAkDAAAADwMAAADM CQAAAk1TRnQBSQFMAgEBAgEAASABAAEgAQABEAEAARABAAT/AQkBAAj/AUIBTQE2AQQGAAE2AQQCAAEo AwABQAMAARADAAEBAQABCAYAAQQYAAGAAgABgAMAAoABAAGAAwABgAEAAYABAAKAAgADwAEAAcAB3AHA AQAB8AHKAaYBAAEzBQABMwEAATMBAAEzAQACMwIAAxYBAAMcAQADIgEAAykBAANVAQADTQEAA0IBAAM5 AQABgAF8Af8BAAJQAf8BAAGTAQAB1gEAAf8B7AHMAQABxgHWAe8BAAHWAucBAAGQAakBrQIAAf8BMwMA AWYDAAGZAwABzAIAATMDAAIzAgABMwFmAgABMwGZAgABMwHMAgABMwH/AgABZgMAAWYBMwIAAmYCAAFm AZkCAAFmAcwCAAFmAf8CAAGZAwABmQEzAgABmQFmAgACmQIAAZkBzAIAAZkB/wIAAcwDAAHMATMCAAHM AWYCAAHMAZkCAALMAgABzAH/AgAB/wFmAgAB/wGZAgAB/wHMAQABMwH/AgAB/wEAATMBAAEzAQABZgEA ATMBAAGZAQABMwEAAcwBAAEzAQAB/wEAAf8BMwIAAzMBAAIzAWYBAAIzAZkBAAIzAcwBAAIzAf8BAAEz AWYCAAEzAWYBMwEAATMCZgEAATMBZgGZAQABMwFmAcwBAAEzAWYB/wEAATMBmQIAATMBmQEzAQABMwGZ AWYBAAEzApkBAAEzAZkBzAEAATMBmQH/AQABMwHMAgABMwHMATMBAAEzAcwBZgEAATMBzAGZAQABMwLM AQABMwHMAf8BAAEzAf8BMwEAATMB/wFmAQABMwH/AZkBAAEzAf8BzAEAATMC/wEAAWYDAAFmAQABMwEA AWYBAAFmAQABZgEAAZkBAAFmAQABzAEAAWYBAAH/AQABZgEzAgABZgIzAQABZgEzAWYBAAFmATMBmQEA AWYBMwHMAQABZgEzAf8BAAJmAgACZgEzAQADZgEAAmYBmQEAAmYBzAEAAWYBmQIAAWYBmQEzAQABZgGZ AWYBAAFmApkBAAFmAZkBzAEAAWYBmQH/AQABZgHMAgABZgHMATMBAAFmAcwBmQEAAWYCzAEAAWYBzAH/ AQABZgH/AgABZgH/ATMBAAFmAf8BmQEAAWYB/wHMAQABzAEAAf8BAAH/AQABzAEAApkCAAGZATMBmQEA AZkBAAGZAQABmQEAAcwBAAGZAwABmQIzAQABmQEAAWYBAAGZATMBzAEAAZkBAAH/AQABmQFmAgABmQFm ATMBAAGZATMBZgEAAZkBZgGZAQABmQFmAcwBAAGZATMB/wEAApkBMwEAApkBZgEAA5kBAAKZAcwBAAKZ Af8BAAGZAcwCAAGZAcwBMwEAAWYBzAFmAQABmQHMAZkBAAGZAswBAAGZAcwB/wEAAZkB/wIAAZkB/wEz AQABmQHMAWYBAAGZAf8BmQEAAZkB/wHMAQABmQL/AQABzAMAAZkBAAEzAQABzAEAAWYBAAHMAQABmQEA AcwBAAHMAQABmQEzAgABzAIzAQABzAEzAWYBAAHMATMBmQEAAcwBMwHMAQABzAEzAf8BAAHMAWYCAAHM AWYBMwEAAZkCZgEAAcwBZgGZAQABzAFmAcwBAAGZAWYB/wEAAcwBmQIAAcwBmQEzAQABzAGZAWYBAAHM ApkBAAHMAZkBzAEAAcwBmQH/AQACzAIAAswBMwEAAswBZgEAAswBmQEAA8wBAALMAf8BAAHMAf8CAAHM Af8BMwEAAZkB/wFmAQABzAH/AZkBAAHMAf8BzAEAAcwC/wEAAcwBAAEzAQAB/wEAAWYBAAH/AQABmQEA AcwBMwIAAf8CMwEAAf8BMwFmAQAB/wEzAZkBAAH/ATMBzAEAAf8BMwH/AQAB/wFmAgAB/wFmATMBAAHM AmYBAAH/AWYBmQEAAf8BZgHMAQABzAFmAf8BAAH/AZkCAAH/AZkBMwEAAf8BmQFmAQAB/wKZAQAB/wGZ AcwBAAH/AZkB/wEAAf8BzAIAAf8BzAEzAQAB/wHMAWYBAAH/AcwBmQEAAf8CzAEAAf8BzAH/AQAC/wEz AQABzAH/AWYBAAL/AZkBAAL/AcwBAAJmAf8BAAFmAf8BZgEAAWYC/wEAAf8CZgEAAf8BZgH/AQAC/wFm AQABIQEAAaUBAANfAQADdwEAA4YBAAOWAQADywEAA7IBAAPXAQAD3QEAA+MBAAPqAQAD8QEAA/gBAAHw AfsB/wEAAaQCoAEAA4ADAAH/AgAB/wMAAv8BAAH/AwAB/wEAAf8BAAL/AgAD/wcAAf8B9wdmCv8GAAH/ IQABtQFsAeoDbAH3Af8BCQG7ArUB9wFmAQAB/wHtARUBZgEVAWYBFQFmAhUBZgQVIgABtQG8AbUDuwH3 Af8CTQG8AUkBtQFmAQAB/wHtAQcB7wO1A/cBtQPtAWYiAAG1Af8B8wEZAd0BVgH3Av8B8wHwAQcBtQFm Af8BAAHtA/8B7wL0ARkB9wHdAgkB7QFmIgABtQH/AfMCGQHdAbUB/wHjAU0B8gFQAbsBZgH/AQAB7QP/ AbUB/wL0AfcBGQHdAQkB7QFmAf8hAAG1Af8B9AHzAhkBtQP/AfQB8QG7AWYB/wEAAe0BvAIHAbsB7wG1 Ae8CtQL3AZIBFQH/IAAB/wG1Af8B9AEZAfMBGQG7Af8BdQHjAf8BUAG1AWwB/wEAAbUD/wEHA/8B7wH0 AhkB9wEVAf8hAAG1Bf8BuwP/AfEBbAJmAf8BAAH3A/8BBwP/AbUC9AEZAfcBFQH/IQABtQHxAwcB7wG7 Af8BlAF1AbUBvAFmAfEB/wEAAfcB8AG8BQcB7wG1Ae8B9wG1ARUB/yAAAf8BtQHyAvMB3QIJA/8BtQFm AfEB/wIAAbUD/wEHA/8B7wL/AfQBtQEVAf8hAAG1Bf8BCQG8AQkCuwHxAv8CAAG1A/8BvAP/AQcD/wG1 AWYB/yEAAbUBuwHvAbUD9wGuA/8BAAL/AgAGtAetAacB/yEAAbUB/wHwArwBCQG1Aa4E/wEAAf8CAAG0 A9wB1gjVAa0B/yEAAbUC/wH0AhkBCQGuA/8EAAH/CLQGrSIAAbUF/wHzAZED/zQAAf8CBwXvAfcB/wIA Af8zAAFCAU0BPgcAAT4DAAEoAwABQAMAARADAAEBAQABAQUAAYAXAAP/AQAB/AIAAX4EAAGAAQEBAAEB BAABgAEBAQABAQQAAYABAAGAAQEEAAGAAQABgAUAAYABAAGABwABgAUAAYABAAGABQABgAEAAYAGAAEB AYAFAAGAAQEBgAUAAYABCQGABQABgAEFAYAFAAGAAQ8BAAEBBAABgAEPAv8FAAE3Av8EAAs= mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/SqlEditorFactory.cs0000644000175000017500000000751711127003600030322 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace MySql.Data.VisualStudio.Editors { [Guid(GuidStrings.SqlEditorFactory)] public sealed class SqlEditorFactory : IVsEditorFactory, IDisposable { private MySqlDataProviderPackage package; private ServiceProvider serviceProvider; #region IVsEditorFactory Members int IVsEditorFactory.Close() { return VSConstants.S_OK; } int IVsEditorFactory.CreateEditorInstance(uint grfCreateDoc, string pszMkDocument, string pszPhysicalView, IVsHierarchy pvHier, uint itemid, IntPtr punkDocDataExisting, out IntPtr ppunkDocView, out IntPtr ppunkDocData, out string pbstrEditorCaption, out Guid pguidCmdUI, out int pgrfCDW) { pgrfCDW = 0; pguidCmdUI = VSConstants.GUID_TextEditorFactory; SqlEditorPane editor = new SqlEditorPane(serviceProvider); ppunkDocData = Marshal.GetIUnknownForObject(editor.Window); ppunkDocView = Marshal.GetIUnknownForObject(editor); pbstrEditorCaption = ""; return VSConstants.S_OK; } int IVsEditorFactory.MapLogicalView(ref Guid logicalView, out string physicalView) { physicalView = null; if (VSConstants.LOGVIEWID_Primary == logicalView) { // --- Primary view uses null as physicalView return VSConstants.S_OK; } else { // --- You must return E_NOTIMPL for any unrecognized logicalView values return VSConstants.E_NOTIMPL; } } int IVsEditorFactory.SetSite(Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp) { serviceProvider = new ServiceProvider(psp); return VSConstants.S_OK; } #endregion #region IDisposable Members void IDisposable.Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (disposing) { // --- Here we dispose all managed and unmanaged resources if (serviceProvider != null) { serviceProvider.Dispose(); serviceProvider = null; } } } #endregion } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/SqlEditor.cs0000644000175000017500000001414111127003600026761 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using Microsoft.VisualStudio.Shell; using System.Data.Common; using MySql.Data.MySqlClient; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using System.Globalization; using System.IO; namespace MySql.Data.VisualStudio.Editors { public partial class SqlEditor : BaseEditorControl { private DbConnection connection; private DbProviderFactory factory; public SqlEditor() { InitializeComponent(); factory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient"); if (factory == null) throw new Exception("MySql Data Provider is not correctly registered"); tabControl1.TabPages.Remove(resultsPage); } public SqlEditor(ServiceProvider sp) : this() { serviceProvider = sp; codeEditor.Init(sp); } #region Overrides protected override string GetFileFormatList() { return "MySQL Script Files (*.mysql)\n*.mysql\n\n"; } protected override void SaveFile(string fileName) { using (StreamWriter writer = new StreamWriter(fileName, false)) { writer.Write(codeEditor.Text); } } protected override void LoadFile(string fileName) { if (!File.Exists(fileName)) return; using (StreamReader reader = new StreamReader(fileName)) { string sql = reader.ReadToEnd(); codeEditor.Text = sql; } } protected override bool IsDirty { get { return codeEditor.IsDirty; } set { codeEditor.IsDirty = value; } } #endregion private void connectButton_Click(object sender, EventArgs e) { resultsPage.Hide(); ConnectDialog d = new ConnectDialog(); d.Connection = connection; DialogResult r = d.ShowDialog(); if (r == DialogResult.Cancel) return; connection = d.Connection; UpdateButtons(); } private void runSqlButton_Click(object sender, EventArgs e) { string sql = codeEditor.Text.Trim(); if (sql.StartsWith("SELECT", StringComparison.InvariantCultureIgnoreCase)) ExecuteSelect(sql); else ExecuteScript(sql); } private void ExecuteSelect(string sql) { tabControl1.TabPages.Clear(); MySqlDataAdapter da = new MySqlDataAdapter(sql, (MySqlConnection)connection); DataTable dt = new DataTable(); try { da.Fill(dt); tabControl1.TabPages.Add(resultsPage); resultsGrid.DataSource = dt; } catch (Exception ex) { messages.Text = ex.Message; } finally { tabControl1.TabPages.Add(messagesPage); } } private void ExecuteScript(string sql) { tabControl1.TabPages.Clear(); MySqlScript script = new MySqlScript((MySqlConnection)connection, sql); try { int rows = script.Execute(); messages.Text = String.Format("{0} row(s) affected", rows); } catch (Exception ex) { messages.Text = ex.Message; } finally { tabControl1.TabPages.Add(messagesPage); } } private void validateSqlButton_Click(object sender, EventArgs e) { } private void disconnectButton_Click(object sender, EventArgs e) { connection.Close(); UpdateButtons(); } private void UpdateButtons() { bool connected = connection.State == ConnectionState.Open; runSqlButton.Enabled = connected; // validateSqlButton.Enabled = connected; disconnectButton.Enabled = connected; connectButton.Enabled = !connected; serverLabel.Text = String.Format("Server: {0}", connected ? connection.ServerVersion : ""); DbConnectionStringBuilder builder = factory.CreateConnectionStringBuilder(); builder.ConnectionString = connection.ConnectionString; userLabel.Text = String.Format("User: {0}", connected ? builder["userid"] as string : ""); dbLabel.Text = String.Format("Database: {0}", connected ? connection.Database : ""); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/ConnectDialog.Designer.cs0000644000175000017500000002671711127003600031337 0ustar directhexdirecthexnamespace MySql.Data.VisualStudio { partial class ConnectDialog { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.serverName = new System.Windows.Forms.TextBox(); this.database = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); this.password = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.userId = new System.Windows.Forms.TextBox(); this.cancelButton = new System.Windows.Forms.Button(); this.connectButton = new System.Windows.Forms.Button(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.advancedButton = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.simplePanel = new System.Windows.Forms.Panel(); this.connectionProperties = new System.Windows.Forms.PropertyGrid(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.simplePanel.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(2, 10); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(70, 13); this.label1.TabIndex = 0; this.label1.Text = "Server name:"; // // serverName // this.serverName.Location = new System.Drawing.Point(109, 7); this.serverName.Name = "serverName"; this.serverName.Size = new System.Drawing.Size(318, 20); this.serverName.TabIndex = 1; this.serverName.Text = "localhost"; this.serverName.Leave += new System.EventHandler(this.serverName_Leave); // // database // this.database.FormattingEnabled = true; this.database.Location = new System.Drawing.Point(145, 95); this.database.Name = "database"; this.database.Size = new System.Drawing.Size(282, 21); this.database.TabIndex = 9; this.database.Leave += new System.EventHandler(this.database_Leave); this.database.DropDown += new System.EventHandler(this.database_DropDown); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(65, 98); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(56, 13); this.label5.TabIndex = 8; this.label5.Text = "Database:"; // // password // this.password.Location = new System.Drawing.Point(145, 68); this.password.Name = "password"; this.password.Size = new System.Drawing.Size(282, 20); this.password.TabIndex = 5; this.password.Leave += new System.EventHandler(this.password_Leave); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(77, 43); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(44, 13); this.label2.TabIndex = 2; this.label2.Text = "User Id:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(65, 71); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(56, 13); this.label3.TabIndex = 4; this.label3.Text = "Password:"; // // userId // this.userId.Location = new System.Drawing.Point(145, 40); this.userId.Name = "userId"; this.userId.Size = new System.Drawing.Size(282, 20); this.userId.TabIndex = 3; this.userId.Leave += new System.EventHandler(this.userId_Leave); // // cancelButton // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(270, 246); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 3; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; // // connectButton // this.connectButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.connectButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.connectButton.Location = new System.Drawing.Point(189, 246); this.connectButton.Name = "connectButton"; this.connectButton.Size = new System.Drawing.Size(75, 23); this.connectButton.TabIndex = 4; this.connectButton.Text = "Connect"; this.connectButton.UseVisualStyleBackColor = true; // // pictureBox1 // this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Top; this.pictureBox1.Image = global::MySql.Data.VisualStudio.Properties.Resources.sql_editor_banner; this.pictureBox1.Location = new System.Drawing.Point(0, 0); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(450, 89); this.pictureBox1.TabIndex = 5; this.pictureBox1.TabStop = false; // // advancedButton // this.advancedButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.advancedButton.Location = new System.Drawing.Point(351, 246); this.advancedButton.Name = "advancedButton"; this.advancedButton.Size = new System.Drawing.Size(90, 23); this.advancedButton.TabIndex = 10; this.advancedButton.Text = "Advanced >>"; this.advancedButton.UseVisualStyleBackColor = true; this.advancedButton.Click += new System.EventHandler(this.advancedButton_Click); // // label4 // this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label4.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.label4.Location = new System.Drawing.Point(17, 233); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(424, 2); this.label4.TabIndex = 12; // // simplePanel // this.simplePanel.Controls.Add(this.database); this.simplePanel.Controls.Add(this.userId); this.simplePanel.Controls.Add(this.label3); this.simplePanel.Controls.Add(this.label2); this.simplePanel.Controls.Add(this.label5); this.simplePanel.Controls.Add(this.password); this.simplePanel.Controls.Add(this.label1); this.simplePanel.Controls.Add(this.serverName); this.simplePanel.Location = new System.Drawing.Point(12, 100); this.simplePanel.Name = "simplePanel"; this.simplePanel.Size = new System.Drawing.Size(440, 133); this.simplePanel.TabIndex = 13; // // connectionProperties // this.connectionProperties.Location = new System.Drawing.Point(13, 100); this.connectionProperties.Name = "connectionProperties"; this.connectionProperties.Size = new System.Drawing.Size(426, 330); this.connectionProperties.TabIndex = 14; this.connectionProperties.Visible = false; // // ConnectDialog // this.AcceptButton = this.connectButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(450, 284); this.Controls.Add(this.simplePanel); this.Controls.Add(this.label4); this.Controls.Add(this.advancedButton); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.connectButton); this.Controls.Add(this.cancelButton); this.Controls.Add(this.connectionProperties); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ConnectDialog"; this.Text = "Connect to MySQL"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.simplePanel.ResumeLayout(false); this.simplePanel.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox serverName; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button connectButton; private System.Windows.Forms.TextBox password; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox userId; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox database; private System.Windows.Forms.Label label5; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Button advancedButton; private System.Windows.Forms.Label label4; private System.Windows.Forms.Panel simplePanel; private System.Windows.Forms.PropertyGrid connectionProperties; } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/VSCodeEditorWindow.cs0000644000175000017500000002066411127003600030544 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.TextManager.Interop; using System.Windows.Forms; using System.Drawing; namespace MySql.Data.VisualStudio.Editors { internal class VSCodeEditorWindow : NativeWindow, System.Windows.Forms.IMessageFilter, IOleCommandTarget, IDisposable { ServiceBroker services; VSCodeEditor coreEditor; private IOleCommandTarget cmdTarget; private uint cmdTargetCookie; public VSCodeEditorWindow(ServiceBroker sb, UserControl parent) { services = sb; coreEditor = new VSCodeEditor(parent.Handle, services); //Create window IVsCodeWindow win = coreEditor.CodeWindow; cmdTarget = win as IOleCommandTarget; IVsTextView textView; int hr = win.GetPrimaryView(out textView); if (hr != VSConstants.S_OK) Marshal.ThrowExceptionForHR(hr); // assign the window handle IntPtr commandHwnd = textView.GetWindowHandle(); AssignHandle(commandHwnd); //Register priority command target hr = services.VsRegisterPriorityCommandTarget.RegisterPriorityCommandTarget( 0, (IOleCommandTarget)this, out cmdTargetCookie); if (hr != VSConstants.S_OK) Marshal.ThrowExceptionForHR(hr); //Add message filter Application.AddMessageFilter((System.Windows.Forms.IMessageFilter)this); } public VSCodeEditor CoreEditor { get { return coreEditor; } } public void SetWindowPos(Rectangle r) { if (coreEditor == null) return; NativeMethods.SetWindowPos(coreEditor.Hwnd, IntPtr.Zero, r.Left, r.Top, r.Width, r.Height, 0x4); } public void SetFocus() { if (coreEditor == null) return; NativeMethods.SetFocus(coreEditor.Hwnd); } public override void DestroyHandle() { ReleaseHandle(); } #region IDisposable Members public void Dispose() { //Remove message filter Application.RemoveMessageFilter((System.Windows.Forms.IMessageFilter)this); if (services != null) { // Remove this object from the list of the priority command targets. if (cmdTargetCookie != 0) { IVsRegisterPriorityCommandTarget register = services.VsRegisterPriorityCommandTarget; if (null != register) { int hr = register.UnregisterPriorityCommandTarget(cmdTargetCookie); if (hr != VSConstants.S_OK) Marshal.ThrowExceptionForHR(hr); } cmdTargetCookie = 0; } services = null; } if (coreEditor != null) { IVsCodeWindow win = coreEditor.CodeWindow; win.Close(); coreEditor = null; } } #endregion #region IMessageFilter Members /// /// Filters out a message before it is dispatched /// /// The message to be dispatched. You cannot modify this message. /// True to filter the message and stop it from being dispatched; false to allow the message to continue to the next filter or control. public bool PreFilterMessage(ref Message m) { //IVsFilterKeys2 performs advanced keyboard message translation IVsFilterKeys2 filterKeys2 = services.VsFilterKeys2; MSG[] messages = new MSG[1]; messages[0].hwnd = m.HWnd; messages[0].lParam = m.LParam; messages[0].wParam = m.WParam; messages[0].message = (uint)m.Msg; Guid cmdGuid; uint cmdCode; int cmdTranslated; int keyComboStarts; int hr = filterKeys2.TranslateAcceleratorEx(messages, (uint)__VSTRANSACCELEXFLAGS.VSTAEXF_UseTextEditorKBScope //Translates keys using TextEditor key bindings. Equivalent to passing CMDUIGUID_TextEditor, CMDSETID_StandardCommandSet97, and guidKeyDupe for scopes and the VSTAEXF_IgnoreActiveKBScopes flag. | (uint)__VSTRANSACCELEXFLAGS.VSTAEXF_AllowModalState, //By default this function cannot be called when the shell is in a modal state, since command routing is inherently dangerous. However if you must access this in a modal state, specify this flag, but keep in mind that many commands will cause unpredictable behavior if fired. 0, null, out cmdGuid, out cmdCode, out cmdTranslated, out keyComboStarts); if (hr != VSConstants.S_OK) return false; return cmdTranslated != 0; } #endregion #region IOleCommandTarget Members /// /// Executes a specified command or displays help for a command. /// /// Pointer to command group /// Identifier of command to execute /// Options for executing the command /// Pointer to input arguments /// Pointer to command output /// public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { return cmdTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } /// /// Queries the object for the status of one or more commands generated by user interface events. /// /// Pointer to command group /// Number of commands in prgCmds array /// Array of commands /// Pointer to name or status of command /// public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { return cmdTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } #endregion } internal static class NativeMethods { [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] internal static extern IntPtr SetFocus(IntPtr hWnd); [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.U1)] internal static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, int flags); } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/TableNamePromptDialog.resx0000644000175000017500000001327111127003600031604 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/MySplitter.cs0000644000175000017500000000431011127003600027164 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace MySql.Data.VisualStudio.Editors { public class MySplitter : Splitter { public MySplitter() { } protected override void OnPaint(PaintEventArgs e) { Rectangle r = ClientRectangle; SolidBrush brush = new SolidBrush(SystemColors.Control); Pen light = new Pen(SystemColors.ControlLightLight); Pen dark = new Pen(SystemColors.ControlDarkDark); e.Graphics.FillRectangle(brush, r); e.Graphics.DrawLine(light, r.Left + 1, r.Top + 1, r.Left + 1, r.Bottom - 2); e.Graphics.DrawLine(light, r.Left + 1, r.Top + 1, r.Right - 2, r.Top + 1); e.Graphics.DrawLine(dark, r.Right - 1, r.Top, r.Right - 1, r.Bottom - 1); e.Graphics.DrawLine(dark, r.Left, r.Bottom - 1, r.Width, r.Bottom - 1); // base.OnPaint(e); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/ConnectDialog.cs0000644000175000017500000001212511127003600027564 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.Common; namespace MySql.Data.VisualStudio { public partial class ConnectDialog : Form { private int bigSize = 522; private int smallSize = 312; private DbProviderFactory factory; private DbConnectionStringBuilder connectionStringBuilder; private bool populated = false; public ConnectDialog() { InitializeComponent(); factory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient"); if (factory == null) throw new Exception("MySql Data Provider is not correctly registered"); connectionStringBuilder = factory.CreateConnectionStringBuilder(); connectionProperties.SelectedObject = connectionStringBuilder; } public DbConnection Connection { get { DbConnection c = factory.CreateConnection(); c.ConnectionString = connectionStringBuilder.ConnectionString; c.Open(); return c; } set { if (value != null) { connectionStringBuilder.ConnectionString = value.ConnectionString; Rebind(); } } } private void advancedButton_Click(object sender, EventArgs e) { this.SuspendLayout(); if (this.Size.Height > 400) { advancedButton.Text = "Advanced >>"; Height = smallSize; simplePanel.Visible = true; connectionProperties.Visible = false; Rebind(); } else { advancedButton.Text = "Simple <<"; Height = bigSize; simplePanel.Visible = false; connectionProperties.Visible = true; } this.ResumeLayout(); } private void Rebind() { serverName.Text = connectionStringBuilder["server"] as string; userId.Text = connectionStringBuilder["userid"] as string; password.Text = connectionStringBuilder["password"] as string; database.Text = connectionStringBuilder["database"] as string; } private void database_DropDown(object sender, EventArgs e) { if (populated) return; populated = true; try { using (DbConnection c = factory.CreateConnection()) { c.ConnectionString = connectionStringBuilder.ConnectionString; c.Open(); DbCommand cmd = c.CreateCommand(); cmd.CommandText = "SHOW DATABASES"; using (DbDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) database.Items.Add(reader.GetString(0)); } } } catch (Exception) { } } private void serverName_Leave(object sender, EventArgs e) { connectionStringBuilder["server"] = serverName.Text.Trim(); } private void userId_Leave(object sender, EventArgs e) { connectionStringBuilder["userid"] = userId.Text.Trim(); } private void password_Leave(object sender, EventArgs e) { connectionStringBuilder["password"] = password.Text.Trim(); } private void database_Leave(object sender, EventArgs e) { connectionStringBuilder["database"] = database.Text.Trim(); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/GenerateChangeScriptDialog.Designer.cs0000644000175000017500000001133011127003600033754 0ustar directhexdirecthexnamespace MySql.Data.VisualStudio.Editors { partial class GenerateChangeScriptDialog { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.sqlBox = new System.Windows.Forms.TextBox(); this.noButton = new System.Windows.Forms.Button(); this.yesButton = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(14, 10); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(94, 15); this.label1.TabIndex = 0; this.label1.Text = "Current changes"; // // sqlBox // this.sqlBox.Location = new System.Drawing.Point(17, 42); this.sqlBox.Multiline = true; this.sqlBox.Name = "sqlBox"; this.sqlBox.ReadOnly = true; this.sqlBox.Size = new System.Drawing.Size(577, 292); this.sqlBox.TabIndex = 1; // // noButton // this.noButton.Location = new System.Drawing.Point(507, 355); this.noButton.Name = "noButton"; this.noButton.Size = new System.Drawing.Size(87, 27); this.noButton.TabIndex = 2; this.noButton.Text = "No"; this.noButton.UseVisualStyleBackColor = true; this.noButton.Click += new System.EventHandler(this.noButton_Click); // // yesButton // this.yesButton.Location = new System.Drawing.Point(413, 355); this.yesButton.Name = "yesButton"; this.yesButton.Size = new System.Drawing.Size(87, 27); this.yesButton.TabIndex = 3; this.yesButton.Text = "Yes"; this.yesButton.UseVisualStyleBackColor = true; this.yesButton.Click += new System.EventHandler(this.yesButton_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(119, 361); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(239, 15); this.label2.TabIndex = 4; this.label2.Text = "Do you want to save these changes to a file?"; // // GenerateChangeScriptDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(609, 396); this.Controls.Add(this.label2); this.Controls.Add(this.yesButton); this.Controls.Add(this.noButton); this.Controls.Add(this.sqlBox); this.Controls.Add(this.label1); this.Font = new System.Drawing.Font("Segoe UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "GenerateChangeScriptDialog"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Save Change Script"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox sqlBox; private System.Windows.Forms.Button noButton; private System.Windows.Forms.Button yesButton; private System.Windows.Forms.Label label2; } }mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/UDFEditor.resx0000644000175000017500000001326611127003600027223 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/GenerateChangeScriptDialog.resx0000644000175000017500000001326611127003600032603 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Editors/GenerateChangeScriptDialog.cs0000644000175000017500000000520011127003600032214 0ustar directhexdirecthex// Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace MySql.Data.VisualStudio.Editors { partial class GenerateChangeScriptDialog : Form { string sql; public GenerateChangeScriptDialog(TableNode node) { sql = node.GetSaveSql(); InitializeComponent(); sqlBox.Text = sql; } private void yesButton_Click(object sender, EventArgs e) { SaveFileDialog dlg = new SaveFileDialog(); dlg.DefaultExt = ".sql"; dlg.CheckPathExists = true; dlg.Filter = "SQL Files|*.sql|All Files|*.*"; dlg.OverwritePrompt = true; dlg.Title = "Save Change Script"; dlg.AutoUpgradeEnabled = false; dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); DialogResult result = dlg.ShowDialog(); if (DialogResult.OK == result) WriteOutChangeScript(dlg.FileName); Close(); } private void noButton_Click(object sender, EventArgs e) { Close(); } private void WriteOutChangeScript(string fileName) { StreamWriter sw = new StreamWriter(fileName); sw.Write(sql); sw.Flush(); sw.Close(); } } } mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Templates/0000755000175000017500000000000011127003600025050 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.VisualStudio/Templates/MySqlDataProviderPackage.vsdir0000644000175000017500000000017111127003600032746 0ustar directhexdirecthexMySQL Script.mysql|{79A115C9-B133-4891-9E7B-242509DAD272}|#106|80|#109|{79A115C9-B133-4891-9E7B-242509DAD272}|#401|0|#107mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Templates/MySQL Script.mysql0000644000175000017500000000000211127003600030321 0ustar directhexdirecthex mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Targets/0000755000175000017500000000000011127003600024523 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.VisualStudio/Targets/VS2010.targets0000644000175000017500000000027311127003600026753 0ustar directhexdirecthex mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Targets/VS2008.targets0000644000175000017500000000027211127003600026761 0ustar directhexdirecthex mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Targets/blank.targets0000644000175000017500000000012111127003600027177 0ustar directhexdirecthex mysql-connector-net-6.4.3/Source/MySql.VisualStudio/Targets/VS.targets0000644000175000017500000000012111127003600026440 0ustar directhexdirecthex mysql-connector-net-6.4.3/Source/MySql.Data.Entity/0000755000175000017500000000000011127003600022603 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Data.Entity/Generators/0000755000175000017500000000000011127003600024714 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Data.Entity/Generators/SelectGenerator.cs0000644000175000017500000003144611127003600030341 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Text; using System.Diagnostics; using System.Data.Common.CommandTrees; using System.Data.Metadata.Edm; using System.Collections.Generic; using MySql.Data.MySqlClient; using System.Data; namespace MySql.Data.Entity { class SelectGenerator : SqlGenerator { Stack selectStatements = new Stack(); #region Properties private SelectStatement CurrentSelect { get { return selectStatements.Count == 0 ? null : selectStatements.Peek(); } } #endregion public override string GenerateSQL(DbCommandTree tree) { DbQueryCommandTree commandTree = tree as DbQueryCommandTree; SqlFragment fragment = null; DbExpression e = commandTree.Query; switch (commandTree.Query.ExpressionKind) { case DbExpressionKind.Project: fragment = e.Accept(this); Debug.Assert(fragment is SelectStatement); break; } return fragment.ToString(); } public override SqlFragment Visit(DbDistinctExpression expression) { SelectStatement select = VisitInputExpressionEnsureSelect(expression.Argument, null, null); select.IsDistinct = true; return select; } public override SqlFragment Visit(DbFilterExpression expression) { SelectStatement select = VisitInputExpressionEnsureSelect(expression.Input.Expression, expression.Input.VariableName, expression.Input.VariableType); select = WrapIfNotCompatible(select, expression.ExpressionKind); select.Where = expression.Predicate.Accept(this); return select; } public override SqlFragment Visit(DbGroupByExpression expression) { // first process the input DbGroupExpressionBinding e = expression.Input; SelectStatement innerSelect = VisitInputExpressionEnsureSelect(e.Expression, e.VariableName, e.VariableType); scope.Add(e.GroupVariableName, innerSelect); SelectStatement select = WrapIfNotCompatible(innerSelect, expression.ExpressionKind); CollectionType ct = (CollectionType)expression.ResultType.EdmType; RowType rt = (RowType)ct.TypeUsage.EdmType; int propIndex = 0; foreach (DbExpression key in expression.Keys) { var fragment = key.Accept(this); select.AddGroupBy(fragment); propIndex++; var colFragment = fragment as ColumnFragment; if (colFragment != null) { colFragment = colFragment.Clone(); colFragment.ColumnAlias = String.Format("K{0}", propIndex); select.Columns.Add(colFragment); } } for (int agg = 0; agg < expression.Aggregates.Count; agg++) { DbAggregate a = expression.Aggregates[agg]; DbFunctionAggregate fa = a as DbFunctionAggregate; if (fa == null) throw new NotSupportedException(); string alias = rt.Properties[propIndex++].Name; ColumnFragment functionCol = new ColumnFragment(null, null); functionCol.Literal = HandleFunction(fa, a.Arguments[0].Accept(this)); functionCol.ColumnAlias = alias; select.Columns.Add(functionCol); } return select; } private SqlFragment HandleFunction(DbFunctionAggregate fa, SqlFragment arg) { Debug.Assert(fa.Arguments.Count == 1); if (fa.Function.NamespaceName != "Edm") throw new NotSupportedException(); FunctionFragment fragment = new FunctionFragment(); fragment.Name = fa.Function.Name; if (fa.Function.Name == "BigCount") fragment.Name = "COUNT"; else fragment.Name = fa.Function.Name.ToUpperInvariant(); fragment.Distinct = fa.Distinct; fragment.Argmument = arg; return fragment; //return new CastExpression(aggregate, GetDbType(functionAggregate.ResultType.EdmType)); } public override SqlFragment Visit(DbCrossJoinExpression expression) { Debug.Assert(expression.Inputs.Count == 2); return HandleJoinExpression(expression.Inputs[0], expression.Inputs[1], expression.ExpressionKind, null); } public override SqlFragment Visit(DbJoinExpression expression) { return HandleJoinExpression(expression.Left, expression.Right, expression.ExpressionKind, expression.JoinCondition); } private SqlFragment HandleJoinExpression(DbExpressionBinding left, DbExpressionBinding right, DbExpressionKind joinType, DbExpression joinCondition) { JoinFragment join = new JoinFragment(); join.JoinType = Metadata.GetOperator(joinType); join.Left = VisitInputExpression(left.Expression, left.VariableName, left.VariableType); join.Left = WrapJoinInputIfNecessary(join.Left, false); join.Right = VisitInputExpression(right.Expression, right.VariableName, right.VariableType); join.Right = WrapJoinInputIfNecessary(join.Right, true); if (join.Right is SelectStatement) { SelectStatement select = join.Right as SelectStatement; if (select.IsWrapped) select.Name = right.VariableName; } // now handle the ON case if (joinCondition != null) join.Condition = joinCondition.Accept(this); return join; } public SelectStatement WrapIfNotCompatible(SelectStatement select, DbExpressionKind expressionKind) { if (select.IsCompatible(expressionKind)) return select; SelectStatement newSelect = new SelectStatement(); select.Wrap(scope); select.Scoped = true; newSelect.From = select; return newSelect; } private InputFragment WrapJoinInputIfNecessary(InputFragment fragment, bool isRightPart) { if (fragment is SelectStatement || fragment is UnionFragment) { fragment.Wrap(scope); fragment.Scoped = true; } else if (fragment is JoinFragment && isRightPart) { SelectStatement select = new SelectStatement(); select.From = fragment; select.Name = fragment.Name; select.Wrap(scope); return select; } return fragment; } public override SqlFragment Visit(DbNewInstanceExpression expression) { Debug.Assert(expression.ResultType.EdmType is CollectionType); SelectStatement s = new SelectStatement(); ColumnFragment c = new ColumnFragment(null, null); if (expression.Arguments.Count != 0) c.Literal = (LiteralFragment)expression.Arguments[0].Accept(this); else c.Literal = new LiteralFragment("NULL"); c.ColumnAlias = "X"; s.Columns.Add(c); return s; } public override SqlFragment Visit(DbProjectExpression expression) { SelectStatement select = VisitInputExpressionEnsureSelect(expression.Input.Expression, expression.Input.VariableName, expression.Input.VariableType); // see if we need to wrap this select inside a new select select = WrapIfNotCompatible(select, expression.ExpressionKind); Debug.Assert(expression.Projection is DbNewInstanceExpression); VisitNewInstanceExpression(select, expression.Projection as DbNewInstanceExpression); return select; } private SelectStatement VisitInputExpressionEnsureSelect(DbExpression e, string name, TypeUsage type) { InputFragment fragment = VisitInputExpression(e, name, type); if (fragment is SelectStatement) return (fragment as SelectStatement); SelectStatement s = new SelectStatement(); // if the fragment is a union then it needs to be wrapped if (fragment is UnionFragment) (fragment as UnionFragment).Wrap(scope); s.From = fragment; return s; } public override SqlFragment Visit(DbElementExpression expression) { SelectStatement s = VisitInputExpressionEnsureSelect(expression.Argument, null, null); s.Wrap(scope); return s; } public override SqlFragment Visit(DbSortExpression expression) { SelectStatement select = VisitInputExpressionEnsureSelect(expression.Input.Expression, expression.Input.VariableName, expression.Input.VariableType); select = WrapIfNotCompatible(select, expression.ExpressionKind); foreach (DbSortClause sortClause in expression.SortOrder) { select.AddOrderBy(new SortFragment( sortClause.Expression.Accept(this), sortClause.Ascending)); } return select; } public override SqlFragment Visit(DbLimitExpression expression) { SelectStatement select = (SelectStatement)VisitInputExpressionEnsureSelect( expression.Argument, null, null); select = WrapIfNotCompatible(select, expression.ExpressionKind); select.Limit = expression.Limit.Accept(this); return select; } public override SqlFragment Visit(DbSkipExpression expression) { SelectStatement select = VisitInputExpressionEnsureSelect(expression.Input.Expression, expression.Input.VariableName, expression.Input.VariableType); select = WrapIfNotCompatible(select, DbExpressionKind.Sort); foreach (DbSortClause sortClause in expression.SortOrder) { select.AddOrderBy( new SortFragment(sortClause.Expression.Accept(this), sortClause.Ascending)); } // if we wrapped above, then this wrap will not create a new one so there // is no harm in calling it select = WrapIfNotCompatible(select, expression.ExpressionKind); select.Skip = expression.Count.Accept(this); return select; } public override SqlFragment Visit(DbUnionAllExpression expression) { UnionFragment f = new UnionFragment(); Debug.Assert(expression.Left is DbProjectExpression); Debug.Assert(expression.Right is DbProjectExpression); SelectStatement left = VisitInputExpressionEnsureSelect(expression.Left, null, null); Debug.Assert(left.Name == null); // left.Wrap(null); SelectStatement right = VisitInputExpressionEnsureSelect(expression.Right, null, null); Debug.Assert(right.Name == null); // right.Wrap(null); f.Left = left; f.Right = right; return f; } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Generators/FunctionProcessor.cs0000644000175000017500000001664211127003600030741 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2010 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Common.CommandTrees; using System.Diagnostics; namespace MySql.Data.Entity { class FunctionProcessor { private static readonly Dictionary bitwiseFunctions = new Dictionary(); private static readonly Dictionary dateFunctions = new Dictionary(); private static readonly Dictionary stringFunctions = new Dictionary(); private static readonly Dictionary mathFunctions = new Dictionary(); private SqlGenerator callingGenerator; static FunctionProcessor() { bitwiseFunctions.Add("BitwiseAnd", "&"); bitwiseFunctions.Add("BitwiseNot", "!"); bitwiseFunctions.Add("BitwiseOr", "|"); bitwiseFunctions.Add("BitwiseXor", "^"); dateFunctions.Add("CurrentDateTime", "NOW()"); dateFunctions.Add("Year", "YEAR({0})"); dateFunctions.Add("Month", "MONTH({0})"); dateFunctions.Add("Day", "DAY({0})"); dateFunctions.Add("Hour", "HOUR({0})"); dateFunctions.Add("Minute", "MINUTE({0})"); dateFunctions.Add("Second", "SECOND({0})"); stringFunctions.Add("Concat", "CONCAT({0}, {1})"); stringFunctions.Add("IndexOf", "LOCATE({0}, {1})"); stringFunctions.Add("Left", "LEFT({0}, {1})"); stringFunctions.Add("Length", "LENGTH({0})"); stringFunctions.Add("LTrim", "LTRIM({0})"); stringFunctions.Add("Replace", "REPLACE({0}, {1}, {2})"); stringFunctions.Add("Reverse", "REVERSE({0})"); stringFunctions.Add("Right", "RIGHT({0}, {1})"); stringFunctions.Add("RTrim", "RTRIM({0})"); stringFunctions.Add("Substring", "SUBSTR({0}, {1}, {2})"); stringFunctions.Add("ToLower", "LOWER({0})"); stringFunctions.Add("ToUpper", "UPPER({0})"); stringFunctions.Add("Trim", "TRIM({0})"); mathFunctions.Add("Abs", "ABS({0})"); mathFunctions.Add("Ceiling", "CEILING({0})"); mathFunctions.Add("Floor", "FLOOR({0})"); mathFunctions.Add("Round", "ROUND"); } public SqlFragment Generate(DbFunctionExpression e, SqlGenerator caller) { callingGenerator = caller; if (bitwiseFunctions.ContainsKey(e.Function.Name)) return BitwiseFunction(e); else if (dateFunctions.ContainsKey(e.Function.Name)) return GenericFunction(dateFunctions, e); else if (stringFunctions.ContainsKey(e.Function.Name)) return GenericFunction(stringFunctions, e); else if (mathFunctions.ContainsKey(e.Function.Name)) return GenericFunction(mathFunctions, e); else return UserDefinedFunction(e); } private SqlFragment UserDefinedFunction(DbFunctionExpression e) { FunctionFragment f = new FunctionFragment(); f.Name = Metadata.TryGetValueMetadataProperty(e.Function, "StoreFunctionNameAttribute"); if (String.IsNullOrEmpty(f.Name)) f.Name = e.Function.Name; f.Quoted = !Metadata.TryGetValueMetadataProperty(e.Function, "BuiltInAttribute"); bool isFuncNiladic = Metadata.TryGetValueMetadataProperty(e.Function, "NiladicFunctionAttribute"); if (isFuncNiladic && e.Arguments.Count > 0) throw new InvalidOperationException("Niladic functions cannot have parameters"); ListFragment list = new ListFragment(); string delimiter = ""; foreach (DbExpression arg in e.Arguments) { if (delimiter.Length > 0) list.Append(new LiteralFragment(delimiter)); list.Append(arg.Accept(callingGenerator)); delimiter = ", "; } f.Argmument = list; return f; } private SqlFragment BitwiseFunction(DbFunctionExpression e) { StringBuilder sql = new StringBuilder(); int arg = 0; if (e.Arguments.Count > 1) sql.AppendFormat("({0})", e.Arguments[arg++].Accept(callingGenerator)); sql.AppendFormat(" {0} ({1})", bitwiseFunctions[e.Function.Name], e.Arguments[arg].Accept(callingGenerator)); return new LiteralFragment(sql.ToString()); } private SqlFragment GenericFunction(Dictionary funcs, DbFunctionExpression e) { SqlFragment[] frags = new SqlFragment[e.Arguments.Count]; for (int i=0; i < e.Arguments.Count; i++) frags[i] = e.Arguments[i].Accept(callingGenerator); string sql; switch (e.Function.Name) { case "Round": // Special handling for Round as it has more than one signature. sql = HandleFunctionRound(e); break; default: sql = String.Format(funcs[e.Function.Name], frags); break; } return new LiteralFragment(sql); } private string HandleFunctionRound(DbFunctionExpression e) { StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.Append(mathFunctions[e.Function.Name]); sqlBuilder.Append("("); Debug.Assert(e.Arguments.Count <= 2, "Round should have at most 2 arguments"); sqlBuilder.Append(e.Arguments[0].Accept(callingGenerator)); sqlBuilder.Append(", "); if (e.Arguments.Count > 1) { sqlBuilder.Append(e.Arguments[1].Accept(callingGenerator)); } else { sqlBuilder.Append("0"); } sqlBuilder.Append(")"); return sqlBuilder.ToString(); } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Generators/FunctionFragment.cs0000644000175000017500000001210311127003600030511 0ustar directhexdirecthex// Copyright (C) 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Common.CommandTrees; namespace MySql.Data.Entity { class FunctionProcessor { private static readonly Dictionary bitwiseFunctions = new Dictionary(); private static readonly Dictionary dateFunctions = new Dictionary(); private static readonly Dictionary stringFunctions = new Dictionary(); private static readonly Dictionary mathFunctions = new Dictionary(); private SqlGenerator callingGenerator; static FunctionProcessor() { bitwiseFunctions.Add("BitwiseAnd", "&"); bitwiseFunctions.Add("BitwiseNot", "!"); bitwiseFunctions.Add("BitwiseOr", "|"); bitwiseFunctions.Add("BitwiseXor", "^"); dateFunctions.Add("CurrentDateTime", "NOW()"); dateFunctions.Add("Year", "YEAR({0})"); dateFunctions.Add("Month", "MONTH({0})"); dateFunctions.Add("Day", "DAY({0})"); dateFunctions.Add("Hour", "HOUR({0})"); dateFunctions.Add("Minute", "MINUTE({0})"); dateFunctions.Add("Second", "SECOND({0})"); stringFunctions.Add("Concat", "CONCAT({0}, {1})"); stringFunctions.Add("IndexOf", "LOCATE({0}, {1})"); stringFunctions.Add("Left", "LEFT({0}, {1})"); stringFunctions.Add("Length", "LENGTH({0})"); stringFunctions.Add("LTrim", "LTRIM({0})"); stringFunctions.Add("Replace", "REPLACE({0}, {1}, {2})"); stringFunctions.Add("Reverse", "REVERSE({0})"); stringFunctions.Add("Right", "RIGHT({0}, {1})"); stringFunctions.Add("RTrim", "RTRIM({0})"); stringFunctions.Add("Substring", "SUBSTR({0}, {1}, {2})"); stringFunctions.Add("ToLower", "LOWER({0})"); stringFunctions.Add("ToUpper", "UPPER({0})"); stringFunctions.Add("Trim", "TRIM({0})"); mathFunctions.Add("Abs", "ABS({0})"); mathFunctions.Add("Ceiling", "CEILING({0})"); mathFunctions.Add("Floor", "FLOOR({0})"); mathFunctions.Add("Round", "ROUND({0})"); } public SqlFragment Generate(DbFunctionExpression e, SqlGenerator caller) { callingGenerator = caller; if (bitwiseFunctions.ContainsKey(e.Function.Name)) return BitwiseFunction(e); else if (dateFunctions.ContainsKey(e.Function.Name)) return GenericFunction(dateFunctions, e); else if (stringFunctions.ContainsKey(e.Function.Name)) return GenericFunction(stringFunctions, e); else if (mathFunctions.ContainsKey(e.Function.Name)) return GenericFunction(mathFunctions, e); return null; } private SqlFragment BitwiseFunction(DbFunctionExpression e) { StringBuilder sql = new StringBuilder(); int arg = 0; if (e.Arguments.Count > 1) sql.AppendFormat("({0})", e.Arguments[arg++].Accept(callingGenerator)); sql.AppendFormat(" {0} ({1})", bitwiseFunctions[e.Function.Name], e.Arguments[arg].Accept(callingGenerator)); return new LiteralFragment(sql.ToString()); } private SqlFragment GenericFunction(Dictionary funcs, DbFunctionExpression e) { SqlFragment[] frags = new SqlFragment[e.Arguments.Count]; for (int i=0; i < e.Arguments.Count; i++) frags[i] = e.Arguments[i].Accept(callingGenerator); string sql = String.Format(funcs[e.Function.Name], frags); return new LiteralFragment(sql); } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Generators/FunctionGenerator.cs0000644000175000017500000000476511127003600030713 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Common.CommandTrees; using System.Data.Metadata.Edm; using System.Data; namespace MySql.Data.Entity { class FunctionGenerator : SqlGenerator { public CommandType CommandType { get; private set; } public override string GenerateSQL(DbCommandTree commandTree) { DbFunctionCommandTree tree = (commandTree as DbFunctionCommandTree); EdmFunction function = tree.EdmFunction; CommandType = CommandType.StoredProcedure; string cmdText = (string)function.MetadataProperties["CommandTextAttribute"].Value; if (String.IsNullOrEmpty(cmdText)) { string schema = (string)function.MetadataProperties["Schema"].Value; if (String.IsNullOrEmpty(schema)) schema = function.NamespaceName; string functionName = (string)function.MetadataProperties["StoreFunctionNameAttribute"].Value; if (String.IsNullOrEmpty(functionName)) functionName = function.Name; return String.Format("`{0}`", functionName); } else { CommandType = CommandType.Text; return cmdText; } } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Generators/SymbolTable.cs0000644000175000017500000000135411127003600027463 0ustar directhexdirecthexusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace MySql.Data.Entity { class SymbolTable { public SymbolTable() { Symbols = new Dictionary(); } private Dictionary Symbols { get; set; } public void Add(string name, SqlFragment fragment) { Debug.Assert(!Symbols.ContainsKey(name)); if (fragment.Name == null) fragment.Name = name; Symbols.Add(name, fragment); } public SqlFragment Lookup(string name) { return Symbols[name]; } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Generators/InsertGenerator.cs0000644000175000017500000000540511127003600030362 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Text; using System.Collections.Generic; using System.Data.Common.CommandTrees; using System.Data.Metadata.Edm; using MySql.Data.MySqlClient; using System.Data.Common; using System.Diagnostics; using System; namespace MySql.Data.Entity { class InsertGenerator : SqlGenerator { public override string GenerateSQL(DbCommandTree tree) { DbInsertCommandTree commandTree = tree as DbInsertCommandTree; InsertStatement statement = new InsertStatement(); DbExpressionBinding e = commandTree.Target; statement.Target = (InputFragment)e.Expression.Accept(this); foreach (DbSetClause setClause in commandTree.SetClauses) statement.Sets.Add(setClause.Property.Accept(this)); foreach (DbSetClause setClause in commandTree.SetClauses) { DbExpression value = setClause.Value; SqlFragment valueFragment = value.Accept(this); statement.Values.Add(valueFragment); if (values == null) values = new Dictionary(); if (value.ExpressionKind != DbExpressionKind.Null) { EdmMember property = ((DbPropertyExpression)setClause.Property).Property; values.Add(property, valueFragment); } } if (commandTree.Returning != null) statement.ReturningSelect = GenerateReturningSql(commandTree, commandTree.Returning); return statement.ToString(); } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Generators/SqlGenerator.cs0000644000175000017500000004261311127003600027657 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Diagnostics; using System.Text; using System.Data; using System.Collections.Generic; using System.Data.Common.CommandTrees; using System.Data.Metadata.Edm; using MySql.Data.MySqlClient; using System.Globalization; namespace MySql.Data.Entity { abstract class SqlGenerator : DbExpressionVisitor { protected string tabs = String.Empty; private int parameterCount = 1; protected Scope scope = new Scope(); protected int propertyLevel; protected Dictionary values; public SqlGenerator() { Parameters = new List(); } #region Properties public List Parameters { get; private set; } // protected SymbolTable Symbols { get; private set; } #endregion public virtual string GenerateSQL(DbCommandTree commandTree) { throw new NotImplementedException(); } protected string CreateUniqueParameterName() { return String.Format("@gp{0}", parameterCount++); } #region DbExpressionVisitor Base Implementations public override SqlFragment Visit(DbVariableReferenceExpression expression) { PropertyFragment fragment = new PropertyFragment(); fragment.Properties.Add(expression.VariableName); return fragment; } public override SqlFragment Visit(DbPropertyExpression expression) { propertyLevel++; PropertyFragment fragment = expression.Instance.Accept(this) as PropertyFragment; fragment.Properties.Add(expression.Property.Name); propertyLevel--; // if we are not at the top level property then just return if (propertyLevel > 0) return fragment; ColumnFragment column = new ColumnFragment(null, fragment.LastProperty); column.PropertyFragment = fragment; InputFragment input = scope.FindInputFromProperties(fragment); if (input != null) column.TableName = input.Name; // now we need to check if our column name was possibly renamed if (input is TableFragment) return column; SelectStatement select = input as SelectStatement; UnionFragment union = input as UnionFragment; if (select != null) select.HasDifferentNameForColumn(column); else if (union != null) union.HasDifferentNameForColumn(column); // input is a table, selectstatement, or unionstatement return column; } public override SqlFragment Visit(DbScanExpression expression) { EntitySetBase target = expression.Target; TableFragment fragment = new TableFragment(); MetadataProperty property; bool propExists = target.MetadataProperties.TryGetValue("DefiningQuery", true, out property); if (propExists && property.Value != null) fragment.DefiningQuery = new LiteralFragment(property.Value as string); else { fragment.Schema = target.EntityContainer.Name; fragment.Table = target.Name; propExists = target.MetadataProperties.TryGetValue("Schema", true, out property); if (propExists && property.Value != null) fragment.Schema = property.Value as string; propExists = target.MetadataProperties.TryGetValue("Table", true, out property); if (propExists && property.Value != null) fragment.Table = property.Value as string; } return fragment; } public override SqlFragment Visit(DbParameterReferenceExpression expression) { return new LiteralFragment("@" + expression.ParameterName); } public override SqlFragment Visit(DbNotExpression expression) { SqlFragment f = expression.Argument.Accept(this); Debug.Assert(f is NegatableFragment); NegatableFragment nf = f as NegatableFragment; nf.Negate(); return nf; } public override SqlFragment Visit(DbIsEmptyExpression expression) { ExistsFragment f = new ExistsFragment(expression.Argument.Accept(this)); f.Negate(); return f; } public override SqlFragment Visit(DbFunctionExpression expression) { FunctionProcessor gen = new FunctionProcessor(); return gen.Generate(expression, this); } public override SqlFragment Visit(DbConstantExpression expression) { PrimitiveTypeKind pt = ((PrimitiveType)expression.ResultType.EdmType).PrimitiveTypeKind; string literal = Metadata.GetNumericLiteral(pt, expression.Value); if (literal != null) return new LiteralFragment(literal); else if (pt == PrimitiveTypeKind.Boolean) return new LiteralFragment((bool)expression.Value ? "1" : "0"); else { // use a parameter for non-numeric types so we get proper // quoting MySqlParameter p = new MySqlParameter(); p.ParameterName = CreateUniqueParameterName(); p.DbType = Metadata.GetDbType(expression.ResultType); p.Value = Metadata.NormalizeValue(expression.ResultType, expression.Value); Parameters.Add(p); return new LiteralFragment(p.ParameterName); } } public override SqlFragment Visit(DbComparisonExpression expression) { return VisitBinaryExpression(expression.Left, expression.Right, Metadata.GetOperator(expression.ExpressionKind)); } public override SqlFragment Visit(DbAndExpression expression) { return VisitBinaryExpression(expression.Left, expression.Right, "AND"); } public override SqlFragment Visit(DbOrExpression expression) { return VisitBinaryExpression(expression.Left, expression.Right, "OR"); } public override SqlFragment Visit(DbCastExpression expression) { //TODO: handle casting return expression.Argument.Accept(this); } public override SqlFragment Visit(DbLikeExpression expression) { LikeFragment f = new LikeFragment(); f.Argument = expression.Argument.Accept(this); f.Pattern = expression.Pattern.Accept(this); if (expression.Escape.ExpressionKind != DbExpressionKind.Null) f.Escape = expression.Escape.Accept(this); return f; } public override SqlFragment Visit(DbCaseExpression expression) { CaseFragment c = new CaseFragment(); Debug.Assert(expression.When.Count == expression.Then.Count); for (int i = 0; i < expression.When.Count; ++i) { c.When.Add(expression.When[i].Accept(this)); c.Then.Add(expression.Then[i].Accept(this)); } if (expression.Else != null && !(expression.Else is DbNullExpression)) c.Else = expression.Else.Accept(this); return c; } public override SqlFragment Visit(DbIsNullExpression expression) { IsNullFragment f = new IsNullFragment(); f.Argument = expression.Argument.Accept(this); return f; } public override SqlFragment Visit(DbIntersectExpression expression) { throw new NotSupportedException(); } public override SqlFragment Visit(DbNullExpression expression) { return new LiteralFragment("NULL"); } public override SqlFragment Visit(DbArithmeticExpression expression) { if (expression.ExpressionKind == DbExpressionKind.UnaryMinus) { ListFragment f = new ListFragment(); f.Append("-("); f.Append(expression.Arguments[0].Accept(this)); f.Append(")"); return f; } string op = String.Empty; switch (expression.ExpressionKind) { case DbExpressionKind.Divide: op = "/"; break; case DbExpressionKind.Minus: op = "-"; break; case DbExpressionKind.Modulo: op = "%"; break; case DbExpressionKind.Multiply: op = "*"; break; case DbExpressionKind.Plus: op = "+"; break; default: throw new NotSupportedException(); } return VisitBinaryExpression(expression.Arguments[0], expression.Arguments[1], op); } protected void VisitNewInstanceExpression(SelectStatement select, DbNewInstanceExpression expression) { Debug.Assert(expression.ResultType.EdmType is RowType); RowType row = expression.ResultType.EdmType as RowType; for (int i = 0; i < expression.Arguments.Count; i++) { ColumnFragment col; SqlFragment fragment = expression.Arguments[i].Accept(this); if (fragment is ColumnFragment) col = fragment as ColumnFragment; else { col = new ColumnFragment(null, null); col.Literal = fragment; } col.ColumnAlias = row.Properties[i].Name; select.Columns.Add(col); } } public override SqlFragment Visit(DbTreatExpression expression) { throw new NotSupportedException(); } public override SqlFragment Visit(DbRelationshipNavigationExpression expression) { throw new NotSupportedException(); } public override SqlFragment Visit(DbRefExpression expression) { throw new NotSupportedException(); } public override SqlFragment Visit(DbOfTypeExpression expression) { throw new NotSupportedException(); } public override SqlFragment Visit(DbIsOfExpression expression) { throw new NotSupportedException(); } public override SqlFragment Visit(DbRefKeyExpression expression) { throw new NotSupportedException(); } public override SqlFragment Visit(DbEntityRefExpression expression) { throw new NotSupportedException(); } public override SqlFragment Visit(DbExceptExpression expression) { throw new NotSupportedException(); } public override SqlFragment Visit(DbExpression expression) { throw new InvalidOperationException(); } public override SqlFragment Visit(DbDerefExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbApplyExpression expression) { throw new NotSupportedException(); } #endregion #region DBExpressionVisitor methods normally overridden public override SqlFragment Visit(DbUnionAllExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbSortExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbSkipExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbQuantifierExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbProjectExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbNewInstanceExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbLimitExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbJoinExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbGroupByExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbFilterExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbElementExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbDistinctExpression expression) { throw new NotImplementedException(); } public override SqlFragment Visit(DbCrossJoinExpression expression) { throw new NotImplementedException(); } #endregion protected InputFragment VisitInputExpression(DbExpression e, string name, TypeUsage type) { SqlFragment f = e.Accept(this); Debug.Assert(f is InputFragment); InputFragment inputFragment = f as InputFragment; inputFragment.Name = name; if (inputFragment is TableFragment && type != null) (inputFragment as TableFragment).Type = type; if (name != null) scope.Add(name, inputFragment); return inputFragment; } protected SelectStatement GenerateReturningSql(DbModificationCommandTree tree, DbExpression returning) { SelectStatement select = new SelectStatement(); Debug.Assert(returning is DbNewInstanceExpression); VisitNewInstanceExpression(select, returning as DbNewInstanceExpression); select.From = (InputFragment)tree.Target.Expression.Accept(this); ListFragment where = new ListFragment(); where.Append(" row_count() > 0"); EntitySetBase table = ((DbScanExpression)tree.Target.Expression).Target; bool foundIdentity = false; foreach (EdmMember keyMember in table.ElementType.KeyMembers) { SqlFragment value; if (!values.TryGetValue(keyMember, out value)) { if (foundIdentity) throw new NotSupportedException(); foundIdentity = true; value = new LiteralFragment("last_insert_id()"); } where.Append(String.Format(" AND `{0}`=", keyMember)); where.Append(value); } select.Where = where; return select; } #region Private Methods SqlFragment VisitBinaryExpression(DbExpression left, DbExpression right, string op) { BinaryFragment f = new BinaryFragment(); f.Operator = op; f.Left = left.Accept(this); f.WrapLeft = ShouldWrapExpression(left); f.Right = right.Accept(this); f.WrapRight = ShouldWrapExpression(right); return f; } private bool ShouldWrapExpression(DbExpression e) { switch (e.ExpressionKind) { case DbExpressionKind.Property: case DbExpressionKind.ParameterReference: case DbExpressionKind.Constant: return false; } return true; } #endregion } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Generators/Scope.cs0000644000175000017500000000656611127003600026331 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace MySql.Data.Entity { class Scope { private Dictionary scopeTable = new Dictionary(); public void Add(string name, InputFragment fragment) { scopeTable.Add(name, fragment); } public void Remove(InputFragment fragment) { if (fragment == null) return; if (fragment.Name != null) scopeTable.Remove(fragment.Name); if (fragment is SelectStatement) Remove((fragment as SelectStatement).From); else if (fragment is JoinFragment) { JoinFragment j = fragment as JoinFragment; Remove(j.Left); Remove(j.Right); } else if (fragment is UnionFragment) { UnionFragment u = fragment as UnionFragment; Remove(u.Left); Remove(u.Right); } } public InputFragment GetFragment(string name) { if (!scopeTable.ContainsKey(name)) return null; return scopeTable[name]; } public InputFragment FindInputFromProperties(PropertyFragment fragment) { Debug.Assert(fragment != null); PropertyFragment propertyFragment = fragment as PropertyFragment; Debug.Assert(propertyFragment != null); if (propertyFragment.Properties.Count >= 2) { for (int x = propertyFragment.Properties.Count - 2; x >= 0; x--) { string reference = propertyFragment.Properties[x]; InputFragment input = GetFragment(reference); if (input == null) continue; if (input.Scoped) return input; if (input is SelectStatement) return (input as SelectStatement).From; continue; } } Debug.Fail("Should have found an input"); return null; } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Generators/UpdateGenerator.cs0000644000175000017500000000531211127003600030335 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Text; using System.Data.Common.CommandTrees; using System.Data.Metadata.Edm; using MySql.Data.MySqlClient; using System.Collections.Generic; namespace MySql.Data.Entity { class UpdateGenerator : SqlGenerator { public override string GenerateSQL(DbCommandTree tree) { DbUpdateCommandTree commandTree = tree as DbUpdateCommandTree; UpdateStatement statement = new UpdateStatement(); //scope.Push(commandTree.Target.VariableName); statement.Target = commandTree.Target.Expression.Accept(this); foreach (DbSetClause setClause in commandTree.SetClauses) { statement.Properties.Add(setClause.Property.Accept(this)); DbExpression value = setClause.Value; SqlFragment valueFragment = value.Accept(this); statement.Values.Add(valueFragment); if (values == null) values = new Dictionary(); if (value.ExpressionKind != DbExpressionKind.Null) { EdmMember property = ((DbPropertyExpression)setClause.Property).Property; values.Add(property, valueFragment); } } statement.Where = commandTree.Predicate.Accept(this); if (commandTree.Returning != null) statement.ReturningSelect = GenerateReturningSql(commandTree, commandTree.Returning); return statement.ToString(); } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Generators/DeleteGenerator.cs0000644000175000017500000000341511127003600030317 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Text; using System.Data.Common.CommandTrees; using System.Data.Metadata.Edm; using MySql.Data.MySqlClient; namespace MySql.Data.Entity { class DeleteGenerator : SqlGenerator { public override string GenerateSQL(DbCommandTree tree) { DbDeleteCommandTree commandTree = tree as DbDeleteCommandTree; DeleteStatement statement = new DeleteStatement(); //scope.Push(null); statement.Target = commandTree.Target.Expression.Accept(this); statement.Where = commandTree.Predicate.Accept(this); return statement.ToString(); } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Fragments/0000755000175000017500000000000011127003600024531 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Data.Entity/Fragments/TableFragment.cs0000644000175000017500000000360311127003600027575 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data.Metadata.Edm; using System.Diagnostics; namespace MySql.Data.Entity { class TableFragment : InputFragment { public string Schema; public string Table; public SqlFragment DefiningQuery; public TypeUsage Type; public List Columns; public TableFragment() { Scoped = true; } public override void WriteSql(StringBuilder sql) { if (DefiningQuery != null) sql.AppendFormat("({0})", DefiningQuery); else sql.AppendFormat("{0}", QuoteIdentifier(Table)); base.WriteSql(sql); } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Fragments/SymbolFragment.cs0000644000175000017500000000332011127003600030007 0ustar directhexdirecthex// Copyright (C) 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Text; using System.Data.Metadata.Edm; namespace MySql.Data.Entity { class SymbolFragment : SqlFragment { public SymbolFragment() : base() { } public string Property { get; set; } public SqlFragment Fragment { get; set; } //protected override string InnerText //{ // get // { // return String.Format("{0}.{1}", QuoteIdentifier(Fragment.Name), // QuoteIdentifier(Property)); // } //} } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Fragments/SqlFragment.cs0000644000175000017500000003012311127003600027302 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2010 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Text; using System.Collections.Generic; using System.Collections; using System.Diagnostics; namespace MySql.Data.Entity { internal abstract class SqlFragment { static char[] quoteChars = new char[3] { '\'', '"', '`' }; protected string QuoteIdentifier(string id) { if (id.IndexOfAny(quoteChars) < 0) return String.Format("`{0}`", id); else return id; } public abstract void WriteSql(StringBuilder sql); public override string ToString() { StringBuilder sqlText = new StringBuilder(); WriteSql(sqlText); return sqlText.ToString(); } protected void WriteList(IEnumerable list, StringBuilder sql) { string sep = ""; foreach (SqlFragment s in list) { sql.Append(sep); sql.Append("\r\n"); s.WriteSql(sql); sep = ", "; } } } internal class BinaryFragment : NegatableFragment { public SqlFragment Left; public SqlFragment Right; public string Operator; public bool WrapLeft; public bool WrapRight; public override void WriteSql(StringBuilder sql) { if (IsNegated && Operator != "=") sql.Append("NOT ("); // do left arg if (WrapLeft) sql.Append("("); Left.WriteSql(sql); if (WrapLeft) sql.Append(")"); if (IsNegated && Operator == "=") sql.Append(" != "); else sql.AppendFormat(" {0} ", Operator); // now right arg if (WrapRight) sql.Append("("); Right.WriteSql(sql); if (WrapRight) sql.Append(")"); if (IsNegated && Operator != "=") sql.Append(")"); } } internal class CaseFragment : SqlFragment { public List When = new List(); public List Then = new List(); public SqlFragment Else = null; public override void WriteSql(StringBuilder sql) { sql.Append("CASE"); for (int i = 0; i < When.Count; i++) { sql.Append(" WHEN ("); When[i].WriteSql(sql); sql.Append(") THEN ("); Then[i].WriteSql(sql); sql.Append(") "); } if (Else != null) { sql.Append(" ELSE ("); Else.WriteSql(sql); sql.Append(") "); } sql.Append("END"); } } internal class ColumnFragment : SqlFragment { public ColumnFragment(string tableName, string columnName) { TableName = tableName; ColumnName = columnName; } public SqlFragment Literal { get; set; } public string TableName { get; set; } public string ColumnName { get; set; } public string ColumnAlias { get; set; } public string ActualColumnName { get { return String.IsNullOrEmpty(ColumnName) ? ColumnAlias : ColumnName; } } public PropertyFragment PropertyFragment { get; set; } public override void WriteSql(StringBuilder sql) { if (Literal != null) { Debug.Assert(ColumnAlias != null); Literal.WriteSql(sql); } else { if (TableName != null) sql.AppendFormat("{0}.", QuoteIdentifier(TableName)); sql.AppendFormat("{0}", QuoteIdentifier(ColumnName)); } if (ColumnAlias != null && ColumnAlias != ColumnName) sql.AppendFormat(" AS {0}", QuoteIdentifier(ColumnAlias)); } public ColumnFragment Clone() { ColumnFragment cf = new ColumnFragment(TableName, ColumnName); cf.ColumnAlias = ColumnAlias; cf.Literal = Literal; return cf; } public void PushInput(string inputName) { if (PropertyFragment == null) PropertyFragment = new PropertyFragment(); PropertyFragment.PushProperty(inputName); } public override bool Equals(object obj) { if (!(obj is ColumnFragment)) return false; ColumnFragment column = obj as ColumnFragment; if (column.PropertyFragment != null && PropertyFragment != null) return column.PropertyFragment.Equals(PropertyFragment); if (column.TableName != TableName) return false; if (column.ColumnName != ColumnName) return false; if (column.ColumnAlias != ColumnAlias) return false; return true; } } internal class ExistsFragment : NegatableFragment { public SqlFragment Argument; public ExistsFragment(SqlFragment f) { Argument = f; } public override void WriteSql(StringBuilder sql) { sql.Append(IsNegated ? "NOT " : ""); sql.Append("EXISTS("); Argument.WriteSql(sql); sql.Append(")"); } } internal class FunctionFragment : SqlFragment { public bool Distinct; public SqlFragment Argmument; public string Name; public bool Quoted; public override void WriteSql(StringBuilder sql) { string name = Quoted ? QuoteIdentifier(Name) : Name; sql.AppendFormat("{0}({1}", name, Distinct ? "DISTINCT " : ""); Argmument.WriteSql(sql); sql.Append(")"); } } internal class IsNullFragment : NegatableFragment { public SqlFragment Argument; public override void WriteSql(StringBuilder sql) { Argument.WriteSql(sql); sql.AppendFormat(" IS {0} NULL", IsNegated ? "NOT" : ""); } } internal class LikeFragment : NegatableFragment { public SqlFragment Argument; public SqlFragment Pattern; public SqlFragment Escape; public override void WriteSql(StringBuilder sql) { Argument.WriteSql(sql); if (IsNegated) sql.Append(" NOT "); sql.Append(" LIKE "); Pattern.WriteSql(sql); if (Escape != null) { sql.Append(" ESCAPE "); Escape.WriteSql(sql); } } } internal class ListFragment : SqlFragment { public List Fragments = new List(); public void Append(string s) { Fragments.Add(new LiteralFragment(s)); } public void Append(SqlFragment s) { Fragments.Add(s); } public override void WriteSql(StringBuilder sql) { foreach (SqlFragment f in Fragments) f.WriteSql(sql); } } internal class NegatableFragment : SqlFragment { public bool IsNegated; public void Negate() { IsNegated = !IsNegated; } public override void WriteSql(StringBuilder sql) { Debug.Fail("This method should be overridden"); } } internal class LiteralFragment : SqlFragment { public string Literal; public LiteralFragment(string literal) { Literal = literal; } public override void WriteSql(StringBuilder sql) { sql.Append(Literal); } } internal class PropertyFragment : SqlFragment { public PropertyFragment() { Properties = new List(); } public List Properties { get; private set; } public override void WriteSql(StringBuilder sql) { throw new NotImplementedException(); } public string LastProperty { get { return Properties.Count == 0 ? null : Properties[Properties.Count - 1]; } } public void Trim(string name) { int index = Properties.LastIndexOf(name); Properties.RemoveRange(index + 1, Properties.Count - index - 1); } public void PushProperty(string property) { Properties.Insert(0, property); } public override bool Equals(object obj) { if (!(obj is PropertyFragment)) return false; PropertyFragment prop = obj as PropertyFragment; Debug.Assert(Properties != null && prop.Properties != null); int aIndex = Properties.Count - 1; int bIndex = prop.Properties.Count - 1; while (aIndex >= 0 && bIndex >= 0) if (String.Compare(Properties[aIndex--], prop.Properties[bIndex--], true) != 0) return false; return true; } public PropertyFragment Clone() { PropertyFragment newPF = new PropertyFragment(); foreach (string prop in Properties) newPF.Properties.Add(prop); return newPF; } } internal class SortFragment : SqlFragment { public SortFragment(SqlFragment column, bool ascending) { Column = column; Ascending = ascending; } public SqlFragment Column { get; set; } public bool Ascending { get; set; } public override void WriteSql(StringBuilder sql) { ColumnFragment columnFragment = Column as ColumnFragment; Debug.Assert(columnFragment != null); columnFragment.WriteSql(sql); sql.AppendFormat(" {0}", Ascending ? "ASC" : "DESC"); } } internal class UnionFragment : InputFragment { public bool Distinct = false; public override void WriteInnerSql(StringBuilder sql) { Left.WriteSql(sql); sql.Append(Distinct ? " UNION DISTINCT " : " UNION ALL "); Right.WriteSql(sql); } public bool HasDifferentNameForColumn(ColumnFragment column) { Debug.Assert(Left is SelectStatement); Debug.Assert(Right is SelectStatement); if ((Left as SelectStatement).HasDifferentNameForColumn(column)) return true; return (Right as SelectStatement).HasDifferentNameForColumn(column); } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Fragments/JoinFragment.cs0000644000175000017500000000366511127003600027455 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Text; using System.Diagnostics; namespace MySql.Data.Entity { class JoinFragment : InputFragment { public SqlFragment Condition; public string JoinType; public override void WriteInnerSql(StringBuilder sql) { Left.WriteSql(sql); sql.AppendFormat(" {0} ", JoinType); Right.WriteSql(sql); if (Condition != null) { sql.Append(" ON "); Condition.WriteSql(sql); } } //public override void WriteSql(StringBuilder sql) //{ // // we don't want our join to write out its name // string name = Name; // Name = null; // base.WriteSql(sql); // Name = name; //} } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Fragments/InputFragment.cs0000644000175000017500000000564211127003600027652 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MySql.Data.Entity { abstract class InputFragment : SqlFragment { // not all input classes will support two inputs but union and join do // in cases where only one input is used, Left is it public InputFragment Left; public InputFragment Right; public InputFragment() { } public InputFragment(string name) { Name = name; } public string Name { get; set; } public bool IsWrapped { get; private set; } public bool Scoped { get; set; } public virtual void Wrap(Scope scope) { IsWrapped = true; Scoped = true; if (scope == null) return; if (Left != null) scope.Remove(Left); if (Right != null) scope.Remove(Right); } public virtual void WriteInnerSql(StringBuilder sql) { } public override void WriteSql(StringBuilder sql) { if (IsWrapped) sql.Append("("); WriteInnerSql(sql); if (IsWrapped) sql.Append(")"); if (Name == null) return; if (this is TableFragment || (IsWrapped && !(this is JoinFragment))) sql.AppendFormat(" AS {0}", QuoteIdentifier(Name)); } public ColumnFragment GetColumnFromProperties(PropertyFragment properties) { ColumnFragment col = Left.GetColumnFromProperties(properties); if (col == null) col = Right.GetColumnFromProperties(properties); return col; } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Fragments/ListFragment.cs0000644000175000017500000000417111127003600027462 0ustar directhexdirecthex// Copyright (C) 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Collections.Generic; using System.Text; namespace MySql.Data.Entity { class ListFragment : SqlFragment { public ListFragment(string sep) { Items = new List(); Seperator = sep; } public List Items { get; private set; } public string Seperator { get; set; } public void Append(string s) { Items.Add(new SqlFragment(s)); } public void Append(SqlFragment s) { Items.Add(s); } /* protected override string InnerText { get { string seperator = ""; StringBuilder sb = new StringBuilder(); foreach (SqlFragment f in Items) { sb.AppendFormat("{0}{1}", seperator, f); seperator = Seperator; } return sb.ToString(); } }*/ } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/T4Templates/0000755000175000017500000000000011127003600024751 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Data.Entity/T4Templates/SSDLToMySQL.tt0000644000175000017500000001726711127003600027275 0ustar directhexdirecthex<# //--------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------- // This T4 template generates MySQL from an instance of // System.Data.Metadata.Edm.StoreItemCollection, an object representation // of the SSDL. This MySQL is compatible with MySQL 4.1 and higher. //--------------------------------------------------------------------- // Note: We will resolve all paths in assembly directives at runtime, taking // macros into account (e.g. $(DevEnvDir), $(ProjectDir), etc.) #> <#@ assembly name="System.Core" #> <#@ assembly name="System.Data.Entity" #> <#@ assembly name="System.Data.Entity.Design" #> <#@ assembly name="$(DevEnvDir)Microsoft.Data.Entity.Design.DatabaseGeneration.dll"#> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> <#@ import namespace="System.Data.Entity.Design" #> <#@ import namespace="System.Data.Metadata.Edm" #> <#@ import namespace="Microsoft.Data.Entity.Design.DatabaseGeneration" #> <#@ import namespace="System.Runtime.Remoting.Messaging" #> <#@ import namespace="System.Text.RegularExpressions" #> <#@ template language="C#" debug="true" hostspecific="true" #> <#@ include file="GenerateTSQL.Utility.ttinclude"#> <#@ include file="GenerateMySQL.Utility.ttinclude"#> <#@ output extension = ".mysql" #> <# // +++++++++++++++++++++++++++++++++++++++++++++++++ // Setup for the template (initializing variables, etc.) // +++++++++++++++++++++++++++++++++++++++++++++++++ string databaseName = this.GetInput(EdmParameterBag.ParameterName.DatabaseName.ToString()); string edmxPath = this.GetInput(EdmParameterBag.ParameterName.EdmxPath.ToString()); Version targetVersion = this.GetInput(EdmParameterBag.ParameterName.TargetVersion.ToString()); if (false == InitializeAndValidateExistingStore()) { #> -- Warning: There were errors validating the existing SSDL. Drop statements -- will not be generated. <# } #> -- ----------------------------------------------------------- -- Entity Designer DDL Script for MySQL Server 4.1 and higher -- ----------------------------------------------------------- -- Date Created: <#=DateTime.Now#> <# if (!String.IsNullOrEmpty(edmxPath)) { #> -- Generated from EDMX file: <#=MyId(edmxPath)#> -- Target version: <#=MyId(targetVersion.ToString())#> <# } #> -- -------------------------------------------------- <# if (!String.IsNullOrEmpty(databaseName)) { #> DROP DATABASE IF EXISTS `<#=MyId(databaseName)#>`; CREATE DATABASE `<#=MyId(databaseName)#>`; USE `<#=MyId(databaseName)#>`; <# } #> -- -------------------------------------------------- -- Dropping existing FOREIGN KEY constraints -- NOTE: if the constraint does not exist, an ignorable error will be reported. -- -------------------------------------------------- <# foreach (AssociationSet associationSet in ExistingStore.GetAllAssociationSets()) { ReferentialConstraint constraint = associationSet.ElementType.ReferentialConstraints.Single(); string constraintName = MyId(WriteFKConstraintName(constraint)); AssociationSetEnd dependentSetEnd = associationSet.AssociationSetEnds.Where(ase => ase.CorrespondingAssociationEndMember == constraint.ToRole).Single(); string dependentTableName = MyId(dependentSetEnd.EntitySet.GetTableName()); #> -- ALTER TABLE `<#=dependentTableName#>` DROP CONSTRAINT `<#=constraintName#>`; <# } #> -- -------------------------------------------------- -- Dropping existing tables -- -------------------------------------------------- SET foreign_key_checks = 0; <# foreach (EntitySet entitySet in ExistingStore.GetAllEntitySets()) { string tableName = MyId(entitySet.GetTableName()); #> DROP TABLE IF EXISTS `<#=tableName#>`; <# } #> SET foreign_key_checks = 1; -- -------------------------------------------------- -- Creating all tables -- -------------------------------------------------- <# foreach (EntitySet entitySet in Store.GetAllEntitySets()) { string tableName = MyId(entitySet.GetTableName()); #> -- Creating table '<#=tableName#>' CREATE TABLE `<#=tableName#>` ( <# for (int p = 0; p < entitySet.ElementType.Properties.Count; p++) { EdmProperty prop = entitySet.ElementType.Properties[p]; #> `<#=MyId(prop.Name)#>` <#=WriteMySqlType(prop)#> <#=WriteMySqlIdentity(prop, targetVersion)#> <#=WriteNullable(prop.Nullable)#><#=(p < entitySet.ElementType.Properties.Count - 1) ? "," : ""#> <# } #> ); <# } #> -- -------------------------------------------------- -- Creating all PRIMARY KEY constraints -- -------------------------------------------------- <# foreach (EntitySet entitySet in Store.GetAllEntitySets()) { string tableName = MyId(entitySet.GetTableName()); bool hasAutoColumn = false; foreach (EdmProperty keyProperty in entitySet.ElementType.GetKeyProperties()) { if (IsIdentity(keyProperty, targetVersion)) { hasAutoColumn = true; break; } } if (hasAutoColumn) continue; #> -- Creating primary key on <#=WriteMySqlColumns(entitySet.ElementType.GetKeyProperties(), ',')#> in table '<#=tableName#>' ALTER TABLE `<#=tableName#>` ADD CONSTRAINT `PK_<#=tableName#>` PRIMARY KEY (<#=WriteMySqlColumns(entitySet.ElementType.GetKeyProperties(), ',')#> ); <# } #> -- -------------------------------------------------- -- Creating all FOREIGN KEY constraints -- -------------------------------------------------- <# foreach (AssociationSet associationSet in Store.GetAllAssociationSets()) { ReferentialConstraint constraint = associationSet.ElementType.ReferentialConstraints.Single(); AssociationSetEnd dependentSetEnd = associationSet.AssociationSetEnds.Where(ase => ase.CorrespondingAssociationEndMember == constraint.ToRole).Single(); AssociationSetEnd principalSetEnd = associationSet.AssociationSetEnds.Where(ase => ase.CorrespondingAssociationEndMember == constraint.FromRole).Single(); string dependentTableName = MyId(dependentSetEnd.EntitySet.GetTableName()); string principalTableName = MyId(principalSetEnd.EntitySet.GetTableName()); #> -- Creating foreign key on <#=WriteMySqlColumns(constraint.ToProperties, ',')#> in table '<#=dependentTableName#>' ALTER TABLE `<#=dependentTableName#>` ADD CONSTRAINT `<#=WriteFKConstraintName(constraint)#>` FOREIGN KEY (<#=WriteMySqlColumns(constraint.ToProperties, ',')#>) REFERENCES `<#=principalTableName#>` (<#=WriteMySqlColumns(constraint.FromProperties, ',')#>) ON DELETE <#=GetDeleteAction(constraint)#> ON UPDATE NO ACTION; <# // if the foreign keys are part of the primary key on the dependent end, then we should not add a constraint. if (!dependentSetEnd.EntitySet.ElementType.GetKeyProperties().Take(constraint.ToProperties.Count()).OrderBy(r => r.Name).SequenceEqual(constraint.ToProperties.OrderBy(r => r.Name))) { #> -- Creating non-clustered index for FOREIGN KEY '<#=WriteFKConstraintName(constraint)#>' CREATE INDEX `IX_<#=WriteFKConstraintName(constraint)#>` ON `<#=dependentTableName#>` (<#=WriteMySqlColumns(constraint.ToProperties, ',')#>); <# } #> <# } #> -- -------------------------------------------------- -- Script has ended -- -------------------------------------------------- mysql-connector-net-6.4.3/Source/MySql.Data.Entity/T4Templates/GenerateMySQL.Utility.ttinclude0000644000175000017500000000641111127003600032752 0ustar directhexdirecthex<# // ++++++++++++++++++++++++++++++++++++++++++++++++++ // NOTE: This include template also requires an assembly // reference to $(DevEnvDir)\Microsoft.Data.Entity.Design.DatabaseGeneration.dll // and a namespace reference to Microsoft.Data.Entity.Design.DatabaseGeneration // in the parent template. Commented-out examples are provided below (replace '!' with '#'): // // // ++++++++++++++++++++++++++++++++++++++++++++++++++ #> <#@ assembly name="System.Core" #> <#@ assembly name="System.Data.Entity" #> <#@ assembly name="System.Data.Entity.Design" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> <#@ import namespace="System.Data.Entity.Design" #> <#@ import namespace="System.Data.Metadata.Edm" #> <#@ import namespace="System.Runtime.Remoting.Messaging" #> <#@ import namespace="System.Text.RegularExpressions" #> <#+ // ++++++++++++++++++++++++++++++++++++++++++++++++++ // Common Helper properties and methods for the T4 templates // used by the 'Generate Database' feature // in the Entity Designer. // ++++++++++++++++++++++++++++++++++++++++++++++++++ private static readonly string PROVIDER_NAME_MYSQL = "MySql.Data.MySqlClient"; /// /// Determine if the given provider invariant name is MySQL /// private bool IsMySql { get { return (this.ProviderInvariantName.Equals(PROVIDER_NAME_MYSQL, StringComparison.Ordinal)); } } /// /// Escape identifiers enclosed by backticks within the template /// private static string MyId(string userIdentifier) { if (String.IsNullOrEmpty(userIdentifier)) return userIdentifier; return userIdentifier.Replace("`", "``"); } private static bool IsIdentity(EdmProperty property, Version targetVersion) { return (property.GetStoreGeneratedPatternValue(targetVersion, DataSpace.SSpace) == StoreGeneratedPattern.Identity && true == IsIntegerOrDecimalType(property)); } private static string WriteMySqlType(EdmProperty property) { if (property.TypeUsage.EdmType.Name == "guid") return "CHAR(36) BINARY"; return property.ToStoreType(); } /// /// If the property has a StoreGeneratedPattern=Identity annotation and /// is of an integer or decimal type, write 'IDENTITY(1,1)', otherwise an empty string /// private static string WriteMySqlIdentity(EdmProperty property, Version targetVersion) { if (IsIdentity(property, targetVersion)) { return "AUTO_INCREMENT PRIMARY KEY"; } return String.Empty; } /// /// Write out the columns of a table given the Properties of an EntityType, /// escaping the identifier names. /// private static string WriteMySqlColumns(IEnumerable properties, char delimiter) { StringBuilder serializedProperties = new StringBuilder(); foreach (EdmProperty property in properties) { serializedProperties.Append(string.Format("`{0}`", MyId(property.Name))); serializedProperties.Append(delimiter + " "); } return serializedProperties.ToString().Trim().TrimEnd(delimiter); } #>mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Statements/0000755000175000017500000000000011127003600024732 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Data.Entity/Statements/SelectStatement.cs0000644000175000017500000002210111127003600030361 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Collections.Generic; using System.Text; using System; using System.Collections; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Data.Common.CommandTrees; namespace MySql.Data.Entity { class SelectStatement : InputFragment { private Dictionary columnHash; private bool hasRenamedColumns; public SelectStatement() : base(null) { Columns = new List(); } public InputFragment From; public List Columns { get; private set; } public SqlFragment Where; public SqlFragment Limit; public SqlFragment Skip; public List GroupBy { get; private set; } public List OrderBy { get; private set; } public bool IsDistinct; public void AddGroupBy(SqlFragment f) { if (GroupBy == null) GroupBy = new List(); GroupBy.Add(f); } public void AddOrderBy(SortFragment f) { if (OrderBy == null) OrderBy = new List(); OrderBy.Add(f); } public override void WriteSql(StringBuilder sql) { if (IsWrapped) sql.Append("("); sql.Append("SELECT"); if (IsDistinct) sql.Append(" DISTINCT "); WriteList(Columns, sql); if (From != null) { sql.Append("\r\nFROM "); From.WriteSql(sql); } if (Where != null) { sql.Append("\r\n WHERE "); Where.WriteSql(sql); } if (GroupBy != null) { sql.Append("\r\n GROUP BY "); WriteList(GroupBy, sql); } WriteOrderBy(sql); if (Limit != null || Skip != null) { sql.Append(" LIMIT "); if (Skip != null) sql.AppendFormat("{0},", Skip); if (Limit == null) sql.Append("18446744073709551615"); else sql.AppendFormat("{0}", Limit); } if (IsWrapped) { sql.Append(")"); if (Name != null) sql.AppendFormat(" AS {0}", QuoteIdentifier(Name)); } } private void WriteOrderBy(StringBuilder sql) { if (OrderBy == null) return; sql.Append("\r\n ORDER BY "); WriteList(OrderBy, sql); } public override void Wrap(Scope scope) { base.Wrap(scope); // now we need to add default columns if necessary if (Columns.Count == 0) AddDefaultColumns(scope); // next we need to remove child extents of the select from scope if (Name != null) { scope.Remove(this); scope.Add(Name, this); } } void AddDefaultColumns(Scope scope) { if (columnHash == null) columnHash = new Dictionary(); List columns = GetDefaultColumnsForFragment(From); foreach (ColumnFragment column in columns) { // first we need to set the input for this column InputFragment input = scope.FindInputFromProperties(column.PropertyFragment); column.TableName = input.Name; // then we rename the column if necessary if (columnHash.ContainsKey(column.ColumnName)) { column.ColumnAlias = MakeColumnNameUnique(column.ColumnName); columnHash.Add(column.ColumnAlias, column); } else columnHash.Add(column.ColumnName, column); Columns.Add(column); } } List GetDefaultColumnsForFragment(InputFragment input) { List columns = new List(); if (input is TableFragment) { return GetDefaultColumnsForTable(input as TableFragment); } else if (input is JoinFragment || input is UnionFragment) { Debug.Assert(input.Left != null); columns = GetDefaultColumnsForFragment(input.Left); if (input is JoinFragment && input.Right != null) { List right = GetDefaultColumnsForFragment(input.Right); columns.AddRange(right); } } else if (input is SelectStatement) { SelectStatement select = input as SelectStatement; foreach (ColumnFragment cf in select.Columns) { ColumnFragment newColumn = new ColumnFragment(cf.TableName, cf.ActualColumnName); newColumn.PushInput(cf.ActualColumnName); columns.Add(newColumn); } } else throw new NotImplementedException(); if (!String.IsNullOrEmpty(input.Name) && input.Name != From.Name) foreach (ColumnFragment c in columns) c.PushInput(input.Name); return columns; } List GetDefaultColumnsForTable(TableFragment table) { List columns = new List(); foreach (EdmProperty property in Metadata.GetProperties(table.Type.EdmType)) { ColumnFragment col = new ColumnFragment(table.Name, property.Name); col.PushInput(property.Name); col.PushInput(table.Name); columns.Add(col); } return columns; } private string MakeColumnNameUnique(string baseName) { int i = 1; hasRenamedColumns = true; while (true) { string name = String.Format("{0}{1}", baseName, i); if (!columnHash.ContainsKey(name)) return name; i++; } } public bool HasDifferentNameForColumn(ColumnFragment column) { if (!hasRenamedColumns) return false; foreach (ColumnFragment c in Columns) { if (!c.Equals(column)) continue; if (String.IsNullOrEmpty(c.ColumnAlias)) return false; column.ColumnName = c.ColumnAlias; return true; } return false; } public bool IsCompatible(DbExpressionKind expressionKind) { switch (expressionKind) { case DbExpressionKind.Filter: return Where == null && Columns.Count == 0; case DbExpressionKind.Project: return Columns.Count == 0; case DbExpressionKind.Limit: return Limit == null; case DbExpressionKind.Skip: return Skip == null; case DbExpressionKind.Sort: return Columns.Count == 0 && GroupBy == null && OrderBy == null; case DbExpressionKind.GroupBy: return Columns.Count == 0 && GroupBy == null && OrderBy == null && Limit == null; } throw new InvalidOperationException(); } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Statements/DeleteStatement.cs0000644000175000017500000000315211127003600030351 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Text; namespace MySql.Data.Entity { class DeleteStatement : SqlFragment { public SqlFragment Target { get; set; } public SqlFragment Where { get; set; } public override void WriteSql(StringBuilder sql) { sql.Append("DELETE FROM "); Target.WriteSql(sql); if (Where != null) { sql.Append(" WHERE "); Where.WriteSql(sql); } } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Statements/InsertStatement.cs0000644000175000017500000000435211127003600030416 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Text; using System.Collections.Generic; namespace MySql.Data.Entity { class InsertStatement : SqlFragment { public InsertStatement() { Sets = new List(); Values = new List(); } public InputFragment Target { get; set; } public List Sets { get; private set; } public List Values { get; private set; } public SelectStatement ReturningSelect; public override void WriteSql(StringBuilder sql) { sql.Append("INSERT INTO "); Target.WriteSql(sql); if (Sets.Count > 0) { sql.Append("("); WriteList(Sets, sql); sql.Append(")"); } sql.Append(" VALUES "); sql.Append("("); WriteList(Values, sql); sql.Append(")"); if (ReturningSelect != null) { sql.Append(";\r\n"); ReturningSelect.WriteSql(sql); } } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Statements/UpdateStatement.cs0000644000175000017500000000473111127003600030375 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Text; using System.Collections.Generic; namespace MySql.Data.Entity { class UpdateStatement : SqlFragment { public UpdateStatement() { Properties = new List(); Values = new List(); } public SqlFragment Target { get; set; } public List Properties { get; private set; } public List Values { get; private set; } public SqlFragment Where { get; set; } public SelectStatement ReturningSelect; public override void WriteSql(StringBuilder sql) { sql.Append("UPDATE "); Target.WriteSql(sql); sql.Append(" SET "); string seperator = ""; for (int i = 0; i < Properties.Count; i++) { sql.Append(seperator); Properties[i].WriteSql(sql); sql.Append("="); Values[i].WriteSql(sql); seperator = ", "; } if (Where != null) { sql.Append(" WHERE "); Where.WriteSql(sql); } if (ReturningSelect != null) { sql.Append(";\r\n"); ReturningSelect.WriteSql(sql); } } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Statements/BaseStatement.cs0000644000175000017500000000361711127003600030027 0ustar directhexdirecthex// Copyright (C) 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace MySql.Data.Entity { class BaseStatement : SqlFragment { public BaseStatement(BaseStatement parent) { Parent = parent; if (Parent == null) Variables = new Dictionary(); else Variables = Parent.Variables; } protected BaseStatement Parent { get; set; } protected Dictionary Variables { get; private set; } public void IndexFragment(SqlFragment fragment, string name) { Debug.Assert(!Variables.ContainsKey(name)); Variables.Add(name, fragment); } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/MySql.Data.Entity.csproj0000644000175000017500000001270711127003600027224 0ustar directhexdirecthex Debug AnyCPU 9.0.30729 2.0 {EDED3135-95D2-4BCE-A810-F3F2AD7935B7} Library Properties MySql.Data.Entity MySql.Data.Entity v4.0 512 3.5 false publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false true true full false bin\Debug\ TRACE;DEBUG;CLR4 prompt 4 AllRules.ruleset pdbonly true bin\Release\ TRACE;CLR4 prompt 4 AllRules.ruleset Properties\VersionInfo.cs Component Code True True Resources.resx ResXFileCodeGenerator Resources.Designer.cs {E9DF5ED1-4CBD-4226-B931-9A51610AC14D} MySql.Data mysql-connector-net-6.4.3/Source/MySql.Data.Entity/ProviderManifest.cs0000644000175000017500000002712511127003600026422 0ustar directhexdirecthex // Copyright (C) 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.IO; using System.Reflection; using System.Data; using System.Xml; using System.Data.Common; using System.Data.Metadata.Edm; using System.Diagnostics; using MySql.Data.Entity.Properties; namespace MySql.Data.MySqlClient { internal class MySqlProviderManifest : DbXmlEnabledProviderManifest { string manifestToken; public MySqlProviderManifest(string version) : base(GetManifest()) { manifestToken = version; } private static XmlReader GetManifest() { return GetXmlResource("MySql.Data.Entity.Properties.ProviderManifest.xml"); } protected override XmlReader GetDbInformation(string informationType) { if (informationType == DbProviderManifest.StoreSchemaDefinition) { return GetStoreSchemaDescription(); } if (informationType == DbProviderManifest.StoreSchemaMapping) { return GetStoreSchemaMapping(); } throw new ProviderIncompatibleException(String.Format("The provider returned null for the informationType '{0}'.", informationType)); } private XmlReader GetStoreSchemaMapping() { return GetMappingResource("SchemaMapping.msl"); } private XmlReader GetStoreSchemaDescription() { double version = double.Parse(manifestToken); if (version < 5.0) throw new NotSupportedException("Your version of MySQL is not currently supported"); if (version < 5.1) return GetMappingResource("SchemaDefinition-5.0.ssdl"); if (version < 5.5) return GetMappingResource("SchemaDefinition-5.1.ssdl"); return GetMappingResource("SchemaDefinition-5.5.ssdl"); } public override TypeUsage GetEdmType(TypeUsage storeType) { if (storeType == null) { throw new ArgumentNullException("storeType"); } string storeTypeName = storeType.EdmType.Name.ToLowerInvariant(); if (!base.StoreTypeNameToEdmPrimitiveType.ContainsKey(storeTypeName)) { throw new ArgumentException(String.Format("The underlying provider does not support the type '{0}'.", storeTypeName)); } PrimitiveType edmPrimitiveType = base.StoreTypeNameToEdmPrimitiveType[storeTypeName]; return TypeUsage.CreateDefaultTypeUsage(edmPrimitiveType); } private const int CHAR_MAXLEN = 255; private const int VARCHAR_MAXLEN = 65535; private const int MEDIUMTEXT_MAXLEN = 16777215; private const int LONGTEXT_MAXLEN = 1073741823; private const int BINARY_MAXLEN = 255; private const int VARBINARY_MAXLEN = 65535; private const int MEDIUMBLOB_MAXLEN = 16777215; private const int LONGBLOB_MAXLEN = 2147483647; public override TypeUsage GetStoreType(TypeUsage edmType) { if (edmType == null) throw new ArgumentNullException("edmType"); Debug.Assert(edmType.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType); PrimitiveType primitiveType = edmType.EdmType as PrimitiveType; if (primitiveType == null) throw new ArgumentException(String.Format(Resources.TypeNotSupported, edmType)); ReadOnlyMetadataCollection facets = edmType.Facets; switch (primitiveType.PrimitiveTypeKind) { case PrimitiveTypeKind.Boolean: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bool"]); case PrimitiveTypeKind.Byte: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["tinyint"]); case PrimitiveTypeKind.Int16: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]); case PrimitiveTypeKind.Int32: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["int"]); case PrimitiveTypeKind.Int64: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bigint"]); case PrimitiveTypeKind.Guid: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["guid"]); case PrimitiveTypeKind.Double: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["double"]); case PrimitiveTypeKind.Single: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]); case PrimitiveTypeKind.Decimal: { byte precision = 10; byte scale = 0; Facet facet; if (edmType.Facets.TryGetValue("Precision", false, out facet)) { if (!facet.IsUnbounded && facet.Value != null) precision = (byte)facet.Value; } if (edmType.Facets.TryGetValue("Scale", false, out facet)) { if (!facet.IsUnbounded && facet.Value != null) scale = (byte)facet.Value; } return TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], precision, scale); } case PrimitiveTypeKind.Binary: { bool isFixedLength = null != facets["FixedLength"].Value && (bool)facets["FixedLength"].Value; Facet f = facets["MaxLength"]; bool isMaxLength = f.IsUnbounded || null == f.Value || (int)f.Value > MEDIUMBLOB_MAXLEN; int maxLength = !isMaxLength ? (int)f.Value : LONGBLOB_MAXLEN; string typeName = String.Empty; if (isFixedLength) { if (maxLength < CHAR_MAXLEN) typeName = "tinyblob"; else if (maxLength < MEDIUMBLOB_MAXLEN) typeName = "blob"; else if (maxLength < LONGTEXT_MAXLEN) typeName = "mediumblob"; else typeName = "longblob"; } else { typeName = isMaxLength || maxLength > BINARY_MAXLEN ? "varbinary" : "binary"; maxLength = isMaxLength ? VARBINARY_MAXLEN : maxLength; } return TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isFixedLength, maxLength); } case PrimitiveTypeKind.String: { bool isUnicode = null == facets["Unicode"].Value || (bool)facets["Unicode"].Value; bool isFixedLength = null != facets["FixedLength"].Value && (bool)facets["FixedLength"].Value; Facet f = facets["MaxLength"]; // maxlen is true if facet value is unbounded, the value is bigger than the limited string sizes *or* the facet // value is null. this is needed since functions still have maxlength facet value as null bool isMaxLength = f.IsUnbounded || null == f.Value || (int)f.Value > MEDIUMTEXT_MAXLEN; int maxLength = !isMaxLength ? (int)f.Value : LONGTEXT_MAXLEN; string typeName = String.Empty; if (isFixedLength) { if (maxLength < CHAR_MAXLEN) typeName = "char"; else if (maxLength < LONGTEXT_MAXLEN) typeName = "mediumtext"; else typeName = "longtext"; } else { typeName = isMaxLength || maxLength > CHAR_MAXLEN ? "varchar" : "char"; maxLength = isMaxLength ? VARCHAR_MAXLEN : maxLength; } if (typeName.EndsWith("char") && isUnicode) typeName = "n" + typeName; return TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType[typeName], isUnicode, isFixedLength, maxLength); } case PrimitiveTypeKind.DateTimeOffset: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["timestamp"]); case PrimitiveTypeKind.DateTime: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["datetime"]); case PrimitiveTypeKind.Time: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["time"]); default: throw new NotSupportedException(String.Format(Resources.NoStoreTypeForEdmType, edmType, primitiveType.PrimitiveTypeKind)); } } private static XmlReader GetXmlResource(string resourceName) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); Stream stream = executingAssembly.GetManifestResourceStream(resourceName); return XmlReader.Create(stream); } private static XmlReader GetMappingResource(string resourceBaseName) { string rez = GetResourceAsString( String.Format("MySql.Data.Entity.Properties.{0}", resourceBaseName)); StringReader sr = new StringReader(rez); return XmlReader.Create(sr); } private static string GetResourceAsString(string resourceName) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); Stream s = executingAssembly.GetManifestResourceStream(resourceName); StreamReader sr = new StreamReader(s); string resourceAsString = sr.ReadToEnd(); sr.Close(); s.Close(); return resourceAsString; } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/EFMySqlDataReader.cs0000644000175000017500000001640311127003600026333 0ustar directhexdirecthex// Copyright (c) 2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data.Common; using MySql.Data.MySqlClient; using System.Collections; using System.Data; using System.Data.Metadata.Edm; using System.Globalization; using System.Text; namespace MySql.Data.Entity { class EFMySqlDataReader : DbDataReader { private EFMySqlCommand command; private MySqlDataReader reader; private PrimitiveType[] types; public EFMySqlDataReader(EFMySqlCommand cmd, MySqlDataReader wrappedReader) { command = cmd; reader = wrappedReader; types = command.ColumnTypes; } #region Properties public override int Depth { get { return reader.Depth; } } public override int FieldCount { get { return reader.FieldCount; } } public override bool HasRows { get { return reader.HasRows; } } public override bool IsClosed { get { return reader.IsClosed; } } public override int RecordsAffected { get { return reader.RecordsAffected; } } public override object this[string name] { get { return GetValue(GetOrdinal(name)); } } public override object this[int ordinal] { get { return GetValue(ordinal); } } #endregion public override void Close() { GC.SuppressFinalize(this); reader.Close(); } public override bool GetBoolean(int ordinal) { return (bool)GetValue(ordinal); } public override byte GetByte(int ordinal) { return reader.GetByte(ordinal); } public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length) { return reader.GetBytes(ordinal, dataOffset, buffer, bufferOffset, length); } public override char GetChar(int ordinal) { return reader.GetChar(ordinal); } public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) { return reader.GetChars(ordinal, dataOffset, buffer, bufferOffset, length); } public override string GetDataTypeName(int ordinal) { if (types != null) return types[ordinal].Name; return reader.GetDataTypeName(ordinal); } public override DateTime GetDateTime(int ordinal) { return reader.GetDateTime(ordinal); } public override decimal GetDecimal(int ordinal) { return reader.GetDecimal(ordinal); } public override double GetDouble(int ordinal) { return reader.GetDouble(ordinal); } public override IEnumerator GetEnumerator() { return reader.GetEnumerator(); } public override Type GetFieldType(int ordinal) { if (types != null) return types[ordinal].ClrEquivalentType; return reader.GetFieldType(ordinal); } public override float GetFloat(int ordinal) { return reader.GetFloat(ordinal); } public override Guid GetGuid(int ordinal) { return reader.GetGuid(ordinal); } public override short GetInt16(int ordinal) { return reader.GetInt16(ordinal); } public override int GetInt32(int ordinal) { return reader.GetInt32(ordinal); } public override long GetInt64(int ordinal) { return reader.GetInt64(ordinal); } public override string GetName(int ordinal) { return reader.GetName(ordinal); } public override int GetOrdinal(string name) { return reader.GetOrdinal(name); } public override DataTable GetSchemaTable() { return reader.GetSchemaTable(); } public override string GetString(int ordinal) { return reader.GetString(ordinal); } public override object GetValue(int ordinal) { object value = reader.GetValue(ordinal); if (types != null) { if (!(value is DBNull) && value.GetType() != types[ordinal].ClrEquivalentType) value = ChangeType(value, types[ordinal].ClrEquivalentType); } return value; } private object ChangeType(object sourceValue, Type targetType) { if (sourceValue is byte[]) { if (targetType == typeof(Guid)) return new Guid((byte[])sourceValue); else if (targetType == typeof(bool)) { byte[] bytes = (byte[])sourceValue; return bytes[0] == '1'; } } if (sourceValue is DateTime && targetType == typeof(DateTimeOffset)) { return new DateTimeOffset((DateTime)sourceValue); } return Convert.ChangeType(sourceValue, targetType, CultureInfo.InvariantCulture); } public override int GetValues(object[] values) { for (int i = 0; i < values.Length; ++i) values[i] = GetValue(i); return values.Length; } public override bool IsDBNull(int ordinal) { return reader.IsDBNull(ordinal); } public override bool NextResult() { return reader.NextResult(); } public override bool Read() { return reader.Read(); } protected override void Dispose(bool disposing) { GC.SuppressFinalize(this); if (disposing) reader.Dispose(); base.Dispose(disposing); } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Metadata.cs0000644000175000017500000001701511127003600024656 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2010 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data; using System.Data.Metadata.Edm; using System.Data.Common.CommandTrees; using System.Collections.Generic; using System.Globalization; using System.Diagnostics; namespace MySql.Data.Entity { class Metadata { public static string GetNumericLiteral(PrimitiveTypeKind type, object value) { switch (type) { case PrimitiveTypeKind.Byte: case PrimitiveTypeKind.Int16: case PrimitiveTypeKind.Int32: case PrimitiveTypeKind.Int64: case PrimitiveTypeKind.SByte: return value.ToString(); case PrimitiveTypeKind.Double: return ((double)value).ToString("R", CultureInfo.InvariantCulture); case PrimitiveTypeKind.Single: return ((float)value).ToString("R", CultureInfo.InvariantCulture); case PrimitiveTypeKind.Decimal: return ((decimal)value).ToString(CultureInfo.InvariantCulture); } return null; } public static bool IsNumericType(TypeUsage typeUsage) { PrimitiveType pt = (PrimitiveType)typeUsage.EdmType; switch (pt.PrimitiveTypeKind) { case PrimitiveTypeKind.Byte: case PrimitiveTypeKind.Double: case PrimitiveTypeKind.Single: case PrimitiveTypeKind.Int16: case PrimitiveTypeKind.Int32: case PrimitiveTypeKind.Int64: case PrimitiveTypeKind.SByte: return true; default: return false; } } public static DbType GetDbType(TypeUsage typeUsage) { PrimitiveType pt = (PrimitiveType)typeUsage.EdmType; switch (pt.PrimitiveTypeKind) { case PrimitiveTypeKind.Binary: return DbType.Binary; case PrimitiveTypeKind.Boolean: return DbType.Boolean; case PrimitiveTypeKind.Byte: return DbType.Byte; case PrimitiveTypeKind.DateTime: return DbType.DateTime; case PrimitiveTypeKind.DateTimeOffset: return DbType.DateTime; case PrimitiveTypeKind.Decimal: return DbType.Decimal; case PrimitiveTypeKind.Double: return DbType.Double; case PrimitiveTypeKind.Single: return DbType.Single; case PrimitiveTypeKind.Guid: return DbType.Guid; case PrimitiveTypeKind.Int16: return DbType.Int16; case PrimitiveTypeKind.Int32: return DbType.Int32; case PrimitiveTypeKind.Int64: return DbType.Int64; case PrimitiveTypeKind.SByte: return DbType.SByte; case PrimitiveTypeKind.String: return DbType.String; case PrimitiveTypeKind.Time: return DbType.Time; // case PrimitiveTypeKind.UInt16: return DbType.UInt16; // case PrimitiveTypeKind.UInt32: return DbType.UInt32; // case PrimitiveTypeKind.UInt64: return DbType.UInt64; default: throw new InvalidOperationException( string.Format("Unknown PrimitiveTypeKind {0}", pt.PrimitiveTypeKind)); } } public static object NormalizeValue(TypeUsage type, object value) { PrimitiveType pt = (PrimitiveType)type.EdmType; if (pt.PrimitiveTypeKind != PrimitiveTypeKind.DateTimeOffset) return value; DateTimeOffset dto = (DateTimeOffset)value; DateTime dt = dto.DateTime; if (dt.Year < 1970) return new DateTime(1970, 1, 1, 0, 0, 1); return dt; } public static ParameterDirection ModeToDirection(ParameterMode mode) { switch (mode) { case ParameterMode.In: return ParameterDirection.Input; case ParameterMode.Out: return ParameterDirection.Output; case ParameterMode.InOut: return ParameterDirection.InputOutput; default: Debug.Assert(mode == ParameterMode.ReturnValue); return ParameterDirection.ReturnValue; } } public static bool IsComparisonOperator(string op) { switch (op) { case "=": case "<": case ">": case "<=": case ">=": case "!=": return true; default: return false; } } public static string GetOperator(DbExpressionKind expressionKind) { switch (expressionKind) { case DbExpressionKind.Equals: return "="; case DbExpressionKind.LessThan: return "<"; case DbExpressionKind.GreaterThan: return ">"; case DbExpressionKind.LessThanOrEquals: return "<="; case DbExpressionKind.GreaterThanOrEquals: return ">="; case DbExpressionKind.NotEquals: return "!="; case DbExpressionKind.LeftOuterJoin: return "LEFT OUTER JOIN"; case DbExpressionKind.InnerJoin: return "INNER JOIN"; case DbExpressionKind.CrossJoin: return "CROSS JOIN"; case DbExpressionKind.FullOuterJoin: return "OUTER JOIN"; } throw new NotSupportedException("expression kind not supported"); } internal static IList GetProperties(EdmType type) { if (type is EntityType) return ((EntityType)type).Properties; if (type is ComplexType) return ((ComplexType)type).Properties; if (type is RowType) return ((RowType)type).Properties; throw new NotSupportedException(); } internal static T TryGetValueMetadataProperty(MetadataItem mi, string name) { MetadataProperty property; bool exists = mi.MetadataProperties.TryGetValue(name, true, out property); if (exists) return (T)property.Value; return default(T); } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Properties/0000755000175000017500000000000011127003600024737 5ustar directhexdirecthexmysql-connector-net-6.4.3/Source/MySql.Data.Entity/Properties/SchemaDefinition-5.1.ssdl0000644000175000017500000007461111127003600031351 0ustar directhexdirecthex SELECT /* Tables */ CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `Id`, TABLE_CATALOG AS `Catalog`, TABLE_SCHEMA AS `Schema`, TABLE_NAME AS `Name` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA=schema() SELECT /* Table columns */ CONCAT(TABLE_SCHEMA, '.', TABLE_NAME, '.', COLUMN_NAME) AS `Id`, CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `ParentId`, COLUMN_NAME AS `Name`, ORDINAL_POSITION AS `Ordinal`, CASE IS_NULLABLE WHEN 'YES' THEN 1 ELSE 0 END AS `IsNullable`, IF(LEFT(COLUMN_TYPE,10) = 'tinyint(1)', 'bool', IF (LEFT(COLUMN_TYPE,10) = 'binary(16)' OR LEFT(COLUMN_TYPE,8) = 'char(36)', 'guid', IF (INSTR(COLUMN_TYPE, 'unsigned') = 0, DATA_TYPE, CONCAT('u', DATA_TYPE)))) AS `TypeName`, IF (CHARACTER_MAXIMUM_LENGTH > 2147483647, 2147483647, CHARACTER_MAXIMUM_LENGTH) AS `MaxLength`, NUMERIC_PRECISION AS `Precision`, 0 AS `DateTimePrecision`, NUMERIC_SCALE AS `Scale`, NULL AS `CollationCatalog`, NULL AS `CollationSchema`, COLLATION_NAME AS `CollationName`, NULL AS `CharacterSetCatalog`, NULL AS `CharacterSetSchema`, CHARACTER_SET_NAME AS `CharacterSetName`, 0 AS `IsMultiSet`, CASE WHEN EXTRA LIKE '%auto%' THEN 1 ELSE 0 END AS `IsIdentity`, CASE WHEN EXTRA LIKE '%auto%' THEN 1 ELSE 0 END AS `IsStoreGenerated`, IF (COLUMN_TYPE = 'tinyint(1)', -128, COLUMN_DEFAULT) AS `Default` FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=schema() SELECT /* Views */ CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `Id`, TABLE_CATALOG AS`CatalogName`, TABLE_SCHEMA AS `SchemaName`, TABLE_NAME AS `Name`, VIEW_DEFINITION AS `ViewDefinition`, CASE IS_UPDATABLE WHEN 'YES' THEN 1 ELSE 0 END AS `IsUpdatable` FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA=schema() SELECT /* View columns */ CONCAT(TABLE_SCHEMA, '.', TABLE_NAME, '.', COLUMN_NAME) AS `Id`, CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `ParentId`, COLUMN_NAME AS `Name`, ORDINAL_POSITION AS `Ordinal`, CASE IS_NULLABLE WHEN 'YES' THEN 1 ELSE 0 END AS `IsNullable`, IF(LEFT(COLUMN_TYPE,10) = 'tinyint(1)', 'bool', IF (LEFT(COLUMN_TYPE,10) = 'binary(16)' OR LEFT(COLUMN_TYPE,8) = 'char(36)', 'guid', IF (INSTR(COLUMN_TYPE, 'unsigned') = 0, DATA_TYPE, CONCAT('u', DATA_TYPE)))) AS `TypeName`, IF (CHARACTER_MAXIMUM_LENGTH > 2147483647, 2147483647, CHARACTER_MAXIMUM_LENGTH) AS `MaxLength`, NUMERIC_PRECISION AS `Precision`, 0 AS `DateTimePrecision`, NUMERIC_SCALE AS `Scale`, NULL AS `CollationCatalog`, NULL AS `CollationSchema`, COLLATION_NAME AS `CollationName`, NULL AS `CharacterSetCatalog`, NULL AS `CharacterSetSchema`, CHARACTER_SET_NAME AS `CharacterSetName`, 0 AS `IsMultiSet`, CASE WHEN EXTRA LIKE '%auto%' THEN 1 ELSE 0 END AS `IsIdentity`, CASE WHEN EXTRA LIKE '%auto%' THEN 1 ELSE 0 END AS `IsStoreGenerated`, COLUMN_DEFAULT AS `Default` FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=schema() SELECT /* Functions */ CONCAT(ROUTINE_SCHEMA, '.', SPECIFIC_NAME) AS `Id`, ROUTINE_CATALOG AS `CatalogName`, ROUTINE_SCHEMA AS `SchemaName`, ROUTINE_NAME AS `Name`, SUBSTRING_INDEX(DTD_IDENTIFIER, '(', 1) AS `ReturnTypeName`, NULL AS `ReturnMaxLength`, NULL AS `ReturnPrecision`, 0 AS `ReturnDateTimePrecision`, NULL AS `ReturnScale`, NULL AS `ReturnCollationCatalog`, NULL AS `ReturnCollationSchema`, NULL AS `ReturnCollationName`, NULL AS `ReturnCharacterSetCatalog`, NULL AS `ReturnCharacterSetSchema`, NULL AS `ReturnCharacterSetName`, NULL AS `ReturnIsMultiSet`, NULL AS `IsAggregate`, NULL AS `IsBuiltIn`, NULL AS `IsNiladic` FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='FUNCTION' AND ROUTINE_SCHEMA=schema() SELECT /* Procedures */ CONCAT(ROUTINE_SCHEMA, '.', SPECIFIC_NAME) AS `Id`, ROUTINE_CATALOG AS `CatalogName`, ROUTINE_SCHEMA AS `SchemaName`, ROUTINE_NAME AS `Name` FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='PROCEDURE' AND ROUTINE_SCHEMA=schema() SELECT /* Function parameters */ NULL AS `Id`, NULL AS `ParentId`, NULL AS `Name`, NULL AS `Ordinal`, NULL AS `TypeName`, NULL AS `MaxLength`, NULL AS `Precision`, NULL AS `DateTimePrecision`, NULL AS `Scale`, NULL AS `CollatioCatalog`, NULL AS `CollationSchema`, NULL AS `CollationName`, NULL AS `CharacterSetCatalog`, NULL AS `CharacterSetSchema`, NULL AS `CharacterSetName`, NULL AS `IsMultiSet`, NULL AS `Mode`, NULL AS `Default` SELECT /* Procedure parameters */ NULL AS `Id`, NULL AS `ParentId`, NULL AS `Name`, NULL AS `Ordinal`, NULL AS `TypeName`, NULL AS `MaxLength`, NULL AS `Precision`, NULL AS `DateTimePrecision`, NULL AS `Scale`, NULL AS `CollatioCatalog`, NULL AS `CollationSchema`, NULL AS `CollationName`, NULL AS `CharacterSetCatalog`, NULL AS `CharacterSetSchema`, NULL AS `CharacterSetName`, NULL AS `IsMultiSet`, NULL AS `Mode`, NULL AS `Default` SELECT /* Constraints */ CONCAT(CONSTRAINT_SCHEMA, '.', TABLE_NAME, '.', CONSTRAINT_NAME) AS `Id`, CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `ParentId`, CONSTRAINT_NAME AS `Name`, CONSTRAINT_TYPE AS `ConstraintType`, 0 AS `IsDeferrable`, 0 AS `IsInitiallyDeferred` FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE != 'CHECK' AND TABLE_SCHEMA=schema() SELECT /* Check constraints */ NULL AS `Id`, NULL AS `Expression` SELECT /* Constraint columns */ CONCAT(CONSTRAINT_SCHEMA, '.', TABLE_NAME, '.', CONSTRAINT_NAME) AS `ConstraintId`, CONCAT(TABLE_SCHEMA, '.', TABLE_NAME, '.', COLUMN_NAME) AS `ColumnId` FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA=schema() SELECT CONCAT(CONSTRAINT_SCHEMA, '.', TABLE_NAME, '.', CONSTRAINT_NAME) AS `Id`, UPDATE_RULE AS `UpdateRule`, DELETE_RULE AS `DeleteRule` FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS SELECT CONCAT(FC.CONSTRAINT_SCHEMA, '.', FC.CONSTRAINT_NAME, '.', FC.ORDINAL_POSITION) AS `Id`, CONCAT(PC.TABLE_SCHEMA, '.', PC.TABLE_NAME, '.', PC.COLUMN_NAME) AS `ToColumnId`, CONCAT(FC.TABLE_SCHEMA, '.', FC.TABLE_NAME, '.', FC.COLUMN_NAME) AS `FromColumnId`, CONCAT(FC.CONSTRAINT_SCHEMA, '.', FC.TABLE_NAME, '.', FC.CONSTRAINT_NAME) AS `ConstraintId`, FC.ORDINAL_POSITION AS `Ordinal` FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS PC /* PRIMARY KEY COLS*/ ON RC.UNIQUE_CONSTRAINT_SCHEMA = PC.CONSTRAINT_SCHEMA AND RC.UNIQUE_CONSTRAINT_NAME = PC.CONSTRAINT_NAME AND RC.REFERENCED_TABLE_NAME = PC.TABLE_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS FC /* FOREIGN KEY COLS*/ ON RC.CONSTRAINT_SCHEMA = FC.CONSTRAINT_SCHEMA AND RC.CONSTRAINT_NAME = FC.CONSTRAINT_NAME AND RC.TABLE_NAME = FC.TABLE_NAME AND PC.ORDINAL_POSITION = FC.ORDINAL_POSITION SELECT /* View constraints */ NULL AS `Id`, NULL AS `ParentId`, NULL AS `Name`, NULL AS `ConstraintType`, NULL AS `Expression`, NULL AS `UpdateRule`, NULL AS `DeleteRule` SELECT /* View constraint columns */ NULL AS `ConstraintId`, NULL AS `ColumnId` SELECT /* View foreign keys */ NULL AS `Id`, NULL AS `ToColumnId`, NULL AS `FromColumnId`, NULL AS `ConstraintId`, 0 AS `Ordinal` mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Properties/SchemaDefinition-5.5.ssdl0000644000175000017500000010106311127003600031345 0ustar directhexdirecthex SELECT /* Tables */ CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `Id`, TABLE_CATALOG AS `Catalog`, TABLE_SCHEMA AS `Schema`, TABLE_NAME AS `Name` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA=schema() SELECT /* Table columns */ CONCAT(TABLE_SCHEMA, '.', TABLE_NAME, '.', COLUMN_NAME) AS `Id`, CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `ParentId`, COLUMN_NAME AS `Name`, ORDINAL_POSITION AS `Ordinal`, CASE IS_NULLABLE WHEN 'YES' THEN 1 ELSE 0 END AS `IsNullable`, IF(LEFT(COLUMN_TYPE,10) = 'tinyint(1)', 'bool', IF (LEFT(COLUMN_TYPE,10) = 'binary(16)' OR LEFT(COLUMN_TYPE,8) = 'char(36)', 'guid', IF (INSTR(COLUMN_TYPE, 'unsigned') = 0, DATA_TYPE, CONCAT('u', DATA_TYPE)))) AS `TypeName`, IF (CHARACTER_MAXIMUM_LENGTH > 2147483647, 2147483647, CHARACTER_MAXIMUM_LENGTH) AS `MaxLength`, NUMERIC_PRECISION AS `Precision`, 0 AS `DateTimePrecision`, NUMERIC_SCALE AS `Scale`, NULL AS `CollationCatalog`, NULL AS `CollationSchema`, COLLATION_NAME AS `CollationName`, NULL AS `CharacterSetCatalog`, NULL AS `CharacterSetSchema`, CHARACTER_SET_NAME AS `CharacterSetName`, 0 AS `IsMultiSet`, CASE WHEN EXTRA LIKE '%auto%' THEN 1 ELSE 0 END AS `IsIdentity`, CASE WHEN EXTRA LIKE '%auto%' THEN 1 ELSE 0 END AS `IsStoreGenerated`, COLUMN_DEFAULT AS `Default` FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=schema() SELECT /* Views */ CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `Id`, TABLE_CATALOG AS`CatalogName`, TABLE_SCHEMA AS `SchemaName`, TABLE_NAME AS `Name`, VIEW_DEFINITION AS `ViewDefinition`, CASE IS_UPDATABLE WHEN 'YES' THEN 1 ELSE 0 END AS `IsUpdatable` FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA=schema() SELECT /* View columns */ CONCAT(TABLE_SCHEMA, '.', TABLE_NAME, '.', COLUMN_NAME) AS `Id`, CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `ParentId`, COLUMN_NAME AS `Name`, ORDINAL_POSITION AS `Ordinal`, CASE IS_NULLABLE WHEN 'YES' THEN 1 ELSE 0 END AS `IsNullable`, IF(LEFT(COLUMN_TYPE,10) = 'tinyint(1)', 'bool', IF (LEFT(COLUMN_TYPE,10) = 'binary(16)' OR LEFT(COLUMN_TYPE,8) = 'char(36)', 'guid', IF (INSTR(COLUMN_TYPE, 'unsigned') = 0, DATA_TYPE, CONCAT('u', DATA_TYPE)))) AS `TypeName`, IF (CHARACTER_MAXIMUM_LENGTH > 2147483647, 2147483647, CHARACTER_MAXIMUM_LENGTH) AS `MaxLength`, NUMERIC_PRECISION AS `Precision`, 0 AS `DateTimePrecision`, NUMERIC_SCALE AS `Scale`, NULL AS `CollationCatalog`, NULL AS `CollationSchema`, COLLATION_NAME AS `CollationName`, NULL AS `CharacterSetCatalog`, NULL AS `CharacterSetSchema`, CHARACTER_SET_NAME AS `CharacterSetName`, 0 AS `IsMultiSet`, CASE WHEN EXTRA LIKE '%auto%' THEN 1 ELSE 0 END AS `IsIdentity`, CASE WHEN EXTRA LIKE '%auto%' THEN 1 ELSE 0 END AS `IsStoreGenerated`, COLUMN_DEFAULT AS `Default` FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=schema() SELECT /* Functions */ CONCAT(ROUTINE_SCHEMA, '.', SPECIFIC_NAME) AS `Id`, ROUTINE_CATALOG AS `CatalogName`, ROUTINE_SCHEMA AS `SchemaName`, ROUTINE_NAME AS `Name`, SUBSTRING_INDEX(DTD_IDENTIFIER, '(', 1) AS `ReturnTypeName`, NULL AS `ReturnMaxLength`, NULL AS `ReturnPrecision`, 0 AS `ReturnDateTimePrecision`, NULL AS `ReturnScale`, NULL AS `ReturnCollationCatalog`, NULL AS `ReturnCollationSchema`, NULL AS `ReturnCollationName`, NULL AS `ReturnCharacterSetCatalog`, NULL AS `ReturnCharacterSetSchema`, NULL AS `ReturnCharacterSetName`, NULL AS `ReturnIsMultiSet`, NULL AS `IsAggregate`, NULL AS `IsBuiltIn`, NULL AS `IsNiladic` FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='FUNCTION' AND ROUTINE_SCHEMA=schema() SELECT /* Procedures */ CONCAT(ROUTINE_SCHEMA, '.', SPECIFIC_NAME) AS `Id`, ROUTINE_CATALOG AS `CatalogName`, ROUTINE_SCHEMA AS `SchemaName`, ROUTINE_NAME AS `Name` FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='PROCEDURE' AND ROUTINE_SCHEMA=schema() SELECT CONCAT(f.SPECIFIC_SCHEMA, '.', f.SPECIFIC_NAME, '.', f.PARAMETER_NAME) AS `Id`, CONCAT(f.SPECIFIC_SCHEMA, '.', f.SPECIFIC_NAME) AS `ParentId`, f.PARAMETER_NAME AS `Name`, f.ORDINAL_POSITION `Ordinal`, f.DATA_TYPE AS `TypeName`, f.CHARACTER_MAXIMUM_LENGTH AS `MaxLength`, f.NUMERIC_PRECISION AS`Precision`, NULL AS `DateTimePrecision`, f.NUMERIC_SCALE AS `Scale`, NULL AS `CollationCatalog`, NULL AS `CollationSchema`, f.COLLATION_NAME AS `CollationName`, NULL AS `CharacterSetCatalog`, NULL AS `CharacterSetSchema`, f.CHARACTER_SET_NAME AS `CharacterSetName`, CAST(0 as decimal(0,0)) AS `IsMultiSet`, f.PARAMETER_MODE AS `Mode`, NULL AS `Default` FROM INFORMATION_SCHEMA.PARAMETERS f INNER JOIN INFORMATION_SCHEMA.ROUTINES r ON f.SPECIFIC_SCHEMA = r.ROUTINE_SCHEMA AND f.SPECIFIC_NAME = r.SPECIFIC_NAME AND r.ROUTINE_TYPE = 'FUNCTION' WHERE r.ROUTINE_SCHEMA=schema() AND f.ORDINAL_POSITION > 0 SELECT CONCAT(f.SPECIFIC_SCHEMA, '.', f.SPECIFIC_NAME, '.', f.PARAMETER_NAME) AS `Id`, CONCAT(f.SPECIFIC_SCHEMA, '.', f.SPECIFIC_NAME) AS `ParentId`, f.PARAMETER_NAME AS `Name`, f.ORDINAL_POSITION `Ordinal`, f.DATA_TYPE AS `TypeName`, f.CHARACTER_MAXIMUM_LENGTH AS `MaxLength`, f.NUMERIC_PRECISION AS`Precision`, NULL AS `DateTimePrecision`, f.NUMERIC_SCALE AS `Scale`, NULL AS `CollationCatalog`, NULL AS `CollationSchema`, f.COLLATION_NAME AS `CollationName`, NULL AS `CharacterSetCatalog`, NULL AS `CharacterSetSchema`, f.CHARACTER_SET_NAME AS `CharacterSetName`, CAST(0 as decimal(0,0)) AS `IsMultiSet`, f.PARAMETER_MODE AS `Mode`, NULL AS `Default` FROM INFORMATION_SCHEMA.PARAMETERS f INNER JOIN INFORMATION_SCHEMA.ROUTINES r ON f.SPECIFIC_SCHEMA = r.ROUTINE_SCHEMA AND f.SPECIFIC_NAME = r.SPECIFIC_NAME AND r.ROUTINE_TYPE = 'PROCEDURE' WHERE r.ROUTINE_SCHEMA=schema() AND f.ORDINAL_POSITION > 0 SELECT /* Constraints */ CONCAT(CONSTRAINT_SCHEMA, '.', TABLE_NAME, '.', CONSTRAINT_NAME) AS `Id`, CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `ParentId`, CONSTRAINT_NAME AS `Name`, CONSTRAINT_TYPE AS `ConstraintType`, 0 AS `IsDeferrable`, 0 AS `IsInitiallyDeferred` FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE != 'CHECK' AND TABLE_SCHEMA=schema() SELECT /* Check constraints */ NULL AS `Id`, NULL AS `Expression` SELECT /* Constraint columns */ CONCAT(CONSTRAINT_SCHEMA, '.', TABLE_NAME, '.', CONSTRAINT_NAME) AS `ConstraintId`, CONCAT(TABLE_SCHEMA, '.', TABLE_NAME, '.', COLUMN_NAME) AS `ColumnId` FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA=schema() SELECT CONCAT(CONSTRAINT_SCHEMA, '.', TABLE_NAME, '.', CONSTRAINT_NAME) AS `Id`, UPDATE_RULE AS `UpdateRule`, DELETE_RULE AS `DeleteRule` FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS SELECT CONCAT(FC.CONSTRAINT_SCHEMA, '.', FC.CONSTRAINT_NAME, '.', FC.ORDINAL_POSITION) AS `Id`, CONCAT(PC.TABLE_SCHEMA, '.', PC.TABLE_NAME, '.', PC.COLUMN_NAME) AS `ToColumnId`, CONCAT(FC.TABLE_SCHEMA, '.', FC.TABLE_NAME, '.', FC.COLUMN_NAME) AS `FromColumnId`, CONCAT(FC.CONSTRAINT_SCHEMA, '.', FC.TABLE_NAME, '.', FC.CONSTRAINT_NAME) AS `ConstraintId`, FC.ORDINAL_POSITION AS `Ordinal` FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS PC /* PRIMARY KEY COLS*/ ON RC.UNIQUE_CONSTRAINT_SCHEMA = PC.CONSTRAINT_SCHEMA AND RC.UNIQUE_CONSTRAINT_NAME = PC.CONSTRAINT_NAME AND RC.REFERENCED_TABLE_NAME = PC.TABLE_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS FC /* FOREIGN KEY COLS*/ ON RC.CONSTRAINT_SCHEMA = FC.CONSTRAINT_SCHEMA AND RC.CONSTRAINT_NAME = FC.CONSTRAINT_NAME AND RC.TABLE_NAME = FC.TABLE_NAME AND PC.ORDINAL_POSITION = FC.ORDINAL_POSITION SELECT /* View constraints */ NULL AS `Id`, NULL AS `ParentId`, NULL AS `Name`, NULL AS `ConstraintType`, NULL AS `Expression`, NULL AS `UpdateRule`, NULL AS `DeleteRule` SELECT /* View constraint columns */ NULL AS `ConstraintId`, NULL AS `ColumnId` SELECT /* View foreign keys */ NULL AS `Id`, NULL AS `ToColumnId`, NULL AS `FromColumnId`, NULL AS `ConstraintId`, 0 AS `Ordinal` mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Properties/Resources.Designer.cs0000644000175000017500000001054311127003600031002 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:4.0.30319.235 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace MySql.Data.Entity.Properties { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MySql.Data.Entity.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// /// Looks up a localized string similar to The connection parameter must reference an object of type MySql.Data.MySqlConnection. /// internal static string ConnectionMustBeOfTypeMySqlConnection { get { return ResourceManager.GetString("ConnectionMustBeOfTypeMySqlConnection", resourceCulture); } } /// /// Looks up a localized string similar to There is no store type corresponding to the EDM type '{0}' of primitive type '{1}'.. /// internal static string NoStoreTypeForEdmType { get { return ResourceManager.GetString("NoStoreTypeForEdmType", resourceCulture); } } /// /// Looks up a localized string similar to The underlying provider does not support the type '{0}'.. /// internal static string TypeNotSupported { get { return ResourceManager.GetString("TypeNotSupported", resourceCulture); } } /// /// Looks up a localized string similar to Result type of a function is expected to be a collection of RowType or PrimitiveType. /// internal static string WrongFunctionResultType { get { return ResourceManager.GetString("WrongFunctionResultType", resourceCulture); } } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Properties/Resources.resx0000644000175000017500000001455111127003600027622 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 The connection parameter must reference an object of type MySql.Data.MySqlConnection There is no store type corresponding to the EDM type '{0}' of primitive type '{1}'. The underlying provider does not support the type '{0}'. Result type of a function is expected to be a collection of RowType or PrimitiveType mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Properties/AssemblyInfo.cs0000644000175000017500000000520511127003600027663 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MySql.Data.Entity")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Oracle")] [assembly: AssemblyProduct("MySql.Data.Entity")] [assembly: AssemblyCopyright("Copyright © 2008, 2010, Oracle and/or its affiliates. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("540e7b3c-bd0b-4980-96d1-5d140d303f7e")] [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyName("ConnectorNet")] [assembly: InternalsVisibleTo("MySql.Data.Entity.Tests, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100d973bda91f71752c78294126974a41a08643168271f65fc0fb3cd45f658da01fbca75ac74067d18e7afbf1467d7a519ce0248b13719717281bb4ddd4ecd71a580dfe0912dfc3690b1d24c7e1975bf7eed90e4ab14e10501eedf763bff8ac204f955c9c15c2cf4ebf6563d8320b6ea8d1ea3807623141f4b81ae30a6c886b3ee1")]mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Properties/SchemaDefinition-5.0.ssdl0000644000175000017500000007313111127003600031344 0ustar directhexdirecthex SELECT /* Tables */ CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `Id`, TABLE_CATALOG AS `Catalog`, TABLE_SCHEMA AS `Schema`, TABLE_NAME AS `Name` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA=schema() SELECT /* Table columns */ CONCAT(TABLE_SCHEMA, '.', TABLE_NAME, '.', COLUMN_NAME) AS `Id`, CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `ParentId`, COLUMN_NAME AS `Name`, ORDINAL_POSITION AS `Ordinal`, CASE IS_NULLABLE WHEN 'YES' THEN 1 ELSE 0 END AS `IsNullable`, IF(LEFT(COLUMN_TYPE,10) = 'tinyint(1)', 'bool', IF (LEFT(COLUMN_TYPE,10) = 'binary(16)' OR LEFT(COLUMN_TYPE,8) = 'char(36)', 'guid', IF (INSTR(COLUMN_TYPE, 'unsigned') = 0, DATA_TYPE, CONCAT('u', DATA_TYPE)))) AS `TypeName`, IF (CHARACTER_MAXIMUM_LENGTH > 2147483647, 2147483647, CHARACTER_MAXIMUM_LENGTH) AS `MaxLength`, NUMERIC_PRECISION AS `Precision`, 0 AS `DateTimePrecision`, NUMERIC_SCALE AS `Scale`, NULL AS `CollationCatalog`, NULL AS `CollationSchema`, COLLATION_NAME AS `CollationName`, NULL AS `CharacterSetCatalog`, NULL AS `CharacterSetSchema`, CHARACTER_SET_NAME AS `CharacterSetName`, 0 AS `IsMultiSet`, CASE WHEN EXTRA LIKE '%auto%' THEN 1 ELSE 0 END AS `IsIdentity`, CASE WHEN EXTRA LIKE '%auto%' THEN 1 ELSE 0 END AS `IsStoreGenerated`, COLUMN_DEFAULT AS `Default` FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=schema() SELECT /* Views */ CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `Id`, TABLE_CATALOG AS`CatalogName`, TABLE_SCHEMA AS `SchemaName`, TABLE_NAME AS `Name`, VIEW_DEFINITION AS `ViewDefinition`, CASE IS_UPDATABLE WHEN 'YES' THEN 1 ELSE 0 END AS `IsUpdatable` FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA=schema() SELECT /* View columns */ CONCAT(TABLE_SCHEMA, '.', TABLE_NAME, '.', COLUMN_NAME) AS `Id`, CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `ParentId`, COLUMN_NAME AS `Name`, ORDINAL_POSITION AS `Ordinal`, CASE IS_NULLABLE WHEN 'YES' THEN 1 ELSE 0 END AS `IsNullable`, IF(LEFT(COLUMN_TYPE,10) = 'tinyint(1)', 'bool', IF (LEFT(COLUMN_TYPE,10) = 'binary(16)' OR LEFT(COLUMN_TYPE,8) = 'char(36)', 'guid', IF (INSTR(COLUMN_TYPE, 'unsigned') = 0, DATA_TYPE, CONCAT('u', DATA_TYPE)))) AS `TypeName`, IF (CHARACTER_MAXIMUM_LENGTH > 2147483647, 2147483647, CHARACTER_MAXIMUM_LENGTH) AS `MaxLength`, NUMERIC_PRECISION AS `Precision`, 0 AS `DateTimePrecision`, NUMERIC_SCALE AS `Scale`, NULL AS `CollationCatalog`, NULL AS `CollationSchema`, COLLATION_NAME AS `CollationName`, NULL AS `CharacterSetCatalog`, NULL AS `CharacterSetSchema`, CHARACTER_SET_NAME AS `CharacterSetName`, 0 AS `IsMultiSet`, CASE WHEN EXTRA LIKE '%auto%' THEN 1 ELSE 0 END AS `IsIdentity`, CASE WHEN EXTRA LIKE '%auto%' THEN 1 ELSE 0 END AS `IsStoreGenerated`, COLUMN_DEFAULT AS `Default` FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=schema() SELECT /* Functions */ CONCAT(ROUTINE_SCHEMA, '.', SPECIFIC_NAME) AS `Id`, ROUTINE_CATALOG AS `CatalogName`, ROUTINE_SCHEMA AS `SchemaName`, ROUTINE_NAME AS `Name`, SUBSTRING_INDEX(DTD_IDENTIFIER, '(', 1) AS `ReturnTypeName`, NULL AS `ReturnMaxLength`, NULL AS `ReturnPrecision`, 0 AS `ReturnDateTimePrecision`, NULL AS `ReturnScale`, NULL AS `ReturnCollationCatalog`, NULL AS `ReturnCollationSchema`, NULL AS `ReturnCollationName`, NULL AS `ReturnCharacterSetCatalog`, NULL AS `ReturnCharacterSetSchema`, NULL AS `ReturnCharacterSetName`, NULL AS `ReturnIsMultiSet`, NULL AS `IsAggregate`, NULL AS `IsBuiltIn`, NULL AS `IsNiladic` FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='FUNCTION' AND ROUTINE_SCHEMA=schema() SELECT /* Procedures */ CONCAT(ROUTINE_SCHEMA, '.', SPECIFIC_NAME) AS `Id`, ROUTINE_CATALOG AS `CatalogName`, ROUTINE_SCHEMA AS `SchemaName`, ROUTINE_NAME AS `Name` FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_TYPE='PROCEDURE' AND ROUTINE_SCHEMA=schema() SELECT /* Function parameters */ NULL AS `Id`, NULL AS `ParentId`, NULL AS `Name`, NULL AS `Ordinal`, NULL AS `TypeName`, NULL AS `MaxLength`, NULL AS `Precision`, NULL AS `DateTimePrecision`, NULL AS `Scale`, NULL AS `CollatioCatalog`, NULL AS `CollationSchema`, NULL AS `CollationName`, NULL AS `CharacterSetCatalog`, NULL AS `CharacterSetSchema`, NULL AS `CharacterSetName`, NULL AS `IsMultiSet`, NULL AS `Mode`, NULL AS `Default` SELECT /* Procedure parameters */ NULL AS `Id`, NULL AS `ParentId`, NULL AS `Name`, NULL AS `Ordinal`, NULL AS `TypeName`, NULL AS `MaxLength`, NULL AS `Precision`, NULL AS `DateTimePrecision`, NULL AS `Scale`, NULL AS `CollatioCatalog`, NULL AS `CollationSchema`, NULL AS `CollationName`, NULL AS `CharacterSetCatalog`, NULL AS `CharacterSetSchema`, NULL AS `CharacterSetName`, NULL AS `IsMultiSet`, NULL AS `Mode`, NULL AS `Default` SELECT /* Constraints */ CONCAT(CONSTRAINT_SCHEMA, '.', TABLE_NAME, '.', CONSTRAINT_NAME) AS `Id`, CONCAT(TABLE_SCHEMA, '.', TABLE_NAME) AS `ParentId`, CONSTRAINT_NAME AS `Name`, CONSTRAINT_TYPE AS `ConstraintType`, 0 AS `IsDeferrable`, 0 AS `IsInitiallyDeferred` FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE != 'CHECK' AND TABLE_SCHEMA=schema() SELECT /* Check constraints */ NULL AS `Id`, NULL AS `Expression` SELECT /* Constraint columns */ CONCAT(CONSTRAINT_SCHEMA, '.', TABLE_NAME, '.', CONSTRAINT_NAME) AS `ConstraintId`, CONCAT(TABLE_SCHEMA, '.', TABLE_NAME, '.', COLUMN_NAME) AS `ColumnId` FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA=schema() SELECT CONCAT(CONSTRAINT_SCHEMA, '.', TABLE_NAME, '.', CONSTRAINT_NAME) AS `Id`, 'NO ACTION' AS `UpdateRule`, 'NO ACTION' AS `DeleteRule` FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE='FOREIGN KEY' SELECT /* Foreign keys */ CONCAT(KCU.TABLE_SCHEMA, '.', KCU.CONSTRAINT_NAME, '.', KCU.ORDINAL_POSITION) AS `Id`, CONCAT(KCU.REFERENCED_TABLE_SCHEMA, '.', KCU.REFERENCED_TABLE_NAME, '.', KCU.REFERENCED_COLUMN_NAME) AS `ToColumnId`, CONCAT(KCU.TABLE_SCHEMA, '.', KCU.TABLE_NAME, '.', KCU.COLUMN_NAME) AS `FromColumnId`, CONCAT(KCU.TABLE_SCHEMA, '.', KCU.TABLE_NAME, '.', KCU.CONSTRAINT_NAME) AS `ConstraintId`, KCU.ORDINAL_POSITION AS `Ordinal` FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS TC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KCU WHERE TC.CONSTRAINT_TYPE = 'FOREIGN KEY' AND TC.TABLE_SCHEMA = KCU.TABLE_SCHEMA AND TC.TABLE_NAME = KCU.TABLE_NAME AND TC.CONSTRAINT_NAME = KCU.CONSTRAINT_NAME AND TC.TABLE_SCHEMA = schema() SELECT /* View constraints */ NULL AS `Id`, NULL AS `ParentId`, NULL AS `Name`, NULL AS `ConstraintType`, NULL AS `Expression`, NULL AS `UpdateRule`, NULL AS `DeleteRule` SELECT /* View constraint columns */ NULL AS `ConstraintId`, NULL AS `ColumnId` SELECT /* View foreign keys */ NULL AS `Id`, NULL AS `ToColumnId`, NULL AS `FromColumnId`, NULL AS `ConstraintId`, 0 AS `Ordinal` mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Properties/ProviderManifest.xml0000644000175000017500000016522411127003600030754 0ustar directhexdirecthex mysql-connector-net-6.4.3/Source/MySql.Data.Entity/Properties/SchemaMapping.msl0000644000175000017500000005177211127003600030204 0ustar directhexdirecthex mysql-connector-net-6.4.3/Source/MySql.Data.Entity/ProviderServices.cs0000644000175000017500000004271311127003600026437 0ustar directhexdirecthex// Copyright (c) 2008 MySQL AB, 2008-2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data.Common; using System.Data.Common.CommandTrees; using System.Collections.Generic; using System.Data.Metadata.Edm; using System.Data; using MySql.Data.Entity; using System.Reflection; using System.Diagnostics; using MySql.Data.Entity.Properties; using System.Text; using System.Linq; namespace MySql.Data.MySqlClient { internal partial class MySqlProviderServices : DbProviderServices { internal static readonly MySqlProviderServices Instance; static MySqlProviderServices() { Instance = new MySqlProviderServices(); } protected override DbCommandDefinition CreateDbCommandDefinition( DbProviderManifest providerManifest, DbCommandTree commandTree) { if (commandTree == null) throw new ArgumentNullException("commandTree"); SqlGenerator generator = null; if (commandTree is DbQueryCommandTree) generator = new SelectGenerator(); else if (commandTree is DbInsertCommandTree) generator = new InsertGenerator(); else if (commandTree is DbUpdateCommandTree) generator = new UpdateGenerator(); else if (commandTree is DbDeleteCommandTree) generator = new DeleteGenerator(); else if (commandTree is DbFunctionCommandTree) generator = new FunctionGenerator(); string sql = generator.GenerateSQL(commandTree); EFMySqlCommand cmd = new EFMySqlCommand(); cmd.CommandText = sql; if (generator is FunctionGenerator) cmd.CommandType = (generator as FunctionGenerator).CommandType; SetExpectedTypes(commandTree, cmd); EdmFunction function = null; if (commandTree is DbFunctionCommandTree) function = (commandTree as DbFunctionCommandTree).EdmFunction; // Now make sure we populate the command's parameters from the CQT's parameters: foreach (KeyValuePair queryParameter in commandTree.Parameters) { DbParameter parameter = cmd.CreateParameter(); parameter.ParameterName = queryParameter.Key; parameter.Direction = ParameterDirection.Input; parameter.DbType = Metadata.GetDbType(queryParameter.Value); FunctionParameter funcParam; if (function != null && function.Parameters.TryGetValue(queryParameter.Key, false, out funcParam)) { parameter.ParameterName = funcParam.Name; parameter.Direction = Metadata.ModeToDirection(funcParam.Mode); parameter.DbType = Metadata.GetDbType(funcParam.TypeUsage); } cmd.Parameters.Add(parameter); } // Now add parameters added as part of SQL gen foreach (DbParameter p in generator.Parameters) cmd.Parameters.Add(p); return CreateCommandDefinition(cmd); } /// /// Sets the expected column types /// private void SetExpectedTypes(DbCommandTree commandTree, EFMySqlCommand cmd) { if (commandTree is DbQueryCommandTree) SetQueryExpectedTypes(commandTree as DbQueryCommandTree, cmd); else if (commandTree is DbFunctionCommandTree) SetFunctionExpectedTypes(commandTree as DbFunctionCommandTree, cmd); } /// /// Sets the expected column types for a given query command tree /// private void SetQueryExpectedTypes(DbQueryCommandTree tree, EFMySqlCommand cmd) { DbProjectExpression projectExpression = tree.Query as DbProjectExpression; if (projectExpression != null) { EdmType resultsType = projectExpression.Projection.ResultType.EdmType; StructuralType resultsAsStructuralType = resultsType as StructuralType; if (resultsAsStructuralType != null) { cmd.ColumnTypes = new PrimitiveType[resultsAsStructuralType.Members.Count]; for (int ordinal = 0; ordinal < resultsAsStructuralType.Members.Count; ordinal++) { EdmMember member = resultsAsStructuralType.Members[ordinal]; PrimitiveType primitiveType = member.TypeUsage.EdmType as PrimitiveType; cmd.ColumnTypes[ordinal] = primitiveType; } } } } /// /// Sets the expected column types for a given function command tree /// private void SetFunctionExpectedTypes(DbFunctionCommandTree tree, EFMySqlCommand cmd) { if (tree.ResultType != null) { Debug.Assert(tree.ResultType.EdmType.BuiltInTypeKind == BuiltInTypeKind.CollectionType, Resources.WrongFunctionResultType); CollectionType collectionType = (CollectionType)(tree.ResultType.EdmType); EdmType elementType = collectionType.TypeUsage.EdmType; if (elementType.BuiltInTypeKind == BuiltInTypeKind.RowType) { ReadOnlyMetadataCollection members = ((RowType)elementType).Members; cmd.ColumnTypes = new PrimitiveType[members.Count]; for (int ordinal = 0; ordinal < members.Count; ordinal++) { EdmMember member = members[ordinal]; PrimitiveType primitiveType = (PrimitiveType)member.TypeUsage.EdmType; cmd.ColumnTypes[ordinal] = primitiveType; } } else if (elementType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType) { cmd.ColumnTypes = new PrimitiveType[1]; cmd.ColumnTypes[0] = (PrimitiveType)elementType; } else { Debug.Fail(Resources.WrongFunctionResultType); } } } protected override string GetDbProviderManifestToken(DbConnection connection) { // we need the connection option to determine what version of the server // we are connected to bool shouldClose = false; if (connection.State == ConnectionState.Closed) { connection.Open(); shouldClose = true; } double version = double.Parse(connection.ServerVersion.Substring(0, 3)); if (shouldClose) connection.Close(); if (version < 5.0) throw new NotSupportedException("Versions of MySQL prior to 5.0 are not currently supported"); if (version < 5.1) return "5.0"; if (version < 5.5) return "5.1"; return "5.5"; } protected override DbProviderManifest GetDbProviderManifest(string manifestToken) { return new MySqlProviderManifest(manifestToken); } #if CLR4 protected override void DbCreateDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { if (connection == null) throw new ArgumentNullException("connection"); MySqlConnection conn = connection as MySqlConnection; if (conn == null) throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection"); string query = DbCreateDatabaseScript(null, storeItemCollection); using (MySqlConnection c = new MySqlConnection()) { MySqlConnectionStringBuilder sb = new MySqlConnectionStringBuilder(conn.ConnectionString); string dbName = sb.Database; sb.Database = null; c.ConnectionString = sb.ConnectionString; c.Open(); string fullQuery = String.Format("CREATE DATABASE `{0}`; USE `{0}`; {1}", dbName, query); MySqlScript s = new MySqlScript(c, fullQuery); s.Execute(); } } protected override bool DbDatabaseExists(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { if (connection == null) throw new ArgumentNullException("connection"); MySqlConnection conn = connection as MySqlConnection; if (conn == null) throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection"); MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(); builder.ConnectionString = conn.ConnectionString; string dbName = builder.Database; builder.Database = null; using (MySqlConnection c = new MySqlConnection(builder.ConnectionString)) { c.Open(); DataTable table = c.GetSchema("Databases", new string[] { dbName }); if (table != null && table.Rows.Count == 1) return true; return false; } } protected override void DbDeleteDatabase(DbConnection connection, int? commandTimeout, StoreItemCollection storeItemCollection) { if (connection == null) throw new ArgumentNullException("connection"); MySqlConnection conn = connection as MySqlConnection; if (conn == null) throw new ArgumentException(Resources.ConnectionMustBeOfTypeMySqlConnection, "connection"); MySqlConnectionStringBuilder builder = new MySqlConnectionStringBuilder(); builder.ConnectionString = conn.ConnectionString; string dbName = builder.Database; builder.Database = null; using (MySqlConnection c = new MySqlConnection(builder.ConnectionString)) { c.Open(); MySqlCommand cmd = new MySqlCommand(String.Format("DROP DATABASE IF EXISTS `{0}`", dbName), c); if (commandTimeout.HasValue) cmd.CommandTimeout = commandTimeout.Value; cmd.ExecuteNonQuery(); } } protected override string DbCreateDatabaseScript(string providerManifestToken, StoreItemCollection storeItemCollection) { StringBuilder sql = new StringBuilder(); sql.AppendLine("-- MySql script"); sql.AppendLine("-- Created on " + DateTime.Now); foreach (EntityContainer container in storeItemCollection.GetItems()) { // now output the tables foreach (EntitySet es in container.BaseEntitySets.OfType()) { sql.Append(GetTableCreateScript(es)); } // now output the foreign keys foreach (AssociationSet a in container.BaseEntitySets.OfType()) { sql.Append(GetAssociationCreateScript(a.ElementType)); } } return sql.ToString(); } private string GetAssociationCreateScript(AssociationType a) { StringBuilder sql = new StringBuilder(); StringBuilder keySql = new StringBuilder(); if (a.IsForeignKey) { EntityType childType = (EntityType)a.ReferentialConstraints[0].ToProperties[0].DeclaringType; EntityType parentType = (EntityType)a.ReferentialConstraints[0].FromProperties[0].DeclaringType; sql.AppendLine(String.Format( "ALTER TABLE `{0}` ADD CONSTRAINT {1}", childType.Name, a.Name)); sql.Append("\t FOREIGN KEY ("); string delimiter = ""; foreach (EdmProperty p in a.ReferentialConstraints[0].ToProperties) { EdmMember member; if (!childType.KeyMembers.TryGetValue(p.Name, false, out member)) keySql.AppendLine(String.Format( "ALTER TABLE `{0}` ADD KEY (`{1}`);", childType.Name, p.Name)); sql.AppendFormat("{0}{1}", delimiter, p.Name); delimiter = ", "; } sql.AppendLine(")"); delimiter = ""; sql.Append(String.Format("\tREFERENCES {0} (", parentType.Name)); foreach (EdmProperty p in a.ReferentialConstraints[0].FromProperties) { EdmMember member; if (!parentType.KeyMembers.TryGetValue(p.Name, false, out member)) keySql.AppendLine(String.Format( "ALTER TABLE `{0}` ADD KEY (`{1}`);", parentType.Name, p.Name)); sql.AppendFormat("{0}{1}", delimiter, p.Name); delimiter = ", "; } sql.AppendLine(");"); sql.AppendLine(); } keySql.Append(sql.ToString()); return keySql.ToString(); } #endif private string GetTableCreateScript(EntitySet entitySet) { EntityType e = entitySet.ElementType; StringBuilder sql = new StringBuilder("CREATE TABLE "); sql.AppendFormat("`{0}`(", e.Name); string delimiter = ""; bool hasPK = false; foreach (EdmProperty c in e.Properties) { Facet facet; hasPK = hasPK || (c.TypeUsage.Facets.TryGetValue("StoreGeneratedPattern", false, out facet) && facet.Value.Equals(StoreGeneratedPattern.Identity)); sql.AppendFormat("{0}{1}\t`{2}` {3}{4}", delimiter, Environment.NewLine, c.Name, GetColumnType(c.TypeUsage), GetFacetString(c)); delimiter = ", "; } sql.AppendLine(");"); sql.AppendLine(); if (!hasPK && e.KeyMembers.Count > 0) { sql.Append(String.Format( "ALTER TABLE `{0}` ADD PRIMARY KEY (", e.Name)); delimiter = ""; foreach (EdmMember m in e.KeyMembers) { sql.AppendFormat("{0}{1}", delimiter, m.Name); delimiter = ", "; } sql.AppendLine(");"); sql.AppendLine(); } return sql.ToString(); } private string GetColumnType(TypeUsage type) { string t = type.EdmType.Name; if (t.StartsWith("u")) { t = t.Substring(1).ToUpperInvariant() + " UNSIGNED"; } else if (String.Compare(t, "guid", true) == 0) return "CHAR(36) BINARY"; return t; } private string GetFacetString(EdmProperty column) { StringBuilder sql = new StringBuilder(); Facet facet; ReadOnlyMetadataCollection facets = column.TypeUsage.Facets; if (column.TypeUsage.EdmType.BaseType.Name == "String") { if (facets.TryGetValue("MaxLength", true, out facet)) sql.AppendFormat(" ({0})", facet.Value); } if (facets.TryGetValue("Nullable", true, out facet) && (bool)facet.Value == false) sql.Append(" NOT NULL"); if (facets.TryGetValue("StoreGeneratedPattern", true, out facet) && facet.Value.Equals(StoreGeneratedPattern.Identity)) sql.Append(" AUTO_INCREMENT PRIMARY KEY"); return sql.ToString(); } private bool IsStringType(TypeUsage type) { return false; } } } mysql-connector-net-6.4.3/Source/MySql.Data.Entity/EFMySqlCommand.cs0000644000175000017500000001013011127003600025704 0ustar directhexdirecthex// Copyright (c) 2009 Sun Microsystems, Inc. // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Data.Common; using System.Data.Metadata.Edm; using System.Data; using MySql.Data.MySqlClient; namespace MySql.Data.Entity { class EFMySqlCommand : DbCommand, ICloneable { private bool designTimeVisible = true; private DbConnection connection; private MySqlCommand command = new MySqlCommand(); internal PrimitiveType[] ColumnTypes; #region Properties public override string CommandText { get { return command.CommandText; } set { command.CommandText = value; } } public override int CommandTimeout { get { return command.CommandTimeout; } set { command.CommandTimeout = value; } } public override CommandType CommandType { get { return command.CommandType; } set { command.CommandType = value; } } public override bool DesignTimeVisible { get { return designTimeVisible; } set { designTimeVisible = value; } } protected override DbConnection DbConnection { get { return connection; } set { connection = value; command.Connection = (MySqlConnection)value; } } protected override DbTransaction DbTransaction { get { return command.Transaction; } set { command.Transaction = (MySqlTransaction)value; } } protected override DbParameterCollection DbParameterCollection { get { return command.Parameters; } } public override UpdateRowSource UpdatedRowSource { get { return command.UpdatedRowSource; } set { command.UpdatedRowSource = value; } } #endregion public override void Cancel() { command.Cancel(); } protected override DbParameter CreateDbParameter() { return new MySqlParameter(); } protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) { return new EFMySqlDataReader(this, command.ExecuteReader(behavior)); } public override int ExecuteNonQuery() { return command.ExecuteNonQuery(); } public override object ExecuteScalar() { return command.ExecuteScalar(); } public override void Prepare() { command.Prepare(); } #region ICloneable Members public object Clone() { EFMySqlCommand clone = new EFMySqlCommand(); clone.connection = connection; clone.ColumnTypes = ColumnTypes; clone.command = (MySqlCommand)((ICloneable)command).Clone(); return clone; } #endregion } } mysql-connector-net-6.4.3/CHANGES0000644000175000017500000000766011127003600017157 0ustar directhexdirecthex6.4.3 (ga) - Modified SqlFragment.QuoteIdentifier to add MySQL quotes around identifiers (MySQL bug #61635, Oracle bug #12707285). - Modified the SchemaDefinition-5.5.ssdl to treat char(36) columns as GUID (MySQL bug #61657, Oracle bug #12708208). 6.4.2 (rc) - Fixed Entity Framework provider GROUP BY clause generation by adding all group by keys to the SELECT statement (MySQL bug #46742, Oracle bug #12622129). - Modified ProviderManifest.xml to map TIMESTAMP db fields to the DateTime .NET type (MySQL bug #55351, Oracle bug #12652602). - Modified MySqlConnection.BeginTransaction to throw a NotSupportedException when Snapshot isolation level is requested (MySQL bug #61589, Oracle bug #12698020). 6.4.1 (beta) - modified schema1.sql in MySql.Web to remove ENGINE declaration on table creation (Oracle bug #12311974). - fixed performance issue with executing stored procedures with output parameters (MySQL bug #60366, Oracle bug#12425959) - Introduced more detailed exceptions for invalid connection strings errors (MySQL bug#44654, MySQL bug#53076). - Introduced the real NUnit framework to the CF test suite and fixed issues on BaseTest to properly run with CF libraries. - Modified MySql.Data.Entity.ProviderServices to use the correct schema definition file when server is 5.5 or greater (Oracle bug #12407444). - Introduced a new unit test to ensure a commit will not timeout after a heavly load of inserts (MySQL bug #58004). - fixed ISSchemaProvider to use the information schema to retrieve parameter metadata when running against server 5.5.3 or greater (MySQL bug #48007, Oracle bug #12539685). - Fixed MySqlProviderManifest.GetStoreSchemaDescription() to return the correct schema definition depending on the server version. - Fixed Driver creation to not crash when it can't instantiate MySqlTrace type because of missing permissions (MySQL bug #59202, Oracle bug #12548114). - Added entity framework support for MySQL Server Round(X, D) function (MySQL bug #58552, Oracle bug #11765569). - Introduced a connection string check and exception to notify that it is not possible to use SSL related keywords when running on the Compact Framework. Also all SSL related keywords in ConnectionStringBuilder are now hidden when running on the Compact Framework (MySQL bug #60600). - Fixed MembershipProvider to only return exact matches when calling GetUser(string username) and GetUserNameByEmail (MySQL bug #61027, Oracle bug #12562287). - added the ability to raise a join on the right side of a join to a derived table in EF code generation (bug #48791) - Reintroduced implementations for DbCreateDatabase, DbDatabaseExists, DbDeleteDatabase and DbCreateDatabaseScript in MySqlProviderServices. In this update none of those methods require access to the mysql database (MySQL bug #59168, Oracle bug #11766128). - Modified EFMySqlDataReader to read byte[] values as booleans when the server incorrectly reports bits as binaries when they are members of internal EF UNIONS (MySQL bug #60652, Oracle bug #12593193). - Modified Connection.Open() to not reuse existing driver instance when that instance is closed. Also made Connection.Abort() always close the current driver, even if the connection is pooled. (MySQL bug #58316, Oracle bug #12613102). - Added Visual Studio DDEX support for Compact Framework projects (MySQL bug #54607, Oracle bug #12605152). - Added Replication connection string option to indicate that the connection is using read-only replicated servers This is the first step toward better replication support. 6.4.0 - Implemented Cache Server Properties connection option - Implementd Windows authentication when used against a 5.5 server - Implementd table caching - Introduced workaround to unexpected query aborts (server 5.1+) when executing a datareader after a command.Cancel() (MySQL bug#60541). - Fixed SetSite issues with Visual Studio 2010 integration (MySQL bug#60723, Oracle bug #12394470) mysql-connector-net-6.4.3/Release Notes.txt0000644000175000017500000000746111127003600021355 0ustar directhexdirecthexConnector/Net 6.4 Release Notes ------------------------------------ Welcome to the release notes for Connector/Net 6.4 What's new in 6.4 -------------------- - Support for Windows authentication in the driver - Support for table caching (see below) - Improved SQL generation from the Entity Framework provider - Connection failover support What we know is broken ---------------------- - Documentation has not been updated yet. - The Generated Database Wizard will save the file with the extension .sql. You will need to manually change the extension to .mysql to use the new editor. What we changed in 6.3.7 that came over to 6.4 ------------------------ We introduced a slight change in behavior with 6.3.7. We did this as part of a larger change to address a performance issue. It's a relatively minor change in behavior however we encourage you to read this section carefully and review your application for areas that might be affected. We have made the Use Procedure Bodies flag obsolete and introduced the Check Parameters option. They server mainly the same purpose. The Check Parameters option is true by default. Setting to false tells Connector/Net to not fetch any routine or parameter metadata and to simply trust what the user has specified. This can greatly increase performance but it also puts significant pressure on the application developer to give the parameters in the right order. The next change in behavior is that Connector/Net no longer allows you to call a stored function without specifying a return value. We are now using the presence of a return value parameter as a signal that we should execute the routine as a stored function. If you don't care about the return value, then give a place holder value. The next change is that if you user has insufficient permissions to retrieve parameter metadata, you are not connecting to server 5.5 or later, and you have specified Check Parameters then the connector will throw an InvalidOperationException indicating that you have insufficient privileges to retrieve routine parameter metadata. In the past the connector would silently use the parameters you gave on the command. We apologize for introducing these changes in a GA product but we felt it was important as these changes greatly increase the speed that we execute stored routines. Table Caching ------------- We have not yet updated the documentation so we write a few words on table caching here. Table Caching is a new feature that users can use to cache slow-changing datasets on the client side. This is useful for apps that are designed to use readers but you still want to minimize trips to the server for slow-changing tables. It is transparent to the user. It is not enabled by default. To enable caching, add 'table cache=true' to your connection string. You can also use the 'Default Table Cache Age' connection string option to specify the number of seconds a table is cached before being discarded. You can also set caching and cache age options on a per command basis. Please note that the cache age property is in "seconds". In the future we may extend this feature to allow the end user to provide their own implementation or we may provide an implementation of table caching that can take advantage of services such as memcached or velocity. Connection Failover ------------------- We are introducing a new connection string keyword called 'Replication'. By setting this to yes or true you are indicating that this connection will use a set of replicated servers. With this release replicated servers are only supported on TCP/IP connections and it supports connection failover on the initial connection. The servers are specified comma-separated. An example would be 'server=server1,server2,server3; replication=yes' mysql-connector-net-6.4.3/README0000644000175000017500000000515211127003600017036 0ustar directhexdirecthexMySQL Connector/Net 6.x This is a release of MySQL Connector/Net, Oracle's dual- license ADO.Net Driver for MySQL. For the avoidance of doubt, this particular copy of the software is released under the version 2 of the GNU General Public License. MySQL Connector/Net is brought to you by the MySQL team at Oracle. Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved. CONTENTS * License * Documentation Location * Third-Party Component Notices LICENSE The MySQL Connector/Net is licensed under the terms of the GPLv2 , like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FLOSS License Exception . License information can be found in the COPYING file. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. DOCUMENTATION LOCATION The documentation currently exists in MSDN help format and is located in the 'doc' directory. This software is OSI Certified Open Source Software. OSI Certified is a certification mark of the Open Source Initiative. *************************************************************** Third-Party Component Notices **************************************************************** This distribution may include materials developed by third parties. For license and attribution notices for these materials, please refer to the documentation that accompanies this distribution. GPLv2 Disclaimer For the avoidance of doubt, except that if any license choice other than GPL or LGPL is available it will apply instead, Oracle elects to use only the General Public License version 2 (GPLv2) at this time for any software where a choice of GPL license versions is made available with the language indicating that GPLv2 or any later version may be used, or where a choice of which version of the GPL is applied is otherwise unspecified. mysql-connector-net-6.4.3/MySQLClient-mono.sln0000644000175000017500000003006311127003600021745 0ustar directhexdirecthex Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Web", "MySql.Web\Providers\MySql.Web.csproj", "{C28B1166-1380-445D-AEC1-8A18B990DD18}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Web.Tests", "MySql.Web\Tests\MySql.Web.Tests.csproj", "{DC704374-EC50-4167-93AA-8D262136502E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data", "MySql.Data\Provider\MySql.Data.csproj", "{E9DF5ED1-4CBD-4226-B931-9A51610AC14D}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MySql.Data.Tests", "MySql.Data\Tests\MySql.Data.Tests.csproj", "{F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Commercial|Any CPU = Commercial|Any CPU Commercial|Mixed Platforms = Commercial|Mixed Platforms Commercial|x64 = Commercial|x64 Commercial|x86 = Commercial|x86 Debug|Any CPU = Debug|Any CPU Debug|Mixed Platforms = Debug|Mixed Platforms Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 GPL|Any CPU = GPL|Any CPU GPL|Mixed Platforms = GPL|Mixed Platforms GPL|x64 = GPL|x64 GPL|x86 = GPL|x86 Release|Any CPU = Release|Any CPU Release|Mixed Platforms = Release|Mixed Platforms Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {C28B1166-1380-445D-AEC1-8A18B990DD18}.Commercial|Any CPU.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Commercial|Any CPU.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Commercial|Mixed Platforms.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Commercial|Mixed Platforms.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Commercial|x64.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Commercial|x86.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|Any CPU.Build.0 = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|x64.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Debug|x86.ActiveCfg = Debug|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.GPL|Any CPU.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.GPL|Any CPU.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.GPL|Mixed Platforms.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.GPL|Mixed Platforms.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.GPL|x64.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.GPL|x86.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|Any CPU.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|Any CPU.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|Mixed Platforms.Build.0 = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|x64.ActiveCfg = Release|Any CPU {C28B1166-1380-445D-AEC1-8A18B990DD18}.Release|x86.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Commercial|Any CPU.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Commercial|Any CPU.Build.0 = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Commercial|Mixed Platforms.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Commercial|Mixed Platforms.Build.0 = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Commercial|x64.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Commercial|x86.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Debug|Any CPU.Build.0 = Debug|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Debug|x64.ActiveCfg = Debug|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Debug|x86.ActiveCfg = Debug|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.GPL|Any CPU.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.GPL|Any CPU.Build.0 = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.GPL|Mixed Platforms.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.GPL|Mixed Platforms.Build.0 = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.GPL|x64.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.GPL|x86.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Release|Any CPU.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Release|Any CPU.Build.0 = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Release|Mixed Platforms.Build.0 = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Release|x64.ActiveCfg = Release|Any CPU {DC704374-EC50-4167-93AA-8D262136502E}.Release|x86.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|Any CPU.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|Any CPU.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|Mixed Platforms.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|Mixed Platforms.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|x64.ActiveCfg = Release|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|x86.ActiveCfg = Release|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Commercial|x86.Build.0 = Release|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|Any CPU.Build.0 = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|x64.ActiveCfg = Debug|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|x86.ActiveCfg = Debug|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Debug|x86.Build.0 = Debug|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|Any CPU.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|Any CPU.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|Mixed Platforms.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|Mixed Platforms.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|x64.ActiveCfg = Release|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|x86.ActiveCfg = Release|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.GPL|x86.Build.0 = Release|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|Any CPU.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|Any CPU.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|Mixed Platforms.Build.0 = Release|Any CPU {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|x64.ActiveCfg = Release|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|x86.ActiveCfg = Release|x86 {E9DF5ED1-4CBD-4226-B931-9A51610AC14D}.Release|x86.Build.0 = Release|x86 {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Commercial|Any CPU.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Commercial|Any CPU.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Commercial|Mixed Platforms.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Commercial|Mixed Platforms.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Commercial|x64.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Commercial|x86.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|Any CPU.Build.0 = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|x64.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Debug|x86.ActiveCfg = Debug|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.GPL|Any CPU.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.GPL|Any CPU.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.GPL|Mixed Platforms.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.GPL|Mixed Platforms.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.GPL|x64.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.GPL|x86.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|Any CPU.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|Any CPU.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|Mixed Platforms.Build.0 = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|x64.ActiveCfg = Release|Any CPU {F29E5B3D-7F76-4CF9-BF5E-8E3A1377B1E4}.Release|x86.ActiveCfg = Release|Any CPU {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|Any CPU.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|Any CPU.Build.0 = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|Mixed Platforms.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|Mixed Platforms.Build.0 = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|x64.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|x86.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Commercial|x86.Build.0 = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Debug|Any CPU.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Debug|Mixed Platforms.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Debug|Mixed Platforms.Build.0 = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Debug|x64.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Debug|x86.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Debug|x86.Build.0 = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|Any CPU.ActiveCfg = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|Any CPU.Build.0 = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|Mixed Platforms.ActiveCfg = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|Mixed Platforms.Build.0 = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|x64.ActiveCfg = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|x86.ActiveCfg = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.GPL|x86.Build.0 = GPL|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Release|Any CPU.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Release|Mixed Platforms.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Release|Mixed Platforms.Build.0 = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Release|x64.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Release|x86.ActiveCfg = Commercial|x86 {F533FC43-6C05-4A64-8AF6-72B690EB06C3}.Release|x86.Build.0 = Commercial|x86 EndGlobalSection GlobalSection(MonoDevelopProperties) = preSolution StartupItem = MySql.Web\Providers\MySql.Web.csproj version = 0.1 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal mysql-connector-net-6.4.3/Samples/0000755000175000017500000000000011127003600017557 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/Async/0000755000175000017500000000000011127003600020634 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/Async/cs/0000755000175000017500000000000011127003600021241 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/Async/cs/Form1.cs0000644000175000017500000002204611127003600022560 0ustar directhexdirecthexusing System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using MySql.Data.MySqlClient; namespace Async { /// /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TextBox nonQueryOutput; private System.Windows.Forms.Button nonQueryGo; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox server; private System.Windows.Forms.TextBox uid; private System.Windows.Forms.TextBox pwd; private System.Windows.Forms.TextBox database; private System.Windows.Forms.Timer timer1; private System.ComponentModel.IContainer components; private MySqlConnection conn; private MySqlCommand cmd; private int nextTime; private IAsyncResult asyncResult; private DateTime start; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); } /// /// Clean up any resources being used. /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.database = new System.Windows.Forms.TextBox(); this.pwd = new System.Windows.Forms.TextBox(); this.uid = new System.Windows.Forms.TextBox(); this.server = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.nonQueryGo = new System.Windows.Forms.Button(); this.nonQueryOutput = new System.Windows.Forms.TextBox(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.tabControl1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.tabPage1.SuspendLayout(); this.SuspendLayout(); // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(504, 370); this.tabControl1.TabIndex = 0; // // tabPage2 // this.tabPage2.Controls.Add(this.database); this.tabPage2.Controls.Add(this.pwd); this.tabPage2.Controls.Add(this.uid); this.tabPage2.Controls.Add(this.server); this.tabPage2.Controls.Add(this.label4); this.tabPage2.Controls.Add(this.label3); this.tabPage2.Controls.Add(this.label2); this.tabPage2.Controls.Add(this.label1); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Size = new System.Drawing.Size(496, 344); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Configuration"; // // database // this.database.Location = new System.Drawing.Point(116, 128); this.database.Name = "database"; this.database.Size = new System.Drawing.Size(228, 20); this.database.TabIndex = 7; this.database.Text = ""; // // pwd // this.pwd.Location = new System.Drawing.Point(116, 92); this.pwd.Name = "pwd"; this.pwd.Size = new System.Drawing.Size(228, 20); this.pwd.TabIndex = 6; this.pwd.Text = ""; // // uid // this.uid.Location = new System.Drawing.Point(116, 56); this.uid.Name = "uid"; this.uid.Size = new System.Drawing.Size(228, 20); this.uid.TabIndex = 5; this.uid.Text = ""; // // server // this.server.Location = new System.Drawing.Point(116, 20); this.server.Name = "server"; this.server.Size = new System.Drawing.Size(228, 20); this.server.TabIndex = 4; this.server.Text = ""; // // label4 // this.label4.Location = new System.Drawing.Point(16, 128); this.label4.Name = "label4"; this.label4.TabIndex = 3; this.label4.Text = "Database:"; // // label3 // this.label3.Location = new System.Drawing.Point(16, 92); this.label3.Name = "label3"; this.label3.TabIndex = 2; this.label3.Text = "Password:"; // // label2 // this.label2.Location = new System.Drawing.Point(16, 56); this.label2.Name = "label2"; this.label2.TabIndex = 1; this.label2.Text = "User Id:"; // // label1 // this.label1.Location = new System.Drawing.Point(16, 20); this.label1.Name = "label1"; this.label1.TabIndex = 0; this.label1.Text = "Server/Host:"; // // tabPage1 // this.tabPage1.Controls.Add(this.nonQueryGo); this.tabPage1.Controls.Add(this.nonQueryOutput); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Size = new System.Drawing.Size(496, 344); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "NonQuery"; // // nonQueryGo // this.nonQueryGo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.nonQueryGo.Location = new System.Drawing.Point(404, 312); this.nonQueryGo.Name = "nonQueryGo"; this.nonQueryGo.TabIndex = 1; this.nonQueryGo.Text = "Go"; this.nonQueryGo.Click += new System.EventHandler(this.nonQueryGo_Click); // // nonQueryOutput // this.nonQueryOutput.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.nonQueryOutput.Location = new System.Drawing.Point(12, 36); this.nonQueryOutput.Multiline = true; this.nonQueryOutput.Name = "nonQueryOutput"; this.nonQueryOutput.Size = new System.Drawing.Size(468, 268); this.nonQueryOutput.TabIndex = 0; this.nonQueryOutput.Text = ""; // // timer1 // this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(504, 370); this.Controls.Add(this.tabControl1); this.Name = "Form1"; this.Text = "Form1"; this.tabControl1.ResumeLayout(false); this.tabPage2.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void nonQueryGo_Click(object sender, System.EventArgs e) { string connStr = String.Format("server={0};uid={1};pwd={2};database={3}", server.Text, uid.Text, pwd.Text, database.Text); conn = new MySqlConnection(connStr); try { conn.Open(); string sql = "DROP TABLE IF EXISTS AsyncSampleTable; CREATE TABLE AsyncSampleTable (numVal int)"; cmd = new MySqlCommand(sql, conn); cmd.ExecuteNonQuery(); sql = "DROP PROCEDURE IF EXISTS AsyncSample;" + "CREATE PROCEDURE AsyncSample() BEGIN " + "set @x=0; repeat set @x=@x+1; until @x > 5000000 end repeat; " + "INSERT INTO AsyncSampleTable VALUES (1); end;"; cmd.CommandText = sql; cmd.ExecuteNonQuery(); cmd.CommandText = "AsyncSample"; cmd.CommandType = CommandType.StoredProcedure; asyncResult = cmd.BeginExecuteNonQuery(); nextTime = 5; timer1.Enabled = true; start = DateTime.Now; } catch (Exception ex) { MessageBox.Show("Exception: " + ex.Message); } } private void timer1_Tick(object sender, System.EventArgs e) { if (! asyncResult.IsCompleted) { TimeSpan ts = DateTime.Now.Subtract(start); if (ts.TotalSeconds > nextTime) { nonQueryOutput.Text += Convert.ToInt32(ts.TotalSeconds) + " seconds" + Environment.NewLine; nextTime += 5; } return; } int recordsAffected = cmd.EndExecuteNonQuery(asyncResult); nonQueryOutput.Text += "Records Affected = " + recordsAffected; conn.Close(); timer1.Enabled = false; } } } mysql-connector-net-6.4.3/Samples/Async/cs/Form1.resx0000644000175000017500000003703511127003600023140 0ustar directhexdirecthex text/microsoft-resx 1.3 System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 True False True Private Private 4, 4 False True True Private Private 4, 4 Private False Private Private False Private Private False Private Private False Private False Private Private False Private Private False Private Private False Private Private False True True Private Private 4, 4 False Private Private Private False Private Private 17, 17 Private False (Default) False Form1 False 4, 4 True 80 True Private mysql-connector-net-6.4.3/Samples/Async/cs/App.ico0000644000175000017500000000206611127003600022461 0ustar directhexdirecthex &(( @wwwwwwwwwwwwwwpDDDDDDDDDDDDDDppppppppppppppppppppDDDDDDDDDDDDDDpLLLLLLLLLNItpDDDDDDDDDDDDD@( wwwwwwwDDDDDDDGOGOGOGOGOGOGOGOGHGLGDDDDDDmysql-connector-net-6.4.3/Samples/Async/cs/AssemblyInfo.cs0000644000175000017500000000457211127003600024173 0ustar directhexdirecthexusing System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] mysql-connector-net-6.4.3/Samples/Async/cs/Async.csproj0000644000175000017500000001017411127003600023543 0ustar directhexdirecthex Local 8.0.50727 2.0 {4DEB1579-3952-4A42-9AA7-18AD522F02FF} Debug AnyCPU App.ico Async JScript Grid IE50 false WinExe Async OnBuildSuccess bin\Debug\ false 285212672 false DEBUG;TRACE true 4096 false false false false false 4 full prompt bin\Release\ false 285212672 false TRACE false 4096 false true false false false 4 none prompt MySQL.Data ..\..\bin\net-1.1\Debug\MySQL.Data.dll System System.Data System.Drawing System.Windows.Forms System.XML Form Form1.cs Designer mysql-connector-net-6.4.3/Samples/TableEditor/0000755000175000017500000000000011127003600021755 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/TableEditor/CS/0000755000175000017500000000000011127003600022262 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/TableEditor/CS/Form1.cs0000644000175000017500000002553211127003600023604 0ustar directhexdirecthex// Copyright (C) 2004-2005 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using MySql.Data.MySqlClient; namespace TableEditor { /// /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox tables; private System.Windows.Forms.TextBox server; private System.Windows.Forms.TextBox userid; private System.Windows.Forms.TextBox password; private System.Windows.Forms.Button connectBtn; private System.Windows.Forms.Button updateBtn; /// /// Required designer variable. /// private System.ComponentModel.Container components = null; private System.Windows.Forms.ComboBox databaseList; private System.Windows.Forms.Label label5; private MySqlConnection conn; private DataTable data; private MySqlDataAdapter da; private System.Windows.Forms.DataGrid dataGrid; private MySqlCommandBuilder cb; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// /// Clean up any resources being used. /// protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.server = new System.Windows.Forms.TextBox(); this.userid = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.password = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.connectBtn = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.tables = new System.Windows.Forms.ComboBox(); this.dataGrid = new System.Windows.Forms.DataGrid(); this.updateBtn = new System.Windows.Forms.Button(); this.databaseList = new System.Windows.Forms.ComboBox(); this.label5 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(8, 11); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(48, 16); this.label1.TabIndex = 0; this.label1.Text = "Server:"; // // server // this.server.Location = new System.Drawing.Point(56, 8); this.server.Name = "server"; this.server.Size = new System.Drawing.Size(320, 20); this.server.TabIndex = 1; this.server.Text = ""; // // userid // this.userid.Location = new System.Drawing.Point(56, 32); this.userid.Name = "userid"; this.userid.Size = new System.Drawing.Size(120, 20); this.userid.TabIndex = 3; this.userid.Text = ""; // // label2 // this.label2.Location = new System.Drawing.Point(8, 37); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(48, 16); this.label2.TabIndex = 2; this.label2.Text = "User Id:"; // // password // this.password.Location = new System.Drawing.Point(260, 32); this.password.Name = "password"; this.password.PasswordChar = '*'; this.password.Size = new System.Drawing.Size(116, 20); this.password.TabIndex = 5; this.password.Text = ""; // // label3 // this.label3.Location = new System.Drawing.Point(192, 37); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(56, 16); this.label3.TabIndex = 4; this.label3.Text = "Password:"; // // connectBtn // this.connectBtn.Location = new System.Drawing.Point(400, 8); this.connectBtn.Name = "connectBtn"; this.connectBtn.TabIndex = 6; this.connectBtn.Text = "Connect"; this.connectBtn.Click += new System.EventHandler(this.connectBtn_Click); // // label4 // this.label4.Location = new System.Drawing.Point(8, 109); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(64, 16); this.label4.TabIndex = 0; this.label4.Text = "Tables"; // // tables // this.tables.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.tables.Location = new System.Drawing.Point(80, 104); this.tables.Name = "tables"; this.tables.Size = new System.Drawing.Size(296, 21); this.tables.TabIndex = 7; this.tables.SelectedIndexChanged += new System.EventHandler(this.tables_SelectedIndexChanged); // // dataGrid // this.dataGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGrid.DataMember = ""; this.dataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dataGrid.Location = new System.Drawing.Point(8, 136); this.dataGrid.Name = "dataGrid"; this.dataGrid.Size = new System.Drawing.Size(544, 312); this.dataGrid.TabIndex = 8; // // updateBtn // this.updateBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.updateBtn.Location = new System.Drawing.Point(477, 104); this.updateBtn.Name = "updateBtn"; this.updateBtn.TabIndex = 9; this.updateBtn.Text = "Update"; this.updateBtn.Click += new System.EventHandler(this.updateBtn_Click); // // databaseList // this.databaseList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.databaseList.Location = new System.Drawing.Point(80, 80); this.databaseList.Name = "databaseList"; this.databaseList.Size = new System.Drawing.Size(296, 21); this.databaseList.TabIndex = 11; this.databaseList.SelectedIndexChanged += new System.EventHandler(this.databaseList_SelectedIndexChanged); // // label5 // this.label5.Location = new System.Drawing.Point(8, 85); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(64, 16); this.label5.TabIndex = 10; this.label5.Text = "Databases"; // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(560, 453); this.Controls.Add(this.databaseList); this.Controls.Add(this.label5); this.Controls.Add(this.updateBtn); this.Controls.Add(this.dataGrid); this.Controls.Add(this.tables); this.Controls.Add(this.connectBtn); this.Controls.Add(this.password); this.Controls.Add(this.label3); this.Controls.Add(this.userid); this.Controls.Add(this.label2); this.Controls.Add(this.server); this.Controls.Add(this.label1); this.Controls.Add(this.label4); this.Name = "Form1"; this.Text = "Form1"; ((System.ComponentModel.ISupportInitialize)(this.dataGrid)).EndInit(); this.ResumeLayout(false); } #endregion /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.Run(new Form1()); } private void connectBtn_Click(object sender, System.EventArgs e) { if (conn != null) conn.Close(); string connStr = String.Format("server={0};user id={1}; password={2}; database=mysql; pooling=false", server.Text, userid.Text, password.Text ); try { conn = new MySqlConnection( connStr ); conn.Open(); GetDatabases(); } catch (MySqlException ex) { MessageBox.Show( "Error connecting to the server: " + ex.Message ); } } private void GetDatabases() { MySqlDataReader reader = null; MySqlCommand cmd = new MySqlCommand("SHOW DATABASES", conn); try { reader = cmd.ExecuteReader(); databaseList.Items.Clear(); while (reader.Read()) { databaseList.Items.Add( reader.GetString(0) ); } } catch (MySqlException ex) { MessageBox.Show("Failed to populate database list: " + ex.Message ); } finally { if (reader != null) reader.Close(); } } private void databaseList_SelectedIndexChanged(object sender, System.EventArgs e) { MySqlDataReader reader = null; conn.ChangeDatabase( databaseList.SelectedItem.ToString() ); MySqlCommand cmd = new MySqlCommand("SHOW TABLES", conn); try { reader = cmd.ExecuteReader(); tables.Items.Clear(); while (reader.Read()) { tables.Items.Add( reader.GetString(0) ); } } catch (MySqlException ex) { MessageBox.Show("Failed to populate table list: " + ex.Message ); } finally { if (reader != null) reader.Close(); } } private void tables_SelectedIndexChanged(object sender, System.EventArgs e) { data = new DataTable(); da = new MySqlDataAdapter("SELECT * FROM " + tables.SelectedItem.ToString(), conn ); cb = new MySqlCommandBuilder( da ); da.Fill( data ); dataGrid.DataSource = data; } private void updateBtn_Click(object sender, System.EventArgs e) { DataTable changes = data.GetChanges(); da.Update( changes ); data.AcceptChanges(); } } } mysql-connector-net-6.4.3/Samples/TableEditor/CS/Form1.resx0000644000175000017500000003263411127003600024161 0ustar directhexdirecthex text/microsoft-resx 1.3 System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 False Private Private Private False Private Private False Private False Private Private Private False Private False Private Private False Private Private False Private Private Private False Private False Private Private False Private Private Private False Private False Private Private False (Default) False False 8, 8 True 80 True Private Form1 mysql-connector-net-6.4.3/Samples/TableEditor/CS/App.ico0000644000175000017500000000206611127003600023502 0ustar directhexdirecthex &(( @wwwwwwwwwwwwwwpDDDDDDDDDDDDDDppppppppppppppppppppDDDDDDDDDDDDDDpLLLLLLLLLNItpDDDDDDDDDDDDD@( wwwwwwwDDDDDDDGOGOGOGOGOGOGOGOGHGLGDDDDDDmysql-connector-net-6.4.3/Samples/TableEditor/CS/AssemblyInfo.cs0000644000175000017500000000671311127003600025213 0ustar directhexdirecthex// Copyright (C) 2004-2005 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] mysql-connector-net-6.4.3/Samples/TableEditor/CS/TableEditor.build0000644000175000017500000000211311127003600025476 0ustar directhexdirecthex TableEditor sample mysql-connector-net-6.4.3/Samples/TableEditor/CS/TableEditor.csproj0000644000175000017500000001027011127003600025702 0ustar directhexdirecthex Local 8.0.50727 2.0 {EE6AE06F-6BAC-4265-89B3-9CB5099D2D70} Debug AnyCPU App.ico TableEditor JScript Grid IE50 false WinExe TableEditor OnBuildSuccess bin\Debug\ false 285212672 false DEBUG;TRACE true 4096 false false false false false 4 full prompt bin\Release\ false 285212672 false TRACE false 4096 false true false false false 4 none prompt MySQL.Data ..\..\..\bin\net-1.1\Debug\MySQL.Data.dll System System.Data System.Drawing System.Windows.Forms System.XML Code Form Form1.cs Designer mysql-connector-net-6.4.3/Samples/TableEditor/VB/0000755000175000017500000000000011127003600022264 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/TableEditor/VB/TableEditor.vbproj0000644000175000017500000001063311127003600025711 0ustar directhexdirecthex Local 8.0.50727 2.0 {B1FDEC2E-E8B1-4239-A03A-8B096585F610} Debug AnyCPU TableEditor None JScript Grid IE50 false WinExe Binary On Off TableEditor TableEditor.Form1 WindowsFormsWithCustomSubMain bin\ TableEditor.xml 285212672 true true true false false false false 1 42016,42017,42018,42019,42032 full bin\ TableEditor.xml 285212672 false true false true false false false 1 42016,42017,42018,42019,42032 none MySQL.Data ..\..\..\bin\net-1.1\Debug\MySQL.Data.dll System System.Data System.Drawing System.Windows.Forms System.XML Code Form Form1.vb Designer mysql-connector-net-6.4.3/Samples/TableEditor/VB/Form1.resx0000644000175000017500000003266711127003600024171 0ustar directhexdirecthex text/microsoft-resx 1.3 System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Assembly False Assembly False Assembly Assembly False Assembly Assembly False Assembly Assembly Assembly False Assembly False Assembly Assembly Assembly False Assembly False Assembly Assembly Assembly False Assembly False Assembly Assembly Assembly False Assembly False Assembly Assembly False Assembly Assembly False (Default) False Form1 False 8, 8 True 80 True Assembly mysql-connector-net-6.4.3/Samples/TableEditor/VB/AssemblyInfo.vb0000644000175000017500000000364511127003600025220 0ustar directhexdirecthex' Copyright (C) 2004-2005 MySQL AB ' ' This program is free software; you can redistribute it and/or modify ' it under the terms of the GNU General Public License version 2 as published by ' the Free Software Foundation ' ' There are special exceptions to the terms and conditions of the GPL ' as it is applied to this software. View the full text of the ' exception in file EXCEPTIONS in the directory of this software ' distribution. ' ' This program is distributed in the hope that it will be useful, ' but WITHOUT ANY WARRANTY; without even the implied warranty of ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ' GNU General Public License for more details. ' ' You should have received a copy of the GNU General Public License ' along with this program; if not, write to the Free Software ' Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes 'The following GUID is for the ID of the typelib if this project is exposed to COM ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: mysql-connector-net-6.4.3/Samples/TableEditor/VB/Form1.vb0000644000175000017500000002621411127003600023606 0ustar directhexdirecthex' Copyright (C) 2004-2005 MySQL AB ' ' This program is free software; you can redistribute it and/or modify ' it under the terms of the GNU General Public License version 2 as published by ' the Free Software Foundation ' ' There are special exceptions to the terms and conditions of the GPL ' as it is applied to this software. View the full text of the ' exception in file EXCEPTIONS in the directory of this software ' distribution. ' ' This program is distributed in the hope that it will be useful, ' but WITHOUT ANY WARRANTY; without even the implied warranty of ' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ' GNU General Public License for more details. ' ' You should have received a copy of the GNU General Public License ' along with this program; if not, write to the Free Software ' Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Imports System Imports System.Data Imports System.Windows.Forms Imports MySql.Data.MySqlClient Public Class Form1 Inherits System.Windows.Forms.Form Dim conn As MySqlConnection Dim data As DataTable Dim da As MySqlDataAdapter Dim cb As MySqlCommandBuilder #Region " Windows Form Designer generated code " Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() 'Add any initialization after the InitializeComponent() call End Sub 'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. Friend WithEvents databaseList As System.Windows.Forms.ComboBox Friend WithEvents label5 As System.Windows.Forms.Label Friend WithEvents updateBtn As System.Windows.Forms.Button Friend WithEvents dataGrid As System.Windows.Forms.DataGrid Friend WithEvents tables As System.Windows.Forms.ComboBox Friend WithEvents connectBtn As System.Windows.Forms.Button Friend WithEvents password As System.Windows.Forms.TextBox Friend WithEvents label3 As System.Windows.Forms.Label Friend WithEvents userid As System.Windows.Forms.TextBox Friend WithEvents label2 As System.Windows.Forms.Label Friend WithEvents server As System.Windows.Forms.TextBox Friend WithEvents label1 As System.Windows.Forms.Label Friend WithEvents label4 As System.Windows.Forms.Label Private Sub InitializeComponent() Me.databaseList = New System.Windows.Forms.ComboBox Me.label5 = New System.Windows.Forms.Label Me.updateBtn = New System.Windows.Forms.Button Me.dataGrid = New System.Windows.Forms.DataGrid Me.tables = New System.Windows.Forms.ComboBox Me.connectBtn = New System.Windows.Forms.Button Me.password = New System.Windows.Forms.TextBox Me.label3 = New System.Windows.Forms.Label Me.userid = New System.Windows.Forms.TextBox Me.label2 = New System.Windows.Forms.Label Me.server = New System.Windows.Forms.TextBox Me.label1 = New System.Windows.Forms.Label Me.label4 = New System.Windows.Forms.Label CType(Me.dataGrid, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'databaseList ' Me.databaseList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList Me.databaseList.Location = New System.Drawing.Point(80, 80) Me.databaseList.Name = "databaseList" Me.databaseList.Size = New System.Drawing.Size(296, 21) Me.databaseList.TabIndex = 24 ' 'label5 ' Me.label5.Location = New System.Drawing.Point(8, 88) Me.label5.Name = "label5" Me.label5.Size = New System.Drawing.Size(64, 16) Me.label5.TabIndex = 23 Me.label5.Text = "Databases" ' 'updateBtn ' Me.updateBtn.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.updateBtn.Location = New System.Drawing.Point(464, 104) Me.updateBtn.Name = "updateBtn" Me.updateBtn.Size = New System.Drawing.Size(80, 23) Me.updateBtn.TabIndex = 22 Me.updateBtn.Text = "Update" ' 'dataGrid ' Me.dataGrid.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _ Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.dataGrid.DataMember = "" Me.dataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText Me.dataGrid.Location = New System.Drawing.Point(8, 136) Me.dataGrid.Name = "dataGrid" Me.dataGrid.Size = New System.Drawing.Size(536, 384) Me.dataGrid.TabIndex = 21 ' 'tables ' Me.tables.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList Me.tables.Location = New System.Drawing.Point(80, 104) Me.tables.Name = "tables" Me.tables.Size = New System.Drawing.Size(296, 21) Me.tables.TabIndex = 20 ' 'connectBtn ' Me.connectBtn.Location = New System.Drawing.Point(400, 8) Me.connectBtn.Name = "connectBtn" Me.connectBtn.TabIndex = 19 Me.connectBtn.Text = "Connect" ' 'password ' Me.password.Location = New System.Drawing.Point(264, 32) Me.password.Name = "password" Me.password.PasswordChar = Microsoft.VisualBasic.ChrW(42) Me.password.Size = New System.Drawing.Size(116, 20) Me.password.TabIndex = 18 Me.password.Text = "" ' 'label3 ' Me.label3.Location = New System.Drawing.Point(192, 40) Me.label3.Name = "label3" Me.label3.Size = New System.Drawing.Size(56, 16) Me.label3.TabIndex = 17 Me.label3.Text = "Password:" ' 'userid ' Me.userid.Location = New System.Drawing.Point(56, 32) Me.userid.Name = "userid" Me.userid.Size = New System.Drawing.Size(120, 20) Me.userid.TabIndex = 16 Me.userid.Text = "" ' 'label2 ' Me.label2.Location = New System.Drawing.Point(8, 40) Me.label2.Name = "label2" Me.label2.Size = New System.Drawing.Size(48, 16) Me.label2.TabIndex = 15 Me.label2.Text = "User Id:" ' 'server ' Me.server.Location = New System.Drawing.Point(56, 8) Me.server.Name = "server" Me.server.Size = New System.Drawing.Size(320, 20) Me.server.TabIndex = 14 Me.server.Text = "" ' 'label1 ' Me.label1.Location = New System.Drawing.Point(8, 16) Me.label1.Name = "label1" Me.label1.Size = New System.Drawing.Size(48, 16) Me.label1.TabIndex = 12 Me.label1.Text = "Server:" ' 'label4 ' Me.label4.Location = New System.Drawing.Point(8, 112) Me.label4.Name = "label4" Me.label4.Size = New System.Drawing.Size(64, 16) Me.label4.TabIndex = 13 Me.label4.Text = "Tables" ' 'Form1 ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(552, 525) Me.Controls.Add(Me.databaseList) Me.Controls.Add(Me.label5) Me.Controls.Add(Me.updateBtn) Me.Controls.Add(Me.dataGrid) Me.Controls.Add(Me.tables) Me.Controls.Add(Me.connectBtn) Me.Controls.Add(Me.password) Me.Controls.Add(Me.label3) Me.Controls.Add(Me.userid) Me.Controls.Add(Me.label2) Me.Controls.Add(Me.server) Me.Controls.Add(Me.label1) Me.Controls.Add(Me.label4) Me.Name = "Form1" Me.Text = "Form1" CType(Me.dataGrid, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub #End Region Private Sub connectBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles connectBtn.Click If Not conn Is Nothing Then conn.Close() Dim connStr As String connStr = String.Format("server={0};user id={1}; password={2}; database=mysql; pooling=false", _ server.Text, userid.Text, password.Text ) Try conn = New MySqlConnection(connStr) conn.Open() GetDatabases() Catch ex As MySqlException MessageBox.Show("Error connecting to the server: " + ex.Message) End Try End Sub Private Sub GetDatabases() Dim reader As MySqlDataReader reader = Nothing Dim cmd As New MySqlCommand("SHOW DATABASES", conn) Try reader = cmd.ExecuteReader() databaseList.Items.Clear() While (reader.Read()) databaseList.Items.Add(reader.GetString(0)) End While Catch ex As MySqlException MessageBox.Show("Failed to populate database list: " + ex.Message) Finally If Not reader Is Nothing Then reader.Close() End Try End Sub Private Sub databaseList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles databaseList.SelectedIndexChanged Dim reader As MySqlDataReader conn.ChangeDatabase(databaseList.SelectedItem.ToString()) Dim cmd As New MySqlCommand("SHOW TABLES", conn) Try reader = cmd.ExecuteReader() tables.Items.Clear() While (reader.Read()) tables.Items.Add(reader.GetString(0)) End While Catch ex As MySqlException MessageBox.Show("Failed to populate table list: " + ex.Message) Finally If Not reader Is Nothing Then reader.Close() End Try End Sub Private Sub tables_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles tables.SelectedIndexChanged data = New DataTable da = New MySqlDataAdapter("SELECT * FROM " + tables.SelectedItem.ToString(), conn) cb = New MySqlCommandBuilder(da) da.Fill(data) dataGrid.DataSource = data End Sub Private Sub updateBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles updateBtn.Click Dim changes As DataTable = data.GetChanges() da.Update(changes) data.AcceptChanges() End Sub End Class mysql-connector-net-6.4.3/Samples/TableEditor/VB/TableEditor.build0000644000175000017500000000244211127003600025505 0ustar directhexdirecthex TableEditor sample mysql-connector-net-6.4.3/Samples/Profiling/0000755000175000017500000000000011127003600021510 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/Profiling/cs/0000755000175000017500000000000011127003600022115 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/Profiling/cs/Form1.Designer.cs0000644000175000017500000002726611127003600025204 0ustar directhexdirecthexnamespace Profiling { partial class Form1 { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.server = new System.Windows.Forms.TextBox(); this.userid = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.password = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.database = new System.Windows.Forms.TextBox(); this.sockets = new System.Windows.Forms.CheckBox(); this.portNum = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.pipeName = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.useNamedPipes = new System.Windows.Forms.CheckBox(); this.memName = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.useSharedMem = new System.Windows.Forms.CheckBox(); this.output = new System.Windows.Forms.TextBox(); this.testBtn = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 15); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(41, 13); this.label1.TabIndex = 0; this.label1.Text = "Server:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(12, 40); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(44, 13); this.label2.TabIndex = 1; this.label2.Text = "User Id:"; // // server // this.server.Location = new System.Drawing.Point(59, 8); this.server.Name = "server"; this.server.Size = new System.Drawing.Size(149, 20); this.server.TabIndex = 2; // // userid // this.userid.Location = new System.Drawing.Point(59, 34); this.userid.Name = "userid"; this.userid.Size = new System.Drawing.Size(149, 20); this.userid.TabIndex = 3; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(214, 37); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(56, 13); this.label3.TabIndex = 4; this.label3.Text = "Password:"; // // password // this.password.Location = new System.Drawing.Point(276, 37); this.password.Name = "password"; this.password.Size = new System.Drawing.Size(149, 20); this.password.TabIndex = 5; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(214, 15); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(56, 13); this.label4.TabIndex = 6; this.label4.Text = "Database:"; // // database // this.database.Location = new System.Drawing.Point(276, 8); this.database.Name = "database"; this.database.Size = new System.Drawing.Size(149, 20); this.database.TabIndex = 7; this.database.Text = "test"; // // sockets // this.sockets.AutoSize = true; this.sockets.Checked = true; this.sockets.CheckState = System.Windows.Forms.CheckState.Checked; this.sockets.Location = new System.Drawing.Point(15, 65); this.sockets.Name = "sockets"; this.sockets.Size = new System.Drawing.Size(84, 17); this.sockets.TabIndex = 8; this.sockets.Text = "Use TCP/IP"; this.sockets.UseVisualStyleBackColor = true; // // portNum // this.portNum.Location = new System.Drawing.Point(220, 62); this.portNum.Name = "portNum"; this.portNum.Size = new System.Drawing.Size(53, 20); this.portNum.TabIndex = 10; this.portNum.Text = "3306"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(139, 65); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(29, 13); this.label5.TabIndex = 9; this.label5.Text = "Port:"; // // pipeName // this.pipeName.Location = new System.Drawing.Point(220, 86); this.pipeName.Name = "pipeName"; this.pipeName.Size = new System.Drawing.Size(53, 20); this.pipeName.TabIndex = 13; this.pipeName.Text = "MYSQL"; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(139, 89); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(62, 13); this.label6.TabIndex = 12; this.label6.Text = "Pipe Name:"; // // useNamedPipes // this.useNamedPipes.AutoSize = true; this.useNamedPipes.Checked = true; this.useNamedPipes.CheckState = System.Windows.Forms.CheckState.Checked; this.useNamedPipes.Location = new System.Drawing.Point(15, 88); this.useNamedPipes.Name = "useNamedPipes"; this.useNamedPipes.Size = new System.Drawing.Size(111, 17); this.useNamedPipes.TabIndex = 11; this.useNamedPipes.Text = "Use Named Pipes"; this.useNamedPipes.UseVisualStyleBackColor = true; // // memName // this.memName.Location = new System.Drawing.Point(220, 109); this.memName.Name = "memName"; this.memName.Size = new System.Drawing.Size(53, 20); this.memName.TabIndex = 16; this.memName.Text = "MYSQL"; // // label7 // this.label7.AutoSize = true; this.label7.Location = new System.Drawing.Point(139, 112); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(78, 13); this.label7.TabIndex = 15; this.label7.Text = "Memory Name:"; // // useSharedMem // this.useSharedMem.AutoSize = true; this.useSharedMem.Checked = true; this.useSharedMem.CheckState = System.Windows.Forms.CheckState.Checked; this.useSharedMem.Location = new System.Drawing.Point(15, 111); this.useSharedMem.Name = "useSharedMem"; this.useSharedMem.Size = new System.Drawing.Size(122, 17); this.useSharedMem.TabIndex = 14; this.useSharedMem.Text = "Use Shared Memory"; this.useSharedMem.UseVisualStyleBackColor = true; // // output // this.output.Location = new System.Drawing.Point(12, 160); this.output.Multiline = true; this.output.Name = "output"; this.output.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.output.Size = new System.Drawing.Size(413, 332); this.output.TabIndex = 17; // // testBtn // this.testBtn.Location = new System.Drawing.Point(350, 102); this.testBtn.Name = "testBtn"; this.testBtn.Size = new System.Drawing.Size(75, 23); this.testBtn.TabIndex = 18; this.testBtn.Text = "Test"; this.testBtn.UseVisualStyleBackColor = true; this.testBtn.Click += new System.EventHandler(this.testBtn_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(436, 504); this.Controls.Add(this.testBtn); this.Controls.Add(this.output); this.Controls.Add(this.memName); this.Controls.Add(this.label7); this.Controls.Add(this.useSharedMem); this.Controls.Add(this.pipeName); this.Controls.Add(this.label6); this.Controls.Add(this.useNamedPipes); this.Controls.Add(this.portNum); this.Controls.Add(this.label5); this.Controls.Add(this.sockets); this.Controls.Add(this.database); this.Controls.Add(this.label4); this.Controls.Add(this.password); this.Controls.Add(this.label3); this.Controls.Add(this.userid); this.Controls.Add(this.server); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox server; private System.Windows.Forms.TextBox userid; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox password; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox database; private System.Windows.Forms.CheckBox sockets; private System.Windows.Forms.TextBox portNum; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox pipeName; private System.Windows.Forms.Label label6; private System.Windows.Forms.CheckBox useNamedPipes; private System.Windows.Forms.TextBox memName; private System.Windows.Forms.Label label7; private System.Windows.Forms.CheckBox useSharedMem; private System.Windows.Forms.TextBox output; private System.Windows.Forms.Button testBtn; } } mysql-connector-net-6.4.3/Samples/Profiling/cs/Form1.cs0000644000175000017500000001233411127003600023433 0ustar directhexdirecthexusing System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.Common; using MySql.Data.MySqlClient; using System.Diagnostics; namespace Profiling { public partial class Form1 : Form { MySqlConnection connection; public Form1() { InitializeComponent(); } private void Log(string s) { output.Text += "\r\n" + s; output.Refresh(); } private void testBtn_Click(object sender, EventArgs e) { output.Clear(); DateTime start = DateTime.Now; Log("Starting tests at " + start.ToString()); try { if (sockets.Checked) { Log("\r\nTesting sockets"); TestSockets(); } if (useNamedPipes.Checked) { Log("\r\nTesting named pipes"); TestNamedPipes(); } if (useSharedMem.Checked) { Log("\r\nTesting shared memory"); TestSharedMemory(); } Log("Done!"); } catch (Exception ex) { Log(ex.Message); } TimeSpan ts = DateTime.Now.Subtract(start); Log(ts.ToString()); } private void TestSockets() { Test(String.Format( "server={0};uid={1};password={2};database={3};port={4}", server.Text, userid.Text, password.Text, database.Text, portNum.Text)); } private void TestNamedPipes() { Test(String.Format( "server={0};uid={1};password={2};database={3};protocol=pipe;pipe={4}", server.Text, userid.Text, password.Text, database.Text, pipeName.Text)); } private void TestSharedMemory() { Test(String.Format( "server={0};uid={1};password={2};database={3};protocol=memory;shared memory name={4}", server.Text, userid.Text, password.Text, database.Text, memName.Text)); } private void Test(string connectionString) { string[] desc = new string[4] { "no compression, no pooling", "no compression, pooling", "compression, no pooling", "compression, pooling" }; string[] addons = new string[4] { ";compress=false;pooling=false", ";compress=false;pooling=true", ";compress=true;pooling=false", ";compress=true;pooling=true"}; for (int x=0; x < addons.Length; x++) { if (connection != null) connection.Close(); Log("\r\nTest " + desc[x]); connection = new MySqlConnection(connectionString + addons[x]); connection.Open(); Log("\r\nnot using prepared tests"); DoInsertTests(false); DoSelectTests(false); Log("\r\nusing prepared tests"); DoInsertTests(true); DoSelectTests(true); } } private void DoInsertTests(bool prepared) { Log("Starting Insert tests"); MySqlCommand cmd = new MySqlCommand("DROP TABLE IF EXISTS test", connection); cmd.ExecuteNonQuery(); cmd.CommandText = "CREATE TABLE test (id INT, name VARCHAR(50), fl FLOAT, dt DATETIME)"; cmd.ExecuteNonQuery(); cmd.CommandText = "INSERT INTO test VALUES (?id, ?name, ?f1, ?dt)"; cmd.Parameters.Add("?id", MySqlDbType.Int32); cmd.Parameters.Add("?name", MySqlDbType.VarChar); cmd.Parameters.Add("?f1", MySqlDbType.Float); cmd.Parameters.Add("?dt", MySqlDbType.Datetime); if (prepared) cmd.Prepare(); for (int x=0; x < 500; x++) { cmd.Parameters[0].Value = x; cmd.Parameters[1].Value = "Test"; cmd.Parameters[2].Value = 0.0; cmd.Parameters[3].Value = DateTime.Now; cmd.ExecuteNonQuery(); } } private void DoSelectTests(bool prepared) { Log("Starting select tests"); MySqlCommand cmd = new MySqlCommand("SELECT * FROM test", connection); cmd.CommandTimeout = 0; using (MySqlDataReader reader = cmd.ExecuteReader()) { int count = 0; while (reader.Read()) { int id = reader.GetInt32(0); Trace.WriteLine("id = " + id); string name = reader.GetString(1); float fl = reader.GetFloat(2); DateTime dt = reader.GetDateTime(3); count++; } Log("read " + count + " records"); } } } }mysql-connector-net-6.4.3/Samples/Profiling/cs/Profiling.csproj0000644000175000017500000000666511127003600025305 0ustar directhexdirecthex Debug AnyCPU 8.0.50727 2.0 {79AEF3F3-2D3F-4CF4-91C8-BE94F77B6150} WinExe Properties Profiling Profiling true full false bin\Debug\ DEBUG;TRACE prompt 4 pdbonly true bin\Release\ TRACE prompt 4 False ..\..\..\mysqlclient\bin\net-2.0\Debug\MySql.Data.dll Form Form1.cs Designer Form1.cs ResXFileCodeGenerator Resources.Designer.cs Designer True Resources.resx SettingsSingleFileGenerator Settings.Designer.cs True Settings.settings True mysql-connector-net-6.4.3/Samples/Profiling/cs/Form1.resx0000644000175000017500000001326611127003600024014 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 mysql-connector-net-6.4.3/Samples/Profiling/cs/Program.cs0000644000175000017500000000073411127003600024057 0ustar directhexdirecthexusing System; using System.Collections.Generic; using System.Windows.Forms; namespace Profiling { static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }mysql-connector-net-6.4.3/Samples/Profiling/cs/Properties/0000755000175000017500000000000011127003600024251 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/Profiling/cs/Properties/Settings.Designer.cs0000644000175000017500000000210511127003600030135 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.112 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Profiling.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "8.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } } mysql-connector-net-6.4.3/Samples/Profiling/cs/Properties/Resources.Designer.cs0000644000175000017500000000543611127003600030321 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.112 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace Profiling.Properties { /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Profiling.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } } mysql-connector-net-6.4.3/Samples/Profiling/cs/Properties/Resources.resx0000644000175000017500000001275411127003600027137 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 mysql-connector-net-6.4.3/Samples/Profiling/cs/Properties/AssemblyInfo.cs0000644000175000017500000000236211127003600027176 0ustar directhexdirecthexusing System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Profiling")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Profiling")] [assembly: AssemblyCopyright("Copyright © 2006")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2c383097-c402-454b-bb02-57d84d96a540")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] mysql-connector-net-6.4.3/Samples/Profiling/cs/Properties/Settings.settings0000644000175000017500000000037111127003600027634 0ustar directhexdirecthex mysql-connector-net-6.4.3/Samples/Pocket PC/0000755000175000017500000000000011127003600021267 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/Pocket PC/Tester/0000755000175000017500000000000011127003600022535 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/Pocket PC/Tester/Form1.Designer.cs0000644000175000017500000001155511127003600025616 0ustar directhexdirecthexnamespace DeviceApplication1 { partial class MainForm { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; private System.Windows.Forms.MainMenu mainMenu1; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.runTestsMenu = new System.Windows.Forms.MenuItem(); this.showDetailsMenu = new System.Windows.Forms.MenuItem(); this.label1 = new System.Windows.Forms.Label(); this.testTree = new System.Windows.Forms.TreeView(); this.imageList1 = new System.Windows.Forms.ImageList(); this.runSelected = new System.Windows.Forms.MenuItem(); this.SuspendLayout(); // // mainMenu1 // this.mainMenu1.MenuItems.Add(this.menuItem1); // // menuItem1 // this.menuItem1.MenuItems.Add(this.runTestsMenu); this.menuItem1.MenuItems.Add(this.showDetailsMenu); this.menuItem1.MenuItems.Add(this.runSelected); this.menuItem1.Text = "&Options"; // // runTestsMenu // this.runTestsMenu.Text = "&Run Tests"; this.runTestsMenu.Click += new System.EventHandler(this.runTestsMenu_Click); // // showDetailsMenu // this.showDetailsMenu.Text = "&Show Details..."; this.showDetailsMenu.Click += new System.EventHandler(this.showDetailsMenu_Click); // // label1 // this.label1.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold); this.label1.Location = new System.Drawing.Point(11, 11); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(108, 20); this.label1.Text = "Tests:"; // // testTree // this.testTree.ImageIndex = 2; this.testTree.ImageList = this.imageList1; this.testTree.Location = new System.Drawing.Point(3, 34); this.testTree.Name = "testTree"; this.testTree.SelectedImageIndex = 2; this.testTree.Size = new System.Drawing.Size(234, 231); this.testTree.TabIndex = 17; this.imageList1.Images.Clear(); this.imageList1.Images.Add(((System.Drawing.Image)(resources.GetObject("resource")))); this.imageList1.Images.Add(((System.Drawing.Image)(resources.GetObject("resource1")))); this.imageList1.Images.Add(((System.Drawing.Image)(resources.GetObject("resource2")))); // // runSelected // this.runSelected.Text = "Run Selected &Tests"; this.runSelected.Click += new System.EventHandler(this.runSelected_Click); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(240, 268); this.Controls.Add(this.testTree); this.Controls.Add(this.label1); this.Menu = this.mainMenu1; this.Name = "MainForm"; this.Text = "MySQL Tester"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem runTestsMenu; private System.Windows.Forms.Label label1; private System.Windows.Forms.TreeView testTree; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.MenuItem showDetailsMenu; private System.Windows.Forms.MenuItem runSelected; } } mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/Form1.cs0000644000175000017500000001400611127003600024051 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using MySql.Data.MySqlClient.Tests; using System.Reflection; using System.Collections; using System.Threading; namespace DeviceApplication1 { public partial class MainForm : Form { private TestRunner runner; public delegate void NodeUpdater(int fixture, int test, int index); public NodeUpdater updater; int fixtureStart; int fixtureEnd; int testStart; int testEnd; public MainForm() { InitializeComponent(); LoadTests(); updater = new NodeUpdater(UpdateNode); } private void LoadTests() { runner = new TestRunner(); ArrayList tests = runner.LoadTests(); foreach (TestCollection tc in tests) { TreeNode fixture = testTree.Nodes.Add(tc.name); fixture.Tag = tc; foreach (TestMethod tm in tc.testMethods) { TreeNode test = fixture.Nodes.Add(tm.member.Name); test.Tag = tm; } } } private void RunTests() { Thread t = new Thread(new ThreadStart(RunTestsWorker)); t.Start(); } private void UpdateNode(int fixture, int test, int index) { TreeNode node; if (test == -1) node = testTree.Nodes[fixture]; else node = testTree.Nodes[fixture].Nodes[test]; node.ImageIndex = index; node.SelectedImageIndex = index; } private void RunTestsWorker() { for (int i = fixtureStart; i < fixtureEnd; i++) { int fixtureIndex = 1; try { TestCollection tc = (TestCollection)testTree.Nodes[i].Tag; runner.StartFixture(tc); int myTestEnd = testEnd; if (testEnd == -1) myTestEnd = tc.testMethods.Count; for (int x = testStart; x < myTestEnd; x++) { int index = 1; if (!runner.RunTest(i, x)) { fixtureIndex = 0; index = 0; } this.Invoke(updater, i, x, index); } runner.EndFixture(tc); } catch (Exception ex) { fixtureIndex = 0; } this.Invoke(updater, i, -1, fixtureIndex); } } private void showDetailsMenu_Click(object sender, EventArgs e) { if (testTree.SelectedNode == null) MessageBox.Show("No test selected"); FailDetails fd = new FailDetails(); TreeNode node = testTree.SelectedNode; if (node.Parent == null) { TestCollection tc = (TestCollection)node.Tag; fd.Message = tc.message; fd.Trace = tc.stack; } else { TestMethod tm = (TestMethod)node.Tag; fd.Message = tm.message; fd.Trace = tm.stack; } fd.ShowDialog(); } private void runTestsMenu_Click(object sender, EventArgs e) { ResetTree(); fixtureStart = 0; fixtureEnd = testTree.Nodes.Count; testStart = 0; testEnd = -1; RunTests(); } private void runSelected_Click(object sender, EventArgs e) { if (testTree.SelectedNode == null) MessageBox.Show("No test selected"); ResetTree(); TreeNode selNode = testTree.SelectedNode; testStart = 0; testEnd = -1; if (selNode.Parent != null) { testStart = selNode.Index; testEnd = testStart + 1; selNode = selNode.Parent; } fixtureStart = selNode.Index; fixtureEnd = fixtureStart + 1; RunTests(); } private void ResetTree() { foreach (TreeNode node in testTree.Nodes) { node.ImageIndex = 2; node.SelectedImageIndex = 2; foreach (TreeNode test in node.Nodes) { test.ImageIndex = 2; test.SelectedImageIndex = 2; } } } } }mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/Tester.csproj0000644000175000017500000001145611127003600025234 0ustar directhexdirecthex Debug AnyCPU 8.0.50727 2.0 {C3904AC7-1888-42CF-A3AC-7ADC1BA41704} WinExe Properties DeviceApplication1 DeviceApplication1 {4D628B5B-2FBC-4AA6-8C16-197242AEB884};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} PocketPC 3C41C503-53EF-4c2a-8DD4-A8217CAD115E 4.20 DeviceApplication1 v2.0 true full false bin\Debug\ DEBUG;TRACE;$(PlatformFamilyName) true true prompt 512 4 Off pdbonly true bin\Release\ TRACE;$(PlatformFamilyName) true true prompt 512 4 Off Form FailDetails.cs Form Form1.cs Designer FailDetails.cs Designer Form1.cs ResXFileCodeGenerator Resources.Designer.cs Designer True Resources.resx True {710D9251-17A3-4429-9A91-63F03267F310} MySql.Data.Tests.CF Always mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/Form1.resx0000644000175000017500000001762511127003600024437 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 134, 17 iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAFpJREFUOE9j/A8E DOiAkRFDCCyARSlQDAlAlBDGyFrgbGI0IquBaoS4gFTNMPUgrZQbQK7tUH0MZDt/1AB41FMhGqmSkMgx BCUpwzIEsYkKa2YiJleiZF0IBwCCRi/wAJMMHQAAAABJRU5ErkJggg== iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAGVJREFUOE9j/A8E DGiAkUEJXQjM/89wD1McZAAMMPxX/E8MRtUD5RGjEVkNwlKQF4i0GV0d2PsQgjinYzWAXM1wfaMGABMh mTGA0EdpNFKcDkjNBzCnoyRlUg3BmpmIyZXIamBsAB5jSfqm8jHwAAAAAElFTkSuQmCC iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAACVJREFUOE9j/A8E DJQAkAGUAAZKNINdP2rAaBiMpgNwLqA4LwAAlW3Aa6noFWgAAAAASUVORK5CYII= POCKET_PC_2003_PORTRAIT True mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/FailDetails.resx0000644000175000017500000001425211127003600025625 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 17, 17 POCKET_PC_2003_PORTRAIT True mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/Program.cs0000644000175000017500000000056611127003600024502 0ustar directhexdirecthexusing System; using System.Collections.Generic; using System.Windows.Forms; namespace DeviceApplication1 { static class Program { /// /// The main entry point for the application. /// [MTAThread] static void Main() { Application.Run(new MainForm()); } } }mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/FailDetails.cs0000644000175000017500000000316011127003600025245 0ustar directhexdirecthex// Copyright (C) 2004-2007 MySQL AB // // MySQL Connector/NET is licensed under the terms of the GPLv2 // , like most // MySQL Connectors. There are special exceptions to the terms and // conditions of the GPLv2 as it is applied to this software, see the // FLOSS License Exception // . // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace DeviceApplication1 { public partial class FailDetails : Form { public FailDetails() { InitializeComponent(); } public string Message { set { msg.Text = value; } } public string Trace { set { trace.Text = value; } } } }mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/FailDetails.Designer.cs0000644000175000017500000000761011127003600027010 0ustar directhexdirecthexnamespace DeviceApplication1 { partial class FailDetails { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; private System.Windows.Forms.MainMenu mainMenu1; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.msg = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.trace = new System.Windows.Forms.TextBox(); this.ok = new System.Windows.Forms.Button(); this.SuspendLayout(); // // msg // this.msg.Location = new System.Drawing.Point(3, 34); this.msg.Multiline = true; this.msg.Name = "msg"; this.msg.Size = new System.Drawing.Size(234, 52); this.msg.TabIndex = 0; // // label1 // this.label1.Location = new System.Drawing.Point(3, 11); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(100, 20); this.label1.Text = "Message"; // // label2 // this.label2.Location = new System.Drawing.Point(3, 98); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(100, 20); this.label2.Text = "Stack trace"; // // trace // this.trace.Location = new System.Drawing.Point(3, 121); this.trace.Multiline = true; this.trace.Name = "trace"; this.trace.Size = new System.Drawing.Size(234, 118); this.trace.TabIndex = 3; // // ok // this.ok.DialogResult = System.Windows.Forms.DialogResult.OK; this.ok.Location = new System.Drawing.Point(165, 256); this.ok.Name = "ok"; this.ok.Size = new System.Drawing.Size(72, 20); this.ok.TabIndex = 5; this.ok.Text = "OK"; // // FailDetails // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.AutoScroll = true; this.ClientSize = new System.Drawing.Size(240, 294); this.ControlBox = false; this.Controls.Add(this.ok); this.Controls.Add(this.label2); this.Controls.Add(this.trace); this.Controls.Add(this.label1); this.Controls.Add(this.msg); this.MinimizeBox = false; this.Name = "FailDetails"; this.Text = "FailDetails"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.TextBox msg; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox trace; private System.Windows.Forms.Button ok; } }mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/Properties/0000755000175000017500000000000011127003600024671 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/Pocket PC/Tester/Properties/red.png0000644000175000017500000000040011127003600026143 0ustar directhexdirecthexPNG  IHDRasRGBgAMA a cHRMz&u0`:pQ<tEXtSoftwarePaint.NET v3.05\ZIDAT8Oc 耑C,E)P @Zlb4"jT0 @P} d;xS!1%)2 kf"&Wd]F/ IENDB`mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/Properties/green.png0000644000175000017500000000041311127003600026475 0ustar directhexdirecthexPNG  IHDRasRGBgAMA a cHRMz&u0`:pQ<tEXtSoftwarePaint.NET v3.05\eIDAT8Oc hA ]pSd 0WO FY R]8c5\p}!1Gi4RH0$eR ɕj`lcI1IENDB`mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/Properties/Resources.Designer.cs0000644000175000017500000000473211127003600030737 0ustar directhexdirecthex//------------------------------------------------------------------------------ // // This code was generated by a tool. // Runtime Version:2.0.50727.312 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // //------------------------------------------------------------------------------ namespace DeviceApplication1.Properties { using System; /// /// A strongly-typed resource class, for looking up localized strings, etc. /// // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; internal Resources() { } /// /// Returns the cached ResourceManager instance used by this class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DeviceApplication1.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } } mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/Properties/Resources.resx0000644000175000017500000001276211127003600027556 0ustar directhexdirecthex text/microsoft-resx 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/Properties/white.png0000644000175000017500000000031311127003600026514 0ustar directhexdirecthexPNG  IHDRasRGBgAMA a cHRMz&u0`:pQ<tEXtSoftwarePaint.NET v3.05\%IDAT8Oc J4]?jhp.8/mkhIENDB`mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/Properties/AssemblyInfo.cs0000644000175000017500000000235411127003600027617 0ustar directhexdirecthexusing System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DeviceApplication1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("DeviceApplication1")] [assembly: AssemblyCopyright("Copyright © Microsoft 2007")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("add8ee1a-806b-4fba-bd00-1507ed0a2087")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] mysql-connector-net-6.4.3/Samples/Pocket PC/Tester/MySql.Data.Tests.CF.dll.config0000644000175000017500000000026511127003600030006 0ustar directhexdirecthex mysql-connector-net-6.4.3/Samples/Pocket PC/MobileExplorer/0000755000175000017500000000000011127003600024217 5ustar directhexdirecthexmysql-connector-net-6.4.3/Samples/Pocket PC/MobileExplorer/Form1.cs0000644000175000017500000004221211127003600025533 0ustar directhexdirecthexusing System; using System.Data; using System.IO; using System.Drawing; using System.Collections; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace MobileExplorer { /// /// Summary description for Form1. /// public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Button serverConnect; private System.Windows.Forms.Panel chooseServerPanel; private System.Windows.Forms.Panel showServerPanel; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label activeServer; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox objectTypeList; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox dbList; private System.Windows.Forms.ListBox objectList; private System.Windows.Forms.Label label5; private System.Windows.Forms.ListBox serverList; private System.Windows.Forms.Button backToChooserBtn; private System.Windows.Forms.Panel tableViewPanel; private System.Windows.Forms.Label label6; private System.Windows.Forms.DataGrid tableGrid; private System.Windows.Forms.Button backToServerBtn; private System.Windows.Forms.Button showObject; private System.Windows.Forms.MainMenu mainMenu1; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem newServer; private MySqlConnection server; private System.Windows.Forms.Label activeTable; private ArrayList servers; private System.Windows.Forms.MenuItem deleteServer; private System.Windows.Forms.Panel spViewPanel; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox spText; private System.Windows.Forms.Button ok; private System.Windows.Forms.Button cancel; private System.Windows.Forms.Label activeProc; private ServerConfig activeConfig; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); server = new MySqlConnection(); servers = new ArrayList(); LoadServers(); } /// /// Clean up any resources being used. /// protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.chooseServerPanel = new System.Windows.Forms.Panel(); this.serverConnect = new System.Windows.Forms.Button(); this.serverList = new System.Windows.Forms.ListBox(); this.label1 = new System.Windows.Forms.Label(); this.showServerPanel = new System.Windows.Forms.Panel(); this.label5 = new System.Windows.Forms.Label(); this.objectList = new System.Windows.Forms.ListBox(); this.dbList = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.objectTypeList = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.activeServer = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.backToChooserBtn = new System.Windows.Forms.Button(); this.tableViewPanel = new System.Windows.Forms.Panel(); this.label6 = new System.Windows.Forms.Label(); this.activeTable = new System.Windows.Forms.Label(); this.tableGrid = new System.Windows.Forms.DataGrid(); this.backToServerBtn = new System.Windows.Forms.Button(); this.showObject = new System.Windows.Forms.Button(); this.mainMenu1 = new System.Windows.Forms.MainMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.newServer = new System.Windows.Forms.MenuItem(); this.deleteServer = new System.Windows.Forms.MenuItem(); this.spViewPanel = new System.Windows.Forms.Panel(); this.label7 = new System.Windows.Forms.Label(); this.activeProc = new System.Windows.Forms.Label(); this.spText = new System.Windows.Forms.TextBox(); this.ok = new System.Windows.Forms.Button(); this.cancel = new System.Windows.Forms.Button(); // // chooseServerPanel // this.chooseServerPanel.Controls.Add(this.serverConnect); this.chooseServerPanel.Controls.Add(this.serverList); this.chooseServerPanel.Controls.Add(this.label1); this.chooseServerPanel.Location = new System.Drawing.Point(4, 4); this.chooseServerPanel.Size = new System.Drawing.Size(220, 296); // // serverConnect // this.serverConnect.Location = new System.Drawing.Point(132, 212); this.serverConnect.Text = "Connect"; this.serverConnect.Click += new System.EventHandler(this.serverConnect_Click); // // serverList // this.serverList.Location = new System.Drawing.Point(12, 32); this.serverList.Size = new System.Drawing.Size(192, 170); // // label1 // this.label1.Location = new System.Drawing.Point(12, 12); this.label1.Size = new System.Drawing.Size(140, 20); this.label1.Text = "Configured Servers"; // // showServerPanel // this.showServerPanel.Controls.Add(this.objectList); this.showServerPanel.Controls.Add(this.showObject); this.showServerPanel.Controls.Add(this.backToChooserBtn); this.showServerPanel.Controls.Add(this.label5); this.showServerPanel.Controls.Add(this.dbList); this.showServerPanel.Controls.Add(this.label4); this.showServerPanel.Controls.Add(this.objectTypeList); this.showServerPanel.Controls.Add(this.label3); this.showServerPanel.Controls.Add(this.activeServer); this.showServerPanel.Controls.Add(this.label2); this.showServerPanel.Location = new System.Drawing.Point(4, 4); this.showServerPanel.Size = new System.Drawing.Size(228, 264); // // label5 // this.label5.Location = new System.Drawing.Point(12, 104); this.label5.Text = "Objects"; // // objectList // this.objectList.Location = new System.Drawing.Point(12, 120); this.objectList.Size = new System.Drawing.Size(200, 100); // // dbList // this.dbList.Location = new System.Drawing.Point(80, 40); this.dbList.Size = new System.Drawing.Size(132, 22); this.dbList.SelectedIndexChanged += new System.EventHandler(this.dbList_SelectedIndexChanged); // // label4 // this.label4.Location = new System.Drawing.Point(12, 40); this.label4.Size = new System.Drawing.Size(72, 20); this.label4.Text = "Database:"; // // objectTypeList // this.objectTypeList.Items.Add("Tables"); this.objectTypeList.Items.Add("Stored Procedures"); this.objectTypeList.Items.Add("User Defined Functions"); this.objectTypeList.Items.Add("Views"); this.objectTypeList.Location = new System.Drawing.Point(80, 76); this.objectTypeList.Size = new System.Drawing.Size(132, 22); this.objectTypeList.SelectedIndexChanged += new System.EventHandler(this.objectTypeList_SelectedIndexChanged); // // label3 // this.label3.Location = new System.Drawing.Point(12, 76); this.label3.Size = new System.Drawing.Size(48, 20); this.label3.Text = "Object:"; // // activeServer // this.activeServer.Location = new System.Drawing.Point(80, 12); this.activeServer.Size = new System.Drawing.Size(128, 20); // // label2 // this.label2.Location = new System.Drawing.Point(12, 12); this.label2.Size = new System.Drawing.Size(48, 20); this.label2.Text = "Server:"; // // backToChooserBtn // this.backToChooserBtn.Location = new System.Drawing.Point(64, 232); this.backToChooserBtn.Text = "Back"; this.backToChooserBtn.Click += new System.EventHandler(this.backToChooserBtn_Click); // // tableViewPanel // this.tableViewPanel.Controls.Add(this.backToServerBtn); this.tableViewPanel.Controls.Add(this.tableGrid); this.tableViewPanel.Controls.Add(this.activeTable); this.tableViewPanel.Controls.Add(this.label6); this.tableViewPanel.Location = new System.Drawing.Point(4, 4); this.tableViewPanel.Size = new System.Drawing.Size(224, 264); // // label6 // this.label6.Location = new System.Drawing.Point(12, 12); this.label6.Size = new System.Drawing.Size(52, 20); this.label6.Text = "Table:"; // // activeTable // this.activeTable.Location = new System.Drawing.Point(60, 12); this.activeTable.Size = new System.Drawing.Size(152, 20); // // tableGrid // this.tableGrid.Location = new System.Drawing.Point(4, 32); this.tableGrid.Size = new System.Drawing.Size(216, 196); this.tableGrid.Text = "dataGrid1"; // // backToServerBtn // this.backToServerBtn.Location = new System.Drawing.Point(144, 236); this.backToServerBtn.Text = "Back"; this.backToServerBtn.Click += new System.EventHandler(this.backToServerBtn_Click); // // showObject // this.showObject.Location = new System.Drawing.Point(140, 232); this.showObject.Text = "Show"; this.showObject.Click += new System.EventHandler(this.showObject_Click); // // mainMenu1 // this.mainMenu1.MenuItems.Add(this.menuItem1); // // menuItem1 // this.menuItem1.MenuItems.Add(this.newServer); this.menuItem1.MenuItems.Add(this.deleteServer); this.menuItem1.Text = "Servers"; // // newServer // this.newServer.Text = "&New..."; this.newServer.Click += new System.EventHandler(this.newServer_Click); // // deleteServer // this.deleteServer.Text = "&Delete"; this.deleteServer.Click += new System.EventHandler(this.deleteServer_Click); // // spViewPanel // this.spViewPanel.Controls.Add(this.cancel); this.spViewPanel.Controls.Add(this.ok); this.spViewPanel.Controls.Add(this.spText); this.spViewPanel.Controls.Add(this.activeProc); this.spViewPanel.Controls.Add(this.label7); this.spViewPanel.Location = new System.Drawing.Point(4, 4); this.spViewPanel.Size = new System.Drawing.Size(220, 296); // // label7 // this.label7.Location = new System.Drawing.Point(8, 12); this.label7.Size = new System.Drawing.Size(72, 20); this.label7.Text = "Procedure:"; // // activeProc // this.activeProc.Location = new System.Drawing.Point(80, 12); this.activeProc.Size = new System.Drawing.Size(132, 20); // // spText // this.spText.Location = new System.Drawing.Point(8, 36); this.spText.Multiline = true; this.spText.Size = new System.Drawing.Size(204, 192); this.spText.Text = ""; // // ok // this.ok.Location = new System.Drawing.Point(64, 236); this.ok.Text = "OK"; this.ok.Click += new System.EventHandler(this.ok_Click); // // cancel // this.cancel.Location = new System.Drawing.Point(140, 236); this.cancel.Text = "Cancel"; this.cancel.Click += new System.EventHandler(this.cancel_Click); // // Form1 // this.ClientSize = new System.Drawing.Size(230, 372); this.Controls.Add(this.chooseServerPanel); this.Controls.Add(this.tableViewPanel); this.Controls.Add(this.showServerPanel); this.Controls.Add(this.spViewPanel); this.Menu = this.mainMenu1; this.Text = "Form1"; } #endregion /// /// The main entry point for the application. /// static void Main() { Application.Run(new Form1()); } private void serverConnect_Click(object sender, System.EventArgs e) { activeConfig = (ServerConfig)servers[serverList.SelectedIndex]; server.ConnectionString = "server=" + activeConfig.host + ";uid=" + activeConfig.uid + ";pwd=" + activeConfig.pwd + ";pooling=false;database=mysql"; MessageBox.Show(server.ConnectionString, "connstr"); objectList.Items.Clear(); activeServer.Text = activeConfig.name; try { server.Open(); MySqlCommand cmd = new MySqlCommand("SHOW DATABASES", server); using (MySqlDataReader reader = cmd.ExecuteReader()) { dbList.Items.Clear(); while (reader.Read()) { dbList.Items.Add(reader.GetString(0)); } } } catch (MySqlException ex) { MessageBox.Show(ex.Message); } showServerPanel.BringToFront(); } private void dbList_SelectedIndexChanged(object sender, System.EventArgs e) { try { server.Close(); server.ConnectionString = "server=monster;uid=reggie;pwd=reggie;database=" + dbList.SelectedItem; server.Open(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void objectTypeList_SelectedIndexChanged(object sender, System.EventArgs e) { string sql = null; objectList.Items.Clear(); switch (objectTypeList.SelectedIndex) { case 0: sql = "SHOW TABLES"; break; case 1: if (!server.ServerVersion.StartsWith("5")) return; sql = "SELECT name FROM mysql.proc WHERE db='" + server.Database + "'"; break; case 2: sql = "select name from mysql.func"; break; case 3: return; } MySqlCommand cmd = new MySqlCommand(sql, server); using (MySqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) objectList.Items.Add(reader.GetString(0)); } } private void backToChooserBtn_Click(object sender, System.EventArgs e) { server.Close(); this.chooseServerPanel.BringToFront(); } private void backToServerBtn_Click(object sender, System.EventArgs e) { activeTable.Text = String.Empty; tableGrid.DataSource = null; showServerPanel.BringToFront(); } private void ShowTable() { DataSet ds = new DataSet(); MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM " + objectList.SelectedItem, server); activeTable.Text = objectList.SelectedItem.ToString(); da.Fill(ds); tableGrid.DataSource = ds.Tables[0]; this.tableViewPanel.BringToFront(); } private void ShowProc() { MySqlCommand cmd = new MySqlCommand("SHOW CREATE PROCEDURE " + objectList.SelectedItem, server); using (MySqlDataReader reader = cmd.ExecuteReader()) { reader.Read(); string body = reader.GetString(2); body = body.Replace("\n", "\r\n"); spText.Text = body; } activeProc.Text = objectList.SelectedItem.ToString(); spViewPanel.BringToFront(); } private void showObject_Click(object sender, System.EventArgs e) { switch (objectTypeList.SelectedIndex) { case 0: ShowTable(); break; case 1: ShowProc(); break; } } private void newServer_Click(object sender, System.EventArgs e) { NewServerDialog d = new NewServerDialog(); DialogResult result = d.ShowDialog(); if (result == DialogResult.Cancel) return; ServerConfig sc = d.GetServerConfig(); servers.Add(sc); serverList.Items.Add(sc); SaveServers(); } private void SaveServers() { FileStream fs = new FileStream(@"\My Documents\MobileExplorer.dat", FileMode.Create); StreamWriter sw = new StreamWriter(fs); foreach (ServerConfig sc in servers) { string line = sc.name + "|" + sc.host + "|" + sc.uid + "|" + sc.pwd; sw.WriteLine(line); } sw.Close(); fs.Close(); } private void LoadServers() { servers.Clear(); serverList.Items.Clear(); try { if (!File.Exists(@"\My Documents\MobileExplorer.dat")) return; StreamReader sr = new StreamReader(@"\My Documents\MobileExplorer.dat"); string line = sr.ReadLine(); while (line != null) { string[] parts = line.Split('|'); ServerConfig sc = new ServerConfig(); sc.name = parts[0]; sc.host = parts[1]; sc.uid = parts[2]; sc.pwd = parts[3]; servers.Add(sc); serverList.Items.Add(sc.name); line = sr.ReadLine(); } sr.Close(); } catch (Exception ex) { } } private void deleteServer_Click(object sender, System.EventArgs e) { if (serverList.SelectedIndex == -1) { MessageBox.Show("You do not have a server selected"); return; } ServerConfig sc = (ServerConfig)servers[serverList.SelectedIndex]; DialogResult result = MessageBox.Show("Are you sure you want to delete server '" + sc.name + "'", "Delete Server", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button3); if (result == DialogResult.Cancel) return; if (result == DialogResult.No) return; servers.RemoveAt(serverList.SelectedIndex); SaveServers(); } private void cancel_Click(object sender, System.EventArgs e) { activeProc.Text = String.Empty; spText.Text = String.Empty; showServerPanel.BringToFront(); } private void ok_Click(object sender, System.EventArgs e) { MySqlCommand cmd = new MySqlCommand("DROP PROCEDURE " + objectList.SelectedItem + ";" + spText.Text, server); cmd.ExecuteNonQuery(); activeProc.Text = String.Empty; spText.Text = String.Empty; showServerPanel.BringToFront(); } } internal struct ServerConfig { public string name; public string host; public string uid; public string pwd; } } mysql-connector-net-6.4.3/Samples/Pocket PC/MobileExplorer/NewServerDialog.cs0000644000175000017500000001203111127003600027603 0ustar directhexdirecthexusing System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace MobileExplorer { /// /// Summary description for NewServerDialog. /// public class NewServerDialog : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button okBtn; private System.Windows.Forms.TextBox name; private System.Windows.Forms.TextBox host; private System.Windows.Forms.TextBox uid; private System.Windows.Forms.TextBox pwd; private System.Windows.Forms.Button cancelBtn; public NewServerDialog() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// /// Clean up any resources being used. /// protected override void Dispose( bool disposing ) { base.Dispose( disposing ); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.name = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.host = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.uid = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.pwd = new System.Windows.Forms.TextBox(); this.okBtn = new System.Windows.Forms.Button(); this.cancelBtn = new System.Windows.Forms.Button(); // // label1 // this.label1.Location = new System.Drawing.Point(8, 12); this.label1.Size = new System.Drawing.Size(52, 20); this.label1.Text = "Name:"; // // name // this.name.Location = new System.Drawing.Point(8, 28); this.name.Size = new System.Drawing.Size(168, 22); this.name.Text = ""; // // label2 // this.label2.Location = new System.Drawing.Point(8, 72); this.label2.Size = new System.Drawing.Size(52, 20); this.label2.Text = "Host:"; // // host // this.host.Location = new System.Drawing.Point(8, 88); this.host.Size = new System.Drawing.Size(168, 22); this.host.Text = ""; // // label3 // this.label3.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular); this.label3.Location = new System.Drawing.Point(8, 120); this.label3.Size = new System.Drawing.Size(60, 20); this.label3.Text = "User Id:"; // // uid // this.uid.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular); this.uid.Location = new System.Drawing.Point(8, 136); this.uid.Size = new System.Drawing.Size(168, 22); this.uid.Text = ""; // // label4 // this.label4.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular); this.label4.Location = new System.Drawing.Point(8, 168); this.label4.Size = new System.Drawing.Size(60, 20); this.label4.Text = "Password:"; // // pwd // this.pwd.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular); this.pwd.Location = new System.Drawing.Point(8, 184); this.pwd.Size = new System.Drawing.Size(168, 22); this.pwd.Text = ""; // // okBtn // this.okBtn.Location = new System.Drawing.Point(104, 220); this.okBtn.Text = "OK"; this.okBtn.Click += new System.EventHandler(this.okBtn_Click); // // cancelBtn // this.cancelBtn.Location = new System.Drawing.Point(24, 220); this.cancelBtn.Text = "Cancel"; this.cancelBtn.Click += new System.EventHandler(this.cancelBtn_Click); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; // // NewServerDialog // this.ClientSize = new System.Drawing.Size(190, 272); this.ControlBox = false; this.Controls.Add(this.cancelBtn); this.Controls.Add(this.okBtn); this.Controls.Add(this.pwd); this.Controls.Add(this.label4); this.Controls.Add(this.uid); this.Controls.Add(this.label3); this.Controls.Add(this.host); this.Controls.Add(this.label2); this.Controls.Add(this.name); this.Controls.Add(this.label1); this.MaximizeBox = false; this.MinimizeBox = false; this.Text = "NewServerDialog"; } #endregion private void cancelBtn_Click(object sender, System.EventArgs e) { this.Close(); } private void okBtn_Click(object sender, System.EventArgs e) { this.Close(); } internal ServerConfig GetServerConfig() { ServerConfig sc = new ServerConfig(); sc.name = name.Text; sc.host = host.Text; sc.uid = uid.Text; sc.pwd = pwd.Text; return sc; } } } mysql-connector-net-6.4.3/Samples/Pocket PC/MobileExplorer/Form1.resx0000644000175000017500000006115611127003600026117 0ustar directhexdirecthex text/microsoft-resx 1.3 System.Windows.Forms.Design.CFResXResourceReader, System.CF.Design, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a System.Windows.Forms.Design.CFResXResourceWriter, System.CF.Design, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a False True Private 4, 4 True Private False Private Private Private False Private False Private Private False True Private 4, 4 True Private False Private Private Private False Private Private False Private False Private Private Private False Private False Private Private False Private Private False Private Private False Private Private False True Private 4, 4 True Private False Private Private False Private Private False Private Private False Private Private False Private Private Private 17, 17 Private Private Private Private Private Private Private False True Private 4, 4 True Private False Private Private False Private Private Private False Private False Private Private False Private Private False (Default) False False 4, 4 True 80 True Private Form1 mysql-connector-net-6.4.3/Samples/Pocket PC/MobileExplorer/AssemblyInfo.cs0000644000175000017500000000357311127003600027151 0ustar directhexdirecthexusing System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified - the assembly cannot be signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. // (*) If the key file and a key name attributes are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP - that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the file is installed into the CSP and used. // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] mysql-connector-net-6.4.3/Samples/Pocket PC/MobileExplorer/MobileExplorer.sln0000644000175000017500000000210611127003600027664 0ustar directhexdirecthexMicrosoft Visual Studio Solution File, Format Version 8.00 Project("{20D4826A-C6FA-45DB-90F4-C717570B9F32}") = "MobileExplorer", "MobileExplorer.csdproj", "{64CC840B-DDA1-4CBB-98FC-FC19FF591C3C}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution Debug = Debug Release = Release EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {64CC840B-DDA1-4CBB-98FC-FC19FF591C3C}.Debug.ActiveCfg = Debug|Windows CE {64CC840B-DDA1-4CBB-98FC-FC19FF591C3C}.Debug.Build.0 = Debug|Windows CE {64CC840B-DDA1-4CBB-98FC-FC19FF591C3C}.Debug.Deploy.0 = Debug|Windows CE {64CC840B-DDA1-4CBB-98FC-FC19FF591C3C}.Release.ActiveCfg = Release|Windows CE {64CC840B-DDA1-4CBB-98FC-FC19FF591C3C}.Release.Build.0 = Release|Windows CE {64CC840B-DDA1-4CBB-98FC-FC19FF591C3C}.Release.Deploy.0 = Release|Windows CE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal mysql-connector-net-6.4.3/Samples/Pocket PC/MobileExplorer/MobileExplorer.csdproj0000644000175000017500000001556211127003600030546 0ustar directhexdirecthex mysql-connector-net-6.4.3/Samples/Pocket PC/MobileExplorer/NewServerDialog.resx0000644000175000017500000002735111127003600030172 0ustar directhexdirecthex text/microsoft-resx 1.3 System.Windows.Forms.Design.CFResXResourceReader, System.CF.Design, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a System.Windows.Forms.Design.CFResXResourceWriter, System.CF.Design, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a False Private Private Private False Private False Private Private Private Private False False Private Private Private False Private False Private Private Private False Private False Private Private False Private Private False (Default) False NewServerDialog False 4, 4 True 80 True Private