You are on page 1of 11
Eee eke ges na eee ees 00 CODE » . PROJECT BREE 28 torus stutt tounge 7 Ke Linking ASPNET MVC with DB2 Table a Vitilevu, 9 Jul 2014 AAAI 5.0068 votes) Rate this: able How to link ASP.NET MVC wit Download asp.net. to, as400.tip - 211.2 KB Overview In this article, | will explain a simple example of linking a DB2 table (AS400) to an ADO.NET DataSet using ASP.NET MVC 4 in Visual Studio 2012. twill also feature Mvescaffolding to cater for CRUD operations, Objective By the end of this topic, | wll create an ASP.NET MVC 4 web application that allows the user to add, update and delete records from 4 DB2 table using customisable CRUD methods provided. The application will also create an audit trail of who updated the table and when, In AS400 ‘This example used is a product master file located in the AS400 database called Product. Here we have a physical file by the name of Product located in the library named RAYALS, CaaS Te Ivis set up as follows according to the Data Description Specification (ODS) of a physical file in iSeries, where NAME is the name of the product (character of size 30), DESCRP (size 100) is the description, followed by PRICE (size 15) and QTY (quantity of size 10). In Visual Studio 2012 We create @ new project. selecting ASP.NET MVC 4 Web application in Visual Studio 2012. seit Bi] ssracrempn weed Vinnice pe §& [RSDNIET Dymamic Dats Entities Web Application Vieustco G Following that, we name it as SampleProductInterface in the location specified. Name (SompleProductinteface Locaton: Os\ey\Web Apps\Main\Source\ Solution names SompleProdustinteface Then, we will select the ‘Internet Application’ as the template and accept the remaining default settings ROUSENETNNETPea ttf (ae oi Mibik WeDAR Sal = 3 un Sao Uk Tee = aac Se Geax ‘This will take a while when the solution is created for the first time, When itis ready, you should see the following folders ang files created in the Solution explorer. Search Solution Explorer Chl) a +67 Solution ‘SampleProductiterface' @ projects 4-55 SampleProductintertace > + Properties > ew References bl App_02t fad App cart Iii Content fad Contolters ad Fiter ad Images fad Models Scripts ia Viewer +B favicenico > +4) Globalasex + packages.cenfio » +B Webconfig 1D SwnpleProducnkertce Te > + Properties > ea References > fal Contes SBD iw nls Similar to previous MVC versions, MVC 4 has the usual Controllers, Models and Views folders as shown above. We can modify the layout ofthe initial page when the application starts We will select the _Layoutcshtml razor file located as follows. 4 fal Views Did Account > ml Home 4 ial Shared “F&1l aninDartinl.echtenl From there, we can change the page ttle and action lnk ttle (highlighted) to whatever we want. Hide Copy Cod

@ltml ActionLink("Product Master Update", "Index", "Home")

Creating the Dataset to Contain the AS400 table We then create a DataSet in the Models folder. Right click the folder ‘Models’ and add item, select Data and choose DataSet. a viatce ao 4G sconereiyows nots Viale oa a aa = 4B. tesa 01conoe Gear oath hae tas rodvmotseoa Wie Predicted Inthe Server Explorer toolbox, we connect as follows: x0gj00L 4, Gi Dits Connections select the “# icon and the following window wll appear. The name ofthe server wl appear inthe blue rectangle shown below Enter information to conmectto the elected dat source or lek “Change” to choose asiferent dos source and/or provider Osta sauce NET Frama Oats Brovider for OLE DE 2 ‘OLE DB Provider (leba2terisiosteMoAa OLE DB Provider =) Datatinks, Enter server oe file narne Serverorfilenamne: PEPKORAL {og onto the server Use Windows NTIntegrated Seu © sea specific user mare and passwerd: E-Binkpsewerd ElAliw suing psiword Advanced = Gea a ‘As shown above, the main thing is to get the correct Data source followed by the OLEDS provider. The other field to complete is the ‘Server or File name’ Don't forget to click on the Test Connection’ button to confirm that the remote server is connectable. Following that, you can click “Ok’. The following connection will be shown below, under the Data Connections section as TBMDA4@@ . BARBUDA, Sever plore - ox os Heo & 4 Data Connections By clicking on the Tables folder, you will see the following lst of tables existing in that particular library (eg, RAYALS), We will be focusing on the product table. We click on the PRODUCT table on the left pane (server explorer) and drag it to the ProductDataSet.xsd file on the right. This will create an instance of the table in the xsd. aes 5Q. Fill,GetData 0 Model Setup In the Models folder, we then create a class of ProductsMaster that is responsible for entering data from the web UI to the 'AS400 table Product. Every time a new product is added to the AS400 table, we have an audit trail of who did it and when, Hide Copy Code CRUD Creation with Mvcscaffolding We go to the package manager console and call the command Mvcscaf folding to create the relevant CRUD features for the ProductMaster class. First, we install mvcscaffolding by typing install-package mvcscaf folding on the PM> prompt as shown below: ackage micscaffolding Once everything is installed for mvcscaf folding, the prompt will appear again as below with the trail of messages above it Successfully installed ‘Tascatfoléing.Core 1.0.0". Installing 'T4scaffolding 1.0.8". Successfully installed 'TaScaffolding 1.0.8". ‘Installing 'MvcScaffolding 1.@.9". Successfully installed ‘MvcScaffolding 1.0.9". Adding ‘TaScaffolding Core 1.0.0" to SampleProduct Interface. Successfully acded ‘T4Scaffolding.Core 1.0.0° to SampleProductInterface. Adding ‘T4Scaffolding 1.0.2" to SampleProductInterFace. Successfully added ‘T4Scaffolding 1.0.8" to SampleProductinterface. Adding ‘MveScaffelding 1.0.9" to SenplefroductInterfece. Successfully acded ‘MvcScaffolding 1.0.9" to SampleProductinterface. PHD all the following command in the Package Console Manager prompt to create the necessary CRUD views for the ProductMaster classin the Views/ProductMasters folder. Scaffold Controller ProductMaster -Repository -Force. der and Class Creating DAL Fo! Create a DAL folder in the project as follows. This is where classes to access and modify the AS400 tables will be written 4% ProductMastersControllercs b_ #3 ProductMastersController ial bia Filters > iad Images 4 tel Models > #c* AccourtModeln.cs 4 sgl ProduciDataSetxed b-©3A ProductDataSecDesianenes “Then, create a class in DAL folder called UnitO/Workcs or whatever you may prefer. using SampleProductinterface.Models; using Sample?roductInterface.Models.ProductDataSetTableadapters; using Systens using Systen.collections.Generic; using Systen.bata.O1eDb; using System.Lings using System.Web public class UnitofWork « public string HostName, Library, UserName, Password, DBConnectionstrings public static string GetConnectionstring (string host, string Library, string username, string password) t ‘string _sqlConnectionString = string.Format (C’Provider=18H0A400.DataSource.1;ata Source={@};Persist Security Info=True; Password={3};User ID={2);Catalog Library List=(1)", host, library, username, password); return _sqlConnectionString; y public UnitofWork(string environment) { HostNane = "BARBUDA"; UserNane = "MICKY"s Password = "MOUSE"; Library = "RAYALS"; DBConnectionString = GetConnectionstring(HostNane, Library, UserName, Password); y public void WeiteToproduct(ProductMaster prd) { using (var ta = new PRODUCTTableAdapter()) ta.Connection = new OLedbConnection(DaConnectionstring) ; using (var ds = new ProductDataset()) { var productRow = ds.PRODUCT.NewPRODUCTRON() 5 productRow.NAME = prd.ProductNane roductRow.DESCRP = prd.Description; productRow.PRICE = prd.Price; productRow.QTY = prd. Quantity; dds . PRODUCT .AddPRODUCTRow( product Row); try { //insert into as4ee table ‘ta.Update(ds.PRODUCT) ; catch (Exception ex) { ‘throw new ApplicationException("Failed to insert Row into PRODUCT File", ex); y In the above code, the WriteToProduct() methad is the main process used to write to the AS400 file. The constructor sets the login credentials for the AS4OO server, with Host, Library, Username and Password, The WriteToProduct() method will ‘then connect to the AS400 using the connection string derived from the credentials initiated in the constructor and write to the dataset (ProductDataSet) from the product master fle (ProductMas ter). The table adapter (PRODUCTTableAdapter) will then execute an insert statement to get the dataset values and write to the PRODUCT table in AS400. Modifying Controller Methoc Inthe controller, the Create method should look like this: [nttpPost] public ActionResult Create(ProductMaster productnaster) t UnitOFWork Uow = new Uni tOFWOrk(); Sf (Modelstete. IsValid) { //call uow to insert into AS408 vow hniteToProduct (productnaster); productnaster.Usernane = Environnent.UserNane; productnaster Datetntered = DateTine. Now; productnasterfepository..InsertOrUpdate(productnaster); productnasterRepository.Save() return RedirectTokction( "Index" ); p else { return View(); > y Inthe above code, we are caling the UnitOfWork method WriteToProduct() which will write to the AS400 table. Then prior to updating the SQL server table ProductMaster, we ensure that the Username and DateEntered fields are populated by assigning the current Windows username and current time (DateT ime. NOW) to ther respective values. So in this instance, we willbe populating 2 tables, one in the AS400 via the method Wr'iteToProduct() and the other using the controller Editt_ method productmasterRepository.InsertOrUpdate (productmaster) and productmasterRepository.Save() Nodifying the cshtml View In the_Layoutcshtmt file (located in Views/Shared), we will also add an extralline to enable access to the Indexshtm page for updating the ProductMaster table, The extra line (third line) shown below is where the ActionLink for ProductMasters will pint to the Indexcshim! page when the tab labelled ‘Products Update’ is selected
    <> ‘Then in the _CreateOrEditeshtm! ile (located in Views/ProductMasters), delete the following rows:
    @ltm1.LabelFor(model => nodel.Usernane)
    ‘The program will automatically populate these fields in the ProgramMaster (SQL server table) at the point of creation, so we won't need to touch them at all Running the Application Press F5 to run the web application, You will see the following screen: oe Home Producstpdate. About Contact Home Page. Modify this template to jump:star your ASH NeT MVC application, Click on the Products Update link to get to the following page: act ter Updat oduct Master Update iam Wee, a Index ‘Create New ProductNameDescription Price Quantity UsernameDateEntered 1 sane Rec Pere epson ‘The above field name display can be formatted to a more readable presentation, but for naw our focus is on demonstrating how this application will update the AS400 table At this moment, a database instance of ProductMaster would have been created ‘on the App. Data folder ofthe project. Click on the ‘Create New’ link and the following page will show. The filed values were typed in. Create ProduaName Pringle Ong Description Pringles Original Favor 2 ‘quanty 3 x {eran} Backait From there, lick on the ‘Create’ button and the method 'WriteToProduct (will be invoked to write to the AS400 table PRODUCT. Looking at the query on the PRODUCT table, the row has indeed been added as shown below: [rae ic [owce [ow T Page Peg ana = ‘The next time we visit the index cshtml page, we will see a record detailing our entry into the AS400 table with the user profile and timestamp, This ends our simple demonstration of populating an AS400 table via an ASP.NET MVC 4 web application. Points of Interest ‘There is nothing particularly complex in deriving the above solution. The main thing is to get the correct DB2 (AS400) credential settings and things will be straight forward from there. License ‘This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Share yw B tcmor oO About the Author levu Software Developer Australia No Biography provided You may also be interested in... Multiple Models in a View in ASP.NET MVC 4 / ‘A More Powerful BinaryReader/Writer Myc 5 ASP.NET MVC interview questions with answers AJAX based CRUD tables using ASP.NET MVC 3 and jTable jQuery plug. Tetris on Canvas CRUD operation on multiple tables with AngularJS and ASP.NET MVC Part-2 Comments and Discussions ‘You must Sign In to use this message board. 2 Prev Next incompleto Member 12194318 14-Oct-18 9:52 El autor de este disque tutorial lo hizo a medias. algo a media es mediocre, veo que le hacen preguntas y no responde, Si publican algo que sea completo Sign In: View Thread & Unable to view table from the server explorer of Visual Studi: Member 10723035 16-Nov-14 16:34 Hi |ollowed the steps but after successfully connecting via server explorer the tables is blank Its still unable to find *PRODUCTTableAdapter()", PRODUCT” and "ProductDataSetTableAdapters;" sing Productinterface Models ProductOataSetTableAdapters; PRODUCTTableAdapter() By clicking on the Tables folder, My lst of tables is blank in that particular library (eg. ARVI1). We will be focusing on the product table, Under "Data Connections IBMDA400.XXX.YY is mentioned and not my library (Y¥=default entry) [Also when Add Connection the "OLE DB Provider" doesn't have IBM DB2 for iS/os ibmdad00 ole db provider instead | have "IBM DB2 for i IBMDA400 OLE DB provider ~ Please suggest. Thanks Arvin Sign In-View Thread & Could you make project code available for download? Member 11001286 8-Aug-14 11:49 U have different default data sources in my 2012 studio (no provider for db2). Do you have to install addition driver from third party for the db2 provider you use? | installed ibm data server driver 9.7 version with studio plug-in. But unfortunately, the plug-in does not register with studio 2012 since there is no data source from IBM show up on data source list, So | could not add server connection to db? in 2012 studio at all. But with 2010 studio, iam data source showed properly. But | could not build mveé project in studio 2010. | would like to download your sample code, to see if could get around problem and still build my myc4 project in studio 2012 without having db2 server connection on server explorer. Thanks! Juny Fan Sign n-View Thread & Refresh 1 (Jceneral [E] News @ Suggestion @ Question feBug [Answer Bloke q[yPraise [Brant admin Permalink Advertise | Privacy [Cookies [Terms of Use [Mobile Qe Vweb6 281907141 |Last dated 9 ul 2014 G sence ngage | ¥ Layout: fixed | fluid Article Copyright 2014 by Vitleva Everything else Copyright © CodeProject, 1999-2019

You might also like