Added Bearer oAuth Authentication:

* Create User with roles
* Login
* Authorization without roles
This commit is contained in:
CMS4390\marantalu
2017-11-23 16:31:30 +01:00
parent 0961b72054
commit 7a6e75ffd5
39 changed files with 4884 additions and 113 deletions
+31
View File
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.10.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider></providers>
</entityFramework>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" /></startup><system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add description=".Net Framework Data Provider for MySQL" invariant="MySql.Data.MySqlClient" name="MySQL Data Provider" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.10.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.10.4.0" newVersion="6.10.4.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
@@ -0,0 +1,71 @@
using System;
using System.Linq;
using System.Web.Helpers;
using Step.Model;
namespace Step.Database.Controllers
{
public class UsersController : IDisposable
{
private DatabaseContext dbCtx;
public UsersController()
{
// Initialize database context
dbCtx = new DatabaseContext();
}
public void Dispose()
{
// Clear database context
dbCtx.Dispose();
}
public void Create(string userName, string password, string firstName, string lastName, int roleId)
{
// Create a new user model with params
UserModel user = new UserModel()
{
Username = userName,
Password = Crypto.HashPassword(password),
FirstName = firstName,
LastName = lastName,
RoleId = roleId,
SecurityStamp = Guid.NewGuid().ToString()
};
// Add to database
dbCtx.Users.Add(user);
// Commit changes
dbCtx.SaveChanges();
}
public UserModel Find(int id)
{
// Find user by Id with Role object included
return dbCtx.Users.Include("Role").Where(u => u.UserId == id).First();
}
public UserModel Find(string username)
{
// Find user by Id with Role object included
return dbCtx.Users.Include("Role").Where(u => u.Username == username).FirstOrDefault();
}
public UserModel Find(string username, string password)
{
// Find if username exists
UserModel user = Find(username);
if (user != null)
{
// Check if the passwords match
if (Crypto.VerifyHashedPassword(user.Password, password) != true)
{
return null;
}
}
return user;
}
}
}
+24
View File
@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Step.Model;
using MySql.Data.Entity;
namespace Step.Database
{
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class DatabaseContext : DbContext
{
public DbSet<UserModel> Users { get; set; }
public DbSet<RoleModel> Roles { get; set; }
public DatabaseContext()
: base("databaseConnection")
{
}
}
}
+36
View File
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Le informazioni generali relative a un assembly sono controllate dal seguente
// set di attributi. Modificare i valori di questi attributi per modificare le informazioni
// associate a un assembly.
[assembly: AssemblyTitle("Step.Database")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Step.Database")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili
// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da
// COM, impostare su true l'attributo ComVisible per tale tipo.
[assembly: ComVisible(false)]
// Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi
[assembly: Guid("357d5ee1-ffc8-489b-9232-22cf474d9a6f")]
// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori:
//
// Versione principale
// Versione secondaria
// Numero di build
// Revisione
//
// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
// usando l'asterisco '*' come illustrato di seguito:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+95
View File
@@ -0,0 +1,95 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{357D5EE1-FFC8-489B-9232-22CF474D9A6F}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Step.Database</RootNamespace>
<AssemblyName>Step.Database</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll</HintPath>
</Reference>
<Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.SqlServer.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNet.Identity.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.Identity.EntityFramework.2.2.1\lib\net45\Microsoft.AspNet.Identity.EntityFramework.dll</HintPath>
</Reference>
<Reference Include="MySql.Data">
<HintPath>..\packages\MySql.Data.6.10.4\lib\net452\MySql.Data.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="MySql.Data.Entity.EF6, Version=6.9.10.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
<HintPath>..\packages\MySql.Data.Entity.6.9.10\lib\net45\MySql.Data.Entity.EF6.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Web.Helpers.Crypto, Version=3.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\System.Web.Helpers.Crypto.3.2.3\lib\net40\System.Web.Helpers.Crypto.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Controllers\UsersController.cs" />
<Compile Include="DatabaseContext.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Step.Model\Step.Model.csproj">
<Project>{631375dd-06d3-49bb-8130-d9ddb34c429d}</Project>
<Name>Step.Model</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="docs\MySqlCommand.xml" />
<Content Include="docs\MySqlCommandBuilder.xml" />
<Content Include="docs\MySqlConnection.xml" />
<Content Include="docs\MySqlConnectionStringBuilder.xml" />
<Content Include="docs\MySqlDataAdapter.xml" />
<Content Include="docs\MySqlDataReader.xml" />
<Content Include="docs\MySqlException.xml" />
<Content Include="docs\MySqlHelper.xml" />
<Content Include="docs\MySqlParameter.xml" />
<Content Include="docs\MySqlParameterCollection.xml" />
<Content Include="docs\MySqlTransaction.xml" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
+934
View File
@@ -0,0 +1,934 @@
<docs>
<ClassSummary>
<summary>Represents a SQL statement to execute against a MySQL database. This class cannot be inherited.</summary>
<remarks>
<B>MySqlCommand</B> features the following methods for executing commands at a MySQL database:
<list type="table">
<listheader>
<term>Item</term>
<term>Description</term>
</listheader>
<item>
<term>
<a href="MySql.Data.MySqlClient.MySqlCommand.ExecuteReader_overloads.html">ExecuteReader</a>
</term>
<description>Executes commands that return rows.</description>
</item>
<item>
<term>
<a href="MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery.html">ExecuteNonQuery</a>
</term>
<description>Executes commands such as SQL INSERT, DELETE, and UPDATE statements.</description>
</item>
<item>
<term>
<a href="MySql.Data.MySqlClient.MySqlCommand.ExecuteScalar.html">ExecuteScalar</a>
</term>
<description>Retrieves a single value (for example, an aggregate value) from a database.</description>
</item>
</list>
You can reset the <B>CommandText</B> property and reuse the <B>MySqlCommand</B>
object. However, you must close the <A
href="MySql.Data.MySqlClient.MySqlDataReader.html">MySqlDataReader</A>
before you can execute a new or previous command.
If a <A href="MySql.Data.MySqlClient.MySqlException.html">MySqlException</A> is
generated by the method executing a <B>MySqlCommand</B>, the <A
href="MySql.Data.MySqlClient.MySqlConnection.html">MySqlConnection</A>
remains open. It is the responsibility of the programmer to close the connection.
<note>
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.
</note>
</remarks>
<example>
The following example creates a <A href="frlrfsystemdatasqlclientsqlcommandclasstopic.htm">MySqlCommand</A> and
a <B>MySqlConnection</B>. The <B>MySqlConnection</B> is opened and set as the <A
href="frlrfsystemdatasqlclientsqlcommandclassconnectiontopic.htm">Connection</A>
for the <B>MySqlCommand</B>. The example then calls <A
href="frlrfsystemdatasqlclientsqlcommandclassexecutenonquerytopic.htm">ExecuteNonQuery</A>,
and closes the connection. To accomplish this, the <B>ExecuteNonQuery</B> is
passed a connection string and a query string that is a SQL INSERT
statement.
<code lang="vbnet">
Public Sub InsertRow(myConnectionString As String)
&quot; 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
</code>
<code lang="C#">
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();
}
</code>
</example>
</ClassSummary>
<ctor1>
<overloads>
<summary>
Initializes a new instance of the MySqlCommand class.
</summary>
<example>
The following example creates a MySqlCommand and sets some of its properties.
<para></para>
<note>
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.
</note>
<code lang="vbnet">
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
</code>
<code lang="C#">
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;
}
</code>
<code lang="C++">
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;
};
</code>
</example>
</overloads>
<summary>
Initializes a new instance of the MySqlCommand class.
</summary>
<remarks>
The base constructor initializes all fields to their default values. The
following table shows initial property values for an instance of <see cref="MySqlCommand"/>.
<list type="table">
<listheader>
<term>Properties</term>
<term>Initial Value</term>
</listheader>
<item>
<term>
<see cref="CommandText"/>
</term>
<term>empty string ("")</term>
</item>
<item>
<term>
<see cref="CommandTimeout"/>
</term>
<term>0</term>
</item>
<item>
<term>
<see cref="CommandType"/>
</term>
<term>CommandType.Text</term>
</item>
<item>
<term>
<see cref="Connection"/>
</term>
<term>Null</term>
</item>
</list>
<para>
You can change the value for any of these properties through a separate call to
the property.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlCommand"/> and
sets some of its properties.
<code lang="vbnet">
Public Sub CreateMySqlCommand()
Dim myCommand As New MySqlCommand()
myCommand.CommandType = CommandType.Text
End Sub
</code>
<code lang="C#">
public void CreateMySqlCommand()
{
MySqlCommand myCommand = new MySqlCommand();
myCommand.CommandType = CommandType.Text;
}
</code>
</example>
</ctor1>
<ctor2>
<summary>
Initializes a new instance of the <see cref="MySqlCommand"/> class with the text of the query.
</summary>
<param name="cmdText">The text of the query.</param>
<remarks>
When an instance of <see cref="MySqlCommand"/> is created,
the following read/write properties are set to initial values.
<list type="table">
<listheader>
<term>Properties</term>
<term>Initial Value</term>
</listheader>
<item>
<term>
<see cref="CommandText"/>
</term>
<term>
<i>cmdText</i>
</term>
</item>
<item>
<term>
<see cref="CommandTimeout"/>
</term>
<term>0</term>
</item>
<item>
<term>
<see cref="CommandType"/>
</term>
<term>CommandType.Text</term>
</item>
<item>
<term>
<see cref="Connection"/>
</term>
<term>Null</term>
</item>
</list>
<para>
You can change the value for any of these properties through a separate call to
the property.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlCommand"/> and
sets some of its properties.
<code lang="vbnet">
Public Sub CreateMySqlCommand()
Dim sql as String = "SELECT * FROM mytable"
Dim myCommand As New MySqlCommand(sql)
myCommand.CommandType = CommandType.Text
End Sub
</code>
<code lang="C#">
public void CreateMySqlCommand()
{
string sql = "SELECT * FROM mytable";
MySqlCommand myCommand = new MySqlCommand(sql);
myCommand.CommandType = CommandType.Text;
}
</code>
</example>
</ctor2>
<ctor3>
<summary>
Initializes a new instance of the <see cref="MySqlCommand"/> class
with the text of the query and a <see cref="MySqlConnection"/>.
</summary>
<param name="cmdText">The text of the query.</param>
<param name="connection">
A <see cref="MySqlConnection"/> that represents the
connection to an instance of SQL Server.
</param>
<remarks>
When an instance of <see cref="MySqlCommand"/> is created,
the following read/write properties are set to initial values.
<list type="table">
<listheader>
<term>Properties</term>
<term>Initial Value</term>
</listheader>
<item>
<term>
<see cref="CommandText"/>
</term>
<term>
<i>cmdText</i>
</term>
</item>
<item>
<term>
<see cref="CommandTimeout"/>
</term>
<term>0</term>
</item>
<item>
<term>
<see cref="CommandType"/>
</term>
<term>CommandType.Text</term>
</item>
<item>
<term>
<see cref="Connection"/>
</term>
<term>
<i>connection</i>
</term>
</item>
</list>
<para>
You can change the value for any of these properties through a separate call to
the property.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlCommand"/> and
sets some of its properties.
<code lang="vbnet">
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
</code>
<code lang="C#">
public void CreateMySqlCommand()
{
MySqlConnection conn = new MySqlConnection("server=myserver")
string sql = "SELECT * FROM mytable";
MySqlCommand myCommand = new MySqlCommand(sql, conn);
myCommand.CommandType = CommandType.Text;
}
</code>
</example>
</ctor3>
<ctor4>
<summary>
Initializes a new instance of the <see cref="MySqlCommand"/> class
with the text of the query, a <see cref="MySqlConnection"/>, and the
<see cref="MySqlTransaction"/>.
</summary>
<param name="cmdText">The text of the query.</param>
<param name="connection">
A <see cref="MySqlConnection"/> that represents the
connection to an instance of SQL Server.
</param>
<param name="transaction">
The <see cref="MySqlTransaction"/> in which the <see cref="MySqlCommand"/> executes.
</param>
<remarks>
When an instance of <see cref="MySqlCommand"/> is created,
the following read/write properties are set to initial values.
<list type="table">
<listheader>
<term>Properties</term>
<term>Initial Value</term>
</listheader>
<item>
<term>
<see cref="CommandText"/>
</term>
<term>
<i>cmdText</i>
</term>
</item>
<item>
<term>
<see cref="CommandTimeout"/>
</term>
<term>0</term>
</item>
<item>
<term>
<see cref="CommandType"/>
</term>
<term>CommandType.Text</term>
</item>
<item>
<term>
<see cref="Connection"/>
</term>
<term>
<i>connection</i>
</term>
</item>
</list>
<para>
You can change the value for any of these properties through a separate call to
the property.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlCommand"/> and
sets some of its properties.
<code lang="vbnet">
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
</code>
<code lang="C#">
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;
}
</code>
</example>
</ctor4>
<ExecuteNonQuery>
<summary>
Executes a SQL statement against the connection and returns the number of rows affected.
</summary>
<returns>Number of rows affected</returns>
<remarks>
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.
</remarks>
<example>
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.
<code lang="vbnet">
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
</code>
<code lang="C#">
public void CreateMySqlCommand(string myExecuteQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myExecuteQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
</code>
</example>
</ExecuteNonQuery>
<ExecuteReader1>
<summary>
Sends the <see cref="CommandText"/> to the <see cref="MySqlConnection">Connection</see>,
and builds a <see cref="MySqlDataReader"/> using one of the <see cref="CommandBehavior"/> values.
</summary>
<param name="behavior">
One of the <see cref="CommandBehavior"/> values.
</param>
<remarks>
<para>
When the <see cref="CommandType"/> property is set to <B>StoredProcedure</B>,
the <see cref="CommandText"/> property should be set to the name of the stored
procedure. The command executes this stored procedure when you call
<B>ExecuteReader</B>.
</para>
<para>
The <see cref="MySqlDataReader"/> supports a special mode that enables large binary
values to be read efficiently. For more information, see the <B>SequentialAccess</B>
setting for <see cref="CommandBehavior"/>.
</para>
<para>
While the <see cref="MySqlDataReader"/> is in use, the associated
<see cref="MySqlConnection"/> is busy serving the <B>MySqlDataReader</B>.
While in this state, no other operations can be performed on the
<B>MySqlConnection</B> other than closing it. This is the case until the
<see cref="MySqlDataReader.Close"/> method of the <B>MySqlDataReader</B> is called.
If the <B>MySqlDataReader</B> is created with <B>CommandBehavior</B> set to
<B>CloseConnection</B>, closing the <B>MySqlDataReader</B> closes the connection
automatically.
</para>
<note>
When calling ExecuteReader with the SingleRow behavior, you should be aware that using a <i>limit</i>
clause in your SQL will cause all rows (up to the limit given) to be retrieved by the client. The
<see cref="MySqlDataReader.Read"/> 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 <i>limit</i> clause is not necessary, it should
be avoided.
</note>
</remarks>
<returns>
A <see cref="MySqlDataReader"/> object.
</returns>
</ExecuteReader1>
<ExecuteReader>
<summary>
Sends the <see cref="CommandText"/> to the <see cref="MySqlConnection">Connection</see>
and builds a <see cref="MySqlDataReader"/>.
</summary>
<returns>
A <see cref="MySqlDataReader"/> object.
</returns>
<remarks>
<para>
When the <see cref="CommandType"/> property is set to <B>StoredProcedure</B>,
the <see cref="CommandText"/> property should be set to the name of the stored
procedure. The command executes this stored procedure when you call
<B>ExecuteReader</B>.
</para>
<para>
While the <see cref="MySqlDataReader"/> is in use, the associated
<see cref="MySqlConnection"/> is busy serving the <B>MySqlDataReader</B>.
While in this state, no other operations can be performed on the
<B>MySqlConnection</B> other than closing it. This is the case until the
<see cref="MySqlDataReader.Close"/> method of the <B>MySqlDataReader</B> is called.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlCommand"/>, then executes it by
passing a string that is a SQL SELECT statement, and a string to use to connect to the
data source.
<code lang="vbnet">
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
</code>
<code lang="C#">
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();
}
}
</code>
</example>
</ExecuteReader>
<Prepare>
<summary>
Creates a prepared version of the command on an instance of MySQL Server.
</summary>
<remarks>
<para>
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.
</para>
</remarks>
<example>
The following example demonstrates the use of the <b>Prepare</b> method.
<code lang="VB.NET">
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
</code>
<code lang="C#">
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();
}
</code>
</example>
</Prepare>
<ExecuteScalar>
<summary>
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.
</summary>
<returns>
The first column of the first row in the result set, or a null reference if the
result set is empty
</returns>
<remarks>
<para>
Use the <B>ExecuteScalar</B> method to retrieve a single value (for example,
an aggregate value) from a database. This requires less code than using the
<see cref="ExecuteReader()"/> method, and then performing the operations necessary
to generate the single value using the data returned by a <see cref="MySqlDataReader"/>
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlCommand"/> and then
executes it using <B>ExecuteScalar</B>. 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.
<code lang="vbnet">
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
</code>
<code lang="C#">
public void CreateMySqlCommand(string myScalarQuery, MySqlConnection myConnection)
{
MySqlCommand myCommand = new MySqlCommand(myScalarQuery, myConnection);
myCommand.Connection.Open();
myCommand.ExecuteScalar();
myConnection.Close();
}
</code>
<code lang="C++">
public:
void CreateMySqlCommand(String* myScalarQuery, MySqlConnection* myConnection)
{
MySqlCommand* myCommand = new MySqlCommand(myScalarQuery, myConnection);
myCommand-&gt;Connection-&gt;Open();
myCommand-&gt;ExecuteScalar();
myConnection-&gt;Close();
}
</code>
</example>
</ExecuteScalar>
<CommandText>
<summary>
Gets or sets the SQL statement to execute at the data source.
</summary>
<value>
The SQL statement or stored procedure to execute. The default is an empty string.
</value>
<remarks>
<para>
When the <see cref="CommandType"/> property is set to <B>StoredProcedure</B>,
the <B>CommandText</B> 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.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlCommand"/> and sets some of its properties.
<code lang="vbnet">
Public Sub CreateMySqlCommand()
Dim myCommand As New MySqlCommand()
myCommand.CommandText = "SELECT * FROM Mytable ORDER BY id"
myCommand.CommandType = CommandType.Text
End Sub
</code>
<code lang="C#">
public void CreateMySqlCommand()
{
MySqlCommand myCommand = new MySqlCommand();
myCommand.CommandText = "SELECT * FROM mytable ORDER BY id";
myCommand.CommandType = CommandType.Text;
}
</code>
</example>
</CommandText>
<CommandTimeout>
<summary>
Gets or sets the wait time before terminating the attempt to execute a command
and generating an error.
</summary>
<value>
The time (in seconds) to wait for the command to execute. The default is 30
seconds.
</value>
<remarks>
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.
</remarks>
</CommandTimeout>
<CommandType>
<summary>
Gets or sets a value indicating how the <see cref="CommandText"/> property is to be interpreted.
</summary>
<value>
One of the <see cref="System.Data.CommandType"/> values. The default is <B>Text</B>.
</value>
<remarks>
<para>
When you set the <B>CommandType</B> property to <B>StoredProcedure</B>, you
should set the <see cref="CommandText"/> property to the name of the stored
procedure. The command executes this stored procedure when you call one of the
Execute methods.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlCommand"/> and sets some of its properties.
<code lang="vbnet">
Public Sub CreateMySqlCommand()
Dim myCommand As New MySqlCommand()
myCommand.CommandType = CommandType.Text
End Sub
</code>
<code lang="C#">
public void CreateMySqlCommand()
{
MySqlCommand myCommand = new MySqlCommand();
myCommand.CommandType = CommandType.Text;
}
</code>
</example>
</CommandType>
<Connection>
<summary>
Gets or sets the <see cref="MySqlConnection"/> used by this instance of the
<see cref="MySqlCommand"/>.
</summary>
<value>
The connection to a data source. The default value is a null reference
(<B>Nothing</B> in Visual Basic).
</value>
<remarks>
<para>
If you set <B>Connection</B> while a transaction is in progress and the
<see cref="Transaction"/> property is not null, an <see cref="InvalidOperationException"/>
is generated. If the <B>Transaction</B> property is not null and the transaction
has already been committed or rolled back, <B>Transaction</B> is set to
null.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlCommand"/> and sets some of its properties.
<code lang="vbnet">
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
</code>
<code lang="C#">
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;
}
</code>
</example>
</Connection>
<IsPrepared>
</IsPrepared>
<LastInsertedId>
<summary>Provides the id of the last inserted row.</summary>
<value>
Id of the last inserted row. -1 if none exists.
</value>
<remarks>
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.
</remarks>
</LastInsertedId>
<Parameters>
<summary>
Get the <see cref="MySqlParameterCollection"/>
</summary>
<value>
The parameters of the SQL statement or stored procedure. The default is
an empty collection.
</value>
<remarks>
Connector/Net does not support unnamed parameters. Every parameter added to the collection must
have an associated name.
</remarks>
<example>
The following example creates a <see cref="MySqlCommand"/> and displays its parameters.
To accomplish this, the method is passed a <see cref="MySqlConnection"/>, a query string
that is a SQL SELECT statement, and an array of <see cref="MySqlParameter"/> objects.
<code lang="vbnet">
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() &amp; ControlChars.Cr
Next i
Console.WriteLine(myMessage)
End Sub
</code>
<code lang="C#">
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&lt;myParamArray.Length; j++)
{
myCommand.Parameters.Add(myParamArray[j]) ;
}
string myMessage = "";
for (int i = 0; i &lt; myCommand.Parameters.Count; i++)
{
myMessage += myCommand.Parameters[i].ToString() + "\n";
}
MessageBox.Show(myMessage);
}
</code>
</example>
</Parameters>
<Transaction>
<summary>
Gets or sets the <see cref="MySqlTransaction"/> within which the <see cref="MySqlCommand"/> executes.
</summary>
<value>
The <see cref="MySqlTransaction"/>. The default value is a null reference (<B>Nothing</B> in Visual Basic).
</value>
<remarks>
You cannot set the <B>Transaction</B> 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 <see cref="MySqlTransaction"/> object that is not connected
to the same <see cref="MySqlConnection"/> as the <see cref="MySqlCommand"/> object,
an exception will be thrown the next time you attempt to execute a statement.
</remarks>
</Transaction>
<UpdatedRowSource>
<summary>
Gets or sets how command results are applied to the <see cref="DataRow"/>
when used by the <see cref="System.Data.Common.DbDataAdapter.Update"/> method
of the <see cref="System.Data.Common.DbDataAdapter"/>.
</summary>
<value>
One of the <see cref="UpdateRowSource"/> values.
</value>
<remarks>
<para>
The default <see cref="System.Data.UpdateRowSource"/> value is
<B>Both</B> unless the command is automatically generated (as in the case of the
<see cref="MySqlCommandBuilder"/>), in which case the default is <B>None</B>.
</para>
</remarks>
</UpdatedRowSource>
</docs>
+321
View File
@@ -0,0 +1,321 @@
<docs>
<class>
<summary>
Automatically generates single-table commands used to reconcile changes made to a DataSet with the associated MySQL database. This class cannot be inherited.
</summary>
<remarks>
<para>
The <see cref="MySqlDataAdapter"/> does not automatically generate the SQL statements required to
reconcile changes made to a <see cref="System.Data.DataSet">DataSet</see> with the associated instance of MySQL.
However, you can create a <B>MySqlCommandBuilder</B> object to automatically generate SQL statements for
single-table updates if you set the <see cref="MySqlDataAdapter.SelectCommand">SelectCommand</see> property
of the <B>MySqlDataAdapter</B>. Then, any additional SQL statements that you do not set are generated by the
<B>MySqlCommandBuilder</B>.
</para>
<para>
The <B>MySqlCommandBuilder</B> registers itself as a listener for <see cref="MySqlDataAdapter.OnRowUpdating">RowUpdating</see>
events whenever you set the <see cref="DataAdapter"/> property. You can only associate one
<B>MySqlDataAdapter</B> or <B>MySqlCommandBuilder</B> object with each other at one time.
</para>
<para>
To generate INSERT, UPDATE, or DELETE statements, the <B>MySqlCommandBuilder</B> uses the
<B>SelectCommand</B> property to retrieve a required set of metadata automatically. If you change
the <B>SelectCommand</B> after the metadata has is retrieved (for example, after the first update), you
should call the <see cref="RefreshSchema"/> method to update the metadata.
</para>
<para>
The <B>SelectCommand</B> must also return at least one primary key or unique
column. If none are present, an <I>InvalidOperation</I> exception is generated,
and the commands are not generated.
</para>
<para>
The <B>MySqlCommandBuilder</B> also uses the <see cref="MySqlCommand.Connection">Connection</see>,
<see cref="MySqlCommand.CommandTimeout">CommandTimeout</see>, and <see cref="MySqlCommand.Transaction">Transaction</see>
properties referenced by the <B>SelectCommand</B>. The user should call
<B>RefreshSchema</B> if any of these properties are modified, or if the
<B>SelectCommand</B> itself is replaced. Otherwise the <see cref="MySqlDataAdapter.InsertCommand">InsertCommand</see>,
<see cref="MySqlDataAdapter.UpdateCommand">UpdateCommand</see>, and
<see cref="MySqlDataAdapter.DeleteCommand">DeleteCommand</see> properties retain
their previous values.
</para>
<para>
If you call <i>Dispose</i>, the <B>MySqlCommandBuilder</B> is disassociated
from the <B>MySqlDataAdapter</B>, and the generated commands are no longer used.
</para>
<note>
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.
</note>
</remarks>
<example>
The following example uses the <see cref="MySqlCommand"/>, along
<see cref="MySqlDataAdapter"/> and <see cref="MySqlConnection"/>, to
select rows from a data source. The example is passed an initialized
<see cref="System.Data.DataSet"/>, 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 <B>MySqlCommandBuilder</B>.
<code lang="vbnet">
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
</code>
<code lang="C#">
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;
}
</code>
</example>
</class>
<Ctor>
<summary>
Initializes a new instance of the <see cref="MySqlCommandBuilder"/> class.
</summary>
</Ctor>
<Ctor2>
<summary>
Initializes a new instance of the <see cref="MySqlCommandBuilder"/> class
with the associated <see cref="MySqlDataAdapter"/> object.
</summary>
<param name="adapter">
The <see cref="MySqlDataAdapter"/> to use.
</param>
<remarks>
<para>
The <see cref="MySqlCommandBuilder"/> registers itself as a listener for
<see cref="MySqlDataAdapter.RowUpdating"/> events that are generated by the
<see cref="MySqlDataAdapter"/> specified in this property.
</para>
<para>
When you create a new instance <B>MySqlCommandBuilder</B>, any existing
<B>MySqlCommandBuilder</B> associated with this <B>MySqlDataAdapter</B>
is released.
</para>
</remarks>
</Ctor2>
<DataAdapter>
<summary>
Gets or sets a <see cref="MySqlDataAdapter"/> object for which SQL statements are automatically generated.
</summary>
<value>
A <see cref="MySqlDataAdapter"/> object.
</value>
<remarks>
<para>
The <see cref="MySqlCommandBuilder"/> registers itself as a listener for
<see cref="MySqlDataAdapter.RowUpdating"/> events that are generated by the
<see cref="MySqlDataAdapter"/> specified in this property.
</para>
<para>
When you create a new instance <B>MySqlCommandBuilder</B>, any existing
<B>MySqlCommandBuilder</B> associated with this <B>MySqlDataAdapter</B>
is released.
</para>
</remarks>
</DataAdapter>
<QuotePrefix>
<summary>
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.
</summary>
<value>
The beginning character or characters to use. The default value is `.
</value>
<remarks>
Database objects in MySQL can contain special characters such as spaces that would
make normal SQL strings impossible to correctly parse. Use of the <b>QuotePrefix</b>
and the <see cref="QuoteSuffix"/> properties allows the <see cref="MySqlCommandBuilder"/>
to build SQL commands that handle this situation.
</remarks>
</QuotePrefix>
<QuoteSuffix>
<summary>
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.
</summary>
<value>
The beginning character or characters to use. The default value is `.
</value>
<remarks>
Database objects in MySQL can contain special characters such as spaces that would
make normal SQL strings impossible to correctly parse. Use of the <see cref="QuotePrefix"/>
and the <b>QuoteSuffix</b> properties allows the <see cref="MySqlCommandBuilder"/>
to build SQL commands that handle this situation.
</remarks>
</QuoteSuffix>
<DeriveParameters>
<summary>
</summary>
<remarks>
</remarks>
</DeriveParameters>
<GetDeleteCommand>
<summary>
Gets the automatically generated <see cref="MySqlCommand"/> object
required to perform deletions on the database.
</summary>
<returns>
The <see cref="MySqlCommand"/> object generated to handle delete operations.
</returns>
<remarks>
<para>
An application can use the <B>GetDeleteCommand</B> method for informational
or troubleshooting purposes because it returns the <see cref="MySqlCommand"/>
object to be executed.
</para>
<para>
You can also use <B>GetDeleteCommand</B> as the basis of a modified command.
For example, you might call <B>GetDeleteCommand</B> and modify the
<see cref="MySqlCommand.CommandTimeout"/> value, and then explicitly set that on the
<see cref="MySqlDataAdapter"/>.
</para>
<para>
After the SQL statement is first generated, the application must explicitly
call <see cref="RefreshSchema"/> if it changes the statement in any way.
Otherwise, the <B>GetDeleteCommand</B> 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
<see cref="System.Data.Common.DataAdapter.Update"/> or <B>GetDeleteCommand</B>.
</para>
</remarks>
</GetDeleteCommand>
<GetInsertCommand>
<summary>
Gets the automatically generated <see cref="MySqlCommand"/> object
required to perform insertions on the database.
</summary>
<returns>
The <see cref="MySqlCommand"/> object generated to handle insert operations.
</returns>
<remarks>
<para>
An application can use the <B>GetInsertCommand</B> method for informational
or troubleshooting purposes because it returns the <see cref="MySqlCommand"/>
object to be executed.
</para>
<para>
You can also use the <B>GetInsertCommand</B> as the basis of a modified command.
For example, you might call <B>GetInsertCommand</B> and modify the
<see cref="MySqlCommand.CommandTimeout"/> value, and then explicitly set that on the
<see cref="MySqlDataAdapter"/>.
</para>
<para>
After the SQL statement is first generated, the application must explicitly
call <see cref="RefreshSchema"/> if it changes the statement in any way.
Otherwise, the <B>GetInsertCommand</B> 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
<see cref="System.Data.Common.DataAdapter.Update"/> or <B>GetInsertCommand</B>.
</para>
</remarks>
</GetInsertCommand>
<GetUpdateCommand>
<summary>
Gets the automatically generated <see cref="MySqlCommand"/> object
required to perform updates on the database.
</summary>
<returns>
The <see cref="MySqlCommand"/> object generated to handle update operations.
</returns>
<remarks>
<para>
An application can use the <B>GetUpdateCommand</B> method for informational
or troubleshooting purposes because it returns the <see cref="MySqlCommand"/>
object to be executed.
</para>
<para>
You can also use <B>GetUpdateCommand</B> as the basis of a modified command.
For example, you might call <B>GetUpdateCommand</B> and modify the
<see cref="MySqlCommand.CommandTimeout"/> value, and then explicitly set that on the
<see cref="MySqlDataAdapter"/>.
</para>
<para>
After the SQL statement is first generated, the application must explicitly
call <see cref="RefreshSchema"/> if it changes the statement in any way.
Otherwise, the <B>GetUpdateCommand</B> 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
<see cref="System.Data.Common.DataAdapter.Update"/> or <B>GetUpdateCommand</B>.
</para>
</remarks>
</GetUpdateCommand>
<RefreshSchema>
<summary>
Refreshes the database schema information used to generate INSERT, UPDATE, or
DELETE statements.
</summary>
<remarks>
<para>
An application should call <B>RefreshSchema</B> whenever the SELECT statement
associated with the <see cref="MySqlCommandBuilder"/> changes.
</para>
<para>
An application should call <B>RefreshSchema</B> whenever the
<see cref="MySqlDataAdapter.SelectCommand"/> value of the <see cref="MySqlDataAdapter"/> changes.
</para>
</remarks>
</RefreshSchema>
</docs>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,55 @@
<docs>
<Server>
<summary>
Gets or sets the name or address of the MySQL instance to connect to.
</summary>
<remarks>
If this property is not set, then the provider will attempt to
connect to <b>localhost</b> even though this property will return
<b>String.Empty</b>.
</remarks>
<example>
</example>
</Server>
<Database>
<summary>
Gets or sets the name of the database that should be selected
when the connection is first opened.
</summary>
<remarks>
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 <see cref="ChangeDatabase"/> method.
</remarks>
<example>
</example>
</Database>
<ConnectionProtocol>
<summary>
Gets or sets the connection protocol that is being used for this
connection.
</summary>
<remarks>
</remarks>
<example>
</example>
</ConnectionProtocol>
<PipeName>
<summary>
Gets or sets the name of the named pipe object that the provider
should use.
</summary>
<remarks>
This property has no effect unless the <see cref="ConnectionProtocol"/>
property has been set to <b>NamedPipe</b>.
</remarks>
<example>
</example>
</PipeName>
</docs>
+801
View File
@@ -0,0 +1,801 @@
<docs>
<class>
<summary>
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.
</summary>
<remarks>
<para>
The <B>MySQLDataAdapter</B>, serves as a bridge between a <see cref="System.Data.DataSet"/>
and MySQL for retrieving and saving data. The <B>MySQLDataAdapter</B> provides this
bridge by mapping <see cref="DbDataAdapter.Fill(DataSet)"/>, which changes the data in the
<B>DataSet</B> to match the data in the data source, and <see cref="System.Data.Common.DbDataAdapter.Update(System.Data.DataSet)"/>,
which changes the data in the data source to match the data in the <B>DataSet</B>,
using the appropriate SQL statements against the data source.
</para>
<para>
When the <B>MySQLDataAdapter</B> fills a <B>DataSet</B>, 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
<see cref="System.Data.MissingSchemaAction"/> property is set to <see cref="System.Data.MissingSchemaAction.AddWithKey"/>.
You may also have the <B>MySQLDataAdapter</B> create the schema of the <B>DataSet</B>,
including primary key information, before filling it with data using <see cref="System.Data.Common.DbDataAdapter.FillSchema(DataTable, SchemaType)"/>.
</para>
<para>
<B>MySQLDataAdapter</B> is used in conjunction with <see cref="MySqlConnection"/>
and <see cref="MySqlCommand"/> to increase performance when connecting to a MySQL database.
</para>
<para>
The <B>MySQLDataAdapter</B> also includes the <see cref="MySqlDataAdapter.SelectCommand"/>,
<see cref="MySqlDataAdapter.InsertCommand"/>, <see cref="MySqlDataAdapter.DeleteCommand"/>,
<see cref="MySqlDataAdapter.UpdateCommand"/>, and <see cref="DataAdapter.TableMappings"/>
properties to facilitate the loading and updating of data.
</para>
<para>
When an instance of <B>MySQLDataAdapter</B> is created, the read/write properties
are set to initial values. For a list of these values, see the <B>MySQLDataAdapter</B>
constructor.
</para>
<note>
Please be aware that the <see cref="DataColumn"/> 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.
</note>
</remarks>
<example>
The following example creates a <see cref="MySqlCommand"/> and a <see cref="MySqlConnection"/>.
The <B>MySqlConnection</B> is opened and set as the <see cref="MySqlCommand.Connection"/> for the
<B>MySqlCommand</B>. The example then calls <see cref="MySqlCommand.ExecuteNonQuery"/>, and closes
the connection. To accomplish this, the <B>ExecuteNonQuery</B> is
passed a connection string and a query string that is a SQL INSERT
statement.
<code lang="vbnet">
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
</code>
<code lang="C#">
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;
}
</code>
</example>
</class>
<Ctor>
<overloads></overloads>
<summary>
Initializes a new instance of the MySqlDataAdapter class.
</summary>
<remarks>
<para>
When an instance of <see cref="MySqlDataAdapter"/> is created,
the following read/write properties are set to the following initial
values.
</para>
<list type="table">
<listheader>
<term>Properties</term>
<term>Initial Value</term>
</listheader>
<item>
<term>
<see cref="MissingMappingAction"/>
</term>
<term>
<B>MissingMappingAction.Passthrough</B>
</term>
</item>
<item>
<term>
<see cref="MissingSchemaAction"/>
</term>
<term>
<B>MissingSchemaAction.Add</B>
</term>
</item>
</list>
<para>
You can change the value of any of these properties through a separate call
to the property.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlDataAdapter"/> and sets some of
its properties.
<code lang="vbnet">
Public Sub CreateSqlDataAdapter()
Dim conn As MySqlConnection = New MySqlConnection("Data Source=localhost;" &amp; _
"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) " &amp; _
"VALUES (@id, @name)", conn)
da.UpdateCommand = New MySqlCommand("UPDATE mytable SET id=@id, name=@name " &amp; _
"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
</code>
<code lang="C#">
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;
}
</code>
</example>
</Ctor>
<Ctor1>
<summary>
Initializes a new instance of the <see cref="MySqlDataAdapter"/> class with
the specified <see cref="MySqlCommand"/> as the <see cref="SelectCommand"/>
property.
</summary>
<param name="selectCommand">
<see cref="MySqlCommand"/> that is a SQL SELECT statement or stored procedure and is set
as the <see cref="SelectCommand"/> property of the <see cref="MySqlDataAdapter"/>.
</param>
<remarks>
<para>
When an instance of <see cref="MySqlDataAdapter"/> is created,
the following read/write properties are set to the following initial
values.
</para>
<list type="table">
<listheader>
<term>Properties</term>
<term>Initial Value</term>
</listheader>
<item>
<term>
<see cref="MissingMappingAction"/>
</term>
<term>
<B>MissingMappingAction.Passthrough</B>
</term>
</item>
<item>
<term>
<see cref="MissingSchemaAction"/>
</term>
<term>
<B>MissingSchemaAction.Add</B>
</term>
</item>
</list>
<para>
You can change the value of any of these properties through a separate call
to the property.
</para>
<para>
When <B>SelectCommand</B> (or any of the other command properties) is assigned
to a previously created <see cref="MySqlCommand"/>, the <B>MySqlCommand</B> is not cloned.
The <B>SelectCommand</B> maintains a reference to the previously created <B>MySqlCommand</B>
object.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlDataAdapter"/> and sets some of
its properties.
<code lang="vbnet">
Public Sub CreateSqlDataAdapter()
Dim conn As MySqlConnection = New MySqlConnection("Data Source=localhost;" &amp; _
"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) " &amp; _
"VALUES (@id, @name)", conn)
da.UpdateCommand = New MySqlCommand("UPDATE mytable SET id=@id, name=@name " &amp; _
"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
</code>
<code lang="C#">
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;
}
</code>
</example>
</Ctor1>
<Ctor2>
<summary>
Initializes a new instance of the <see cref="MySqlDataAdapter"/> class with
a <see cref="SelectCommand"/> and a <see cref="MySqlConnection"/> object.
</summary>
<param name="selectCommandText">
A <b>String</b> that is a SQL SELECT statement or stored procedure to be used by
the <see cref="SelectCommand"/> property of the <see cref="MySqlDataAdapter"/>.
</param>
<param name="connection">
A <see cref="MySqlConnection"/> that represents the connection.
</param>
<remarks>
<para>
This implementation of the <see cref="MySqlDataAdapter"/> opens and closes a <see cref="MySqlConnection"/>
if it is not already open. This can be useful in a an application that must call the
<see cref="DbDataAdapter.Fill(DataSet)"/> method for two or more <B>MySqlDataAdapter</B> objects.
If the <B>MySqlConnection</B> is already open, you must explicitly call
<see cref="MySqlConnection.Close"/> or <see cref="MySqlConnection.Dispose()"/> to close it.
</para>
<para>
When an instance of <see cref="MySqlDataAdapter"/> is created,
the following read/write properties are set to the following initial
values.
</para>
<list type="table">
<listheader>
<term>Properties</term>
<term>Initial Value</term>
</listheader>
<item>
<term>
<see cref="MissingMappingAction"/>
</term>
<term>
<B>MissingMappingAction.Passthrough</B>
</term>
</item>
<item>
<term>
<see cref="MissingSchemaAction"/>
</term>
<term>
<B>MissingSchemaAction.Add</B>
</term>
</item>
</list>
<para>
You can change the value of any of these properties through a separate call
to the property.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlDataAdapter"/> and sets some of
its properties.
<code lang="vbnet">
Public Sub CreateSqlDataAdapter()
Dim conn As MySqlConnection = New MySqlConnection("Data Source=localhost;" &amp; _
"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) " &amp; _
"VALUES (@id, @name)", conn)
da.UpdateCommand = New MySqlCommand("UPDATE mytable SET id=@id, name=@name " &amp; _
"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
</code>
<code lang="C#">
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;
}
</code>
</example>
</Ctor2>
<Ctor3>
<summary>
Initializes a new instance of the <see cref="MySqlDataAdapter"/> class with
a <see cref="SelectCommand"/> and a connection string.
</summary>
<param name="selectCommandText">
A <see cref="string"/> that is a SQL SELECT statement or stored procedure to
be used by the <see cref="SelectCommand"/> property of the <see cref="MySqlDataAdapter"/>.
</param>
<param name="selectConnString">The connection string</param>
<remarks>
<para>
When an instance of <see cref="MySqlDataAdapter"/> is created,
the following read/write properties are set to the following initial
values.
</para>
<list type="table">
<listheader>
<term>Properties</term>
<term>Initial Value</term>
</listheader>
<item>
<term>
<see cref="MissingMappingAction"/>
</term>
<term>
<B>MissingMappingAction.Passthrough</B>
</term>
</item>
<item>
<term>
<see cref="MissingSchemaAction"/>
</term>
<term>
<B>MissingSchemaAction.Add</B>
</term>
</item>
</list>
<para>
You can change the value of any of these properties through a separate call
to the property.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlDataAdapter"/> and sets some of
its properties.
<code lang="vbnet">
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) " &amp; _
"VALUES (@id, @name)", conn)
da.UpdateCommand = New MySqlCommand("UPDATE mytable SET id=@id, name=@name " &amp; _
"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
</code>
<code lang="C#">
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;
}
</code>
</example>
</Ctor3>
<DeleteCommand>
<summary>
Gets or sets a SQL statement or stored procedure used to delete records from the data set.
</summary>
<value>
A <see cref="MySqlCommand"/> used during <see cref="System.Data.Common.DbDataAdapter.Update(System.Data.DataSet)"/> to delete records in the
database that correspond to deleted rows in the <see cref="DataSet"/>.
</value>
<remarks>
<para>
During <see cref="System.Data.Common.DbDataAdapter.Update(System.Data.DataSet)"/>, if this property is not set and primary key information
is present in the <see cref="DataSet"/>, the <B>DeleteCommand</B> can be generated
automatically if you set the <see cref="SelectCommand"/> property and use the
<see cref="MySqlCommandBuilder"/>. Then, any additional commands that you do not set are
generated by the <B>MySqlCommandBuilder</B>. This generation logic requires key column
information to be present in the <B>DataSet</B>.
</para>
<para>
When <B>DeleteCommand</B> is assigned to a previously created <see cref="MySqlCommand"/>,
the <B>MySqlCommand</B> is not cloned. The <B>DeleteCommand</B> maintains a reference
to the previously created <B>MySqlCommand</B> object.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlDataAdapter"/> and sets the
<see cref="SelectCommand"/> and <B>DeleteCommand</B> properties. It assumes you have already
created a <see cref="MySqlConnection"/> object.
<code lang="vbnet">
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
</code>
<code lang="C#">
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;
}
</code>
</example>
</DeleteCommand>
<InsertCommand>
<summary>
Gets or sets a SQL statement or stored procedure used to insert records into the data set.
</summary>
<value>
A <see cref="MySqlCommand"/> used during <see cref="System.Data.Common.DbDataAdapter.Update(System.Data.DataSet)"/> to insert records into the
database that correspond to new rows in the <see cref="DataSet"/>.
</value>
<remarks>
<para>
During <see cref="System.Data.Common.DbDataAdapter.Update(System.Data.DataSet)"/>, if this property is not set and primary key information
is present in the <see cref="DataSet"/>, the <B>InsertCommand</B> can be generated
automatically if you set the <see cref="SelectCommand"/> property and use the
<see cref="MySqlCommandBuilder"/>. Then, any additional commands that you do not set are
generated by the <B>MySqlCommandBuilder</B>. This generation logic requires key column
information to be present in the <B>DataSet</B>.
</para>
<para>
When <B>InsertCommand</B> is assigned to a previously created <see cref="MySqlCommand"/>,
the <B>MySqlCommand</B> is not cloned. The <B>InsertCommand</B> maintains a reference
to the previously created <B>MySqlCommand</B> object.
</para>
<note>
If execution of this command returns rows, these rows may be added to the <B>DataSet</B>
depending on how you set the <see cref="MySqlCommand.UpdatedRowSource"/> property of the <B>MySqlCommand</B> object.
</note>
</remarks>
<example>
The following example creates a <see cref="MySqlDataAdapter"/> and sets the
<see cref="SelectCommand"/> and <B>InsertCommand</B> properties. It assumes you have already
created a <see cref="MySqlConnection"/> object.
<code lang="vbnet">
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
</code>
<code lang="C#">
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;
}
</code>
</example>
</InsertCommand>
<UpdateCommand>
<summary>
Gets or sets a SQL statement or stored procedure used to updated records in the data source.
</summary>
<value>
A <see cref="MySqlCommand"/> used during <see cref="System.Data.Common.DbDataAdapter.Update(System.Data.DataSet)"/> to update records in the
database with data from the <see cref="DataSet"/>.
</value>
<remarks>
<para>
During <see cref="System.Data.Common.DbDataAdapter.Update(System.Data.DataSet)"/>, if this property is not set and primary key information
is present in the <see cref="DataSet"/>, the <B>UpdateCommand</B> can be generated
automatically if you set the <see cref="SelectCommand"/> property and use the
<see cref="MySqlCommandBuilder"/>. Then, any additional commands that you do not set are
generated by the <B>MySqlCommandBuilder</B>. This generation logic requires key column
information to be present in the <B>DataSet</B>.
</para>
<para>
When <B>UpdateCommand</B> is assigned to a previously created <see cref="MySqlCommand"/>,
the <B>MySqlCommand</B> is not cloned. The <B>UpdateCommand</B> maintains a reference
to the previously created <B>MySqlCommand</B> object.
</para>
<note>
If execution of this command returns rows, these rows may be merged with the DataSet
depending on how you set the <see cref="MySqlCommand.UpdatedRowSource"/> property of the <B>MySqlCommand</B> object.
</note>
</remarks>
<example>
The following example creates a <see cref="MySqlDataAdapter"/> and sets the
<see cref="SelectCommand"/> and <B>UpdateCommand</B> properties. It assumes you have already
created a <see cref="MySqlConnection"/> object.
<code lang="vbnet">
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
</code>
<code lang="C#">
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;
}
</code>
</example>
</UpdateCommand>
<SelectCommand>
<summary>
Gets or sets a SQL statement or stored procedure used to select records in the data source.
</summary>
<value>
A <see cref="MySqlCommand"/> used during <see cref="System.Data.Common.DbDataAdapter.Fill(DataSet)"/> to select records from the
database for placement in the <see cref="DataSet"/>.
</value>
<remarks>
<para>
When <B>SelectCommand</B> is assigned to a previously created <see cref="MySqlCommand"/>,
the <B>MySqlCommand</B> is not cloned. The <B>SelectCommand</B> maintains a reference to the
previously created <B>MySqlCommand</B> object.
</para>
<para>
If the <B>SelectCommand</B> does not return any rows, no tables are added to the
<see cref="DataSet"/>, and no exception is raised.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlDataAdapter"/> and sets the
<see cref="SelectCommand"/> and <B>InsertCommand</B> properties. It assumes you have already
created a <see cref="MySqlConnection"/> object.
<code lang="vbnet">
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
</code>
<code lang="C#">
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;
}
</code>
</example>
</SelectCommand>
</docs>
+452
View File
@@ -0,0 +1,452 @@
<docs>
<ClassSummary>
<summary>
Provides a means of reading a forward-only stream of rows from a MySQL database. This class cannot be inherited.
</summary>
<remarks>
<para>
To create a <B>MySQLDataReader</B>, you must call the <see cref="MySqlCommand.ExecuteReader()"/>
method of the <see cref="MySqlCommand"/> object, rather than directly using a constructor.
</para>
<para>
While the <B>MySqlDataReader</B> is in use, the associated <see cref="MySqlConnection"/>
is busy serving the <B>MySqlDataReader</B>, and no other operations can be performed
on the <B>MySqlConnection</B> other than closing it. This is the case until the
<see cref="MySqlDataReader.Close"/> method of the <B>MySqlDataReader</B> is called.
</para>
<para>
<see cref="MySqlDataReader.IsClosed"/> and <see cref="MySqlDataReader.RecordsAffected"/>
are the only properties that you can call after the <B>MySqlDataReader</B> is
closed. Though the <B>RecordsAffected</B> property may be accessed at any time
while the <B>MySqlDataReader</B> exists, always call <B>Close</B> before returning
the value of <B>RecordsAffected</B> to ensure an accurate return value.
</para>
<para>
For optimal performance, <B>MySqlDataReader</B> avoids creating
unnecessary objects or making unnecessary copies of data. As a result, multiple calls
to methods such as <see cref="MySqlDataReader.GetValue"/> return a reference to the
same object. Use caution if you are modifying the underlying value of the objects
returned by methods such as <B>GetValue</B>.
</para>
</remarks>
<example>
The following example creates a <see cref="MySqlConnection"/>,
a <see cref="MySqlCommand"/>, and a <B>MySqlDataReader</B>. The example reads through
the data, writing it out to the console. Finally, the example closes the <B>MySqlDataReader</B>, then the
<B>MySqlConnection</B>.
<code lang="vbnet">
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) &amp; ", " &amp; 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
</code>
<code lang="C#">
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();
}
</code>
</example>
</ClassSummary>
<GetBytes>
<remarks>
<para>
<B>GetBytes</B> 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 <B>GetBytes</B> has already been used
to obtain bytes from the field. This may be the case, for example, if the
<see cref="MySqlDataReader"/> is reading a large data structure into a buffer.
For more information, see the <B>SequentialAccess</B> setting for
<see cref="MySqlCommand.CommandBehavior"/>.
</para>
<para>
If you pass a buffer that is a null reference (<B>Nothing</B> in Visual
Basic), <B>GetBytes</B> returns the length of the field in bytes.
</para>
<para>
No conversions are performed; therefore the data retrieved must already be a
byte array.
</para>
</remarks>
</GetBytes>
<GetTimeSpan>
<overloads/>
<summary>
Gets the value of the specified column as a <see cref="TimeSpan"/> object.
</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>Time</b> value.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="column">The zero-based column ordinal or column name.</param>
<returns>The value of the specified column.</returns>
</GetTimeSpan>
<GetDateTime>
<summary>
Gets the value of the specified column as a <see cref="DateTime"/> object.
</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>DateTime</b> object.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
<note>
<para>
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 <see cref="GetMySqlDateTime(int)"/>.
</para>
<para>
The behavior of reading a zero datetime column using this method is defined by the
<i>ZeroDateTimeBehavior</i> connection string option. For more information on this option,
please refer to <see cref="MySqlConnection.ConnectionString"/>.
</para>
</note>
</remarks>
<param name="i">The zero-based column ordinal.</param>
<returns>The value of the specified column.</returns>
</GetDateTime>
<GetDateTimeS>
<summary>
Gets the value of the specified column as a <see cref="DateTime"/> object.
</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>DateTime</b> object.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
<note>
<para>
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 <see cref="GetMySqlDateTime(int)"/>.
</para>
<para>
The behavior of reading a zero datetime column using this method is defined by the
<i>ZeroDateTimeBehavior</i> connection string option. For more information on this option,
please refer to <see cref="MySqlConnection.ConnectionString"/>.
</para>
</note>
</remarks>
<param name="column">The column name.</param>
<returns>The value of the specified column.</returns>
</GetDateTimeS>
<GetMySqlDateTime>
<summary>
Gets the value of the specified column as a <see cref="MySql.Data.Types.MySqlDateTime"/> object.
</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>DateTime</b> object.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="column">The zero-based column ordinal or column name.</param>
<returns>The value of the specified column.</returns>
</GetMySqlDateTime>
<GetString>
<summary>
Gets the value of the specified column as a <see cref="String"/> object.
</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>String</b> object.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="i">The zero-based column ordinal.</param>
<returns>The value of the specified column.</returns>
</GetString>
<GetStringS>
<summary>
Gets the value of the specified column as a <see cref="String"/> object.
</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>String</b> object.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="column">The column name.</param>
<returns>The value of the specified column.</returns>
</GetStringS>
<GetDecimal>
<summary>
Gets the value of the specified column as a <see cref="Decimal"/> object.
</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>Decimal</b> object.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="i">The zero-based column ordinal</param>
<returns>The value of the specified column.</returns>
</GetDecimal>
<GetDecimalS>
<summary>
Gets the value of the specified column as a <see cref="Decimal"/> object.
</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>Decimal</b> object.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="column">The column name</param>
<returns>The value of the specified column.</returns>
</GetDecimalS>
<GetDouble>
<summary>Gets the value of the specified column as a double-precision floating point number.</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>Double</b> object.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="i">The zero-based column ordinal.</param>
<returns>The value of the specified column.</returns>
</GetDouble>
<GetDoubleS>
<summary>Gets the value of the specified column as a double-precision floating point number.</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>Double</b> object.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="column">The column name</param>
<returns>The value of the specified column.</returns>
</GetDoubleS>
<GetFloat>
<summary>
Gets the value of the specified column as a single-precision floating point number.
</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>Float</b> object.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="i">The zero-based column ordinal.</param>
<returns>The value of the specified column.</returns>
</GetFloat>
<GetFloatS>
<summary>
Gets the value of the specified column as a single-precision floating point number.
</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>Float</b> object.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="column">The column name</param>
<returns>The value of the specified column.</returns>
</GetFloatS>
<GetGiud>
<summary>Gets the value of the specified column as a globally-unique identifier (GUID).</summary>
<param name="i">The zero-based column ordinal.</param>
<returns>The value of the specified column.</returns>
</GetGiud>
<GetGiudS>
<summary>Gets the value of the specified column as a globally-unique identifier (GUID).</summary>
<param name="column">The column name</param>
<returns>The value of the specified column.</returns>
</GetGiudS>
<GetInt16>
<summary>Gets the value of the specified column as a 16-bit signed integer.</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>16 bit integer</b> value.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="i">The zero-based column ordinal.</param>
<returns>The value of the specified column.</returns>
</GetInt16>
<GetInt16S>
<summary>Gets the value of the specified column as a 16-bit signed integer.</summary>
<remarks>
<para>
No conversions are performed; threfore, the data retrieved must already be a <b>16 bit integer</b> value.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="column">The column name</param>
<returns>The value of the specified column.</returns>
</GetInt16S>
<GetInt32>
<summary>Gets the value of the specified column as a 32-bit signed integer.</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>32 bit integer</b> value.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="i">The zero-based column ordinal.</param>
<returns>The value of the specified column.</returns>
</GetInt32>
<GetInt32S>
<summary>Gets the value of the specified column as a 32-bit signed integer.</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>32 bit integer</b> value.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="column">The column name.</param>
<returns>The value of the specified column.</returns>
</GetInt32S>
<GetInt64>
<summary>Gets the value of the specified column as a 64-bit signed integer.</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>64 bit integer</b> value.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="i">The zero-based column ordinal.</param>
<returns>The value of the specified column.</returns>
</GetInt64>
<GetInt64S>
<summary>Gets the value of the specified column as a 64-bit signed integer.</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>64 bit integer</b> value.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="column">The column name.</param>
<returns>The value of the specified column.</returns>
</GetInt64S>
<GetUInt16>
<summary>Gets the value of the specified column as a 16-bit unsigned integer.</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>16 bit unsigned integer</b> value.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="column">The zero-based column ordinal or column name.</param>
<returns>The value of the specified column.</returns>
</GetUInt16>
<GetUInt32>
<summary>Gets the value of the specified column as a 32-bit unsigned integer.</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>32 bit unsigned integer</b> value.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="column">The zero-based column ordinal or column name.</param>
<returns>The value of the specified column.</returns>
</GetUInt32>
<GetUInt64>
<summary>Gets the value of the specified column as a 64-bit unsigned integer.</summary>
<remarks>
<para>
No conversions are performed; therefore, the data retrieved must already be a <b>64 bit unsigned integer</b> value.
</para>
<para>
Call IsDBNull to check for null values before calling this method.
</para>
</remarks>
<param name="column">The zero-based column ordinal or column name.</param>
<returns>The value of the specified column.</returns>
</GetUInt64>
</docs>
+53
View File
@@ -0,0 +1,53 @@
<MyDocs>
<MyMembers name="Class">
<remarks>
<para>
This class is created whenever the MySql Data Provider encounters an error generated from the server.
</para>
<para>
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
<see cref="MySqlDataReader"/> objects or <see cref="MySqlConnection"/> objects.
</para>
</remarks>
<example>
The following example generates a <B>MySqlException</B> due to a missing server,
and then displays the exception.
<code lang="vbnet">
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
</code>
<code lang="C#">
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 );
}
}
</code>
</example>
</MyMembers>
</MyDocs>
+53
View File
@@ -0,0 +1,53 @@
<MyDocs>
<MyMembers name="Class">
<remarks>
<para>
This class is created whenever the MySql Data Provider encounters an error generated from the server.
</para>
<para>
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
<see cref="MySqlDataReader"/> objects or <see cref="MySqlConnection"/> objects.
</para>
</remarks>
<example>
The following example generates a <B>MySqlException</B> due to a missing server,
and then displays the exception.
<code lang="vbnet">
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
</code>
<code lang="C#">
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 );
}
}
</code>
</example>
</MyMembers>
</MyDocs>
+45
View File
@@ -0,0 +1,45 @@
<MyDocs>
<MyMembers name="Class">
<remarks>
Parameter names are not case sensitive.
</remarks>
<example>
The following example creates multiple instances of <B>MySqlParameter</B> through the
<see cref="MySqlParameterCollection"/> collection within the <see cref="MySqlDataAdapter"/>.
These parameters are used to select data from the data source and place the data
in the <see cref="DataSet"/>. This example assumes that a <B>DataSet</B> and a
<B>MySqlDataAdapter</B> have already been created with the appropriate schema, commands,
and connection.
<code lang="vbnet">
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
</code>
<code lang="C#">
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);
}
</code>
</example>
</MyMembers>
</MyDocs>
@@ -0,0 +1,45 @@
<MyDocs>
<MyMembers name="Class">
<remarks>
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.
</remarks>
<example>
The following example creates multiple instances of <see cref="MySqlParameter"/>
through the <B>MySqlParameterCollection</B> collection within the <see cref="MySqlDataAdapter"/>.
These parameters are used to select data within the data source and place the data in
the <see cref="System.Data.DataSet"/>. This code assumes that a <B>DataSet</B> and a <B>MySqlDataAdapter</B>
have already been created with the appropriate schema, commands, and connection.
<code lang="vbnet">
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
</code>
<code lang="C#">
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);
}
</code>
</example>
</MyMembers>
</MyDocs>
+329
View File
@@ -0,0 +1,329 @@
<docs>
<Class>
<summary>
Represents a SQL transaction to be made in a MySQL database. This class cannot be inherited.
</summary>
<remarks>
The application creates a <B>MySqlTransaction</B> object by calling <see cref="MySqlConnection.BeginTransaction()"/>
on the <see cref="MySqlConnection"/> object. All subsequent operations associated with the
transaction (for example, committing or aborting the transaction), are performed on the
<B>MySqlTransaction</B> object.
</remarks>
<example>
The following example creates a <see cref="MySqlConnection"/> and a <B>MySqlTransaction</B>.
It also demonstrates how to use the <see cref="MySqlConnection.BeginTransaction()"/>,
<see cref="MySqlTransaction.Commit"/>, and <see cref="MySqlTransaction.Rollback"/> methods.
<code lang="vbnet">
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 " &amp; ex.GetType().ToString() &amp; _
" was encountered while attempting to roll back the transaction.")
End If
End Try
Console.WriteLine("An exception of type " &amp; e.GetType().ToString() &amp; _
"was encountered while inserting the data.")
Console.WriteLine("Neither record was written to database.")
Finally
myConnection.Close()
End Try
End Sub 'RunTransaction
</code>
<code lang="C#">
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();
}
}
</code>
</example>
</Class>
<Rollback>
<summary>
Rolls back a transaction from a pending state.
</summary>
<remarks>
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).
</remarks>
<example>
The following example creates a <see cref="MySqlConnection"/> and a
<see cref="MySqlTransaction"/>. It also demonstrates how to use the
<see cref="MySqlConnection.BeginTransaction()"/>, <see cref="Commit"/>, and <B>Rollback</B>
methods.
<code lang="vbnet">
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 " &amp; ex.GetType().ToString() &amp; _
" was encountered while attempting to roll back the transaction.")
End If
End Try
Console.WriteLine("An exception of type " &amp; e.GetType().ToString() &amp; _
"was encountered while inserting the data.")
Console.WriteLine("Neither record was written to database.")
Finally
myConnection.Close()
End Try
End Sub
</code>
<code lang="C#">
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();
}
}
</code>
</example>
</Rollback>
<Commit>
<summary>
Commits the database transaction.
</summary>
<remarks>
The <b>Commit</b> method is equivalent to the MySQL SQL statement
COMMIT.
</remarks>
<example>
The following example creates a <see cref="MySqlConnection"/> and a
<see cref="MySqlTransaction"/>. It also demonstrates how to use the
<see cref="MySqlConnection.BeginTransaction()"/>, <see cref="Commit"/>, and <B>Rollback</B>
methods.
<code lang="vbnet">
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 " &amp; ex.GetType().ToString() &amp; _
" was encountered while attempting to roll back the transaction.")
End If
End Try
Console.WriteLine("An exception of type " &amp; e.GetType().ToString() &amp; _
"was encountered while inserting the data.")
Console.WriteLine("Neither record was written to database.")
Finally
myConnection.Close()
End Try
End Sub
</code>
<code lang="C#">
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();
}
}
</code>
</example>
</Commit>
</docs>
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.2.0" targetFramework="net462" />
<package id="Microsoft.AspNet.Identity.Core" version="2.2.1" targetFramework="net461" />
<package id="Microsoft.AspNet.Identity.EntityFramework" version="2.2.1" targetFramework="net461" />
<package id="MySql.Data" version="6.10.4" targetFramework="net462" />
<package id="MySql.Data.Entity" version="6.9.10" targetFramework="net462" />
<package id="System.Web.Helpers.Crypto" version="3.2.3" targetFramework="net462" />
</packages>
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v13.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
-15
View File
@@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Step.Model
{
public class LoginViewModel
{
public string Username { get; set; }
public string Password { get; set; }
}
}
-6
View File
@@ -1,6 +0,0 @@
declare module server {
interface loginViewModel {
username: string;
password: string;
}
}
+23
View File
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Step.Model
{
[Table("roles")]
public class RoleModel
{
[Key]
[Column("id")]
public int RoleId { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("level")]
public int Level { get; set; }
public List<UserModel> Users { get; set; }
}
}
+8
View File
@@ -0,0 +1,8 @@
declare module server {
interface roleModel {
roleId: number;
name: string;
level: number;
users: server.UserModel[];
}
}
+27 -10
View File
@@ -30,7 +30,20 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.dll</HintPath>
</Reference>
<Reference Include="EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<HintPath>..\packages\EntityFramework.6.2.0\lib\net45\EntityFramework.SqlServer.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNet.Identity.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll</HintPath>
</Reference>
<Reference Include="Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.AspNet.Identity.EntityFramework.2.2.1\lib\net45\Microsoft.AspNet.Identity.EntityFramework.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
@@ -40,28 +53,32 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="LoginViewModel.cs">
<Compile Include="RoleModel.cs">
<Generator>DtsGenerator</Generator>
<LastGenOutput>LoginViewModel.cs.d.ts</LastGenOutput>
</Compile>
<Compile Include="TestModel.cs">
<Generator>DtsGenerator</Generator>
<LastGenOutput>TestModel.cs.d.ts</LastGenOutput>
<LastGenOutput>RoleModel.cs.d.ts</LastGenOutput>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UserModel.cs">
<Generator>DtsGenerator</Generator>
<LastGenOutput>UserModel.cs.d.ts</LastGenOutput>
</Compile>
</ItemGroup>
<ItemGroup>
<TypeScriptCompile Include="LoginViewModel.cs.d.ts">
<TypeScriptCompile Include="RoleModel.cs.d.ts">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>LoginViewModel.cs</DependentUpon>
<DependentUpon>RoleModel.cs</DependentUpon>
</TypeScriptCompile>
<TypeScriptCompile Include="TestModel.cs.d.ts">
<TypeScriptCompile Include="UserModel.cs.d.ts">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>TestModel.cs</DependentUpon>
<DependentUpon>UserModel.cs</DependentUpon>
</TypeScriptCompile>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>XCOPY $(ProjectDir)*.d.ts $(SolutionDir)Step\wwwroot\src\@types /C /Y /O</PostBuildEvent>
-15
View File
@@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Step.Model
{
public class TestModel
{
public int Id { get; set; }
}
}
-5
View File
@@ -1,5 +0,0 @@
declare module server {
interface testModel {
id: number;
}
}
+33
View File
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Step.Model
{
[Table("user")]
public class UserModel
{
[Key]
[Column("id")]
public int UserId { get; set; }
[Required]
[Column("username")]
public string Username { get; set; }
[Column("first_name")]
public string FirstName { get; set; }
[Column("last_name")]
public string LastName { get; set; }
[Column("password")]
public string Password { get; set; }
[Column("security_stamp")]
public string SecurityStamp { get; set; }
[Column("role_id")]
public int RoleId { get; set; }
[ForeignKey("RoleId")]
public RoleModel Role { get; set; }
}
}
+12
View File
@@ -0,0 +1,12 @@
declare module server {
interface userModel {
userId: number;
username: string;
firstName: string;
lastName: string;
password: string;
securityStamp: string;
roleId: number;
role: server.RoleModel;
}
}
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="6.2.0" targetFramework="net462" />
<package id="Microsoft.AspNet.Identity.Core" version="2.2.1" targetFramework="net462" />
<package id="Microsoft.AspNet.Identity.EntityFramework" version="2.2.1" targetFramework="net462" />
</packages>
+6
View File
@@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Step.Model", "Step.Model\St
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Step.UI", "Step.UI\Step.UI.csproj", "{20FC0937-E7CA-4693-95F9-7A948EFD173B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Step.Database", "Step.Database\Step.Database.csproj", "{357D5EE1-FFC8-489B-9232-22CF474D9A6F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -27,6 +29,10 @@ Global
{20FC0937-E7CA-4693-95F9-7A948EFD173B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{20FC0937-E7CA-4693-95F9-7A948EFD173B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{20FC0937-E7CA-4693-95F9-7A948EFD173B}.Release|Any CPU.Build.0 = Release|Any CPU
{357D5EE1-FFC8-489B-9232-22CF474D9A6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{357D5EE1-FFC8-489B-9232-22CF474D9A6F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{357D5EE1-FFC8-489B-9232-22CF474D9A6F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{357D5EE1-FFC8-489B-9232-22CF474D9A6F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
+11 -1
View File
@@ -46,9 +46,19 @@
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.10.4.0" newVersion="6.10.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Cors" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<connectionStrings>
<add name="databaseConnection" providerName="MySql.Data.MySqlClient" connectionString="Server=localhost;Database=test;Uid=root;Pwd=root;" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
+44 -24
View File
@@ -1,5 +1,4 @@
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using System.Web.Http;
@@ -8,41 +7,62 @@ using System.IO;
using System.Reflection;
using Microsoft.Owin.FileSystems;
using System.Configuration;
using Microsoft.Owin.Security.OAuth;
using Step.Provider;
[assembly: OwinStartup(typeof(Step.App_Start.Startup))]
namespace Step.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
public class Startup
{
// Configurazione HTTP di avvio
HttpConfiguration config = new HttpConfiguration();
public void Configuration(IAppBuilder app)
{
// Configure HTTP
HttpConfiguration config = new HttpConfiguration();
// Registrazione delle Web API
WebApiConfig.Register(config);
// Register Web API config
WebApiConfig.Register(config);
// Registrazione di Swagger
SwaggerConfig.Register(config);
// Register Swagger config
SwaggerConfig.Register(config);
// Registrazione di SignalR
app.MapSignalR();
// Configure authentication
ConfigureOAuth(app);
app.UseWebApi(config);
// Register SignalR
app.MapSignalR();
var directoryBrowsing = ConfigurationManager.AppSettings["enableDirectoryBrowsing"] == "true";
app.UseWebApi(config);
string rootDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..", "wwwroot");
var options = new FileServerOptions()
{
EnableDefaultFiles = !directoryBrowsing,
EnableDirectoryBrowsing = directoryBrowsing,
RequestPath = PathString.Empty,
FileSystem = new PhysicalFileSystem(rootDir)
};
var directoryBrowsing = ConfigurationManager.AppSettings["enableDirectoryBrowsing"] == "true";
app.UseFileServer(options);
string rootDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..", "wwwroot");
var options = new FileServerOptions()
{
EnableDefaultFiles = !directoryBrowsing,
EnableDirectoryBrowsing = directoryBrowsing,
RequestPath = PathString.Empty,
FileSystem = new PhysicalFileSystem(rootDir)
};
app.UseFileServer(options);
}
private void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
//TODO: In modalità di produzione impostare AllowInsecureHttp = false
AllowInsecureHttp = true
};
app.UseOAuthAuthorizationServer(OAuthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
}
}
-23
View File
@@ -1,23 +0,0 @@
using Step.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
namespace Step.Controllers
{
[RoutePrefix("api/data")]
public class DataController : ApiController
{
[ResponseType(typeof(TestModel))]
[Route(""), HttpGet]
public IHttpActionResult Test()
{
return Ok(new TestModel() { Id = 42 });
}
}
}
+14 -10
View File
@@ -5,21 +5,25 @@ using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Step.Database.Controllers;
using System.Web.Http.Controllers;
using System.Security.Claims;
namespace Step.Controllers
{
[RoutePrefix("api/login")]
public class LoginController : ApiController
{
[Route(), HttpPost]
public IHttpActionResult DoLogin(LoginViewModel model)
[RoutePrefix("api/login")]
public class LoginController : ApiController
{
if (model.Username == "utente" && model.Password == "finto") return Ok();
return Unauthorized();
[Route(), HttpPost]
public IHttpActionResult DoLogin(UserModel model)
{
UsersController usersController = new UsersController();
usersController.Create(model.Username, "passwor", "nome","cognome", 1);
if (model.Username == "utente" && model.Password == "finto") return Ok();
return Unauthorized();
}
}
}
}
+43
View File
@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin.Security.OAuth;
using Step.Database.Controllers;
using Step.Model;
using System.Security.Claims;
namespace Step.Provider
{
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (UsersController usersController = new UsersController())
{
UserModel user = usersController.Find(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("username", user.Username));
identity.AddClaim(new Claim("role", user.Role.Level.ToString()));
context.Validated(identity);
}
}
}
}
+9 -4
View File
@@ -74,6 +74,9 @@
<Reference Include="Microsoft.Owin.Security, Version=3.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Owin.Security.3.1.0\lib\net45\Microsoft.Owin.Security.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Owin.Security.OAuth, Version=3.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Owin.Security.OAuth.3.1.0\lib\net45\Microsoft.Owin.Security.OAuth.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Owin.StaticFiles, Version=3.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Owin.StaticFiles.3.1.0\lib\net45\Microsoft.Owin.StaticFiles.dll</HintPath>
</Reference>
@@ -142,11 +145,11 @@
<Compile Include="App_Start\Startup.cs" />
<Compile Include="App_Start\SwaggerConfig.cs" />
<Compile Include="App_Start\WebApiConfig.cs" />
<Compile Include="Controllers\DataController.cs" />
<Compile Include="Controllers\DataHub.cs" />
<Compile Include="Controllers\LoginController.cs" />
<Compile Include="program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Provider\ApplicationOAuthProvider.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="App.config" />
@@ -192,9 +195,7 @@
<Content Include="wwwroot\index.html" />
<Content Include="wwwroot\webpack.config.js" />
</ItemGroup>
<ItemGroup>
<Folder Include="Provider\" />
</ItemGroup>
<ItemGroup />
<ItemGroup>
<None Include="packages.config" />
<Content Include="wwwroot\.editorconfig" />
@@ -274,6 +275,10 @@
<Content Include="wwwroot\Scripts\jquery-3.2.1.slim.min.map" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Step.Database\Step.Database.csproj">
<Project>{357d5ee1-ffc8-489b-9232-22cf474d9a6f}</Project>
<Name>Step.Database</Name>
</ProjectReference>
<ProjectReference Include="..\Step.Model\Step.Model.csproj">
<Project>{631375dd-06d3-49bb-8130-d9ddb34c429d}</Project>
<Name>Step.Model</Name>
+2
View File
@@ -17,11 +17,13 @@
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.8" targetFramework="net462" />
<package id="Microsoft.Net.Compilers" version="2.4.0" targetFramework="net462" developmentDependency="true" />
<package id="Microsoft.Owin" version="3.1.0" targetFramework="net462" />
<package id="Microsoft.Owin.Cors" version="3.1.0" targetFramework="net462" />
<package id="Microsoft.Owin.FileSystems" version="3.1.0" targetFramework="net462" />
<package id="Microsoft.Owin.Host.HttpListener" version="3.1.0" targetFramework="net462" />
<package id="Microsoft.Owin.Host.SystemWeb" version="3.1.0" targetFramework="net462" />
<package id="Microsoft.Owin.Hosting" version="3.1.0" targetFramework="net462" />
<package id="Microsoft.Owin.Security" version="3.1.0" targetFramework="net462" />
<package id="Microsoft.Owin.Security.OAuth" version="3.1.0" targetFramework="net462" />
<package id="Microsoft.Owin.StaticFiles" version="3.1.0" targetFramework="net462" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net462" />
<package id="Newtonsoft.Json" version="10.0.3" targetFramework="net462" />
+8
View File
@@ -0,0 +1,8 @@
declare module server {
interface roleModel {
roleId: number;
name: string;
level: number;
users: server.UserModel[];
}
}
+7
View File
@@ -0,0 +1,7 @@
declare module server {
interface rolesModel {
roleId: number;
name: string;
users: server.UserModel[];
}
}
+12
View File
@@ -0,0 +1,12 @@
declare module server {
interface userModel {
userId: number;
username: string;
firstName: string;
lastName: string;
password: string;
securityStamp: string;
roleId: number;
role: server.RoleModel;
}
}