#sqlconnection
Explore tagged Tumblr posts
Text
How to create a SQL dataset in C#
The dataset in Visual Studio.Net represents a localized version of data from the database you are using. You can use the data stored in the dataset, no matter your connection is closed or not. Let’s see how a dataset can be created. First, up all you need SQL connection, see how to setup connection and adapter. Build up your query with appropriate columns, then use Fill method of adapter class…
View On WordPress
0 notes
Text
Skid row i remember you

#Skid row i remember you download
** Single print order can either print or save as PDF. If the icon is greyed then these notes can not be transposed. Please check "notes" icon for transpose options. * Where transpose of I Remember You sheet music available ( not all our notes can be transposed) & prior to print. Be careful to transpose first then print (or save as PDF). If your desired notes are transposable, you will be able to transpose them after purchase. If you selected -1 Semitone for score originally in C, transposition into B would be made. This means if the composers started the song in original key of the score is C, 1 Semitone means transposition into C#. If it is completely white simply click on it and the following options will appear: Original, 1 Semitione, 2 Semitnoes, 3 Semitones, -1 Semitone, -2 Semitones, -3 Semitones. You can do this by checking the bottom of the viewer where a "notes" icon is presented. Most of our scores are traponsosable, but not all of them so we strongly advise that you check this prior to making your online purchase. If not, the notes icon will remain grayed. If transposition is available, then various semitones transposition options will appear. In order to transpose click the "notes" icon at the bottom of the viewer.
#Skid row i remember you download
After you complete your order, you will receive an order confirmation e-mail where a download link will be presented for you to obtain the notes. NET Framework Version:9 ASP.NET Version.This week we are giving away Michael Buble 'It's a Wonderful Day' score completely free. Awesome classic song by Skid Row, single called 'I Remember You'(All rights are reserved by Skid Row, Sebastian Bach and the record company concerned.)Lyric. Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1110 Song_song.Page_PreInit(Object sender, EventArgs e) +387 ModFunctions.GetSetCookie(String cookieName, Int16 daysToExpire) +330 Check out I Remember You song lyrics in English and listen to I Remember You song. ModFunctions.GetCountryIdFromDB(String defaultValue) +21 I Remember You Lyrics- Get Skid Row I Remember You song Lyrics in English. TryOpen(TaskCompletionSource`1 retry) +413 TryOpenInner(TaskCompletionSource`1 retry) +202 TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +312 TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +258 TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +156 TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +1529 It reached number six on the US Billboard Hot 100 and number 23 on the Mainstream Rock Tracks in early 1990. Composed as a power ballad, it was written by bandmates Rachel Bolan and Dave 'the Snake' Sabo. It was released in November 1989 as the third single from their eponymous debut album. UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +109 'I Remember You' is a song by American heavy metal band Skid Row. CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +964 CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +70 CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +1085 ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) +1431 Information regarding the origin and location of the exception can be identified using the exception stack trace below. Please review the stack trace for more information about the error and where it originated in the code.Įxception Details: 32Exception: The wait operation timed outĪn unhandled exception was generated during the execution of the current web request. The wait operation timed out Description: An unhandled exception occurred during the execution of the current web request. The wait operation timed out Server Error in '/' Application.

0 notes
Text
Integrate authorize.net with microsoft dynamics rms

#INTEGRATE AUTHORIZE.NET WITH MICROSOFT DYNAMICS RMS HOW TO#
#INTEGRATE AUTHORIZE.NET WITH MICROSOFT DYNAMICS RMS DRIVER#
Authorize.Microsoft Dynamics Retail Management System feature packs, service packs, and hotfixes are cumulative.Authorize.Net Data in Power Automate Desktop via ODBC.Check out our other articles for more ways to work with Power Automate (Desktop & Online): This article walks through using CData Connect Server with Power Automate Desktop. With CData Connect, you get live connectivity to Authorize.Net data within your Microsoft Power Automate workflows. Now you have a workflow to move Authorize.Net data into a CSV file. Once you have configured all the actions for the flow, click the disk icon to save the flow. SQL Connection: %SQLConnection% (the variable from the "Open SQL connection" action above)Īfter configuring the properties, save the action.Add a Close SQL Connection ActionĪdd a "Close SQL connection" action (Actions -> Database) and configure the properties. Variable to write to: %QueryResult% (the variable from the "Execute SQL statement" action above)Īfter configuring the properties, save the action.Add a Write to CSV File ActionĪdd a "Write to CSV file" action (Actions -> File) and configure the properties. SQL statement: SELECT * FROM SettledBatchListĪfter configuring the properties, save the action.SQL connection: %SQLConnection% (the variable from the "Open SQL connection" action above).Get connection by: SQL connection variable.Add an Execute SQL Statement ActionĪdd an "Execute SQL statement" action (Actions -> Database) and configure the properties. Click "Test Connection" to ensure the connection is configured properlyĪfter building the connection string in the Data Link Properties wizard, save the action.Select the database: use the database configured above (e.g.Enter information to log onto the server: select "Use a specific username and password" and use CData Connect credentials.Select or enter a server name: set to the address and port of the SQL (TDS) endpoint of CData Connect, separated by a comma (e.g.
#INTEGRATE AUTHORIZE.NET WITH MICROSOFT DYNAMICS RMS DRIVER#
On the Provider tab: select Microsoft OLE DB Driver for SQL Server.Add an Open SQL Connection ActionĪdd an "Open SQL connection" action (Actions -> Database) and click the option to build the Connection string. In the flow editor, you can add the actions to connect to Authorize.Net, query Authorize.Net using SQL, and write the query results to a CSV document. Open Microsoft Power Automate, add a new flow, and name the flow. Integrate Authorize.Net Data into Power Automate WorkflowsĪfter configuring CData Connect with Authorize.Net, you are ready to integrate Authorize.Net data into your Power Automate workflows. Click Privileges -> Add and add the new user (or an existing user) with the appropriate permissions.This property is used to authenticate that you are authorized to submit website transactions. TransactionKey: The transaction key associated with your payment gateway account.Note that this value is not the same as the login Id that you use to log in to the Merchant Interface. LoginID: The API login Id associated with your payment gateway account.If you are using a developer test account, set this to 'TRUE'. If you are using a production account, this property can be left blank. UseSandbox: The Authorize.Net API to be used to process transactions.You can obtain the necessary connection properties on the Security Settings -> General Settings page after logging into your Merchant Account. Select "Authorize.Net" from Available Data Sources.Įnter the necessary authentication properties to connect to Authorize.Net.Log into Connect Server and click Databases.Connect looks exactly like a SQL Server database to Power Automate and uses optimized data processing out of the box to push all supported SQL operations (filters, JOINs, etc) directly to Authorize.Net, leveraging server-side processing to quickly return Authorize.Net data.Ĭreate a Virtual SQL Database for Authorize.Net DataĬData Connect Server uses a straightforward, point-and-click interface to connect to data sources and generate APIs.
#INTEGRATE AUTHORIZE.NET WITH MICROSOFT DYNAMICS RMS HOW TO#
This article shows how to integrate Authorize.Net data into a simple workflow, moving Authorize.Net data into a CSV file.ĬData Connect provides a pure SQL interface for Authorize.Net, allowing you to easily integrate with live Authorize.Net data in Power Automate - without replicating the data. CData Connect enables you to access live Authorize.Net data in workflow automation tools like Power Automate.

0 notes
Text
Net framework 4.0 windows 7 ultimate 32 bit 無料ダウンロード.Download Microsoft .NET Framework 4 (スタンドアロンのインストーラー) from Official Microsoft Download Center
Net framework 4.0 windows 7 ultimate 32 bit 無料ダウンロード.Results for "net framework v4 0 30319 download for windows 7 32 bit"
Other versions.Download Microsoft .NET Framework 4 (Standalone Installer) from Official Microsoft Download Center
Feb 21, · Framework 4 の Web インストーラー パッケージでは、対象のコンピューターのアーキテクチャおよび OS 上で実行する場合に必要となる.NET Framework コンポーネントがダウンロードされ、インストールされます。 インストールにはインターネット接続が必要です。 The Framework is a highly compatible, in-place update to the Framework 4, Framework and Framework The offline package can be used in situations where the web installer cannot be used due to lack of internet connectivity Framework は、.NET Framework 4、、、、、、、、および に対する高度に互換性のあるインプレース更新です。 インターネット接続がないために Web インストーラー を使用できない状況では、オフライン パッケージを使用
Net framework 4.0 windows 7 ultimate 32 bit 無料ダウンロード.Download Microsoft .NET Framework 4 (Web インストーラー) from Official Microsoft Download Center
Jan 09, · Windows 10, Windows 7 Service Pack 1, Windows , Windows Server R2 SP1, Windows Server , Windows Server R2, Windows Server This update is supported on the following platforms Framework product installed: Windows 7 SP1 (x86 and x64) Windows (x86 and x64) Framework は、.NET Framework 4、、、、、、、、および に対する高度に互換性のあるインプレース更新です。 インターネット接続がないために Web インストーラー を使用できない状況では、オフライン パッケージを使用 Apr 26, · 重要: 複数言語の Framework 4 Language Pack (例えば日本語 Language pack と ドイツ語 Language Pack )を一台のマシンにインストールされている環境で、修復もしくはアンインストールをする場合にエラーが生じる場合があります。 詳細についてはリリースノートをご覧ください。
NET Framework 4. NET Framework 4、4. インターネット接続がないために Web インストーラー を使用できない状況では、オフライン パッケージを使用できます。 このパッケージは Web インストーラーよりも大きく、言語パックは含まれていません。 効率と帯域幅の要件を最適化するために、オフライン インストーラーの代わりに Web インストーラーを使用することをお勧めします。. Windows 7 Service Pack 1 SP1 およびWindows Server R2 SP1 では、[コントロール パネル] の [ プログラムと機能 ] の項目の下に. Windows Server では、[コントロール パネル] の [ インストールされた更新プログラム ] の項目の下に [Microsoft Windows 用の更新プログラム KB ] が表示されます。. Windows 8. Windows 10 Anniversary Update バージョン 、Windows 10 Creators Update バージョン 、および Windows Server では、[コントロール パネル] の [ インストールされた更新プログラム ] の項目の下に [Microsoft Windows用の更新プログラム KB ] が表示されます。.
Windows 10 Fall Creators Update バージョン では、[コントロール ���ネル] の [ インストールされた更新プログラム ] の項目の下に [Microsoft Windows用の更新プログラム KB ] が表示されます。. 注: パッケージ インストーラー NDPKBxxAllOS-ENU. exe は 年 7 月 10 日に更新されました。 年 7 月 10 日より前にインストーラーをダウンロードした場合は、最新バージョン 4. Windows RT 8. マイクロソフトのサポート ファイルをダウンロードする方法については、「 オンライン サービスからマイクロソフトのサポート ファイルを入手する方法 」を参照してください。. マイクロソフトでは、アップロード時点の最新のウイルス検査プログラムを使用して、配布ファイルのウイルス チェックを行っています。 配布ファイルはセキュリティで保護されたサーバー上に置かれており、権限のない第三者が無断でファイルを変更できないようになっています。.
NET Framework API の SqlConnection. ConnectionString プロパティを使用して null または空の接続文字列を設定する問題が修正されています。 この状況で、. SqlConnection と一緒に接続文字列で使用される問題が修正されています。 この状況で、非同期クエリ操作により、クライアントから不正な TDS プロトコル要求ストリームが送信されます。 これにより、非同期クエリ API が失敗します。 [、System. AppDomain またはプロセスのシャットダウン中に行われた作業から除外する AppContext スイッチを追加します。 この問題により、ファイナライザー スレッドのタイミングに関して不当な仮定をするアプリケーションのクラッシュの可能性が減ることがあります ただし、排除されることはありません 。 [、WindowsBase.
IMEPad を使用して 元のテキストとは異なる言語で 複数の文字を単一の文字に置き換えると発生する WPF のクラッシュが修正されています。 [、PresentationFramework. NET Framework は、. NET Framework 3. NET Framework に依存して COM コンポーネントの初期化を行い、制限付きのアクセス許可で実行すると、正しく起動または実行されず、"アクセスが拒否されました"、"クラスが登録されていません"、または "原因不明の理由により、内部エラーが発生しました" というエラーが返されることがあります。. この更新プログラムでサポートされているさまざまなコマンド ライン オプションの詳細については、 「. NET Framework 配置ガイド 開発者向け 」の「コマンド ライン オプション」を参照してください。. この更新プログラムのインストール後にコンピュータの再起動が必要になる場合があります。 この更新プログラムをインストールする前に、. NET Framework を使用しているすべてのアプリケーションを終了することをお勧めします。.
Windows Server Version Windows 10, version , all editions Windows 10, version , all editions Windows 10, version , all editions Windows Server R2 Windows 8. RSS フィードを購読する. はい いいえ. サポートに役立つご意見をお聞かせください。 改善にご協力いただけますか?
0 notes
Text
Windows 7 ultimate 64 bit net framework 無料ダウンロード.Microsoft Net Framework 4 For Windows 7 Ultimate 64 Bit
Windows 7 ultimate 64 bit net framework 無料ダウンロード.Windows 用の Microsoft .NET Framework 4.7.2 オフライン インストーラー
“Windowsを再インストールしたいけど、インストールメディアが見つからない!”場合に便利.Windows 用の Microsoft .NET Framework オフライン インストーラー
Jan 09, · Windows 10, Windows 7 Service Pack 1, Windows , Windows Server R2 SP1, Windows Server , Windows Server R2, Windows Server この更新プログラムは、.NET Framework 製品がインストールされている次のプラットフォームでサポートされます。 Windows 7 SP1 (x86 および x64) Jun 30, · Установка Net Framework 4 7 блокируется Windows Server R2 и из за отсутствия обновления Dcompiler. Microsoft Net Framework скачать бесплатно для 32 X64 Bit Программа Майкрософт НЕТ Фреймворк Windows 7 8 Xp Free Software Com Ua Dec 17, · Windows 7のISOイメージファイルをダウンロードする際は、Windows 7のプロダクトキーが必要です。 「Firefox 64」で廃止されたフィードプレビューと Missing: net framework
Windows 7 ultimate 64 bit net framework 無料ダウンロード.Microsoft ダウンロード センターから Windows 7 SP1 および Windows Server R2 SP1 をインストールする前に実行する手順
Jan 09, · Windows 10, Windows 7 Service Pack 1, Windows , Windows Server R2 SP1, Windows Server , Windows Server R2, Windows Server この更新プログラムは、.NET Framework 製品がインストールされている次のプラットフォームでサポートされます。 Windows 7 SP1 (x86 および x64) Windows Update から SP1 をインストールできない場合は、Microsoft ダウンロード センターからインストール パッケージをダウンロードし、SP1 を手動でインストールできます。 Microsoft web サイトの Windows 7 Service Pack 1 のダウンロードページ に移動します。Missing: net framework Aug 15, · Microsoft ダウンロード センターで Windows 7 SP1 または Windows Server R2 SP1 をインストールする。 これらの手順の実行方法については、この資料の「詳細」に記載されている詳細な手順を参照してください。
NET Framework 4. NET Framework 4、4. インターネット接続がないために Web インストーラー を使用できない状況では、オフライン パッケージを使用できます。 このパッケージは Web インストーラーよりも大きく、言語パックは含まれていません。 効率と帯域幅の要件を最適化するために、オフライン インストーラーの代わりに Web インストーラーを使用することをお勧めします。. Windows 7 Service Pack 1 SP1 およびWindows Server R2 SP1 では、[コントロール パネル] の [ プログラムと機能 ] の項目の下に. Windows Server では、[コントロール パネル] の [ インストールされた更新プログラム ] の項目の下に [Microsoft Windows 用の更新プログラム KB ] が表示されます。. Windows 8. Windows 10 Anniversary Update バージョン 、Windows 10 Creators Update バージョン 、および Windows Server では、[コントロール パネル] の [ インストールされた更新プログラム ] の項目の下に [Microsoft Windows用の更新プログラム KB ] が表示されます。.
Windows 10 Fall Creators Update バージョン では、[コントロール パネル] の [ インストールされた更新プログラム ] の項目の下に [Microsoft Windows用の更新プログラム KB ] が表示されます。. 注: パッケージ インストーラー NDPKBxxAllOS-ENU. exe は 年 7 月 10 日に更新されました。 年 7 月 10 日より前にインストーラーをダウンロードした場合は、最新バージョン 4. Windows RT 8. マイクロソフトのサポート ファイルをダウンロードする方法については、「 オンライン サービスからマイクロソフトのサポート ファイルを入手する方法 」を参照してください。. マイクロソフトでは、アップロード時点の最新のウイルス検査プログラムを使用して、配布ファイルのウイルス チェックを行っています。 配布ファイルはセキュリティで保護されたサーバー上に置かれており、権限のない第三者が無断でファイルを変更できないようになっています。.
NET Framework API の SqlConnection. ConnectionString プロパティを使用して null または空の接続文字列を設定する問題が修正されています。 この状況で、. SqlConnection と一緒に接続文字列で使用される問題が修正されています。 この状況で、非同期クエリ操作により、クライアントから不正な TDS プロトコル要求ストリームが送信されます。 これにより、非同期クエリ API が失敗します。 [、System. AppDomain またはプロセスのシャットダウン中に行われた作業から除外する AppContext スイッチを追加します。 この問題により、ファイナライザー スレッドのタイミングに関して不当な仮定をするアプリケーションのクラッシュの可能性が減ることがあります ただし、排除されることはありません 。 [、WindowsBase. IMEPad を使用して 元のテキストとは異なる言語で 複数の文字を単一の文字に置き換えると発生する WPF のクラッシュが修正されています。 [、PresentationFramework.
NET Framework は、. NET Framework 3. NET Framework に依存して COM コンポーネントの初期化を行い、制限付きのアクセス許可で実行すると、正しく起動または実行されず、"アクセスが拒否されました"、"クラスが登録されていません"、または "原因不明の理由により、内部エラーが発生しました" というエラーが返されることがあります。. この更新プログラムでサポートされているさまざまなコマンド ライン オプションの詳細については、 「.
NET Framework 配置ガイド 開発者向け 」の「コマンド ライン オプション」を参照してください。. この更新プログラムのインストール後にコンピュータの再起動が必要になる場合があります。 この更新プログラムをインストールする前に、. NET Framework を使用しているすべてのアプリケーションを終了することをお勧めします。. Windows Server Version Windows 10, version , all editions Windows 10, version , all editions Windows 10, version , all editions Windows Server R2 Windows 8.
RSS フィードを購読する. はい いいえ. サポートに役立つご意見をお聞かせください。 改善にご協力いただけますか?
0 notes
Text
CRUD Operation Using Ajax
SQl Scripts
create table Employee (EmployeeID int primary key identity,Name nvarchar(50),Age int,State nvarchar(50),Country nvarchar(50))
ALTER TABLE Employee
ADD FOREIGN KEY (DesignationID) REFERENCES tbl_Designation(Id);
--Insert and Update Employee
ALTER Procedure [dbo].[InsertUpdateEmployee]
(
@Id integer,
@Name nvarchar(50),
@Age integer,
@State nvarchar(50),
@Country nvarchar(50),
@Action varchar(10),
@DesignationID int
)
As
Begin
if @Action='Insert'
Begin
Insert into Employee(Name,Age,[State],Country,DesignationID) values(@Name,@Age,@State,@Country,@DesignationID);
End
if @Action='Update'
Begin
Update Employee set Name=@Name,Age=@Age,[State]=@State,Country=@Country,DesignationID=@DesignationID where EmployeeID=@Id;
End
End
----
--Select Employees
ALTER Procedure [dbo].[SelectEmployee]
as
Begin
SELECT EmployeeID,Name,Age,State,Country,DesignationName
FROM Employee
INNER JOIN tbl_Designation
ON Employee.DesignationID = tbl_Designation.Id;
End
---
--Delete Employee
Create Procedure DeleteEmployee
(
@Id integer
)
as
Begin
Delete Employee where EmployeeID=@Id;
End
-------------------------
Models class
Employee.cs public class Employee { public int EmployeeID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string State { get; set; }
public string Country { get; set; }
public Nullable<bool> IsDeleted { get; set; } public Nullable<int> DesignationId { get; set; } public string DesignationName { get; set; } }*****EmployeeDb.cs
using System;using System.Collections.Generic;using System.Configuration;using System.Data;using System.Data.SqlClient;using System.Linq;using System.Web;
namespace EmployeeCrudOperationUsingAjax.Models{ public class EmployeeDB { //declare connection string string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
//Return list of all Employees public List<Employee> ListAll() { List<Employee> lst = new List<Employee>(); using (SqlConnection con = new SqlConnection(cs)) { con.Open(); SqlCommand com = new SqlCommand("SelectEmployee", con); com.CommandType = CommandType.StoredProcedure; SqlDataReader rdr = com.ExecuteReader(); while (rdr.Read()) { lst.Add(new Employee { EmployeeID = Convert.ToInt32(rdr["EmployeeId"]), Name = rdr["Name"].ToString(), Age = Convert.ToInt32(rdr["Age"]), State = rdr["State"].ToString(), Country = rdr["Country"].ToString(), // DesignationId= int.Parse(rdr["DesignationId"].ToString()), DesignationName = rdr["DesignationName"].ToString() }); } return lst; } }
//Method for Adding an Employee public int Add(Employee emp) { int i; using (SqlConnection con = new SqlConnection(cs)) { con.Open(); SqlCommand com = new SqlCommand("InsertUpdateEmployee", con); com.CommandType = CommandType.StoredProcedure; com.Parameters.AddWithValue("@Id", emp.EmployeeID); com.Parameters.AddWithValue("@Name", emp.Name); com.Parameters.AddWithValue("@Age", emp.Age); com.Parameters.AddWithValue("@State", emp.State); com.Parameters.AddWithValue("@Country", emp.Country); com.Parameters.AddWithValue("@DesignationID", emp.DesignationId); com.Parameters.AddWithValue("@Action", "Insert"); i = com.ExecuteNonQuery(); } return i; }
//Method for Updating Employee record public int Update(Employee emp) { int i; using (SqlConnection con = new SqlConnection(cs)) { con.Open(); SqlCommand com = new SqlCommand("InsertUpdateEmployee", con); com.CommandType = CommandType.StoredProcedure; com.Parameters.AddWithValue("@Id", emp.EmployeeID); com.Parameters.AddWithValue("@Name", emp.Name); com.Parameters.AddWithValue("@Age", emp.Age); com.Parameters.AddWithValue("@State", emp.State); com.Parameters.AddWithValue("@Country", emp.Country); com.Parameters.AddWithValue("@DesignationID", emp.DesignationId); com.Parameters.AddWithValue("@Action", "Update"); i = com.ExecuteNonQuery(); } return i; }
//Method for Deleting an Employee public int Delete(int ID) { int i; using (SqlConnection con = new SqlConnection(cs)) { con.Open(); SqlCommand com = new SqlCommand("DeleteEmployee", con); com.CommandType = CommandType.StoredProcedure; com.Parameters.AddWithValue("@Id", ID); i = com.ExecuteNonQuery(); } return i; } }}
***********************
HomeController.cs
using EmployeeCrudOperationUsingAjax.Models;using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Services;
namespace EmployeeCrudOperationUsingAjax.Controllers{ public class HomeController : Controller { EmployeeDB empDB = new EmployeeDB(); EmployeeDBEntities Entities = new EmployeeDBEntities(); // GET: Home public ActionResult Index() { //Pass All Department List Using ViewBag List<tbl_Designation> DesigList = Entities.tbl_Designation.ToList(); ViewBag.ListOfDesignation = new SelectList(DesigList, "Id","DesignationName"); return View(); } public JsonResult List() { return Json(empDB.ListAll(), JsonRequestBehavior.AllowGet); }
public JsonResult Add(Employee emp) { return Json(empDB.Add(emp), JsonRequestBehavior.AllowGet); }
public JsonResult GetbyID(int ID) { var Employee = empDB.ListAll().Find(x => x.EmployeeID.Equals(ID)); return Json(Employee, JsonRequestBehavior.AllowGet); }
public JsonResult Update(Employee emp) { return Json(empDB.Update(emp), JsonRequestBehavior.AllowGet); }
public JsonResult Delete(int ID) { return Json(empDB.Delete(ID), JsonRequestBehavior.AllowGet); }
}}
*************Index.chtml
@model EmployeeCrudOperationUsingAjax.Models.Employee@{ Layout = null;}
<!DOCTYPE html>
<html><head> <meta name="viewport" content="width=device-width" /> <title>Index</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="~/scripts/jquery-1.12.4.js"></script> <script src="~/scripts/bootstrap.js"></script>
<script src="~/scripts/employee.js"></script> </head><body> <div class="container"> <h2>Employees Record</h2> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="clearTextBox();">Add New Employee</button><br /><br /> <table class="table table-bordered table-hover"> <thead> <tr> <th> ID </th> <th> Name </th> <th> Age </th> <th> State </th> <th> Country </th> <th> Designation </th> <th> Action </th> </tr> </thead> <tbody class="tbody"></tbody> </table> </div> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title" id="myModalLabel">Add Employee</h4> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="EmployeeId">ID</label> <input type="text" class="form-control" id="EmployeeID" placeholder="Id" disabled="disabled" /> </div> <div class="form-group"> <label for="Name">Name</label> <input type="text" class="form-control" id="Name" placeholder="Name" /> </div> <div class="form-group"> <label for="Age">Age</label> <input type="text" class="form-control" id="Age" placeholder="Age" /> </div> <div class="form-group"> @Html.DropDownListFor(m => m.DesignationId, ViewBag.ListOfDesignation as SelectList, "--Select Designation--", new { @id = "DesignationID", @class = "form-control" }) </div> <div class="form-group"> <label for="State">State</label> <input type="text" class="form-control" id="State" placeholder="State" /> </div> <div class="form-group"> <label for="Country">Country</label> <input type="text" class="form-control" id="Country" placeholder="Country" /> </div></form> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" id="btnAdd" onclick="return Add();">Add</button> <button type="button" class="btn btn-primary" id="btnUpdate" style="display:none;" onclick="Update();">Update</button> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </body></html>
********
Create Employee.js in Scripts Folder
//Load Data in Table when documents is ready $(document).ready(function () { loadData(); alert('Hi')});
//Load Data function function loadData() { $.ajax({ url: "/Home/List", type: "GET", contentType: "application/json;charset=utf-8", dataType: "json", success: function (result) { var html = ''; $.each(result, function (key, item) { html += '<tr>'; html += '<td>' + item.EmployeeID + '</td>'; html += '<td>' + item.Name + '</td>'; html += '<td>' + item.Age + '</td>'; html += '<td>' + item.State + '</td>'; html += '<td>' + item.Country + '</td>'; html += '<td>' + item.DesignationName + '</td>'; html += '<td><a href="#" onclick="return getbyID(' + item.EmployeeID + ')">Edit</a> | <a href="#" onclick="Delele(' + item.EmployeeID + ')">Delete</a></td>'; html += '</tr>'; }); $('.tbody').html(html); }, error: function (errormessage) { alert(errormessage.responseText); } });}
//Add Data Function function Add() { var res = validate(); if (res == false) { return false; } var empObj = { EmployeeID: $('#EmployeeID').val(), Name: $('#Name').val(), Age: $('#Age').val(), State: $('#State').val(), Country: $('#Country').val(), DesignationID: $('#DesignationID').val() }; $.ajax({ url: "/Home/Add", data: JSON.stringify(empObj), type: "POST", contentType: "application/json;charset=utf-8", dataType: "json", success: function (result) { loadData(); $('#myModal').modal('hide'); }, error: function (errormessage) { alert(errormessage.responseText); } });}
//Function for getting the Data Based upon Employee ID function getbyID(EmpID) { $('#Name').css('border-color', 'lightgrey'); $('#Age').css('border-color', 'lightgrey'); $('#State').css('border-color', 'lightgrey'); $('#Country').css('border-color', 'lightgrey'); $.ajax({ url: "/Home/getbyID/" + EmpID, typr: "GET", contentType: "application/json;charset=UTF-8", dataType: "json", success: function (result) { $('#EmployeeID').val(result.EmployeeID); $('#Name').val(result.Name); $('#Age').val(result.Age); $('#State').val(result.State); $('#Country').val(result.Country);
$('#myModal').modal('show'); $('#btnUpdate').show(); $('#btnAdd').hide(); }, error: function (errormessage) { alert(errormessage.responseText); } }); return false;}
//function for updating employee's record function Update() { var res = validate(); if (res == false) { return false; } var empObj = { EmployeeID: $('#EmployeeID').val(), Name: $('#Name').val(), Age: $('#Age').val(), State: $('#State').val(), Country: $('#Country').val(), DesignationID: $('#DesignationID').val() }; $.ajax({ url: "/Home/Update", data: JSON.stringify(empObj), type: "POST", contentType: "application/json;charset=utf-8", dataType: "json", success: function (result) { loadData(); $('#myModal').modal('hide'); $('#EmployeeID').val(""); $('#Name').val(""); $('#Age').val(""); $('#State').val(""); $('#Country').val(""); }, error: function (errormessage) { alert(errormessage.responseText); } });}
//function for deleting employee's record function Delele(ID) { var ans = confirm("Are you sure you want to delete this Record?"); if (ans) { $.ajax({ url: "/Home/Delete/" + ID, type: "POST", contentType: "application/json;charset=UTF-8", dataType: "json", success: function (result) { loadData(); }, error: function (errormessage) { alert(errormessage.responseText); } }); }}
//Function for clearing the textboxes function clearTextBox() { $('#EmployeeID').val(""); $('#Name').val(""); $('#Age').val(""); $('#State').val(""); $('#Country').val(""); $('#btnUpdate').hide(); $('#btnAdd').show(); $('#Name').css('border-color', 'lightgrey'); $('#Age').css('border-color', 'lightgrey'); $('#State').css('border-color', 'lightgrey'); $('#Country').css('border-color', 'lightgrey');}//Valdidation using jquery function validate() { var isValid = true; if ($('#Name').val().trim() == "") { $('#Name').css('border-color', 'Red'); isValid = false; } else { $('#Name').css('border-color', 'lightgrey'); } if ($('#Age').val().trim() == "") { $('#Age').css('border-color', 'Red'); isValid = false; } else { $('#Age').css('border-color', 'lightgrey'); } if ($('#State').val().trim() == "") { $('#State').css('border-color', 'Red'); isValid = false; } else { $('#State').css('border-color', 'lightgrey'); } if ($('#Country').val().trim() == "") { $('#Country').css('border-color', 'Red'); isValid = false; } else { $('#Country').css('border-color', 'lightgrey'); } return isValid;}
0 notes
Text
Ado.Net connection,adapter,dataset and dataview explained
I wrote this post for those who have no idea about C# database connection. When starting with Visual Studio language like C#/VB.Net, you need to understand the concept of adapter, dataset and data view. SQL connection SQL connection class helps you to build the connection string.Visual studio can build connection string for you or can create your in App config [Solution Explorer] Use SQL…
View On WordPress
#ado.net#C#connectionstring#dataadapter#Database#DatagridView#Dataset#Datasource#DataView#sqlconnection
0 notes
Text
Hướng dẫn INSERT hình ảnh vào SQL Server
BaĐể chèn vào và truy xuất hình ảnh từ cơ sở dữ liệu máy chủ SQL mà không cần sử dụng các thủ tục được lưu trữ và cũng để thực hiện các thao tác chèn, tìm kiếm, cập nhật và xóa và điều hướng các bản ghi.
Khi chúng ta muốn chèn hình ảnh vào cơ sở dữ liệu, trước tiên chúng ta phải tạo một bảng trong cơ sở dữ liệu, chúng ta có thể sử dụng kiểu dữ liệu 'image' hoặc 'binary' để lưu trữ hình ảnh.
create table student(sno int primary key,sname varchar(50),course varchar(50),fee money,photo image)
Truy vấn để tạo bảng trong ứng dụng của chúng ta
Thiết kế giao diện
Thiết kế biểu mẫu như trên với 1 control PictureBox, 1 control OpenFileDialog, 4 Labels, 4 control TextBox và 11 control Buttons.
Thuộc tính PictureBox1
BorderStyle = Cố định3D; SizeMode = StrechImage
Lưu ý rằng control OpenFileDialog xuất hiện bên dưới biểu mẫu (không phải trên biểu mẫu), có thể được sử dụng để duyệt hình ảnh.
Bắt đầu lập trình
using thư viện
using System.Data.SqlClient
Trong ứng dụng này, chúng ta sẽ tìm kiếm một bản ghi bằng cách lấy đầu vào từ InputBox. Đối với điều này, chúng tôi phải thêm tham chiếu đến Microsoft.VisualBasic.
Thêm tham chiếu vào 'Microsoft.VisualBasic'
Goto Project Menu -> Add Reference -> chọn 'Microsoft.VisualBasic' từ tab .NET.
Để sử dụng tham chiếu này, chúng tôi phải bao gồm không gian tên:
using Microsoft.VisualBasic
Chuyển đổi hình ảnh thành dữ liệu nhị phân
Chúng ta không thể lưu trữ hình ảnh trực tiếp vào cơ sở dữ liệu. Đối với điều này, chúng tôi có hai giải pháp: Để lưu trữ vị trí của hình ảnh trong cơ sở dữ liệu
Chuyển đổi hình ảnh thành dữ liệu nhị phân và chèn dữ liệu nhị phân đó vào cơ sở dữ liệu và chuyển đổi dữ liệu đó trở lại hình ảnh trong khi truy xuất các bản ghi. Nếu chúng ta lưu trữ vị trí của một hình ảnh trong cơ sở dữ liệu và giả sử nếu hình ảnh đó bị xóa hoặc di chuyển khỏi vị trí đó, chúng tôi sẽ gặp phải vấn đề khi truy xuất các bản ghi. Vì vậy, tốt hơn là chuyển đổi hình ảnh thành dữ liệu nhị phân và chèn dữ liệu nhị phân đó vào cơ sở dữ liệu và chuyển đổi lại thành hình ảnh trong khi truy xuất bản ghi.
Chúng ta có thể chuyển đổi một hình ảnh thành dữ liệu nhị phân bằng cách sử dụng
FileStream
MemoryStream
1. FileStream sử dụng vị trí tệp để chuyển đổi hình ảnh thành dữ liệu nhị phân mà chúng ta có thể / không cung cấp trong khi cập nhật bản ghi.
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read); byte[] photo_aray = new byte[fs.Length]; fs.Read(photo_aray, 0, photo_aray.Length);
2. Vì vậy, tốt hơn là sử dụng MemoryStream sử dụng hình ảnh trong PictureBox để chuyển đổi hình ảnh thành dữ liệu nhị phân.
MemoryStream ms = new MemoryStream(); pictureBox1.Image.Save(ms, ImageFormat.Jpeg); byte[] photo_aray = new byte[ms.Length]; ms.Position = 0; ms.Read(photo_aray, 0, photo_aray.Length);
Để sử dụng FileStream hoặc MemoryStream, chúng ta phải using thư viên:
using System.IO
OpenFileDialog Control Chúng ta sử dụng điều khiển OpenFileDialog để duyệt các hình ảnh (ảnh) để chèn vào bản ghi
Tải chi tiết ràng buộc vào dataTable
Trong ứng dụng này. chúng ta sử dụng phương thức Find () để tìm kiếm một bản ghi, yêu cầu chi tiết về cột khóa chính, có thể được cung cấp bằng câu lệnh:
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
Trỏ tới bản ghi hiện tại trong dataTable
Sau khi tìm kiếm một bản ghi, chúng ta phải lấy chỉ mục của bản ghi đó để có thể điều hướng các bản ghi tiếp theo và trước đó.
rno= ds.Tables[0].Rows.IndexOf(drow);
code tham khảo
using System; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Drawing.Imaging; using System.IO; using Microsoft.VisualBasic; namespace inserting_imgs { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlConnection con; SqlCommand cmd; SqlDataAdapter adapter; DataSet ds; int rno = 0; MemoryStream ms; byte[] photo_aray; private void Form1_Load(object sender, EventArgs e) { con = new SqlConnection("user id=sa;password=123;database=prash"); loaddata(); showdata(); } void loaddata() { adapter = new SqlDataAdapter("select sno,sname,course,fee,photo from student", con); adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey; ds = new DataSet(); adapter.Fill(ds, "student"); } void showdata() { if (ds.Tables[0].Rows.Count > 0) { textBox1.Text = ds.Tables[0].Rows[rno][0].ToString(); textBox2.Text = ds.Tables[0].Rows[rno][1].ToString(); textBox3.Text = ds.Tables[0].Rows[rno][2].ToString(); textBox4.Text = ds.Tables[0].Rows[rno][3].ToString(); pictureBox1.Image = null; if (ds.Tables[0].Rows[rno][4] != System.DBNull.Value) { photo_aray = (byte[])ds.Tables[0].Rows[rno][4]; MemoryStream ms = new MemoryStream(photo_aray); pictureBox1.Image = Image.FromStream(ms); } } else MessageBox.Show("No Records"); } private void browse_Click(object sender, EventArgs e) { openFileDialog1.Filter = "jpeg|*.jpg|bmp|*.bmp|all files|*.*"; DialogResult res = openFileDialog1.ShowDialog(); if (res == DialogResult.OK) { pictureBox1.Image = Image.FromFile(openFileDialog1.FileName); } } private void newbtn_Click(object sender, EventArgs e) { cmd = new SqlCommand("select max(sno)+10 from student", con); con.Open(); textBox1.Text = cmd.ExecuteScalar().ToString(); con.Close(); textBox2.Text = textBox3.Text = textBox4.Text = ""; pictureBox1.Image = null; } private void insert_Click(object sender, EventArgs e) { cmd = new SqlCommand("insert into student(sno,sname,course,fee,photo) values(" + textBox1.Text + ",'" + textBox2.TabIndex + "','" + textBox3.Text + "'," + textBox4.Text + ",@photo)", con); conv_photo(); con.Open(); int n = cmd.ExecuteNonQuery(); con.Close(); if (n > 0) { MessageBox.Show("record inserted"); loaddata(); } else MessageBox.Show("insertion failed"); } void conv_photo() { //converting photo to binary data if (pictureBox1.Image != null) { //using FileStream:(will not work while updating, if image is not changed) //FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read); //byte[] photo_aray = new byte[fs.Length]; //fs.Read(photo_aray, 0, photo_aray.Length); //using MemoryStream: ms = new MemoryStream(); pictureBox1.Image.Save(ms, ImageFormat.Jpeg); byte[] photo_aray = new byte[ms.Length]; ms.Position = 0; ms.Read(photo_aray, 0, photo_aray.Length); cmd.Parameters.AddWithValue("@photo", photo_aray); } } private void search_Click(object sender, EventArgs e) { try { int n = Convert.ToInt32(Interaction.InputBox("Enter sno:", "Search", "20", 100, 100)); DataRow drow; drow = ds.Tables[0].Rows.Find(n); if (drow != null) { rno = ds.Tables[0].Rows.IndexOf(drow); textBox1.Text = drow[0].ToString(); textBox2.Text = drow[1].ToString(); textBox3.Text = drow[2].ToString(); textBox4.Text = drow[3].ToString(); pictureBox1.Image = null; if (drow[4] != System.DBNull.Value) { photo_aray = (byte[])drow[4]; MemoryStream ms = new MemoryStream(photo_aray); pictureBox1.Image = Image.FromStream(ms); } } else MessageBox.Show("Record Not Found"); } catch { MessageBox.Show("Invalid Input"); } } private void update_Click(object sender, EventArgs e) { cmd = new SqlCommand("update student set sname='" + textBox2.Text + "', course='" + textBox3.Text + "', fee='" + textBox4.Text + "', photo=@photo where sno=" + textBox1.Text, con); conv_photo(); con.Open(); int n = cmd.ExecuteNonQuery(); con.Close(); if (n > 0) { MessageBox.Show("Record Updated"); loaddata(); } else MessageBox.Show("Updation Failed"); } private void delete_Click(object sender, EventArgs e) { cmd = new SqlCommand("delete from student where sno=" + textBox1.Text, con); con.Open(); int n = cmd.ExecuteNonQuery(); con.Close(); if (n > 0) { MessageBox.Show("Record Deleted"); loaddata(); rno = 0; showdata(); } else MessageBox.Show("Deletion Failed"); } private void first_Click(object sender, EventArgs e) { rno = 0; showdata(); MessageBox.Show("First record"); } private void previous_Click(object sender, EventArgs e) { if (rno > 0) { rno--; showdata(); } else MessageBox.Show("First record"); } private void next_Click(object sender, EventArgs e) { if (rno < ds.Tables[0].Rows.Count - 1) { rno++; showdata(); } else MessageBox.Show("Last record"); } private void last_Click(object sender, EventArgs e) { rno = ds.Tables[0].Rows.Count - 1; showdata(); MessageBox.Show("Last record"); } private void exit_Click(object sender, EventArgs e) { this.Close(); } } }
Bài viết gốc: https://www.c-sharpcorner.com/UploadFile/e628d9/inserting-retrieving-images-from-sql-server-database-without-using-stored-procedures/
0 notes
Text
Exploring the .NET open source hybrid ORM library RepoDB
It's nice to explore alternatives, especially in open source software. Just because there's a way, or an "official" way doesn't mean it's the best way.
Today I'm looking at RepoDb. It says it's "a hybrid ORM library for .NET. It is your best alternative ORM to both Dapper and Entity Framework." Cool, let's take a look.
Michael Pendon, the author puts his micro-ORM in the same category as Dapper and EF. He says "RepoDb is a new hybrid micro-ORM for .NET designed to cater the missing pieces of both micro-ORMs and macro-ORMs (aka full-ORMs). Both are fast, efficient and easy-to-use. They are also addressing different use-cases."
Dapper is a great and venerable library that is great if you love SQL. Repo is a hybrid ORM and offers more than one way to query, and support a bunch of popular databases:
SqlServer
SqLite
MySql
PostgreSql
Here's some example code:
/* Dapper */ using (var connection = new SqlConnection(ConnectionString)) { var customers = connection.Query<Customer>("SELECT Id, Name, DateOfBirth, CreatedDateUtc FROM [dbo].[Customer];"); } /* RepoDb - Raw */ using (var connection = new SqlConnection(ConnectionString)) { var customers = connection.ExecuteQuery<Customer>("SELECT Id, Name, DateOfBirth, CreatedDateUtc FROM [dbo].[Customer];"); } /* RepoDb - Fluent */ using (var connection = new SqlConnection(ConnectionString)) { var customers = connection.QueryAll<Customer>(); }
I like RepoDB's strongly typed Fluent insertion syntax:
/* RepoDb - Fluent */ using (var connection = new SqlConnection(connectionString)) { var id = connection.Insert<Customer, int>(new Customer { Name = "John Doe", DateOfBirth = DateTime.Parse("1970/01/01"), CreatedDateUtc = DateTime.UtcNow }); }
Speaking of inserts, it's BulkInsert (my least favorite thing to do) is super clean:
using (var connection = new SqlConnection(ConnectionString)) { var customers = GenerateCustomers(1000); var insertedRows = connection.BulkInsert(customers); }
The most interesting part of RepoDB is that it formally acknowledges 2nd layer caches and has a whole section on caching in the excellent RepoDB official documentation. I have a whole LazyCache subsystem behind my podcast site that is super fast but added some complexity to the code with more Func<T> that I would have preferred.
This is super clean, just passing in an ICache when you start the connection and then mention the key when querying.
var cache = CacheFactory.GetMemoryCache(); using (var connection = new SqlConnection(connectionString).EnsureOpen()) { var products = connection.QueryAll<Product>(cacheKey: "products", cache: cache); } using (var repository = new DbRepository<Product, SqlConnection>(connectionString)) { var products = repository.QueryAll(cacheKey: "products"); }
It also shows how to do generated cache keys...also clean:
// An example of the second cache key convention: var cache = CacheFactory.GetMemoryCache(); using (var connection = new SqlConnection(connectionString).EnsureOpen()) { var productId = 5; Query<Product>(product => product.Id == productId, cacheKey: $"product-id-{productId}", cache: cache); }
And of course, if you like to drop into SQL directly for whatever reason, you can .ExecuteQuery() and call sprocs or use inline SQL as you like. So far I'm enjoying RepoDB very much. It's thoughtfully designed and well documented and fast. Give it a try and see if you like it to?
Why don't you head over to https://github.com/mikependon/RepoDb now and GIVE THEM A STAR. Encourage open source. Try it on your own project and go tweet the author and share your thoughts!
Sponsor: Have you tried developing in Rider yet? This fast and feature-rich cross-platform IDE improves your code for .NET, ASP.NET, .NET Core, Xamarin, and Unity applications on Windows, Mac, and Linux.
© 2020 Scott Hanselman. All rights reserved.
Exploring the .NET open source hybrid ORM library RepoDB published first on https://deskbysnafu.tumblr.com/
0 notes
Text
Exploring the .NET open source hybrid ORM library RepoDB
It's nice to explore alternatives, especially in open source software. Just because there's a way, or an "official" way doesn't mean it's the best way.
Today I'm looking at RepoDb. It says it's "a hybrid ORM library for .NET. It is your best alternative ORM to both Dapper and Entity Framework." Cool, let's take a look.
Michael Pendon, the author puts his micro-ORM in the same category as Dapper and EF. He says "RepoDb is a new hybrid micro-ORM for .NET designed to cater the missing pieces of both micro-ORMs and macro-ORMs (aka full-ORMs). Both are fast, efficient and easy-to-use. They are also addressing different use-cases."
Dapper is a great and venerable library that is great if you love SQL. Repo is a hybrid ORM and offers more than one way to query, and support a bunch of popular databases:
SqlServer
SqLite
MySql
PostgreSql
Here's some example code:
/* Dapper */ using (var connection = new SqlConnection(ConnectionString)) { var customers = connection.Query<Customer>("SELECT Id, Name, DateOfBirth, CreatedDateUtc FROM [dbo].[Customer];"); } /* RepoDb - Raw */ using (var connection = new SqlConnection(ConnectionString)) { var customers = connection.ExecuteQuery<Customer>("SELECT Id, Name, DateOfBirth, CreatedDateUtc FROM [dbo].[Customer];"); } /* RepoDb - Fluent */ using (var connection = new SqlConnection(ConnectionString)) { var customers = connection.QueryAll<Customer>(); }
I like RepoDB's strongly typed Fluent insertion syntax:
/* RepoDb - Fluent */ using (var connection = new SqlConnection(connectionString)) { var id = connection.Insert<Customer, int>(new Customer { Name = "John Doe", DateOfBirth = DateTime.Parse("1970/01/01"), CreatedDateUtc = DateTime.UtcNow }); }
Speaking of inserts, it's BulkInsert (my least favorite thing to do) is super clean:
using (var connection = new SqlConnection(ConnectionString)) { var customers = GenerateCustomers(1000); var insertedRows = connection.BulkInsert(customers); }
The most interesting part of RepoDB is that it formally acknowledges 2nd layer caches and has a whole section on caching in the excellent RepoDB official documentation. I have a whole LazyCache subsystem behind my podcast site that is super fast but added some complexity to the code with more Func<T> that I would have preferred.
This is super clean, just passing in an ICache when you start the connection and then mention the key when querying.
var cache = CacheFactory.GetMemoryCache(); using (var connection = new SqlConnection(connectionString).EnsureOpen()) { var products = connection.QueryAll<Product>(cacheKey: "products", cache: cache); } using (var repository = new DbRepository<Product, SqlConnection>(connectionString)) { var products = repository.QueryAll(cacheKey: "products"); }
It also shows how to do generated cache keys...also clean:
// An example of the second cache key convention: var cache = CacheFactory.GetMemoryCache(); using (var connection = new SqlConnection(connectionString).EnsureOpen()) { var productId = 5; Query<Product>(product => product.Id == productId, cacheKey: $"product-id-{productId}", cache: cache); }
And of course, if you like to drop into SQL directly for whatever reason, you can .ExecuteQuery() and call sprocs or use inline SQL as you like. So far I'm enjoying RepoDB very much. It's thoughtfully designed and well documented and fast. Give it a try and see if you like it to?
Why don't you head over to https://github.com/mikependon/RepoDb now and GIVE THEM A STAR. Encourage open source. Try it on your own project and go tweet the author and share your thoughts!
Sponsor: Have you tried developing in Rider yet? This fast and feature-rich cross-platform IDE improves your code for .NET, ASP.NET, .NET Core, Xamarin, and Unity applications on Windows, Mac, and Linux.
© 2020 Scott Hanselman. All rights reserved.
Exploring the .NET open source hybrid ORM library RepoDB published first on http://7elementswd.tumblr.com/
0 notes
Text
How to Perform Edit Operation In Asp.Net MVC
New Post has been published on https://is.gd/3ly1Dm
How to Perform Edit Operation In Asp.Net MVC

In this article we will understand How to Perform Edit Operation in Asp.Net MVC By Sagar Jaybhay.
How to Perform Edit Operation In Asp.Net MVC
Created Edit method in EmployeeController which is shown below and strongly typed EditView for this.
[HttpGet] public ActionResult Edit(string EmpID) var Employye = new BusinessLogic.Business().GetEmployee(EmpID); return View(Employye);
Edit Model In Asp.net MVC
Now after creating a view and click on edit link you will find below the window
Edit Employee In Asp.Net MVC
But if you see above image gender will display in textbox but we want dropdown list so we need to modify this as per our requirement. We modify our view, but in this, you should rename DropDownList Name to EmpGender as our model property is EmpGender so it will bind value directly.
@model WebApplication1.Models.Employee @ ViewBag.Title = "Edit"; <h2>Edit</h2> @using (Html.BeginForm()) @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Employee</h4> <hr /> @Html.ValidationSummary(true, "", new @class = "text-danger" ) <div class="form-group"> @Html.LabelFor(model => model.EmpID, htmlAttributes: new @class = "control-label col-md-2" ) <div class="col-md-10"> @Html.EditorFor(model => model.EmpID, new htmlAttributes = new @class = "form-control" ) @Html.ValidationMessageFor(model => model.EmpID, "", new @class = "text-danger" ) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.EmpName, htmlAttributes: new @class = "control-label col-md-2" ) <div class="col-md-10"> @Html.EditorFor(model => model.EmpName, new htmlAttributes = new @class = "form-control" ) @Html.ValidationMessageFor(model => model.EmpName, "", new @class = "text-danger" ) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.EmpSalary, htmlAttributes: new @class = "control-label col-md-2" ) <div class="col-md-10"> @Html.EditorFor(model => model.EmpSalary, new htmlAttributes = new @class = "form-control" ) @Html.ValidationMessageFor(model => model.EmpSalary, "", new @class = "text-danger" ) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.EmpGender, htmlAttributes: new @class = "control-label col-md-2" ) <div class="col-md-10"> @Html.DropDownList("EmpGender", new List<SelectListItem> new SelectListItem Text="Male" ,Value="Male", new SelectListItem Text="Female" ,Value="female", "Select Gender") @Html.ValidationMessageFor(model => model.EmpGender, "", new @class = "text-danger" ) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.EmpCity, htmlAttributes: new @class = "control-label col-md-2" ) <div class="col-md-10"> @Html.EditorFor(model => model.EmpCity, new htmlAttributes = new @class = "form-control" ) @Html.ValidationMessageFor(model => model.EmpCity, "", new @class = "text-danger" ) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.EmpEmail, htmlAttributes: new @class = "control-label col-md-2" ) <div class="col-md-10"> @Html.EditorFor(model => model.EmpEmail, new htmlAttributes = new @class = "form-control" ) @Html.ValidationMessageFor(model => model.EmpEmail, "", new @class = "text-danger" ) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.DepartmentID, htmlAttributes: new @class = "control-label col-md-2" ) <div class="col-md-10"> @Html.EditorFor(model => model.DepartmentID, new htmlAttributes = new @class = "form-control" ) @Html.ValidationMessageFor(model => model.DepartmentID, "", new @class = "text-danger" ) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Save" class="btn btn-default" /> </div> </div> </div> <div> @Html.ActionLink("Back to List", "Index") </div>
Gender Edit Model
But when we click on the save button it will throw an error resource that can not found. Why because EmployeeController class does not have Edit Method which responds to Post a request for Edit. Below is an error is thrown when we click on the Save button.
Server Error in ‘/’ Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. Requested URL: /Employee/Edit
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.8.4075.0
Error in Asp.Net MVC
To Update Employee, we create one stored procedure in our database which is below,
Create Procedure [dbo].[spUpdateEmployee] @emptid int, @name nvarchar(20), @salary float, @gender nvarchar(20), @city nvarchar(20), @email nvarchar(30), @deptid int as begin Update Employee set EmpEmail=@email,EmpName=@name,EmpSalary=@salary,EmpGender=@gender, DepartmentID=@deptid where EmpID=@emptid; End Now we need to call this Procedure in our database class the method is below public void UpdateEmployee(int EmpId, string Name, string Email, string Gender, double salary, int deptid, string city) using (var con = new SqlConnection(this._ConnectionString)) con.Open(); var cmd = new SqlCommand("spUpdateEmployee", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("name", SqlDbType.NVarChar, 20)); cmd.Parameters.Add(new SqlParameter("salary", SqlDbType.Float, 50)); cmd.Parameters.Add(new SqlParameter("gender", SqlDbType.NVarChar, 50)); cmd.Parameters.Add(new SqlParameter("city", SqlDbType.NVarChar, 50)); cmd.Parameters.Add(new SqlParameter("email", SqlDbType.NVarChar, 50)); cmd.Parameters.Add(new SqlParameter("deptid", SqlDbType.Int, 50)); cmd.Parameters.Add(new SqlParameter("emptid", SqlDbType.Int, 50)); cmd.Parameters["name"].Value = Name; cmd.Parameters["salary"].Value = salary; cmd.Parameters["gender"].Value = Gender; cmd.Parameters["city"].Value = city; cmd.Parameters["email"].Value = Email; cmd.Parameters["deptid"].Value = deptid; cmd.Parameters["emptid"].Value = EmpId; cmd.ExecuteNonQuery();
After this, we create a method in business class, which is shown below
public void UpdateEmployee(Employee employee) this.dataAccess.UpdateEmployee(employee.EmpID,employee.EmpName, employee.EmpEmail, employee.EmpGender, employee.EmpSalary, employee.DepartmentID, employee.EmpCity);
Now we create a method in our EmployeeController for handling post request of Edit method which is shown in below
[HttpPost] public ActionResult Edit(Employee employee) if (ModelState.IsValid) new BusinessLogic.Business().UpdateEmployee(employee); return RedirectToAction("DisplayCompleteEmployee"); return View(employee);
First, we see all Employee from our list and click on Edit link for this display all Employee UI looks like below
Edit Link Click In Asp.Net MVC
After clicking on edit we edit details Ui looks like below
Edit In Asp.net MVC
After clicking on Save we return to DisplayEmployee List and our updated values reflected on UI as expected.
Completed Edit in Asp.Net MVC
Now our edit functionality is completed.
GitHub Pages :- https://github.com/Sagar-Jaybhay/AspNetRazor
0 notes
Text
How to add a dropdownlist that’s dynamically populated from database to each row in datatable gridview
So I’ve created a fully functional gridview that has the two last columns as dropdownlists that are populated from the database and they read/write from it. But I needed to implement search unto the gridview so I used the Datatables.net plugin, It works perfectly but as soon as I add the drop down lists, the search is disabled. Unless I add them through javascript and I’m not nearly experienced enough in that field to accomplish that on my own.
Before I switched to the datatable plug in, I used to just append the dropdownlists I needed at the Rowdatabound event of the gridview, How can I achieve something similar through javascript ?
This is the java script code :
var TableContent = "<tr>"; if (!$("#req").length) $("body").append("<table id='req'></table>"); else $('#req').prepend($('<thead>').append($('.add_ADU'))); var colns = [ { "data": "Request_ID", title: "ID", }, { "data": "Student_ID", visible:true }, { "data": "Type", visible:true }, { "data": "Description", visible:true }, { "data": "Language", visible:true }, { "data": "PUC", visible:true }, { "data": "Quantity", title: "Quantity" }, { "data": "Comments", title: "Comments" }, { "data": "Fees", title: "Fees" }, { "data": "Date", title: "Date" }, { "data": "Payment_Status", title: "Payment Status" }, { "data": "Payment_Date", title: "Payment Date" }, { "data": "Student_Name", title: "Student Name", visible:true }, { "data": "Payment_ID",title:"Payment ID", title: "Phone" }, { "data": "Addressed_To",title: "Addressed To", visible:true }, { "data": "username", title:"Assigned To",visible:true }, { "data": "status", title:"Status",visible:true } ]; var table = $('#req').DataTable({ select: true, "columns": colns, "order": [[ 12, "desc" ]], "initComplete": function (settings, json) { reset_table_page_length($(window).height()); }, }); $("#req tr").append( '<select id="assign"' + '<option value="Paid">him</option>' + '<option value="NotPaid">her</option>' + '</select>' ) $("#req_filter").prepend( '<select id="inp-sel-status-fltr" class="table-toolbar-inp">' + '<option value="Paid">Paid</option>' + '<option value="NotPaid">Not Paid</option>'+ '</select>' ) $("#inp-sel-status-fltr").change(function myfunction() { filter_table_by_status($(this).val()); }); function filter_table_by_status(val) { table.column(10).search(val); table.draw(); }
As pathetic as it is, this is how far I’ve gotten to achieving what I’m trying to :
$("#req tr").append( '<select id="assign"' + '<option value="Paid">him</option>' + '<option value="NotPaid">her</option>' + '</select>')
This is the HTML code for the gridview :
<div class="container"> <asp:GridView BorderWidth="0" CssClass="stripe compact order-column row-border" runat="server" AutoGenerateColumns="true" ID="req" OnRowDataBound="req_RowDataBound" ClientIDMode="Static" Style="width: 100% !important"> <HeaderStyle CssClass="add_ADU" /> </asp:GridView>
and in the code behind I would just append the dropdownlists and then query the data I needed and populate them with it using this code:
protected void req_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { DataTable table = new DataTable(); var openCloseddl = e.Row.FindControl("openCloseddl") as DropDownList; var assignddl = e.Row.FindControl("assignToddl") as DropDownList; assignddl.DataMember = "username"; assignddl.DataValueField = "username"; assignddl.DataSource = table; //get the values of the conditions that define which staff var request_id = e.Row.Cells[0].Text; var type = e.Row.Cells[3].Text; var description = e.Row.Cells[4].Text; var puc = e.Row.Cells[6].Text; var quantity = e.Row.Cells[7].Text; //fetch which staff member it's assigned to if exists. SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["studentOrderUpload"].ConnectionString); SqlCommand comm = new SqlCommand("SELECT username from request_status WHERE request_id = @request_id and type = @type and description = @description and puc = @puc and quantity = @quantity", conn); comm.Parameters.AddWithValue("@request_id", request_id); comm.Parameters.AddWithValue("@type", type); comm.Parameters.AddWithValue("@description", description); comm.Parameters.AddWithValue("@puc", puc); comm.Parameters.AddWithValue("@quantity", quantity); try { conn.Open(); object result = comm.ExecuteScalar(); string resultText = (result == null ? "" : result.ToString()); conn.Close(); //if it's not assigned to anyone, show every staff member. if (resultText == "") { if (type.ToLower().Contains("customized")) { SqlCommand cmd1 = new SqlCommand("select username from staff where type = 'customized'", conn); conn.Open(); SqlDataAdapter ad1 = new SqlDataAdapter(cmd1); ad1.Fill(table); conn.Close(); assignddl.DataBind(); assignddl.SelectedValue = "Scholarship"; if (openCloseddl.SelectedValue == "Open") { openCloseddl.Enabled = true; } assignddl.Items.RemoveAt(1); } else { SqlCommand cmd1 = new SqlCommand("select username from staff where type ='standard'", conn); conn.Open(); SqlDataAdapter ad1 = new SqlDataAdapter(cmd1); ad1.Fill(table); conn.Close(); assignddl.DataBind(); } assignddl.Items.Insert(0, new ListItem("Select User")); openCloseddl.Enabled = false; if (openCloseddl.SelectedValue == "Open" && type.ToLower().Contains("customized")) { openCloseddl.Enabled = true; } } //if it's assigned to someone, show only the assigned staff, else { if (type.ToLower().Contains("customized")) { SqlCommand cmd1 = new SqlCommand("select username from staff where type = 'customized'", conn); conn.Open(); SqlDataAdapter ad1 = new SqlDataAdapter(cmd1); ad1.Fill(table); conn.Close(); assignddl.DataBind(); assignddl.SelectedValue = "Scholarship"; if (openCloseddl.SelectedValue == "Open") { openCloseddl.Enabled = true; } assignddl.Items.RemoveAt(1); } else { SqlCommand cmd1 = new SqlCommand("select username from staff where type = 'standard'", conn); conn.Open(); SqlDataAdapter ad1 = new SqlDataAdapter(cmd1); ad1.Fill(table); conn.Close(); assignddl.DataBind(); assignddl.SelectedValue = resultText; } } if (openCloseddl != null) { SqlCommand comm1 = new SqlCommand("SELECT status from request_status WHERE request_id = @request_id and type = @type and description = @description and puc = @puc and quantity = @quantity", conn); comm1.Parameters.AddWithValue("@request_id", request_id); comm1.Parameters.AddWithValue("@type", type); comm1.Parameters.AddWithValue("@description", description); comm1.Parameters.AddWithValue("@puc", puc); comm1.Parameters.AddWithValue("@quantity", quantity); conn.Open(); object result1 = comm1.ExecuteScalar(); conn.Close(); if (result1.ToString() == "Closed") { openCloseddl.SelectedValue = "Closed"; openCloseddl.Enabled = false; assignddl.Enabled = false; if ((HttpContext.Current.User.Identity.Name.Equals("DocRequestAdmin"))) { assignddl.Enabled = true; openCloseddl.Enabled = true; } } } } catch (Exception ee) { var error = ee.Message; conn.Close(); } var paid = e.Row.Cells[12].Text; if (paid.Contains("Not")) { assignddl.SelectedValue = "Select User"; assignddl.Enabled = false; openCloseddl.Enabled = false; } } }
Which is irrelevant at this point I believe, since I’m trying to do this through javascript.
This is a screenshot of what the grid looks like, the dropdown lists I want to add should exist in the last two columns “Assigned To” and “Status”
1 Answer
There is a built in render function in data tables which you can call in your columns objects. The function accepts 3 arguments, the first one is the value of the property which you specified in your “data” property, and the third will return the value of the whole underlying object.
You can read about it here.
For example:
{ "data": "username", title:"Assigned To", visible:true, render: function(data, type, row) { //do sth here } }
In the above render function, the data parameter will return the value of the “username” property, and the row parameter will return the value of all properties of the underlying object.
You can use the data provided by the row parameter to append a value and an id to your dropdown list. If your row parameter returns an array of objects, you can do a for loop to iterate and append every value to the select element.
Archive from: https://stackoverflow.com/questions/59015626/how-to-add-a-dropdownlist-thats-dynamically-populated-from-database-to-each-row
from https://knowledgewiki.org/how-to-add-a-dropdownlist-thats-dynamically-populated-from-database-to-each-row-in-datatable-gridview/
0 notes
Text
ASP.NET - Generate Excel files programmatically with EPPlus

If you've stumbled upon this post it most likely means that you're looking for a way to generate MS Excel XLS / XLSX files within your ASP.NET web application. The typical scenario for such needis the following one: you have a DBMS from where you pull off some data - using a OleDBConnection, a SqlConnection, an EntityFramework model or anything database-fetching technique - which you want to send to your users through a downloadable MS Excel file. In purely theoretical terms, you might think about doing this using the MS Office Interop libraries, using a technique similar to what we explained in a couple other articles: Programmatically convert MS Word DOC and DOCX files to PDF using Office Interop Programmatically Access, Read and Edit MS Word DOC and DOCX files using Office Interop However, if you are here (or if you already read those posts) you most likely already know that the Microsoft Office primary interop assemblies (PIAs), better known as Office Interop, are not something you should rely upon: although there is an ASP.NET library package specifically designed to handle MS Excel files, the whole Office.Interop set of libraries is not meant to be used in web applications and will definitely cause you some nasty setup and configuration issues, such as those we enumerated (and tried to deal with) there. Luckily enough, there's a good news for you: a NuGet library package that does basically the same tasks you might want to use the Microsoft.Office.Interop.Excel namespace for, while working way better than that in a typical web application scenario: and it's also completely free to use! We're talking of EPPlus, a great library developed by Jan Kallman and available either on GitHub and as a compiled, full-flegded NuGet package. The project is licensed under the GNU Library General Public License (LGPL), meaning that it can be used everywhere. In this post we'll briefly show how we can install this great tool on a typical Visual Studio environment and then use it to generate a MS Excel file from a standard ASP.NET DataTable which we (ideally) pulled off by a DBMS of some sort.
Installing EPPlus
The most practical way to install EPPlus from Visual Studio is to open the NuGet Package Manager Console (View > Other Windows > Package Manager Console) and type the following command: If you prefer to install it through the .NET CLI, you can use this command from an elevated command prompt or powershell prompt: Version notes It's worth noting that this test-drive was performed using EPPlus version 4.5.3.1, which was the latest available version at the time of writing: such version is fully compatible with all the most recent versionf of the .NET Framework, from 3.5 to 4.7.x (we tested it with 4.7.2).
EPPlus usage example
Without further ado, here's a full source code sample that will convert a standard DataTable to a XLSX Excel file and then send it to the user for the download: As we can see, this is an ActionResult method that could fit on any ASP.NET MVC Controller: if you're not using ASP.NET MVC you can still use it, just copy the method content wherever you need to (classic ASP.NET, Console Application, Windows Forms, and so on). The code is quite self-explanatory and full of comments that should hopefully explain the various processing steps. However, let's briefly summarize what are we doing here: We fetch a DataTable object using a custom Data Provider method. We create a ExcelPackage object, which is the main container used by EPPlus for the XLSX file. We add a ExcelWorksheet inside the ExcelPackage, which is the worksheet we'll put the data in. We iterate the DataTable columns, adding them to the first row of our worksheet to build our header row. We iterate the DataTable rows, adding each one of them to our worksheet (starting from row 2), so that each DataTable row will result in a corresponding worksheet row. Once the conversion between the DataTable and the ExcelPackage is done, we create a MemoryStream to store the ExcelPackage binary data, then convert it to a byte array. We prepare the HTML response and send the XLSX file to the user with Content-Disposition attachment, so that the browser will force the download of the file. It's worth noting that we used a one-liner function to retrieve the proper mime-type for XLSX files (which is "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"): such function is available only since .NET Framework 4.5 and it's the preferred method to retrieve mime-types since then. If you need to retrieve the mime-type with older .NET Frameworks, you can use one of the various workaround described in this other post.
Conclusion
That's basically it, at least for now: I will definitely write again about the topic in the near future and share additional code samples. Meanwhile, feel free to use or modify the above code to your specific needs and enjoy the DataTable-to-XSLX conversion thanks to EPPlus! Read the full article
0 notes
Text
Connect to MSSQL with java/android
Hi guys!
I’ll share how to connect to MSSQL with java eh
STEP 1 : Get the ConnectionClass.java
https://gist.github.com/n0ran1/6cf55170502036a127058996eeb95601
Lemme explain bit
private static String myweburl = "www.example.com"; // your domain / put public ip address public static final String ip = myweburl + ":3031"; // 3031 is port number for mssql server instance that you set in sql server configuration static final String classs = "net.sourceforge.jtds.jdbc.Driver"; static final String db = "MDMV1"; //database name static final String un = "sa"; //username to login database String password = "12345"; //password to login database
ASUS_X450L:3031 //ASUS_X450L is your pc name / you can put the pc local ip address
1599 is port number you set in IIS. (Ignore if you won’t check your domain connection) Open IIS, Default Web Site > Bindings
STEP 2 : Add jtds jar
https://github.com/n0ran1/SQLConnection/blob/master/jtds-1.2.7.jar
Put into libs folder
STEP 3 : Allow port in Port Forwarding
Setup :
Open cmd.exe, type ipconfig and press enter.
Find ipV4 address, it is your local ip.
Type your local ip in browser and go.
It will open the router page. Login and set the port forwarding , allow 3031(port number you set in step 1)
Important :
Make sure your pc connect to wifi which your router has broadcasted
If your local ip changed, please update it in port forwarding.
STEP 4 : Consume it
ConnectionClass connectionClass = new ConnectionClass(this); Connection con = connectionClass.CONN();
STEP 5 : DONE. Do the sql command
Select, Update, Delete, Insert
0 notes
Text
your ASP.NET Web pages
your ASP.NET Web pages
For this project, you will be continuing to enhance your course project. From previous work, you should now have an application that is connected to a database for display and updating of your data. The application uses an sqlConnection object and data-bound controls for the data connection, but this represents some problems for future development, and this is a good time to examine the…
View On WordPress
0 notes
Text
BEL
namespace BusinessEntitierLayer { public class ResultOutPut { public string Result { get; set; } public string Output_msg { get; set; } public string Status { get; set; } }
DBFiles
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString; DataTable dt = new DataTable();
//Add Department public DataTable AddDepartment(string DepartmentName) { SqlConnection conn = new SqlConnection(constr); SqlCommand cmd = new SqlCommand("sp_DepartmentAdd", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DepartmentName", DepartmentName); try { conn.Open(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(dt); return dt; } catch (Exception) {
throw; } finally { conn.Close(); } }
Service
[WebMethod] public ResultOutPut[] ClientEDDV(string Action, int CID, int UID) { DBFile obj = new DBFile(); DataTable dt = obj.ClientEDDV(Action, CID, UID); List<ResultOutPut> ResultList = new List<ResultOutPut>(); try { foreach (DataRow item in dt.Rows) { ResultOutPut ClientEDDVList = new ResultOutPut(); ClientEDDVList.Result = item["Result"].ToString(); ClientEDDVList.Output_msg = item["Output_msg"].ToString(); ClientEDDVList.Status = item["Status"].ToString(); ResultList.Add(ClientEDDVList); } } catch (Exception) {
throw; } return ResultList.ToArray(); }
Jquery
function AddDepartmentFunc() {
var Department = $("#txtAddDepartment").val();
if (Department != "") { //swal("Good job!", "You clicked the button!", "success"); $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "../../services/DepartmentWebService.asmx/AddDepartment", data: "{'DepartmentName':'" + Department + "'}", dataType: "json", success: function (data) { var obj = data.d; for (var i = 0; i < obj.length; i++) { var MsgResult = obj[i].Result; var OutPutMsg = obj[i].Output_msg; var MsgStatus = obj[i].Status; swal("", OutPutMsg, MsgStatus).then(function () { location.reload(); }); //swal("", OutPutMsg, MsgStatus); } }, error: function (result) { alert("Error Occured"); } }); } else { $("#txtAddDepartment").addClass("is-invalid"); } }
1 note
·
View note