Refresh Postgis connections

Feb 16, 2009 at 4:45 PM

Hi

I'm using the following code to refresh SharpMap

private void RefreshMap()
{
//--> Use SharpMap to generate the map image
picMap.Image = _sharpMap.GetMap();

}

However this code appears to be simply refreshing the picImage without refreshing the Postgis connections. I placed MessageBox messages in key places. This were displayed during the Initialization stage of opening SharpMap but were not displayed during the above refresh procedure.

I need the connections refreshed to display information rewlative to particula ID numbers within the Postgis tables.

Does SharpMap have a method of refreshing this connection? I've attempted a number of off-the-wall thoughts with no success.

Bob

Coordinator
Feb 18, 2009 at 11:47 AM
Hello Bob,
I assume you have a or several VectorLayer(s) with a PostGis Provider(s).
What is it you want to change according to the selected ID (DefinitionQuery of Postgis-Provider, Datasource of VectorLayer, ...)
The call to _sharpMap.GetMap() should requery the postgis-providers with the current settings.
Perhaps
System.Diagnostics.Debug.WriteLine( string.Format("\n{0}\n{1}\n", "executing sql:", strSQL));
in PostGis Providers
GetGeometriesInView

ExecuteIntersectionQuery
functions could help trace the error.
Hth FObermaier

It couldn't be a caching problem (Web)?
Feb 18, 2009 at 12:31 PM
Hi Fobermaier
I have two layers, geometry and text, through a Definition Query of Postgis Provider.
The Postgis connection is controlled through a variable. When I change the variable I want the connection to follow.
Unfortunately, in my case the GetMap() is refreshing the image but is not refreshing the Postgis cionnection except when I shutdown and restart.
I'm new to C# and I am wondering if my code isn't structured the way it should be or if there is a method of calling the Defenition Query directly (the preferred method)?
Code follows -
Bob

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using SharpMap.Layers;

using System.Collections.ObjectModel;

using System.Drawing.Printing;

using System.IO;

using System.Threading;

namespace WindowsFormsApplication1

{

public partial class frmGraphics : Form

{

//--> Define the SharpMap object

SharpMap.Map _sharpMap;

//--> Zoom Factor

const float ZOOM_FACTOR = 0.1f;

string filecontents;

string contentsoffile;

public frmGraphics()

{

InitializeComponent();

StreamReader sr = new StreamReader("C:\\IDW32\\Library\\Connection.txt");

string contentsoffile = sr.ReadToEnd();

sr.DiscardBufferedData();

sr.Close();

StreamReader sr2 = new StreamReader("C:\\IDW32\\Library\\P&ID.txt");

string filecontents = sr2.ReadToEnd();

sr2.DiscardBufferedData();

sr2.Close();

//--> Initialize the Map

_sharpMap = new SharpMap.Map(new Size(1000, 900));

_sharpMap.BackColor = Color.Silver;

SharpMap.Layers.VectorLayer myLayer = new SharpMap.Layers.VectorLayer("My Layer");

string ConnStr = contentsoffile;

//--> Add the first Layer

SharpMap.Data.Providers.PostGIS provider = new SharpMap.Data.Providers.PostGIS(ConnStr, "p_id.p_id", "the_geom", "public");//create a new provider

provider.DefinitionQuery = filecontents; //configure the definitionQuery

myLayer.DataSource = provider; //assign the provider to the layer

MessageBox.Show("Initiate" + filecontents);

//Setup linestyle

myLayer.Style.Line.Width = 1 / 8;

myLayer.Style.Line.Color = Color.Black;

myLayer.Style.Line.EndCap = System.Drawing.Drawing2D.LineCap.Round; //Round end

myLayer.Style.EnableOutline = true;

myLayer.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; //Render smooth lines

myLayer.MaxVisible = 40000;

RefreshMap();

//Set up a text layer

SharpMap.Layers.LabelLayer layText = new SharpMap.Layers.LabelLayer("Text Layer");

SharpMap.Data.Providers.PostGIS provider2 = new SharpMap.Data.Providers.PostGIS(ConnStr, "p_id.p_id", "the_geom", "public");//create a new provider

provider2.DefinitionQuery = filecontents; //configure the definitionQuery

layText.DataSource = provider2; //assign the provider to the layer

layText.Enabled = true;

layText.LabelColumn = "process_name";

layText.Style = new SharpMap.Styles.LabelStyle();

layText.Style.ForeColor = Color.Black;

layText.Style.Font = new Font("Arial", 10);

layText.Style.HorizontalAlignment = SharpMap.Styles.LabelStyle.HorizontalAlignmentEnum.Left;

layText.Style.VerticalAlignment = SharpMap.Styles.LabelStyle.VerticalAlignmentEnum.Bottom;

layText.Style.Offset = new PointF(3, 3);

layText.Style.Halo = new Pen(Color.Silver, 2);

layText.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

_sharpMap.Layers.Add(myLayer); //Add geometry label to viewer

_sharpMap.Layers.Add(layText); //Add label layer to viewer

}

public void RefreshMap()

{

System.Threading.Thread.Sleep(1);

//--> Use SharpMap to generate the map image

_sharpMap.GetMap();

}

public void RefreshConnection()

{

}

private object MyLayer()

{

throw new NotImplementedException();

}

void Form1_Load(object sender, EventArgs e)

{

//--> Zoom to extent

_sharpMap.ZoomToExtents();

RefreshMap();

}

private void button1_Click(object sender, EventArgs e)

{

_sharpMap.Zoom -= _sharpMap.Zoom * ZOOM_FACTOR;

RefreshMap();

}

private void button2_Click(object sender, EventArgs e)

{

_sharpMap.Zoom += _sharpMap.Zoom * ZOOM_FACTOR;

RefreshMap();

}

private void button3_Click(object sender, EventArgs e)

{

_sharpMap.ZoomToExtents();

RefreshMap();

}

private void picMap_MouseClick(object sender, MouseEventArgs e)

{

//--> Convert mouse click point from mimage coordinates to world coordinates

SharpMap.Geometries.Point p = _sharpMap.ImageToWorld(new PointF(e.X, e.Y));

//--> Recenter Map

_sharpMap.Center.X = p.X;

_sharpMap.Center.Y = p.Y;

RefreshMap();

}

private void button4_Click(object sender, EventArgs e)

{

RefreshMap();

}

internal void InitializeWatcher(FileInfo configurationFile, IList<string> configurationSections)

{

fWatcher = new FileSystemWatcher

{

Path = @"C:\\IDW32\\Library\\p&id.txt",

Filter = "p&id.txt",

NotifyFilter = (NotifyFilters.CreationTime | NotifyFilters.LastWrite |

NotifyFilters.FileName)

};

fWatcher.Created += new FileSystemEventHandler(fWatcher_Created);

fWatcher.Changed += new FileSystemEventHandler(fWatcher_Changed);

fWatcher.EnableRaisingEvents = true;

}

void fWatcher_Created(object sender, FileSystemEventArgs e)

{

RefreshMap();

// throw new NotImplementedException("Create");

}

public void fWatcher_Changed(object sender, FileSystemEventArgs e)

{

System.Threading.Thread.Sleep(1);

StreamReader sr2 = new StreamReader("C:\\IDW32\\Library\\P&ID.txt");

string filecontents = sr2.ReadToEnd();

sr2.DiscardBufferedData();

sr2.Close();

// RefreshConnection();

RefreshMap();

MessageBox.Show("1..." +filecontents);

}

private string Remove(int p, int p_2)

{

throw new NotImplementedException();

}

private string Replace()

{

throw new NotImplementedException();

}

private string Remove()

{

throw new NotImplementedException();

}

}

}

----- Original Message -----
From: [email removed]
To: [email removed]
Sent: Wednesday, February 18, 2009 4:47 AM
Subject: Re: Refresh Postgis connections [SharpMap:47259]

From: fobermaier

Hello Bob,
I assume you have a or several VectorLayer(s) with a PostGis Provider(s).
What is it you want to change according to the selected ID (DefinitionQuery of Postgis-Provider, Datasource of VectorLayer, ...)
The call to _sharpMap.GetMap() should requery the postgis-providers with the current settings.
Perhaps
System.Diagnostics.Debug.WriteLine( string.Format("\n{0}\n{1}\n", "executing sql:", strSQL));
in PostGis Providers
GetGeometriesInView

ExecuteIntersectionQuery
functions could help trace the error.
Hth FObermaier

It couldn't be a caching problem (Web)?
Coordinator
Feb 18, 2009 at 1:06 PM
Edited Feb 18, 2009 at 1:07 PM
Hi Bob, maybe something like:

private void SetDefinitionQuery(definitionQuery)
{
    (this._sharpMap.Layers["process_name"].DataSource as SharpMap.Data.Providers.PostGIS).DefinitionQuery = definitionQuery
}


then everyrtime you read the contents of the file call it passing in the new definitionQuery before calling RefreshMap.. hth jd
Coordinator
Feb 18, 2009 at 2:41 PM
Hi Bob,
assuming your FileSystemWatcher is working - I did not find the call to
InitializeWatcher(FileInfo configurationFile, IList<string> configurationSections)
- you still need to - as john pointed out - set the DefinitionQuery property according to the contents of your file, e.g.
public void fWatcher_Changed(object sender, FileSystemEventArgs e)
{
System.Threading.Thread.Sleep(1);
StreamReader sr2 = new StreamReader("C:\\IDW32\\Library\\P&ID.txt");
string filecontents = sr2.ReadToEnd();
sr2.DiscardBufferedData();
sr2.Close();

(_sharpMap.Layers["My Layer"].DataSource as SharpMap.Data.Providers.PostGIS).DefinitionQuery = filecontents
(_sharpMap.Layers["Text Layer"].DataSource as SharpMap.Data.Providers.PostGIS).DefinitionQuery = filecontents

// RefreshConnection();
RefreshMap();
//MessageBox.Show("1..." +filecontents);

}
Hth FObermaier
Feb 18, 2009 at 8:54 PM
I don't understand why 'DataSource' in the following -

(_sharpMap.Layers["My Layer"].DataSource as

SharpMap.Data.Providers.PostGIS).DefinitionQuery = filecontents;

shows an error when the same reference in -

SharpMap.Data.Providers.PostGIS provider = new SharpMap.Data.Providers.PostGIS(ConnStr, "p_id.p_id", "the_geom", "public");//create a new provider

provider.DefinitionQuery = filecontents; //configure the definitionQuery

myLayer.DataSource = provider; //assign the provider to the layer

is acceptable?

If I leave the reference to 'DataSource' out of the argument an error suggests that I need to work in the keyword 'new'.

Bob

----- Original Message -----
From: [email removed]
To: [email removed]
Sent: Wednesday, February 18, 2009 7:43 AM
Subject: Re: Refresh Postgis connections [SharpMap:47259]

From: fobermaier

Hi Bob,
assuming your FileSystemWatcher is working - I did not find the call to
InitializeWatcher(FileInfo configurationFile, IList<string> configurationSections)
- you still need to - as john pointed out - set the DefinitionQuery property according to the contents of your file, e.g.
public void fWatcher_Changed(object sender, FileSystemEventArgs e)
{
System.Threading.Thread.Sleep(1);
StreamReader sr2 = new StreamReader("C:\\IDW32\\Library\\P&ID.txt");
string filecontents = sr2.ReadToEnd();
sr2.DiscardBufferedData();
sr2.Close();

(_sharpMap.Layers["My Layer"].DataSource as SharpMap.Data.Providers.PostGIS).DefinitionQuery = filecontents
(_sharpMap.Layers["Text Layer"].DataSource as SharpMap.Data.Providers.PostGIS).DefinitionQuery = filecontents

// RefreshConnection();
RefreshMap();
//MessageBox.Show("1..." +filecontents);

}
Hth FObermaier
Coordinator
Feb 19, 2009 at 6:55 AM
Hi Bob, what kind of error did you get, is it that you can't compile or is it at runtime (statcktrace)?
Could you post the content of your "P&ID.txt" file?
FObermaier
Feb 20, 2009 at 4:16 PM

Hi fobermaier

With '.DataSource' 

Error = "SharpMap.Layers.ILayer does not contain a definition for 'DataSource' and no extension method ...."

The puzzles me since we are referring to the the layer described in code above which acceptes '.DataSource'.

With ".DataSource' removed it's a run time exception seen below.

The P&ID.text is -

P_ID.P_ID.P_ID_ID= '303' 

after I change the 3 to a 4 and save the text file.

The P&ID text file directs the connection properly during startup.

Bob

Exception -

System.Reflection.TargetInvocationException was unhandled
Message="Exception has been thrown by the target of an invocation."
Source="mscorlib"
StackTrace:
at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Delegate.DynamicInvokeImpl(Object[] args)
at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
at System.Windows.Forms.ContainerControl.WndProc(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at WindowsFormsApplication1.Program.Main() in C:\Documents and Settings\Robert\My Documents\Visual Studio 2008\Projects\Data Graphics\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.NullReferenceException
Message="Object reference not set to an instance of an object."
Source="Data Graphics"
StackTrace:
at WindowsFormsApplication1.frmGraphics.RefreshConnection() in C:\Documents and Settings\Robert\My Documents\Visual Studio 2008\Projects\Data Graphics\Graphics.cs:line 109
at WindowsFormsApplication1.frmGraphics.fWatcher_Changed(Object sender, FileSystemEventArgs e) in C:\Documents and Settings\Robert\My Documents\Visual Studio 2008\Projects\Data Graphics\Graphics.cs:line 207
InnerException: 

 

Coordinator
Feb 20, 2009 at 4:31 PM
Ah, we're getting closer.. 

public void fWatcher_Changed(object sender, FileSystemEventArgs e)

 System.Threading.Thread.Sleep(1); 
 StreamReader sr2 = new StreamReader("C:\\IDW32\\Library\\P&ID.txt"); 
 string filecontents = sr2.ReadToEnd(); 
 sr2.DiscardBufferedData(); 
 sr2.Close(); 
 ((_sharpMap.Layers["My Layer"] as SharpMap.Layers.VectorLayer).DataSource as SharpMap.Data.Providers.PostGIS).DefinitionQuery = filecontents 
 ((_sharpMap.Layers["Text Layer"] as SharpMap.Layers.LabelLayer).DataSource as SharpMap.Data.Providers.PostGIS).DefinitionQuery = filecontents 
 // RefreshConnection(); 
 RefreshMap();  //MessageBox.Show("1..." +filecontents);
}
 

we had both forgotten to cast the layer to VectorLayer
hth jd
Feb 20, 2009 at 5:49 PM
I still get a - "Exception has been thrown by the target of an invocation." error. There was also a suggestion to use the keyword 'new'.
After various tials I've come up with this as having the fewest problems. C# tell me that after the second 'as', a 'type' is expected.
Is "SharpMap.Data.Providers.PostGIS( "p_id.p_id", "the_geom", "public")" not a type?

(( _sharpMap.Layers["My Layer"]as SharpMap.Layers.VectorLayer).DataSource

as (new SharpMap.Data.Providers.PostGIS( "p_id.p_id", "the_geom", "public")).DefinitionQuery = filecontents;

Bob

----- Original Message -----
From: [email removed]
To: [email removed]
Sent: Friday, February 20, 2009 9:31 AM
Subject: Re: Refresh Postgis connections [SharpMap:47259]

From: johndiss

Ah, we're getting closer..

public void fWatcher_Changed(object sender, FileSystemEventArgs e)
{
System.Threading.Thread.Sleep(1);
StreamReader sr2 = new StreamReader("C:\\IDW32\\Library\\P&ID.txt");
string filecontents = sr2.ReadToEnd();
sr2.DiscardBufferedData();
sr2.Close();
((_sharpMap.Layers["My Layer"] as SharpMap.Layers.VectorLayer).DataSource as SharpMap.Data.Providers.PostGIS).DefinitionQuery = filecontents
((_sharpMap.Layers["Text Layer"] as SharpMap.Layers.LabelLayer).DataSource as SharpMap.Data.Providers.PostGIS).DefinitionQuery = filecontents
// RefreshConnection();
RefreshMap(); //MessageBox.Show("1..." +filecontents);
}


we had both forgotten to cast the layer to VectorLayer
hth jd
Coordinator
Feb 20, 2009 at 8:34 PM
Hi Bob, I have had a little play around, I havent run this code as I didnt have the designer part of your code - I have put a stub version equivalent to the designer in just to let it compile - you will not want to copy that part... Hopefully all the handlers will still be attached correctly in your code.. hth jd

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using SharpMap;
using SharpMap.Data.Providers;
using SharpMap.Layers;
using SharpMap.Styles;
using Point = SharpMap.Geometries.Point;

namespace Demo
{
    public partial class frmGraphics//temp file representing the designer.cs file - do not copy
    {
        protected Button button1;
        protected Button button2;
        protected Button button3;
        protected Button button4;
        protected PictureBox picMap; //this is a guess as to what is in your application
        private FileSystemWatcher fWatcher;

        private void InitializeComponent()
        {
            //do some initialization
        }
    }

    public partial class frmGraphics : Form
    {
        //--> Define the SharpMap object

        //--> Zoom Factor

        private const float ZOOM_FACTOR = 0.1f;
        private readonly Map _sharpMap;

        public frmGraphics()
        {
            InitializeComponent();

            string connectionString = File.ReadAllText("C:\\IDW32\\Library\\Connection.txt");//note usually we would use the connectionStrings in the app.config file for this

            //--> Initialize the Map

            _sharpMap = new Map(new Size(1000, 900)) { BackColor = Color.Silver };

            PostGIS provider = new PostGIS(connectionString, "p_id.p_id", "the_geom", "public"); //create a new provider

            VectorLayer myLayer = new VectorLayer("My Layer");

            myLayer.Style = new VectorStyle
                                {
                                    Line =
                                        {
                                            Width = (1.0F / 8.0F),
                                            Color = Color.Black,
                                            EndCap = LineCap.Round
                                        },
                                    EnableOutline = true
                                };

            //--> Add the first Layer

            myLayer.DataSource = provider; //assign the provider to the layer

            myLayer.SmoothingMode = SmoothingMode.AntiAlias; //Render smooth lines

            myLayer.MaxVisible = 40000;

 

            //Set up a text layer

            LabelLayer layText = new LabelLayer("Text Layer");

            layText.DataSource = provider;//we are reusing the same provider

            layText.Enabled = true;

            layText.LabelColumn = "process_name";

            layText.Style = new LabelStyle
                                {
                                    ForeColor = Color.Black,
                                    Font = new Font("Arial", 10),
                                    HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left,
                                    VerticalAlignment = LabelStyle.VerticalAlignmentEnum.Bottom,
                                    Offset = new PointF(3, 3),
                                    Halo = new Pen(Color.Silver, 2)
                                };

            layText.TextRenderingHint = TextRenderingHint.AntiAlias;

            _sharpMap.Layers.Add(myLayer); //Add geometry label to viewer

            _sharpMap.Layers.Add(layText); //Add label layer to viewer

            RefreshMap();

        }

        public void RefreshMap()
        {
            Thread.Sleep(1);

            //--> Use SharpMap to generate the map image
            string definitionQuery = GetDefinitionQueryText();

            SetDefinitionQueryOnLayer(_sharpMap.Layers["My Layer"], definitionQuery);//we only need to set the definition query via one layer as they share the same provider

            Image im = _sharpMap.GetMap();

            //NOTE: the call do get map creates a new bitmap - you still need to assign it to your image control
            //(or use a MapImage control and call the Refresh method of that) myGuess is below
            //picMap.Image = im;
            MessageBox.Show(definitionQuery);

        }

        private void Form1_Load(object sender, EventArgs e)//it looks like the form has been renamed but the handler may still be active on its old name
        {
            //--> Zoom to extent

            _sharpMap.ZoomToExtents();

            RefreshMap();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            _sharpMap.Zoom -= _sharpMap.Zoom * ZOOM_FACTOR;

            RefreshMap();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            _sharpMap.Zoom += _sharpMap.Zoom * ZOOM_FACTOR;

            RefreshMap();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            _sharpMap.ZoomToExtents();

            RefreshMap();
        }

        private void picMap_MouseClick(object sender, MouseEventArgs e)
        {
            //--> Convert mouse click point from mimage coordinates to world coordinates

            _sharpMap.Center = _sharpMap.ImageToWorld(new PointF(e.X, e.Y));

            //--> Recenter Map

            RefreshMap();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            RefreshMap();
        }

        internal void InitializeWatcher(FileInfo configurationFile, IList<string> configurationSections)
        {
            fWatcher = new FileSystemWatcher

                           {
                               Path = @"C:\\IDW32\\Library\\p&id.txt",
                               Filter = "p&id.txt",
                               NotifyFilter = (NotifyFilters.CreationTime | NotifyFilters.LastWrite |
                                               NotifyFilters.FileName)
                           };

            fWatcher.Created += fWatcher_Created;

            fWatcher.Changed += fWatcher_Changed;

            fWatcher.EnableRaisingEvents = true;
        }

        private void fWatcher_Created(object sender, FileSystemEventArgs e)
        {
            Debug.WriteLine("Handling file created event");
            RefreshMap();

        }

        public string GetDefinitionQueryText()
        {
            return File.ReadAllText("C:\\IDW32\\Library\\P&ID.txt");
        }

        public void fWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            Debug.WriteLine("Handling file changed event");

            RefreshMap();
        }

        private static void SetDefinitionQueryOnLayer(ILayer layer, string definitionQuery)
        {
            IProvider provider;
            if (layer is VectorLayer)
                provider = ((VectorLayer)layer).DataSource;
            else if (layer is LabelLayer)
                provider = ((LabelLayer)layer).DataSource;
            else
                throw new Exception("Invalid Layer Type");

            if (provider is PostGIS)
                ((PostGIS)provider).DefinitionQuery = definitionQuery;
            else
                throw new Exception("Unexpected provider");

        }
    }
}

Feb 22, 2009 at 6:26 PM
Hi John
That works very well.
Thanks very much for all of your help.
Bob
----- Original Message -----
From: [email removed]
To: [email removed]
Sent: Friday, February 20, 2009 1:34 PM
Subject: Re: Refresh Postgis connections [SharpMap:47259]

From: johndiss

Hi Bob, I have had a little play around, I havent run this code as I didnt have the designer part of your code - I have put a stub version equivalent to the designer in just to let it compile - you will not want to copy that part... Hopefully all the handlers will still be attached correctly in your code.. hth jd

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using SharpMap;
using SharpMap.Data.Providers;
using SharpMap.Layers;
using SharpMap.Styles;
using Point = SharpMap.Geometries.Point;

namespace Demo
{
public partial class frmGraphics//temp file representing the designer.cs file - do not copy
{
protected Button button1;
protected Button button2;
protected Button button3;
protected Button button4;
protected PictureBox picMap; //this is a guess as to what is in your application
private FileSystemWatcher fWatcher;

private void InitializeComponent()
{
//do some initialization
}
}

public partial class frmGraphics : Form
{
//--> Define the SharpMap object

//--> Zoom Factor

private const float ZOOM_FACTOR = 0.1f;
private readonly Map _sharpMap;

public frmGraphics()
{
InitializeComponent();

string connectionString = File.ReadAllText("C:\\IDW32\\Library\\Connection.txt");//note usually we would use the connectionStrings in the app.config file for this

//--> Initialize the Map

_sharpMap = new Map(new Size(1000, 900)) { BackColor = Color.Silver };

PostGIS provider = new PostGIS(connectionString, "p_id.p_id", "the_geom", "public"); //create a new provider

VectorLayer myLayer = new VectorLayer("My Layer");

myLayer.Style = new VectorStyle
{
Line =
{
Width = (1.0F / 8.0F),
Color = Color.Black,
EndCap = LineCap.Round
},
EnableOutline = true
};

//--> Add the first Layer

myLayer.DataSource = provider; //assign the provider to the layer

myLayer.SmoothingMode = SmoothingMode.AntiAlias; //Render smooth lines

myLayer.MaxVisible = 40000;

//Set up a text layer

LabelLayer layText = new LabelLayer("Text Layer");

layText.DataSource = provider;//we are reusing the same provider

layText.Enabled = true;

layText.LabelColumn = "process_name";

layText.Style = new LabelStyle
{
ForeColor = Color.Black,
Font = new Font("Arial", 10),
HorizontalAlignment = LabelStyle.HorizontalAlignmentEnum.Left,
VerticalAlignment = LabelStyle.VerticalAlignmentEnum.Bottom,
Offset = new PointF(3, 3),
Halo = new Pen(Color.Silver, 2)
};

layText.TextRenderingHint = TextRenderingHint.AntiAlias;

_sharpMap.Layers.Add(myLayer); //Add geometry label to viewer

_sharpMap.Layers.Add(layText); //Add label layer to viewer

RefreshMap();

}

public void RefreshMap()
{
Thread.Sleep(1);

//--> Use SharpMap to generate the map image
string definitionQuery = GetDefinitionQueryText();

SetDefinitionQueryOnLayer(_sharpMap.Layers["My Layer"], definitionQuery);//we only need to set the definition query via one layer as they share the same provider

Image im = _sharpMap.GetMap();

//NOTE: the call do get map creates a new bitmap - you still need to assign it to your image control
//(or use a MapImage control and call the Refresh method of that) myGuess is below
//picMap.Image = im;
MessageBox.Show(definitionQuery);

}

private void Form1_Load(object sender, EventArgs e)//it looks like the form has been renamed but the handler may still be active on its old name
{
//--> Zoom to extent

_sharpMap.ZoomToExtents();

RefreshMap();
}

private void button1_Click(object sender, EventArgs e)
{
_sharpMap.Zoom -= _sharpMap.Zoom * ZOOM_FACTOR;

RefreshMap();
}

private void button2_Click(object sender, EventArgs e)
{
_sharpMap.Zoom += _sharpMap.Zoom * ZOOM_FACTOR;

RefreshMap();
}

private void button3_Click(object sender, EventArgs e)
{
_sharpMap.ZoomToExtents();

RefreshMap();
}

private void picMap_MouseClick(object sender, MouseEventArgs e)
{
//--> Convert mouse click point from mimage coordinates to world coordinates

_sharpMap.Center = _sharpMap.ImageToWorld(new PointF(e.X, e.Y));

//--> Recenter Map

RefreshMap();
}

private void button4_Click(object sender, EventArgs e)
{
RefreshMap();
}

internal void InitializeWatcher(FileInfo configurationFile, IList<string> configurationSections)
{
fWatcher = new FileSystemWatcher

{
Path = @"C:\\IDW32\\Library\\p&id.txt",
Filter = "p&id.txt",
NotifyFilter = (NotifyFilters.CreationTime | NotifyFilters.LastWrite |
NotifyFilters.FileName)
};

fWatcher.Created += fWatcher_Created;

fWatcher.Changed += fWatcher_Changed;

fWatcher.EnableRaisingEvents = true;
}

private void fWatcher_Created(object sender, FileSystemEventArgs e)
{
Debug.WriteLine("Handling file created event");
RefreshMap();

}

public string GetDefinitionQueryText()
{
return File.ReadAllText("C:\\IDW32\\Library\\P&ID.txt");
}

public void fWatcher_Changed(object sender, FileSystemEventArgs e)
{
Debug.WriteLine("Handling file changed event");

RefreshMap();
}

private static void SetDefinitionQueryOnLayer(ILayer layer, string definitionQuery)
{
IProvider provider;
if (layer is VectorLayer)
provider = ((VectorLayer)layer).DataSource;
else if (layer is LabelLayer)
provider = ((LabelLayer)layer).DataSource;
else
throw new Exception("Invalid Layer Type");

if (provider is PostGIS)
((PostGIS)provider).DefinitionQuery = definitionQuery;
else
throw new Exception("Unexpected provider");

}
}
}