When you are creating the windows forms application, It is hard to center align the control or set of controls in the windows form. The workout for this is pretty simple. Add a TableLayoutPanel control. It should have only one row with height equal to 100% and one column with width equal to 100%. In the properties section change the Dock property to Fill. Now add the desired control to form or add a container control like FlowLayoutPanel,GroupBox, Panel, TableLayoutPanel, TabControl etc and add controls to it. Change the Anchor property to single control or container to None. This will display all the single control or all the controls added to that container aligned in the center of the form even when the form is resized.
I am sure that there may be other ways around to this problem but this is so far the simplest I discovered while playing with the code.
Monday, November 9, 2009
Thursday, October 15, 2009
Connecting Adobe Flex to SQL Server - Part 2 (Adobe Flex)
Create After creating .Net web services, they need to be integrated with Flex to show data.
- Open IIS (Internet Information services) Manager and add crossdomain.xml to the root of the website. This file is required for flash to access the webserver content.
- <?xml version="1.0" ?>
- <cross-domain-policy>
- <allow-access-from domain="*"/>
- <site-control permitted-cross-domain-policies="all"/>
- <allow-http-request-headers-from domain="*" headers="*"/>
- </cross-domain-policy>
- Create a new Flex project in Adobe Flex Builder.
- The main MXML file contains <mx:WebService> component. The layout contains <mx:ViewStack> with two <mx:VBox> containers, one with DataGrid and other with Form for new record insertion. <mx:WebService>contains reference to all its operations using <mx:Operation> tag with result event, handling the result for every operation. All these result handler events are essentially calling the webservice’s GetDataSet method to refresh the databound ArrayCollection instance. There is an “itemEditEnd” event handler for dataGrid which fires webservice’s UpdateRecord method, when user ends editing for dataGrid item. When user clicks the “Delete” button, Actionscript code behind the MXML file gets the CONTACTID from the row selected by the user and calls the webservice’s DeleteRecord method. When user wants to insert a new record, view changes the selected child to Form for new record insertion, and on user submit, webservice’s InsertRecord method is called. Part of the code is adapted from Flex Builder “Create Application from Database” designer generated code.
- <?xml version="1.0" encoding="utf-8"?>
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
- layout="vertical" pageTitle="Flex SQL Server Application"
- creationComplete="initApp()">
- <!-- Link to external Actionscript file -->
- <mx:Script source="FlexDBAppScript.as" />
- <mx:WebService id="websvc"
- wsdl="http://localhost/WebService/Contacts.asmx?wsdl"
- showBusyCursor="true"
- fault="faultHandler(event)">
- <mx:operation name="GetDataSet"
- result="GetDataSetHandler(event)"/>
- <mx:operation name="InsertRecord"
- result="InsertRecordhandler(event)"/>
- <mx:operation name="DeleteRecord"
- result="DeleteRecordHandler(event)"/>
- <mx:operation name="UpdateRecord"
- result="UpdateRecordHandler(event)"/>
- </mx:WebService>
- <mx:ViewStack id="appView" width="100%" height="100%">
- <mx:VBox id="displayGrid">
- <mx:DataGrid id="dataGrid"
- dataProvider="{dataArray}" rowCount="10"
- editable="true" resizableColumns="true"
- itemEditEnd="ItemEditEnd(event)">
- <mx:columns>
- <mx:DataGridColumn headerText="Contact ID" dataField="CONTACTID" editable="false"/>
- <mx:DataGridColumn headerText="First Name" dataField="FIRST_NAME" />
- <mx:DataGridColumn headerText="Last Name" dataField="LAST_NAME" />
- <mx:DataGridColumn headerText="City" dataField="CITY" />
- <mx:DataGridColumn headerText="State" dataField="STATE" />
- </mx:columns>
- </mx:DataGrid>
- <mx:HBox>
- <mx:Button label="Add New" id="btnAddNew" click="GoToInsertForm()"/>
- <mx:Button label="Delete" id="btnDelete" click="DeleteItem()"/>
- </mx:HBox>
- </mx:VBox>
- <mx:VBox id="insertForm">
- <mx:Form id="ContactForm" label="Insert New Record">
- <mx:FormHeading label="Insert New Record"/>
- <mx:FormItem label="First Name:" id="First_Name_form">
- <mx:TextInput id="tInp_First_Name" text=""/>
- </mx:FormItem>
- <mx:FormItem label="Last Name:" id="Last_Name_form">
- <mx:TextInput id="tInp_Last_Name" text=""/>
- </mx:FormItem>
- <mx:FormItem label="City:" id="City_form">
- <mx:TextInput id="tInp_City" text=""/>
- </mx:FormItem>
- <mx:FormItem label="State:" id="State_form">
- <mx:TextInput id="tInp_State" text=""/>
- </mx:FormItem>
- </mx:Form>
- <mx:HBox>
- <mx:Button label="Save" id="btnSubmit" click="InsertItem()"/>
- <mx:Button label="Cancel" id="btnCancel" click="GoToDisplayGrid()"/>
- </mx:HBox>
- </mx:VBox>
- </mx:ViewStack>
- </mx:Application>
- The actionscript code for MXML file is contained in a separate .as file.
- // Actionscript file for FlexDBApp.mxml
- // Part of the code is adapted from Flex- Create Application from Database generated code.
- import mx.collections.ArrayCollection;
- import mx.controls.Alert;
- import mx.events.CloseEvent;
- import mx.events.DataGridEvent;
- import mx.rpc.AsyncToken;
- import mx.rpc.events.FaultEvent;
- import mx.rpc.events.ResultEvent;
- [Bindable]
- public var dataArray:ArrayCollection = new ArrayCollection();
- private function initApp():void
- {
- // Initialize and load the web service
- websvc.loadWSDL();
- websvc.GetDataSet();
- }
- /**
- * Result event handler for websvc GetDataSetHandler call
- */
- private function GetDataSetHandler(e:ResultEvent):void
- {
- // Populate dataArray with dataset table
- dataArray = e.result.Tables.Contacts.Rows;
- }
- /**
- * Event handler for Add New Button Click event
- */
- public function GoToInsertForm():void
- {
- // Change te view's selected child to insert form
- appView.selectedChild = insertForm;
- }
- /**
- * Event handlet for Save Button Click event
- */
- public function InsertItem():void
- {
- websvc.InsertRecord(tInp_First_Name.text, tInp_Last_Name.text, tInp_City.text, tInp_State.text);
- GoToDisplayGrid();
- }
- /**
- * Event handler for Delete Button Click event
- */
- public function GoToDisplayGrid():void
- {
- // Change te view's selected child to display Grid
- appView.selectedChild = displayGrid;
- }
- /**
- * Result event handler for websvc InsertRecordhandler call
- */
- private function InsertRecordhandler(e:ResultEvent):void
- {
- // Replopulate the dataArray after transaction
- websvc.GetDataSet();
- }
- /**
- * Event handler triggered when the user finishes editing an entry
- * triggers an "update" server command
- */
- private function ItemEditEnd(e:DataGridEvent):void
- {
- // Get row number of the edited row
- var dgRowIndex:int = e.rowIndex;
- // Get name of DataField being edited
- var dgFieldName:String = e.dataField;
- // Get Column Index being edited
- var dgColIndex:int = e.columnIndex;
- var vo:* = dataArray[dgRowIndex];
- var col:DataGridColumn = dataGrid.columns[dgColIndex];
- var newvalue:String = dataGrid.itemEditorInstance[col.editorDataField];
- vo[dgFieldName] = newvalue;
- websvc.UpdateRecord(vo.CONTACTID, vo.FIRST_NAME, vo.LAST_NAME, vo.CITY, vo.STATE);
- }
- /**
- * Result event handler for websvc UpdateRecordHandler call
- */
- private function UpdateRecordHandler(e:ResultEvent):void
- {
- // Replopulate the dataArray after transaction
- websvc.GetDataSet();
- }
- /**
- * Event handler for Delete Button Click event
- */
- public function DeleteItem():void
- {
- if (dataGrid.selectedItem)
- {
- Alert.show("Are you sure you want to delete the selected record?",
- "Confirm Delete", 3, this, DeleteClickHandler);
- }
- }
- /**
- * Event handler function for the Confirm dialog raises when the Delete Button is pressed.
- * If the pressed button was Yes, then the product is deleted.
- * @param object event
- * @return nothing
- */
- private function DeleteClickHandler(event:CloseEvent):void
- {
- var indexForDelete:int = dataGrid.selectedIndex;
- if (indexForDelete == -1)
- {
- return;
- }
- if (event.detail == Alert.YES)
- {
- var vo:* = dataArray[indexForDelete];
- websvc.DeleteRecord(vo.CONTACTID);
- }
- }
- /**
- * Result event handler for websvc DeleteRecordHandler call
- */
- private function DeleteRecordHandler(e:ResultEvent):void
- {
- // Replopulate the dataArray after transaction
- websvc.GetDataSet();
- }
- /**
- *Fault event handler for websvc WebService call
- */
- private function faultHandler(event:FaultEvent):void
- {
- Alert.show(event.fault.message, "Application Error");
- }
Tuesday, October 13, 2009
Connecting Adobe Flex to SQL Server - Part 1 (.Net WebService)
This blog is in transition to be moved to new URL. The new and updated version of this post is located at REST Web Services With ASP.Net Web API
Flex is really one of the cool coding languages with lot of flexibility and scope for development. It compiles into SWF file as an end product, which is a client side technology. Flex cannot connect to SQL server directly like ASP.Net or any other server side languages. It uses .net web services to connect to SQL server.
There can be different ways to connect Flex to SQL Server. The method described in this post requires following software:
Flex is really one of the cool coding languages with lot of flexibility and scope for development. It compiles into SWF file as an end product, which is a client side technology. Flex cannot connect to SQL server directly like ASP.Net or any other server side languages. It uses .net web services to connect to SQL server.
There can be different ways to connect Flex to SQL Server. The method described in this post requires following software:
- Visual Studio 2008 any version or Visual Web Developer Express Edition
- Flex Builder 3
- SQL Server 2005 (Full Version or Express Edition)
- IIS (Internet Information Services)
- Open Visual Studio 2008. Click File –> New Website. Select ASP.NET Web Service as project template and rename webservice(.asmx) file as Contacts.asmx.
- For this example I have created a new database named “Sample” with a table called “Contacts”. The scheme of the table is shown below.
- After the new web service is created in VS, open web.config and add connection string for new SQL Sever database between appSettings and System.Web.
- <connectionStrings>
- <add name="SampleDBConn" connectionString="Data Source=SERVER_NAME\SQLEXPRESS;Initial Catalog=SAMPLE;Integrated Security=True" providerName="System.Data.SqlClient" />
- </connectionStrings>
- Create a new database helper class in App_Code directory named “DBConn.cs". It contains various functions for creating SqlDbConnection, opening & closing the connection, creating and filling a new DataSet from a given select query etc.
- using System;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- /// <summary>
- /// Helper class to provide access to database
- /// </summary>
- public class DBConn
- {
- private string connString;
- private SqlConnection sqlConn;
- public DBConn()
- {
- try
- {
- connString = ConfigurationManager.ConnectionStrings["SampleDBConn"].ConnectionString;
- }
- catch (Exception ex)
- {
- throw new ConfigurationErrorsException(
- "Required database isn't configured. Please add connection info to Web.config for 'AdventureWorks' database.", ex);
- }
- sqlConn = new SqlConnection(connString);
- }
- /// <summary>
- /// Open Connection for SQL transactions
- /// </summary>
- public void OpenSqlConnection()
- {
- if(sqlConn.State == ConnectionState.Closed)
- sqlConn.Open();
- }
- /// <summary>
- /// Close connection after transactions
- /// </summary>
- public void CloseSqlConnection()
- {
- if (sqlConn.State == ConnectionState.Open)
- sqlConn.Close();
- }
- /// <summary>
- /// Creates new SqlCommand for given query string
- /// </summary>
- /// <param name="queryString">Query String</param>
- /// <returns>SqlCommand</returns>
- public SqlCommand CreateSQLCommand(string queryString)
- {
- return new SqlCommand(queryString, sqlConn);
- }
- /// <summary>
- /// Creates and adds parameter to SqlCommand
- /// </summary>
- /// <param name="command">SqlCommand</param>
- /// <param name="parameterName">Paramater Name</param>
- /// <param name="value">Paramater Value</param>
- public void CreateParameter(SqlCommand command, string parameterName, object value)
- {
- SqlParameter param = command.CreateParameter();
- param.ParameterName = parameterName;
- param.Value = value;
- command.Parameters.Add(param);
- }
- /// <summary>
- /// Creates a new dataset and fills it with data for given query
- /// </summary>
- /// <param name="selectCmd">Select Query</param>
- /// <param name="tabName">TableName</param>
- /// <returns>DataSet</returns>
- public DataSet ReturnDataSet(string selectCmd, string tabName)
- {
- sqlConn.Open();
- DataSet dSet = new DataSet();
- SqlDataAdapter sqlDBAdapter = new SqlDataAdapter(selectCmd, sqlConn);
- sqlDBAdapter.Fill(dSet, tabName);
- sqlConn.Close();
- return dSet;
- }
- }
- In the code-behind webservice (asmx) file, create different WebMethods for retrieving, inserting, updating and deleting the data from the database. I have created a web method for data retrieval returning the C# DataSet. All these functions are using DBConn.cs, the database helper class created in previous step. The table used in this example is Conatcts table created in previous steps.
- using System;
- using System.Data;
- using System.Data.SqlClient;
- using System.Text;
- using System.Web.Services;
- /// <summary>
- /// Summary description for Contact
- /// </summary>
- [WebService(Namespace = "http://tempuri.org/")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- public class Contacts : WebService
- {
- private DBConn dbConnection;
- private readonly string[] FieldNames = {"CONTACTID, FIRST_NAME, LAST_NAME, CITY, STATE"};
- public Contacts()
- {
- dbConnection = new DBConn();
- }
- /// <summary>
- /// Get data as DataSet
- /// </summary>
- /// <returns>DataSet</returns>
- [WebMethod]
- public DataSet GetDataSet()
- {
- try
- {
- StringBuilder sql = new StringBuilder(128);
- sql.Append("SELECT ");
- sql.Append(String.Join(",", FieldNames));
- sql.Append(" FROM CONTACTS");
- return dbConnection.ReturnDataSet(sql.ToString(), "Contacts");
- }
- catch (Exception ex)
- {
- throw new Exception("Data Rerieval Error", ex);
- }
- }
- /// <summary>
- /// Inserts a new record
- /// </summary>
- [WebMethod]
- public void InsertRecord(string First_Name, string Last_Name, string City, string State)
- {
- try
- {
- string qString = @"INSERT INTO CONTACTS (FIRST_NAME, LAST_NAME, CITY, STATE) VALUES (@FIRST_NAME, @LAST_NAME, @CITY, @STATE)";
- dbConnection.OpenSqlConnection();
- SqlCommand sqlCmd = dbConnection.CreateSQLCommand(qString);
- dbConnection.CreateParameter(sqlCmd, "@FIRST_NAME", First_Name);
- dbConnection.CreateParameter(sqlCmd, "@LAST_NAME", Last_Name);
- dbConnection.CreateParameter(sqlCmd, "@CITY", City);
- dbConnection.CreateParameter(sqlCmd, "@STATE", State);
- sqlCmd.ExecuteNonQuery();
- dbConnection.CloseSqlConnection();
- }
- catch (Exception ex)
- {
- throw new Exception("Data Rerieval Error", ex);
- }
- }
- /// <summary>
- /// Updates the database record
- /// </summary>
- [WebMethod]
- public void UpdateRecord(double ContactID, string First_Name, string Last_Name, string City, string State)
- {
- try
- {
- string qString = @"UPDATE CONTACTS SET FIRST_NAME = @FIRST_NAME, LAST_NAME = @LAST_NAME, CITY = @CITY, STATE = @STATE WHERE CONTACTID = @CONTACTID ";
- dbConnection.OpenSqlConnection();
- SqlCommand sqlCmd = dbConnection.CreateSQLCommand(qString);
- dbConnection.CreateParameter(sqlCmd, "@CONTACTID", ContactID);
- dbConnection.CreateParameter(sqlCmd, "@FIRST_NAME", First_Name);
- dbConnection.CreateParameter(sqlCmd, "@LAST_NAME", Last_Name);
- dbConnection.CreateParameter(sqlCmd, "@CITY", City);
- dbConnection.CreateParameter(sqlCmd, "@STATE", State);
- sqlCmd.ExecuteNonQuery();
- dbConnection.CloseSqlConnection();
- }
- catch (Exception ex)
- {
- throw new Exception("Data Rerieval Error", ex);
- }
- }
- /// <summary>
- /// Delete records from database
- /// </summary>
- [WebMethod]
- public void DeleteRecord(double ContactID)
- {
- try
- {
- string qString = @"DELETE FROM CONTACTS WHERE CONTACTID = @CONTACTID ";
- dbConnection.OpenSqlConnection();
- SqlCommand sqlCmd = dbConnection.CreateSQLCommand(qString);
- dbConnection.CreateParameter(sqlCmd, "@CONTACTID", ContactID);
- sqlCmd.ExecuteNonQuery();
- dbConnection.CloseSqlConnection();
- }
- catch (Exception ex)
- {
- throw new Exception("Data Rerieval Error", ex);
- }
- }
- }
- Set the Contacts.asmx file as start up page, and try invoking various webmethods to make sure that the new webservice is successfully running and retrieving the data.
- This finishes the .net webservice part of the connection process.
Subscribe to:
Posts (Atom)