08 January, 2013

Copy Files From an FTP Server Pt. 1

Recently I was posed with a dilemma. We are using a 3rd party application for taking data from a file, scrubbing, quality checking and finally pushing it into a database for use by our main product. This data comes from different sources and is dropped onto an FTP server. The 3rd party application could technically hand that as it can function “on file drop”. There are, however, two limitations to the 3rd party app’s functionality.

  • It does not recognize that a file has changed. Only that a new file has arrived.
  • The 3rd party app runs on a server that is on a different network than the FTP server is on.

With these issues in mind, my task was to make it work, and make it work on file drop.

The solution I arrived at was to create a console application that will poll the FTP server, and if a file drop has occurred, copy that file to a location where the 3rd party service can see it. I should note that there are some 500 clients each with their own file drop. Some clients are migrated to using the new 3rd party application while others still are on the old, and rather inefficient way of importing this data.

First, I need some static properties. Note the RE_GEX constant, this will allow me to parse the string returned from the FTP server directly listing call. I got this expression from a Bing search, not sure where I got it from, but it does work.

static string RootFtpUri;
static string FtpDestinationRoot;
const string RE_GEX = @"^([d-])([rwxt-]{3}){3}\s+\d{1,}\s+.*?(\d{1,})\s+(\w+\s+\d{1,2}\s+(?:\d{4})?)(\d{1,2}:\d{2})?\s+(.+?)\s?$";
static Regex _regex;
static NetworkCredential Credentials;
static string LogFilePath;



I setup the properties:




FtpDestinationRoot = ConfigurationManager.AppSettings["FtpDestinationRoot"];
var di = new DirectoryInfo(FtpDestinationRoot);
if (!di.Exists) di.Create();
RootFtpUri = ConfigurationManager.AppSettings["RootFtpUri"];
Credentials = new NetworkCredential(ConfigurationManager.AppSettings["FtpUsername"], ConfigurationManager.AppSettings["FtpPass"]);
_regex = new Regex(RE_GEX, RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);



Of course, I use the AppSettings from the app.config file to hold all the pertinent information just in case something changes, like the FPT server name, or the login credentials required. This allows me to make those changes without having to re-build and re-deploy the application.



 



The data for each dealer, their FTP username, drop directory and the name of the dropped file is stored in a MSSQL database. My application then, polls the database to see which files I would need to copy over to the new location.  I have a Records class which holds the required data from the SQL database. I put that into a list.



 




var records = (from d in dt.AsEnumerable()
select new FTPRecord
{
FTPServerAddress = d.Field<string>("FTPServerAddress"),
FTPServerUsername = d.Field<string>("FTPServerUsername"),
FTPServerPassword = d.Field<string>("FTPServerPassword"),
FTPServerFilePath = ParseFPTServerFilePath(d.Field<string>("FTPServerFilePath")),
DMSTypeID = d.Field<Int16>("DMSTypeID"),
Status = d.Field<string>("Status"),
RecordType = d.Field<string>("RecordType"),
NextScheduledAttempt = d.Field<DateTime?>("NextScheduledAttempt")
}).ToList();



The call to the method “ParseFTPServerFilePath” merely strips away any preceding slashes that sometimes get put in when the data is created.



Then it goes to the FTP server and looks for the file, if it exists, I copy the file over. But wait, remember how the 3rd party app only sees new files and not changed files? That process doesn’t work, so I first delete the existing file in the new location before copying the new file from the FTP server.



We have to setup the required stuff for accessing the FTP server, as well as where we are going to put the file. If the destination directory does not exist, we of course have to create it or the whole thing will blow up – and not in a spectacular way so it’s really just a waste of time and effort not to do it.




var destinationFilePath = string.Format("{0}\\{1}\\{2}", FtpDestinationRoot, r.FTPServerUsername, r.FTPServerFilePath.Replace('/', '\\'));
var fi = new FileInfo(destinationFilePath);
var di = new DirectoryInfo(fi.DirectoryName);
if (!di.Exists) di.Create();
var ftpFilePath = string.Format("{0}/{1}/{2}", RootFtpUri, r.FTPServerUsername, r.FTPServerFilePath);
var request = (FtpWebRequest)WebRequest.Create(ftpFilePath);
request.Credentials = Credentials;
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
var line = string.Empty;



Then connect and grab the directory listing from the FTP server. This comes back in the standard UNIX format which looks something like:



-rw-r--r-- 1 ftp ftp        2107325 Jan 08 00:24 INV.CSV



The RegEx takes each line and chunks it into groups, I check to see if the first group is a “d” – this signifies it is a directory – which I bypass and go to the next line. I also check to see if the 6th group is a dot or double dot (“.” or “..”) these are not real files so I pass that line up as well. Now, if the first group is not “d” and the 6th group is not “.” or “..” that means I have a file! W00t!



The RegEx spits out groups in the following format:



comp.Groups[0]    {-rw-r--r-- 1 ftp ftp        2107325 Jan 08 00:24 INV.CSV}
comp.Groups[1] {-}
comp.Groups[2] {r--}
comp.Groups[3] {2107325}
comp.Groups[4] {Jan 08 }
comp.Groups[5] {00:24}
comp.Groups[6] {INV.CSV}



Group 0 is the actual directory entry string, group 3 is the size, 4 & 5 are the date and time and 6 is the file name.




using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
while ((line = sr.ReadLine()) != null)
{
var comp = _regex.Match(line);
if (comp.Groups[1].ToString() == "d") continue;
if (comp.Groups[6].ToString() == "." || comp.Groups[6].ToString() == "..") continue;
if (fi.Exists)
{
var ftpSize = NullableParser.ParseInt64(comp.Groups[3].ToString());
var ftpLastDate = NullableParser.ParseDateTime(comp.Groups[4].ToString());
if (ftpLastDate > DateTime.Now) return; // File is actually from last year (or older) but FTP only returns month/day and .NET assumes current year.
if (r.NextScheduledAttempt == null || ftpSize != fi.Length || ftpLastDate > fi.LastWriteTime)
{
fi.Delete();
Thread.Sleep(30000);
fi = new FileInfo(destinationFilePath);
}
}
}
}
}
}



 



Then comes another problem, what if the file on the FTP server hasn’t changed? I don’t want to unnecessarily copy files that haven’t changed and cause the import process to kick off if it isn’t needed. So I check first for the size of the file, if the size is different, I delete the existing and copy the new. If the file is the same, I then check the date on the file, if the date of the file on the FTP server is newer than the one on the network location, I delete and copy.



If there is no file on the destination location, I copy it from FTP without further ado. This affords us a manner in which we can re-import the data if need be for whatever reason. We simply go to the network location and delete the file and it will be re-copied and kick off the import process.



Next time, I’ll go through creating the Windows Service that runs this thing.

19 May, 2011

Recovering a SQLEXPRESS Installation

I inherited a desktop machine at work. It wasn’t scrubbed and re-fitted with a fresh install when I arrived. Recently I have been examining processes for Single-Sign-On, and really needed to play around with the local installation of SqlExpress, so as not to screw up the dev database for everyone else. One problem though, the previous tenant of the machine followed best security practices and remove the BUILTIN\Administrators user from the database and I nobody knew the System Administrator (sa) password - add to that, the sa account was disabled (again, good security practice!).

With that in mind, I set out on the path to discover how I can recover that installation, and not have to go through the process of uninstalling and re-installing SqlExpress. I finally came across this old post at Phoenix blog.

A few things to keep in mind; His instructions are for full-blown SQL Server, so instead of using “NET STOP MSSQLSERVER” you’ll have to use “NET STOP MSSQL$SQLEXPRESS”. This is for all the stop and starts. Also, one has to have local administrator privileges on the machine, if you don’t have that, as far as I know, you’re pretty much up a creek without a paddle. The process is quick and simple really, I’ll post the steps here (without the nice screen-scrapes that Deepak has in his blog, you can go there and look at them if you need to).
1) Open command line window
2) type NET STOP MSSQL$SQLEXPRESS and wait for the service to stop
3) type NET START MSSQL$SQLEXPRESS /m - this puts sql server in single-user mode (I am not sure what that is really, but hey,it works!)
4) Open your SQL Server Management Studio, and click “New Query” you’ll be presented with the connection dialog window, select the instance of SqlExpress and open the connection.
5) In the new query window type “sp_addsrvrolemember ‘YOUR_USER_NAME’, ‘SYSADMIN’” (sans quotes, of course). This will add your login to the sysadmin role.
6) Close Management Studio.
7) Back in the command prompt window type “NET STOP MSSQL$SQLEXPRESS” to stop the service
8) Next time “NET START MSSQL$SQLEXPRESS” in the command prompt to start the service again, but in normal mode (not single user mode this time, notice the lack of ‘/m’ switch in the command.

06 May, 2011

SalesForce excitement with .NET

Been getting to work some with the SalesForce Apex API, grabbing and pushing data from and to the SalesForce data store. After a bit of a learning curve, it's turning out to not be fairly easy going. I do need to look a bit deeper into bulk uploads, as some of the stuff we'll be pushing is 30K plus recordsets, granted, that isn't a lot, but could be enough that using their bulk API might make sense.

Next project on deck is creating a Single-Sign-On into SalesForce. This is going to be a bit more daunting I think. All of the SalesForce samples and help deal with OpenSSO running on it's own server. We're going to go with the Windows Identity Foundation tools, using the SSO into SalesForce as a launching pad for a new login process for all of the apps across the board. Creating an SSO for everything will mean that all logins will hit the same page, utilize the same processes, no matter if they come to the app via a web browser, or an iPhone, or a Xoom tablet or whatever. Should be great fun and a terrific learning experience.

FireFox 4 jQuery document height and width

I ran into a little problem the other day. I had some jQuery goodness running along just fine and dandy. Everything was Jake while using Chrome and Internet Explorer 9 and FireFox 3, but when I looked at the site using FireFox 4, it didn't work right.

After some aggravating trial and error, I discovered the culprit. See, in the jQuery documentation, they say you can use two methods to get the height and width of a document:

$(document).height();
$(document).css('height');

The former gives you just the pixel numbers, while the latter is supposed to give you the entire CSS height (i.e. "450" for the first, and "450px" for the second). The problem is, that FireFox 4 doesn't recognize $(document).css('height') - or width for that matter. So you have to get it with just the .height() command, and append 'px' to the end of it.

17 March, 2011

CSS funkiness with Firefox

Normally, I check page layout and styles in IE and in Firefox. These two, I've found, have pretty much been good. If it works in those, it works usually in Chrome and Opera as well. I never check Safari, frankly that browser just slows down my system. My advice to folks using Safari is pretty much "use something else".

Anyway, I was fitting a checkbox today, and cursed a little under my breath when it didn't show up properly positioned in IE9. It's possible that if I'd been using IE8 or even IE7, I might not have found this, since those pretty much handle CSS in the same manner as Firefox. To be honest, I was ready for this to be IE9's fault, so I fired up Chrome and Opera to verify my assumptions. You could have knocked me over with a feather when the page rendered in Chrome and Opera just the same as it did in IE9. It was Firefox that was the problem.

Now, I'm used to making exceptions for IE, so I had to do a bit of research on how to do it with Firefox, and this is what I found:

<style type="text/css">
.complete-checkbox
{
position:relative;
top:23px;
display:block;
float:right;
color:white;
font-weight:bold;
}

@-moz-document url-prefix() {
.complete-checkbox-ff
{
position:relative;
top:0px;
display:block;
float:right;
color:white;
font-weight:bold;
}
}
</style>



Essentially, I added a second class specifically for Firefox and used those properties only if the browser is Mozilla.

06 June, 2008

ESRI & ASP.NET Master Pages

One of the great things about VS 2005 & ASP.NET 2.0+ is the ability to quickly and easily create and user Master Pages in your ASP.NET web application.

One of the horribly difficult things about Master Pages is when using mash-ups, figuring out how they work exactly. Ok, if you don't know about Master Pages, then you should probably investigate them some.

A Master Page is not really a page, but rather a template that holds containers into which pages render (but can also regular HTML there as well). So a Master Page can have your title, image banner, navigation links, login stuff, breadcrumb trail...all that stuff, and also contains one or more "ContentPlaceHolder" controls.

The problem when putting an ArcGIS Server map in a page that has a master page is that when the page is rendered, the name of the map changes. That is, if you leave you map the default "Map1" name, when rendered, it has the name "ct00_ContentPlaceHolder1_Map1". Assuming, of course, you lave the ContentPlaceHolder name the default AND you put the map in the first instance of the ContentPlaceHolder controls.

This creates issue when attempting to access the map via JavaScript. In the WebMapApp.js file that is defaultly created when a Web Mapping Application is created in VS2005, it is assuming that you leave everything as the default names when you put stuff in the map. With that in mind, it uses names like "Map1", "TaskResults1" etc.

To fix this, I created a global var in the javascript file:

var webMapControlPrefix = "ctl00_ContentPlaceHolder1_";



So, for instance, the setpageElementSizes() function goes to define the scale bar , it used to do:



webMapAppScaleBar = document.getElementById("ScaleBar1");



But now, I have it looking like this:



webMapAppScaleBar = document.getElementById(webMapControlPrefix+"ScaleBar1");



You probably get the idea. If not, drop a comment and I'll see what I can find out about whatever confusion there is.







21 April, 2008

GridView RowUpdating: Stupid, stupid stupid error

Making an error in your code is one thing. But making an error that is so brilliantly, blatantly and egregiously stupid...well, that is something wholly and completely different.

Case in point. I have a GridView control on a page. I need to be able to edit that GridView control. However, to populate the GridView, I need a dataset which contains a " WHERE [COLUMN] IN (values)" where clause. The problem is, that the SqlDataSource really doesn't seem to support this very easily. I'm almost-but-not-quite certain it probably-might-possibly does, but I couldn't figure it out.

Because of that, I needed to bind the GridView to a DataSource programmatically. And that I did, right off the bat, right when the page loads, because, you know, I want the damn data right the hell away.

So what I neglected to do was put the data binding declarations in the good ol' trusty "if (!Page.IsPostBack)" statement. Which means that each and ever time the page loaded (i.e, when I clicked the "Edit" and "Update" links) the GridView was rebound to the original data. No fracking wonder my stuff wasn't working.

31 March, 2008

Highlighting features with ArcGis Server 9.2

I have the need to highlight items when the user selects to zoom to a particular item from a custom search. If I was using the ResultsTask control, then the user could simply check the checkbox next to the feature, and it would highlight. However, since the client doesn't like the treeview style of the ResultsTask, I have put the search results into an HTML table. Now, when the user selects to zoom to a feature, it will automatically highlight the feature.

I found this code in the ESRI forums, and it works well.

// This gives us a nice light blue color. You can change the color to whatever you want.
ESRI.ArcGIS.ADF.ArcGISServer.RgbColor irgbc = new ESRI.ArcGIS.ADF.ArcGISServer.RgbColor();
irgbc.Red = 50;
irgbc.Green = 255;
irgbc.Blue = 255;
irgbc.AlphaValue = 255;

ESRI.ArcGIS.ADF.ArcGISServer.FIDSet fids = new ESRI.ArcGIS.ADF.ArcGISServer.FIDSet();
int[] ids = new int[1];
ids[0] = Convert.ToInt32(key); //<-- OBJECTID of the feature to highlight
fids.FIDArray = ids;

ESRI.ArcGIS.ADF.ArcGISServer.MapDescription mapdesc = ((MapFunctionality)mf).MapDescription;
ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription[] layerdescs = mapdesc.LayerDescriptions;
ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription layerdesc = layerdescs[layerid];
layerdesc.Visible = true;
layerdesc.SelectionColor = irgbc;
layerdesc.SelectionFeatures = fids.FIDArray;

The problem with the above code is that it highlights the entire area. Not bad for point features, but for polygons, it covers everything underneath it completely. I tried adjusting the RgbColor.AlphaValue, but that didn't change anything at all. I'm thinking that is a red herring, and doesn't really do anything at all. So what I decided to do was instead of filling the entire polygon, I just use ShowSelectBuffer as seen below:

ESRI.ArcGIS.ADF.ArcGISServer.RgbColor irgbc = new ESRI.ArcGIS.ADF.ArcGISServer.RgbColor();
irgbc.Red = 50;
irgbc.Green = 255;
irgbc.Blue = 255;
irgbc.AlphaValue = 255;

ESRI.ArcGIS.ADF.ArcGISServer.FIDSet fids = new ESRI.ArcGIS.ADF.ArcGISServer.FIDSet();
int[] ids = new int[1];
ids[0] = Convert.ToInt32(key);
fids.FIDArray = ids;

ESRI.ArcGIS.ADF.ArcGISServer.MapDescription mapdesc = ((MapFunctionality)mf).MapDescription;
ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription[] layerdescs = mapdesc.LayerDescriptions;
ESRI.ArcGIS.ADF.ArcGISServer.LayerDescription layerdesc = layerdescs[layerid];
layerdesc.Visible = true;
layerdesc.ShowSelectionBuffer = true;
layerdesc.SelectionFeatures = fids.FIDArray;



By using LayerDescription.ShowSelectBuffer, the feature is outlined with the highligh color, instead of filled in. This gives us the ability to see what is within the feature, while still knowing where the feature was located.



References:



http://forums.esri.com/Thread.asp?c=158&f=2276&t=211190&mc=12#msgid719661



http://forums.esri.com/Thread.asp?c=158&f=2276&t=223224&mc=1




28 March, 2008

ESRI breaks my custom zoom to method

I have an ArcGIS Server application. The client didn't like the standard format ESRI uses for displaying search results. So I made my own version. Basically, I return an HTML table through Callback scripting and populate a DIV with it. That table contains a column which is a hyperlink which calls functionality to zoom to that particular feature. Here's my code for that:

 System.Data.DataTable dataTable = null;
ESRI.ArcGIS.ADF.Web.DataSources.IMapFunctionality mf = (ESRI.ArcGIS.ADF.Web.DataSources.IMapFunctionality )Map1.GetFunctionality(0);
if (mf != null)
{
ESRI.ArcGIS.ADF.Web.DataSources.IGISResource gisresource = mf.Resource;
bool supported = gisresource.SupportsFunctionality(typeof(ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality));
int shapeInd = -1;
if (supported)
{
ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality qfunc;
qfunc = (ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality)gisresource.CreateFunctionality(typeof(ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality), null);
string[] lids;
string[] lnames;
qfunc.GetQueryableLayers(null, out lids, out lnames);



All this works splendidly...or at least it did. That was until I went an used ESRI's MapIdentify tool. This tool by default puts things in the task results panel. When I used the zoom to functionality in the task results panel, I noticed that my custom zoom to method suddenly quick functioning. This was distressing to say the least. It seems that every time I actually start to feel like I somewhat understand ArcGIS, I get blind-sided by something stupid like this.



After some careful debugging, I discovered what was happening was that ESRI stacks new MapResourceItems on top of the actual map when you interact with the task results. So originally my code was working fine when I was getting MapResourceItems[0] since that was the only MapResourceItem. But after running the task results, both the layer names and layer ids returned from the GetQueryalbleLayers() method were coming back as GUIDs.



My solution was to loop through all MapResourceItems until I found a MapResourceItem with a name that matches the map name.





  System.Data.DataTable dataTable = null;
ESRI.ArcGIS.ADF.Web.DataSources.IMapFunctionality mf = null;
for (int i = 0; i < this.MapResourceManager1.ResourceItems.Count; i++)
{
if (string.Compare(this.MapResourceManager1.ResourceItems[i].Name, this.m_mapName, true) == 0)
{
mf = (ESRI.ArcGIS.ADF.Web.DataSources.IMapFunctionality)Map1.GetFunctionality(i);
}
}
if (mf != null)
{
ESRI.ArcGIS.ADF.Web.DataSources.IGISResource gisresource = mf.Resource;
bool supported = gisresource.SupportsFunctionality(typeof(ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality));
int shapeInd = -1;
if (supported)
{
ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality qfunc;
qfunc = (ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality)gisresource.CreateFunctionality(typeof(ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality), null);
string[] lids;
string[] lnames;
qfunc.GetQueryableLayers(null, out lids, out lnames);

19 March, 2008

BlogMyCode VS2005 plugin

I have been using Windows Live Writer for quite a while now. I like it. It contains all the info for my different blogs. It is a desktop app. Makes it easy to start a post, save it as a draft, and continue it on later and when you actually get around to posting, it uses current date/time stamp. I know blogger for instance, will post a draft with the date/time stamp of when you started it, now when you finish it.

What I have not been doing is using WLW to its full extent, or even, it seems, a portion of that extent. As I was finally getting it setup on my work computer (I had to bypass the lockout for Windows Update to do it - don't tell the IS folks, ok?). As I was searching for plugins for WLW, I can across a plugin for Visual Studio 2005 which, I have to tell you, Is freaking awesome!

BlogMyCode is Microsoft Visual Studio 2005 plugin, that helps you to blog formatted source code, by using Windows Live Writer.

BlogMyCode adds a "Blog This" element to your context menu in VS2005. Highlight some code, right-click, select "Blog This" and in just a few steps, you get this:

public ParcelIdentify(Map map, string filePath)


{


    m_map = map;


    m_filePath = filePath;


    SetupIdentify();


 


}



The drawback I have found so far (and it is probably a setting somewhere in WLW) is that when I do the "Blog This", it opens a new instance of WLW and starts a new post.



You can get the BlogMyCode VS2005 plugin here.

10 March, 2008

Using SQL Database images in the ASP.NET ReportViewer


One of the criteria for a project was for the user to input data into the database for viewing in a report. The user entered data, and uploaded an image for the report. Now, I've added images to an SQL database before. But years and years ago, way back when there wasn't an 'image' type for a field in SQL. Instead, I believe the type for the field was called 'binary' or something along those lines. The process for inserting an image into an MSSQL image field is a little different than it was before.

I start off with the ASP.NET System.Web.UI.WebControls.FileUpload control for uploading a file through the web page. Back in the ASP days, there wasn't a process for this built into ASP, so we had to 1) buy a DLL for doing this or 2) make a DLL for doing this. Either way, it wasn't integrated, and required either and ActiveX control or a Java applet to get the job done.

The data the user entered was to be available in a report created in ReportViewer. The Reporting Services report has an image object, which has the option for defining it as a database image, and define the field in the database that has the image. Now, the implication is that one would have to define the field and the report would get the data, and display the image. Easy as pie. But the reality is something wholly different. After days on end of searching and searching and reading forum posts and tutorials ad-infinitum, I finally found (although I have to admit, I don't know where now) that it isn't as simple and easy as they let on. You can't just put:

=Fields!ImageField.Value


and have it display an image. No. The report must start with a string for the image, and then the report converts that string to an image. So the question becomes 'how do I get the the data into string format?' Oddly, you have to convert the data to base 64 string, then convert it FROM base 64 string. I don't know why, but I do know this works.

=System.Convert.FromBase64String(System.Convert.ToBase64string(Fields!ImageField.Value))


I don't pretend to know why this is the way it is, but I know that it works, and the image appears. And frankly, since I know how to make it work, I don't really care why I have to do it. Oh, crap, I almost forgot. To use the source Database for a report, you've got to set the MIMEType to either image/jpg, image/png or image/bmp. Again, I don't know why this is, I just know that it is, and that is enough for me.

I spent oodles of time trying to get the image to display, but it just seemed like it would never ever work properly. Finally, I decided to create a quick and dirty (and extremely ugly) desktop application where I would pull the image from the database and assign it to a PictureBox control. What I found was as I would pull the image out of the database, and using a MemoryStream to convert it to an actual image.



System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandText = "SELECT * FROM [REPORT_TABLE]";
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString = _connectionString;
cmd.Connection = conn;
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(cmd.CommandText, conn);
DataSet ds = new DataSet();
da.Fill(ds);
DataRow dr = ds.Tables[0].Rows[0];
Byte[] b = (Byte[])dr["IMAGEFIELD"];
MemoryStream ms = new MemoryStream(b);
this.pictureBox1.Image = Image.FromStream(ms);



This code, while it appears on the surface that it should work, didn't. It would kick out the ambiguous "Parameter is not valid" error message at the "Image.FromStream(ms)" line. After several days of googleing and reading what was said by others regarding this error, I discovered that my code was syntactically correct and there was no real reason why it wasn't working. That is when it hit me. I wonder if I'm putting the data into the database correctly?

For inserting the data, at first I was using a stored procedure, through an SqlDataSource and it appeared to be working. That is to say, it didn't kick out any errors. Then I figured I would just go through the process of creating the SqlDataSource and, for lack of a better description, manually insert the data. Again, this seemed to work fine. No errors. But still the image was not visible in the report, and in my desktop application, it would error when trying to create the image "FromStream(Stream stream)". This got me to thinking, so I took a step back and instead of using the SqlDataSource, I decided to try using System.Data.SqlClient to insert the data and image. And lo' and behold this method worked. I don't know what is funky with SqlDataSource method, but what I know is that it didn't work - but that using SqlClient does work, and that is all that really matters to me.


string uploadFileName = string.Empty;
byte[] imageBytes = null;
if(imageUpload != null&& imageUpload.HasFile)
{
uploadFileName = imagUpload.FileName;
imageBytes = imageUpload.FileBytes;
}
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString = _connectionString;
cmd.CommandText = "INSERT INTO REPORT_TABLE (IMAGEFIELD,IMAGENAME) VALUES (@image,@filename)";
cmd.Parameters.Add("@image", SqlDbType.Image, imageBytes.Length).Value = imageBytes;
cmd.Parameters.Add("@filename", SqlDbType.VarChar, 50).Value = uploadFileName;
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();



Now, just inserting the imageBytes object into the command text did not work. I had to add it as a Parameter to the SqlCommand object. Why? Hell, I don't know, but I know it works, and that is what counts for me at this point. So I put added 23 parameters to the Command object (one for each column of course) and set the values accordingly

cmd.Parameters.Add("@image", SqlDbType.Image, _imageBytes.Length).Value = _imageBytes;


This put the image into the database properly. I'm guessing the parameter is required because it actually defines exactly what DBType we are dealing with, where an normal insert statement wouldn't. At any rate it WORKS! Now the image goes into the database, and get extracted by the ReportViewer and displays properly in the report.

w00t!



Technorati Tags: , , , ,

20 February, 2008

Drill through reports in ASP.NET

In a recent ASP.NET application (coded in C# - natch) I had the cause to create a report, which contained a hyper link which in turn displayed a second report based on data from the first report. In researching this, I discovered this is called a drill through report.

I found information at CodeProject.com regarding drill down reports. The difference between what Shirley did, and what I was doing is that I already had the dataset for the report created. I created a dataset with two data tables in it. I haven't tried it, but I'm guessing that I could have easily put as many tables as I needed if I were going to drill down farther than just one level.

I used the same dataset for both reports. But when I went to perform the drill down, I received the following error:
"A data source instance has not been supplied for the data source [report data source name]"

So I slap my forehead, call my self a dunce, and make sure that both tables are represented by data sources (or would that be data sourcii?). At any rate, I kept getting the same error, which is what led me to googling the error message to see what the problem is. Based on Shirley's article, I realized that I would be required to set the data source for the new report in the ReportViewer_Drillthrough event handler.

Here is my code:

protected void ReportViewer_Drillthrough(object sender, Microsoft.Reporting.WebForms.DrillthroughEventArgs e)
{
Microsoft.Reporting.WebForms.
LocalReport localReport = (Microsoft.Reporting.WebForms.LocalReport)e.Report;
localReport.DataSources.Clear();
this.ObjectDataSource3.SelectParameters[0].DefaultValue = e.Report.GetParameters()[0].Values[0].ToString().Trim();
Microsoft.Reporting.WebForms.
ReportDataSource rds = new Microsoft.Reporting.WebForms.ReportDataSource("ReportDataSet_TABLE",this.ObjectDataSource3.Select());
localReport.DataSources.Add(rds);
}

A bit of breakdown for those who have a hard time following my crappy coding style:
First off, I set a LocalReport object ot the DrillthroughEventArgs.Report object. Then I clear the data sources because I'm going to add a new one, and I certainly don't want the report getting confused. I set the default value of the SelectParameters[0] (the only parameter for this report) to the only parameter that is passed. If there are more parameters in your report, then you would, of course, be required to set them all. For this instance, I had only one.

Then I had to create a new ReportDataSource object. At first I tried simply added the ObjectDataSource3 to my localReport.DataSources, but that didn't fly because I guess an ObjectDataSource is different from a ReportDataSource. Then I figured I would just cast the ObjectDataSource as a ReportDataSource. But that didn't fly either. You can't cast the former as the latter. So I was resigned to create a new one. I gave the new one the same name as the DataSource I defined in my report. Then I added the ReportDataSource to my localReport.DataSources collection, and voila!

Oh, and don't try to refresh the localReport. For some reason it seems to resort back to the parent report. I don't know why, and frankly don't really care, as long as I know how to handle it, it's all good.




Technorati Tags: , , , , ,

04 February, 2008

Working Client-Side with CheckBoxLists

One of the new things I have been playing with are CheckBoxLists. This is a server control which is DataBindable. It creates a list of CheckBox controls. You can define if the list is displayed horizontally, or vertically. I am using a couple of these in a new application and ran into some problems accessing them with JavaScript. This application doesn't ever do a real-honest-to-goodness postback. Instead, all calls to the server are handled through Callbacks. Callbacks aren't really what I'm here to talk about, so if you need to learn more about them, I would recommend popping on over to ASP.NET and checking out their forums and other areas of that site. It is chock full of excellent information.

Ok, back to where I was. Getting to the CheckBoxList stuff. The CheckBoxList renders its ID on the HTML side slightly different from a normal control. Since the control generates multiple sub-controls. For instance, normally, if you had a CheckBox and gave it the ID of "myCheckBox" then to access it in JavaScript you'd simply do something like var chkbx = document.getElementById('<%=myCheckBox.ClientID %>'); and voila! you have access to your CheckBox control. But as stated, the CheckBoxList generates multiple CheckBoxes. The problem was how in the world do I access these? How do I do capture a client side event with a databound list like this? I mean, the list could change daily right? What I came up with (and it probably isn't the _best_ way to go about it, but it certainly works) is to add an attribute to the generated CheckBox in the DataBound EventHandler for the CheckBoxList control. Using DataBound of course because that means the list has been completed.

The CheckBoxList, like the DropDownList (and several other controls) contains the .Items parameter which is the ListItemCollection object. What I ended up doing is adding an "onclick" attribute to each item, passing to the JavaScript the client id of the actual CheckBox control, the text and the value (really, I only needed the control client id and the text, but I figured I'd go ahead and throw in the value for good measure. I separated the ClientID, Text and Value data with a colon (:) so I could easily split it back on the client side.

protected void checkBoxList_DataBound(object sender, EventArgs e)
{
CheckBoxList cbl = (CheckBoxList)sender;
for (int i = 0; i < style="color: rgb(51, 51, 255);">string controlName = cbl.ClientID + "_" + i;
cbl.Items[i].Attributes.Add("onclick", "javascript:checkBoxChanged('" + controlName + ":" + cbl.Items[i].Text + ":" + cbl.Items[i].Value + "')");
cbl.Items[i].Selected = true;
}
}


I use the same DataBound Event Handler for all of the CheckBoxList controls since there is nothing happening that is actually specific to any one CheckBoxList, they all call the same JavaScript. However, getting the control information, and whether or not it is checked, back to the client side is only half the battle. The check boxes are part of a data filter which will display data in a GridView. The user can click on or off all or part of the list items to decrease or expand the scope of the data displayed. So I need to put these checked boxes into some kind of JavaScript array so that when the time comes to do the Callback to populate the GridView, I have all the required data to build the filter server-side.

var checkedBoxesArray = new Array();
function checkBoxChanged(controlInfo) {
var ary = controlInfo.split(":");
var chkBx = document.getElementById(ary[0]);
if(chkBx.checked) {
// check to see if the check box already exists (it shouldn't)
for(x in checkedBoxesArray) {
if(controlInfo == checkedBoxesArray[x]) return; // <-- get out of here, it's already there, and there is nothing else to do
}
checkedBoxesArray[checkedBoxesArray.length+1] = controlInfo;
}else {
for(x in checkedBoxesArray) {
// find the checkbox information in the array and remove it (it should be there)
if (controlInfo == checkedBoxesArray[x]) {
checkedBoxesArray.splice(x,1);
break; // <-- No use going through all of them if we don't have to , right?
}
}
}
}


Then I could access the checkedBoxesArray in the JavaScript function which actually creates the querystring style callback event arguments which are used on the server-side to create the data filter.

07 January, 2008

XP does not support hosting on a UNC share?


It occurs to me that for nearly a decade now Microsoft has been championing the 'thin client.' Saying things like "the network is the OS" and wanting businesses, developers and others to move to heavy-hitting powerful server platforms that would contain most of the programs and information, and the users would have more watered down desktops which would access most of their applications (office, mail, etc) from the server.

So imagine my shock, surprise and stream of words filthy enough to make a sailor blush when I kept getting this error while trying to publish a website:
Error 5 An error occurred loading a configuration file: Failed to start monitoring changes to '\\[machinename]\[drive]$\[directory]\[website]\bin\ko' because the network BIOS command limit has been reached. For more information on this error, please refer to Microsoft knowledge base article 810886. Hosting on a UNC share is not supported for the Windows XP Platform.

WTF? Hosting on a UNC share is not supported? How the hell can this be? Microsoft touts how Visual Studio 2005 is such a great development platform. How collaboration and all that jazz is great and easy and built right into it. What kind of crack are they smoking? If hosting on a UNC is not supported, how in God's green earth are we supposed to develop web applications? On our desktops? Sure, ok, but what about all that great built-in collaboration? Oh, I guess that baby gets thrown out with the bathwater in this one.

What makes things worse is that this seems to be a rather sporadic error. On top of that, I can run the publish command, get this error with a fold like "ko" (as above) and run it again, making no changes, and it gives me a different folder. Seems almost totally random. Thankfully, all the folders it was complaining about were either 1) localization folders added by their AJAX control toolkit, or 2) App_Theme folders that we weren't using anyway. So I was able to delete all those without causing undue issues with the site.

Checking the KB article the error instructs you to (http://support.microsoft.com/?kbid=810886) doesn't really do much for me. First off, the development server we are using didn't have these keys at all in their registry. The KB article is for windows 2000 server, and we are using Windows Server 2k3. So this article is pointless. Every Google find points back to the same damn MS KB article.

AAAAAAAAARRRRRRRGGGGGHHHHHHH!!!!!

I just had to rant a bit.
Sorry.

19 December, 2007

Getting the map to zoom to a feature in ESRI webADF is a chore

ESRI can be as frustrating as it can get. My lack of experience with ASP.NET 2.0/3.0 combined with the vast differences betwen the desktop functionality of ArcGIS and the web functionality of ArcIMS / WebADF is giving me gray hair faster then my kids every could dream of doing.

I have a .NET pretty much out of the box site - that is, I went into "ArcIMS Web Manager for the Microsoft .NET Framework" and setup a new site. I have some queries that had to be customized, and I ran out of time trying to get the TaskResults panel to display the query results (I'll post about that experience when I have a little more time), so I put them in an HTML table in their own panel. I have a hyperlink in the table which, when clicked, should zoom to that feature on the map. I have looked and, and am using some code from this thread how can i zoom to my selected features - only it isn't working fully.

// This is the method to zoom to the feature, param 'key' is the objectid of the feature, and the param 'layer' is the name of the feature layer
protected void ZoomToFeature(string key, string layer)
{
ESRI.ArcGIS.ADF.Web.DataSources.IMS.MapFunctionality mf;
ESRI.ArcGIS.ADF.IMS.Carto.MapView mv;
mf = (ESRI.ArcGIS.ADF.Web.DataSources.IMS.MapFunctionality)Map1.GetFunctionality(0);
mv = mf.MapView;
ESRI.ArcGIS.ADF.IMS.Carto.Layer.FeatureLayer queryLayer;
queryLayer = (FeatureLayer)mv.Layers.FindByName(layer);
Filter queryFilter = new Filter();
QueryParameters queryParams = new QueryParameters(queryFilter);
queryFilter.WhereExpression = "ObjectID = '" + key + "'";
queryFilter.Tolerance = 20;
queryFilter.ToleranceUnits = BufferUnits.Meters;
queryParams.ReturnGeometries = true;
queryParams.ReturnGlobalEnvelope = true;
ESRI.ArcGIS.ADF.IMS.Display.Symbol.FeatureSymbol fs = new ESRI.ArcGIS.ADF.IMS.Display.Symbol.SimpleFillSymbol(System.Drawing.Color.White, System.Drawing.Color.Red, ESRI.ArcGIS.ADF.IMS.Display.Symbol.PolygonFillType.Solid);
ESRI.ArcGIS.ADF.IMS.Display.Renderer.SimpleRenderer sr = new ESRI.ArcGIS.ADF.IMS.Display.Renderer.SimpleRenderer(fs);
queryLayer.Visible = true;
FeatureTable ft = queryLayer.Query(queryParams);
if (ft.Rows.Count &gt; 0)
{
ESRI.ArcGIS.ADF.IMS.Geometry.Geometry featureGeom = (ESRI.ArcGIS.ADF.IMS.Geometry.Geometry)ft.Rows[0]["#SHAPE#"];
ESRI.ArcGIS.ADF.Web.Geometry.Geometry adfGEom = ESRI.ArcGIS.ADF.Web.DataSources.IMS.Converter.ToADFGeometry(featureGeom);
ESRI.ArcGIS.ADF.Web.Geometry.Envelope adfEnv = ESRI.ArcGIS.ADF.Web.Geometry.Envelope.GetMinimumEnclosingEnvelope(adfGEom);
Map1.Extent = adfEnv;
}
Map1.Refresh();
}

// This is the code in RaiseCallbackEvent(string responseString) method which calls the ZoomToFeature method
this.ZoomToFeature(eventArg, layerArg);
response = Map1.CallbackResults.ToString();

I am getting new envelope for the feature, and I am setting the map extents to that envelope. I know this works because I put some dummy code in a Map1_ExtentsChanged event handler and checked to ensure the map extents were changed. Then I hit Map1.Refresh(); but the map does not change. I'm returning the Map1.CallBackResults.ToString();, but I'm ignorant of what to do with the results on the client side. The RaiseCallbackEvent method returns the 'response' string.


After playing around and doing some more searching with different keywords, I found this thread; The ESRI Map control does not refresh ..... which talks about client side map.redraw(); giving the following example:

var map = Maps['<%=Map1.ClientID %>'];
map.redraw();

I thought this would solve my problem and it almost-but-not-quite does. It does redraw the map (at least it looks like it does). But what I get is a completely blank map until I either zoom in or out. Then the map appears zoomed to roughly the correct location (depending on if I zoomed in or out to make it show up). Also works using the mouse wheel.




Technorati Tags: , , , ,

13 December, 2007

I might be going crazy

This is getting more annoying by the fracking minute!!!!!!!!

I need a search with cascading combo boxes. That is, when the search panel is displayed, combobox1 is populated, and combobox2 is empty. When the user selects a value from combobox1, it then populates combobox2 with values based on combobox1. Simple enough right? I get that population of the boxes down pat, no problems there. Doing through Callback and everything so the page doesn't have to refresh or anything like that.

Here is my problem. I need the results to display in the ESRI.ArcGIS.ADF.Web.UI.WebControls.TaskResults results panel - we'll call it TaskResults1 (because that is what it is called when the site is created through the ESRI ArcIMS manager). I have tried just putting the code in there, but to no avail. I have tried creating a QueryAttributesTask and defaulting the values to what I need, and executing the task. Still no dice.

The values get put into the TaskResults1 results, but they just don't display. I can't figure why they don't display. I know they are there because after I perform the query, if I do a canned search, or use the MapIdentify feature (both of which add data to the TaskResults1 container), the results display with the new data.

I have tried finding help on the ESRI forums, but that is slow and I'm on a deadline.

I'll keep trying different wild and crazy stuff to see if I can figure it out.

Hmmmm....I wonder if I can refresh the TaskResults1 container from client side java?

29 October, 2007

ESRI 9.2 lacks info regarding VS 2005

ESRI seems to like to play things very close to the vest - so to speak. It is difficult to find information on just about anything dealing with creating class libraries in .NET to work with ArcGIS 9.2, even though they tout that 9.2 is built on the .NET Framework 2.0. So far, 99% of the articles, tutorials or help I have found have been for pre-9.2 and VS 2003 (Framework 1.1).

To be fair, I have found a few PDF files discussing 9.2 and .NET 2.0, but that is about it. They are actually PDFs made from PowerPoint slides that I'm certain were from some conference or demonstration given probably a year or so ago. But the walkthroughs they have on their site for VS 2003 - which seem exceptional in detail - are conspicuously missing for VS 2005. Everything I have found that deals with VS 2005 centers around the ArcGIS SDK which , of course, didn't get installed on my system along with ArcGIS 9.2, and is not downloadable from ESRI - which I find strange. It seems to me that other companies make their SDK readily available to developers, but ESRI doesn't seem to want to play that game for some reason.

So here I am, about a week into the project. I've got most of the VBA code translated, but I can't test any of it because I can't get the crap to work properly in ArcMap, and I can't find any decent assistance on the 'net. I guess I'm going to have to go be the quintessential n00b at the ESRI forums and beg for some sort of help. I hate doing that, but, like Duke Wayne said "A man's gotta do what a man's gotta do" ( or someone said that anyway ).

Here are the walkthrough/tutorials that I found pertaining to ESRI and .NET if anyone is interested/needs them:

The way I'm looking at this right now, It seems like it would be infinitely easier to create a desktop app and add the ArcMap to the app, instead of trying to create modules to run in ArcMap. But that isn't the way things are right now, so I've gotta do what they want done.




Technorati Tags: , , ,

17 October, 2007

Converting VBA code to .Net

My latest torture assignment is to convert legacy VBA code in ArcView applications to the .NET Framework. I haven't decided yet if I will convert them to VB .NET or C#, but since I like the C# language better, I will probably attempt to convert them to C#. But then, that somewhat depends on ArcView and how it handles these things. I haven't much (any) experience with ArcView so this is all new territory to me.

I did find a couple of somewhat useful links regarding converting VBA to .NET:

Converting Code from VBA to Visual Basic .NET

Convert VBA to VB .Net and C#

I found this VBA script which purports to export VBA modules, class modules and forms associated with an ArcView document to a separate folder. I haven't tried it yet as I won't get ArcView loaded until tomorrow. But I'm certainly going to give it a go. Anything to make things easier!

Export VBA Code

Okay, I don't know if the module will work at any rate because we can't compile the ArcView project here. I tapped another developer who actually has ArcView on her machine and we were going to run this module, but the guy who created this project has referenced some Autodesk stuff, which we don't have. So we have to export the modules,classes and forms one at a time. There are quite a few of them there.

I'll keep you posted on what entails with converting the VBA to C# code as this endeavor progresses.

13 September, 2007

Altering QueryString with Javascript

I'm making a grid in a legacy ASP application. That's right kids, ASP as in Active Server Pages. Old School stuff. None of the ultra-kewl .NET does it all for you stuff. Which, BTW, I really love because I can do so much more so much faster and better. But, alas, the client says "ASP only!" so, I go with ASP.

What they wanted to do was display their data in a grid. Yeah, right, ASP and datagrids, that is a rich one. So what I did was something almost, but not quite, completely different from a grid. I put their data in an HTML table with alternating row colors (hey, at least they think it's in a grid).

But of course, in any good datagrid, one must be able to click on the grid headers and VOILA! the grid sorts by the header clicked. This, I figured out, to do with JavaScript via the QueryString. The table is in an IFRAME, so the URL is never displayed to the end user. Doing this keeps the displayed URL fairly nice and neat. My original though, which seemed to work fairly well was just to cut the QueryString off at the desired parameter, and replace that parameter with the new one as such:

function reSortGrid(str)
{
var idx = location.href.indexOf('&sortby');
var loc = location.href.substring(0, idx);
loc = loc + '&sortby=' + str;
location.href = loc;
}
But then it occurred to me that if any parameters existed beyond the parameter I was replacing, they would be lost. No, what I really needed was to replace the existing sortby parameter within the actual string, while maintaining the rest of the string. This took a little thinking on my part, and what I came up with is:
function resortGrid(str)
{
var newQueryString = '';
if (location.href.indexOf('&sortby') > -1)
{
var locArray = new Array();
locArray = location.href.split('&');
for (i=0; iif (locArray[i].indexOf('sortby') > -1)
{
locArray[i] = "sortby=" + str;
// check to see if this is the start of the QueryString
if (locArray[i].indexOf('?') == -1)
newQueryString = newQueryString + '&' + locArray[i];
else
newQueryString = locArray[i];
}
}else{
newQueryString = location.href + '&sortby=' + str;
}
location.href = newQueryString;
}
So what I ended up with is a QueryString with the correct parameter changed, and the rest of the parameters intact.

14 August, 2007

Old School

This is becoming less of a blog about C# lately, and more of a blog about web programming in general. Hopefully I'll get back to C# sooner, rather than later.

Currently, my project is to enhance and expand an application written in ASP and...get this...Delphi!!!! And I have to tell you, after using C# and ASP.NET for the past 5 years, ASP SUCKS!! And not just a little, ASP sucks splendidly!

The current problem I fighting with is accessing an MS Access database via ASP. Getting there the first time isn't too bad, but when I try to get to it a second time, it blows up with that oh so informative error of:
Provider error '80004005'

Unspecified error

/Bridge/facilities/facmain.inc, line 13

Now, if Microsoft could any more ambiguous, I don't know how. It looks like I'm going to have make a separate DB connection for each RecordSet. This seems stupid and entirely inefficient, but as Duke Wayne said "A man's gotta do what a man's gotta do."

I am seriously not wanting to delve into that Delphi portion of the project, but that is coming soon enough.




Technorati Tags: , ,