Wednesday, February 9, 2011

Silverlight - Drag / Drop / Snap To Grid




Here is a very simple example of how to do Drag & drop and Snap To grid


The XAML


<UserControl x:Class="SilverlightApplication7.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"

    d:DesignHeight="500" d:DesignWidth="500">



    <Canvas Height="500" Width="500" x:Name="mainCanvas">



    </Canvas>

</UserControl>



The Code Behind


using System;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Media;



namespace SilverlightApplication7

{

    public partial class MainPage : UserControl

    {

        Canvas dragcanvas;

        bool isDragging = false;

        private Point clickPosition;



        public MainPage()

        {

            InitializeComponent();

            // draw the Grid

            double canvasHeight = 500;

            double canvasWidth = 500;

            for (double x = 1; x < canvasHeight; x += 10)

            {

                mainCanvas.Children.Add(new System.Windows.Shapes.Line()

                {

                    X1 = 0,

                    X2 = canvasWidth,

                    Y1 = x,

                    Y2 = x,

                    Stroke = new SolidColorBrush(Colors.LightGray),

                    StrokeThickness = .50

                });

            }



            for (double x = 1; x < canvasWidth; x += 10)

            {

                mainCanvas.Children.Add(new System.Windows.Shapes.Line()

                {

                    X1 = x,

                    X2 = x,

                    Y1 = canvasHeight,

                    Y2 = 0,

                    Stroke = new SolidColorBrush(Colors.LightGray),

                    StrokeThickness = .50

                });

            }

            // Add  a canvas to test the Drag Drop & Snap To Grid

            // You can use any Control to drag and drop



            dragcanvas = new Canvas() { Background = new SolidColorBrush(Colors.Yellow) };

            dragcanvas.Height = 30;

            dragcanvas.Width = 200;

            // Setup Events for Drag & drop

            dragcanvas.MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(dragcanvas_MouseLeftButtonDown);

            dragcanvas.MouseLeftButtonUp += new System.Windows.Input.MouseButtonEventHandler(dragcanvas_MouseLeftButtonUp);

            dragcanvas.MouseMove += new System.Windows.Input.MouseEventHandler(dragcanvas_MouseMove);

            mainCanvas.Children.Add(dragcanvas);

            // Border

            Border border = new Border()

            {

                BorderThickness = new Thickness(1),

                BorderBrush = new SolidColorBrush(Colors.Black),

                Height = 31,

                Width = 201,

                Padding = new Thickness(5)

            };

            dragcanvas.Children.Add(border);

            // Text Block

            border.Child = new TextBlock() { Text = "Drag Me Around and Snap to Grid!!!" };

        }



        private void dragcanvas_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)

        {

            var draggableControl = (Canvas)sender;



            if (isDragging)

            {

                Point currentPosition = e.GetPosition(mainCanvas);

                double xPoint = currentPosition.X - clickPosition.X;

                double yPoint = currentPosition.Y - clickPosition.Y;

                Canvas.SetLeft(draggableControl, xPoint);

                Canvas.SetTop(draggableControl, yPoint);

            }

        }



        private void dragcanvas_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)

        {

            isDragging = false;

            var draggableControl = (Canvas)sender;

            // When Mouse is released get tthe position and snap to the nearest 10 Pixels

            Point currentPosition = e.GetPosition(mainCanvas);

            Canvas.SetLeft(draggableControl, Roundoff(currentPosition.X - clickPosition.X));

            Canvas.SetTop(draggableControl, Roundoff(currentPosition.Y - clickPosition.Y));

            draggableControl.ReleaseMouseCapture();

        }



        private void dragcanvas_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)

        {

            isDragging = true;

            var draggableControl = (Canvas)sender;

            clickPosition = e.GetPosition(draggableControl);

            draggableControl.CaptureMouse();

        }



        private double Roundoff(double points)

        {

            return Math.Round(points / 10, 0) * 10;

        }

    }

}

Thursday, December 2, 2010

Connecting To Oracle using MS Enterprise Libraries

I have had many queries from my colleagues who would like to access Oracle from MS Enterprise Libraries. So I have set up this quick easy example.
Hope this helps you to get started.

I have setup the code in layers

Configuration in web/app.config
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data"/>
</configSections>
<connectionStrings>
<!--ORACLE-->
<add name="MYDBNAME" providerName="System.Data.OracleClient" connectionString="Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=YourServerName)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=XE)));User Id=USERNAME;Password=PASSWORD"/>-->
</connectionStrings>
<dataConfiguration defaultDatabase="MYDBNAME">
</dataConfiguration>


Now in your Data Access Layer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data.Common;
using System.Data;
using System.Configuration;


namespace MYAPP.DAL
{
public class SampleQuery
{
Database db = DatabaseFactory.CreateDatabase();

// this method will return the version of the DB if you have a version table in the database
public int GetDBVersion()
{
DbCommand dbCommand = db.GetStoredProcCommand("GetDBVersion");
DataSet ds = db.ExecuteDataSet(dbCommand);
return Convert.ToInt32( ds.Tables[0].Rows[0][0].ToString());
}
public DataTable GetSomeData(string param1, string param2)
{
DataSet ds = null;

DbCommand dbCommand = db.GetStoredProcCommand("GETSOMEDATA");
db.AddInParameter(dbCommand, "param1", DbType.String, param1);
db.AddInParameter(dbCommand, "param2", DbType.String, param2);
try
{
ds = db.ExecuteDataSet(dbCommand);
}
catch { }

return ds.Tables[0];
}
}
}


Procedures in Oracle
create or replace
procedure GETDBVERSION (cur_OUT OUT sys_refcursor)
is
BEGIN
OPEN cur_OUT FOR
SELECT version FROM DBVersionTable;
END;

create or replace
procedure GETSOMEDATA (param1 IN VARCHAR2,param2 IN VARCHAR2,cur_out OUT sys_refcursor)
is
PID1 varchar2(36);
PID2 varchar2(36);
BEGIN
PID1 :=param1;
PID2 :=param2;
OPEN cur_OUT FOR
SELECT * from SomeTable
where FieldID1=PID2
and FieldID2=PID1 ;
end;

Sunday, August 9, 2009

using init parameters with silverlight

if you are writing highly configurable applications in silverlight we may want to use a lot of parameters that the user can set. Since there is no config file with silverlight because it runs on the client you can set these parameters in the web.config of the web application that launches your silverlight application.

First you need to add some setting in the web.config file of the web app that launches your silverlight

Here below I have a WFC service that can change for each user install. So I needed to configure the WCF URI that I will be using from Silverlight. In my web.config I added a simple Key value setting in Appsettings in the web.config file.







Secondly in the page load event of the Form that launches you Silverlight App you need to have this code. Reads the Web.config and then dynalically loads up silverlight init parameters.

This is the markup for the silverlight control in the ASPX page.
<asp:silverlight id="MySilverligtControl" runat="server" windowless="true" source="~/ClientBin/MySilverligtApp.SL.xap?v=1.00.00.09" minimumversion="2.0.31005.0" width="100%" height="100%">


protected void Page_Load(object sender, EventArgs e)
{
// required to load parameters to Silverlight. As silverlight runs on the client it has no config file
StringBuilder configSettings = new StringBuilder();
configSettings.AppendFormat("{0}={1}", "MyServiceURI",System.Configuration.ConfigurationSettings.AppSettings["MyServiceURI"].ToString());
configSettings.Append(",");
configSettings.AppendFormat("{0}={1}", "MyNextParameter", System.Configuration.ConfigurationSettings.AppSettings["MyNextparameter"].ToString());
MySilverligtControl.InitParameters = configSettings.ToString();
}

In silverlight app. in your app.xaml code behind in the Application_Startup event you add this piece of code.

private void Application_Startup(object sender, StartupEventArgs e)
{
// Load up Parameters from WEB.Config
Application.Current.Resources.Add("MyServiceURI", e.InitParams["MyServiceURI"]);
Application.Current.Resources.Add("MyNextParameter", e.InitParams["MyNextParameter"]);
}


that's it. you can now have parameters set in web.config and read by the silverlight application.

Thursday, June 18, 2009

Dynamic WCF Connection with Silverlight

When you are using Silverlight sometimes the WCF Web service you are connecting to can be different on each deployment. To overcome the hardcoding proxy issue you can hand code your connection.

Here I have a static class that i access on every call to the WCF web service.

this is how I use this to communicate with WCF webservice

ActionServiceClient proxy = ServiceUtil.GetActionServiceClient();
proxy.YourMethodCompleted += new EventHandler(proxy_GetPositionListCompleted);
proxy.GetPositionListAsync(request);



public static ActionService.ActionServiceClient GetActionServiceClient()
{
BasicHttpBinding binding = new BasicHttpBinding(System.Windows.Browser.HtmlPage.Document.DocumentUri.Scheme.ToLower() == "https" ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None);
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;
binding.SendTimeout = new TimeSpan(0, 2, 0);
binding.ReceiveTimeout = new TimeSpan(0, 2, 0);
return new ActionService.ActionServiceClient(binding, new EndpointAddress(
new Uri(Application.Current.Resources["ActionServiceURL"].ToString())));
}

The only thing of note is the endpoint address, its added as a resource to the silverlight application in the init parameters in the ASPX page that launches silverlight. I will explain in another blog how to use init parameters in silverlight.


Saturday, March 1, 2008

Clearing Browser Caching for Silverlight

If you are having problems with your clients browser not being updated with the latest .xap in your loader aspx or html page. You need to add the follwoing to your URL.


source="~/ClientBin/WorkFlow21.SL.xap?v=1.00.00.03


So you keep incrementing the version number and the browser will load the latest xap file.

Saturday, February 23, 2008

Searching and Sorting a Generic List

If some of you are using arraylists or generic lists and are finding it difficult to search or sort a list for a Specific property value in the object, then below is a simple piece of code that uses anonymous delegates to accomplish this.


Example: Say you have a List with type object

public class Person

{

private string firstname;

private string lastname;

public string FirstName{get{return firstname;} set {firstname=value;}}

public string LastName{get{return lasttname;} set {lastname=value;}}


public Person()

{


}


}

// usage
List pl = new List();
// add items
pl.Add(new Person(){FirstName="Fred",LastName="Besterwitch"});
pl.Add(new Person(){FirstName="Eric",LastName="Johnson"});
pl.Add(new Person(){FirstName="Eric",LastName="Clapton"});
pl.Add(new Person(){FirstName="Mark",LastName="knophler"});
pl.Add(new Person(){FirstName="Carlos",LastName="Santana"});


string Searchfor="Santana";

Person person = (Person)pl.Find(
delegate(Person p)
{ return p.LastName.Trim().ToUpper().Equals(Searchfor.Trim().ToUpper());
}
);